dispach 0.2.0-pilot.2 → 0.2.0-pilot.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/APEv2Parser-v1059sdf.js +5 -0
- package/dist/{APEv2Parser-e7k9bv13.js.map → APEv2Parser-v1059sdf.js.map} +1 -1
- package/dist/{AiffParser-btgza62h.js → AiffParser-d63xfxy7.js} +2 -2
- package/dist/App-7vmwg2rx.js +11 -0
- package/dist/{App-pg0dr8an.js.map → App-7vmwg2rx.js.map} +1 -1
- package/dist/{AsfParser-rxeats6m.js → AsfParser-e9qw1zww.js} +3 -3
- package/dist/{AsfParser-rxeats6m.js.map → AsfParser-e9qw1zww.js.map} +1 -1
- package/dist/{ConfigEditor-9qa0sktq.js → ConfigEditor-63sykb3e.js} +4 -4
- package/dist/{ConfigEditor-9qa0sktq.js.map → ConfigEditor-63sykb3e.js.map} +1 -1
- package/dist/{DsdiffParser-kv863bc1.js → DsdiffParser-g4e89wz9.js} +3 -3
- package/dist/{DsdiffParser-kv863bc1.js.map → DsdiffParser-g4e89wz9.js.map} +1 -1
- package/dist/{DsfParser-hjwbg1q5.js → DsfParser-qa5yh5p1.js} +3 -3
- package/dist/{DsfParser-hjwbg1q5.js.map → DsfParser-qa5yh5p1.js.map} +1 -1
- package/dist/FlacParser-nyx65j1q.js +5 -0
- package/dist/{KeyProbe-1ps2524b.js → KeyProbe-n5p1w903.js} +3 -3
- package/dist/{KeyProbe-1ps2524b.js.map → KeyProbe-n5p1w903.js.map} +1 -1
- package/dist/{MP4Parser-3che75e1.js → MP4Parser-4at4dbvx.js} +3 -3
- package/dist/{MP4Parser-3che75e1.js.map → MP4Parser-4at4dbvx.js.map} +1 -1
- package/dist/{MatroskaParser-8hmdtx8q.js → MatroskaParser-gg2gtj81.js} +3 -3
- package/dist/{MatroskaParser-8hmdtx8q.js.map → MatroskaParser-gg2gtj81.js.map} +1 -1
- package/dist/{MpegParser-71aj1y8y.js → MpegParser-5h5c2yvc.js} +2 -2
- package/dist/{MusepackParser-87r0dynk.js → MusepackParser-9qew0gyx.js} +3 -3
- package/dist/{MusepackParser-87r0dynk.js.map → MusepackParser-9qew0gyx.js.map} +1 -1
- package/dist/{OggParser-w42xrxch.js → OggParser-t2z5byqa.js} +3 -3
- package/dist/{OggParser-w42xrxch.js.map → OggParser-t2z5byqa.js.map} +1 -1
- package/dist/{Picker-vj5ynnq2.js → Picker-32jwxayd.js} +3 -3
- package/dist/{Picker-vj5ynnq2.js.map → Picker-32jwxayd.js.map} +1 -1
- package/dist/{SessionPicker-hfbpherr.js → SessionPicker-yjbqbstr.js} +3 -3
- package/dist/{SessionPicker-hfbpherr.js.map → SessionPicker-yjbqbstr.js.map} +1 -1
- package/dist/{SkillBrowser-1d1fm1xj.js → SkillBrowser-ry8bvw8y.js} +3 -3
- package/dist/{SkillBrowser-1d1fm1xj.js.map → SkillBrowser-ry8bvw8y.js.map} +1 -1
- package/dist/{WavPackParser-87x24j40.js → WavPackParser-p843j2sp.js} +3 -3
- package/dist/{WavPackParser-87x24j40.js.map → WavPackParser-p843j2sp.js.map} +1 -1
- package/dist/{WaveParser-dgrykdpk.js → WaveParser-fx5fb7kt.js} +2 -2
- package/dist/{WizardApp-b4q48t4z.js → WizardApp-f2rfq172.js} +3 -3
- package/dist/{WizardApp-b4q48t4z.js.map → WizardApp-f2rfq172.js.map} +1 -1
- package/dist/{channels-d4xkxfar.js → channels-yshcsfap.js} +5 -5
- package/dist/{channels-d4xkxfar.js.map → channels-yshcsfap.js.map} +1 -1
- package/dist/client.d.ts +1937 -18
- package/dist/{config-p97t4qmk.js → config-29kq9vdx.js} +12 -12
- package/dist/{config-p97t4qmk.js.map → config-29kq9vdx.js.map} +1 -1
- package/dist/{credential-pq5ckfn8.js → credential-3d0edjdj.js} +5 -5
- package/dist/{credential-pq5ckfn8.js.map → credential-3d0edjdj.js.map} +1 -1
- package/dist/{index-kqdrdn38.js → index-0za0pzfc.js} +6 -6
- package/dist/{index-kqdrdn38.js.map → index-0za0pzfc.js.map} +1 -1
- package/dist/{index-pckx0hsw.js → index-1744qpr9.js} +5 -5
- package/dist/{index-pckx0hsw.js.map → index-1744qpr9.js.map} +1 -1
- package/dist/{index-v9mmd35e.js → index-22wv6mv5.js} +4 -4
- package/dist/{index-v9mmd35e.js.map → index-22wv6mv5.js.map} +1 -1
- package/dist/{index-tn16vrgz.js → index-242qsp5x.js} +7 -7
- package/dist/{index-tn16vrgz.js.map → index-242qsp5x.js.map} +1 -1
- package/dist/{index-ry1zw01x.js → index-2c264w09.js} +11 -11
- package/dist/index-2c264w09.js.map +13 -0
- package/dist/{index-szet76ct.js → index-3et72809.js} +26 -26
- package/dist/{index-szet76ct.js.map → index-3et72809.js.map} +2 -2
- package/dist/{index-vkh83ncj.js → index-438j3bwz.js} +3 -3
- package/dist/{index-vkh83ncj.js.map → index-438j3bwz.js.map} +1 -1
- package/dist/{index-e36yxmj2.js → index-55w9ttsc.js} +15 -15
- package/dist/{index-e36yxmj2.js.map → index-55w9ttsc.js.map} +2 -2
- package/dist/index-5gb3jt0d.js +6 -0
- package/dist/{index-4kgtfze8.js.map → index-5gb3jt0d.js.map} +1 -1
- package/dist/{index-f1vcncyr.js → index-653bpmm7.js} +2 -2
- package/dist/{index-5sjysvn1.js → index-6xymgmbr.js} +4 -4
- package/dist/{index-5sjysvn1.js.map → index-6xymgmbr.js.map} +1 -1
- package/dist/{index-999yf0d2.js → index-7ccn530n.js} +169 -169
- package/dist/{index-999yf0d2.js.map → index-7ccn530n.js.map} +11 -11
- package/dist/{index-gp4z9cn5.js → index-81982mhh.js} +7 -7
- package/dist/{index-gp4z9cn5.js.map → index-81982mhh.js.map} +1 -1
- package/dist/index-8j2chqz9.js +6 -0
- package/dist/{index-p0wjy7d6.js.map → index-8j2chqz9.js.map} +1 -1
- package/dist/{index-pyajzr2x.js → index-8v9e6sg4.js} +7 -7
- package/dist/{index-pyajzr2x.js.map → index-8v9e6sg4.js.map} +1 -1
- package/dist/index-93x98xe2.js +5 -0
- package/dist/{index-7gcqnh4j.js.map → index-93x98xe2.js.map} +2 -2
- package/dist/{index-xm9pw8zm.js → index-a2xv0d12.js} +4 -4
- package/dist/{index-xm9pw8zm.js.map → index-a2xv0d12.js.map} +1 -1
- package/dist/{index-552k3p6x.js → index-afzr95s2.js} +4 -4
- package/dist/{index-552k3p6x.js.map → index-afzr95s2.js.map} +1 -1
- package/dist/{index-87hc4xtp.js → index-ah3edkkd.js} +5 -5
- package/dist/{index-87hc4xtp.js.map → index-ah3edkkd.js.map} +1 -1
- package/dist/index-b2cwz1p4.js +70 -0
- package/dist/index-b2cwz1p4.js.map +12 -0
- package/dist/{index-r9yr9z01.js → index-c20594s9.js} +10 -10
- package/dist/{index-r9yr9z01.js.map → index-c20594s9.js.map} +1 -1
- package/dist/index-c7k0tr9z.js +6 -0
- package/dist/{index-3wzageha.js.map → index-c7k0tr9z.js.map} +2 -2
- package/dist/{index-akyngwhg.js → index-d4ap27z8.js} +4 -4
- package/dist/{index-akyngwhg.js.map → index-d4ap27z8.js.map} +1 -1
- package/dist/index-dm2ydvh7.js +6 -0
- package/dist/{index-99arhztm.js.map → index-dm2ydvh7.js.map} +1 -1
- package/dist/{index-jq292533.js → index-dr4bmkvw.js} +4 -4
- package/dist/{index-jq292533.js.map → index-dr4bmkvw.js.map} +1 -1
- package/dist/{index-p82s92n0.js → index-ftqdrptv.js} +4 -4
- package/dist/{index-p82s92n0.js.map → index-ftqdrptv.js.map} +1 -1
- package/dist/{index-d05kzgz3.js → index-fzq4awfm.js} +6 -6
- package/dist/{index-d05kzgz3.js.map → index-fzq4awfm.js.map} +1 -1
- package/dist/index-gbz3n3zp.js +6 -0
- package/dist/{index-gznvv86v.js.map → index-gbz3n3zp.js.map} +1 -1
- package/dist/{index-mjxqf1s1.js → index-gq51j1v4.js} +2 -2
- package/dist/{index-5v2ynsw9.js → index-gqad9zr3.js} +6 -6
- package/dist/{index-5v2ynsw9.js.map → index-gqad9zr3.js.map} +1 -1
- package/dist/{index-7tws4a98.js → index-gta69aw8.js} +38 -38
- package/dist/{index-7tws4a98.js.map → index-gta69aw8.js.map} +5 -5
- package/dist/{index-mdhrmj2j.js → index-hgbpwf9n.js} +3 -3
- package/dist/{index-mdhrmj2j.js.map → index-hgbpwf9n.js.map} +1 -1
- package/dist/{index-7xefn7m0.js → index-jaw3fzhk.js} +4 -4
- package/dist/{index-7xefn7m0.js.map → index-jaw3fzhk.js.map} +1 -1
- package/dist/{index-q9gwzp5j.js → index-mhncbgvg.js} +4 -4
- package/dist/{index-q9gwzp5j.js.map → index-mhncbgvg.js.map} +1 -1
- package/dist/{index-96cf3zz4.js → index-n9hvdky5.js} +4 -4
- package/dist/{index-96cf3zz4.js.map → index-n9hvdky5.js.map} +1 -1
- package/dist/{index-1c7kcyfq.js → index-p2yxw774.js} +4 -4
- package/dist/{index-1c7kcyfq.js.map → index-p2yxw774.js.map} +1 -1
- package/dist/{index-tqrx302v.js → index-pnz56nvf.js} +5 -5
- package/dist/{index-tqrx302v.js.map → index-pnz56nvf.js.map} +1 -1
- package/dist/{index-0a07ca51.js → index-ppafg4wv.js} +22 -22
- package/dist/{index-0a07ca51.js.map → index-ppafg4wv.js.map} +2 -2
- package/dist/{index-rsc5p35w.js → index-r6rpt940.js} +6 -6
- package/dist/{index-rsc5p35w.js.map → index-r6rpt940.js.map} +1 -1
- package/dist/{index-kmaq9hx4.js → index-r8cpr3za.js} +4 -4
- package/dist/{index-kmaq9hx4.js.map → index-r8cpr3za.js.map} +1 -1
- package/dist/{index-7zrpcfhj.js → index-rgdredf1.js} +4 -4
- package/dist/{index-7zrpcfhj.js.map → index-rgdredf1.js.map} +1 -1
- package/dist/{index-b8d2y1cb.js → index-ryw27wwe.js} +4 -4
- package/dist/{index-b8d2y1cb.js.map → index-ryw27wwe.js.map} +1 -1
- package/dist/{index-7e78cat9.js → index-sa3y3qk9.js} +4 -4
- package/dist/{index-7e78cat9.js.map → index-sa3y3qk9.js.map} +1 -1
- package/dist/{index-8wd4ymdg.js → index-svkzkfn0.js} +3 -3
- package/dist/{index-8wd4ymdg.js.map → index-svkzkfn0.js.map} +1 -1
- package/dist/index-v700serf.js +5 -0
- package/dist/{index-8wqf1n2y.js.map → index-v700serf.js.map} +2 -2
- package/dist/{index-rhsrphzb.js → index-v7jvv9ng.js} +4 -4
- package/dist/{index-rhsrphzb.js.map → index-v7jvv9ng.js.map} +1 -1
- package/dist/{index-pk385zk4.js → index-vbr1kf2g.js} +2 -2
- package/dist/index-wzk2npdh.js +8 -0
- package/dist/{index-dpa6r43h.js.map → index-wzk2npdh.js.map} +2 -2
- package/dist/{index-k99avg4y.js → index-y3cmd2g8.js} +4 -4
- package/dist/{index-k99avg4y.js.map → index-y3cmd2g8.js.map} +1 -1
- package/dist/index.js +128 -128
- package/dist/index.js.map +4 -4
- package/dist/serve.d.ts +7 -0
- package/dist/serve.d.ts.map +1 -1
- package/dist/{web-t6d2vbx0.js → web-10856pm1.js} +4 -4
- package/dist/{web-t6d2vbx0.js.map → web-10856pm1.js.map} +1 -1
- package/dist/wire.d.ts +923 -7
- package/dist/wrapper-rgk1asmr.js +5 -0
- package/dist/{wrapper-8x4hpa5z.js.map → wrapper-rgk1asmr.js.map} +1 -1
- package/package.json +6 -5
- package/dist/APEv2Parser-e7k9bv13.js +0 -5
- package/dist/App-pg0dr8an.js +0 -11
- package/dist/FlacParser-7tvpty5w.js +0 -5
- package/dist/index-3wzageha.js +0 -6
- package/dist/index-4kgtfze8.js +0 -6
- package/dist/index-4t6mjaz9.js +0 -70
- package/dist/index-4t6mjaz9.js.map +0 -12
- package/dist/index-7gcqnh4j.js +0 -5
- package/dist/index-8wqf1n2y.js +0 -5
- package/dist/index-99arhztm.js +0 -6
- package/dist/index-dpa6r43h.js +0 -8
- package/dist/index-gznvv86v.js +0 -6
- package/dist/index-p0wjy7d6.js +0 -6
- package/dist/index-ry1zw01x.js.map +0 -13
- package/dist/wrapper-8x4hpa5z.js +0 -5
- /package/dist/{AiffParser-btgza62h.js.map → AiffParser-d63xfxy7.js.map} +0 -0
- /package/dist/{FlacParser-7tvpty5w.js.map → FlacParser-nyx65j1q.js.map} +0 -0
- /package/dist/{MpegParser-71aj1y8y.js.map → MpegParser-5h5c2yvc.js.map} +0 -0
- /package/dist/{WaveParser-dgrykdpk.js.map → WaveParser-fx5fb7kt.js.map} +0 -0
- /package/dist/{index-f1vcncyr.js.map → index-653bpmm7.js.map} +0 -0
- /package/dist/{index-mjxqf1s1.js.map → index-gq51j1v4.js.map} +0 -0
- /package/dist/{index-pk385zk4.js.map → index-vbr1kf2g.js.map} +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{_t,K,Ae,Je,FA,gr,cr,lr,ts,Zn,ns,os,rs,Pr,is,et,Xn,$n,gs,tt,cs,eo,ls,Is,us,Gr,Fr,ds,Es,Cs,ps}from"./index-4t6mjaz9.js";import{qe,Kr,Yr,hs,Qs,o,I,P,Ge,Q,i,lA,U,T,hA}from"./index-999yf0d2.js";import{readFile as kt}from"node:fs/promises";var wt=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(c){return t[c]??null}let s={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},d={nan:"NaN"};return(c)=>{switch(c.code){case"invalid_type":{let p=d[c.expected]??c.expected,b=hs(c.input),S=d[b]??b;return`Invalid input: expected ${p}, received ${S}`}case"invalid_value":if(c.values.length===1)return`Invalid input: expected ${Yr(c.values[0])}`;return`Invalid option: expected one of ${Kr(c.values,"|")}`;case"too_big":{let p=c.inclusive?"<=":"<",b=e(c.origin);if(b)return`Too big: expected ${c.origin??"value"} to have ${p}${c.maximum.toString()} ${b.unit??"elements"}`;return`Too big: expected ${c.origin??"value"} to be ${p}${c.maximum.toString()}`}case"too_small":{let p=c.inclusive?">=":">",b=e(c.origin);if(b)return`Too small: expected ${c.origin} to have ${p}${c.minimum.toString()} ${b.unit}`;return`Too small: expected ${c.origin} to be ${p}${c.minimum.toString()}`}case"invalid_format":{let p=c;if(p.format==="starts_with")return`Invalid string: must start with "${p.prefix}"`;if(p.format==="ends_with")return`Invalid string: must end with "${p.suffix}"`;if(p.format==="includes")return`Invalid string: must include "${p.includes}"`;if(p.format==="regex")return`Invalid string: must match pattern ${p.pattern}`;return`Invalid ${s[p.format]??c.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${c.divisor}`;case"unrecognized_keys":return`Unrecognized key${c.keys.length>1?"s":""}: ${Kr(c.keys,", ")}`;case"invalid_key":return`Invalid key in ${c.origin}`;case"invalid_union":if(c.options&&Array.isArray(c.options)&&c.options.length>0)return`Invalid discriminator value. Expected ${c.options.map((b)=>`'${b}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${c.origin}`;default:return"Invalid input"}}};function de(){return{localeError:wt()}}qe(de());function _r(t={}){let e=t.now??(()=>new Date),s=new Map;return{approver:(c)=>new Promise((p)=>{let b={pending:{approvalId:c.approvalId,agentId:c.agentId,slug:c.slug,callId:c.callId,match:c.match,mutating:c.mutating,reason:c.reason,requestedAt:e().toISOString()},settle:(S)=>{s.delete(c.approvalId),p(S)}};s.set(c.approvalId,b),c.signal.addEventListener("abort",()=>b.settle(!1),{once:!0})}),pending:(c)=>[...s.values()].map((p)=>p.pending).filter((p)=>p.agentId===c).sort((p,b)=>p.requestedAt.localeCompare(b.requestedAt)),resolve:(c,p)=>{let b=s.get(c);if(b===void 0)return!1;return b.settle(p),!0},get size(){return s.size}}}function h(t,e,s={}){return new Response(JSON.stringify({error:t}),{status:e,headers:{"content-type":"application/json; charset=utf-8",...s}})}function ke(){return h({code:"unauthorized",message:"Missing or invalid bearer token.",hint:"Send Authorization: Bearer <token>, where the token is either the value of the variable named by server.tokenEnv or an operator key from POST /v1/keys. A revoked key, an expired one and a wrong one answer the same way on purpose."},401)}function De(){return h({code:"claim_spent",message:"That claim has already been exchanged.",hint:"A claim is good for one key. Use the key it minted; if it is lost, restart with --claim to print a new one — a claim lives in the process rather than the database, so it never outlives the boot that printed it."},401)}function St(t,e){return h({code:"capability_required",message:`This credential cannot ${e}.`,hint:`The key is scoped, and "${t}" is not among its capabilities. GET /v1/keys shows what each key may do; mint another with POST /v1/keys, or use the server token. An unscoped key has all of them.`,field:"scope.can"},403)}function Se(t,e){if(t.length!==e.length)return!1;let s=0;for(let d=0;d<t.length;d+=1)s|=t.charCodeAt(d)^e.charCodeAt(d);return s===0}function xt(t){let e=t.headers.get("authorization")??"";return e.startsWith("Bearer ")?e.slice(7):""}async function Et(t){let e=xt(t.request);if(t.expected!==void 0&&Se(e,t.expected))return{kind:"token"};if(e!==""){let s=await t.keys.findLive(await cr(e),new Date(t.at).toISOString());if(s!==void 0)return await t.keys.touch(s.keyId,new Date(t.at).toISOString()),{kind:"key",keyId:s.keyId,label:s.label,...s.scope===void 0?{}:{scope:s.scope}};if(t.claim!==void 0&&Se(e,t.claim.token)){if(t.request.method!=="POST"||t.pathname!=="/v1/keys")return ke();if(!t.claim.live())return De();return{kind:"claim"}}}return ke()}var Ue="dispach.bearer";function Tt(t){let e=t.headers.get("sec-websocket-protocol");if(e===null)return;let s=e.split(",").map((c)=>c.trim()),d=s.indexOf(Ue);return d===-1?void 0:s[d+1]??""}function Ct(t,e){let s=new Headers(t.headers);return s.set("authorization",`Bearer ${e}`),new Request(t.url,{method:t.method,headers:s})}function x(t,e){return t.meta({...e})}function ne(t,e){return t.meta({description:e})}var Nt=i({id:x(o().trim().min(1),{code:"sender_invalid",hint:'Send { "from": { "id": "agent:ops-bot", "kind": "agent" } }, or omit it entirely for a turn the token-holder is sending itself.',description:"Stable identifier for the sender. Appears on the turn row and in events."}),kind:x(T(et,{error:(t)=>{let e=typeof t.input==="string"?t.input:void 0,s=e===void 0?void 0:_t(e,et);return`from.kind must be one of: ${et.join(", ")}.${s===void 0?"":` Did you mean "${s}"?`}`}}),{code:"sender_invalid",hint:'This field decides the trust boundary — "agent" fences the message and blocks mutating tools for the turn, "user" does not — so there is no default and an unknown value is refused rather than guessed at. A turn the token-holder is sending itself omits "from".',description:'The trust boundary. "agent" fences the text as data and blocks mutating tools for the whole turn.'}),name:x(o().optional(),{code:"sender_invalid",hint:"A display name, shown beside the sender id. Omit it rather than sending an empty string.",description:"Human-readable name for the sender."})}).meta({description:"Attribution for a turn somebody other than the token-holder is sending. Omit for your own."}),jt=x(lA([hA("none"),i({channel:o().min(1),to:o().min(1)})]),{code:"deliver_invalid",hint:'A bare channel id is not enough on an API turn: the request has no originating conversation, so there is no recipient to infer. Send { "channel": "tg", "to": "12345" }, or "none" to read the reply from the event stream.',description:'Where the reply goes. "none" leaves it on the event stream and in the store.'}),Be=i({text:x(o().trim().min(1),{code:"message_text_required",hint:'Send { "text": "..." }. An empty turn would be billed for a full prompt and produce nothing.',description:"What to say to the agent."}),sessionKey:ne(o().min(1).optional(),"Which conversation this belongs to. Defaults to `api:default`."),deliver:jt.optional(),from:Nt.optional(),stream:ne(P().optional(),"Stream the turn's events inline as SSE rather than returning a handle."),chunks:ne(P().optional(),"Include per-token `model.chunk` frames. Off by default — the reader decides.")}),Fe=i({granted:x(P(),{code:"approval_decision_required",hint:'Send { "granted": true } or { "granted": false }. There is no default: one direction would deny a call over a typo and the other would grant one, and neither is a decision anybody made.',description:"Whether the blocked tool call may proceed."})}),At=i({agents:Q(o().min(1)).optional().meta({code:"key_scope_agents_invalid",hint:'Send { "agents": ["milo"] } — a list of agent ids. Omit it for a key that reaches every agent. An id naming no agent on this server is reported rather than silently matching nothing.',description:"Agent ids this key may reach. Absent means all of them."}),sessions:o().min(1).optional().meta({code:"key_scope_sessions_invalid",hint:'Send { "sessions": "team_42:" } — a session-key prefix, with an optional trailing "*". A prefix rather than a list, because the conversations this key will cover do not exist yet when it is minted.',description:"Session-key prefix. Absent means every session."}),can:Q(T(["read","chat","write","admin","peer"])).optional().meta({code:"key_scope_can_invalid",hint:'Send { "can": ["chat", "read"] }. read (every GET), chat (send a message, answer an approval, stop a turn), write (schedules, phase, clearing a session), admin (keys, provisioning, start/stop/reload), and peer (a plugin route that asks for it — an A2A endpoint — and nothing else). Absent means all five; an empty array means none, and is honoured as written.',description:"Capabilities this key may exercise. Absent means all of them."}),participant:o().min(1).optional().meta({code:"key_scope_participant_invalid",hint:'Send { "participant": "user:018f…" } — the id this key speaks for. Every turn it starts acts for that participant: a from naming anyone else is refused, and an omitted one is filled in. Omit it for a backend that names senders itself.',description:"The participant every turn this key starts acts for. Absent: any sender."}),expiresIn:I().int().positive().optional().meta({code:"key_scope_expires_invalid",hint:'Send { "expiresIn": 3600 } — whole seconds from now, as a number. Relative rather than an absolute instant, because that would need the caller and this server to agree about the clock; the response reports the absolute expiresAt this server computed.',description:"Seconds until this key stops authenticating. Absent means never."})}),He=i({label:x(o(),{code:"key_label_required",hint:'Send { "label": "my browser" }. A label is required rather than defaulted because it is the only thing distinguishing two credentials in a listing, and "key 2" is a name nobody can act on when deciding which to revoke.',description:"How this credential is shown in a listing. Required; see `keyLabelProblem`."}),scope:At.optional().meta({code:"key_scope_invalid",hint:'Send { "scope": { "agents": ["milo"], "can": ["chat"] } }, or omit it entirely for a key that reaches everything — which is what every key minted before scopes existed does.',description:"Opt-in narrowing. Absent is an unscoped key."})}),Ke=i({phase:x(o().min(1),{code:"phase_invalid",hint:"Send the name of a phase this agent's manifest declares. `GET /v1/agents/:id` lists them.",description:"The phase to move this session into."})}),We=i({reason:x(o().optional(),{code:"agent_stop_invalid",hint:"A short note, recorded on the row and shown wherever the agent is reported as off.",description:"Why, for whoever reads the listing later."})}),Pt=i({path:x(o().min(1),{code:"config_path_unknown",hint:"GET /v1/agents/:id/config lists every field this surface may change, with what each one does.",description:"A dotted path, exactly as it appears in the manifest — `tools.pinned`, `model.main.id`."}),value:x(o(),{code:"config_value_unreadable",hint:'Text, the way it is typed at a terminal: a bare word, a number, true or false, a list as ["a", "b"], or a map as {k: v}. Quote anything containing a colon or a "#".',description:"The new value, as text. Read by the same parser the `config` command uses."}),confirm:ne(P().optional(),"Required only for a field whose own row carries a `confirm` sentence. Absent is not consent.")}),It=i({enabled:ne(P().optional(),"Switch the channel on or off. It takes effect at the agent's next start, because a channel is constructed at boot."),credential:x(o().min(1).optional(),{code:"channel_credential_unreadable",hint:"The value goes into the .env beside the manifest at 0600, under the variable that channel's own entry names. Send a non-empty string; an empty one fails the load exactly as a missing variable does.",description:"The channel's credential — a Telegram bot token. Never returned by any route; only whether it is set."})}),Ve=i({answers:x(U(o(),x(o(),{code:"provision_answer_invalid",hint:"Answers arrive as strings from the terminal and from here, and are validated per step. Send the value as a string — including a boolean-looking choice, whose values are named in GET /v1/provision.",description:"One answer. Always text, whatever the step's type looks like."})).optional(),{code:"provision_answers_required",hint:'Send { "answers": { "name": "milo", … } }. Every step you leave out takes its default, exactly as `init --yes` does with flags; GET /v1/provision lists them.',description:"A subset of the wizard's steps, as strings. `GET /v1/provision` lists every step with its prompt, default and choices. Send this or `template`, not both."}),template:x(o().min(1).optional(),{code:"provision_template_invalid",hint:"Send the template's name as a string. GET /v1/templates lists what this server has.",description:"Create the agent from a template in this server's sandbox instead of from answers. Needs `name`; takes `vars`."}),name:x(o().optional(),{code:"provision_name_required",hint:'Send { "template": "…", "name": "Acme store" }. The id every route keys on is derived from it.',description:"The new agent's name, with `template`. Its slug becomes the id; the template sees both as {{agent.name}} and {{agent.id}}."}),vars:x(U(o(),x(o(),{code:"template_value_invalid",hint:"Template values are one line of text, sent as strings.",description:"One variable's value."})).optional(),{code:"template_value_invalid",hint:`Send { "vars": { "store": "Acme" } }, every value a string. GET /v1/templates lists each template's variables.`,description:"Values for the template's declared variables. A secret variable's value goes to the agent's .env and is never returned."})}),Qe=(t)=>x(o().trim().min(1),{code:"participant_id_invalid",hint:'A participant id as your system knows the person, e.g. "user:018f…". Agents are "agent:<agentId>".',description:`The participant id${t===""?"":` (${t})`}.`}),Ye=i({id:Qe(""),name:ne(o().min(1).optional(),"A display name, shown to agents beside the id."),role:x(T(["admin","member"]).optional(),{code:"participant_role_invalid",hint:'Either "admin" (may assign agents to members) or "member". Omitted is "member".',description:'What the participant may do: "admin" also assigns agents.'})}),Xe=i({kind:x(T(["room","dm"]),{code:"conversation_kind_invalid",hint:'"dm" is one human and one agent and is always answered; "room" is anyone, and an agent answers only when mentioned.',description:"A room or a direct conversation."}),members:x(Q(o().trim().min(1)).min(1),{code:"conversation_members_required",hint:'Participant ids: registered humans, and agents as "agent:<agentId>".',description:"Who is in it."}),title:ne(o().min(1).optional(),"A name for a room, for the embedder's own listing.")}),Ze=i({add:x(Q(o().trim().min(1)).optional(),{code:"conversation_members_required",hint:"Participant ids to add.",description:"Participant ids to add."}),remove:x(Q(o().trim().min(1)).optional(),{code:"conversation_members_required",hint:"Participant ids to remove.",description:"Participant ids to remove."})}),nt=i({text:x(o().trim().min(1),{code:"message_text_required",hint:'Send { "text": "…" }.',description:"What was said."}),mentions:x(Q(o().trim().min(1)).optional(),{code:"conversation_mention_unknown",hint:'Member participant ids this message addresses, e.g. ["agent:crew"]. In a room only a mentioned agent answers.',description:"Members this addresses. In a room, the agents that answer."}),authorId:x(o().trim().min(1).optional(),{code:"conversation_author_required",hint:"Who said it. A key bound to a participant fills this in and may name no one else; an unbound key must name the author.",description:"The human member who said it. Filled in from a participant-bound key."})}),rt=i({participantId:Qe("assignee")}),at=i({presence:x(T(["online","offline"]),{code:"presence_invalid",hint:'Send { "presence": "online" } or "offline". It is pushed by you, never inferred; until it is, a person reads as online and no agent stands in for them.',description:"Whether the person is there. Decides whether their agent stands in for them in a DM."})}),it=i({scope:x(o().trim().min(1),{code:"memory_scope_invalid",hint:'A shared scope: "space", "owner:<participantId>" or "project:<projectId>".',description:"Where the note goes. `owner:<id>` is written only by that person; `space` by an admin or the designated space writer; a project by an admin."}),text:x(o().trim().min(1),{code:"memory_note_empty",hint:'Send { "scope": "space", "text": "…" } — one or two sentences worth remembering.',description:"The note. Recalled into an agent's prompt when a turn is about it."})}),ot=i({name:ne(o().min(1).optional(),"A display name for the embedder's own listing."),agents:x(Q(o().trim().min(1)).optional(),{code:"project_agents_invalid",hint:'Agent ids, bare ("crew", not "agent:crew"). Given, it replaces the membership; omitted, it is left alone.',description:"The agents that share this project's memory. Replaces the list when given."})}),st=i({writer:x(o().trim().min(1),{code:"space_writer_invalid",hint:'A registered participant id, or "agent:<agentId>" for an agent whose memory_write should go to the space.',description:"The one non-admin who may write the space. An agent named here saves every memory_write to the space, so name one that holds nobody's private context."})}),lt=i({bundle:x(U(o(),Ge()),{code:"bundle_files_invalid",hint:'Send { "bundle": <the body GET /v1/agents/:id/export returned> }.',description:"A bundle from GET /v1/agents/:id/export: MEMORY.md, memory/<name>.md and knowledge/<name>.md, nothing else."}),mode:x(T(["skip","overwrite"]).optional(),{code:"bundle_mode_invalid",hint:'Either "skip" (keep a knowledge file that exists, the default) or "overwrite". Memory is always merged note by note.',description:"What to do with a knowledge file the agent already has. Memory is merged either way."})}),ut=i({approve:x(P(),{code:"action_decision_required",hint:'Send { "approve": true } to run the queued call as it was asked, or false to decline it.',description:"Run the queued call (true) or decline it (false)."})}),ct=i({url:x(o().min(1),{code:"webhook_url_invalid",hint:"Send an absolute https:// URL. A receiver on a private network needs the operator to allow it in WEBHOOK_ALLOW.",description:"Where deliveries are POSTed. Checked against every address it resolves to, at subscribe and at every send."}),types:x(Q(o()).min(1),{code:"webhook_types_required",hint:'Send { "types": ["turn.end", "approval.requested"] }. Any event type except model.chunk; the wire spec lists them.',description:"The event types to deliver. `model.chunk` is not deliverable."}),agents:x(Q(o()).min(1).optional(),{code:"webhook_scope_invalid",hint:"Send agent ids this credential can reach, or leave agents out to hear every agent it can reach.",description:"Narrow the subscription to these agents. It can never hear more than the creating credential reaches."})}),dt=i({values:x(U(o(),x(o(),{code:"secret_value_invalid",hint:"Send each value as a non-empty string.",description:"One variable's value. Written to the agent's .env at 0600; never returned."})),{code:"secrets_values_required",hint:'Send { "values": { "MODEL_API_KEY": "…" } }. GET /v1/agents/:id/secrets lists the variables this agent reads.',description:"Variables to write into the agent's .env, keyed by name. Only names the agent's manifest reads are accepted."})});function B(t,e){let s=t.safeParse(e??{});if(s.success)return{ok:!0,value:s.data};let d=s.error.issues[0],c=(d?.path??[]).filter((S)=>typeof S==="string"),p=zt(t,c);return{ok:!1,error:{...{code:"request_body_invalid",message:c.length===0?d?.message??"The request body is invalid.":`${c.join(".")}: ${d?.message}`,hint:"The field above is the one to fix. GET /v1/openapi.json describes every body this server accepts, including the error code each field produces."},...p?.code===void 0?{}:{code:p.code},...p?.hint===void 0?{}:{hint:p.hint},...c.length===0?{}:{field:c.join(".")}}}}function zt(t,e){let s=t,d=fe(t);for(let c of e){if(s=Ot(s,c),s===void 0)break;d=fe(s)??fe(ft(s))??d}return d}function fe(t){let e=t?.meta();if(e?.code===void 0&&e?.hint===void 0)return;return e}function Ot(t,e){let s=ft(t),d=s?.shape;if(d?.[e]!==void 0)return d[e];return s?.def?.valueType}function ft(t){let e=t;for(let s=0;s<8&&e!==void 0;s+=1){let d=e.def?.innerType;if(d===void 0)return e;e=d}return e}var Rt={"GET /v1/health":{summary:"Liveness, the version, and how many agents are hosted."},"GET /v1/ready":{summary:"Whether a turn can be served yet.",statuses:[{code:503,when:"still starting; channels may still be connecting"}]},"GET /v1/activity":{summary:"Whether the process is idle, and when it must next be woken. For an external waker.",statuses:[{code:403,when:"the key is scoped to agents or sessions"}]},"GET /v1/agents":{summary:"Every agent this server knows about, hosted or switched off."},"GET /v1/agents/:id":{summary:"One agent, with its dialect, window, counts and warnings."},"GET /v1/agents/:id/export":{summary:"A slice of the agent as a JSON bundle: its carried memory file, memory archive and knowledge. Never the manifest, secrets or skills."},"POST /v1/agents/:id/import":{summary:"Merge a bundle into the agent: memory note by note, knowledge kept or overwritten. Reloads when the carried file or knowledge changed, and restores everything if that reload refuses.",body:lt,statuses:[{code:400,when:"a path a bundle cannot carry, or a bundle the agent would not load"}]},"POST /v1/agents/:id/reload":{summary:"Re-read the manifest by replacing the agent with a new instance.",statuses:[{code:409,when:"a turn is running — it is not aborted to apply a change"},{code:400,when:"a team member, which has no manifest of its own"}]},"GET /v1/provision":{summary:"The questions creating an agent asks, and whether this server can answer them."},"POST /v1/agents":{summary:"Create an agent, from answers or from a template, and adopt it into this host, live.",body:Ve,statuses:[{code:201,when:"created; `adopted` is empty with an `error` if it is not running"},{code:403,when:"not a loopback bind"},{code:501,when:"this server has no provisioner"}]},"POST /v1/webhooks":{summary:"Subscribe a URL to event types. The signing secret is returned once.",body:ct,statuses:[{code:201,when:"created; `secret` is in this response and no other"},{code:400,when:"a refused URL, an undeliverable type, or agents outside this key's reach"}]},"POST /v1/participants":{summary:"Register a human participant under the embedder's own id. No account is stored.",body:Ye,statuses:[{code:201,when:"registered, or updated if the id existed"}]},"GET /v1/participants":{summary:"The registered human participants."},"DELETE /v1/participants/:participantId":{summary:"Remove a participant and their conversation memberships."},"POST /v1/conversations":{summary:"Create a room or a DM among participants and agents (agent:<id>).",body:Xe,statuses:[{code:201,when:"created"},{code:403,when:"a participant-bound key creating a conversation it is not in"}]},"GET /v1/conversations":{summary:"The conversations this credential can see."},"GET /v1/conversations/:conversationId":{summary:"One conversation and its members."},"PATCH /v1/conversations/:conversationId/members":{summary:"Add or remove members of a room.",body:Ze},"POST /v1/conversations/:conversationId/messages":{summary:"Post a human member's message. In a room only the mentioned agents answer; in a DM the agent always does. Their replies arrive as conversation.message.",body:nt,statuses:[{code:202,when:"logged; the turns it starts run behind the response"},{code:403,when:"a participant-bound key naming another author"}]},"GET /v1/conversations/:conversationId/messages":{summary:"The conversation's log, oldest first, after a sequence number."},"PUT /v1/participants/:participantId/presence":{summary:"Push whether a person is there. In a DM between two people, an offline person's agent stands in for them.",body:at,statuses:[{code:403,when:"a participant-bound key setting someone else's presence"}]},"POST /v1/memory/notes":{summary:"Add a note to a shared memory scope — the space, a person's owner scope, or a project. Agents recall it when a turn is about it.",body:it,statuses:[{code:403,when:"this participant may not write that scope"},{code:404,when:"the scope's owner or project does not exist"}]},"GET /v1/memory/notes":{summary:"Every note in one shared scope, oldest first. An owner scope is readable by its owner."},"DELETE /v1/memory/notes/:noteId":{summary:"Remove a note. Whoever may write its scope may remove it."},"GET /v1/participants/:participantId/memory/reads":{summary:"The person's audit: every time an agent recalled their owner scope for somebody else, stand-ins included."},"GET /v1/projects":{summary:"Projects, each with the agents that share its memory."},"PUT /v1/projects/:projectId":{summary:"Define a project, or replace which agents share its memory. An admin's act.",body:ot},"DELETE /v1/projects/:projectId":{summary:"Remove a project and its notes."},"PUT /v1/memory/space/writer":{summary:"Name the one non-admin who may write the space. An agent named here saves its memory_write to the space.",body:st},"GET /v1/actions":{summary:"Mutating calls stand-ins queued for their owners. A member-bound key sees its own."},"POST /v1/actions/:actionId":{summary:"Approve or decline a queued action. Approved, the exact call runs as the owner's agent and the outcome is posted in the DM.",body:ut,statuses:[{code:404,when:"no such action, or not this key's to decide"},{code:409,when:"already decided"}]},"PUT /v1/agents/:id/assignee":{summary:"Record which member an agent works for. An admin participant's act.",body:rt},"DELETE /v1/agents/:id/assignee":{summary:"Clear an agent's assignment."},"GET /v1/webhooks":{summary:"The subscriptions this credential can see, with their delivery health. Never a secret."},"DELETE /v1/webhooks/:webhookId":{summary:"Delete a subscription and anything it still owed.",statuses:[{code:404,when:"no such subscription, or one outside this key's reach"}]},"GET /v1/usage":{summary:"What every agent in scope cost, per model call, grouped by agent, model, day or sender.",statuses:[{code:400,when:"an unknown grouping or a date that does not parse"}]},"GET /v1/agents/:id/usage":{summary:"What this agent cost, from the meter.",statuses:[{code:400,when:"an unknown grouping or a date that does not parse"}]},"GET /v1/agents/:id/turns":{summary:"Every turn this agent has taken, newest first, across sessions, paged by `before`.",statuses:[{code:400,when:"`limit` or `before` is not a positive whole number"}]},"GET /v1/templates":{summary:"The templates an agent can be created from, and the variables each declares."},"GET /v1/agents/:id/secrets":{summary:"Which variables the agent's manifest reads, and whether each is set. Never a value.",statuses:[{code:501,when:"this server has no credential writer"}]},"PUT /v1/agents/:id/secrets":{summary:"Write the agent's credentials into its .env and apply them: reload or adopt.",body:dt,statuses:[{code:200,when:"written; `applied` says whether the agent is running on them"},{code:400,when:"a variable the manifest does not read, or an empty value"},{code:501,when:"this server has no credential writer"}]},"POST /v1/agents/:id/stop":{summary:"Switch an agent off durably and drop it from this host now.",body:We,statuses:[{code:409,when:"a turn is running"}]},"POST /v1/agents/:id/start":{summary:"Switch it back on and have this host adopt it.",statuses:[{code:501,when:"this server cannot look up manifests"}]},"POST /v1/agents/:id/messages":{summary:"Start a turn. Returns once accepted; the turn runs detached.",body:Be,statuses:[{code:202,when:"accepted"},{code:429,when:"over limits.maxConcurrentTurns or limits.tokens; nothing recorded"}]},"POST /v1/agents/:id/turns/:turnId/stop":{summary:"Cooperatively stop a turn this API started.",statuses:[{code:409,when:"no cancel handle — a channel or schedule started it"}]},"GET /v1/agents/:id/turns/:turnId/stream":{summary:"One turn's events as SSE, replayed from the start and then live.",query:[{name:"chunks",about:"Include per-token frames. Off by default."},{name:"types",about:"Narrow to these event types, comma-separated."}],statuses:[{code:200,when:"an event stream; see the event table in the wire spec"}]},"GET /v1/events":{summary:"Every event this process emits, as SSE. The firehose.",query:[{name:"agentId",about:"Narrow to one agent."},{name:"sessionKey",about:"Narrow to one conversation."},{name:"chunks",about:"Include per-token frames. Off by default."},{name:"types",about:"Narrow to these event types, comma-separated."}],statuses:[{code:200,when:"an event stream; see the event table in the wire spec"}]},"GET /v1/agents/:id/approvals":{summary:"Questions waiting on a person, oldest first."},"POST /v1/agents/:id/approvals/:approvalId":{summary:"Answer one blocked tool call.",body:Fe},"POST /v1/keys":{summary:"Mint an operator key. The secret is returned once and never again.",body:He,statuses:[{code:201,when:"minted"}]},"GET /v1/keys":{summary:"Every key, live and revoked. Never a secret."},"DELETE /v1/keys/:keyId":{summary:"Revoke a key. A soft delete; the row survives."},"GET /v1/agents/:id/turns/:turnId":{summary:"One turn's stored row."},"GET /v1/agents/:id/sessions":{summary:"Conversations, most recently active first."},"GET /v1/agents/:id/sessions/:key":{summary:"One conversation's summary."},"GET /v1/agents/:id/sessions/:key/messages":{summary:"A page of a conversation's messages.",query:[{name:"limit",about:"How many to return."},{name:"before",about:"Page backwards from this message id."}]},"DELETE /v1/agents/:id/sessions/:key":{summary:"Drop a conversation's history, turns and derived index."},"POST /v1/agents/:id/sessions/:key/phase":{summary:"Move a session into a declared phase.",body:Ke},"GET /v1/agents/:id/config":{summary:"Every manifest field this surface may set, what it does, and its current value."},"PATCH /v1/agents/:id/config":{summary:"Set one manifest field, then replace the agent so it takes effect.",statuses:[{code:409,when:"the field carries a confirm sentence and `confirm` was not true"},{code:409,when:"the agent came from an object, so there is no manifest to edit"},{code:400,when:"the path is not settable here, or the result would not validate"}]},"PATCH /v1/agents/:id/channels/:channelId":{summary:"Connect or disconnect a channel, and set its credential.",statuses:[{code:400,when:"neither `enabled` nor `credential` was sent, or the channel is unknown"},{code:409,when:"the agent came from an object, so there is no manifest to edit"},{code:501,when:"the host supplied no channel actions"}]},"POST /v1/agents/:id/channels/:channelId/unpair":{summary:"Forget a channel's stored pairing, so the next start offers a new code.",statuses:[{code:404,when:"this agent has no such channel"},{code:409,when:"the channel stores no pairing — a typed credential is a PATCH"}]},"GET /v1/agents/:id/schedules":{summary:"Every schedule, from the store."},"POST /v1/agents/:id/schedules":{summary:"Create a schedule. Validated by the manifest's own schedule rules.",statuses:[{code:201,when:"created"}]},"GET /v1/agents/:id/schedules/:sid":{summary:"One schedule's row."},"PATCH /v1/agents/:id/schedules/:sid":{summary:"Replace a schedule the API created.",statuses:[{code:409,when:"the manifest declares it, so reconciliation would undo the write"}]},"DELETE /v1/agents/:id/schedules/:sid":{summary:"Delete a schedule the API created.",statuses:[{code:409,when:"the manifest declares it, so the next boot would re-create it"}]},"POST /v1/agents/:id/schedules/:sid/run":{summary:"Fire a schedule now, out of band.",statuses:[{code:429,when:"over a governor limit; nothing recorded"}]},"GET /v1/agents/:id/tools":{summary:"The resolved catalogue, with trust and phases."},"GET /v1/agents/:id/skills":{summary:"What the skills index holds."},"GET /v1/agents/:id/context":{summary:"The prompt the next turn would be given, without running one.",query:[{name:"sessionKey",about:"Which conversation to assemble for."},{name:"input",about:"Pretend this is the next message."}]},"POST /v1/channels/:channelId/webhook/:agentId":{summary:"A channel provider's webhook. Open by design; the provider authenticates itself."},"GET /v1/openapi.json":{summary:"This document."},"GET /docs":{summary:"A browser reference over this document."}};function Lt(t){return t.startsWith("/v1/")||t==="/docs"}function Mt(t){let e={};for(let s of t.routes){if(!Lt(s.pattern))continue;let d=Rt[`${s.method} ${s.pattern}`];if(d===void 0)continue;let c=s.pattern.replace(/:([A-Za-z0-9_]+)/g,"{$1}"),p=[...s.pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map((j)=>({name:j[1],in:"path",required:!0,schema:{type:"string"}})),b=(d.query??[]).map((j)=>({name:j.name,in:"query",required:!1,description:j.about,schema:{type:"string"}})),S={};for(let j of d.statuses??[])S[String(j.code)]={description:j.when};if(S["200"]===void 0&&S["201"]===void 0){if(S["202"]===void 0)S["200"]={description:"OK"}}if(S["401"]={description:"No credential, or one this server does not accept."},s.pattern.includes(":id"))S["404"]={description:"No such agent, or it is switched off."};e[c]??={};let W={summary:d.summary,...p.length+b.length===0?{}:{parameters:[...p,...b]},responses:S};if(d.body!==void 0)W.requestBody={required:!0,content:{"application/json":{schema:Qs(d.body,{target:"draft-2020-12",io:"input"})}}};e[c][s.method.toLowerCase()]=W}return{openapi:"3.1.0",info:{title:"Dispach agent server",version:Je,description:"Generated from the router table and the request schemas — see openapi.ts. The binding contract is docs/04-SPEC-WIRE.md, which is checked against the code; @dispach/client's types are the response reference."},...t.serverUrl===void 0?{}:{servers:[{url:t.serverUrl}]},components:{securitySchemes:{bearer:{type:"http",scheme:"bearer",description:"An operator key or the configured token."}},schemas:{Error:{type:"object",description:"Every failure has this shape. `hint` is never absent — it is the part that says what to do.",properties:{error:{type:"object",required:["code","message","hint"],properties:{code:{type:"string"},message:{type:"string"},hint:{type:"string"},field:{type:"string"}}}}}}},security:[{bearer:[]}],paths:e}}var Dt=new Set(["127.0.0.1","::1","localhost","[::1]"]);function se(t){return Dt.has(t.toLowerCase())}function re(t){let e=t.trim();if(e===""||e.toLowerCase()==="null")return;try{return new URL(e.includes("://")?e:`http://${e}`).hostname.toLowerCase().replace(/^\[|\]$/g,"")}catch{return}}function xe(t){return se(t)||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}function le(t,e){let s=se(e.host),d=t.headers.get("host"),c=t.headers.get("origin");if(s){let b=d===null?void 0:re(d),S=e.allowedHosts??[];if(!(b!==void 0&&(xe(b)||S.some((j)=>re(j)===b))))return{code:"host_not_allowed",message:`This server does not answer to the host ${d??"(absent)"}.`,hint:"It is bound to loopback, so only a loopback name or address can legitimately reach it — a request addressed to any other name arrived through DNS pointed at this machine, which is how a web page reaches a local server it was never given access to. Add the name to server.allowedHosts if a proxy on this machine needs it.",field:"server.allowedHosts"}}if(c===null)return;let p=re(c);if(p!==void 0){if(xe(p))return;if((e.allowedOrigins??[]).some((b)=>re(b)===p))return;if(!s&&d!==null&&re(d)===p)return}return{code:"origin_not_allowed",message:`Refusing a request from the origin ${c}.`,hint:s?"This server is bound to loopback, so a page served from anywhere else has no business calling it. Add the origin to server.allowedOrigins if you meant to allow it.":"Only a page served from this server's own host may call it. Add the origin to server.allowedOrigins if you meant to allow it — there is no wildcard, deliberately.",field:"server.allowedOrigins"}}function Ut(t,e){let s=t.headers.get("origin");if(s===null)return{};if(le(t,e)!==void 0)return{};return{"access-control-allow-origin":s,vary:"Origin"}}function Bt(t,e){let s=t.headers.get("access-control-request-headers");return{"access-control-allow-methods":e.join(", "),"access-control-allow-headers":s??"authorization, content-type","access-control-max-age":"600"}}function he(t,e){if(t.kind!=="key")return t.kind!=="claim";let s=t.scope?.can;return s===void 0||s.includes(e)}function V(t,e){if(t.kind!=="key")return t.kind!=="claim";let s=t.scope?.agents;return s===void 0||s.includes(e)}function ue(t,e){if(t.kind!=="key")return t.kind!=="claim";let s=t.scope?.sessions;if(s===void 0)return!0;return e.startsWith(s.endsWith("*")?s.slice(0,-1):s)}function ie(t){if(t.kind==="claim")return{agentIds:[]};if(t.kind!=="key")return{};let e=t.scope?.agents,s=t.scope?.sessions;return{...e===void 0?{}:{agentIds:e},...s===void 0?{}:{sessionPrefix:s.endsWith("*")?s.slice(0,-1):s}}}function ht(t){if(t.kind!=="key")return!1;let e=t.scope;return e!==void 0&&(e.agents!==void 0||e.sessions!==void 0||e.can!==void 0)}function pt(t,e){let s=t.kind==="key"?t.scope?.participant:void 0;if(s===void 0)return{ok:!0,from:e};if(e===void 0)return{ok:!0,from:{id:s,kind:"user"}};if(e.id===s&&e.kind==="user")return{ok:!0,from:e};return{ok:!1,error:{code:"sender_not_bound_participant",message:`This key speaks for ${s}, and the message names ${e.kind} ${e.id}.`,hint:`A key bound to a participant starts turns only as that participant, so the tools the turn calls act for them. Omit from (it is filled in), or send from.id "${s}" with kind "user". A backend that names senders itself needs a key minted without scope.participant.`,field:"from"}}}class mt{#e=[];add(t,e,s,d){return this.#e.push({method:t.toUpperCase(),pattern:e,handler:s,capability:d.capability,streaming:d.streaming===!0,segments:Ee(e)}),this}routes(){return this.#e.map(({method:t,pattern:e,handler:s,streaming:d,capability:c})=>({method:t,pattern:e,handler:s,streaming:d,capability:c}))}match(t,e){let s=Ee(e),d=[];for(let c of this.#e){let p=Ft(c.segments,s);if(p===void 0)continue;if(d.push(c),c.method===t.toUpperCase())return{kind:"found",handler:c.handler,params:p,streaming:c.streaming,capability:c.capability}}if(d.length>0)return{kind:"method",allowed:[...new Set(d.map((c)=>c.method))]};return{kind:"none"}}}function Ee(t){return t.split("/").filter((e)=>e!=="")}function Ft(t,e){if(t.length!==e.length)return;let s={};for(let[d,c]of t.entries()){let p=e[d];if(p===void 0)return;if(c.startsWith(":")){try{s[c.slice(1)]=decodeURIComponent(p)}catch{return}continue}if(c!==p)return}return s}var gt=15000;function Ht(t){let e=[];if(t.event!==void 0)e.push(`event: ${t.event}`);if(t.id!==void 0)e.push(`id: ${t.id}`);let s=typeof t.data==="string"?t.data:JSON.stringify(t.data);for(let d of s.split(`
|
|
3
|
-
`))e.push(`data: ${
|
|
2
|
+
import{et,x,te,Je,FA,gr,cr,lr,ns,Pr,Zn,os,rs,is,vr,ss,At,Xn,$n,cs,nt,ls,eo,Is,us,ds,Fr,Ur,Es,Cs,ps,fs}from"./index-b2cwz1p4.js";import{qe,Yr,jr,Qs,ys,o,I,P,Ge,Q,i,lA,U,T,QA}from"./index-7ccn530n.js";import{readFile as St}from"node:fs/promises";var kt=()=>{let n={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(c){return n[c]??null}let l={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},f={nan:"NaN"};return(c)=>{switch(c.code){case"invalid_type":{let m=f[c.expected]??c.expected,b=Qs(c.input),E=f[b]??b;return`Invalid input: expected ${m}, received ${E}`}case"invalid_value":if(c.values.length===1)return`Invalid input: expected ${jr(c.values[0])}`;return`Invalid option: expected one of ${Yr(c.values,"|")}`;case"too_big":{let m=c.inclusive?"<=":"<",b=e(c.origin);if(b)return`Too big: expected ${c.origin??"value"} to have ${m}${c.maximum.toString()} ${b.unit??"elements"}`;return`Too big: expected ${c.origin??"value"} to be ${m}${c.maximum.toString()}`}case"too_small":{let m=c.inclusive?">=":">",b=e(c.origin);if(b)return`Too small: expected ${c.origin} to have ${m}${c.minimum.toString()} ${b.unit}`;return`Too small: expected ${c.origin} to be ${m}${c.minimum.toString()}`}case"invalid_format":{let m=c;if(m.format==="starts_with")return`Invalid string: must start with "${m.prefix}"`;if(m.format==="ends_with")return`Invalid string: must end with "${m.suffix}"`;if(m.format==="includes")return`Invalid string: must include "${m.includes}"`;if(m.format==="regex")return`Invalid string: must match pattern ${m.pattern}`;return`Invalid ${l[m.format]??c.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${c.divisor}`;case"unrecognized_keys":return`Unrecognized key${c.keys.length>1?"s":""}: ${Yr(c.keys,", ")}`;case"invalid_key":return`Invalid key in ${c.origin}`;case"invalid_union":if(c.options&&Array.isArray(c.options)&&c.options.length>0)return`Invalid discriminator value. Expected ${c.options.map((b)=>`'${b}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${c.origin}`;default:return"Invalid input"}}};function fe(){return{localeError:kt()}}qe(fe());function _r(n={}){let e=n.now??(()=>new Date),l=new Map;return{approver:(c)=>new Promise((m)=>{let b={pending:{approvalId:c.approvalId,agentId:c.agentId,slug:c.slug,callId:c.callId,match:c.match,mutating:c.mutating,reason:c.reason,requestedAt:e().toISOString()},settle:(E)=>{l.delete(c.approvalId),m(E)}};l.set(c.approvalId,b),c.signal.addEventListener("abort",()=>b.settle(!1),{once:!0})}),pending:(c)=>[...l.values()].map((m)=>m.pending).filter((m)=>m.agentId===c).sort((m,b)=>m.requestedAt.localeCompare(b.requestedAt)),resolve:(c,m)=>{let b=l.get(c);if(b===void 0)return!1;return b.settle(m),!0},get size(){return l.size}}}function h(n,e,l={}){return new Response(JSON.stringify({error:n}),{status:e,headers:{"content-type":"application/json; charset=utf-8",...l}})}function Se(){return h({code:"unauthorized",message:"Missing or invalid bearer token.",hint:"Send Authorization: Bearer <token>, where the token is either the value of the variable named by server.tokenEnv or an operator key from POST /v1/keys. A revoked key, an expired one and a wrong one answer the same way on purpose."},401)}function Me(){return h({code:"claim_spent",message:"That claim has already been exchanged.",hint:"A claim is good for one key. Use the key it minted; if it is lost, restart with --claim to print a new one — a claim lives in the process rather than the database, so it never outlives the boot that printed it."},401)}function xt(n,e){return h({code:"capability_required",message:`This credential cannot ${e}.`,hint:`The key is scoped, and "${n}" is not among its capabilities. GET /v1/keys shows what each key may do; mint another with POST /v1/keys, or use the server token. An unscoped key has all of them.`,field:"scope.can"},403)}function xe(n,e){if(n.length!==e.length)return!1;let l=0;for(let f=0;f<n.length;f+=1)l|=n.charCodeAt(f)^e.charCodeAt(f);return l===0}function Et(n){let e=n.headers.get("authorization")??"";return e.startsWith("Bearer ")?e.slice(7):""}async function Tt(n){let e=Et(n.request);if(n.expected!==void 0&&xe(e,n.expected))return{kind:"token"};if(e!==""){let l=await n.keys.findLive(await cr(e),new Date(n.at).toISOString());if(l!==void 0)return await n.keys.touch(l.keyId,new Date(n.at).toISOString()),{kind:"key",keyId:l.keyId,label:l.label,...l.scope===void 0?{}:{scope:l.scope}};if(n.claim!==void 0&&xe(e,n.claim.token)){if(n.request.method!=="POST"||n.pathname!=="/v1/keys")return Se();if(!n.claim.live())return Me();return{kind:"claim"}}}return Se()}var Ue="dispach.bearer";function Ct(n){let e=n.headers.get("sec-websocket-protocol");if(e===null)return;let l=e.split(",").map((c)=>c.trim()),f=l.indexOf(Ue);return f===-1?void 0:l[f+1]??""}function _t(n,e){let l=new Headers(n.headers);return l.set("authorization",`Bearer ${e}`),new Request(n.url,{method:n.method,headers:l})}function S(n,e){return n.meta({...e})}function re(n,e){return n.meta({description:e})}var Nt=i({id:S(o().trim().min(1),{code:"sender_invalid",hint:'Send { "from": { "id": "agent:ops-bot", "kind": "agent" } }, or omit it entirely for a turn the token-holder is sending itself.',description:"Stable identifier for the sender. Appears on the turn row and in events."}),kind:S(T(At,{error:(n)=>{let e=typeof n.input==="string"?n.input:void 0,l=e===void 0?void 0:et(e,At);return`from.kind must be one of: ${At.join(", ")}.${l===void 0?"":` Did you mean "${l}"?`}`}}),{code:"sender_invalid",hint:'This field decides the trust boundary — "agent" fences the message and blocks mutating tools for the turn, "user" does not — so there is no default and an unknown value is refused rather than guessed at. A turn the token-holder is sending itself omits "from".',description:'The trust boundary. "agent" fences the text as data and blocks mutating tools for the whole turn.'}),name:S(o().optional(),{code:"sender_invalid",hint:"A display name, shown beside the sender id. Omit it rather than sending an empty string.",description:"Human-readable name for the sender."})}).meta({description:"Attribution for a turn somebody other than the token-holder is sending. Omit for your own."}),jt=S(lA([QA("none"),i({channel:o().min(1),to:o().min(1)})]),{code:"deliver_invalid",hint:'A bare channel id is not enough on an API turn: the request has no originating conversation, so there is no recipient to infer. Send { "channel": "tg", "to": "12345" }, or "none" to read the reply from the event stream.',description:'Where the reply goes. "none" leaves it on the event stream and in the store.'}),Be=i({text:S(o().trim().min(1),{code:"message_text_required",hint:'Send { "text": "..." }. An empty turn would be billed for a full prompt and produce nothing.',description:"What to say to the agent."}),sessionKey:re(o().min(1).optional(),"Which conversation this belongs to. Defaults to `api:default`."),deliver:jt.optional(),from:Nt.optional(),stream:re(P().optional(),"Stream the turn's events inline as SSE rather than returning a handle."),chunks:re(P().optional(),"Include per-token `model.chunk` frames. Off by default — the reader decides.")}),Fe=i({channel:S(o().min(1),{code:"delivery_channel_required",hint:`Name a channel id from the agent's manifest, e.g. { "channel": "tg", ... } — the id, not the type.`,description:"The channel id to send on."}),to:S(o().min(1),{code:"delivery_recipient_required",hint:"The channel's own address for the conversation: a Telegram chat id, a WhatsApp JID, a Slack channel id. The peer id an inbound message arrived with is always right.",description:"Who to send it to, in the channel's own addressing."}),text:S(o().trim().min(1),{code:"delivery_text_required",hint:'Send { "text": "..." }. An empty message has nothing to deliver.',description:"The exact text to send. No model turn runs."}),key:S(o().min(1),{code:"delivery_key_required",hint:"Any string unique to this send, such as your own message id. A retry with the same key is not sent or recorded twice.",description:"Idempotency key: a repeated key is accepted and does nothing."})}),He=i({granted:S(P(),{code:"approval_decision_required",hint:'Send { "granted": true } or { "granted": false }. There is no default: one direction would deny a call over a typo and the other would grant one, and neither is a decision anybody made.',description:"Whether the blocked tool call may proceed."})}),Pt=i({agents:Q(o().min(1)).optional().meta({code:"key_scope_agents_invalid",hint:'Send { "agents": ["milo"] } — a list of agent ids. Omit it for a key that reaches every agent. An id naming no agent on this server is reported rather than silently matching nothing.',description:"Agent ids this key may reach. Absent means all of them."}),sessions:o().min(1).optional().meta({code:"key_scope_sessions_invalid",hint:'Send { "sessions": "team_42:" } — a session-key prefix, with an optional trailing "*". A prefix rather than a list, because the conversations this key will cover do not exist yet when it is minted.',description:"Session-key prefix. Absent means every session."}),can:Q(T(["read","chat","write","admin","peer"])).optional().meta({code:"key_scope_can_invalid",hint:'Send { "can": ["chat", "read"] }. read (every GET), chat (send a message, answer an approval, stop a turn), write (schedules, phase, clearing a session), admin (keys, provisioning, start/stop/reload), and peer (a plugin route that asks for it — an A2A endpoint — and nothing else). Absent means all five; an empty array means none, and is honoured as written.',description:"Capabilities this key may exercise. Absent means all of them."}),participant:o().min(1).optional().meta({code:"key_scope_participant_invalid",hint:'Send { "participant": "user:018f…" } — the id this key speaks for. Every turn it starts acts for that participant: a from naming anyone else is refused, and an omitted one is filled in. Omit it for a backend that names senders itself.',description:"The participant every turn this key starts acts for. Absent: any sender."}),expiresIn:I().int().positive().optional().meta({code:"key_scope_expires_invalid",hint:'Send { "expiresIn": 3600 } — whole seconds from now, as a number. Relative rather than an absolute instant, because that would need the caller and this server to agree about the clock; the response reports the absolute expiresAt this server computed.',description:"Seconds until this key stops authenticating. Absent means never."})}),Ke=i({label:S(o(),{code:"key_label_required",hint:'Send { "label": "my browser" }. A label is required rather than defaulted because it is the only thing distinguishing two credentials in a listing, and "key 2" is a name nobody can act on when deciding which to revoke.',description:"How this credential is shown in a listing. Required; see `keyLabelProblem`."}),scope:Pt.optional().meta({code:"key_scope_invalid",hint:'Send { "scope": { "agents": ["milo"], "can": ["chat"] } }, or omit it entirely for a key that reaches everything — which is what every key minted before scopes existed does.',description:"Opt-in narrowing. Absent is an unscoped key."})}),We=i({phase:S(o().min(1),{code:"phase_invalid",hint:"Send the name of a phase this agent's manifest declares. `GET /v1/agents/:id` lists them.",description:"The phase to move this session into."})}),Ve=i({reason:S(o().optional(),{code:"agent_stop_invalid",hint:"A short note, recorded on the row and shown wherever the agent is reported as off.",description:"Why, for whoever reads the listing later."})}),It=i({path:S(o().min(1),{code:"config_path_unknown",hint:"GET /v1/agents/:id/config lists every field this surface may change, with what each one does.",description:"A dotted path, exactly as it appears in the manifest — `tools.pinned`, `model.main.id`."}),value:S(o(),{code:"config_value_unreadable",hint:'Text, the way it is typed at a terminal: a bare word, a number, true or false, a list as ["a", "b"], or a map as {k: v}. Quote anything containing a colon or a "#".',description:"The new value, as text. Read by the same parser the `config` command uses."}),confirm:re(P().optional(),"Required only for a field whose own row carries a `confirm` sentence. Absent is not consent.")}),zt=i({enabled:re(P().optional(),"Switch the channel on or off. It takes effect at the agent's next start, because a channel is constructed at boot."),credential:S(o().min(1).optional(),{code:"channel_credential_unreadable",hint:"The value goes into the .env beside the manifest at 0600, under the variable that channel's own entry names. Send a non-empty string; an empty one fails the load exactly as a missing variable does.",description:"The channel's credential — a Telegram bot token. Never returned by any route; only whether it is set."})}),Qe=i({answers:S(U(o(),S(o(),{code:"provision_answer_invalid",hint:"Answers arrive as strings from the terminal and from here, and are validated per step. Send the value as a string — including a boolean-looking choice, whose values are named in GET /v1/provision.",description:"One answer. Always text, whatever the step's type looks like."})).optional(),{code:"provision_answers_required",hint:'Send { "answers": { "name": "milo", … } }. Every step you leave out takes its default, exactly as `init --yes` does with flags; GET /v1/provision lists them.',description:"A subset of the wizard's steps, as strings. `GET /v1/provision` lists every step with its prompt, default and choices. Send this or `template`, not both."}),template:S(o().min(1).optional(),{code:"provision_template_invalid",hint:"Send the template's name as a string. GET /v1/templates lists what this server has.",description:"Create the agent from a template in this server's sandbox instead of from answers. Needs `name`; takes `vars`."}),name:S(o().optional(),{code:"provision_name_required",hint:'Send { "template": "…", "name": "Acme store" }. The id every route keys on is derived from it.',description:"The new agent's name, with `template`. Its slug becomes the id; the template sees both as {{agent.name}} and {{agent.id}}."}),vars:S(U(o(),S(o(),{code:"template_value_invalid",hint:"Template values are one line of text, sent as strings.",description:"One variable's value."})).optional(),{code:"template_value_invalid",hint:`Send { "vars": { "store": "Acme" } }, every value a string. GET /v1/templates lists each template's variables.`,description:"Values for the template's declared variables. A secret variable's value goes to the agent's .env and is never returned."})}),Ye=(n)=>S(o().trim().min(1),{code:"participant_id_invalid",hint:'A participant id as your system knows the person, e.g. "user:018f…". Agents are "agent:<agentId>".',description:`The participant id${n===""?"":` (${n})`}.`}),Xe=i({id:Ye(""),name:re(o().min(1).optional(),"A display name, shown to agents beside the id."),role:S(T(["admin","member"]).optional(),{code:"participant_role_invalid",hint:'Either "admin" (may assign agents to members) or "member". Omitted is "member".',description:'What the participant may do: "admin" also assigns agents.'})}),Ze=i({kind:S(T(["room","dm"]),{code:"conversation_kind_invalid",hint:'"dm" is one human and one agent and is always answered; "room" is anyone, and an agent answers only when mentioned.',description:"A room or a direct conversation."}),members:S(Q(o().trim().min(1)).min(1),{code:"conversation_members_required",hint:'Participant ids: registered humans, and agents as "agent:<agentId>".',description:"Who is in it."}),title:re(o().min(1).optional(),"A name for a room, for the embedder's own listing.")}),tt=i({add:S(Q(o().trim().min(1)).optional(),{code:"conversation_members_required",hint:"Participant ids to add.",description:"Participant ids to add."}),remove:S(Q(o().trim().min(1)).optional(),{code:"conversation_members_required",hint:"Participant ids to remove.",description:"Participant ids to remove."})}),rt=i({text:S(o().trim().min(1),{code:"message_text_required",hint:'Send { "text": "…" }.',description:"What was said."}),mentions:S(Q(o().trim().min(1)).optional(),{code:"conversation_mention_unknown",hint:'Member participant ids this message addresses, e.g. ["agent:crew"]. In a room only a mentioned agent answers.',description:"Members this addresses. In a room, the agents that answer."}),authorId:S(o().trim().min(1).optional(),{code:"conversation_author_required",hint:"Who said it. A key bound to a participant fills this in and may name no one else; an unbound key must name the author.",description:"The human member who said it. Filled in from a participant-bound key."})}),at=i({participantId:Ye("assignee")}),it=i({presence:S(T(["online","offline"]),{code:"presence_invalid",hint:'Send { "presence": "online" } or "offline". It is pushed by you, never inferred; until it is, a person reads as online and no agent stands in for them.',description:"Whether the person is there. Decides whether their agent stands in for them in a DM."})}),ot=i({scope:S(o().trim().min(1),{code:"memory_scope_invalid",hint:'A shared scope: "space", "owner:<participantId>" or "project:<projectId>".',description:"Where the note goes. `owner:<id>` is written only by that person; `space` by an admin or the designated space writer; a project by an admin."}),text:S(o().trim().min(1),{code:"memory_note_empty",hint:'Send { "scope": "space", "text": "…" } — one or two sentences worth remembering.',description:"The note. Recalled into an agent's prompt when a turn is about it."})}),st=i({name:re(o().min(1).optional(),"A display name for the embedder's own listing."),agents:S(Q(o().trim().min(1)).optional(),{code:"project_agents_invalid",hint:'Agent ids, bare ("crew", not "agent:crew"). Given, it replaces the membership; omitted, it is left alone.',description:"The agents that share this project's memory. Replaces the list when given."})}),lt=i({writer:S(o().trim().min(1),{code:"space_writer_invalid",hint:'A registered participant id, or "agent:<agentId>" for an agent whose memory_write should go to the space.',description:"The one non-admin who may write the space. An agent named here saves every memory_write to the space, so name one that holds nobody's private context."})}),ut=i({bundle:S(U(o(),Ge()),{code:"bundle_files_invalid",hint:'Send { "bundle": <the body GET /v1/agents/:id/export returned> }.',description:"A bundle from GET /v1/agents/:id/export: MEMORY.md, memory/<name>.md and knowledge/<name>.md, nothing else."}),mode:S(T(["skip","overwrite"]).optional(),{code:"bundle_mode_invalid",hint:'Either "skip" (keep a knowledge file that exists, the default) or "overwrite". Memory is always merged note by note.',description:"What to do with a knowledge file the agent already has. Memory is merged either way."})}),ct=i({approve:S(P(),{code:"action_decision_required",hint:'Send { "approve": true } to run the queued call as it was asked, or false to decline it.',description:"Run the queued call (true) or decline it (false)."})}),dt=i({url:S(o().min(1),{code:"webhook_url_invalid",hint:"Send an absolute https:// URL. A receiver on a private network needs the operator to allow it in WEBHOOK_ALLOW.",description:"Where deliveries are POSTed. Checked against every address it resolves to, at subscribe and at every send."}),types:S(Q(o()).min(1),{code:"webhook_types_required",hint:'Send { "types": ["turn.end", "approval.requested"] }. Any event type except model.chunk; the wire spec lists them.',description:"The event types to deliver. `model.chunk` is not deliverable."}),agents:S(Q(o()).min(1).optional(),{code:"webhook_scope_invalid",hint:"Send agent ids this credential can reach, or leave agents out to hear every agent it can reach.",description:"Narrow the subscription to these agents. It can never hear more than the creating credential reaches."})}),ft=i({values:S(U(o(),S(o(),{code:"secret_value_invalid",hint:"Send each value as a non-empty string.",description:"One variable's value. Written to the agent's .env at 0600; never returned."})),{code:"secrets_values_required",hint:'Send { "values": { "MODEL_API_KEY": "…" } }. GET /v1/agents/:id/secrets lists the variables this agent reads.',description:"Variables to write into the agent's .env, keyed by name. Only names the agent's manifest reads are accepted."})});function F(n,e){let l=n.safeParse(e??{});if(l.success)return{ok:!0,value:l.data};let f=l.error.issues[0],c=(f?.path??[]).filter((E)=>typeof E==="string"),m=Ot(n,c);return{ok:!1,error:{...{code:"request_body_invalid",message:c.length===0?f?.message??"The request body is invalid.":`${c.join(".")}: ${f?.message}`,hint:"The field above is the one to fix. GET /v1/openapi.json describes every body this server accepts, including the error code each field produces."},...m?.code===void 0?{}:{code:m.code},...m?.hint===void 0?{}:{hint:m.hint},...c.length===0?{}:{field:c.join(".")}}}}function Ot(n,e){let l=n,f=he(n);for(let c of e){if(l=Rt(l,c),l===void 0)break;f=he(l)??he(ht(l))??f}return f}function he(n){let e=n?.meta();if(e?.code===void 0&&e?.hint===void 0)return;return e}function Rt(n,e){let l=ht(n),f=l?.shape;if(f?.[e]!==void 0)return f[e];return l?.def?.valueType}function ht(n){let e=n;for(let l=0;l<8&&e!==void 0;l+=1){let f=e.def?.innerType;if(f===void 0)return e;e=f}return e}var Lt={"GET /v1/health":{summary:"Liveness, the version, and how many agents are hosted."},"GET /v1/ready":{summary:"Whether a turn can be served yet.",statuses:[{code:503,when:"still starting; channels may still be connecting"}]},"GET /v1/activity":{summary:"Whether the process is idle, and when it must next be woken. For an external waker.",statuses:[{code:403,when:"the key is scoped to agents or sessions"}]},"GET /v1/agents":{summary:"Every agent this server knows about, hosted or switched off."},"GET /v1/agents/:id":{summary:"One agent, with its dialect, window, counts and warnings."},"GET /v1/agents/:id/export":{summary:"A slice of the agent as a JSON bundle: its carried memory file, memory archive and knowledge. Never the manifest, secrets or skills."},"POST /v1/agents/:id/import":{summary:"Merge a bundle into the agent: memory note by note, knowledge kept or overwritten. Reloads when the carried file or knowledge changed, and restores everything if that reload refuses.",body:ut,statuses:[{code:400,when:"a path a bundle cannot carry, or a bundle the agent would not load"}]},"POST /v1/agents/:id/reload":{summary:"Re-read the manifest by replacing the agent with a new instance.",statuses:[{code:409,when:"a turn is running — it is not aborted to apply a change"},{code:400,when:"a team member, which has no manifest of its own"}]},"GET /v1/provision":{summary:"The questions creating an agent asks, and whether this server can answer them."},"POST /v1/agents":{summary:"Create an agent, from answers or from a template, and adopt it into this host, live.",body:Qe,statuses:[{code:201,when:"created; `adopted` is empty with an `error` if it is not running"},{code:403,when:"not a loopback bind"},{code:501,when:"this server has no provisioner"}]},"POST /v1/webhooks":{summary:"Subscribe a URL to event types. The signing secret is returned once.",body:dt,statuses:[{code:201,when:"created; `secret` is in this response and no other"},{code:400,when:"a refused URL, an undeliverable type, or agents outside this key's reach"}]},"POST /v1/participants":{summary:"Register a human participant under the embedder's own id. No account is stored.",body:Xe,statuses:[{code:201,when:"registered, or updated if the id existed"}]},"GET /v1/participants":{summary:"The registered human participants."},"DELETE /v1/participants/:participantId":{summary:"Remove a participant and their conversation memberships."},"POST /v1/conversations":{summary:"Create a room or a DM among participants and agents (agent:<id>).",body:Ze,statuses:[{code:201,when:"created"},{code:403,when:"a participant-bound key creating a conversation it is not in"}]},"GET /v1/conversations":{summary:"The conversations this credential can see."},"GET /v1/conversations/:conversationId":{summary:"One conversation and its members."},"PATCH /v1/conversations/:conversationId/members":{summary:"Add or remove members of a room.",body:tt},"POST /v1/conversations/:conversationId/messages":{summary:"Post a human member's message. In a room only the mentioned agents answer; in a DM the agent always does. Their replies arrive as conversation.message.",body:rt,statuses:[{code:202,when:"logged; the turns it starts run behind the response"},{code:403,when:"a participant-bound key naming another author"}]},"GET /v1/conversations/:conversationId/messages":{summary:"The conversation's log, oldest first, after a sequence number."},"PUT /v1/participants/:participantId/presence":{summary:"Push whether a person is there. In a DM between two people, an offline person's agent stands in for them.",body:it,statuses:[{code:403,when:"a participant-bound key setting someone else's presence"}]},"POST /v1/memory/notes":{summary:"Add a note to a shared memory scope — the space, a person's owner scope, or a project. Agents recall it when a turn is about it.",body:ot,statuses:[{code:403,when:"this participant may not write that scope"},{code:404,when:"the scope's owner or project does not exist"}]},"GET /v1/memory/notes":{summary:"Every note in one shared scope, oldest first. An owner scope is readable by its owner."},"DELETE /v1/memory/notes/:noteId":{summary:"Remove a note. Whoever may write its scope may remove it."},"GET /v1/participants/:participantId/memory/reads":{summary:"The person's audit: every time an agent recalled their owner scope for somebody else, stand-ins included."},"GET /v1/projects":{summary:"Projects, each with the agents that share its memory."},"PUT /v1/projects/:projectId":{summary:"Define a project, or replace which agents share its memory. An admin's act.",body:st},"DELETE /v1/projects/:projectId":{summary:"Remove a project and its notes."},"PUT /v1/memory/space/writer":{summary:"Name the one non-admin who may write the space. An agent named here saves its memory_write to the space.",body:lt},"GET /v1/actions":{summary:"Mutating calls stand-ins queued for their owners. A member-bound key sees its own."},"POST /v1/actions/:actionId":{summary:"Approve or decline a queued action. Approved, the exact call runs as the owner's agent and the outcome is posted in the DM.",body:ct,statuses:[{code:404,when:"no such action, or not this key's to decide"},{code:409,when:"already decided"}]},"PUT /v1/agents/:id/assignee":{summary:"Record which member an agent works for. An admin participant's act.",body:at},"DELETE /v1/agents/:id/assignee":{summary:"Clear an agent's assignment."},"GET /v1/webhooks":{summary:"The subscriptions this credential can see, with their delivery health. Never a secret."},"DELETE /v1/webhooks/:webhookId":{summary:"Delete a subscription and anything it still owed.",statuses:[{code:404,when:"no such subscription, or one outside this key's reach"}]},"GET /v1/usage":{summary:"What every agent in scope cost, per model call, grouped by agent, model, day or sender.",statuses:[{code:400,when:"an unknown grouping or a date that does not parse"}]},"GET /v1/agents/:id/usage":{summary:"What this agent cost, from the meter.",statuses:[{code:400,when:"an unknown grouping or a date that does not parse"}]},"GET /v1/agents/:id/turns":{summary:"Every turn this agent has taken, newest first, across sessions, paged by `before`.",statuses:[{code:400,when:"`limit` or `before` is not a positive whole number"}]},"GET /v1/templates":{summary:"The templates an agent can be created from, and the variables each declares."},"GET /v1/agents/:id/secrets":{summary:"Which variables the agent's manifest reads, and whether each is set. Never a value.",statuses:[{code:501,when:"this server has no credential writer"}]},"PUT /v1/agents/:id/secrets":{summary:"Write the agent's credentials into its .env and apply them: reload or adopt.",body:ft,statuses:[{code:200,when:"written; `applied` says whether the agent is running on them"},{code:400,when:"a variable the manifest does not read, or an empty value"},{code:501,when:"this server has no credential writer"}]},"DELETE /v1/agents/:id":{summary:"Delete an agent for good: off this host, its rows out of the store, its directory off disk. Needs ?confirm=<id>.",statuses:[{code:400,when:"no ?confirm=<id>"},{code:409,when:"two sandbox directories declare this id"},{code:501,when:"this server cannot delete agents"}]},"POST /v1/agents/:id/stop":{summary:"Switch an agent off durably and drop it from this host now.",body:Ve,statuses:[{code:409,when:"a turn is running"}]},"POST /v1/agents/:id/start":{summary:"Switch it back on and have this host adopt it.",statuses:[{code:501,when:"this server cannot look up manifests"}]},"POST /v1/agents/:id/messages":{summary:"Start a turn. Returns once accepted; the turn runs detached.",body:Be,statuses:[{code:202,when:"accepted"},{code:429,when:"over limits.maxConcurrentTurns or limits.tokens; nothing recorded"}]},"POST /v1/agents/:id/deliveries":{summary:"Send exact text on one of the agent's channels, with no turn. It joins that conversation's history as the agent's.",body:Fe,statuses:[{code:202,when:"queued, or already queued under this key"},{code:404,when:"the agent has no running channel with that id"}]},"POST /v1/agents/:id/turns/:turnId/stop":{summary:"Cooperatively stop a turn this API started.",statuses:[{code:409,when:"no cancel handle — a channel or schedule started it"}]},"GET /v1/agents/:id/turns/:turnId/stream":{summary:"One turn's events as SSE, replayed from the start and then live.",query:[{name:"chunks",about:"Include per-token frames. Off by default."},{name:"types",about:"Narrow to these event types, comma-separated."}],statuses:[{code:200,when:"an event stream; see the event table in the wire spec"}]},"GET /v1/events":{summary:"Every event this process emits, as SSE. The firehose.",query:[{name:"agentId",about:"Narrow to one agent."},{name:"sessionKey",about:"Narrow to one conversation."},{name:"chunks",about:"Include per-token frames. Off by default."},{name:"types",about:"Narrow to these event types, comma-separated."}],statuses:[{code:200,when:"an event stream; see the event table in the wire spec"}]},"GET /v1/agents/:id/approvals":{summary:"Questions waiting on a person, oldest first."},"POST /v1/agents/:id/approvals/:approvalId":{summary:"Answer one blocked tool call.",body:He},"POST /v1/keys":{summary:"Mint an operator key. The secret is returned once and never again.",body:Ke,statuses:[{code:201,when:"minted"}]},"GET /v1/keys":{summary:"Every key, live and revoked. Never a secret."},"DELETE /v1/keys/:keyId":{summary:"Revoke a key. A soft delete; the row survives."},"GET /v1/agents/:id/turns/:turnId":{summary:"One turn's stored row."},"GET /v1/agents/:id/sessions":{summary:"Conversations, most recently active first."},"GET /v1/agents/:id/sessions/:key":{summary:"One conversation's summary."},"GET /v1/agents/:id/sessions/:key/messages":{summary:"A page of a conversation's messages.",query:[{name:"limit",about:"How many to return."},{name:"before",about:"Page backwards from this message id."}]},"DELETE /v1/agents/:id/sessions/:key":{summary:"Drop a conversation's history, turns and derived index."},"POST /v1/agents/:id/sessions/:key/phase":{summary:"Move a session into a declared phase.",body:We},"GET /v1/agents/:id/config":{summary:"Every manifest field this surface may set, what it does, and its current value."},"PATCH /v1/agents/:id/config":{summary:"Set one manifest field, then replace the agent so it takes effect.",statuses:[{code:409,when:"the field carries a confirm sentence and `confirm` was not true"},{code:409,when:"the agent came from an object, so there is no manifest to edit"},{code:400,when:"the path is not settable here, or the result would not validate"}]},"PATCH /v1/agents/:id/channels/:channelId":{summary:"Connect or disconnect a channel, and set its credential.",statuses:[{code:400,when:"neither `enabled` nor `credential` was sent, or the channel is unknown"},{code:409,when:"the agent came from an object, so there is no manifest to edit"},{code:501,when:"the host supplied no channel actions"}]},"POST /v1/agents/:id/channels/:channelId/unpair":{summary:"Forget a channel's stored pairing, so the next start offers a new code.",statuses:[{code:404,when:"this agent has no such channel"},{code:409,when:"the channel stores no pairing — a typed credential is a PATCH"}]},"GET /v1/agents/:id/schedules":{summary:"Every schedule, from the store."},"POST /v1/agents/:id/schedules":{summary:"Create a schedule. Validated by the manifest's own schedule rules.",statuses:[{code:201,when:"created"}]},"GET /v1/agents/:id/schedules/:sid":{summary:"One schedule's row."},"PATCH /v1/agents/:id/schedules/:sid":{summary:"Replace a schedule the API created.",statuses:[{code:409,when:"the manifest declares it, so reconciliation would undo the write"}]},"DELETE /v1/agents/:id/schedules/:sid":{summary:"Delete a schedule the API created.",statuses:[{code:409,when:"the manifest declares it, so the next boot would re-create it"}]},"POST /v1/agents/:id/schedules/:sid/run":{summary:"Fire a schedule now, out of band.",statuses:[{code:429,when:"over a governor limit; nothing recorded"}]},"GET /v1/agents/:id/tools":{summary:"The resolved catalogue, with trust and phases."},"GET /v1/agents/:id/skills":{summary:"What the skills index holds."},"GET /v1/agents/:id/context":{summary:"The prompt the next turn would be given, without running one.",query:[{name:"sessionKey",about:"Which conversation to assemble for."},{name:"input",about:"Pretend this is the next message."}]},"POST /v1/channels/:channelId/webhook/:agentId":{summary:"A channel provider's webhook. Open by design; the provider authenticates itself."},"GET /v1/openapi.json":{summary:"This document."},"GET /docs":{summary:"A browser reference over this document."}};function Dt(n){return n.startsWith("/v1/")||n==="/docs"}function $t(n){let e={};for(let l of n.routes){if(!Dt(l.pattern))continue;let f=Lt[`${l.method} ${l.pattern}`];if(f===void 0)continue;let c=l.pattern.replace(/:([A-Za-z0-9_]+)/g,"{$1}"),m=[...l.pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map((j)=>({name:j[1],in:"path",required:!0,schema:{type:"string"}})),b=(f.query??[]).map((j)=>({name:j.name,in:"query",required:!1,description:j.about,schema:{type:"string"}})),E={};for(let j of f.statuses??[])E[String(j.code)]={description:j.when};if(E["200"]===void 0&&E["201"]===void 0){if(E["202"]===void 0)E["200"]={description:"OK"}}if(E["401"]={description:"No credential, or one this server does not accept."},l.pattern.includes(":id"))E["404"]={description:"No such agent, or it is switched off."};e[c]??={};let V={summary:f.summary,...m.length+b.length===0?{}:{parameters:[...m,...b]},responses:E};if(f.body!==void 0)V.requestBody={required:!0,content:{"application/json":{schema:ys(f.body,{target:"draft-2020-12",io:"input"})}}};e[c][l.method.toLowerCase()]=V}return{openapi:"3.1.0",info:{title:"Dispach agent server",version:Je,description:"Generated from the router table and the request schemas — see openapi.ts. The binding contract is docs/04-SPEC-WIRE.md, which is checked against the code; @dispach/client's types are the response reference."},...n.serverUrl===void 0?{}:{servers:[{url:n.serverUrl}]},components:{securitySchemes:{bearer:{type:"http",scheme:"bearer",description:"An operator key or the configured token."}},schemas:{Error:{type:"object",description:"Every failure has this shape. `hint` is never absent — it is the part that says what to do.",properties:{error:{type:"object",required:["code","message","hint"],properties:{code:{type:"string"},message:{type:"string"},hint:{type:"string"},field:{type:"string"}}}}}}},security:[{bearer:[]}],paths:e}}var Mt=new Set(["127.0.0.1","::1","localhost","[::1]"]);function le(n){return Mt.has(n.toLowerCase())}function ie(n){let e=n.trim();if(e===""||e.toLowerCase()==="null")return;try{return new URL(e.includes("://")?e:`http://${e}`).hostname.toLowerCase().replace(/^\[|\]$/g,"")}catch{return}}function Ee(n){return le(n)||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)}function ue(n,e){let l=le(e.host),f=n.headers.get("host"),c=n.headers.get("origin");if(l){let b=f===null?void 0:ie(f),E=e.allowedHosts??[];if(!(b!==void 0&&(Ee(b)||E.some((j)=>ie(j)===b))))return{code:"host_not_allowed",message:`This server does not answer to the host ${f??"(absent)"}.`,hint:"It is bound to loopback, so only a loopback name or address can legitimately reach it — a request addressed to any other name arrived through DNS pointed at this machine, which is how a web page reaches a local server it was never given access to. Add the name to server.allowedHosts if a proxy on this machine needs it.",field:"server.allowedHosts"}}if(c===null)return;let m=ie(c);if(m!==void 0){if(Ee(m))return;if((e.allowedOrigins??[]).some((b)=>ie(b)===m))return;if(!l&&f!==null&&ie(f)===m)return}return{code:"origin_not_allowed",message:`Refusing a request from the origin ${c}.`,hint:l?"This server is bound to loopback, so a page served from anywhere else has no business calling it. Add the origin to server.allowedOrigins if you meant to allow it.":"Only a page served from this server's own host may call it. Add the origin to server.allowedOrigins if you meant to allow it — there is no wildcard, deliberately.",field:"server.allowedOrigins"}}function Ut(n,e){let l=n.headers.get("origin");if(l===null)return{};if(ue(n,e)!==void 0)return{};return{"access-control-allow-origin":l,vary:"Origin"}}function Bt(n,e){let l=n.headers.get("access-control-request-headers");return{"access-control-allow-methods":e.join(", "),"access-control-allow-headers":l??"authorization, content-type","access-control-max-age":"600"}}function pe(n,e){if(n.kind!=="key")return n.kind!=="claim";let l=n.scope?.can;return l===void 0||l.includes(e)}function W(n,e){if(n.kind!=="key")return n.kind!=="claim";let l=n.scope?.agents;return l===void 0||l.includes(e)}function ce(n,e){if(n.kind!=="key")return n.kind!=="claim";let l=n.scope?.sessions;if(l===void 0)return!0;return e.startsWith(l.endsWith("*")?l.slice(0,-1):l)}function oe(n){if(n.kind==="claim")return{agentIds:[]};if(n.kind!=="key")return{};let e=n.scope?.agents,l=n.scope?.sessions;return{...e===void 0?{}:{agentIds:e},...l===void 0?{}:{sessionPrefix:l.endsWith("*")?l.slice(0,-1):l}}}function pt(n){if(n.kind!=="key")return!1;let e=n.scope;return e!==void 0&&(e.agents!==void 0||e.sessions!==void 0||e.can!==void 0)}function mt(n,e){let l=n.kind==="key"?n.scope?.participant:void 0;if(l===void 0)return{ok:!0,from:e};if(e===void 0)return{ok:!0,from:{id:l,kind:"user"}};if(e.id===l&&e.kind==="user")return{ok:!0,from:e};return{ok:!1,error:{code:"sender_not_bound_participant",message:`This key speaks for ${l}, and the message names ${e.kind} ${e.id}.`,hint:`A key bound to a participant starts turns only as that participant, so the tools the turn calls act for them. Omit from (it is filled in), or send from.id "${l}" with kind "user". A backend that names senders itself needs a key minted without scope.participant.`,field:"from"}}}class gt{#e=[];add(n,e,l,f){return this.#e.push({method:n.toUpperCase(),pattern:e,handler:l,capability:f.capability,streaming:f.streaming===!0,segments:Te(e)}),this}routes(){return this.#e.map(({method:n,pattern:e,handler:l,streaming:f,capability:c})=>({method:n,pattern:e,handler:l,streaming:f,capability:c}))}match(n,e){let l=Te(e),f=[];for(let c of this.#e){let m=Ft(c.segments,l);if(m===void 0)continue;if(f.push(c),c.method===n.toUpperCase())return{kind:"found",handler:c.handler,params:m,streaming:c.streaming,capability:c.capability}}if(f.length>0)return{kind:"method",allowed:[...new Set(f.map((c)=>c.method))]};return{kind:"none"}}}function Te(n){return n.split("/").filter((e)=>e!=="")}function Ft(n,e){if(n.length!==e.length)return;let l={};for(let[f,c]of n.entries()){let m=e[f];if(m===void 0)return;if(c.startsWith(":")){try{l[c.slice(1)]=decodeURIComponent(m)}catch{return}continue}if(c!==m)return}return l}var yt=15000;function Ht(n){let e=[];if(n.event!==void 0)e.push(`event: ${n.event}`);if(n.id!==void 0)e.push(`id: ${n.id}`);let l=typeof n.data==="string"?n.data:JSON.stringify(n.data);for(let f of l.split(`
|
|
3
|
+
`))e.push(`data: ${f}`);return`${e.join(`
|
|
4
4
|
`)}
|
|
5
5
|
|
|
6
|
-
`}function
|
|
6
|
+
`}function be(n){let e=new TextEncoder,l,f,c=!1,m=new ReadableStream({start(b){let E=()=>{if(c)return;if(c=!0,f!==void 0)clearInterval(f);l?.(),l=void 0;try{b.close()}catch{}},V=(k)=>{if(c)return;try{b.enqueue(e.encode(Ht(k)))}catch{E()}};n.signal?.addEventListener("abort",E,{once:!0});let j=n.start({send:V,close:E});if(c){j?.();return}l=j,f=setInterval(()=>{if(c)return;try{b.enqueue(e.encode(`: ping
|
|
7
7
|
|
|
8
|
-
`))}catch{S()}},t.heartbeatMs??gt),d.unref?.()},cancel(){if(c)return;if(c=!0,d!==void 0)clearInterval(d);s?.(),s=void 0}});return new Response(p,{status:t.status??200,headers:{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no"}})}var Gt=':root{--ground: #0b0b0c;--raised: #151517;--line: #26262a;--text: #e8e6e3;--dim: #8b8b93;--accent: #7aa2f7;--warn: #e0af68;--bad: #f7768e;--ok: #9ece6a;--mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;--sans: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--ground);color:var(--text);font:14px / 1.55 var(--sans);-webkit-font-smoothing:antialiased}button{font:inherit;color:inherit;background:var(--raised);border:1px solid var(--line);border-radius:6px;padding:5px 11px;cursor:pointer}button:hover:not(:disabled){border-color:var(--dim)}button:disabled{opacity:.45;cursor:default}button.primary{background:var(--accent);border-color:var(--accent);color:#0b0b0c;font-weight:600}button.bad{color:var(--bad)}input,textarea{font:inherit;color:inherit;background:var(--ground);border:1px solid var(--line);border-radius:6px;padding:8px 10px;width:100%}input:focus,textarea:focus{outline:none;border-color:var(--accent)}.shell{display:grid;grid-template-columns:240px 1fr;height:100vh}.side{background:var(--raised);border-right:1px solid var(--line);display:flex;flex-direction:column;min-height:0}.side header{padding:14px 16px;border-bottom:1px solid var(--line)}.brand{font-weight:650;letter-spacing:.01em}.side nav{padding:8px;overflow-y:auto;flex:1;min-height:0}.side footer{padding:10px 12px;border-top:1px solid var(--line);display:flex;gap:8px;align-items:center}.row-button{display:block;width:100%;text-align:left;background:none;border:none;border-radius:6px;padding:7px 9px;font-family:var(--mono);font-size:12px}.row-button:hover{background:var(--ground)}.row-button[aria-current=true]{background:var(--ground);color:var(--accent)}.group{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--dim);padding:12px 9px 5px}.main{display:flex;flex-direction:column;min-height:0}.bar{display:flex;gap:14px;align-items:baseline;padding:12px 20px;border-bottom:1px solid var(--line);font-size:12px;color:var(--dim);min-height:44px}.bar strong{color:var(--text);font-size:14px;font-weight:600}.bar .spacer{flex:1}.scroll{flex:1;overflow-y:auto;min-height:0;padding:20px}.pad{max-width:780px;margin:0 auto}.row{margin:0 0 16px;white-space:pre-wrap;overflow-wrap:anywhere}.row.user{background:var(--raised);border:1px solid var(--line);border-radius:8px;padding:10px 13px}.label{font-family:var(--mono);font-size:11px;color:var(--dim);margin-bottom:4px}.tool{border-left:2px solid var(--line);padding-left:11px;font-family:var(--mono);font-size:12px}.tool .slug{color:var(--accent)}.tool .out{color:var(--dim);max-height:13em;overflow-y:auto;margin-top:5px}.tool.failed .slug{color:var(--bad)}.tool .mut{color:var(--warn);font-size:11px}.tool .out{display:inline}.fence{border:1px dashed var(--warn);border-radius:6px;padding:7px 9px;margin-top:5px}.fence .why{color:var(--warn);font-size:11px;margin-bottom:4px}.payload-code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:28px;font-weight:600;letter-spacing:.18em;margin:10px 0;-webkit-user-select:all;user-select:all}.channel-input.stale .payload-code{opacity:.35}.payload-qr{display:block;width:240px;max-width:100%;height:auto;border-radius:6px;margin:8px 0}.channel-input.stale .payload-qr{opacity:.35}.note{font-size:12px;color:var(--dim);border-left:2px solid var(--line);padding-left:11px;white-space:pre-wrap}.note.bad{color:var(--bad);border-left-color:var(--bad)}.ask{border:1px solid var(--warn);border-radius:8px;padding:12px 14px;background:#17140e}.ask .what{font-family:var(--mono);font-size:12px;margin:6px 0 10px;white-space:pre-wrap;overflow-wrap:anywhere}.ask .buttons{display:flex;gap:8px}.ask .settled{font-size:12px;color:var(--dim)}details.fold summary{cursor:pointer;color:var(--dim);font-family:var(--mono);font-size:11px}details.fold[open] summary{margin-bottom:5px}details.fold .body{color:var(--dim);font-size:13px}.composer{border-top:1px solid var(--line);padding:12px 20px}.composer .inner{max-width:780px;margin:0 auto;display:flex;gap:9px;align-items:flex-end}.composer textarea{resize:none;min-height:40px;max-height:190px;font-family:var(--sans)}.hint{font-size:11px;color:var(--dim);max-width:780px;margin:6px auto 0}.card{border:1px solid var(--line);border-radius:8px;padding:16px 18px;margin-bottom:14px;background:var(--raised)}.card h2{margin:0 0 4px;font-size:15px}.card p{margin:0 0 12px;color:var(--dim);font-size:13px}table{width:100%;border-collapse:collapse;font-size:13px}th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:var(--dim);font-weight:500;padding:0 10px 7px 0}td{padding:8px 10px 8px 0;border-top:1px solid var(--line);font-family:var(--mono);font-size:12px}td.revoked{color:var(--dim);text-decoration:line-through}.secret{font-family:var(--mono);font-size:12px;background:var(--ground);border:1px solid var(--ok);border-radius:6px;padding:9px 11px;overflow-wrap:anywhere;margin-bottom:8px}.gate{display:grid;place-items:center;height:100vh;padding:20px}.gate .card{max-width:460px;width:100%}.dot{width:7px;height:7px;border-radius:50%;display:inline-block;background:var(--dim)}.dot.live{background:var(--ok)}.dot.busy{background:var(--warn)}@media(max-width:720px){.shell{grid-template-columns:1fr}.side{display:none}}.agent-row{display:block}.agent-row .row-button:disabled{color:var(--dim);cursor:default}.agent-off{color:var(--warn);font-size:11px}.agent-note{display:flex;gap:6px;align-items:baseline;padding:0 9px 6px;font-size:11px;color:var(--dim)}.link{background:none;border:none;padding:0;color:var(--accent);font-size:11px;text-decoration:underline;cursor:pointer}.link:disabled{color:var(--dim);cursor:default;text-decoration:none}.empty{color:var(--dim);font-size:13px;max-width:60ch}.panel-table{width:100%;border-collapse:collapse;font-size:12px}.panel-table th{text-align:left;font-weight:500;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--dim);padding:6px 10px 6px 0;border-bottom:1px solid var(--line)}.panel-table td{padding:9px 10px 9px 0;border-bottom:1px solid var(--line);vertical-align:top}.panel-table tr.off td{color:var(--dim)}.sub{color:var(--dim);font-size:11px;margin-top:2px;max-width:52ch}.channel{border:1px solid var(--line);border-radius:8px;padding:12px 14px;margin-bottom:12px}.channel h3{margin:0 0 6px;font-size:13px;font-weight:500}.status{margin:0;font-size:12px}.status-connected{color:var(--ok)}.status-error,.status-disconnected{color:var(--bad)}.status-needs_input{color:var(--warn)}.channel-input{margin-top:10px;padding:10px;border-radius:6px;background:var(--ground)}.payload{margin:0;font-family:var(--mono);font-size:11px;white-space:pre-wrap;word-break:break-all;max-height:9em;overflow-y:auto}.channel-input.stale .payload{opacity:.45}.warn{color:var(--warn);font-size:12px;margin:0 0 6px}select{font:inherit;color:inherit;background:var(--ground);border:1px solid var(--line);border-radius:6px;padding:8px 10px;width:100%}select:focus{outline:none;border-color:var(--accent)}.provision{display:flex;flex-direction:column;gap:16px;max-width:60ch}.provision>button[type=submit]{align-self:flex-start}.field label{display:block;font-size:12px;color:var(--dim);margin-bottom:5px}.field.invalid input,.field.invalid select{border-color:var(--bad)}.sub{color:var(--dim);font-size:11px}.error{color:var(--bad);font-size:13px;max-width:60ch}.ok{color:var(--ok);font-size:13px}.created{max-width:66ch;font-size:13px}.created h3{font-size:15px;font-weight:600;margin:0 0 10px}.created p{margin:0 0 10px}.blank-secrets{border:1px solid var(--warn);border-radius:6px;padding:11px 13px;margin:14px 0}.blank-secrets p{margin:0 0 6px}.blank-secrets p:last-child{margin:0}.config-row{border-bottom:1px solid var(--line);padding:14px 0;max-width:72ch}.config-row:first-of-type{padding-top:0}.config-head{display:flex;align-items:baseline;gap:8px}.config-row .sub{margin:4px 0 8px;max-width:68ch}.config-row input[type=text],.config-row input:not([type]),.config-row textarea{width:100%;font-family:var(--mono);font-size:12px}.config-row button{margin-top:8px}.config-row label input[type=checkbox]{width:auto;margin-right:4px;vertical-align:baseline}.form-grid{display:grid;grid-template-columns:6em 1fr;gap:8px 12px;align-items:start;max-width:60ch}.form-grid label{font-size:12px;color:var(--dim);padding-top:9px}.form-grid input,.form-grid select{width:100%}.form-grid>div>input+input{margin-top:6px}.warnings{border:1px solid var(--warn);border-radius:6px;padding:.75rem 1rem;margin-bottom:1rem}.warnings h3{margin:0;color:var(--warn)}.warnings .sub{margin:.25rem 0 .75rem;opacity:.8}.warning{margin-top:.5rem}.warning-message{margin:0}.warning .hint{margin:.15rem 0 0;opacity:.75}.channel-actions{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-top:.5rem}.channel-actions form{display:flex;gap:.35rem}.channel-actions input{min-width:14rem}.status-off{opacity:.7}\n',qt=`(function(){const c=document.createElement("link").relList;if(c&&c.supports&&c.supports("modulepreload"))return;for(const h of document.querySelectorAll('link[rel="modulepreload"]'))s(h);new MutationObserver(h=>{for(const o of h)if(o.type==="childList")for(const v of o.addedNodes)v.tagName==="LINK"&&v.rel==="modulepreload"&&s(v)}).observe(document,{childList:!0,subtree:!0});function r(h){const o={};return h.integrity&&(o.integrity=h.integrity),h.referrerPolicy&&(o.referrerPolicy=h.referrerPolicy),h.crossOrigin==="use-credentials"?o.credentials="include":h.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(h){if(h.ep)return;h.ep=!0;const o=r(h);fetch(h.href,o)}})();function Qg(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Rs={exports:{}},Va={};var ph;function Xg(){if(ph)return Va;ph=1;var i=Symbol.for("react.transitional.element"),c=Symbol.for("react.fragment");function r(s,h,o){var v=null;if(o!==void 0&&(v=""+o),h.key!==void 0&&(v=""+h.key),"key"in h){o={};for(var z in h)z!=="key"&&(o[z]=h[z])}else o=h;return h=o.ref,{$$typeof:i,type:s,key:v,ref:h!==void 0?h:null,props:o}}return Va.Fragment=c,Va.jsx=r,Va.jsxs=r,Va}var Eh;function Kg(){return Eh||(Eh=1,Rs.exports=Xg()),Rs.exports}var m=Kg(),Os={exports:{}},de={};var Th;function Zg(){if(Th)return de;Th=1;var i=Symbol.for("react.transitional.element"),c=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),h=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),v=Symbol.for("react.context"),z=Symbol.for("react.forward_ref"),E=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),S=Symbol.for("react.activity"),N=Symbol.iterator;function H(b){return b===null||typeof b!="object"?null:(b=N&&b[N]||b["@@iterator"],typeof b=="function"?b:null)}var G={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},B=Object.assign,re={};function Y(b,R,Q){this.props=b,this.context=R,this.refs=re,this.updater=Q||G}Y.prototype.isReactComponent={},Y.prototype.setState=function(b,R){if(typeof b!="object"&&typeof b!="function"&&b!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,b,R,"setState")},Y.prototype.forceUpdate=function(b){this.updater.enqueueForceUpdate(this,b,"forceUpdate")};function se(){}se.prototype=Y.prototype;function W(b,R,Q){this.props=b,this.context=R,this.refs=re,this.updater=Q||G}var $=W.prototype=new se;$.constructor=W,B($,Y.prototype),$.isPureReactComponent=!0;var Te=Array.isArray;function Z(){}var L={H:null,A:null,T:null,S:null},X=Object.prototype.hasOwnProperty;function J(b,R,Q){var V=Q.ref;return{$$typeof:i,type:b,key:R,ref:V!==void 0?V:null,props:Q}}function le(b,R){return J(b.type,R,b.props)}function q(b){return typeof b=="object"&&b!==null&&b.$$typeof===i}function F(b){var R={"=":"=0",":":"=2"};return"$"+b.replace(/[=:]/g,function(Q){return R[Q]})}var ee=/\\/+/g;function ie(b,R){return typeof b=="object"&&b!==null&&b.key!=null?F(""+b.key):R.toString(36)}function Le(b){switch(b.status){case"fulfilled":return b.value;case"rejected":throw b.reason;default:switch(typeof b.status=="string"?b.then(Z,Z):(b.status="pending",b.then(function(R){b.status==="pending"&&(b.status="fulfilled",b.value=R)},function(R){b.status==="pending"&&(b.status="rejected",b.reason=R)})),b.status){case"fulfilled":return b.value;case"rejected":throw b.reason}}throw b}function _(b,R,Q,V,fe){var he=typeof b;(he==="undefined"||he==="boolean")&&(b=null);var oe=!1;if(b===null)oe=!0;else switch(he){case"bigint":case"string":case"number":oe=!0;break;case"object":switch(b.$$typeof){case i:case c:oe=!0;break;case A:return oe=b._init,_(oe(b._payload),R,Q,V,fe)}}if(oe)return fe=fe(b),oe=V===""?"."+ie(b,0):V,Te(fe)?(Q="",oe!=null&&(Q=oe.replace(ee,"$&/")+"/"),_(fe,R,Q,"",function(Tt){return Tt})):fe!=null&&(q(fe)&&(fe=le(fe,Q+(fe.key==null||b&&b.key===fe.key?"":(""+fe.key).replace(ee,"$&/")+"/")+oe)),R.push(fe)),1;oe=0;var we=V===""?".":V+":";if(Te(b))for(var Ne=0;Ne<b.length;Ne++)V=b[Ne],he=we+ie(V,Ne),oe+=_(V,R,Q,he,fe);else if(Ne=H(b),typeof Ne=="function")for(b=Ne.call(b),Ne=0;!(V=b.next()).done;)V=V.value,he=we+ie(V,Ne++),oe+=_(V,R,Q,he,fe);else if(he==="object"){if(typeof b.then=="function")return _(Le(b),R,Q,V,fe);throw R=String(b),Error("Objects are not valid as a React child (found: "+(R==="[object Object]"?"object with keys {"+Object.keys(b).join(", ")+"}":R)+"). If you meant to render a collection of children, use an array instead.")}return oe}function K(b,R,Q){if(b==null)return b;var V=[],fe=0;return _(b,V,"","",function(he){return R.call(Q,he,fe++)}),V}function te(b){if(b._status===-1){var R=b._result;R=R(),R.then(function(Q){(b._status===0||b._status===-1)&&(b._status=1,b._result=Q)},function(Q){(b._status===0||b._status===-1)&&(b._status=2,b._result=Q)}),b._status===-1&&(b._status=0,b._result=R)}if(b._status===1)return b._result.default;throw b._result}var Ae=typeof reportError=="function"?reportError:function(b){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var R=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof b=="object"&&b!==null&&typeof b.message=="string"?String(b.message):String(b),error:b});if(!window.dispatchEvent(R))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",b);return}console.error(b)},Ee={map:K,forEach:function(b,R,Q){K(b,function(){R.apply(this,arguments)},Q)},count:function(b){var R=0;return K(b,function(){R++}),R},toArray:function(b){return K(b,function(R){return R})||[]},only:function(b){if(!q(b))throw Error("React.Children.only expected to receive a single React element child.");return b}};return de.Activity=S,de.Children=Ee,de.Component=Y,de.Fragment=r,de.Profiler=h,de.PureComponent=W,de.StrictMode=s,de.Suspense=E,de.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=L,de.__COMPILER_RUNTIME={__proto__:null,c:function(b){return L.H.useMemoCache(b)}},de.cache=function(b){return function(){return b.apply(null,arguments)}},de.cacheSignal=function(){return null},de.cloneElement=function(b,R,Q){if(b==null)throw Error("The argument must be a React element, but you passed "+b+".");var V=B({},b.props),fe=b.key;if(R!=null)for(he in R.key!==void 0&&(fe=""+R.key),R)!X.call(R,he)||he==="key"||he==="__self"||he==="__source"||he==="ref"&&R.ref===void 0||(V[he]=R[he]);var he=arguments.length-2;if(he===1)V.children=Q;else if(1<he){for(var oe=Array(he),we=0;we<he;we++)oe[we]=arguments[we+2];V.children=oe}return J(b.type,fe,V)},de.createContext=function(b){return b={$$typeof:v,_currentValue:b,_currentValue2:b,_threadCount:0,Provider:null,Consumer:null},b.Provider=b,b.Consumer={$$typeof:o,_context:b},b},de.createElement=function(b,R,Q){var V,fe={},he=null;if(R!=null)for(V in R.key!==void 0&&(he=""+R.key),R)X.call(R,V)&&V!=="key"&&V!=="__self"&&V!=="__source"&&(fe[V]=R[V]);var oe=arguments.length-2;if(oe===1)fe.children=Q;else if(1<oe){for(var we=Array(oe),Ne=0;Ne<oe;Ne++)we[Ne]=arguments[Ne+2];fe.children=we}if(b&&b.defaultProps)for(V in oe=b.defaultProps,oe)fe[V]===void 0&&(fe[V]=oe[V]);return J(b,he,fe)},de.createRef=function(){return{current:null}},de.forwardRef=function(b){return{$$typeof:z,render:b}},de.isValidElement=q,de.lazy=function(b){return{$$typeof:A,_payload:{_status:-1,_result:b},_init:te}},de.memo=function(b,R){return{$$typeof:g,type:b,compare:R===void 0?null:R}},de.startTransition=function(b){var R=L.T,Q={};L.T=Q;try{var V=b(),fe=L.S;fe!==null&&fe(Q,V),typeof V=="object"&&V!==null&&typeof V.then=="function"&&V.then(Z,Ae)}catch(he){Ae(he)}finally{R!==null&&Q.types!==null&&(R.types=Q.types),L.T=R}},de.unstable_useCacheRefresh=function(){return L.H.useCacheRefresh()},de.use=function(b){return L.H.use(b)},de.useActionState=function(b,R,Q){return L.H.useActionState(b,R,Q)},de.useCallback=function(b,R){return L.H.useCallback(b,R)},de.useContext=function(b){return L.H.useContext(b)},de.useDebugValue=function(){},de.useDeferredValue=function(b,R){return L.H.useDeferredValue(b,R)},de.useEffect=function(b,R){return L.H.useEffect(b,R)},de.useEffectEvent=function(b){return L.H.useEffectEvent(b)},de.useId=function(){return L.H.useId()},de.useImperativeHandle=function(b,R,Q){return L.H.useImperativeHandle(b,R,Q)},de.useInsertionEffect=function(b,R){return L.H.useInsertionEffect(b,R)},de.useLayoutEffect=function(b,R){return L.H.useLayoutEffect(b,R)},de.useMemo=function(b,R){return L.H.useMemo(b,R)},de.useOptimistic=function(b,R){return L.H.useOptimistic(b,R)},de.useReducer=function(b,R,Q){return L.H.useReducer(b,R,Q)},de.useRef=function(b){return L.H.useRef(b)},de.useState=function(b){return L.H.useState(b)},de.useSyncExternalStore=function(b,R,Q){return L.H.useSyncExternalStore(b,R,Q)},de.useTransition=function(){return L.H.useTransition()},de.version="19.2.8",de}var Ah;function bf(){return Ah||(Ah=1,Os.exports=Zg()),Os.exports}var k=bf(),Ds={exports:{}},ka={},Bs={exports:{}},Hs={};var zh;function Vg(){return zh||(zh=1,(function(i){function c(_,K){var te=_.length;_.push(K);e:for(;0<te;){var Ae=te-1>>>1,Ee=_[Ae];if(0<h(Ee,K))_[Ae]=K,_[te]=Ee,te=Ae;else break e}}function r(_){return _.length===0?null:_[0]}function s(_){if(_.length===0)return null;var K=_[0],te=_.pop();if(te!==K){_[0]=te;e:for(var Ae=0,Ee=_.length,b=Ee>>>1;Ae<b;){var R=2*(Ae+1)-1,Q=_[R],V=R+1,fe=_[V];if(0>h(Q,te))V<Ee&&0>h(fe,Q)?(_[Ae]=fe,_[V]=te,Ae=V):(_[Ae]=Q,_[R]=te,Ae=R);else if(V<Ee&&0>h(fe,te))_[Ae]=fe,_[V]=te,Ae=V;else break e}}return K}function h(_,K){var te=_.sortIndex-K.sortIndex;return te!==0?te:_.id-K.id}if(i.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;i.unstable_now=function(){return o.now()}}else{var v=Date,z=v.now();i.unstable_now=function(){return v.now()-z}}var E=[],g=[],A=1,S=null,N=3,H=!1,G=!1,B=!1,re=!1,Y=typeof setTimeout=="function"?setTimeout:null,se=typeof clearTimeout=="function"?clearTimeout:null,W=typeof setImmediate<"u"?setImmediate:null;function $(_){for(var K=r(g);K!==null;){if(K.callback===null)s(g);else if(K.startTime<=_)s(g),K.sortIndex=K.expirationTime,c(E,K);else break;K=r(g)}}function Te(_){if(B=!1,$(_),!G)if(r(E)!==null)G=!0,Z||(Z=!0,F());else{var K=r(g);K!==null&&Le(Te,K.startTime-_)}}var Z=!1,L=-1,X=5,J=-1;function le(){return re?!0:!(i.unstable_now()-J<X)}function q(){if(re=!1,Z){var _=i.unstable_now();J=_;var K=!0;try{e:{G=!1,B&&(B=!1,se(L),L=-1),H=!0;var te=N;try{t:{for($(_),S=r(E);S!==null&&!(S.expirationTime>_&&le());){var Ae=S.callback;if(typeof Ae=="function"){S.callback=null,N=S.priorityLevel;var Ee=Ae(S.expirationTime<=_);if(_=i.unstable_now(),typeof Ee=="function"){S.callback=Ee,$(_),K=!0;break t}S===r(E)&&s(E),$(_)}else s(E);S=r(E)}if(S!==null)K=!0;else{var b=r(g);b!==null&&Le(Te,b.startTime-_),K=!1}}break e}finally{S=null,N=te,H=!1}K=void 0}}finally{K?F():Z=!1}}}var F;if(typeof W=="function")F=function(){W(q)};else if(typeof MessageChannel<"u"){var ee=new MessageChannel,ie=ee.port2;ee.port1.onmessage=q,F=function(){ie.postMessage(null)}}else F=function(){Y(q,0)};function Le(_,K){L=Y(function(){_(i.unstable_now())},K)}i.unstable_IdlePriority=5,i.unstable_ImmediatePriority=1,i.unstable_LowPriority=4,i.unstable_NormalPriority=3,i.unstable_Profiling=null,i.unstable_UserBlockingPriority=2,i.unstable_cancelCallback=function(_){_.callback=null},i.unstable_forceFrameRate=function(_){0>_||125<_?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):X=0<_?Math.floor(1e3/_):5},i.unstable_getCurrentPriorityLevel=function(){return N},i.unstable_next=function(_){switch(N){case 1:case 2:case 3:var K=3;break;default:K=N}var te=N;N=K;try{return _()}finally{N=te}},i.unstable_requestPaint=function(){re=!0},i.unstable_runWithPriority=function(_,K){switch(_){case 1:case 2:case 3:case 4:case 5:break;default:_=3}var te=N;N=_;try{return K()}finally{N=te}},i.unstable_scheduleCallback=function(_,K,te){var Ae=i.unstable_now();switch(typeof te=="object"&&te!==null?(te=te.delay,te=typeof te=="number"&&0<te?Ae+te:Ae):te=Ae,_){case 1:var Ee=-1;break;case 2:Ee=250;break;case 5:Ee=1073741823;break;case 4:Ee=1e4;break;default:Ee=5e3}return Ee=te+Ee,_={id:A++,callback:K,priorityLevel:_,startTime:te,expirationTime:Ee,sortIndex:-1},te>Ae?(_.sortIndex=te,c(g,_),r(E)===null&&_===r(g)&&(B?(se(L),L=-1):B=!0,Le(Te,te-Ae))):(_.sortIndex=Ee,c(E,_),G||H||(G=!0,Z||(Z=!0,F()))),_},i.unstable_shouldYield=le,i.unstable_wrapCallback=function(_){var K=N;return function(){var te=N;N=K;try{return _.apply(this,arguments)}finally{N=te}}}})(Hs)),Hs}var Ch;function kg(){return Ch||(Ch=1,Bs.exports=Vg()),Bs.exports}var qs={exports:{}},at={};var Nh;function Jg(){if(Nh)return at;Nh=1;var i=bf();function c(E){var g="https://react.dev/errors/"+E;if(1<arguments.length){g+="?args[]="+encodeURIComponent(arguments[1]);for(var A=2;A<arguments.length;A++)g+="&args[]="+encodeURIComponent(arguments[A])}return"Minified React error #"+E+"; visit "+g+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(){}var s={d:{f:r,r:function(){throw Error(c(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},h=Symbol.for("react.portal");function o(E,g,A){var S=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:h,key:S==null?null:""+S,children:E,containerInfo:g,implementation:A}}var v=i.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function z(E,g){if(E==="font")return"";if(typeof g=="string")return g==="use-credentials"?g:""}return at.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=s,at.createPortal=function(E,g){var A=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!g||g.nodeType!==1&&g.nodeType!==9&&g.nodeType!==11)throw Error(c(299));return o(E,g,null,A)},at.flushSync=function(E){var g=v.T,A=s.p;try{if(v.T=null,s.p=2,E)return E()}finally{v.T=g,s.p=A,s.d.f()}},at.preconnect=function(E,g){typeof E=="string"&&(g?(g=g.crossOrigin,g=typeof g=="string"?g==="use-credentials"?g:"":void 0):g=null,s.d.C(E,g))},at.prefetchDNS=function(E){typeof E=="string"&&s.d.D(E)},at.preinit=function(E,g){if(typeof E=="string"&&g&&typeof g.as=="string"){var A=g.as,S=z(A,g.crossOrigin),N=typeof g.integrity=="string"?g.integrity:void 0,H=typeof g.fetchPriority=="string"?g.fetchPriority:void 0;A==="style"?s.d.S(E,typeof g.precedence=="string"?g.precedence:void 0,{crossOrigin:S,integrity:N,fetchPriority:H}):A==="script"&&s.d.X(E,{crossOrigin:S,integrity:N,fetchPriority:H,nonce:typeof g.nonce=="string"?g.nonce:void 0})}},at.preinitModule=function(E,g){if(typeof E=="string")if(typeof g=="object"&&g!==null){if(g.as==null||g.as==="script"){var A=z(g.as,g.crossOrigin);s.d.M(E,{crossOrigin:A,integrity:typeof g.integrity=="string"?g.integrity:void 0,nonce:typeof g.nonce=="string"?g.nonce:void 0})}}else g==null&&s.d.M(E)},at.preload=function(E,g){if(typeof E=="string"&&typeof g=="object"&&g!==null&&typeof g.as=="string"){var A=g.as,S=z(A,g.crossOrigin);s.d.L(E,A,{crossOrigin:S,integrity:typeof g.integrity=="string"?g.integrity:void 0,nonce:typeof g.nonce=="string"?g.nonce:void 0,type:typeof g.type=="string"?g.type:void 0,fetchPriority:typeof g.fetchPriority=="string"?g.fetchPriority:void 0,referrerPolicy:typeof g.referrerPolicy=="string"?g.referrerPolicy:void 0,imageSrcSet:typeof g.imageSrcSet=="string"?g.imageSrcSet:void 0,imageSizes:typeof g.imageSizes=="string"?g.imageSizes:void 0,media:typeof g.media=="string"?g.media:void 0})}},at.preloadModule=function(E,g){if(typeof E=="string")if(g){var A=z(g.as,g.crossOrigin);s.d.m(E,{as:typeof g.as=="string"&&g.as!=="script"?g.as:void 0,crossOrigin:A,integrity:typeof g.integrity=="string"?g.integrity:void 0})}else s.d.m(E)},at.requestFormReset=function(E){s.d.r(E)},at.unstable_batchedUpdates=function(E,g){return E(g)},at.useFormState=function(E,g,A){return v.H.useFormState(E,g,A)},at.useFormStatus=function(){return v.H.useHostTransitionStatus()},at.version="19.2.8",at}var jh;function $g(){if(jh)return qs.exports;jh=1;function i(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(c){console.error(c)}}return i(),qs.exports=Jg(),qs.exports}var xh;function Fg(){if(xh)return ka;xh=1;var i=kg(),c=bf(),r=$g();function s(e){var t="https://react.dev/errors/"+e;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n])}return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function h(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function o(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,(t.flags&4098)!==0&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function v(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function z(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function E(e){if(o(e)!==e)throw Error(s(188))}function g(e){var t=e.alternate;if(!t){if(t=o(e),t===null)throw Error(s(188));return t!==e?null:e}for(var n=e,l=t;;){var a=n.return;if(a===null)break;var u=a.alternate;if(u===null){if(l=a.return,l!==null){n=l;continue}break}if(a.child===u.child){for(u=a.child;u;){if(u===n)return E(a),e;if(u===l)return E(a),t;u=u.sibling}throw Error(s(188))}if(n.return!==l.return)n=a,l=u;else{for(var f=!1,d=a.child;d;){if(d===n){f=!0,n=a,l=u;break}if(d===l){f=!0,l=a,n=u;break}d=d.sibling}if(!f){for(d=u.child;d;){if(d===n){f=!0,n=u,l=a;break}if(d===l){f=!0,l=u,n=a;break}d=d.sibling}if(!f)throw Error(s(189))}}if(n.alternate!==l)throw Error(s(190))}if(n.tag!==3)throw Error(s(188));return n.stateNode.current===n?e:t}function A(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=A(e),t!==null)return t;e=e.sibling}return null}var S=Object.assign,N=Symbol.for("react.element"),H=Symbol.for("react.transitional.element"),G=Symbol.for("react.portal"),B=Symbol.for("react.fragment"),re=Symbol.for("react.strict_mode"),Y=Symbol.for("react.profiler"),se=Symbol.for("react.consumer"),W=Symbol.for("react.context"),$=Symbol.for("react.forward_ref"),Te=Symbol.for("react.suspense"),Z=Symbol.for("react.suspense_list"),L=Symbol.for("react.memo"),X=Symbol.for("react.lazy"),J=Symbol.for("react.activity"),le=Symbol.for("react.memo_cache_sentinel"),q=Symbol.iterator;function F(e){return e===null||typeof e!="object"?null:(e=q&&e[q]||e["@@iterator"],typeof e=="function"?e:null)}var ee=Symbol.for("react.client.reference");function ie(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===ee?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case B:return"Fragment";case Y:return"Profiler";case re:return"StrictMode";case Te:return"Suspense";case Z:return"SuspenseList";case J:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case G:return"Portal";case W:return e.displayName||"Context";case se:return(e._context.displayName||"Context")+".Consumer";case $:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case L:return t=e.displayName||null,t!==null?t:ie(e.type)||"Memo";case X:t=e._payload,e=e._init;try{return ie(e(t))}catch{}}return null}var Le=Array.isArray,_=c.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,te={pending:!1,data:null,method:null,action:null},Ae=[],Ee=-1;function b(e){return{current:e}}function R(e){0>Ee||(e.current=Ae[Ee],Ae[Ee]=null,Ee--)}function Q(e,t){Ee++,Ae[Ee]=e.current,e.current=t}var V=b(null),fe=b(null),he=b(null),oe=b(null);function we(e,t){switch(Q(he,t),Q(fe,e),Q(V,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Xd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Xd(t),e=Kd(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}R(V),Q(V,e)}function Ne(){R(V),R(fe),R(he)}function Tt(e){e.memoizedState!==null&&Q(oe,e);var t=V.current,n=Kd(t,e.type);t!==n&&(Q(fe,e),Q(V,n))}function Rt(e){fe.current===e&&(R(V),R(fe)),oe.current===e&&(R(oe),Qa._currentValue=te)}var $l,Ot;function Lt(e){if($l===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\\n( *(at )?)/);$l=t&&t[1]||"",Ot=-1<n.stack.indexOf(\`
|
|
8
|
+
`))}catch{E()}},n.heartbeatMs??yt),f.unref?.()},cancel(){if(c)return;if(c=!0,f!==void 0)clearInterval(f);l?.(),l=void 0}});return new Response(m,{status:n.status??200,headers:{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no"}})}var Gt=':root{--ground: #0b0b0c;--raised: #151517;--line: #26262a;--text: #e8e6e3;--dim: #8b8b93;--accent: #7aa2f7;--warn: #e0af68;--bad: #f7768e;--ok: #9ece6a;--mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;--sans: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--ground);color:var(--text);font:14px / 1.55 var(--sans);-webkit-font-smoothing:antialiased}button{font:inherit;color:inherit;background:var(--raised);border:1px solid var(--line);border-radius:6px;padding:5px 11px;cursor:pointer}button:hover:not(:disabled){border-color:var(--dim)}button:disabled{opacity:.45;cursor:default}button.primary{background:var(--accent);border-color:var(--accent);color:#0b0b0c;font-weight:600}button.bad{color:var(--bad)}input,textarea{font:inherit;color:inherit;background:var(--ground);border:1px solid var(--line);border-radius:6px;padding:8px 10px;width:100%}input:focus,textarea:focus{outline:none;border-color:var(--accent)}.shell{display:grid;grid-template-columns:240px 1fr;height:100vh}.side{background:var(--raised);border-right:1px solid var(--line);display:flex;flex-direction:column;min-height:0}.side header{padding:14px 16px;border-bottom:1px solid var(--line)}.brand{font-weight:650;letter-spacing:.01em}.side nav{padding:8px;overflow-y:auto;flex:1;min-height:0}.side footer{padding:10px 12px;border-top:1px solid var(--line);display:flex;gap:8px;align-items:center}.row-button{display:block;width:100%;text-align:left;background:none;border:none;border-radius:6px;padding:7px 9px;font-family:var(--mono);font-size:12px}.row-button:hover{background:var(--ground)}.row-button[aria-current=true]{background:var(--ground);color:var(--accent)}.group{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--dim);padding:12px 9px 5px}.main{display:flex;flex-direction:column;min-height:0}.bar{display:flex;gap:14px;align-items:baseline;padding:12px 20px;border-bottom:1px solid var(--line);font-size:12px;color:var(--dim);min-height:44px}.bar strong{color:var(--text);font-size:14px;font-weight:600}.bar .spacer{flex:1}.scroll{flex:1;overflow-y:auto;min-height:0;padding:20px}.pad{max-width:780px;margin:0 auto}.row{margin:0 0 16px;white-space:pre-wrap;overflow-wrap:anywhere}.row.user{background:var(--raised);border:1px solid var(--line);border-radius:8px;padding:10px 13px}.label{font-family:var(--mono);font-size:11px;color:var(--dim);margin-bottom:4px}.tool{border-left:2px solid var(--line);padding-left:11px;font-family:var(--mono);font-size:12px}.tool .slug{color:var(--accent)}.tool .out{color:var(--dim);max-height:13em;overflow-y:auto;margin-top:5px}.tool.failed .slug{color:var(--bad)}.tool .mut{color:var(--warn);font-size:11px}.tool .out{display:inline}.fence{border:1px dashed var(--warn);border-radius:6px;padding:7px 9px;margin-top:5px}.fence .why{color:var(--warn);font-size:11px;margin-bottom:4px}.payload-code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:28px;font-weight:600;letter-spacing:.18em;margin:10px 0;-webkit-user-select:all;user-select:all}.channel-input.stale .payload-code{opacity:.35}.payload-qr{display:block;width:240px;max-width:100%;height:auto;border-radius:6px;margin:8px 0}.channel-input.stale .payload-qr{opacity:.35}.note{font-size:12px;color:var(--dim);border-left:2px solid var(--line);padding-left:11px;white-space:pre-wrap}.note.bad{color:var(--bad);border-left-color:var(--bad)}.ask{border:1px solid var(--warn);border-radius:8px;padding:12px 14px;background:#17140e}.ask .what{font-family:var(--mono);font-size:12px;margin:6px 0 10px;white-space:pre-wrap;overflow-wrap:anywhere}.ask .buttons{display:flex;gap:8px}.ask .settled{font-size:12px;color:var(--dim)}details.fold summary{cursor:pointer;color:var(--dim);font-family:var(--mono);font-size:11px}details.fold[open] summary{margin-bottom:5px}details.fold .body{color:var(--dim);font-size:13px}.composer{border-top:1px solid var(--line);padding:12px 20px}.composer .inner{max-width:780px;margin:0 auto;display:flex;gap:9px;align-items:flex-end}.composer textarea{resize:none;min-height:40px;max-height:190px;font-family:var(--sans)}.hint{font-size:11px;color:var(--dim);max-width:780px;margin:6px auto 0}.card{border:1px solid var(--line);border-radius:8px;padding:16px 18px;margin-bottom:14px;background:var(--raised)}.card h2{margin:0 0 4px;font-size:15px}.card p{margin:0 0 12px;color:var(--dim);font-size:13px}table{width:100%;border-collapse:collapse;font-size:13px}th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:var(--dim);font-weight:500;padding:0 10px 7px 0}td{padding:8px 10px 8px 0;border-top:1px solid var(--line);font-family:var(--mono);font-size:12px}td.revoked{color:var(--dim);text-decoration:line-through}.secret{font-family:var(--mono);font-size:12px;background:var(--ground);border:1px solid var(--ok);border-radius:6px;padding:9px 11px;overflow-wrap:anywhere;margin-bottom:8px}.gate{display:grid;place-items:center;height:100vh;padding:20px}.gate .card{max-width:460px;width:100%}.dot{width:7px;height:7px;border-radius:50%;display:inline-block;background:var(--dim)}.dot.live{background:var(--ok)}.dot.busy{background:var(--warn)}@media(max-width:720px){.shell{grid-template-columns:1fr}.side{display:none}}.agent-row{display:block}.agent-row .row-button:disabled{color:var(--dim);cursor:default}.agent-off{color:var(--warn);font-size:11px}.agent-note{display:flex;gap:6px;align-items:baseline;padding:0 9px 6px;font-size:11px;color:var(--dim)}.link{background:none;border:none;padding:0;color:var(--accent);font-size:11px;text-decoration:underline;cursor:pointer}.link:disabled{color:var(--dim);cursor:default;text-decoration:none}.empty{color:var(--dim);font-size:13px;max-width:60ch}.panel-table{width:100%;border-collapse:collapse;font-size:12px}.panel-table th{text-align:left;font-weight:500;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--dim);padding:6px 10px 6px 0;border-bottom:1px solid var(--line)}.panel-table td{padding:9px 10px 9px 0;border-bottom:1px solid var(--line);vertical-align:top}.panel-table tr.off td{color:var(--dim)}.sub{color:var(--dim);font-size:11px;margin-top:2px;max-width:52ch}.channel{border:1px solid var(--line);border-radius:8px;padding:12px 14px;margin-bottom:12px}.channel h3{margin:0 0 6px;font-size:13px;font-weight:500}.status{margin:0;font-size:12px}.status-connected{color:var(--ok)}.status-error,.status-disconnected{color:var(--bad)}.status-needs_input{color:var(--warn)}.channel-input{margin-top:10px;padding:10px;border-radius:6px;background:var(--ground)}.payload{margin:0;font-family:var(--mono);font-size:11px;white-space:pre-wrap;word-break:break-all;max-height:9em;overflow-y:auto}.channel-input.stale .payload{opacity:.45}.warn{color:var(--warn);font-size:12px;margin:0 0 6px}select{font:inherit;color:inherit;background:var(--ground);border:1px solid var(--line);border-radius:6px;padding:8px 10px;width:100%}select:focus{outline:none;border-color:var(--accent)}.provision{display:flex;flex-direction:column;gap:16px;max-width:60ch}.provision>button[type=submit]{align-self:flex-start}.field label{display:block;font-size:12px;color:var(--dim);margin-bottom:5px}.field.invalid input,.field.invalid select{border-color:var(--bad)}.sub{color:var(--dim);font-size:11px}.error{color:var(--bad);font-size:13px;max-width:60ch}.ok{color:var(--ok);font-size:13px}.created{max-width:66ch;font-size:13px}.created h3{font-size:15px;font-weight:600;margin:0 0 10px}.created p{margin:0 0 10px}.blank-secrets{border:1px solid var(--warn);border-radius:6px;padding:11px 13px;margin:14px 0}.blank-secrets p{margin:0 0 6px}.blank-secrets p:last-child{margin:0}.config-row{border-bottom:1px solid var(--line);padding:14px 0;max-width:72ch}.config-row:first-of-type{padding-top:0}.config-head{display:flex;align-items:baseline;gap:8px}.config-row .sub{margin:4px 0 8px;max-width:68ch}.config-row input[type=text],.config-row input:not([type]),.config-row textarea{width:100%;font-family:var(--mono);font-size:12px}.config-row button{margin-top:8px}.config-row label input[type=checkbox]{width:auto;margin-right:4px;vertical-align:baseline}.form-grid{display:grid;grid-template-columns:6em 1fr;gap:8px 12px;align-items:start;max-width:60ch}.form-grid label{font-size:12px;color:var(--dim);padding-top:9px}.form-grid input,.form-grid select{width:100%}.form-grid>div>input+input{margin-top:6px}.warnings{border:1px solid var(--warn);border-radius:6px;padding:.75rem 1rem;margin-bottom:1rem}.warnings h3{margin:0;color:var(--warn)}.warnings .sub{margin:.25rem 0 .75rem;opacity:.8}.warning{margin-top:.5rem}.warning-message{margin:0}.warning .hint{margin:.15rem 0 0;opacity:.75}.channel-actions{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-top:.5rem}.channel-actions form{display:flex;gap:.35rem}.channel-actions input{min-width:14rem}.status-off{opacity:.7}\n',qt=`(function(){const c=document.createElement("link").relList;if(c&&c.supports&&c.supports("modulepreload"))return;for(const h of document.querySelectorAll('link[rel="modulepreload"]'))s(h);new MutationObserver(h=>{for(const o of h)if(o.type==="childList")for(const v of o.addedNodes)v.tagName==="LINK"&&v.rel==="modulepreload"&&s(v)}).observe(document,{childList:!0,subtree:!0});function r(h){const o={};return h.integrity&&(o.integrity=h.integrity),h.referrerPolicy&&(o.referrerPolicy=h.referrerPolicy),h.crossOrigin==="use-credentials"?o.credentials="include":h.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(h){if(h.ep)return;h.ep=!0;const o=r(h);fetch(h.href,o)}})();function Qg(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Rs={exports:{}},Va={};var ph;function Xg(){if(ph)return Va;ph=1;var i=Symbol.for("react.transitional.element"),c=Symbol.for("react.fragment");function r(s,h,o){var v=null;if(o!==void 0&&(v=""+o),h.key!==void 0&&(v=""+h.key),"key"in h){o={};for(var z in h)z!=="key"&&(o[z]=h[z])}else o=h;return h=o.ref,{$$typeof:i,type:s,key:v,ref:h!==void 0?h:null,props:o}}return Va.Fragment=c,Va.jsx=r,Va.jsxs=r,Va}var Eh;function Kg(){return Eh||(Eh=1,Rs.exports=Xg()),Rs.exports}var m=Kg(),Os={exports:{}},de={};var Th;function Zg(){if(Th)return de;Th=1;var i=Symbol.for("react.transitional.element"),c=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),h=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),v=Symbol.for("react.context"),z=Symbol.for("react.forward_ref"),E=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),S=Symbol.for("react.activity"),N=Symbol.iterator;function H(b){return b===null||typeof b!="object"?null:(b=N&&b[N]||b["@@iterator"],typeof b=="function"?b:null)}var G={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},B=Object.assign,re={};function Y(b,R,Q){this.props=b,this.context=R,this.refs=re,this.updater=Q||G}Y.prototype.isReactComponent={},Y.prototype.setState=function(b,R){if(typeof b!="object"&&typeof b!="function"&&b!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,b,R,"setState")},Y.prototype.forceUpdate=function(b){this.updater.enqueueForceUpdate(this,b,"forceUpdate")};function se(){}se.prototype=Y.prototype;function W(b,R,Q){this.props=b,this.context=R,this.refs=re,this.updater=Q||G}var $=W.prototype=new se;$.constructor=W,B($,Y.prototype),$.isPureReactComponent=!0;var Te=Array.isArray;function Z(){}var L={H:null,A:null,T:null,S:null},X=Object.prototype.hasOwnProperty;function J(b,R,Q){var V=Q.ref;return{$$typeof:i,type:b,key:R,ref:V!==void 0?V:null,props:Q}}function le(b,R){return J(b.type,R,b.props)}function q(b){return typeof b=="object"&&b!==null&&b.$$typeof===i}function F(b){var R={"=":"=0",":":"=2"};return"$"+b.replace(/[=:]/g,function(Q){return R[Q]})}var ee=/\\/+/g;function ie(b,R){return typeof b=="object"&&b!==null&&b.key!=null?F(""+b.key):R.toString(36)}function Le(b){switch(b.status){case"fulfilled":return b.value;case"rejected":throw b.reason;default:switch(typeof b.status=="string"?b.then(Z,Z):(b.status="pending",b.then(function(R){b.status==="pending"&&(b.status="fulfilled",b.value=R)},function(R){b.status==="pending"&&(b.status="rejected",b.reason=R)})),b.status){case"fulfilled":return b.value;case"rejected":throw b.reason}}throw b}function _(b,R,Q,V,fe){var he=typeof b;(he==="undefined"||he==="boolean")&&(b=null);var oe=!1;if(b===null)oe=!0;else switch(he){case"bigint":case"string":case"number":oe=!0;break;case"object":switch(b.$$typeof){case i:case c:oe=!0;break;case A:return oe=b._init,_(oe(b._payload),R,Q,V,fe)}}if(oe)return fe=fe(b),oe=V===""?"."+ie(b,0):V,Te(fe)?(Q="",oe!=null&&(Q=oe.replace(ee,"$&/")+"/"),_(fe,R,Q,"",function(Tt){return Tt})):fe!=null&&(q(fe)&&(fe=le(fe,Q+(fe.key==null||b&&b.key===fe.key?"":(""+fe.key).replace(ee,"$&/")+"/")+oe)),R.push(fe)),1;oe=0;var we=V===""?".":V+":";if(Te(b))for(var Ne=0;Ne<b.length;Ne++)V=b[Ne],he=we+ie(V,Ne),oe+=_(V,R,Q,he,fe);else if(Ne=H(b),typeof Ne=="function")for(b=Ne.call(b),Ne=0;!(V=b.next()).done;)V=V.value,he=we+ie(V,Ne++),oe+=_(V,R,Q,he,fe);else if(he==="object"){if(typeof b.then=="function")return _(Le(b),R,Q,V,fe);throw R=String(b),Error("Objects are not valid as a React child (found: "+(R==="[object Object]"?"object with keys {"+Object.keys(b).join(", ")+"}":R)+"). If you meant to render a collection of children, use an array instead.")}return oe}function K(b,R,Q){if(b==null)return b;var V=[],fe=0;return _(b,V,"","",function(he){return R.call(Q,he,fe++)}),V}function te(b){if(b._status===-1){var R=b._result;R=R(),R.then(function(Q){(b._status===0||b._status===-1)&&(b._status=1,b._result=Q)},function(Q){(b._status===0||b._status===-1)&&(b._status=2,b._result=Q)}),b._status===-1&&(b._status=0,b._result=R)}if(b._status===1)return b._result.default;throw b._result}var Ae=typeof reportError=="function"?reportError:function(b){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var R=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof b=="object"&&b!==null&&typeof b.message=="string"?String(b.message):String(b),error:b});if(!window.dispatchEvent(R))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",b);return}console.error(b)},Ee={map:K,forEach:function(b,R,Q){K(b,function(){R.apply(this,arguments)},Q)},count:function(b){var R=0;return K(b,function(){R++}),R},toArray:function(b){return K(b,function(R){return R})||[]},only:function(b){if(!q(b))throw Error("React.Children.only expected to receive a single React element child.");return b}};return de.Activity=S,de.Children=Ee,de.Component=Y,de.Fragment=r,de.Profiler=h,de.PureComponent=W,de.StrictMode=s,de.Suspense=E,de.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=L,de.__COMPILER_RUNTIME={__proto__:null,c:function(b){return L.H.useMemoCache(b)}},de.cache=function(b){return function(){return b.apply(null,arguments)}},de.cacheSignal=function(){return null},de.cloneElement=function(b,R,Q){if(b==null)throw Error("The argument must be a React element, but you passed "+b+".");var V=B({},b.props),fe=b.key;if(R!=null)for(he in R.key!==void 0&&(fe=""+R.key),R)!X.call(R,he)||he==="key"||he==="__self"||he==="__source"||he==="ref"&&R.ref===void 0||(V[he]=R[he]);var he=arguments.length-2;if(he===1)V.children=Q;else if(1<he){for(var oe=Array(he),we=0;we<he;we++)oe[we]=arguments[we+2];V.children=oe}return J(b.type,fe,V)},de.createContext=function(b){return b={$$typeof:v,_currentValue:b,_currentValue2:b,_threadCount:0,Provider:null,Consumer:null},b.Provider=b,b.Consumer={$$typeof:o,_context:b},b},de.createElement=function(b,R,Q){var V,fe={},he=null;if(R!=null)for(V in R.key!==void 0&&(he=""+R.key),R)X.call(R,V)&&V!=="key"&&V!=="__self"&&V!=="__source"&&(fe[V]=R[V]);var oe=arguments.length-2;if(oe===1)fe.children=Q;else if(1<oe){for(var we=Array(oe),Ne=0;Ne<oe;Ne++)we[Ne]=arguments[Ne+2];fe.children=we}if(b&&b.defaultProps)for(V in oe=b.defaultProps,oe)fe[V]===void 0&&(fe[V]=oe[V]);return J(b,he,fe)},de.createRef=function(){return{current:null}},de.forwardRef=function(b){return{$$typeof:z,render:b}},de.isValidElement=q,de.lazy=function(b){return{$$typeof:A,_payload:{_status:-1,_result:b},_init:te}},de.memo=function(b,R){return{$$typeof:g,type:b,compare:R===void 0?null:R}},de.startTransition=function(b){var R=L.T,Q={};L.T=Q;try{var V=b(),fe=L.S;fe!==null&&fe(Q,V),typeof V=="object"&&V!==null&&typeof V.then=="function"&&V.then(Z,Ae)}catch(he){Ae(he)}finally{R!==null&&Q.types!==null&&(R.types=Q.types),L.T=R}},de.unstable_useCacheRefresh=function(){return L.H.useCacheRefresh()},de.use=function(b){return L.H.use(b)},de.useActionState=function(b,R,Q){return L.H.useActionState(b,R,Q)},de.useCallback=function(b,R){return L.H.useCallback(b,R)},de.useContext=function(b){return L.H.useContext(b)},de.useDebugValue=function(){},de.useDeferredValue=function(b,R){return L.H.useDeferredValue(b,R)},de.useEffect=function(b,R){return L.H.useEffect(b,R)},de.useEffectEvent=function(b){return L.H.useEffectEvent(b)},de.useId=function(){return L.H.useId()},de.useImperativeHandle=function(b,R,Q){return L.H.useImperativeHandle(b,R,Q)},de.useInsertionEffect=function(b,R){return L.H.useInsertionEffect(b,R)},de.useLayoutEffect=function(b,R){return L.H.useLayoutEffect(b,R)},de.useMemo=function(b,R){return L.H.useMemo(b,R)},de.useOptimistic=function(b,R){return L.H.useOptimistic(b,R)},de.useReducer=function(b,R,Q){return L.H.useReducer(b,R,Q)},de.useRef=function(b){return L.H.useRef(b)},de.useState=function(b){return L.H.useState(b)},de.useSyncExternalStore=function(b,R,Q){return L.H.useSyncExternalStore(b,R,Q)},de.useTransition=function(){return L.H.useTransition()},de.version="19.2.8",de}var Ah;function bf(){return Ah||(Ah=1,Os.exports=Zg()),Os.exports}var k=bf(),Ds={exports:{}},ka={},Bs={exports:{}},Hs={};var zh;function Vg(){return zh||(zh=1,(function(i){function c(_,K){var te=_.length;_.push(K);e:for(;0<te;){var Ae=te-1>>>1,Ee=_[Ae];if(0<h(Ee,K))_[Ae]=K,_[te]=Ee,te=Ae;else break e}}function r(_){return _.length===0?null:_[0]}function s(_){if(_.length===0)return null;var K=_[0],te=_.pop();if(te!==K){_[0]=te;e:for(var Ae=0,Ee=_.length,b=Ee>>>1;Ae<b;){var R=2*(Ae+1)-1,Q=_[R],V=R+1,fe=_[V];if(0>h(Q,te))V<Ee&&0>h(fe,Q)?(_[Ae]=fe,_[V]=te,Ae=V):(_[Ae]=Q,_[R]=te,Ae=R);else if(V<Ee&&0>h(fe,te))_[Ae]=fe,_[V]=te,Ae=V;else break e}}return K}function h(_,K){var te=_.sortIndex-K.sortIndex;return te!==0?te:_.id-K.id}if(i.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;i.unstable_now=function(){return o.now()}}else{var v=Date,z=v.now();i.unstable_now=function(){return v.now()-z}}var E=[],g=[],A=1,S=null,N=3,H=!1,G=!1,B=!1,re=!1,Y=typeof setTimeout=="function"?setTimeout:null,se=typeof clearTimeout=="function"?clearTimeout:null,W=typeof setImmediate<"u"?setImmediate:null;function $(_){for(var K=r(g);K!==null;){if(K.callback===null)s(g);else if(K.startTime<=_)s(g),K.sortIndex=K.expirationTime,c(E,K);else break;K=r(g)}}function Te(_){if(B=!1,$(_),!G)if(r(E)!==null)G=!0,Z||(Z=!0,F());else{var K=r(g);K!==null&&Le(Te,K.startTime-_)}}var Z=!1,L=-1,X=5,J=-1;function le(){return re?!0:!(i.unstable_now()-J<X)}function q(){if(re=!1,Z){var _=i.unstable_now();J=_;var K=!0;try{e:{G=!1,B&&(B=!1,se(L),L=-1),H=!0;var te=N;try{t:{for($(_),S=r(E);S!==null&&!(S.expirationTime>_&&le());){var Ae=S.callback;if(typeof Ae=="function"){S.callback=null,N=S.priorityLevel;var Ee=Ae(S.expirationTime<=_);if(_=i.unstable_now(),typeof Ee=="function"){S.callback=Ee,$(_),K=!0;break t}S===r(E)&&s(E),$(_)}else s(E);S=r(E)}if(S!==null)K=!0;else{var b=r(g);b!==null&&Le(Te,b.startTime-_),K=!1}}break e}finally{S=null,N=te,H=!1}K=void 0}}finally{K?F():Z=!1}}}var F;if(typeof W=="function")F=function(){W(q)};else if(typeof MessageChannel<"u"){var ee=new MessageChannel,ie=ee.port2;ee.port1.onmessage=q,F=function(){ie.postMessage(null)}}else F=function(){Y(q,0)};function Le(_,K){L=Y(function(){_(i.unstable_now())},K)}i.unstable_IdlePriority=5,i.unstable_ImmediatePriority=1,i.unstable_LowPriority=4,i.unstable_NormalPriority=3,i.unstable_Profiling=null,i.unstable_UserBlockingPriority=2,i.unstable_cancelCallback=function(_){_.callback=null},i.unstable_forceFrameRate=function(_){0>_||125<_?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):X=0<_?Math.floor(1e3/_):5},i.unstable_getCurrentPriorityLevel=function(){return N},i.unstable_next=function(_){switch(N){case 1:case 2:case 3:var K=3;break;default:K=N}var te=N;N=K;try{return _()}finally{N=te}},i.unstable_requestPaint=function(){re=!0},i.unstable_runWithPriority=function(_,K){switch(_){case 1:case 2:case 3:case 4:case 5:break;default:_=3}var te=N;N=_;try{return K()}finally{N=te}},i.unstable_scheduleCallback=function(_,K,te){var Ae=i.unstable_now();switch(typeof te=="object"&&te!==null?(te=te.delay,te=typeof te=="number"&&0<te?Ae+te:Ae):te=Ae,_){case 1:var Ee=-1;break;case 2:Ee=250;break;case 5:Ee=1073741823;break;case 4:Ee=1e4;break;default:Ee=5e3}return Ee=te+Ee,_={id:A++,callback:K,priorityLevel:_,startTime:te,expirationTime:Ee,sortIndex:-1},te>Ae?(_.sortIndex=te,c(g,_),r(E)===null&&_===r(g)&&(B?(se(L),L=-1):B=!0,Le(Te,te-Ae))):(_.sortIndex=Ee,c(E,_),G||H||(G=!0,Z||(Z=!0,F()))),_},i.unstable_shouldYield=le,i.unstable_wrapCallback=function(_){var K=N;return function(){var te=N;N=K;try{return _.apply(this,arguments)}finally{N=te}}}})(Hs)),Hs}var Ch;function kg(){return Ch||(Ch=1,Bs.exports=Vg()),Bs.exports}var qs={exports:{}},at={};var Nh;function Jg(){if(Nh)return at;Nh=1;var i=bf();function c(E){var g="https://react.dev/errors/"+E;if(1<arguments.length){g+="?args[]="+encodeURIComponent(arguments[1]);for(var A=2;A<arguments.length;A++)g+="&args[]="+encodeURIComponent(arguments[A])}return"Minified React error #"+E+"; visit "+g+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(){}var s={d:{f:r,r:function(){throw Error(c(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},h=Symbol.for("react.portal");function o(E,g,A){var S=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:h,key:S==null?null:""+S,children:E,containerInfo:g,implementation:A}}var v=i.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function z(E,g){if(E==="font")return"";if(typeof g=="string")return g==="use-credentials"?g:""}return at.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=s,at.createPortal=function(E,g){var A=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!g||g.nodeType!==1&&g.nodeType!==9&&g.nodeType!==11)throw Error(c(299));return o(E,g,null,A)},at.flushSync=function(E){var g=v.T,A=s.p;try{if(v.T=null,s.p=2,E)return E()}finally{v.T=g,s.p=A,s.d.f()}},at.preconnect=function(E,g){typeof E=="string"&&(g?(g=g.crossOrigin,g=typeof g=="string"?g==="use-credentials"?g:"":void 0):g=null,s.d.C(E,g))},at.prefetchDNS=function(E){typeof E=="string"&&s.d.D(E)},at.preinit=function(E,g){if(typeof E=="string"&&g&&typeof g.as=="string"){var A=g.as,S=z(A,g.crossOrigin),N=typeof g.integrity=="string"?g.integrity:void 0,H=typeof g.fetchPriority=="string"?g.fetchPriority:void 0;A==="style"?s.d.S(E,typeof g.precedence=="string"?g.precedence:void 0,{crossOrigin:S,integrity:N,fetchPriority:H}):A==="script"&&s.d.X(E,{crossOrigin:S,integrity:N,fetchPriority:H,nonce:typeof g.nonce=="string"?g.nonce:void 0})}},at.preinitModule=function(E,g){if(typeof E=="string")if(typeof g=="object"&&g!==null){if(g.as==null||g.as==="script"){var A=z(g.as,g.crossOrigin);s.d.M(E,{crossOrigin:A,integrity:typeof g.integrity=="string"?g.integrity:void 0,nonce:typeof g.nonce=="string"?g.nonce:void 0})}}else g==null&&s.d.M(E)},at.preload=function(E,g){if(typeof E=="string"&&typeof g=="object"&&g!==null&&typeof g.as=="string"){var A=g.as,S=z(A,g.crossOrigin);s.d.L(E,A,{crossOrigin:S,integrity:typeof g.integrity=="string"?g.integrity:void 0,nonce:typeof g.nonce=="string"?g.nonce:void 0,type:typeof g.type=="string"?g.type:void 0,fetchPriority:typeof g.fetchPriority=="string"?g.fetchPriority:void 0,referrerPolicy:typeof g.referrerPolicy=="string"?g.referrerPolicy:void 0,imageSrcSet:typeof g.imageSrcSet=="string"?g.imageSrcSet:void 0,imageSizes:typeof g.imageSizes=="string"?g.imageSizes:void 0,media:typeof g.media=="string"?g.media:void 0})}},at.preloadModule=function(E,g){if(typeof E=="string")if(g){var A=z(g.as,g.crossOrigin);s.d.m(E,{as:typeof g.as=="string"&&g.as!=="script"?g.as:void 0,crossOrigin:A,integrity:typeof g.integrity=="string"?g.integrity:void 0})}else s.d.m(E)},at.requestFormReset=function(E){s.d.r(E)},at.unstable_batchedUpdates=function(E,g){return E(g)},at.useFormState=function(E,g,A){return v.H.useFormState(E,g,A)},at.useFormStatus=function(){return v.H.useHostTransitionStatus()},at.version="19.2.8",at}var jh;function $g(){if(jh)return qs.exports;jh=1;function i(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(c){console.error(c)}}return i(),qs.exports=Jg(),qs.exports}var xh;function Fg(){if(xh)return ka;xh=1;var i=kg(),c=bf(),r=$g();function s(e){var t="https://react.dev/errors/"+e;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n])}return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function h(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function o(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,(t.flags&4098)!==0&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function v(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function z(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function E(e){if(o(e)!==e)throw Error(s(188))}function g(e){var t=e.alternate;if(!t){if(t=o(e),t===null)throw Error(s(188));return t!==e?null:e}for(var n=e,l=t;;){var a=n.return;if(a===null)break;var u=a.alternate;if(u===null){if(l=a.return,l!==null){n=l;continue}break}if(a.child===u.child){for(u=a.child;u;){if(u===n)return E(a),e;if(u===l)return E(a),t;u=u.sibling}throw Error(s(188))}if(n.return!==l.return)n=a,l=u;else{for(var f=!1,d=a.child;d;){if(d===n){f=!0,n=a,l=u;break}if(d===l){f=!0,l=a,n=u;break}d=d.sibling}if(!f){for(d=u.child;d;){if(d===n){f=!0,n=u,l=a;break}if(d===l){f=!0,l=u,n=a;break}d=d.sibling}if(!f)throw Error(s(189))}}if(n.alternate!==l)throw Error(s(190))}if(n.tag!==3)throw Error(s(188));return n.stateNode.current===n?e:t}function A(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=A(e),t!==null)return t;e=e.sibling}return null}var S=Object.assign,N=Symbol.for("react.element"),H=Symbol.for("react.transitional.element"),G=Symbol.for("react.portal"),B=Symbol.for("react.fragment"),re=Symbol.for("react.strict_mode"),Y=Symbol.for("react.profiler"),se=Symbol.for("react.consumer"),W=Symbol.for("react.context"),$=Symbol.for("react.forward_ref"),Te=Symbol.for("react.suspense"),Z=Symbol.for("react.suspense_list"),L=Symbol.for("react.memo"),X=Symbol.for("react.lazy"),J=Symbol.for("react.activity"),le=Symbol.for("react.memo_cache_sentinel"),q=Symbol.iterator;function F(e){return e===null||typeof e!="object"?null:(e=q&&e[q]||e["@@iterator"],typeof e=="function"?e:null)}var ee=Symbol.for("react.client.reference");function ie(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===ee?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case B:return"Fragment";case Y:return"Profiler";case re:return"StrictMode";case Te:return"Suspense";case Z:return"SuspenseList";case J:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case G:return"Portal";case W:return e.displayName||"Context";case se:return(e._context.displayName||"Context")+".Consumer";case $:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case L:return t=e.displayName||null,t!==null?t:ie(e.type)||"Memo";case X:t=e._payload,e=e._init;try{return ie(e(t))}catch{}}return null}var Le=Array.isArray,_=c.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,te={pending:!1,data:null,method:null,action:null},Ae=[],Ee=-1;function b(e){return{current:e}}function R(e){0>Ee||(e.current=Ae[Ee],Ae[Ee]=null,Ee--)}function Q(e,t){Ee++,Ae[Ee]=e.current,e.current=t}var V=b(null),fe=b(null),he=b(null),oe=b(null);function we(e,t){switch(Q(he,t),Q(fe,e),Q(V,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Xd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Xd(t),e=Kd(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}R(V),Q(V,e)}function Ne(){R(V),R(fe),R(he)}function Tt(e){e.memoizedState!==null&&Q(oe,e);var t=V.current,n=Kd(t,e.type);t!==n&&(Q(fe,e),Q(V,n))}function Rt(e){fe.current===e&&(R(V),R(fe)),oe.current===e&&(R(oe),Qa._currentValue=te)}var $l,Ot;function Lt(e){if($l===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\\n( *(at )?)/);$l=t&&t[1]||"",Ot=-1<n.stack.indexOf(\`
|
|
9
9
|
at\`)?" (<anonymous>)":-1<n.stack.indexOf("@")?"@unknown:0:0":""}return\`
|
|
10
10
|
\`+$l+e+Ot}var dn=!1;function il(e,t){if(!e||dn)return"";dn=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var l={DetermineComponentFrameRoot:function(){try{if(t){var O=function(){throw Error()};if(Object.defineProperty(O.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(O,[])}catch(M){var x=M}Reflect.construct(e,[],O)}else{try{O.call()}catch(M){x=M}e.call(O.prototype)}}else{try{throw Error()}catch(M){x=M}(O=e())&&typeof O.catch=="function"&&O.catch(function(){})}}catch(M){if(M&&x&&typeof M.stack=="string")return[M.stack,x.stack]}return[null,null]}};l.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var a=Object.getOwnPropertyDescriptor(l.DetermineComponentFrameRoot,"name");a&&a.configurable&&Object.defineProperty(l.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var u=l.DetermineComponentFrameRoot(),f=u[0],d=u[1];if(f&&d){var y=f.split(\`
|
|
11
11
|
\`),j=d.split(\`
|
|
@@ -58,7 +58,7 @@ Minimum version required to store current data is: \`+q+\`.
|
|
|
58
58
|
<div id="root"></div>
|
|
59
59
|
</body>
|
|
60
60
|
</html>
|
|
61
|
-
`;function Wt(
|
|
61
|
+
`;function Wt(n){let e=2166136261;for(let l=0;l<n.length;l+=1)e^=n.charCodeAt(l),e=Math.imul(e,16777619)>>>0;return`"${e.toString(36)}-${n.length.toString(36)}"`}function me(n,e){return{body:n,contentType:e,etag:Wt(n)}}var vt={"/":me(Kt,"text/html; charset=utf-8"),"/assets/app.js":me(qt,"text/javascript; charset=utf-8"),"/assets/app.css":me(Gt,"text/css; charset=utf-8")},Vt=Object.keys(vt);function Qt(n,e){let l=vt[n];if(l===void 0)return;let f={"content-type":l.contentType,etag:l.etag,"cache-control":"no-cache"};if(e.headers.get("if-none-match")===l.etag)return new Response(null,{status:304,headers:f});return new Response(l.body,{status:200,headers:f})}var Yt=1e6,Jt=25000000,Ce=256,Xt=128,ge=255,Zt=`<!doctype html>
|
|
62
62
|
<html lang="en">
|
|
63
63
|
<head>
|
|
64
64
|
<meta charset="utf-8">
|
|
@@ -78,13 +78,13 @@ Minimum version required to store current data is: \`+q+\`.
|
|
|
78
78
|
</script>
|
|
79
79
|
</body>
|
|
80
80
|
</html>
|
|
81
|
-
`;function en(t){let{runtime:e}=t,s=t.token,d=t.now??(()=>Date.now()),c=d();if(s===void 0&&t.allowUnauthenticated!==!0)throw new Ae({code:"server_token_missing",message:"createHandler was called with no token and no allowUnauthenticated.",hint:"Pass token, or pass allowUnauthenticated: true to state that this handler is mounted somewhere already protected. Defaulting to open would make the safe configuration the one you have to remember."});let p=t.running??new Map,b=t.approvals??_r(),S=()=>t.origin!==void 0&&se(t.origin.host),W=(r)=>S()||r.kind!=="open"&&he(r,"admin"),j=(r)=>{if(t.origin===void 0)return;let n=le(r,t.origin);return n===void 0?void 0:h(n,403)},k=(r,n)=>{if(t.origin===void 0)return n;let a=Ut(r,t.origin);if(Object.keys(a).length===0)return n;let l=new Headers(n.headers);for(let[u,f]of Object.entries(a))l.set(u,f);return new Response(n.body,{status:n.status,statusText:n.statusText,headers:l})},G=!1,N=async()=>{if(s!==void 0||G)return!0;return G=await e.store.operatorKeys.liveCount()>0,G},A=async(r,n,a)=>{if(tn(n)||!await N())return{kind:"open"};let l=await Et({request:r,expected:s,keys:e.store.operatorKeys,claim:t.claim,pathname:n,at:d()});if(l instanceof Response)return l;if(l.kind==="claim")return l;if(a!=="open"&&!he(l,a))return St(a,`${r.method} ${n}`);return l},m=new mt;m.add("GET","/v1/health",()=>y({status:"ok",version:Je,uptimeMs:d()-c,agents:e.list().length}),{capability:"open"}),m.add("GET","/v1/ready",()=>{if(e.ready)return y({status:"ready",agents:e.list().length});if(e.draining)return y({status:"draining",agents:e.list().length},503);return y({status:"starting",agents:e.list().length},503)},{capability:"open"}),m.add("GET","/v1/activity",async(r)=>{let n=r.principal;if(n.kind==="key"&&n.scope!==void 0&&(n.scope.agents!==void 0||n.scope.sessions!==void 0))return h({code:"activity_needs_unscoped_key",message:"Activity covers every agent on this server, and this key is scoped.",hint:"Call this with the server token or an operator key minted with no agents or sessions scope — it is meant for whatever suspends and wakes the process, not for a tenant."},403);return y(await e.activity(d()))},{capability:"admin"}),m.add("GET","/v1/agents",async(r)=>{let n=e.list().map((u)=>Le(e,u)),a=new Set(n.map((u)=>u.id)),l=(await e.store.agentState.list()).filter((u)=>!u.enabled&&!a.has(u.agentId)).map((u)=>({id:u.agentId,name:u.agentId,status:"disabled",...u.reason===void 0?{}:{reason:u.reason},...u.disabledAt===void 0?{}:{disabledAt:u.disabledAt}}));return y(an(r.principal,[...n,...l]))},{capability:"read"}),m.add("GET","/v1/agents/:id",(r)=>C(e,r,async(n)=>{let a=await n.store.schedules.list(n.id),l=e.team(n.id),u=await e.store.conversations.assignment(n.id);return y({...Le(e,n),...u===void 0?{}:{assignedTo:{participantId:u.participantId,...u.assignedBy===void 0?{}:{assignedBy:u.assignedBy},assignedAt:u.assignedAt}},dialect:n.describe().dialect,window:n.window,tools:n.tools.size,catalogueTokens:n.describe().catalogueTokens,skills:n.skills?.skills.length??0,schedules:a.length,...l.length===0?{}:{team:l.map((f)=>({id:f.id,task:f.task,artifact:Object.keys(f.artifact.properties)}))},warnings:[...n.warnings,...n.tools.warnings]})}),{capability:"read"}),m.add("GET","/v1/agents/:id/export",(r)=>C(e,r,async(n)=>{let a=await L(r.principal);if(a!==void 0)return a;let l=r.url.searchParams.get("paths");try{let u=ls(l===null?void 0:l.split(",").map((f)=>f.trim()));return y(Is(n,u))}catch(u){return E(u)}}),{capability:"admin"}),m.add("POST","/v1/agents/:id/import",(r)=>C(e,r,async(n)=>{let a=await L(r.principal);if(a!==void 0)return a;let l=await M(r.request,Jt);if(l.kind==="error")return h(l.error,400);let u=B(lt,l.value);if(!u.ok)return h(u.error,400);try{let f=await us({agent:n,bundle:u.value.bundle,...u.value.mode===void 0?{}:{mode:u.value.mode},reload:async()=>(await e.reload(n.id)).status});return y({id:n.id,...f})}catch(f){return E(f)}}),{capability:"admin"}),m.add("POST","/v1/agents/:id/reload",(r)=>C(e,r,async(n)=>{try{let a=await e.reload(n.id);if(a.status==="pending")return y({id:n.id,status:"pending",adopted:[],running:a.running,holdAfterMs:a.holdAfterMs},202);return y({id:n.id,status:"loaded",adopted:a.adopted.map((l)=>l.id)})}catch(a){if(K(a))return h({code:a.code,message:a.message,hint:a.hint,...a.field===void 0?{}:{field:a.field}},a.code==="agent_turn_in_flight"?409:400);throw a}}),{capability:"admin"}),m.add("GET","/v1/openapi.json",(r)=>y(Mt({routes:m.routes(),serverUrl:`${r.url.protocol}//${r.url.host}`})),{capability:"open"}),m.add("GET","/docs",()=>new Response(Zt,{status:200,headers:{"content-type":"text/html; charset=utf-8"}}),{capability:"open"}),m.add("GET","/v1/provision",(r)=>y({available:t.provision!==void 0,local:S(),allowed:W(r.principal),steps:t.provision?.steps()??[]}),{capability:"read"}),m.add("POST","/v1/agents",async(r)=>{let n=t.provision;if(n===void 0)return h({code:"provisioning_not_supported",message:"This server cannot create agents.",hint:"Creating one writes a directory of files from a question set this process was not given — an embedder mounting this handler over its own agent store is the case that lands here. Run `init` where the sandbox is, or mount an agent directory."},501);if(!W(r.principal))return h({code:"provisioning_not_local",message:"Creating an agent needs either a loopback bind or a credential with the admin capability.",hint:"This route writes files and starts an agent. A token-less loopback server is a supported configuration, so on a non-loopback bind it asks for a credential instead — set server.tokenEnv (the container's DISPACH_API_TOKEN does this) or present an operator key minted with `can: [admin]`. What is refused is provisioning on a server that required no credential at all and is reachable from the network."},403);let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let l=B(Ve,a.value);if(!l.ok)return h(l.error,400);let{answers:u,template:f}=l.value;if(u!==void 0&&f!==void 0)return h({code:"provision_body_ambiguous",message:"The body has both answers and a template.",hint:"Send answers to create an agent the way init does, or template with name and vars to create one from a template in this server's sandbox. Not both.",field:"template"},400);if(u===void 0&&f===void 0)return h({code:"provision_answers_required",message:"The body has neither answers nor a template.",hint:'Send { "answers": { "name": "milo", … } } (GET /v1/provision lists the steps), or { "template": "…", "name": "…", "vars": {…} } (GET /v1/templates lists the templates).',field:"answers"},400);let g;try{g=f===void 0?n.create(u??{}):n.createFromTemplate({template:f,name:l.value.name??"",vars:l.value.vars??{}})}catch(v){if(K(v))return h(v.toDetail(),400);throw v}try{let v=await e.adopt(g.manifestPath);return y({id:g.agentId,dir:g.dir,files:g.files,adopted:v.map((w)=>w.id)},201)}catch(v){return y({id:g.agentId,dir:g.dir,files:g.files,adopted:[],error:K(v)?v.toDetail():{code:"provision_adopt_failed",message:v instanceof Error?v.message:String(v),hint:"The agent was written and is not running. Fix what the message names and `start` it, or restart the host."}},201)}},{capability:"admin"}),m.add("GET","/v1/templates",()=>y({templates:t.provision?.templates()??[]}),{capability:"read"}),m.add("GET","/v1/agents/:id/secrets",async(r)=>{let n=Pe(e,t,r);if(n.kind==="response")return n.response;return y({id:n.id,secrets:n.admin.status(n.manifestPath)})},{capability:"admin"}),m.add("PUT","/v1/agents/:id/secrets",async(r)=>{let n=Pe(e,t,r);if(n.kind==="response")return n.response;let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let l=B(dt,a.value);if(!l.ok)return h(l.error,400);let u;try{u=n.admin.write(n.manifestPath,l.value.values)}catch(w){if(K(w))return h(w.toDetail(),400);throw w}let f={id:n.id,written:u.written,shadowed:u.shadowed},g=e.list().some((w)=>w.id===n.id),v=await e.store.agentState.get(n.id);if(!g&&v?.enabled===!1)return y({...f,applied:"none",adopted:[],stopped:!0});try{if(g){let O=await e.reload(n.id);if(O.status==="pending")return y({...f,applied:"pending",adopted:[]});return y({...f,applied:"reloaded",adopted:O.adopted.map((R)=>R.id)})}let w=await e.adopt(n.manifestPath);return y({...f,applied:"adopted",adopted:w.map((O)=>O.id)})}catch(w){return y({...f,applied:"none",adopted:[],error:K(w)?w.toDetail():{code:"secrets_apply_failed",message:w instanceof Error?w.message:String(w),hint:"The values were written and the agent is not running on them yet. Fix what the message names and reload or start it."}})}},{capability:"admin"}),m.add("POST","/v1/agents/:id/stop",async(r)=>{let n=r.params.id??"";if(!V(r.principal,n))return H("agent",n);let a=e.list().some((w)=>w.id===n),l=await e.store.agentState.get(n);if(!a&&l===void 0)return H("agent",n);let u=await M(r.request);if(u.kind==="error")return h(u.error,400);let f=B(We,u.value);if(!f.ok)return h(f.error,400);let g=f.value.reason?.trim(),v=await e.store.agentState.disable(n,new Date(t.now?.()??Date.now()).toISOString(),g===void 0||g===""?void 0:g);if(a)try{await e.dispose(n,"stopped")}catch(w){if(K(w)&&w.code==="agent_turn_in_flight")return h(w.toDetail(),409);throw w}return y({id:n,status:"disabled",...ye(v)})},{capability:"admin"}),m.add("POST","/v1/agents/:id/start",async(r)=>{let n=r.params.id??"";if(!V(r.principal,n))return H("agent",n);if(e.list().some((f)=>f.id===n)){let f=await e.store.agentState.enable(n);return y({id:n,status:"loaded",...ye(f)})}let a=t.resolveAgent;if(a===void 0)return h({code:"start_not_supported",message:"This server cannot look up a manifest for an agent it is not hosting.",hint:"Starting a stopped agent needs its manifest, which lives wherever agents live — the sandbox for the CLI, a mounted path for a container. This process was built without that lookup, so pass the agent to `serve` and restart it instead."},501);let l=a(n);if(l===void 0)return H("agent",n);let u=await e.store.agentState.enable(n);try{let f=await e.adopt(l);return y({id:n,status:"loaded",...ye(u),adopted:f.map((g)=>g.id)})}catch(f){if(await e.store.agentState.disable(n,new Date(t.now?.()??Date.now()).toISOString(),"start failed"),K(f))return h(f.toDetail(),400);throw f}},{capability:"admin"}),m.add("POST","/v1/agents/:id/messages",async(r)=>C(e,r,async(n)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let l=B(Be,a.value);if(!l.ok)return h(l.error,400);let u=l.value,f=u.chunks===!0,g=u.text,v=u.sessionKey??"api:default",w=ae(r,v);if(w!==void 0)return w;let O=cn(u.deliver);if(O.kind==="error")return h(O.error,400);let R=sn(u.from);if(R.kind==="error")return h(R.error,400);let q=pt(r.principal,R.from);if(!q.ok)return h(q.error,403);let Y=ln(r.request);if(Y.kind==="error")return h(Y.error,400);let X=await n.admit();if(!X.ok)return h(X.error.toDetail(),429);let Z=Zn();if(Y.key!==void 0){let ee=await n.store.turns.claimInboundKey({agentId:n.id,key:Y.key,turnId:Z,inputHash:await un(v,g),now:new Date});if(ee.kind!=="claimed")X.release();if(ee.kind==="replay")return y({turnId:ee.turnId,sessionKey:v,replayed:!0},200);if(ee.kind==="mismatch")return h({code:"idempotency_key_reused",message:`Idempotency-Key "${Y.key}" was already used for a different message.`,hint:`It belongs to turn ${ee.turnId}, whose text or session differed from this request's. Nothing was run. Use a fresh key for a new message, or resend the original text byte for byte to get that turn back. A key is remembered for 24 hours.`,field:"Idempotency-Key"},409)}let be=new AbortController;p.set(Z,be),e.streams.open(Z,{chunks:f});let pn=n.send(g,{admission:X,sessionKey:v,turnId:Z,source:"api",...q.from===void 0?{}:{from:q.from},signal:be.signal}).then(async(ee)=>{let ce=ee.attachments??[];if(O.target===void 0||ee.text.trim()===""&&ce.length===0)return;await e.channels.deliver({agentId:n.id,sessionKey:v,channelId:O.target.channel,recipient:O.target.to,turnId:Z,text:ee.text,...ce.length===0?{}:{attachments:ce}})}).catch(()=>{}).finally(()=>{p.delete(Z)});if(u.stream!==!0)return y({turnId:Z,sessionKey:v},202);return Me(e,Z,{accepted:{turnId:Z,sessionKey:v},status:202,chunks:f})}),{capability:"chat"}),m.add("GET","/v1/agents/:id/turns/:turnId/stream",(r)=>C(e,r,async(n)=>{let a=r.params.turnId??"";if(e.streams.state(a)===void 0){let l=await n.store.turns.get(a);if(l===void 0)return H("turn",a,"No turn with this id has ever run on this agent. A turn id is the `turnId` from POST /v1/agents/:id/messages — check the agent in the path too, since a turn belongs to one.");return dn(l)}return Me(e,a,{chunks:r.url.searchParams.get("chunks")==="true"})}),{capability:"read",streaming:!0}),m.add("POST","/v1/agents/:id/turns/:turnId/stop",(r)=>C(e,r,()=>{let n=r.params.turnId??"",a=p.get(n);if(a===void 0)return h({code:"turn_not_running",message:`No cancel handle for turn ${n} on this API.`,hint:"This surface can stop a turn it started. A turn that has already finished cannot be stopped at all — read its final state from GET /v1/agents/:id/turns/:turnId. A turn started by a channel, a schedule, or another process is running without a handle here."},409);return a.abort(),y({turnId:n,stopping:!0},202)}),{capability:"chat"}),m.add("GET","/v1/agents/:id/approvals",(r)=>C(e,r,async(n)=>y({approvals:b.pending(n.id)})),{capability:"read"}),m.add("POST","/v1/agents/:id/approvals/:approvalId",(r)=>C(e,r,async()=>{let n=await M(r.request);if(n.kind==="error")return h(n.error,400);let a=B(Fe,n.value);if(!a.ok)return h(a.error,400);let l=a.value,u=r.params.approvalId??"";if(!b.resolve(u,l.granted))return h({code:"approval_not_found",message:`No approval with id ${u} is waiting.`,hint:'It was answered already, or its turn ended while it waited — a stopped or timed-out turn abandons its question, and `approval.resolved` reports that as `by: "abandoned"`. GET /v1/agents/:id/approvals lists what is actually waiting. Nothing about a settled approval is kept, so this is also the answer for an id that was never real.'},404);return y({approvalId:u,granted:l.granted})}),{capability:"chat"}),m.add("GET","/",(r)=>ge("/",r),{capability:"open"}),m.add("GET","/assets/app.js",(r)=>ge("/assets/app.js",r),{capability:"open"}),m.add("GET","/assets/app.css",(r)=>ge("/assets/app.css",r),{capability:"open"}),m.add("POST","/v1/keys",async(r)=>{let n=t.claim!==void 0&&rn(r.request)===t.claim.token,a=await M(r.request);if(a.kind==="error")return h(a.error,400);let l=B(He,a.value);if(!l.ok)return h(l.error,400);let u=l.value,f=ts(u.label);if(f!==void 0)return h({code:"key_label_invalid",message:f,hint:`A label is shown in a listing and in the UI, so it is at most ${lr} printable characters on one line. It is a display name, not a description.`,field:"label"},400);if(n&&t.claim?.spend()!==!0)return De();let g=u.scope;if(g?.agents!==void 0){let q=new Set(e.list().map((X)=>X.id));for(let X of await e.store.agentState.list())q.add(X.agentId);let Y=g.agents.filter((X)=>!q.has(X));if(Y.length>0)return h({code:"key_scope_agent_unknown",message:`No agent ${Y.map((X)=>JSON.stringify(X)).join(", ")} on this server.`,hint:"A key scoped to an agent that does not exist authenticates and then reaches nothing, which looks exactly like a working credential until it is used. GET /v1/agents lists what this server holds, stopped agents included.",field:"scope.agents"},400)}let v=g?.expiresIn===void 0?void 0:new Date(d()+g.expiresIn*1000).toISOString(),w=g===void 0?void 0:{...g.agents===void 0?{}:{agents:g.agents},...g.sessions===void 0?{}:{sessions:g.sessions},...g.can===void 0?{}:{can:g.can},...g.participant===void 0?{}:{participant:g.participant}},O=gr(),R=await e.store.operatorKeys.issue({keyId:os(d()),label:u.label.trim(),fingerprint:await cr(O),createdAt:new Date(d()).toISOString(),...w===void 0||Object.keys(w).length===0?{}:{scope:w},...v===void 0?{}:{expiresAt:v}});return y({...R,secret:O},201)},{capability:"admin"}),m.add("GET","/v1/keys",async()=>{let r=await e.store.operatorKeys.list();return y({keys:r,scope:"A key with no scope authenticates every route for every agent this server holds. A scope narrows an already-authenticated caller — it names agents, a session prefix and capabilities, and it is not an identity: there are no users, teams or roles here."})},{capability:"admin"}),m.add("DELETE","/v1/keys/:keyId",async(r)=>{let n=r.params.keyId??"",a=await e.store.operatorKeys.revoke(n,new Date(d()).toISOString());if(a===void 0)return H("key",n,"The id is the `keyId` from POST /v1/keys, not the secret — GET /v1/keys lists them. An already-revoked key is a 200 carrying its original stamp, so this really does mean no such key exists.");return y(a)},{capability:"admin"}),m.add("POST","/v1/webhooks",async(r)=>{let n=await M(r.request);if(n.kind==="error")return h(n.error,400);let a=B(ct,n.value);if(!a.ok)return h(a.error,400);let l=a.value,u=l.types.filter((R)=>!FA.includes(R)||!Es(R));if(u.length>0)return h({code:"webhook_type_invalid",message:`Cannot deliver ${u.join(", ")}.`,hint:"Any type from the event stream except model.chunk, which is one request per token. The wire spec's event table lists them.",field:"types"},400);let f=ie(r.principal);if(l.agents!==void 0){let R=new Set([...e.list().map((Y)=>Y.id),...(await e.store.agentState.list()).map((Y)=>Y.agentId)]),q=l.agents.filter((Y)=>!V(r.principal,Y)||!R.has(Y));if(q.length>0)return h({code:"webhook_scope_invalid",message:`This credential cannot subscribe to ${q.join(", ")}.`,hint:"A subscription hears at most what the key creating it reaches, and only agents this server holds. GET /v1/agents lists them.",field:"agents"},400)}let g=l.agents??f.agentIds,v={...g===void 0?{}:{agents:[...g]},...f.sessionPrefix===void 0?{}:{sessionPrefix:f.sessionPrefix}};try{await e.webhooks.check(l.url)}catch(R){if(K(R))return h(R.toDetail(),400);throw R}let w=ds(),O=await e.store.webhooks.create({subscriptionId:`wh_${crypto.randomUUID().replaceAll("-","").slice(0,20)}`,url:l.url,secret:w,types:[...new Set(l.types)],...Object.keys(v).length===0?{}:{scope:v},createdAt:new Date(t.now?.()??Date.now()).toISOString()});return await e.webhooks.changed(),y({...Ie(O),secret:w},201)},{capability:"admin"}),m.add("GET","/v1/webhooks",async(r)=>{let n=await e.store.webhooks.list();return y({webhooks:n.filter((a)=>ze(r.principal,a)).map(Ie)})},{capability:"admin"}),m.add("DELETE","/v1/webhooks/:webhookId",async(r)=>{let n=r.params.webhookId??"",a=await e.store.webhooks.get(n);if(a===void 0||!ze(r.principal,a))return h({code:"webhook_not_found",message:`No webhook with id "${n}".`,hint:"GET /v1/webhooks lists the subscriptions this credential can see."},404);return await e.store.webhooks.delete(n),await e.webhooks.changed(),y({id:n,deleted:!0})},{capability:"admin"});let _=(r)=>r.kind==="key"?r.scope?.participant:void 0,D=(r,n)=>{let a=_(r);if(a!==void 0&&!n.members.includes(a))return!1;return n.members.every((l)=>{let u=Gr(l);return u===void 0||V(r,u)})},J=(r)=>h({code:"conversation_not_found",message:`No conversation "${r}".`,hint:"GET /v1/conversations lists the ones this credential can see."},404),F=async(r,n)=>{let a=r.params.conversationId??"",l=await e.store.conversations.get(a);if(l===void 0||!D(r.principal,l))return J(a);return n(l)},E=(r)=>{if(!K(r))throw r;return h(r.toDetail(),r.code.endsWith("_not_found")?404:r.code.endsWith("_forbidden")?403:400)};m.add("POST","/v1/participants",async(r)=>{let n=await M(r.request);if(n.kind==="error")return h(n.error,400);let a=B(Ye,n.value);if(!a.ok)return h(a.error,400);try{let l=a.value;return y(await e.conversations.registerParticipant({id:l.id,...l.name===void 0?{}:{name:l.name},...l.role===void 0?{}:{role:l.role}}),201)}catch(l){return E(l)}},{capability:"admin"}),m.add("GET","/v1/participants",async()=>y({participants:await e.store.conversations.participants()}),{capability:"read"}),m.add("DELETE","/v1/participants/:participantId",async(r)=>{let n=r.params.participantId??"";if(!await e.store.conversations.deleteParticipant(n))return h({code:"participant_not_found",message:`No participant "${n}".`,hint:"GET /v1/participants lists them."},404);return y({id:n,deleted:!0})},{capability:"admin"}),m.add("POST","/v1/conversations",async(r)=>{let n=await M(r.request);if(n.kind==="error")return h(n.error,400);let a=B(Xe,n.value);if(!a.ok)return h(a.error,400);let l=_(r.principal);if(l!==void 0&&!a.value.members.includes(l))return h({code:"conversation_creator_not_member",message:`This key speaks for ${l}, who is not among the members.`,hint:`Include "${l}" in members. A backend creating rooms for others needs a key minted without scope.participant.`,field:"members"},403);let u=a.value.members.map((f)=>Gr(f)).filter((f)=>f!==void 0&&!V(r.principal,f));if(u.length>0)return h({code:"conversation_member_unknown",message:`No participant "agent:${u[0]}".`,hint:"That agent is not hosted here. GET /v1/agents lists the ones that are.",field:"members"},400);try{return y(await e.conversations.create({kind:a.value.kind,members:a.value.members,...a.value.title===void 0?{}:{title:a.value.title}}),201)}catch(f){return E(f)}},{capability:"admin"}),m.add("GET","/v1/conversations",async(r)=>{let n=await e.store.conversations.list();return y({conversations:n.filter((a)=>D(r.principal,a))})},{capability:"read"}),m.add("GET","/v1/conversations/:conversationId",(r)=>F(r,async(n)=>y(n)),{capability:"read"}),m.add("PATCH","/v1/conversations/:conversationId/members",(r)=>F(r,async(n)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let l=B(Ze,a.value);if(!l.ok)return h(l.error,400);try{return y(await e.conversations.setMembers(n.id,l.value.add??[],l.value.remove??[]))}catch(u){return E(u)}}),{capability:"admin"}),m.add("POST","/v1/conversations/:conversationId/messages",(r)=>F(r,async(n)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let l=B(nt,a.value);if(!l.ok)return h(l.error,400);let u=_(r.principal),f=l.value.authorId;if(u!==void 0&&f!==void 0&&f!==u)return h({code:"sender_not_bound_participant",message:`This key speaks for ${u}, and the message names ${f}.`,hint:`Omit authorId (it is filled in), or send "${u}". A backend that posts for others needs a key minted without scope.participant.`,field:"authorId"},403);let g=u??f;if(g===void 0)return h({code:"conversation_author_required",message:"A message needs an author.",hint:"Send authorId, the human member who said it. A key bound to a participant fills it in.",field:"authorId"},400);try{let v=await e.conversations.post({conversationId:n.id,authorId:g,text:l.value.text,...l.value.mentions===void 0?{}:{mentions:l.value.mentions}});return y(v,202)}catch(v){return E(v)}}),{capability:"chat"}),m.add("GET","/v1/conversations/:conversationId/messages",(r)=>F(r,async(n)=>{let a=Number(r.url.searchParams.get("after")??0),l=Number(r.url.searchParams.get("limit")??200),u=await e.store.conversations.messages(n.id,{after:Number.isFinite(a)&&a>0?a:0,limit:Number.isFinite(l)&&l>0?Math.min(l,500):200});return y({conversationId:n.id,messages:u,...u.length===0?{}:{nextAfter:u.at(-1)?.seq}})}),{capability:"read"}),m.add("PUT","/v1/participants/:participantId/presence",async(r)=>{let n=r.params.participantId??"",a=_(r.principal);if(a!==void 0&&a!==n)return h({code:"sender_not_bound_participant",message:`This key speaks for ${a}, and the presence names ${n}.`,hint:"A key bound to a participant sets only that participant's presence. The embedder's backend, holding an unbound key, sets anyone's."},403);let l=await M(r.request);if(l.kind==="error")return h(l.error,400);let u=B(at,l.value);if(!u.ok)return h(u.error,400);try{return y(await e.conversations.setPresence(n,u.value.presence))}catch(f){return E(f)}},{capability:"chat"}),m.add("GET","/v1/actions",async(r)=>{let n=r.url.searchParams.get("status"),a=_(r.principal),l=await e.store.conversations.actions({...a===void 0?{}:{ownerId:a},...n==="pending"||n==="done"||n==="failed"||n==="denied"?{status:n}:{}});return y({actions:l.filter((u)=>V(r.principal,u.agentId))})},{capability:"read"}),m.add("POST","/v1/actions/:actionId",async(r)=>{let n=r.params.actionId??"",a=await e.store.conversations.action(n),l=_(r.principal);if(a===void 0||!V(r.principal,a.agentId)||l!==void 0&&l!==a.ownerId)return h({code:"action_not_found",message:`No action "${n}".`,hint:"GET /v1/actions lists the ones waiting on you."},404);let u=await M(r.request);if(u.kind==="error")return h(u.error,400);let f=B(ut,u.value);if(!f.ok)return h(f.error,400);try{return y(await e.conversations.decideAction(n,f.value.approve))}catch(g){if(K(g)&&g.code==="action_already_decided")return h(g.toDetail(),409);return E(g)}},{capability:"chat"}),m.add("PUT","/v1/agents/:id/assignee",(r)=>C(e,r,async(n)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let l=B(rt,a.value);if(!l.ok)return h(l.error,400);let u=_(r.principal);if(u!==void 0){if((await e.store.conversations.participant(u))?.role!=="admin")return h({code:"assignment_requires_admin",message:`${u} is not an admin participant.`,hint:'Only a participant registered with role "admin" assigns agents to members.'},403)}try{return y(await e.conversations.assign({agentId:n.id,participantId:l.value.participantId,...u===void 0?{}:{assignedBy:u}}))}catch(f){return E(f)}}),{capability:"admin"}),m.add("DELETE","/v1/agents/:id/assignee",(r)=>C(e,r,async(n)=>y({id:n.id,unassigned:await e.store.conversations.unassign(n.id)})),{capability:"admin"});let z=(r)=>{let n=_(r);if(n!==void 0||he(r,"admin"))return{ok:!0,actor:n};return{ok:!1,response:h({code:"memory_write_requires_admin",message:"This key is bound to no participant and does not carry admin.",hint:"A member writes through a key minted with scope.participant; the embedder's backend writes shared scopes with an admin key."},403)}};m.add("POST","/v1/memory/notes",async(r)=>{let n=await M(r.request);if(n.kind==="error")return h(n.error,400);let a=B(it,n.value);if(!a.ok)return h(a.error,400);let l=z(r.principal);if(!l.ok)return l.response;try{return y(await e.conversations.addNote({scope:a.value.scope,text:a.value.text,...l.actor===void 0?{}:{authorId:l.actor}}),201)}catch(u){return E(u)}},{capability:"chat"}),m.add("GET","/v1/memory/notes",async(r)=>{let n=r.url.searchParams.get("scope")??"";try{return y({notes:await e.conversations.notes(n,_(r.principal))})}catch(a){return E(a)}},{capability:"read"}),m.add("DELETE","/v1/memory/notes/:noteId",async(r)=>{let n=z(r.principal);if(!n.ok)return n.response;try{return await e.conversations.deleteNote(r.params.noteId??"",n.actor),y({id:r.params.noteId,deleted:!0})}catch(a){return E(a)}},{capability:"chat"}),m.add("GET","/v1/participants/:participantId/memory/reads",async(r)=>{try{return y({reads:await e.conversations.reads(r.params.participantId??"",_(r.principal))})}catch(n){return E(n)}},{capability:"read"});let L=async(r)=>{let n=_(r);if(n===void 0)return;if((await e.store.conversations.participant(n))?.role==="admin")return;return h({code:"memory_scope_forbidden",message:`${n} is not an admin participant.`,hint:'Only a participant registered with role "admin" defines projects and names the space writer.'},403)};m.add("GET","/v1/projects",async()=>y({projects:await e.store.conversations.projects()}),{capability:"read"}),m.add("PUT","/v1/projects/:projectId",async(r)=>{let n=await M(r.request);if(n.kind==="error")return h(n.error,400);let a=B(ot,n.value);if(!a.ok)return h(a.error,400);let l=await L(r.principal);if(l!==void 0)return l;let u=(a.value.agents??[]).find((f)=>!V(r.principal,f));if(u!==void 0)return h({code:"agent_not_found",message:`No agent "${u}".`,hint:"GET /v1/agents lists the ones hosted here."},404);try{return y(await e.conversations.upsertProject({id:r.params.projectId??"",...a.value.name===void 0?{}:{name:a.value.name},...a.value.agents===void 0?{}:{agents:a.value.agents}}))}catch(f){return E(f)}},{capability:"admin"}),m.add("DELETE","/v1/projects/:projectId",async(r)=>{let n=await L(r.principal);if(n!==void 0)return n;let a=r.params.projectId??"";return y({id:a,deleted:await e.store.conversations.deleteProject(a)})},{capability:"admin"}),m.add("PUT","/v1/memory/space/writer",async(r)=>{let n=await M(r.request);if(n.kind==="error")return h(n.error,400);let a=B(st,n.value);if(!a.ok)return h(a.error,400);let l=await L(r.principal);if(l!==void 0)return l;let u=_(r.principal);try{return await e.conversations.setSpaceWriter(a.value.writer,u),y({writer:a.value.writer})}catch(f){return E(f)}},{capability:"admin"}),m.add("GET","/v1/usage",async(r)=>{let n=Re(r.url);if(n.kind==="error")return h(n.error,400);let a=ie(r.principal);return y(await e.store.usage.report({...n.value,...a}))},{capability:"read"}),m.add("GET","/v1/agents/:id/usage",(r)=>C(e,r,async(n)=>{let a=Re(r.url);if(a.kind==="error")return h(a.error,400);let l=ie(r.principal).sessionPrefix;return y({id:n.id,...await e.store.usage.report({...a.value,agentIds:[n.id],...l===void 0?{}:{sessionPrefix:l}})})}),{capability:"read"}),m.add("GET","/v1/agents/:id/turns",(r)=>C(e,r,async(n)=>{let a=Oe(r.url,"limit"),l=Oe(r.url,"before");if(a===null||l===null)return h({code:"turns_page_invalid",message:"`limit` and `before` must be positive whole numbers.",hint:"Pass `before` exactly as the previous page's `nextBefore` returned it, and a `limit` up to 200."},400);let u=ie(r.principal).sessionPrefix,f=await e.store.turns.listForAgent(n.id,{limit:Math.min(a??50,200),...l===void 0?{}:{before:l},...u===void 0?{}:{sessionPrefix:u}});return y({id:n.id,...f})}),{capability:"read"}),m.add("GET","/v1/agents/:id/turns/:turnId",(r)=>C(e,r,async(n)=>{let a=await n.store.turns.get(r.params.turnId??"");if(a===void 0)return H("turn",r.params.turnId??"");return y(a)}),{capability:"read"}),m.add("GET","/v1/agents/:id/sessions",(r)=>C(e,r,async(n)=>y(on(r.principal,await n.store.sessions.list(n.id)))),{capability:"read"}),m.add("GET","/v1/agents/:id/sessions/:key",(r)=>C(e,r,async(n)=>{let a=r.params.key??"",l=ae(r,a);if(l!==void 0)return l;let u=await n.store.sessions.get(n.id,a);if(u===void 0)return H("session",a);return y(u)}),{capability:"read"}),m.add("GET","/v1/agents/:id/sessions/:key/messages",(r)=>C(e,r,async(n)=>{let a=r.url.searchParams.get("before"),l=r.url.searchParams.get("limit"),u=ae(r,r.params.key??"");if(u!==void 0)return u;let f=await n.store.messages.page(n.id,r.params.key??"",{...a===null?{}:{before:Number.parseInt(a,10)},...l===null?{}:{limit:Number.parseInt(l,10)}});return y(f)}),{capability:"read"}),m.add("DELETE","/v1/agents/:id/sessions/:key",(r)=>C(e,r,async(n)=>{let a=ae(r,r.params.key??"");if(a!==void 0)return a;return await n.store.sessions.clear(n.id,r.params.key??""),y({cleared:r.params.key??"",memoryFilesKept:!0})}),{capability:"write"}),m.add("POST","/v1/agents/:id/sessions/:key/phase",(r)=>C(e,r,async(n)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let l=B(Ke,a.value);if(!l.ok)return h(l.error,400);let u=l.value.phase;if(typeof u!=="string"&&u!==null)return h({code:"phase_invalid",message:"phase must be a string, or null to clear it.",hint:'Send { "phase": "triage" }. Phase-scoped tool visibility arrives in Phase 7; the column is written now so a session carries the value across a restart.',field:"phase"},400);let f=ae(r,r.params.key??"");if(f!==void 0)return f;return await n.store.sessions.setPhase(n.id,r.params.key??"",u===null?void 0:u),y({phase:u})}),{capability:"write"}),m.add("GET","/v1/agents/:id/schedules",(r)=>C(e,r,async(n)=>{let a=r.url.searchParams.get("enabled"),l=await n.store.schedules.list(n.id,a===null?{}:{enabled:a==="true"});return y({schedules:l})}),{capability:"read"}),m.add("POST","/v1/agents/:id/schedules",(r)=>C(e,r,async(n)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);return Ne(e,n,a.value,void 0)}),{capability:"write"}),m.add("GET","/v1/agents/:id/schedules/:sid",(r)=>C(e,r,async(n)=>{let a=r.params.sid??"",l=await n.store.schedules.get(n.id,a);return l===void 0?H("schedule",a):y(l)}),{capability:"read"}),m.add("PATCH","/v1/agents/:id/schedules/:sid",(r)=>C(e,r,async(n)=>{let a=r.params.sid??"",l=await n.store.schedules.get(n.id,a);if(l===void 0)return H("schedule",a);let u=Ce(l);if(u!==void 0)return u;let f=await M(r.request);if(f.kind==="error")return h(f.error,400);let g=f.value===null||typeof f.value!=="object"||Array.isArray(f.value)?{}:f.value,{id:v,...w}=g,O={kind:l.kind,expr:l.expr,task:l.task,deliver:l.deliverChannel===void 0||l.deliverTo===void 0?"none":{channel:l.deliverChannel,to:l.deliverTo},session:l.sessionMode,enabled:l.enabled,...l.timezone===void 0?{}:{timezone:l.timezone},...l.role===void 0?{}:{role:l.role},...w,id:l.id};return Ne(e,n,O,l)}),{capability:"write"}),m.add("DELETE","/v1/agents/:id/schedules/:sid",(r)=>C(e,r,async(n)=>{let a=r.params.sid??"",l=await n.store.schedules.get(n.id,a);if(l===void 0)return H("schedule",a);let u=Ce(l);if(u!==void 0)return u;if(!await n.store.schedules.remove(n.id,a))return H("schedule",a);return e.scheduler.changed(),y({removed:a})}),{capability:"write"}),m.add("POST","/v1/agents/:id/schedules/:sid/run",(r)=>C(e,r,async(n)=>{let a=r.params.sid??"",l=await n.store.schedules.get(n.id,a);if(l===void 0)return H("schedule",a);let u=await n.admit();if(!u.ok)return h(u.error.toDetail(),429);let f=ns(),g=Cs(l.sessionMode,l.id,f),v=Zn();return e.streams.open(v),n.send(l.task,{admission:u,sessionKey:g,turnId:v,source:`schedule:${l.id}:manual`,...l.role===void 0?{}:{role:l.role}}).catch(()=>{}),y({scheduleId:l.id,turnId:v,sessionKey:g,outOfBand:!0},202)}),{capability:"write"}),m.add("GET","/v1/agents/:id/config",(r)=>C(e,r,async(n)=>{let a=e.sourceOf(n.id),l=typeof a==="string"?a:void 0,u=l===void 0?void 0:await kt(l,"utf8");return y({...l===void 0?{editable:!1}:{editable:!0,file:l},settings:tt.filter((f)=>eo.includes(f.path)).map((f)=>({path:f.path,means:f.means,...f.confirm===void 0?{}:{confirm:f.confirm},...u===void 0?{}:{value:gs(u,f.path.split("."))}}))})}),{capability:"admin"}),m.add("PATCH","/v1/agents/:id/config",(r)=>C(e,r,async(n)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let l=B(Pt,a.value);if(!l.ok)return h(l.error,400);let u=e.sourceOf(n.id);if(typeof u!=="string")return h({code:"config_not_editable",message:`"${n.id}" was loaded from an object, not from a file, so it has no manifest to change.`,hint:"An embedder holding new settings passes the new object to dispose() and adopt(). This route edits a manifest on disk."},409);let f=cs(l.value.path);if(f===void 0||!eo.includes(f.path))return h({code:"config_path_unknown",message:f?.via===void 0?`"${l.value.path}" is not a field this surface sets.`:`"${l.value.path}" is set by \`${f.via}\`, not by a dotted path.`,hint:f?.via===void 0?`GET /v1/agents/:id/config lists every one. Nearest: ${_t(l.value.path,eo)??eo.join(", ")}.`:"It is a key inside a list entry, and the source editor matches a key at an indent — it cannot index a sequence. That action also validates the handle against the service that issues it.",field:"path"},400);if(f.confirm!==void 0&&l.value.confirm!==!0)return h({code:"config_confirm_required",message:f.confirm,hint:'Send { "confirm": true } beside the value to make this change anyway. Nothing has been written.',field:"confirm"},409);let g;try{g=await Xn({file:u,path:f.path.split("."),value:$n(l.value.value),providers:e.toolProviderFactories,mediaProviders:e.mediaProviderFactories})}catch(w){if(K(w))return h(w.toDetail(),400);throw w}let v;try{v=$e(await e.reload(n.id))}catch(w){if(!K(w))throw w;v=w.toDetail()}return y({path:f.path,before:g.before,after:g.after,reflowed:g.reflowed,...v===void 0?{applied:!0}:{applied:!1,pending:v}})}),{capability:"admin"}),m.add("PATCH","/v1/agents/:id/channels/:channelId",(r)=>C(e,r,async(n)=>{let a=t.channels;if(a===void 0)return h({code:"channels_not_supported",message:"This server cannot change a channel.",hint:"The host did not supply the channel actions — a library caller embedding this handler has to pass them. `dispach serve` does."},501);let l=e.sourceOf(n.id);if(typeof l!=="string")return h({code:"config_not_editable",message:`Agent "${n.id}" was loaded from an object, so it has no manifest to edit.`,hint:"Only an agent loaded from a file can be changed here."},409);let u=await M(r.request);if(u.kind==="error")return h(u.error,400);let f=B(It,u.value);if(!f.ok)return h(f.error,400);let{enabled:g,credential:v}=f.value;if(g===void 0&&v===void 0)return h({code:"channel_patch_empty",message:"Nothing to change.",hint:'Send { "enabled": true | false } to connect or disconnect it, { "credential": "…" } to set its token, or both.'},400);let w=r.params.channelId??"",O=[];try{if(v!==void 0)O.push(a.setCredential(l,w,v).note);if(g!==void 0)O.push((await a.setEnabled(l,w,g)).note)}catch(q){if(!K(q))throw q;return h(q.toDetail(),400)}let R;try{R=$e(await e.reload(n.id))}catch(q){if(!K(q))throw q;R=q.toDetail()}return y({channelId:w,notes:O,...R===void 0?{applied:!0}:{applied:!1,pending:R}})}),{capability:"admin"}),m.add("POST","/v1/agents/:id/channels/:channelId/unpair",(r)=>C(e,r,async(n)=>{let a=r.params.channelId??"",l=await e.channels.reset(n.id,a);if(l==="reset")return y({channelId:a,note:"Pairing forgotten. The channel offers a new code to scan; the old device may still be listed on the phone, which is the only place it can be removed.",restarted:!1});let u=t.channels,f=e.sourceOf(n.id);if(u===void 0||typeof f!=="string")return h({code:l==="unsupported"?"channel_has_no_pairing":"channel_unknown",message:l==="unsupported"?`Channel "${a}" stores no pairing.`:`Agent "${n.id}" has no channel "${a}" registered.`,hint:"Only a channel linked by scanning a code has one to forget. A credential somebody typed is changed with PATCH on this channel, and a channel is switched off with { enabled: false }.",field:"channelId"},l==="unsupported"?409:404);try{return y({channelId:a,...u.unpair(f,a),restarted:!1})}catch(g){if(!K(g))throw g;return h(g.toDetail(),g.code==="channel_unknown"?404:409)}}),{capability:"admin"}),m.add("GET","/v1/agents/:id/tools",(r)=>C(e,r,(n)=>{let a=n.manifest.phases,l=Pr(a);return y(n.tools.specs().map((u)=>({slug:u.slug,summary:u.summary,mutating:u.mutating,trust:u.trust,...u.trustReason===void 0?{}:{trustReason:u.trustReason},provider:u.provider??"local",tags:u.tags,...l?{phases:is(a,u)}:{}})))}),{capability:"read"}),m.add("GET","/v1/agents/:id/skills",(r)=>C(e,r,(n)=>{let a=n.skills;if(a===void 0)return y({skills:[],configured:!1});return y({configured:!0,maxActive:a.maxActive,threshold:a.threshold,cached:a.cached,skills:a.skills.map((l)=>({name:l.name,description:l.frontmatter.description,tokens:l.tokens,...l.frontmatter.whenNotToUse===void 0?{}:{whenNotToUse:l.frontmatter.whenNotToUse},scripts:l.scripts.map((u)=>u.slug)}))})}),{capability:"read"}),m.add("GET","/v1/agents/:id/context",(r)=>C(e,r,async(n)=>{let a=r.url.searchParams.get("sessionKey"),l=r.url.searchParams.get("input");return y(await n.previewContext({...a===null?{}:{sessionKey:a},...l===null?{}:{input:l}}))}),{capability:"read"}),m.add("POST","/v1/channels/:channelId/webhook/:agentId",async(r)=>{let n=await M(r.request);if(n.kind==="error")return h(n.error,400);let a={};r.request.headers.forEach((u,f)=>{a[f.toLowerCase()]=u});let l=await e.channels.handleWebhook(r.params.agentId??"",r.params.channelId??"",{body:n.value,headers:a});return new Response(l.detail??"",{status:l.status,headers:{"content-type":"text/plain; charset=utf-8"}})},{capability:"open"}),m.add("GET","/v1/events",(r)=>{let n=r.url.searchParams.get("agentId");if(n!==null&&!V(r.principal,n))return H("agent",n);let a=r.url.searchParams.get("types")?.split(",").filter(Boolean),l=r.url.searchParams.get("chunks")==="true",u=a?.includes("model.chunk")===!0,f=l||u,g=a?.filter((v)=>!FA.includes(v));if(g!==void 0&&g.length>0){let v=_t(g[0]??"",FA);return h({code:"unknown_event_type",message:`No such event type: ${g.join(", ")}.`,hint:v===void 0?"The full catalogue is the event table in docs/04-SPEC-WIRE.md. Omit ?types= to receive every event.":`Did you mean "${v}"? The full catalogue is the event table in docs/04-SPEC-WIRE.md.`,field:"types"},400)}return ve({...r.request.signal===void 0?{}:{signal:r.request.signal},start:({send:v})=>(v({event:"stream.subscribed",data:{agentId:n??null,types:a??null,chunks:f,...f&&!l?{implied:"types names model.chunk"}:{}}}),e.bus.on("*",(w)=>{if(n!==null&&w.agentId!==n)return;if(w.agentId!==void 0&&!V(r.principal,w.agentId))return;if(w.sessionKey!==void 0&&!ue(r.principal,w.sessionKey))return;if(a!==void 0&&a.length>0&&!a.includes(w.type))return;v({event:w.type,data:w})},{chunks:f}))})},{capability:"read",streaming:!0});let te=async(r)=>{let n;try{n=new URL(r.url)}catch{return h({code:"bad_request_url",message:"The request URL could not be parsed.",hint:"This usually means the server was handed a relative URL. A handler mounted inside another framework needs an absolute request.url."},400)}let a=r.method.toUpperCase();if(a==="OPTIONS"){let v=m.match("OPTIONS",n.pathname);if(v.kind==="method"){let O=m.match("HEAD",n.pathname).kind==="method"&&nn(m,n.pathname),R=[...v.allowed,...v.allowed.includes("GET")&&!O?["HEAD"]:[],"OPTIONS"];return k(r,new Response(null,{status:204,headers:{allow:R.join(", "),...t.origin===void 0?{}:Bt(r,R)}}))}}if(a==="HEAD"){let v=m.match("GET",n.pathname);if(v.kind==="found"){if(v.streaming)return h({code:"method_not_allowed",message:`HEAD is not allowed on ${n.pathname}.`,hint:"This path answers with an open event stream. A HEAD would have to start one and then throw the body away, leaving a subscription nothing ever closes — so it is refused rather than leaked. Use GET, or GET /v1/health to check the server is up."},405,{allow:"GET, OPTIONS"});let w=j(r);if(w!==void 0)return w;let O=await A(r,n.pathname,v.capability);if(O instanceof Response)return O;let R=await _e(v.handler,{request:r,url:n,params:v.params,principal:O});return k(r,new Response(null,{status:R.status,headers:R.headers}))}}let l=oe(a,n.pathname);if(l!==void 0){let v=j(r);if(v!==void 0)return v;return k(r,await bt(r,n,l))}let u=m.match(a,n.pathname);if(u.kind==="method")return h({code:"method_not_allowed",message:`${a} is not allowed on ${n.pathname}.`,hint:`This path accepts ${u.allowed.join(", ")}.`},405,{allow:u.allowed.join(", ")});if(u.kind==="none")return je(r.method,n.pathname);let f=j(r);if(f!==void 0)return f;let g=await A(r,n.pathname,u.capability);if(g instanceof Response)return g;return k(r,await _e(u.handler,{request:r,url:n,params:u.params,principal:g}))},oe=(r,n)=>{let a=/^\/v1\/agents\/([^/]+)\/plugins\/([^/]+)(\/.*)?$/.exec(n);if(a!==null){let u=e.list().find((w)=>w.id===decodeURIComponent(a[1]??"")),f=a[2]??"",g=a[3]??"/",v=u?.pluginRoutes.find((w)=>w.plugin===f&&w.method===r&&w.path===g);return u===void 0||v===void 0?void 0:{agent:u,route:v,path:g}}let l=e.list().flatMap((u)=>u.pluginRoutes.filter((f)=>f.root===n&&f.method===r).map((f)=>({agent:u,route:f,path:f.path})));return l.length===1?l[0]:void 0},bt=async(r,n,a)=>{let{agent:l,route:u,path:f}=a,g=u.capability==="open"?{kind:"open"}:await A(r,n.pathname,u.capability);if(g instanceof Response)return g;if(g.kind==="claim"||!V(g,l.id))return je(r.method,n.pathname);let v=g.kind==="key"?{kind:"key",keyId:g.keyId,label:g.label??""}:u.capability==="open"?{kind:"anonymous"}:{kind:"operator"};try{return await u.handler({request:r,url:n,path:f,caller:v})}catch(w){return h({code:"plugin_route_failed",message:`Plugin "${u.plugin}" failed answering ${r.method} ${n.pathname}: ${w instanceof Error?w.message:String(w)}`,hint:"This is the plugin's error, not the runtime's. The agent's own routes are unaffected."},500)}};return Object.assign(te,{authenticate:(r)=>A(r,"/v1/ws","read")})}function Ce(t){if(t.origin!=="manifest")return;return h({code:"schedule_manifest_owned",message:`Schedule "${t.id}" is declared in this agent's manifest, so the manifest decides it.`,hint:"Writing it here would last until the next start — reconciliation restores every field from the file, enabled included. Change the `schedules:` entry instead, with PATCH /v1/agents/:id/config, or create a separate schedule through this route."},409)}async function Ne(t,e,s,d){if(s===null||typeof s!=="object"||Array.isArray(s))return h({code:"schedule_invalid",message:"A schedule must be a JSON object.",hint:"Send { id, kind, expr, task, deliver } — see docs/02-SPEC-MANIFEST.md."},400);try{let c=ps({agentId:e.id,body:s,channelIds:e.manifest.channels.map((b)=>b.id),roleNames:Object.keys(e.manifest.model),now:Date.now(),origin:"api",...d===void 0?{}:{existing:d}}),p=await e.store.schedules.upsert(c);return t.scheduler.changed(),y(p,d===void 0?201:200)}catch(c){let p=K(c)?c.toDetail():{code:"schedule_invalid",message:c instanceof Error?c.message:String(c),hint:"See docs/02-SPEC-MANIFEST.md for the schedule fields."};return h(p,400)}}function ge(t,e){let s=Qt(t,e.request);if(s===void 0)throw new Ae({code:"web_asset_missing",message:`No web asset for ${t}.`,hint:"The routes in handler.ts and the table in web.ts have diverged, which spec.test.ts asserts cannot happen — so this build is inconsistent. Rebuild with `bun run build`."});return s}function y(t,e=200){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8"}})}function tn(t){return t==="/v1/health"||t==="/v1/ready"||t.startsWith("/v1/channels/")||Vt.includes(t)||t==="/docs"||t==="/v1/openapi.json"}function nn(t,e){let s=t.match("GET",e);return s.kind==="found"&&s.streaming}async function _e(t,e){try{return await t(e)}catch(s){if(K(s))return h(s.toDetail(),400);return h({code:"internal_error",message:s instanceof Error?s.message:String(s),hint:"An unexpected failure in the server. The runtime's event stream carries what happened around it."},500)}}function je(t,e){return h({code:"not_found",message:`No route for ${t} ${e}.`,hint:"Every path is under /v1. See docs/04-SPEC-WIRE.md for the surface."},404)}function H(t,e,s){return h({code:`${t}_not_found`,message:`No ${t} "${e}".`,hint:s??"Check the id — it is case-sensitive, and a session key includes its channel segment."},404)}function rn(t){let e=t.headers.get("authorization")??"";if(!e.startsWith("Bearer "))return;let s=e.slice(7);return s===""?void 0:s}function Pe(t,e,s){let d=s.params.id??"";if(!V(s.principal,d))return{kind:"response",response:H("agent",d)};let c=e.secrets;if(c===void 0)return{kind:"response",response:h({code:"secrets_not_supported",message:"This server cannot write an agent's credentials.",hint:"Credentials go into the .env beside an agent's manifest, and this process was built without a writer for it. Set them where the agent lives, with `config env`, and reload it."},501)};let p=t.sourceOf(d),b=typeof p==="string"?p:e.resolveAgent?.(d);if(b===void 0)return{kind:"response",response:H("agent",d)};return{kind:"found",id:d,manifestPath:b,admin:c}}function Ie(t){return{...t,failing:t.consecutiveFailures>0}}function ze(t,e){let s=ie(t);if(s.agentIds!==void 0){let d=e.scope?.agents;if(d===void 0||!d.every((c)=>s.agentIds?.includes(c)))return!1}if(s.sessionPrefix!==void 0){let d=e.scope?.sessionPrefix;if(d===void 0||!d.startsWith(s.sessionPrefix))return!1}return!0}function Oe(t,e){let s=t.searchParams.get(e);if(s===null)return;let d=Number(s);return Number.isSafeInteger(d)&&d>0?d:null}function Re(t){let e=t.searchParams.get("by"),s=e===null?["agent","model"]:e.split(",").filter((p)=>p!==""),d=s.filter((p)=>!Fr.includes(p));if(d.length>0)return{kind:"error",error:{code:"usage_group_invalid",message:`Cannot group usage by ${d.join(", ")}.`,hint:`Group by any of ${Fr.join(", ")}, comma-separated, or pass by= for one total.`,field:"by"}};let c={};for(let p of["from","to"]){let b=t.searchParams.get(p);if(b===null)continue;let S=Date.parse(b);if(Number.isNaN(S))return{kind:"error",error:{code:"usage_range_invalid",message:`${p} is ${JSON.stringify(b)}, which is not a date.`,hint:"Send ISO-8601, like 2026-09-01 or 2026-09-01T00:00:00Z. `from` is inclusive and `to` exclusive, so a month is from=2026-09-01&to=2026-10-01.",field:p}};c[p]=new Date(S).toISOString()}return{kind:"ok",value:{by:s,...c}}}function C(t,e,s){let d=e.params.id??"",c=t.list().find((p)=>p.id===d);if(c===void 0)return H("agent",d);if(!V(e.principal,d))return H("agent",d);return s(c)}function an(t,e){if(!ht(t))return e;return e.filter((s)=>V(t,s.id))}function on(t,e){if(!ht(t))return e;return e.filter((s)=>ue(t,s.sessionKey))}function ae(t,e){return ue(t.principal,e)?void 0:H("session",e)}function Le(t,e){let s=e.manifest.phases,d=Pr(s);return{id:e.id,name:e.manifest.name??e.id,status:"loaded",model:e.manifest.model.main.id,channels:e.manifest.channels.map((c)=>{let p=t.channels.statusOf(e.id).find((S)=>S.id===c.id),b=typeof c.tokenEnv==="string"?c.tokenEnv:void 0;return{...p??{},id:c.id,type:c.type,enabled:c.enabled,...b===void 0?{}:{credentialEnv:b,credentialSet:e.hasEnv(b)}}}),entryPhase:d?rs(s)??null:null,...d?{phases:Object.keys(s)}:{}}}function ye(t){return{...t.disabledAt===void 0?{}:{disabledAt:t.disabledAt},...t.reason===void 0?{}:{reason:t.reason}}}async function M(t,e=Yt){let s=Number.parseInt(t.headers.get("content-length")??"0",10);if(Number.isFinite(s)&&s>e)return{kind:"error",error:{code:"body_too_large",message:`The request body declares ${s} bytes; the limit is ${e}.`,hint:"This cap is enforced before a channel plugin sees anything, so a plugin never has to defend against a large POST."}};let d=await t.text();if(d.length>e)return{kind:"error",error:{code:"body_too_large",message:`The request body is ${d.length} bytes; the limit is ${e}.`,hint:"Send less. A message longer than this is not a message."}};if(d==="")return{kind:"ok",value:{}};try{return{kind:"ok",value:JSON.parse(d)}}catch(c){return{kind:"error",error:{code:"body_not_json",message:`The request body is not valid JSON: ${c instanceof Error?c.message:String(c)}`,hint:"Send application/json. A shell quoting mistake is the usual cause — check for unescaped quotes inside the payload."}}}}function sn(t){if(t===void 0||t===null)return{kind:"ok",from:void 0};let e=(d,c,p="from")=>({kind:"error",error:{code:"sender_invalid",message:d,hint:c,field:p}});if(typeof t!=="object")return e("from must be an object.",'Send { "from": { "id": "agent:ops-bot", "kind": "agent" } }, or omit it entirely for a turn the token-holder is sending itself.');let s=t;if(typeof s.id!=="string"||s.id.trim()==="")return e("from.id is required and must be a non-empty string.","Use a stable identity in your own namespace — `agent:ops-bot`, `user:018f…`, an email address. It is opaque to this runtime and is recorded on the turn so an audit can answer who asked.","from.id");if(s.id.length>Te)return e(`from.id is ${s.id.length} characters, over the ${Te} limit.`,"A sender id is an identifier, not a payload. It is rendered into the prompt's fence label, so an unbounded one spends the context window the message needs.","from.id");if(typeof s.kind!=="string"||!et.includes(s.kind)){let d=typeof s.kind==="string"?_t(s.kind,et):void 0;return e(`from.kind must be one of: ${et.join(", ")}.`,`${d===void 0?"":`Did you mean "${d}"? `}This field decides the trust boundary — "agent" fences the message and blocks mutating tools for the turn, "user" does not — so there is no default and an unknown value is refused rather than guessed at. A turn the token-holder is sending itself omits "from".`,"from.kind")}if(s.name!==void 0&&typeof s.name!=="string")return e("from.name must be a string when present.","It is a display name only and is rendered inside the fence, never above it. Omit it if you have none.","from.name");return{kind:"ok",from:{id:s.id,kind:s.kind,...s.name===void 0?{}:{name:s.name.slice(0,Xt)}}}}function ln(t){let e=t.headers.get("idempotency-key");if(e===null)return{kind:"ok",key:void 0};let s=e.trim(),d=(c)=>({kind:"error",error:{code:"idempotency_key_invalid",message:c,hint:`Send 1-${me} printable ASCII characters that are unique per logical request — a UUID is the usual choice. Omit the header entirely to accept that a retry runs the turn again. Printable ASCII because the key is a database key, and node:sqlite truncates a bound string at a NUL byte where bun:sqlite stores it whole.`,field:"Idempotency-Key"}});if(s==="")return d("Idempotency-Key is present but empty.");if(s.length>me)return d(`Idempotency-Key is ${s.length} characters, over the ${me} limit.`);if(!/^[\x20-\x7e]+$/.test(s))return d("Idempotency-Key contains characters that are not printable ASCII.");return{kind:"ok",key:s}}async function un(t,e){let s=new TextEncoder().encode(`${t}\x00${e}`),d=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(d)).map((c)=>c.toString(16).padStart(2,"0")).join("")}function cn(t){if(t===void 0||t===null||t==="none")return{kind:"ok",target:void 0};if(typeof t==="object"){let e=t;if(typeof e.channel==="string"&&typeof e.to==="string")return{kind:"ok",target:{channel:e.channel,to:e.to}}}return{kind:"error",error:{code:"deliver_invalid",message:'deliver must be "none" or { channel, to }.',hint:'A bare channel id is not enough on an API turn: the request has no originating conversation, so there is no recipient to infer. Send { "channel": "tg", "to": "12345" }, or "none" to read the reply from the event stream.',field:"deliver"}}}function dn(t){let e=t.status==="running";return ve({start:({send:s,close:d})=>{s({event:e?"stream.unavailable":"stream.ended",data:{turnId:t.turnId,status:t.status,sessionKey:t.sessionKey,...e?{reason:"no buffer for this turn in this process",hint:"The turn is recorded as running but is not observable here — its events are buffered in whichever process is executing it, and buffers are in-memory and per-process. Poll GET /v1/agents/:id/turns/:turnId for the outcome."}:{steps:t.steps,...t.errorCode===void 0?{}:{errorCode:t.errorCode},hint:"This turn finished before you attached and its buffer has been evicted. Its full text is in GET /v1/agents/:id/turns/:turnId."}}}),d();return}})}function Me(t,e,s){return ve({...s?.status===void 0?{}:{status:s.status},start:({send:d,close:c})=>{if(s?.accepted!==void 0)d({event:"turn.accepted",data:s.accepted});let p=t.streams.attach(e,(b)=>{if(d({event:b.type,data:b}),b.type==="turn.end")c()},{chunks:s?.chunks===!0});if(p===void 0){d({event:"stream.unavailable",data:{turnId:e,reason:"no buffer for this turn in this process",hint:"Read the final state from GET /v1/agents/:id/turns/:turnId. Buffers are in-memory and are evicted after a turn ends."}}),c();return}d({event:"stream.replay",data:{turnId:e,state:p.state,events:p.replay.length,truncated:p.truncated,dropped:p.dropped,chunks:p.chunks,...p.truncated?{hint:`The oldest ${p.dropped} event(s) of this turn were discarded to stay under the buffer cap, so this replay starts mid-turn. The turn's final text is complete in GET /v1/agents/:id/turns/:turnId.`}:{}}});for(let b of p.replay)d({event:b.type,data:b});if(p.state==="ended")c();return()=>p.unsubscribe()}})}function $e(t){if(t.status!=="pending")return;return{code:"reload_pending",message:`It applies when the ${t.running} running turn(s) finish; they complete on the settings they started with.`,hint:`New turns keep the old settings for ${t.holdAfterMs} ms, then wait and start on the new ones. The agent.reloaded event says when it is in force.`}}function vi(){let t=gr(),e=!1;return{token:t,live:()=>!e,spend:()=>{if(e)return!1;return e=!0,!0}}}function $t(t){let e=t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t,s=e==="0.0.0.0"||e==="::"||e===""?"127.0.0.1":e;return s.includes(":")?`[${s}]`:s}function Gi(t,e,s){return`http://${$t(t)}:${e}/?claim=${s}`}function Fi(t,e,s){return`curl -sX POST http://${$t(t)}:${e}/v1/keys -H 'Authorization: Bearer ${s}' -H 'content-type: application/json' -d '{"label":"my browser"}'`}function vt(t,e,s=new Map){let d=new Set,c,p=0,b,S=(k)=>{let G=k.type==="model.chunk";for(let N of d){if(N.data.agentId!==void 0&&k.agentId!==N.data.agentId)continue;if(k.agentId!==void 0&&!V(N.data.principal,k.agentId))continue;if(k.sessionKey!==void 0&&!ue(N.data.principal,k.sessionKey))continue;if(G&&!N.data.chunks)continue;try{N.send(JSON.stringify(k))}catch{}}},W=()=>{if(p+=1,b===void 0)b=t.bus.on("model.chunk",S)},j=()=>{if(p===0)return;if(p-=1,p===0)b?.(),b=void 0};return{async accept(k){let G=new URL(k.url),N=Tt(k),A=G.searchParams.get("token"),_=await e(Ct(k,N??A??""));if(_ instanceof Response)return{kind:"reject",response:_};let D=G.searchParams.get("agentId");if(D!==null&&!V(_,D))return{kind:"reject",response:new Response(JSON.stringify({error:{code:"agent_not_found",message:`No agent "${D}".`,hint:"Check the id — it is case-sensitive. A key scoped away from an agent sees exactly what a caller asking for one that does not exist sees."}}),{status:404,headers:{"content-type":"application/json"}})};return{kind:"accept",session:{agentId:D??void 0,chunks:G.searchParams.get("chunks")==="true",principal:_},...N===void 0?{}:{protocol:Ue}}},handlers:{open(k){if(d.add(k),c===void 0)c=t.bus.on("*",S);if(k.data.chunks)W();k.send(JSON.stringify({type:"ws.open",agentId:k.data.agentId??null,chunks:k.data.chunks}))},message(k,G){let N;try{N=JSON.parse(typeof G==="string"?G:new TextDecoder().decode(G))}catch{k.send(JSON.stringify({type:"ws.error",code:"frame_not_json"}));return}if(N.type==="ping"){k.send(JSON.stringify({type:"pong"}));return}if(N.type==="subscribe"){if(N.agentId===void 0&&N.sessionKey!==void 0){k.send(JSON.stringify({type:"ws.error",code:"subscribe_needs_agent_id",hint:"Send { type: 'subscribe', agentId: '<agent>' }. A socket filters on the agent an event carries; sessionKey names a conversation and can never match one, so a socket pointed with it receives nothing."}));return}let z=typeof N.chunks==="boolean"?N.chunks:k.data.chunks;if(z&&!k.data.chunks)W();else if(!z&&k.data.chunks)j();let L=N.agentId??k.data.agentId;if(L!==void 0&&!V(k.data.principal,L)){k.send(JSON.stringify({type:"ws.error",error:{code:"agent_not_found",message:`No agent "${L}".`,hint:"Check the id — it is case-sensitive. A key scoped away from an agent sees exactly what a caller asking for one that does not exist sees."}}));return}k.data={agentId:L,chunks:z,principal:k.data.principal},k.send(JSON.stringify({type:"ws.subscribed",agentId:k.data.agentId??null,chunks:k.data.chunks}));return}if(N.type==="stop"){let z=N.turnId===void 0?void 0:s.get(N.turnId);z?.abort(),k.send(JSON.stringify({type:"ws.stopping",turnId:N.turnId??null,found:z!==void 0}));return}if(N.type!=="message"){k.send(JSON.stringify({type:"ws.error",code:"unknown_frame_type"}));return}let A=k.data.agentId,m=t.list().find((z)=>z.id===A);if(m===void 0){k.send(JSON.stringify({type:"ws.error",code:"agent_not_found"}));return}let _=N.text??"";if(_.trim()===""){k.send(JSON.stringify({type:"ws.error",code:"message_text_required"}));return}let D=pt(k.data.principal,void 0),J=D.ok?D.from:void 0,F=(z)=>{if(!z.ok){k.send(JSON.stringify({type:"ws.error",...z.error.toDetail()}));return}let L=Zn(),te=new AbortController;s.set(L,te),k.send(JSON.stringify({type:"ws.accepted",turnId:L})),m.send(_,{admission:z,sessionKey:N.sessionKey??"api:default",turnId:L,source:"ws",...J===void 0?{}:{from:J},signal:te.signal}).catch(()=>{}).finally(()=>s.delete(L))},E=m.admitNow();if(E!==void 0){F(E);return}m.admit().then(F,(z)=>{k.send(JSON.stringify({type:"ws.error",code:"internal_error",message:z instanceof Error?z.message:String(z)}))})},close(k){if(d.delete(k)&&k.data.chunks)j();if(d.size===0)c?.(),c=void 0}},closeAll(){for(let k of d)try{k.close(1001,"server stopping")}catch{}d.clear(),c?.(),c=void 0,b?.(),b=void 0,p=0}}}async function Ui(t){let{host:e,port:s,runtime:d}=t;if(!se(e)&&t.token===void 0)throw new Ae({code:"server_public_without_token",message:`Refusing to bind ${e}:${s} with no API token.`,hint:"Set the variable named by server.tokenEnv, or bind 127.0.0.1. A public bind with no token exposes every endpoint — including the ones that start a turn — to anyone who can reach the port, and behaves identically to a safe one until someone finds it.",field:"server.host"});let c=new Map,p=en({runtime:d,...t.token===void 0?{}:{token:t.token},...t.token===void 0?{allowUnauthenticated:!0}:{},...t.now===void 0?{}:{now:t.now},running:c,...t.approvals===void 0?{}:{approvals:t.approvals},...t.claim===void 0?{}:{claim:t.claim},...t.resolveAgent===void 0?{}:{resolveAgent:t.resolveAgent},...t.provision===void 0?{}:{provision:t.provision},...t.channels===void 0?{}:{channels:t.channels},...t.secrets===void 0?{}:{secrets:t.secrets},origin:{host:t.host,...t.allowedOrigins===void 0?{}:{allowedOrigins:t.allowedOrigins},...t.allowedHosts===void 0?{}:{allowedHosts:t.allowedHosts}}});if(t.engine==="bun"||t.engine===void 0&&typeof Bun<"u"&&typeof Bun.serve==="function")return fn(p,t,c);return hn(p,t,c)}function fn(t,e,s){let d=vt(e.runtime,t.authenticate,s),c=Bun.serve({port:e.port,hostname:e.host,idleTimeout:Math.min(255,Math.ceil(gt/1000*3)),fetch:async(p,b)=>{if(new URL(p.url).pathname!=="/v1/ws")return t(p);let W=le(p,{host:e.host,...e.allowedOrigins===void 0?{}:{allowedOrigins:e.allowedOrigins},...e.allowedHosts===void 0?{}:{allowedHosts:e.allowedHosts}});if(W!==void 0)return new Response(JSON.stringify({error:W}),{status:403,headers:{"content-type":"application/json; charset=utf-8"}});let j=await d.accept(p);if(j.kind==="reject")return j.response;if(b.upgrade(p,{data:j.session,...j.protocol===void 0?{}:{headers:{"sec-websocket-protocol":j.protocol}}}))return;return new Response("upgrade failed",{status:400})},websocket:{open:(p)=>d.handlers.open(p),message:(p,b)=>d.handlers.message(p,b),close:(p)=>d.handlers.close(p)}});return{url:`http://${e.host}:${c.port}`,port:c.port??e.port,host:e.host,websocket:!0,stop:async()=>{d.closeAll(),await c.stop(!0)}}}async function hn(t,e,s){let{createServer:d}=await import("node:http"),{WebSocketServer:c}=await import("./wrapper-8x4hpa5z.js"),p=vt(e.runtime,t.authenticate,s),b=(A,m)=>{let _=`http://${A.headers.host??`${e.host}:${e.port}`}${A.url??"/"}`,D=new Headers;for(let[F,E]of Object.entries(A.headers))if(typeof E==="string")D.set(F,E);else if(Array.isArray(E))D.set(F,E.join(", "));let J=A.method??"GET";return new Request(_,{method:J,headers:D,...J==="GET"||J==="HEAD"||m===void 0?{}:{body:m}})},S=d((A,m)=>{(async()=>{let _=[];for await(let E of A)_.push(E);let D=await t(b(A,Buffer.concat(_))),J={};if(D.headers.forEach((E,z)=>{J[z]=E}),m.writeHead(D.status,J),D.body===null){m.end();return}let F=D.body.getReader();m.on("close",()=>void F.cancel().catch(()=>{}));for(;;){let{done:E,value:z}=await F.read();if(E)break;m.write(Buffer.from(z))}m.end()})().catch(()=>{if(!m.headersSent)m.writeHead(500);m.end()})}),W=new WeakMap,j=new c({noServer:!0,handleProtocols:(A,m)=>W.get(m)??!1}),k=(A,m,_)=>{A.end(`HTTP/1.1 ${m} Refused\r
|
|
81
|
+
`;function tn(n){let{runtime:e}=n,l=n.token,f=n.now??(()=>Date.now()),c=f();if(l===void 0&&n.allowUnauthenticated!==!0)throw new te({code:"server_token_missing",message:"createHandler was called with no token and no allowUnauthenticated.",hint:"Pass token, or pass allowUnauthenticated: true to state that this handler is mounted somewhere already protected. Defaulting to open would make the safe configuration the one you have to remember."});let m=n.running??new Map,b=n.approvals??_r(),E=()=>n.origin!==void 0&&le(n.origin.host),V=(r)=>E()||r.kind!=="open"&&pe(r,"admin"),j=(r)=>{if(n.origin===void 0)return;let t=ue(r,n.origin);return t===void 0?void 0:h(t,403)},k=(r,t)=>{if(n.origin===void 0)return t;let a=Ut(r,n.origin);if(Object.keys(a).length===0)return t;let s=new Headers(t.headers);for(let[u,d]of Object.entries(a))s.set(u,d);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:s})},q=!1,N=async()=>{if(l!==void 0||q)return!0;return q=await e.store.operatorKeys.liveCount()>0,q},z=async(r,t,a)=>{if(nn(t)||!await N())return{kind:"open"};let s=await Tt({request:r,expected:l,keys:e.store.operatorKeys,claim:n.claim,pathname:t,at:f()});if(s instanceof Response)return s;if(s.kind==="claim")return s;if(a!=="open"&&!pe(s,a))return xt(a,`${r.method} ${t}`);return s},p=new gt;p.add("GET","/v1/health",()=>y({status:"ok",version:Je,uptimeMs:f()-c,agents:e.list().length}),{capability:"open"}),p.add("GET","/v1/ready",()=>{if(e.ready)return y({status:"ready",agents:e.list().length});if(e.draining)return y({status:"draining",agents:e.list().length},503);return y({status:"starting",agents:e.list().length},503)},{capability:"open"}),p.add("GET","/v1/activity",async(r)=>{let t=r.principal;if(t.kind==="key"&&t.scope!==void 0&&(t.scope.agents!==void 0||t.scope.sessions!==void 0))return h({code:"activity_needs_unscoped_key",message:"Activity covers every agent on this server, and this key is scoped.",hint:"Call this with the server token or an operator key minted with no agents or sessions scope — it is meant for whatever suspends and wakes the process, not for a tenant."},403);return y(await e.activity(f()))},{capability:"admin"}),p.add("GET","/v1/agents",async(r)=>{let t=e.list().map((u)=>Le(e,u)),a=new Set(t.map((u)=>u.id)),s=(await e.store.agentState.list()).filter((u)=>!u.enabled&&!a.has(u.agentId)).map((u)=>({id:u.agentId,name:u.agentId,status:"disabled",...u.reason===void 0?{}:{reason:u.reason},...u.disabledAt===void 0?{}:{disabledAt:u.disabledAt}}));return y(on(r.principal,[...t,...s]))},{capability:"read"}),p.add("GET","/v1/agents/:id",(r)=>_(e,r,async(t)=>{let a=await t.store.schedules.list(t.id),s=e.team(t.id),u=await e.store.conversations.assignment(t.id);return y({...Le(e,t),...u===void 0?{}:{assignedTo:{participantId:u.participantId,...u.assignedBy===void 0?{}:{assignedBy:u.assignedBy},assignedAt:u.assignedAt}},dialect:t.describe().dialect,window:t.window,tools:t.tools.size,catalogueTokens:t.describe().catalogueTokens,skills:t.skills?.skills.length??0,schedules:a.length,...s.length===0?{}:{team:s.map((d)=>({id:d.id,task:d.task,artifact:Object.keys(d.artifact.properties)}))},warnings:[...t.warnings,...t.tools.warnings]})}),{capability:"read"}),p.add("GET","/v1/agents/:id/export",(r)=>_(e,r,async(t)=>{let a=await D(r.principal);if(a!==void 0)return a;let s=r.url.searchParams.get("paths");try{let u=Is(s===null?void 0:s.split(",").map((d)=>d.trim()));return y(us(t,u))}catch(u){return C(u)}}),{capability:"admin"}),p.add("POST","/v1/agents/:id/import",(r)=>_(e,r,async(t)=>{let a=await D(r.principal);if(a!==void 0)return a;let s=await M(r.request,Jt);if(s.kind==="error")return h(s.error,400);let u=F(ut,s.value);if(!u.ok)return h(u.error,400);try{let d=await ds({agent:t,bundle:u.value.bundle,...u.value.mode===void 0?{}:{mode:u.value.mode},reload:async()=>(await e.reload(t.id)).status});return y({id:t.id,...d})}catch(d){return C(d)}}),{capability:"admin"}),p.add("POST","/v1/agents/:id/reload",(r)=>_(e,r,async(t)=>{try{let a=await e.reload(t.id);if(a.status==="pending")return y({id:t.id,status:"pending",adopted:[],running:a.running,holdAfterMs:a.holdAfterMs},202);return y({id:t.id,status:"loaded",adopted:a.adopted.map((s)=>s.id)})}catch(a){if(x(a))return h({code:a.code,message:a.message,hint:a.hint,...a.field===void 0?{}:{field:a.field}},a.code==="agent_turn_in_flight"?409:400);throw a}}),{capability:"admin"}),p.add("GET","/v1/openapi.json",(r)=>y($t({routes:p.routes(),serverUrl:`${r.url.protocol}//${r.url.host}`})),{capability:"open"}),p.add("GET","/docs",()=>new Response(Zt,{status:200,headers:{"content-type":"text/html; charset=utf-8"}}),{capability:"open"}),p.add("GET","/v1/provision",(r)=>y({available:n.provision!==void 0,local:E(),allowed:V(r.principal),steps:n.provision?.steps()??[]}),{capability:"read"}),p.add("POST","/v1/agents",async(r)=>{let t=n.provision;if(t===void 0)return h({code:"provisioning_not_supported",message:"This server cannot create agents.",hint:"Creating one writes a directory of files from a question set this process was not given — an embedder mounting this handler over its own agent store is the case that lands here. Run `init` where the sandbox is, or mount an agent directory."},501);if(!V(r.principal))return h({code:"provisioning_not_local",message:"Creating an agent needs either a loopback bind or a credential with the admin capability.",hint:"This route writes files and starts an agent. A token-less loopback server is a supported configuration, so on a non-loopback bind it asks for a credential instead — set server.tokenEnv (the container's DISPACH_API_TOKEN does this) or present an operator key minted with `can: [admin]`. What is refused is provisioning on a server that required no credential at all and is reachable from the network."},403);let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let s=F(Qe,a.value);if(!s.ok)return h(s.error,400);let{answers:u,template:d}=s.value;if(u!==void 0&&d!==void 0)return h({code:"provision_body_ambiguous",message:"The body has both answers and a template.",hint:"Send answers to create an agent the way init does, or template with name and vars to create one from a template in this server's sandbox. Not both.",field:"template"},400);if(u===void 0&&d===void 0)return h({code:"provision_answers_required",message:"The body has neither answers nor a template.",hint:'Send { "answers": { "name": "milo", … } } (GET /v1/provision lists the steps), or { "template": "…", "name": "…", "vars": {…} } (GET /v1/templates lists the templates).',field:"answers"},400);let g;try{g=d===void 0?t.create(u??{}):t.createFromTemplate({template:d,name:s.value.name??"",vars:s.value.vars??{}})}catch(v){if(x(v))return h(v.toDetail(),400);throw v}try{let v=await e.adopt(g.manifestPath);return y({id:g.agentId,dir:g.dir,files:g.files,adopted:v.map((w)=>w.id)},201)}catch(v){return y({id:g.agentId,dir:g.dir,files:g.files,adopted:[],error:x(v)?v.toDetail():{code:"provision_adopt_failed",message:v instanceof Error?v.message:String(v),hint:"The agent was written and is not running. Fix what the message names and `start` it, or restart the host."}},201)}},{capability:"admin"}),p.add("GET","/v1/templates",()=>y({templates:n.provision?.templates()??[]}),{capability:"read"}),p.add("GET","/v1/agents/:id/secrets",async(r)=>{let t=Pe(e,n,r);if(t.kind==="response")return t.response;return y({id:t.id,secrets:t.admin.status(t.manifestPath)})},{capability:"admin"}),p.add("PUT","/v1/agents/:id/secrets",async(r)=>{let t=Pe(e,n,r);if(t.kind==="response")return t.response;let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let s=F(ft,a.value);if(!s.ok)return h(s.error,400);let u;try{u=t.admin.write(t.manifestPath,s.value.values)}catch(w){if(x(w))return h(w.toDetail(),400);throw w}let d={id:t.id,written:u.written,shadowed:u.shadowed},g=e.list().some((w)=>w.id===t.id),v=await e.store.agentState.get(t.id);if(!g&&v?.enabled===!1)return y({...d,applied:"none",adopted:[],stopped:!0});try{if(g){let R=await e.reload(t.id);if(R.status==="pending")return y({...d,applied:"pending",adopted:[]});return y({...d,applied:"reloaded",adopted:R.adopted.map((L)=>L.id)})}let w=await e.adopt(t.manifestPath);return y({...d,applied:"adopted",adopted:w.map((R)=>R.id)})}catch(w){return y({...d,applied:"none",adopted:[],error:x(w)?w.toDetail():{code:"secrets_apply_failed",message:w instanceof Error?w.message:String(w),hint:"The values were written and the agent is not running on them yet. Fix what the message names and reload or start it."}})}},{capability:"admin"}),p.add("POST","/v1/agents/:id/stop",async(r)=>{let t=r.params.id??"";if(!W(r.principal,t))return H("agent",t);let a=e.list().some((w)=>w.id===t),s=await e.store.agentState.get(t);if(!a&&s===void 0)return H("agent",t);let u=await M(r.request);if(u.kind==="error")return h(u.error,400);let d=F(Ve,u.value);if(!d.ok)return h(d.error,400);let g=d.value.reason?.trim(),v=await e.store.agentState.disable(t,new Date(n.now?.()??Date.now()).toISOString(),g===void 0||g===""?void 0:g);if(a)try{await e.dispose(t,"stopped")}catch(w){if(x(w)&&w.code==="agent_turn_in_flight")return h(w.toDetail(),409);throw w}return y({id:t,status:"disabled",...ve(v)})},{capability:"admin"}),p.add("POST","/v1/agents/:id/start",async(r)=>{let t=r.params.id??"";if(!W(r.principal,t))return H("agent",t);if(e.list().some((d)=>d.id===t)){let d=await e.store.agentState.enable(t);return y({id:t,status:"loaded",...ve(d)})}let a=n.resolveAgent;if(a===void 0)return h({code:"start_not_supported",message:"This server cannot look up a manifest for an agent it is not hosting.",hint:"Starting a stopped agent needs its manifest, which lives wherever agents live — the sandbox for the CLI, a mounted path for a container. This process was built without that lookup, so pass the agent to `serve` and restart it instead."},501);let s=a(t);if(s===void 0)return H("agent",t);let u=await e.store.agentState.enable(t);try{let d=await e.adopt(s);return y({id:t,status:"loaded",...ve(u),adopted:d.map((g)=>g.id)})}catch(d){if(await e.store.agentState.disable(t,new Date(n.now?.()??Date.now()).toISOString(),"start failed"),x(d))return h(d.toDetail(),400);throw d}},{capability:"admin"}),p.add("DELETE","/v1/agents/:id",async(r)=>{let t=r.params.id??"";if(!W(r.principal,t))return H("agent",t);let a=e.list().some((v)=>v.id===t),s=await e.store.agentState.get(t),u=n.remover;if(u===void 0)return h({code:"agent_remove_unsupported",message:"This server cannot delete agents.",hint:"`serve` provides deletion; an embedded handler has no sandbox to delete from. Use the CLI's `remove`."},501);if(r.url.searchParams.get("confirm")!==t)return h({code:"agent_remove_unconfirmed",message:`Deleting ${t} needs ?confirm=${t}.`,hint:"It deletes the agent's conversations, memory and files for good, so the request names the agent twice. POST /v1/agents/:id/stop switches one off and keeps everything.",field:"confirm"},400);let d=u.locate(t);if(!d.ok){if(!a&&s===void 0&&d.status===404)return H("agent",t);return h(d.error,d.status)}if(a)try{await e.dispose(t,"stopped")}catch(v){if(x(v))return h(v.toDetail(),409);throw v}let g=await e.store.purgeAgent(t);return await u.deleteDir(d.dir),y({id:t,removed:!0,dir:d.dir,...g})},{capability:"admin"}),p.add("POST","/v1/agents/:id/deliveries",async(r)=>_(e,r,async(t)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let s=F(Fe,a.value);if(!s.ok)return h(s.error,400);let u=s.value;if(!e.channels.hasChannel(t.id,u.channel))return h({code:"delivery_channel_unknown",message:`${t.id} has no running channel "${u.channel}".`,hint:"Name a channel id from the agent's manifest (GET /v1/agents/:id lists them with their status). A disabled channel is not running and cannot send.",field:"channel"},404);let d=Pr({channel:u.channel,peerId:u.to}),g=ae(r,d);if(g!==void 0)return g;let{inserted:v}=await e.channels.deliver({agentId:t.id,sessionKey:d,channelId:u.channel,recipient:u.to,text:u.text,key:u.key});if(v)await t.recordDelivered(u.text,{sessionKey:d});return y({sessionKey:d,key:u.key,duplicate:!v},202)}),{capability:"admin"}),p.add("POST","/v1/agents/:id/messages",async(r)=>_(e,r,async(t)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let s=F(Be,a.value);if(!s.ok)return h(s.error,400);let u=s.value,d=u.chunks===!0,g=u.text,v=u.sessionKey??"api:default",w=ae(r,v);if(w!==void 0)return w;let R=dn(u.deliver);if(R.kind==="error")return h(R.error,400);let L=ln(u.from);if(L.kind==="error")return h(L.error,400);let K=mt(r.principal,L.from);if(!K.ok)return h(K.error,403);let Y=un(r.request);if(Y.kind==="error")return h(Y.error,400);let X=await t.admit();if(!X.ok)return h(X.error.toDetail(),429);let Z=Zn();if(Y.key!==void 0){let ee=await t.store.turns.claimInboundKey({agentId:t.id,key:Y.key,turnId:Z,inputHash:await cn(v,g),now:new Date});if(ee.kind!=="claimed")X.release();if(ee.kind==="replay")return y({turnId:ee.turnId,sessionKey:v,replayed:!0},200);if(ee.kind==="mismatch")return h({code:"idempotency_key_reused",message:`Idempotency-Key "${Y.key}" was already used for a different message.`,hint:`It belongs to turn ${ee.turnId}, whose text or session differed from this request's. Nothing was run. Use a fresh key for a new message, or resend the original text byte for byte to get that turn back. A key is remembered for 24 hours.`,field:"Idempotency-Key"},409)}let we=new AbortController;m.set(Z,we),e.streams.open(Z,{chunks:d});let mn=t.send(g,{admission:X,sessionKey:v,turnId:Z,source:"api",...K.from===void 0?{}:{from:K.from},signal:we.signal}).then(async(ee)=>{let de=ee.attachments??[];if(R.target===void 0||ee.text.trim()===""&&de.length===0)return;await e.channels.deliver({agentId:t.id,sessionKey:v,channelId:R.target.channel,recipient:R.target.to,turnId:Z,text:ee.text,...de.length===0?{}:{attachments:de}})}).catch(()=>{}).finally(()=>{m.delete(Z)});if(u.stream!==!0)return y({turnId:Z,sessionKey:v},202);return De(e,Z,{accepted:{turnId:Z,sessionKey:v},status:202,chunks:d})}),{capability:"chat"}),p.add("GET","/v1/agents/:id/turns/:turnId/stream",(r)=>_(e,r,async(t)=>{let a=r.params.turnId??"";if(e.streams.state(a)===void 0){let s=await t.store.turns.get(a);if(s===void 0)return H("turn",a,"No turn with this id has ever run on this agent. A turn id is the `turnId` from POST /v1/agents/:id/messages — check the agent in the path too, since a turn belongs to one.");return fn(s)}return De(e,a,{chunks:r.url.searchParams.get("chunks")==="true"})}),{capability:"read",streaming:!0}),p.add("POST","/v1/agents/:id/turns/:turnId/stop",(r)=>_(e,r,()=>{let t=r.params.turnId??"",a=m.get(t);if(a===void 0)return h({code:"turn_not_running",message:`No cancel handle for turn ${t} on this API.`,hint:"This surface can stop a turn it started. A turn that has already finished cannot be stopped at all — read its final state from GET /v1/agents/:id/turns/:turnId. A turn started by a channel, a schedule, or another process is running without a handle here."},409);return a.abort(),y({turnId:t,stopping:!0},202)}),{capability:"chat"}),p.add("GET","/v1/agents/:id/approvals",(r)=>_(e,r,async(t)=>y({approvals:b.pending(t.id)})),{capability:"read"}),p.add("POST","/v1/agents/:id/approvals/:approvalId",(r)=>_(e,r,async()=>{let t=await M(r.request);if(t.kind==="error")return h(t.error,400);let a=F(He,t.value);if(!a.ok)return h(a.error,400);let s=a.value,u=r.params.approvalId??"";if(!b.resolve(u,s.granted))return h({code:"approval_not_found",message:`No approval with id ${u} is waiting.`,hint:'It was answered already, or its turn ended while it waited — a stopped or timed-out turn abandons its question, and `approval.resolved` reports that as `by: "abandoned"`. GET /v1/agents/:id/approvals lists what is actually waiting. Nothing about a settled approval is kept, so this is also the answer for an id that was never real.'},404);return y({approvalId:u,granted:s.granted})}),{capability:"chat"}),p.add("GET","/",(r)=>ye("/",r),{capability:"open"}),p.add("GET","/assets/app.js",(r)=>ye("/assets/app.js",r),{capability:"open"}),p.add("GET","/assets/app.css",(r)=>ye("/assets/app.css",r),{capability:"open"}),p.add("POST","/v1/keys",async(r)=>{let t=n.claim!==void 0&&an(r.request)===n.claim.token,a=await M(r.request);if(a.kind==="error")return h(a.error,400);let s=F(Ke,a.value);if(!s.ok)return h(s.error,400);let u=s.value,d=ns(u.label);if(d!==void 0)return h({code:"key_label_invalid",message:d,hint:`A label is shown in a listing and in the UI, so it is at most ${lr} printable characters on one line. It is a display name, not a description.`,field:"label"},400);if(t&&n.claim?.spend()!==!0)return Me();let g=u.scope;if(g?.agents!==void 0){let K=new Set(e.list().map((X)=>X.id));for(let X of await e.store.agentState.list())K.add(X.agentId);let Y=g.agents.filter((X)=>!K.has(X));if(Y.length>0)return h({code:"key_scope_agent_unknown",message:`No agent ${Y.map((X)=>JSON.stringify(X)).join(", ")} on this server.`,hint:"A key scoped to an agent that does not exist authenticates and then reaches nothing, which looks exactly like a working credential until it is used. GET /v1/agents lists what this server holds, stopped agents included.",field:"scope.agents"},400)}let v=g?.expiresIn===void 0?void 0:new Date(f()+g.expiresIn*1000).toISOString(),w=g===void 0?void 0:{...g.agents===void 0?{}:{agents:g.agents},...g.sessions===void 0?{}:{sessions:g.sessions},...g.can===void 0?{}:{can:g.can},...g.participant===void 0?{}:{participant:g.participant}},R=gr(),L=await e.store.operatorKeys.issue({keyId:rs(f()),label:u.label.trim(),fingerprint:await cr(R),createdAt:new Date(f()).toISOString(),...w===void 0||Object.keys(w).length===0?{}:{scope:w},...v===void 0?{}:{expiresAt:v}});return y({...L,secret:R},201)},{capability:"admin"}),p.add("GET","/v1/keys",async()=>{let r=await e.store.operatorKeys.list();return y({keys:r,scope:"A key with no scope authenticates every route for every agent this server holds. A scope narrows an already-authenticated caller — it names agents, a session prefix and capabilities, and it is not an identity: there are no users, teams or roles here."})},{capability:"admin"}),p.add("DELETE","/v1/keys/:keyId",async(r)=>{let t=r.params.keyId??"",a=await e.store.operatorKeys.revoke(t,new Date(f()).toISOString());if(a===void 0)return H("key",t,"The id is the `keyId` from POST /v1/keys, not the secret — GET /v1/keys lists them. An already-revoked key is a 200 carrying its original stamp, so this really does mean no such key exists.");return y(a)},{capability:"admin"}),p.add("POST","/v1/webhooks",async(r)=>{let t=await M(r.request);if(t.kind==="error")return h(t.error,400);let a=F(dt,t.value);if(!a.ok)return h(a.error,400);let s=a.value,u=s.types.filter((L)=>!FA.includes(L)||!Cs(L));if(u.length>0)return h({code:"webhook_type_invalid",message:`Cannot deliver ${u.join(", ")}.`,hint:"Any type from the event stream except model.chunk, which is one request per token. The wire spec's event table lists them.",field:"types"},400);let d=oe(r.principal);if(s.agents!==void 0){let L=new Set([...e.list().map((Y)=>Y.id),...(await e.store.agentState.list()).map((Y)=>Y.agentId)]),K=s.agents.filter((Y)=>!W(r.principal,Y)||!L.has(Y));if(K.length>0)return h({code:"webhook_scope_invalid",message:`This credential cannot subscribe to ${K.join(", ")}.`,hint:"A subscription hears at most what the key creating it reaches, and only agents this server holds. GET /v1/agents lists them.",field:"agents"},400)}let g=s.agents??d.agentIds,v={...g===void 0?{}:{agents:[...g]},...d.sessionPrefix===void 0?{}:{sessionPrefix:d.sessionPrefix}};try{await e.webhooks.check(s.url)}catch(L){if(x(L))return h(L.toDetail(),400);throw L}let w=Es(),R=await e.store.webhooks.create({subscriptionId:`wh_${crypto.randomUUID().replaceAll("-","").slice(0,20)}`,url:s.url,secret:w,types:[...new Set(s.types)],...Object.keys(v).length===0?{}:{scope:v},createdAt:new Date(n.now?.()??Date.now()).toISOString()});return await e.webhooks.changed(),y({...Ie(R),secret:w},201)},{capability:"admin"}),p.add("GET","/v1/webhooks",async(r)=>{let t=await e.store.webhooks.list();return y({webhooks:t.filter((a)=>ze(r.principal,a)).map(Ie)})},{capability:"admin"}),p.add("DELETE","/v1/webhooks/:webhookId",async(r)=>{let t=r.params.webhookId??"",a=await e.store.webhooks.get(t);if(a===void 0||!ze(r.principal,a))return h({code:"webhook_not_found",message:`No webhook with id "${t}".`,hint:"GET /v1/webhooks lists the subscriptions this credential can see."},404);return await e.store.webhooks.delete(t),await e.webhooks.changed(),y({id:t,deleted:!0})},{capability:"admin"});let A=(r)=>r.kind==="key"?r.scope?.participant:void 0,B=(r,t)=>{let a=A(r);if(a!==void 0&&!t.members.includes(a))return!1;return t.members.every((s)=>{let u=Fr(s);return u===void 0||W(r,u)})},J=(r)=>h({code:"conversation_not_found",message:`No conversation "${r}".`,hint:"GET /v1/conversations lists the ones this credential can see."},404),G=async(r,t)=>{let a=r.params.conversationId??"",s=await e.store.conversations.get(a);if(s===void 0||!B(r.principal,s))return J(a);return t(s)},C=(r)=>{if(!x(r))throw r;return h(r.toDetail(),r.code.endsWith("_not_found")?404:r.code.endsWith("_forbidden")?403:400)};p.add("POST","/v1/participants",async(r)=>{let t=await M(r.request);if(t.kind==="error")return h(t.error,400);let a=F(Xe,t.value);if(!a.ok)return h(a.error,400);try{let s=a.value;return y(await e.conversations.registerParticipant({id:s.id,...s.name===void 0?{}:{name:s.name},...s.role===void 0?{}:{role:s.role}}),201)}catch(s){return C(s)}},{capability:"admin"}),p.add("GET","/v1/participants",async()=>y({participants:await e.store.conversations.participants()}),{capability:"read"}),p.add("DELETE","/v1/participants/:participantId",async(r)=>{let t=r.params.participantId??"";if(!await e.store.conversations.deleteParticipant(t))return h({code:"participant_not_found",message:`No participant "${t}".`,hint:"GET /v1/participants lists them."},404);return y({id:t,deleted:!0})},{capability:"admin"}),p.add("POST","/v1/conversations",async(r)=>{let t=await M(r.request);if(t.kind==="error")return h(t.error,400);let a=F(Ze,t.value);if(!a.ok)return h(a.error,400);let s=A(r.principal);if(s!==void 0&&!a.value.members.includes(s))return h({code:"conversation_creator_not_member",message:`This key speaks for ${s}, who is not among the members.`,hint:`Include "${s}" in members. A backend creating rooms for others needs a key minted without scope.participant.`,field:"members"},403);let u=a.value.members.map((d)=>Fr(d)).filter((d)=>d!==void 0&&!W(r.principal,d));if(u.length>0)return h({code:"conversation_member_unknown",message:`No participant "agent:${u[0]}".`,hint:"That agent is not hosted here. GET /v1/agents lists the ones that are.",field:"members"},400);try{return y(await e.conversations.create({kind:a.value.kind,members:a.value.members,...a.value.title===void 0?{}:{title:a.value.title}}),201)}catch(d){return C(d)}},{capability:"admin"}),p.add("GET","/v1/conversations",async(r)=>{let t=await e.store.conversations.list();return y({conversations:t.filter((a)=>B(r.principal,a))})},{capability:"read"}),p.add("GET","/v1/conversations/:conversationId",(r)=>G(r,async(t)=>y(t)),{capability:"read"}),p.add("PATCH","/v1/conversations/:conversationId/members",(r)=>G(r,async(t)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let s=F(tt,a.value);if(!s.ok)return h(s.error,400);try{return y(await e.conversations.setMembers(t.id,s.value.add??[],s.value.remove??[]))}catch(u){return C(u)}}),{capability:"admin"}),p.add("POST","/v1/conversations/:conversationId/messages",(r)=>G(r,async(t)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let s=F(rt,a.value);if(!s.ok)return h(s.error,400);let u=A(r.principal),d=s.value.authorId;if(u!==void 0&&d!==void 0&&d!==u)return h({code:"sender_not_bound_participant",message:`This key speaks for ${u}, and the message names ${d}.`,hint:`Omit authorId (it is filled in), or send "${u}". A backend that posts for others needs a key minted without scope.participant.`,field:"authorId"},403);let g=u??d;if(g===void 0)return h({code:"conversation_author_required",message:"A message needs an author.",hint:"Send authorId, the human member who said it. A key bound to a participant fills it in.",field:"authorId"},400);try{let v=await e.conversations.post({conversationId:t.id,authorId:g,text:s.value.text,...s.value.mentions===void 0?{}:{mentions:s.value.mentions}});return y(v,202)}catch(v){return C(v)}}),{capability:"chat"}),p.add("GET","/v1/conversations/:conversationId/messages",(r)=>G(r,async(t)=>{let a=Number(r.url.searchParams.get("after")??0),s=Number(r.url.searchParams.get("limit")??200),u=await e.store.conversations.messages(t.id,{after:Number.isFinite(a)&&a>0?a:0,limit:Number.isFinite(s)&&s>0?Math.min(s,500):200});return y({conversationId:t.id,messages:u,...u.length===0?{}:{nextAfter:u.at(-1)?.seq}})}),{capability:"read"}),p.add("PUT","/v1/participants/:participantId/presence",async(r)=>{let t=r.params.participantId??"",a=A(r.principal);if(a!==void 0&&a!==t)return h({code:"sender_not_bound_participant",message:`This key speaks for ${a}, and the presence names ${t}.`,hint:"A key bound to a participant sets only that participant's presence. The embedder's backend, holding an unbound key, sets anyone's."},403);let s=await M(r.request);if(s.kind==="error")return h(s.error,400);let u=F(it,s.value);if(!u.ok)return h(u.error,400);try{return y(await e.conversations.setPresence(t,u.value.presence))}catch(d){return C(d)}},{capability:"chat"}),p.add("GET","/v1/actions",async(r)=>{let t=r.url.searchParams.get("status"),a=A(r.principal),s=await e.store.conversations.actions({...a===void 0?{}:{ownerId:a},...t==="pending"||t==="done"||t==="failed"||t==="denied"?{status:t}:{}});return y({actions:s.filter((u)=>W(r.principal,u.agentId))})},{capability:"read"}),p.add("POST","/v1/actions/:actionId",async(r)=>{let t=r.params.actionId??"",a=await e.store.conversations.action(t),s=A(r.principal);if(a===void 0||!W(r.principal,a.agentId)||s!==void 0&&s!==a.ownerId)return h({code:"action_not_found",message:`No action "${t}".`,hint:"GET /v1/actions lists the ones waiting on you."},404);let u=await M(r.request);if(u.kind==="error")return h(u.error,400);let d=F(ct,u.value);if(!d.ok)return h(d.error,400);try{return y(await e.conversations.decideAction(t,d.value.approve))}catch(g){if(x(g)&&g.code==="action_already_decided")return h(g.toDetail(),409);return C(g)}},{capability:"chat"}),p.add("PUT","/v1/agents/:id/assignee",(r)=>_(e,r,async(t)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let s=F(at,a.value);if(!s.ok)return h(s.error,400);let u=A(r.principal);if(u!==void 0){if((await e.store.conversations.participant(u))?.role!=="admin")return h({code:"assignment_requires_admin",message:`${u} is not an admin participant.`,hint:'Only a participant registered with role "admin" assigns agents to members.'},403)}try{return y(await e.conversations.assign({agentId:t.id,participantId:s.value.participantId,...u===void 0?{}:{assignedBy:u}}))}catch(d){return C(d)}}),{capability:"admin"}),p.add("DELETE","/v1/agents/:id/assignee",(r)=>_(e,r,async(t)=>y({id:t.id,unassigned:await e.store.conversations.unassign(t.id)})),{capability:"admin"});let O=(r)=>{let t=A(r);if(t!==void 0||pe(r,"admin"))return{ok:!0,actor:t};return{ok:!1,response:h({code:"memory_write_requires_admin",message:"This key is bound to no participant and does not carry admin.",hint:"A member writes through a key minted with scope.participant; the embedder's backend writes shared scopes with an admin key."},403)}};p.add("POST","/v1/memory/notes",async(r)=>{let t=await M(r.request);if(t.kind==="error")return h(t.error,400);let a=F(ot,t.value);if(!a.ok)return h(a.error,400);let s=O(r.principal);if(!s.ok)return s.response;try{return y(await e.conversations.addNote({scope:a.value.scope,text:a.value.text,...s.actor===void 0?{}:{authorId:s.actor}}),201)}catch(u){return C(u)}},{capability:"chat"}),p.add("GET","/v1/memory/notes",async(r)=>{let t=r.url.searchParams.get("scope")??"";try{return y({notes:await e.conversations.notes(t,A(r.principal))})}catch(a){return C(a)}},{capability:"read"}),p.add("DELETE","/v1/memory/notes/:noteId",async(r)=>{let t=O(r.principal);if(!t.ok)return t.response;try{return await e.conversations.deleteNote(r.params.noteId??"",t.actor),y({id:r.params.noteId,deleted:!0})}catch(a){return C(a)}},{capability:"chat"}),p.add("GET","/v1/participants/:participantId/memory/reads",async(r)=>{try{return y({reads:await e.conversations.reads(r.params.participantId??"",A(r.principal))})}catch(t){return C(t)}},{capability:"read"});let D=async(r)=>{let t=A(r);if(t===void 0)return;if((await e.store.conversations.participant(t))?.role==="admin")return;return h({code:"memory_scope_forbidden",message:`${t} is not an admin participant.`,hint:'Only a participant registered with role "admin" defines projects and names the space writer.'},403)};p.add("GET","/v1/projects",async()=>y({projects:await e.store.conversations.projects()}),{capability:"read"}),p.add("PUT","/v1/projects/:projectId",async(r)=>{let t=await M(r.request);if(t.kind==="error")return h(t.error,400);let a=F(st,t.value);if(!a.ok)return h(a.error,400);let s=await D(r.principal);if(s!==void 0)return s;let u=(a.value.agents??[]).find((d)=>!W(r.principal,d));if(u!==void 0)return h({code:"agent_not_found",message:`No agent "${u}".`,hint:"GET /v1/agents lists the ones hosted here."},404);try{return y(await e.conversations.upsertProject({id:r.params.projectId??"",...a.value.name===void 0?{}:{name:a.value.name},...a.value.agents===void 0?{}:{agents:a.value.agents}}))}catch(d){return C(d)}},{capability:"admin"}),p.add("DELETE","/v1/projects/:projectId",async(r)=>{let t=await D(r.principal);if(t!==void 0)return t;let a=r.params.projectId??"";return y({id:a,deleted:await e.store.conversations.deleteProject(a)})},{capability:"admin"}),p.add("PUT","/v1/memory/space/writer",async(r)=>{let t=await M(r.request);if(t.kind==="error")return h(t.error,400);let a=F(lt,t.value);if(!a.ok)return h(a.error,400);let s=await D(r.principal);if(s!==void 0)return s;let u=A(r.principal);try{return await e.conversations.setSpaceWriter(a.value.writer,u),y({writer:a.value.writer})}catch(d){return C(d)}},{capability:"admin"}),p.add("GET","/v1/usage",async(r)=>{let t=Re(r.url);if(t.kind==="error")return h(t.error,400);let a=oe(r.principal);return y(await e.store.usage.report({...t.value,...a}))},{capability:"read"}),p.add("GET","/v1/agents/:id/usage",(r)=>_(e,r,async(t)=>{let a=Re(r.url);if(a.kind==="error")return h(a.error,400);let s=oe(r.principal).sessionPrefix;return y({id:t.id,...await e.store.usage.report({...a.value,agentIds:[t.id],...s===void 0?{}:{sessionPrefix:s}})})}),{capability:"read"}),p.add("GET","/v1/agents/:id/turns",(r)=>_(e,r,async(t)=>{let a=Oe(r.url,"limit"),s=Oe(r.url,"before");if(a===null||s===null)return h({code:"turns_page_invalid",message:"`limit` and `before` must be positive whole numbers.",hint:"Pass `before` exactly as the previous page's `nextBefore` returned it, and a `limit` up to 200."},400);let u=oe(r.principal).sessionPrefix,d=await e.store.turns.listForAgent(t.id,{limit:Math.min(a??50,200),...s===void 0?{}:{before:s},...u===void 0?{}:{sessionPrefix:u}});return y({id:t.id,...d})}),{capability:"read"}),p.add("GET","/v1/agents/:id/turns/:turnId",(r)=>_(e,r,async(t)=>{let a=await t.store.turns.get(r.params.turnId??"");if(a===void 0)return H("turn",r.params.turnId??"");return y(a)}),{capability:"read"}),p.add("GET","/v1/agents/:id/sessions",(r)=>_(e,r,async(t)=>y(sn(r.principal,await t.store.sessions.list(t.id)))),{capability:"read"}),p.add("GET","/v1/agents/:id/sessions/:key",(r)=>_(e,r,async(t)=>{let a=r.params.key??"",s=ae(r,a);if(s!==void 0)return s;let u=await t.store.sessions.get(t.id,a);if(u===void 0)return H("session",a);return y(u)}),{capability:"read"}),p.add("GET","/v1/agents/:id/sessions/:key/messages",(r)=>_(e,r,async(t)=>{let a=r.url.searchParams.get("before"),s=r.url.searchParams.get("limit"),u=ae(r,r.params.key??"");if(u!==void 0)return u;let d=await t.store.messages.page(t.id,r.params.key??"",{...a===null?{}:{before:Number.parseInt(a,10)},...s===null?{}:{limit:Number.parseInt(s,10)}});return y(d)}),{capability:"read"}),p.add("DELETE","/v1/agents/:id/sessions/:key",(r)=>_(e,r,async(t)=>{let a=ae(r,r.params.key??"");if(a!==void 0)return a;return await t.store.sessions.clear(t.id,r.params.key??""),y({cleared:r.params.key??"",memoryFilesKept:!0})}),{capability:"write"}),p.add("POST","/v1/agents/:id/sessions/:key/phase",(r)=>_(e,r,async(t)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let s=F(We,a.value);if(!s.ok)return h(s.error,400);let u=s.value.phase;if(typeof u!=="string"&&u!==null)return h({code:"phase_invalid",message:"phase must be a string, or null to clear it.",hint:'Send { "phase": "triage" }. Phase-scoped tool visibility arrives in Phase 7; the column is written now so a session carries the value across a restart.',field:"phase"},400);let d=ae(r,r.params.key??"");if(d!==void 0)return d;return await t.store.sessions.setPhase(t.id,r.params.key??"",u===null?void 0:u),y({phase:u})}),{capability:"write"}),p.add("GET","/v1/agents/:id/schedules",(r)=>_(e,r,async(t)=>{let a=r.url.searchParams.get("enabled"),s=await t.store.schedules.list(t.id,a===null?{}:{enabled:a==="true"});return y({schedules:s})}),{capability:"read"}),p.add("POST","/v1/agents/:id/schedules",(r)=>_(e,r,async(t)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);return Ne(e,t,a.value,void 0)}),{capability:"write"}),p.add("GET","/v1/agents/:id/schedules/:sid",(r)=>_(e,r,async(t)=>{let a=r.params.sid??"",s=await t.store.schedules.get(t.id,a);return s===void 0?H("schedule",a):y(s)}),{capability:"read"}),p.add("PATCH","/v1/agents/:id/schedules/:sid",(r)=>_(e,r,async(t)=>{let a=r.params.sid??"",s=await t.store.schedules.get(t.id,a);if(s===void 0)return H("schedule",a);let u=_e(s);if(u!==void 0)return u;let d=await M(r.request);if(d.kind==="error")return h(d.error,400);let g=d.value===null||typeof d.value!=="object"||Array.isArray(d.value)?{}:d.value,{id:v,...w}=g,R={kind:s.kind,expr:s.expr,task:s.task,deliver:s.deliverChannel===void 0||s.deliverTo===void 0?"none":{channel:s.deliverChannel,to:s.deliverTo},session:s.sessionMode,enabled:s.enabled,...s.timezone===void 0?{}:{timezone:s.timezone},...s.role===void 0?{}:{role:s.role},...w,id:s.id};return Ne(e,t,R,s)}),{capability:"write"}),p.add("DELETE","/v1/agents/:id/schedules/:sid",(r)=>_(e,r,async(t)=>{let a=r.params.sid??"",s=await t.store.schedules.get(t.id,a);if(s===void 0)return H("schedule",a);let u=_e(s);if(u!==void 0)return u;if(!await t.store.schedules.remove(t.id,a))return H("schedule",a);return e.scheduler.changed(),y({removed:a})}),{capability:"write"}),p.add("POST","/v1/agents/:id/schedules/:sid/run",(r)=>_(e,r,async(t)=>{let a=r.params.sid??"",s=await t.store.schedules.get(t.id,a);if(s===void 0)return H("schedule",a);let u=await t.admit();if(!u.ok)return h(u.error.toDetail(),429);let d=os(),g=ps(s.sessionMode,s.id,d),v=Zn();return e.streams.open(v),t.send(s.task,{admission:u,sessionKey:g,turnId:v,source:`schedule:${s.id}:manual`,...s.role===void 0?{}:{role:s.role}}).catch(()=>{}),y({scheduleId:s.id,turnId:v,sessionKey:g,outOfBand:!0},202)}),{capability:"write"}),p.add("GET","/v1/agents/:id/config",(r)=>_(e,r,async(t)=>{let a=e.sourceOf(t.id),s=typeof a==="string"?a:void 0,u=s===void 0?void 0:await St(s,"utf8");return y({...s===void 0?{editable:!1}:{editable:!0,file:s},settings:nt.filter((d)=>eo.includes(d.path)).map((d)=>({path:d.path,means:d.means,...d.confirm===void 0?{}:{confirm:d.confirm},...u===void 0?{}:{value:cs(u,d.path.split("."))}}))})}),{capability:"admin"}),p.add("PATCH","/v1/agents/:id/config",(r)=>_(e,r,async(t)=>{let a=await M(r.request);if(a.kind==="error")return h(a.error,400);let s=F(It,a.value);if(!s.ok)return h(s.error,400);let u=e.sourceOf(t.id);if(typeof u!=="string")return h({code:"config_not_editable",message:`"${t.id}" was loaded from an object, not from a file, so it has no manifest to change.`,hint:"An embedder holding new settings passes the new object to dispose() and adopt(). This route edits a manifest on disk."},409);let d=ls(s.value.path);if(d===void 0||!eo.includes(d.path))return h({code:"config_path_unknown",message:d?.via===void 0?`"${s.value.path}" is not a field this surface sets.`:`"${s.value.path}" is set by \`${d.via}\`, not by a dotted path.`,hint:d?.via===void 0?`GET /v1/agents/:id/config lists every one. Nearest: ${et(s.value.path,eo)??eo.join(", ")}.`:"It is a key inside a list entry, and the source editor matches a key at an indent — it cannot index a sequence. That action also validates the handle against the service that issues it.",field:"path"},400);if(d.confirm!==void 0&&s.value.confirm!==!0)return h({code:"config_confirm_required",message:d.confirm,hint:'Send { "confirm": true } beside the value to make this change anyway. Nothing has been written.',field:"confirm"},409);let g;try{g=await Xn({file:u,path:d.path.split("."),value:$n(s.value.value),providers:e.toolProviderFactories,mediaProviders:e.mediaProviderFactories})}catch(w){if(x(w))return h(w.toDetail(),400);throw w}let v;try{v=$e(await e.reload(t.id))}catch(w){if(!x(w))throw w;v=w.toDetail()}return y({path:d.path,before:g.before,after:g.after,reflowed:g.reflowed,...v===void 0?{applied:!0}:{applied:!1,pending:v}})}),{capability:"admin"}),p.add("PATCH","/v1/agents/:id/channels/:channelId",(r)=>_(e,r,async(t)=>{let a=n.channels;if(a===void 0)return h({code:"channels_not_supported",message:"This server cannot change a channel.",hint:"The host did not supply the channel actions — a library caller embedding this handler has to pass them. `dispach serve` does."},501);let s=e.sourceOf(t.id);if(typeof s!=="string")return h({code:"config_not_editable",message:`Agent "${t.id}" was loaded from an object, so it has no manifest to edit.`,hint:"Only an agent loaded from a file can be changed here."},409);let u=await M(r.request);if(u.kind==="error")return h(u.error,400);let d=F(zt,u.value);if(!d.ok)return h(d.error,400);let{enabled:g,credential:v}=d.value;if(g===void 0&&v===void 0)return h({code:"channel_patch_empty",message:"Nothing to change.",hint:'Send { "enabled": true | false } to connect or disconnect it, { "credential": "…" } to set its token, or both.'},400);let w=r.params.channelId??"",R=[];try{if(v!==void 0)R.push(a.setCredential(s,w,v).note);if(g!==void 0)R.push((await a.setEnabled(s,w,g)).note)}catch(K){if(!x(K))throw K;return h(K.toDetail(),400)}let L;try{L=$e(await e.reload(t.id))}catch(K){if(!x(K))throw K;L=K.toDetail()}return y({channelId:w,notes:R,...L===void 0?{applied:!0}:{applied:!1,pending:L}})}),{capability:"admin"}),p.add("POST","/v1/agents/:id/channels/:channelId/unpair",(r)=>_(e,r,async(t)=>{let a=r.params.channelId??"",s=await e.channels.reset(t.id,a);if(s==="reset")return y({channelId:a,note:"Pairing forgotten. The channel offers a new code to scan; the old device may still be listed on the phone, which is the only place it can be removed.",restarted:!1});let u=n.channels,d=e.sourceOf(t.id);if(u===void 0||typeof d!=="string")return h({code:s==="unsupported"?"channel_has_no_pairing":"channel_unknown",message:s==="unsupported"?`Channel "${a}" stores no pairing.`:`Agent "${t.id}" has no channel "${a}" registered.`,hint:"Only a channel linked by scanning a code has one to forget. A credential somebody typed is changed with PATCH on this channel, and a channel is switched off with { enabled: false }.",field:"channelId"},s==="unsupported"?409:404);try{return y({channelId:a,...u.unpair(d,a),restarted:!1})}catch(g){if(!x(g))throw g;return h(g.toDetail(),g.code==="channel_unknown"?404:409)}}),{capability:"admin"}),p.add("GET","/v1/agents/:id/tools",(r)=>_(e,r,(t)=>{let a=t.manifest.phases,s=vr(a);return y(t.tools.specs().map((u)=>({slug:u.slug,summary:u.summary,mutating:u.mutating,trust:u.trust,...u.trustReason===void 0?{}:{trustReason:u.trustReason},provider:u.provider??"local",tags:u.tags,...s?{phases:ss(a,u)}:{}})))}),{capability:"read"}),p.add("GET","/v1/agents/:id/skills",(r)=>_(e,r,(t)=>{let a=t.skills;if(a===void 0)return y({skills:[],configured:!1});return y({configured:!0,maxActive:a.maxActive,threshold:a.threshold,cached:a.cached,skills:a.skills.map((s)=>({name:s.name,description:s.frontmatter.description,tokens:s.tokens,...s.frontmatter.whenNotToUse===void 0?{}:{whenNotToUse:s.frontmatter.whenNotToUse},scripts:s.scripts.map((u)=>u.slug)}))})}),{capability:"read"}),p.add("GET","/v1/agents/:id/context",(r)=>_(e,r,async(t)=>{let a=r.url.searchParams.get("sessionKey"),s=r.url.searchParams.get("input");return y(await t.previewContext({...a===null?{}:{sessionKey:a},...s===null?{}:{input:s}}))}),{capability:"read"}),p.add("POST","/v1/channels/:channelId/webhook/:agentId",async(r)=>{let t=await M(r.request);if(t.kind==="error")return h(t.error,400);let a={};r.request.headers.forEach((u,d)=>{a[d.toLowerCase()]=u});let s=await e.channels.handleWebhook(r.params.agentId??"",r.params.channelId??"",{body:t.value,headers:a});return new Response(s.detail??"",{status:s.status,headers:{"content-type":"text/plain; charset=utf-8"}})},{capability:"open"}),p.add("GET","/v1/events",(r)=>{let t=r.url.searchParams.get("agentId");if(t!==null&&!W(r.principal,t))return H("agent",t);let a=r.url.searchParams.get("types")?.split(",").filter(Boolean),s=r.url.searchParams.get("chunks")==="true",u=a?.includes("model.chunk")===!0,d=s||u,g=a?.filter((v)=>!FA.includes(v));if(g!==void 0&&g.length>0){let v=et(g[0]??"",FA);return h({code:"unknown_event_type",message:`No such event type: ${g.join(", ")}.`,hint:v===void 0?"The full catalogue is the event table in docs/04-SPEC-WIRE.md. Omit ?types= to receive every event.":`Did you mean "${v}"? The full catalogue is the event table in docs/04-SPEC-WIRE.md.`,field:"types"},400)}return be({...r.request.signal===void 0?{}:{signal:r.request.signal},start:({send:v})=>(v({event:"stream.subscribed",data:{agentId:t??null,types:a??null,chunks:d,...d&&!s?{implied:"types names model.chunk"}:{}}}),e.bus.on("*",(w)=>{if(t!==null&&w.agentId!==t)return;if(w.agentId!==void 0&&!W(r.principal,w.agentId))return;if(w.sessionKey!==void 0&&!ce(r.principal,w.sessionKey))return;if(a!==void 0&&a.length>0&&!a.includes(w.type))return;v({event:w.type,data:w})},{chunks:d}))})},{capability:"read",streaming:!0});let ne=async(r)=>{let t;try{t=new URL(r.url)}catch{return h({code:"bad_request_url",message:"The request URL could not be parsed.",hint:"This usually means the server was handed a relative URL. A handler mounted inside another framework needs an absolute request.url."},400)}let a=r.method.toUpperCase();if(a==="OPTIONS"){let v=p.match("OPTIONS",t.pathname);if(v.kind==="method"){let R=p.match("HEAD",t.pathname).kind==="method"&&rn(p,t.pathname),L=[...v.allowed,...v.allowed.includes("GET")&&!R?["HEAD"]:[],"OPTIONS"];return k(r,new Response(null,{status:204,headers:{allow:L.join(", "),...n.origin===void 0?{}:Bt(r,L)}}))}}if(a==="HEAD"){let v=p.match("GET",t.pathname);if(v.kind==="found"){if(v.streaming)return h({code:"method_not_allowed",message:`HEAD is not allowed on ${t.pathname}.`,hint:"This path answers with an open event stream. A HEAD would have to start one and then throw the body away, leaving a subscription nothing ever closes — so it is refused rather than leaked. Use GET, or GET /v1/health to check the server is up."},405,{allow:"GET, OPTIONS"});let w=j(r);if(w!==void 0)return w;let R=await z(r,t.pathname,v.capability);if(R instanceof Response)return R;let L=await Ae(v.handler,{request:r,url:t,params:v.params,principal:R});return k(r,new Response(null,{status:L.status,headers:L.headers}))}}let s=se(a,t.pathname);if(s!==void 0){let v=j(r);if(v!==void 0)return v;return k(r,await wt(r,t,s))}let u=p.match(a,t.pathname);if(u.kind==="method")return h({code:"method_not_allowed",message:`${a} is not allowed on ${t.pathname}.`,hint:`This path accepts ${u.allowed.join(", ")}.`},405,{allow:u.allowed.join(", ")});if(u.kind==="none")return je(r.method,t.pathname);let d=j(r);if(d!==void 0)return d;let g=await z(r,t.pathname,u.capability);if(g instanceof Response)return g;return k(r,await Ae(u.handler,{request:r,url:t,params:u.params,principal:g}))},se=(r,t)=>{let a=/^\/v1\/agents\/([^/]+)\/plugins\/([^/]+)(\/.*)?$/.exec(t);if(a!==null){let u=e.list().find((w)=>w.id===decodeURIComponent(a[1]??"")),d=a[2]??"",g=a[3]??"/",v=u?.pluginRoutes.find((w)=>w.plugin===d&&w.method===r&&w.path===g);return u===void 0||v===void 0?void 0:{agent:u,route:v,path:g}}let s=e.list().flatMap((u)=>u.pluginRoutes.filter((d)=>d.root===t&&d.method===r).map((d)=>({agent:u,route:d,path:d.path})));return s.length===1?s[0]:void 0},wt=async(r,t,a)=>{let{agent:s,route:u,path:d}=a,g=u.capability==="open"?{kind:"open"}:await z(r,t.pathname,u.capability);if(g instanceof Response)return g;if(g.kind==="claim"||!W(g,s.id))return je(r.method,t.pathname);let v=g.kind==="key"?{kind:"key",keyId:g.keyId,label:g.label??""}:u.capability==="open"?{kind:"anonymous"}:{kind:"operator"};try{return await u.handler({request:r,url:t,path:d,caller:v})}catch(w){return h({code:"plugin_route_failed",message:`Plugin "${u.plugin}" failed answering ${r.method} ${t.pathname}: ${w instanceof Error?w.message:String(w)}`,hint:"This is the plugin's error, not the runtime's. The agent's own routes are unaffected."},500)}};return Object.assign(ne,{authenticate:(r)=>z(r,"/v1/ws","read")})}function _e(n){if(n.origin!=="manifest")return;return h({code:"schedule_manifest_owned",message:`Schedule "${n.id}" is declared in this agent's manifest, so the manifest decides it.`,hint:"Writing it here would last until the next start — reconciliation restores every field from the file, enabled included. Change the `schedules:` entry instead, with PATCH /v1/agents/:id/config, or create a separate schedule through this route."},409)}async function Ne(n,e,l,f){if(l===null||typeof l!=="object"||Array.isArray(l))return h({code:"schedule_invalid",message:"A schedule must be a JSON object.",hint:"Send { id, kind, expr, task, deliver } — see docs/02-SPEC-MANIFEST.md."},400);try{let c=fs({agentId:e.id,body:l,channelIds:e.manifest.channels.map((b)=>b.id),roleNames:Object.keys(e.manifest.model),now:Date.now(),origin:"api",...f===void 0?{}:{existing:f}}),m=await e.store.schedules.upsert(c);return n.scheduler.changed(),y(m,f===void 0?201:200)}catch(c){let m=x(c)?c.toDetail():{code:"schedule_invalid",message:c instanceof Error?c.message:String(c),hint:"See docs/02-SPEC-MANIFEST.md for the schedule fields."};return h(m,400)}}function ye(n,e){let l=Qt(n,e.request);if(l===void 0)throw new te({code:"web_asset_missing",message:`No web asset for ${n}.`,hint:"The routes in handler.ts and the table in web.ts have diverged, which spec.test.ts asserts cannot happen — so this build is inconsistent. Rebuild with `bun run build`."});return l}function y(n,e=200){return new Response(JSON.stringify(n),{status:e,headers:{"content-type":"application/json; charset=utf-8"}})}function nn(n){return n==="/v1/health"||n==="/v1/ready"||n.startsWith("/v1/channels/")||Vt.includes(n)||n==="/docs"||n==="/v1/openapi.json"}function rn(n,e){let l=n.match("GET",e);return l.kind==="found"&&l.streaming}async function Ae(n,e){try{return await n(e)}catch(l){if(x(l))return h(l.toDetail(),400);return h({code:"internal_error",message:l instanceof Error?l.message:String(l),hint:"An unexpected failure in the server. The runtime's event stream carries what happened around it."},500)}}function je(n,e){return h({code:"not_found",message:`No route for ${n} ${e}.`,hint:"Every path is under /v1. See docs/04-SPEC-WIRE.md for the surface."},404)}function H(n,e,l){return h({code:`${n}_not_found`,message:`No ${n} "${e}".`,hint:l??"Check the id — it is case-sensitive, and a session key includes its channel segment."},404)}function an(n){let e=n.headers.get("authorization")??"";if(!e.startsWith("Bearer "))return;let l=e.slice(7);return l===""?void 0:l}function Pe(n,e,l){let f=l.params.id??"";if(!W(l.principal,f))return{kind:"response",response:H("agent",f)};let c=e.secrets;if(c===void 0)return{kind:"response",response:h({code:"secrets_not_supported",message:"This server cannot write an agent's credentials.",hint:"Credentials go into the .env beside an agent's manifest, and this process was built without a writer for it. Set them where the agent lives, with `config env`, and reload it."},501)};let m=n.sourceOf(f),b=typeof m==="string"?m:e.resolveAgent?.(f);if(b===void 0)return{kind:"response",response:H("agent",f)};return{kind:"found",id:f,manifestPath:b,admin:c}}function Ie(n){return{...n,failing:n.consecutiveFailures>0}}function ze(n,e){let l=oe(n);if(l.agentIds!==void 0){let f=e.scope?.agents;if(f===void 0||!f.every((c)=>l.agentIds?.includes(c)))return!1}if(l.sessionPrefix!==void 0){let f=e.scope?.sessionPrefix;if(f===void 0||!f.startsWith(l.sessionPrefix))return!1}return!0}function Oe(n,e){let l=n.searchParams.get(e);if(l===null)return;let f=Number(l);return Number.isSafeInteger(f)&&f>0?f:null}function Re(n){let e=n.searchParams.get("by"),l=e===null?["agent","model"]:e.split(",").filter((m)=>m!==""),f=l.filter((m)=>!Ur.includes(m));if(f.length>0)return{kind:"error",error:{code:"usage_group_invalid",message:`Cannot group usage by ${f.join(", ")}.`,hint:`Group by any of ${Ur.join(", ")}, comma-separated, or pass by= for one total.`,field:"by"}};let c={};for(let m of["from","to"]){let b=n.searchParams.get(m);if(b===null)continue;let E=Date.parse(b);if(Number.isNaN(E))return{kind:"error",error:{code:"usage_range_invalid",message:`${m} is ${JSON.stringify(b)}, which is not a date.`,hint:"Send ISO-8601, like 2026-09-01 or 2026-09-01T00:00:00Z. `from` is inclusive and `to` exclusive, so a month is from=2026-09-01&to=2026-10-01.",field:m}};c[m]=new Date(E).toISOString()}return{kind:"ok",value:{by:l,...c}}}function _(n,e,l){let f=e.params.id??"",c=n.list().find((m)=>m.id===f);if(c===void 0)return H("agent",f);if(!W(e.principal,f))return H("agent",f);return l(c)}function on(n,e){if(!pt(n))return e;return e.filter((l)=>W(n,l.id))}function sn(n,e){if(!pt(n))return e;return e.filter((l)=>ce(n,l.sessionKey))}function ae(n,e){return ce(n.principal,e)?void 0:H("session",e)}function Le(n,e){let l=e.manifest.phases,f=vr(l);return{id:e.id,name:e.manifest.name??e.id,status:"loaded",model:e.manifest.model.main.id,channels:e.manifest.channels.map((c)=>{let m=n.channels.statusOf(e.id).find((E)=>E.id===c.id),b=typeof c.tokenEnv==="string"?c.tokenEnv:void 0;return{...m??{},id:c.id,type:c.type,enabled:c.enabled,...b===void 0?{}:{credentialEnv:b,credentialSet:e.hasEnv(b)}}}),entryPhase:f?is(l)??null:null,...f?{phases:Object.keys(l)}:{}}}function ve(n){return{...n.disabledAt===void 0?{}:{disabledAt:n.disabledAt},...n.reason===void 0?{}:{reason:n.reason}}}async function M(n,e=Yt){let l=Number.parseInt(n.headers.get("content-length")??"0",10);if(Number.isFinite(l)&&l>e)return{kind:"error",error:{code:"body_too_large",message:`The request body declares ${l} bytes; the limit is ${e}.`,hint:"This cap is enforced before a channel plugin sees anything, so a plugin never has to defend against a large POST."}};let f=await n.text();if(f.length>e)return{kind:"error",error:{code:"body_too_large",message:`The request body is ${f.length} bytes; the limit is ${e}.`,hint:"Send less. A message longer than this is not a message."}};if(f==="")return{kind:"ok",value:{}};try{return{kind:"ok",value:JSON.parse(f)}}catch(c){return{kind:"error",error:{code:"body_not_json",message:`The request body is not valid JSON: ${c instanceof Error?c.message:String(c)}`,hint:"Send application/json. A shell quoting mistake is the usual cause — check for unescaped quotes inside the payload."}}}}function ln(n){if(n===void 0||n===null)return{kind:"ok",from:void 0};let e=(f,c,m="from")=>({kind:"error",error:{code:"sender_invalid",message:f,hint:c,field:m}});if(typeof n!=="object")return e("from must be an object.",'Send { "from": { "id": "agent:ops-bot", "kind": "agent" } }, or omit it entirely for a turn the token-holder is sending itself.');let l=n;if(typeof l.id!=="string"||l.id.trim()==="")return e("from.id is required and must be a non-empty string.","Use a stable identity in your own namespace — `agent:ops-bot`, `user:018f…`, an email address. It is opaque to this runtime and is recorded on the turn so an audit can answer who asked.","from.id");if(l.id.length>Ce)return e(`from.id is ${l.id.length} characters, over the ${Ce} limit.`,"A sender id is an identifier, not a payload. It is rendered into the prompt's fence label, so an unbounded one spends the context window the message needs.","from.id");if(typeof l.kind!=="string"||!At.includes(l.kind)){let f=typeof l.kind==="string"?et(l.kind,At):void 0;return e(`from.kind must be one of: ${At.join(", ")}.`,`${f===void 0?"":`Did you mean "${f}"? `}This field decides the trust boundary — "agent" fences the message and blocks mutating tools for the turn, "user" does not — so there is no default and an unknown value is refused rather than guessed at. A turn the token-holder is sending itself omits "from".`,"from.kind")}if(l.name!==void 0&&typeof l.name!=="string")return e("from.name must be a string when present.","It is a display name only and is rendered inside the fence, never above it. Omit it if you have none.","from.name");return{kind:"ok",from:{id:l.id,kind:l.kind,...l.name===void 0?{}:{name:l.name.slice(0,Xt)}}}}function un(n){let e=n.headers.get("idempotency-key");if(e===null)return{kind:"ok",key:void 0};let l=e.trim(),f=(c)=>({kind:"error",error:{code:"idempotency_key_invalid",message:c,hint:`Send 1-${ge} printable ASCII characters that are unique per logical request — a UUID is the usual choice. Omit the header entirely to accept that a retry runs the turn again. Printable ASCII because the key is a database key, and node:sqlite truncates a bound string at a NUL byte where bun:sqlite stores it whole.`,field:"Idempotency-Key"}});if(l==="")return f("Idempotency-Key is present but empty.");if(l.length>ge)return f(`Idempotency-Key is ${l.length} characters, over the ${ge} limit.`);if(!/^[\x20-\x7e]+$/.test(l))return f("Idempotency-Key contains characters that are not printable ASCII.");return{kind:"ok",key:l}}async function cn(n,e){let l=new TextEncoder().encode(`${n}\x00${e}`),f=await crypto.subtle.digest("SHA-256",l);return Array.from(new Uint8Array(f)).map((c)=>c.toString(16).padStart(2,"0")).join("")}function dn(n){if(n===void 0||n===null||n==="none")return{kind:"ok",target:void 0};if(typeof n==="object"){let e=n;if(typeof e.channel==="string"&&typeof e.to==="string")return{kind:"ok",target:{channel:e.channel,to:e.to}}}return{kind:"error",error:{code:"deliver_invalid",message:'deliver must be "none" or { channel, to }.',hint:'A bare channel id is not enough on an API turn: the request has no originating conversation, so there is no recipient to infer. Send { "channel": "tg", "to": "12345" }, or "none" to read the reply from the event stream.',field:"deliver"}}}function fn(n){let e=n.status==="running";return be({start:({send:l,close:f})=>{l({event:e?"stream.unavailable":"stream.ended",data:{turnId:n.turnId,status:n.status,sessionKey:n.sessionKey,...e?{reason:"no buffer for this turn in this process",hint:"The turn is recorded as running but is not observable here — its events are buffered in whichever process is executing it, and buffers are in-memory and per-process. Poll GET /v1/agents/:id/turns/:turnId for the outcome."}:{steps:n.steps,...n.errorCode===void 0?{}:{errorCode:n.errorCode},hint:"This turn finished before you attached and its buffer has been evicted. Its full text is in GET /v1/agents/:id/turns/:turnId."}}}),f();return}})}function De(n,e,l){return be({...l?.status===void 0?{}:{status:l.status},start:({send:f,close:c})=>{if(l?.accepted!==void 0)f({event:"turn.accepted",data:l.accepted});let m=n.streams.attach(e,(b)=>{if(f({event:b.type,data:b}),b.type==="turn.end")c()},{chunks:l?.chunks===!0});if(m===void 0){f({event:"stream.unavailable",data:{turnId:e,reason:"no buffer for this turn in this process",hint:"Read the final state from GET /v1/agents/:id/turns/:turnId. Buffers are in-memory and are evicted after a turn ends."}}),c();return}f({event:"stream.replay",data:{turnId:e,state:m.state,events:m.replay.length,truncated:m.truncated,dropped:m.dropped,chunks:m.chunks,...m.truncated?{hint:`The oldest ${m.dropped} event(s) of this turn were discarded to stay under the buffer cap, so this replay starts mid-turn. The turn's final text is complete in GET /v1/agents/:id/turns/:turnId.`}:{}}});for(let b of m.replay)f({event:b.type,data:b});if(m.state==="ended")c();return()=>m.unsubscribe()}})}function $e(n){if(n.status!=="pending")return;return{code:"reload_pending",message:`It applies when the ${n.running} running turn(s) finish; they complete on the settings they started with.`,hint:`New turns keep the old settings for ${n.holdAfterMs} ms, then wait and start on the new ones. The agent.reloaded event says when it is in force.`}}function Gi(){let n=gr(),e=!1;return{token:n,live:()=>!e,spend:()=>{if(e)return!1;return e=!0,!0}}}function en(n){let e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n,l=e==="0.0.0.0"||e==="::"||e===""?"127.0.0.1":e;return l.includes(":")?`[${l}]`:l}function Fi(n,e,l){return`http://${en(n)}:${e}/?claim=${l}`}function Ui(n,e,l){return`curl -sX POST http://${en(n)}:${e}/v1/keys -H 'Authorization: Bearer ${l}' -H 'content-type: application/json' -d '{"label":"my browser"}'`}function bt(n,e,l=new Map){let f=new Set,c,m=0,b,E=(k)=>{let q=k.type==="model.chunk";for(let N of f){if(N.data.agentId!==void 0&&k.agentId!==N.data.agentId)continue;if(k.agentId!==void 0&&!W(N.data.principal,k.agentId))continue;if(k.sessionKey!==void 0&&!ce(N.data.principal,k.sessionKey))continue;if(q&&!N.data.chunks)continue;try{N.send(JSON.stringify(k))}catch{}}},V=()=>{if(m+=1,b===void 0)b=n.bus.on("model.chunk",E)},j=()=>{if(m===0)return;if(m-=1,m===0)b?.(),b=void 0};return{async accept(k){let q=new URL(k.url),N=Ct(k),z=q.searchParams.get("token"),A=await e(_t(k,N??z??""));if(A instanceof Response)return{kind:"reject",response:A};let B=q.searchParams.get("agentId");if(B!==null&&!W(A,B))return{kind:"reject",response:new Response(JSON.stringify({error:{code:"agent_not_found",message:`No agent "${B}".`,hint:"Check the id — it is case-sensitive. A key scoped away from an agent sees exactly what a caller asking for one that does not exist sees."}}),{status:404,headers:{"content-type":"application/json"}})};return{kind:"accept",session:{agentId:B??void 0,chunks:q.searchParams.get("chunks")==="true",principal:A},...N===void 0?{}:{protocol:Ue}}},handlers:{open(k){if(f.add(k),c===void 0)c=n.bus.on("*",E);if(k.data.chunks)V();k.send(JSON.stringify({type:"ws.open",agentId:k.data.agentId??null,chunks:k.data.chunks}))},message(k,q){let N;try{N=JSON.parse(typeof q==="string"?q:new TextDecoder().decode(q))}catch{k.send(JSON.stringify({type:"ws.error",code:"frame_not_json"}));return}if(N.type==="ping"){k.send(JSON.stringify({type:"pong"}));return}if(N.type==="subscribe"){if(N.agentId===void 0&&N.sessionKey!==void 0){k.send(JSON.stringify({type:"ws.error",code:"subscribe_needs_agent_id",hint:"Send { type: 'subscribe', agentId: '<agent>' }. A socket filters on the agent an event carries; sessionKey names a conversation and can never match one, so a socket pointed with it receives nothing."}));return}let O=typeof N.chunks==="boolean"?N.chunks:k.data.chunks;if(O&&!k.data.chunks)V();else if(!O&&k.data.chunks)j();let D=N.agentId??k.data.agentId;if(D!==void 0&&!W(k.data.principal,D)){k.send(JSON.stringify({type:"ws.error",error:{code:"agent_not_found",message:`No agent "${D}".`,hint:"Check the id — it is case-sensitive. A key scoped away from an agent sees exactly what a caller asking for one that does not exist sees."}}));return}k.data={agentId:D,chunks:O,principal:k.data.principal},k.send(JSON.stringify({type:"ws.subscribed",agentId:k.data.agentId??null,chunks:k.data.chunks}));return}if(N.type==="stop"){let O=N.turnId===void 0?void 0:l.get(N.turnId);O?.abort(),k.send(JSON.stringify({type:"ws.stopping",turnId:N.turnId??null,found:O!==void 0}));return}if(N.type!=="message"){k.send(JSON.stringify({type:"ws.error",code:"unknown_frame_type"}));return}let z=k.data.agentId,p=n.list().find((O)=>O.id===z);if(p===void 0){k.send(JSON.stringify({type:"ws.error",code:"agent_not_found"}));return}let A=N.text??"";if(A.trim()===""){k.send(JSON.stringify({type:"ws.error",code:"message_text_required"}));return}let B=mt(k.data.principal,void 0),J=B.ok?B.from:void 0,G=(O)=>{if(!O.ok){k.send(JSON.stringify({type:"ws.error",...O.error.toDetail()}));return}let D=Zn(),ne=new AbortController;l.set(D,ne),k.send(JSON.stringify({type:"ws.accepted",turnId:D})),p.send(A,{admission:O,sessionKey:N.sessionKey??"api:default",turnId:D,source:"ws",...J===void 0?{}:{from:J},signal:ne.signal}).catch(()=>{}).finally(()=>l.delete(D))},C=p.admitNow();if(C!==void 0){G(C);return}p.admit().then(G,(O)=>{k.send(JSON.stringify({type:"ws.error",code:"internal_error",message:O instanceof Error?O.message:String(O)}))})},close(k){if(f.delete(k)&&k.data.chunks)j();if(f.size===0)c?.(),c=void 0}},closeAll(){for(let k of f)try{k.close(1001,"server stopping")}catch{}f.clear(),c?.(),c=void 0,b?.(),b=void 0,m=0}}}async function xi(n){let{host:e,port:l,runtime:f}=n;if(!le(e)&&n.token===void 0)throw new te({code:"server_public_without_token",message:`Refusing to bind ${e}:${l} with no API token.`,hint:"Set the variable named by server.tokenEnv, or bind 127.0.0.1. A public bind with no token exposes every endpoint — including the ones that start a turn — to anyone who can reach the port, and behaves identically to a safe one until someone finds it.",field:"server.host"});let c=new Map,m=tn({runtime:f,...n.token===void 0?{}:{token:n.token},...n.token===void 0?{allowUnauthenticated:!0}:{},...n.now===void 0?{}:{now:n.now},running:c,...n.approvals===void 0?{}:{approvals:n.approvals},...n.claim===void 0?{}:{claim:n.claim},...n.resolveAgent===void 0?{}:{resolveAgent:n.resolveAgent},...n.provision===void 0?{}:{provision:n.provision},...n.channels===void 0?{}:{channels:n.channels},...n.remover===void 0?{}:{remover:n.remover},...n.secrets===void 0?{}:{secrets:n.secrets},origin:{host:n.host,...n.allowedOrigins===void 0?{}:{allowedOrigins:n.allowedOrigins},...n.allowedHosts===void 0?{}:{allowedHosts:n.allowedHosts}}});if(n.engine==="bun"||n.engine===void 0&&typeof Bun<"u"&&typeof Bun.serve==="function")return hn(m,n,c);return pn(m,n,c)}function hn(n,e,l){let f=bt(e.runtime,n.authenticate,l),c=Bun.serve({port:e.port,hostname:e.host,idleTimeout:Math.min(255,Math.ceil(yt/1000*3)),fetch:async(m,b)=>{if(new URL(m.url).pathname!=="/v1/ws")return n(m);let V=ue(m,{host:e.host,...e.allowedOrigins===void 0?{}:{allowedOrigins:e.allowedOrigins},...e.allowedHosts===void 0?{}:{allowedHosts:e.allowedHosts}});if(V!==void 0)return new Response(JSON.stringify({error:V}),{status:403,headers:{"content-type":"application/json; charset=utf-8"}});let j=await f.accept(m);if(j.kind==="reject")return j.response;if(b.upgrade(m,{data:j.session,...j.protocol===void 0?{}:{headers:{"sec-websocket-protocol":j.protocol}}}))return;return new Response("upgrade failed",{status:400})},websocket:{open:(m)=>f.handlers.open(m),message:(m,b)=>f.handlers.message(m,b),close:(m)=>f.handlers.close(m)}});return{url:`http://${e.host}:${c.port}`,port:c.port??e.port,host:e.host,websocket:!0,stop:async()=>{f.closeAll(),await c.stop(!0)}}}async function pn(n,e,l){let{createServer:f}=await import("node:http"),{WebSocketServer:c}=await import("./wrapper-rgk1asmr.js"),m=bt(e.runtime,n.authenticate,l),b=(z,p)=>{let A=`http://${z.headers.host??`${e.host}:${e.port}`}${z.url??"/"}`,B=new Headers;for(let[G,C]of Object.entries(z.headers))if(typeof C==="string")B.set(G,C);else if(Array.isArray(C))B.set(G,C.join(", "));let J=z.method??"GET";return new Request(A,{method:J,headers:B,...J==="GET"||J==="HEAD"||p===void 0?{}:{body:p}})},E=f((z,p)=>{(async()=>{let A=[];for await(let C of z)A.push(C);let B=await n(b(z,Buffer.concat(A))),J={};if(B.headers.forEach((C,O)=>{J[O]=C}),p.writeHead(B.status,J),B.body===null){p.end();return}let G=B.body.getReader();p.on("close",()=>void G.cancel().catch(()=>{}));for(;;){let{done:C,value:O}=await G.read();if(C)break;p.write(Buffer.from(O))}p.end()})().catch(()=>{if(!p.headersSent)p.writeHead(500);p.end()})}),V=new WeakMap,j=new c({noServer:!0,handleProtocols:(z,p)=>V.get(p)??!1}),k=(z,p,A)=>{z.end(`HTTP/1.1 ${p} Refused\r
|
|
82
82
|
content-type: application/json; charset=utf-8\r
|
|
83
|
-
content-length: ${Buffer.byteLength(
|
|
83
|
+
content-length: ${Buffer.byteLength(A)}\r
|
|
84
84
|
connection: close\r
|
|
85
85
|
\r
|
|
86
|
-
${
|
|
87
|
-
export{_r,
|
|
86
|
+
${A}`)};E.on("upgrade",(z,p,A)=>{(async()=>{let B=b(z);if(new URL(B.url).pathname!=="/v1/ws"){p.destroy();return}let J=ue(B,{host:e.host,...e.allowedOrigins===void 0?{}:{allowedOrigins:e.allowedOrigins},...e.allowedHosts===void 0?{}:{allowedHosts:e.allowedHosts}});if(J!==void 0){k(p,403,JSON.stringify({error:J}));return}let G=await m.accept(B);if(G.kind==="reject"){k(p,G.response.status,await G.response.text());return}if(G.protocol!==void 0)V.set(z,G.protocol);j.handleUpgrade(z,p,A,(C)=>{let O={data:G.session,send:(D)=>C.send(D),close:(D,ne)=>C.close(D,ne)};C.on("message",(D,ne)=>{let se=Array.isArray(D)?Buffer.concat(D):D instanceof ArrayBuffer?Buffer.from(D):D;m.handlers.message(O,ne?new Uint8Array(se):se.toString("utf8"))}),C.on("close",()=>m.handlers.close(O)),m.handlers.open(O)})})().catch(()=>p.destroy())}),await new Promise((z,p)=>{E.once("error",p),E.listen(e.port,e.host,()=>{E.removeListener("error",p),z()})});let q=E.address(),N=typeof q==="object"&&q!==null?q.port:e.port;return{url:`http://${e.host}:${N}`,port:N,host:e.host,websocket:!0,stop:()=>new Promise((z)=>{m.closeAll(),j.close(),E.closeAllConnections?.(),E.close(()=>z())})}}function zA(n,e){let l=new URL(n);if(l.pathname="/",l.hostname=en(l.hostname),e!==void 0&&e!=="")l.searchParams.set("agent",e);return l.toString()}
|
|
87
|
+
export{_r,Gi,en,Fi,Ui,xi,zA};
|
|
88
88
|
|
|
89
|
-
//# debugId=
|
|
90
|
-
//# sourceMappingURL=index-
|
|
89
|
+
//# debugId=0929511F836B7F6164756E2164756E21
|
|
90
|
+
//# sourceMappingURL=index-2c264w09.js.map
|