@tansr/cli 0.10.0 → 0.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/tansr-artifacts.json +596 -578
- package/{tansr-bg-FHDDUMK4.mjs → tansr-bg-QY4G2SNZ.mjs} +2 -2
- package/{tansr-chunk-6NUB6YQJ.mjs → tansr-chunk-2C6JKHKM.mjs} +5 -5
- package/{tansr-chunk-O32ZFMNV.mjs → tansr-chunk-53SL6W6G.mjs} +2 -2
- package/{tansr-chunk-RS3LZ6KA.mjs → tansr-chunk-5T7X32UX.mjs} +2 -2
- package/{tansr-chunk-5YXIDPAQ.mjs → tansr-chunk-6OXR4F5Y.mjs} +2 -2
- package/{tansr-chunk-PQNOMC4A.mjs → tansr-chunk-726Y5F3M.mjs} +2 -2
- package/{tansr-chunk-UIBBDNRB.mjs → tansr-chunk-BCOFZJWA.mjs} +2 -2
- package/{tansr-chunk-WT5YKFE7.mjs → tansr-chunk-C6COFFZK.mjs} +2 -2
- package/{tansr-chunk-4OSB7HBB.mjs → tansr-chunk-CI7LFRTK.mjs} +3 -3
- package/{tansr-chunk-ZGQJIXK7.mjs → tansr-chunk-E67N3BDI.mjs} +2 -2
- package/{tansr-chunk-Z6RSXE57.mjs → tansr-chunk-H6JYYWPW.mjs} +10 -10
- package/{tansr-chunk-VJGAX34A.mjs → tansr-chunk-J2ED6CI4.mjs} +2 -2
- package/{tansr-chunk-2HKJ4JJS.mjs → tansr-chunk-J72JGEKH.mjs} +3 -3
- package/{tansr-chunk-MX3N5PNJ.mjs → tansr-chunk-KSBP64Q5.mjs} +2 -2
- package/tansr-chunk-LSYPDTQG.mjs +22 -0
- package/tansr-chunk-NA22YT73.mjs +5 -0
- package/{tansr-chunk-MKOKKJTO.mjs → tansr-chunk-NCIMR6LB.mjs} +2 -2
- package/tansr-chunk-OB47UYHK.mjs +29 -0
- package/{tansr-chunk-JOAFKQNW.mjs → tansr-chunk-OSK64SU3.mjs} +1 -1
- package/{tansr-chunk-Y4DBYZRC.mjs → tansr-chunk-Q6MUMULP.mjs} +2 -2
- package/{tansr-chunk-YOQS3FJQ.mjs → tansr-chunk-QNHXB55W.mjs} +2 -2
- package/{tansr-chunk-2GVQN2VL.mjs → tansr-chunk-S77B4PI7.mjs} +2 -2
- package/{tansr-chunk-B3GJDJ7R.mjs → tansr-chunk-TYJWMSVW.mjs} +2 -2
- package/tansr-chunk-TZJHQ3TT.mjs +38 -0
- package/{tansr-chunk-A5EC3Z2Z.mjs → tansr-chunk-UAEARRRH.mjs} +2 -2
- package/{tansr-chunk-XAR42OOH.mjs → tansr-chunk-UCG4D6ER.mjs} +2 -2
- package/{tansr-chunk-NKZP22Y6.mjs → tansr-chunk-WGXWBU37.mjs} +2 -2
- package/{tansr-chunk-T2BVA5NV.mjs → tansr-chunk-ZY3IR67Q.mjs} +2 -2
- package/tansr-main-5V46X7QH.mjs +7 -0
- package/tansr-marked.esm-R6UL3675.mjs +68 -0
- package/{tansr-render-RTEKXH54.mjs → tansr-render-PUEISX75.mjs} +2 -2
- package/{tansr-run-acp-entry-OYTDDWDR.mjs → tansr-run-acp-entry-ANNUR7IB.mjs} +3 -3
- package/{tansr-run-approvals-entry-53SR25ZU.mjs → tansr-run-approvals-entry-SLLTFTSX.mjs} +2 -2
- package/{tansr-run-auth-entry-QFMRITYM.mjs → tansr-run-auth-entry-X3SXNPOI.mjs} +2 -2
- package/{tansr-run-doctor-DO6CXMRK.mjs → tansr-run-doctor-RYIQQOOK.mjs} +3 -3
- package/{tansr-run-headless-entry-7TNISK4Y.mjs → tansr-run-headless-entry-I53HJDNX.mjs} +2 -2
- package/tansr-run-init-entry-USPWKDRI.mjs +5 -0
- package/tansr-run-logout-entry-KO7ZL2M5.mjs +5 -0
- package/{tansr-run-mcp-serve-entry-M5N7JSAX.mjs → tansr-run-mcp-serve-entry-YMQH7WSF.mjs} +2 -2
- package/{tansr-run-orchestrate-entry-MFDKPE4I.mjs → tansr-run-orchestrate-entry-YN3M6BWY.mjs} +2 -2
- package/{tansr-run-org-entry-TGWBHE55.mjs → tansr-run-org-entry-STRRZVI4.mjs} +2 -2
- package/{tansr-run-policy-entry-E3XZEYGV.mjs → tansr-run-policy-entry-4ENHRAMQ.mjs} +2 -2
- package/{tansr-run-profile-entry-R2KK52TF.mjs → tansr-run-profile-entry-THJMZ7ZA.mjs} +2 -2
- package/tansr-run-serve-entry-N5PK7ACI.mjs +99 -0
- package/{tansr-run-sessions-entry-PZQIF7KY.mjs → tansr-run-sessions-entry-KIT7PALM.mjs} +2 -2
- package/tansr-run-update-entry-HYSKHBB6.mjs +5 -0
- package/tansr-src-JAODAP53.mjs +143 -0
- package/{tansr-startup-account-WI54Z7UU.mjs → tansr-startup-account-QUJKOV6V.mjs} +4 -4
- package/{tansr-startup-model-2MIOO25G.mjs → tansr-startup-model-SREG5HNN.mjs} +3 -3
- package/tansr-tui-DXGFMSII.mjs +75 -0
- package/tansr.mjs +1 -2
- package/tansrd.mjs +265 -265
- package/tansr-chunk-G5YDZOSH.mjs +0 -38
- package/tansr-chunk-IHFZ4MW7.mjs +0 -5
- package/tansr-chunk-PQHOHOTR.mjs +0 -22
- package/tansr-chunk-WMHXOCGD.mjs +0 -29
- package/tansr-run-init-entry-EJ4UX6S7.mjs +0 -5
- package/tansr-run-logout-entry-YJMC6FYS.mjs +0 -5
- package/tansr-run-serve-entry-JVHHZEKM.mjs +0 -99
- package/tansr-run-update-entry-GOW6DQH3.mjs +0 -5
- package/tansr-src-NSNVE7OD.mjs +0 -206
- package/tansr-tui-LUXKR56D.mjs +0 -75
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
+
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
+
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
+
import{a as Bl}from"./tansr-chunk-MWHLITGY.mjs";import{$ as El,Aa as Ml,Ca as Ol,F as Sl,I as wl,J as So,K as ui,M as ei,O as kl,P as xl,S as Rl,X as Il,Y as rn,Z as Tl,_ as Al,aa as Js,ja as hh,la as Cl,oa as _l,v as mh,za as Pl}from"./tansr-chunk-BX7CF5RQ.mjs";import{a as gh}from"./tansr-chunk-QHEQQ2JB.mjs";import{Oa as nh,Ra as ih,Xa as rh,Ya as oh,i as th}from"./tansr-chunk-6OXR4F5Y.mjs";import{a as Zm}from"./tansr-chunk-Q6MUMULP.mjs";import{a as ae,b as sh,c as Xe,d as ah,e as dh,f as Bn,g as $n,h as Qs,i as ch,j as lh,k as uh,l as fh,w as ph}from"./tansr-chunk-H6JYYWPW.mjs";import{A as vl,B as bl,a as On,b as pl,c as fo,d as Gi,e as ml,f as hl,g as gl,h as Wi,j as yl,k as po,l as kr,m as eh,o as mo,p as ho,q as go,r as yo,s as vo,t as bo,u as pt}from"./tansr-chunk-LSYPDTQG.mjs";import{k as op}from"./tansr-chunk-HRKJLVKC.mjs";import{$ as Ip,$a as Ac,$c as Zc,Ac as sm,Bc as $c,Bd as Ws,Be as ol,C as yc,Cc as Kc,Db as oo,Dc as am,De as Bm,E as vc,Eb as Ps,Ee as Dm,Fb as _c,Fe as qm,Gb as Pc,Gc as dm,Gd as Im,Ge as jm,H as Sr,Ha as qp,Hb as Mc,Ib as Oc,Ic as cm,Ie as sl,J as bc,Jb as Bc,Jc as lm,Je as Nm,K as Sc,Kb as Dc,Kc as um,Ke as Um,L as wc,La as jp,Lb as qc,Lc as fm,Le as Lm,Ma as Np,Mb as jc,Mc as Qc,Me as Fm,N as io,Na as Up,Nb as Ms,Nc as pm,Nd as Tm,O as Li,Ob as Nc,Oc as mm,P as kc,Pb as Uc,Pc as Ns,Pd as Am,Pe as Hm,Q as xs,Qb as Lc,Qc as hm,Qd as Em,Rb as Fc,Rc as Us,Rd as Cm,Re as zm,Sb as Os,Sc as gm,Ta as Lp,Tb as Bs,Tc as Ls,U as kp,Ua as Vn,Ub as Hc,Uc as Jc,Va as Cs,Vb as so,Vc as Yc,W as xp,Wa as Tc,Wb as Jp,Wd as _m,We as al,X as Rs,Xa as _s,Ya as Fp,Yb as Ds,Ye as dl,Za as Hp,Zc as Xc,Ze as cl,_ as Is,_a as zp,_b as ao,a as pp,aa as Tp,ac as Yp,b as mp,ba as Ap,bb as In,c as hp,ca as Fi,cc as qs,cd as ym,cf as Ks,d as vn,da as Ep,dc as Xp,dd as Fs,e as Wn,ec as Zp,ed as vm,f as dc,fc as em,fd as bm,g as cc,gc as tm,gd as el,h as lc,hb as ro,hc as nm,i as Bt,ia as Rc,ic as zc,id as Sm,ja as Hi,jc as js,je as il,kb as Gp,kd as wm,ke as Vs,l as uc,la as Ic,le as Pm,m as Ui,mb as Ec,md as km,me as rl,n as fc,na as Cp,nb as Cc,nd as xm,ne as $s,o as ws,oa as _p,ob as Wp,oc as im,od as Rm,p as ks,pa as wi,pb as Vp,pc as rm,q as pc,qa as Ts,qb as $p,r as Sp,ra as As,rb as Kp,rd as Hs,s as mc,sa as Es,t as Gt,tc as Gc,td as zs,u as hc,ua as Pp,uc as Wc,va as Mp,vc as co,ve as Mm,wa as Op,wc as lo,x as Zt,xa as Bp,xd as Gs,y as li,yb as Qp,yc as Vc,yd as tl,z as gc,za as Dp,zc as om,zd as nl,ze as Om}from"./tansr-chunk-BCOFZJWA.mjs";import{A as Km,D as ul,E as fl,H as Qm,I as Jm,J as Ym,K as Xm,M as uo,c as Gm,d as Wm,e as zi,j as ll,o as Vm,t as Et,z as $m}from"./tansr-chunk-2C6JKHKM.mjs";import{a as hs,b as gs,c as sp,d as ap,e as dp,h as ys}from"./tansr-chunk-OKAA4BJC.mjs";import{a as nc,b as ic,p as rc,q as Gn,s as oc}from"./tansr-chunk-OSK64SU3.mjs";import{Fa as Rp,Ia as xc,Ma as wr,n as br,na as wp}from"./tansr-chunk-ZQ3ZK7IL.mjs";import{C as ac,N as he,O as ut,P as Mn,a as nn,c as Si,d as vp,k as bp,l as Ss,n as sc}from"./tansr-chunk-I3TOVAA6.mjs";import{c as bs,e as gp,f as yp}from"./tansr-chunk-F7C6ITED.mjs";import{a as vr,b as np,k as ip,m as We,o as rp}from"./tansr-chunk-NA22YT73.mjs";import{Ba as vs,Fb as lp,Ib as up,Jb as fp,a as Jd,c as r,d as cp,kb as Yd,lb as Xd,nb as Zd,pb as ec,rb as tc,ua as no}from"./tansr-chunk-QWGSXFEJ.mjs";import{c as Lb}from"./tansr-chunk-RRAMVVYF.mjs";import{createHash as Jb,randomUUID as Bh}from"node:crypto";import{createHash as Fb}from"node:crypto";import{mkdir as yh,open as Hb,readFile as vh,readdir as zb}from"node:fs/promises";import wo from"node:path";var bh=new WeakMap;function vT(t){bh.set(t,"sdk2-offload-v1")}function Vi(t){return bh.get(t)??"sdk1"}var ct=class extends Error{constructor(n){super(`SDK2 offload: ${n}`);this.code=n;this.name="OffloadSessionError"}code};function Ys(t,e){let n=t.sdk2SessionFamily;if(e===void 0?n!==void 0:n===void 0||he(n)!==he(e.marker))throw new ct("family_mismatch")}function bT(t,e,n,i){if(!wo.isAbsolute(t)||!["create","reopen"].includes(e)||[n.applicationScopeId,n.sourceId,n.sourceGeneration].some(u=>typeof u!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(u)))throw new ct("family_mismatch");let o=Object.freeze({...n}),s=wo.join(wo.resolve(t),"sdk2-offload-v1",Fb("sha256").update(n.applicationScopeId).digest("hex")),a=wo.join(s,"contract.json"),d=he(o),c=!1,l;return Object.freeze({directory:s,marker:o,checkRoot:async()=>{if(await i?.(),c||await(l??=(async()=>{if(e==="create"||i){await yh(wo.dirname(s),{recursive:!0});try{await yh(s)}catch(m){if(m.code!=="EEXIST")throw m}if((await zb(s)).length===0){let m=await Hb(a,"wx",384);try{await m.writeFile(d),await m.sync()}finally{await m.close()}}}let u;try{u=await vh(a,"utf8")}catch(m){throw m.code==="ENOENT"?new ct("family_missing"):m}if(u!==d)throw new ct("family_mismatch");c=!0})().catch(u=>{throw l=void 0,u})),await vh(a,"utf8")!==d)throw new ct("family_mismatch")}})}function ST(t,e,n,i){if(!t||!("capabilities"in t)||t.capabilities.consistency!=="strong"||!t.capabilities.conditionalPut||t.capabilities.list!=="prefix")throw new ct("source_mismatch");let o=he(n),s=ut(o),a=`sdk2-offload-v1/${s}/`,d=`${a}contract.json`,c=Buffer.from(o),l=p=>`${a}objects/${p}`,f,u=async()=>{await(f??=(async()=>{if(!await t.head(d)){if(i!=="create")throw new ct("family_missing");for await(let R of t.list(a))throw new ct("family_missing");try{await t.put(d,new ReadableStream({start(R){R.enqueue(c),R.close()}}),{bytes:c.length,contentType:"application/json",sha256:ut(o)},{ifNoneMatch:"*"})}catch(R){if(!(R instanceof Wn)||R.kind!=="precondition_failed")throw R}}})().catch(R=>{throw f=void 0,R}));let p=await t.head(d);if(!p)throw new ct("family_missing");if(p.bytes!==c.length||p.sha256!==ut(o))throw new ct("family_mismatch");let v=(await t.get(d)).getReader(),b=Buffer.alloc(0);try{for(;;){let R=await v.read();if(R.done)break;if(b.length+R.value.byteLength>c.length)throw new ct("family_mismatch");b=Buffer.concat([b,R.value])}}finally{await v.cancel().catch(()=>{}),v.releaseLock()}if(!b.equals(c))throw new ct("family_mismatch")},m={capabilities:t.capabilities,put:(p,v,b,R)=>t.put(l(p),v,b,R),get:(p,v,b)=>t.get(l(p),v,b),head:(p,v)=>t.head(l(p),v),async*list(p,v,b){let R=l("");for await(let w of t.list(l(p),v,b)){if(!w.key.startsWith(R))throw new ct("family_mismatch");yield{...w,key:w.key.slice(R.length)}}},delete:(p,v)=>t.delete(p.map(l),v)},g=p=>`sdk2-offload-v1:${s}:${p}`;return{cold:m,index:e&&{upsert:(p,v,b)=>e.upsert({...p,endUserKey:g(p.endUserKey)},v,b),async get(p,v){let b=await e.get(g(p),v);if(b&&b.endUserKey!==g(p))throw new ct("family_mismatch");return b&&{...b,endUserKey:p}},async*list(p,v){for await(let b of e.list(g(p),v)){if(b.endUserKey!==g(p))throw new ct("family_mismatch");yield{...b,endUserKey:p}}},remove:(p,v)=>e.remove(g(p),v)},check:u}}import{access as Yb,mkdir as Dh,readFile as Xb,readdir as Wl,rm as zl,stat as Vl}from"node:fs/promises";import{randomUUID as Sh}from"node:crypto";import{readFileSync as wh}from"node:fs";import{readFile as ko}from"node:fs/promises";import{hostname as Dl}from"node:os";var xr="serveOwner",Gb=5e3,Wb=3e5,Qt=class extends Error{constructor(n){super(`Session ownership: ${n}`);this.code=n;this.name="ServeSessionOwnershipError"}code},kh=new WeakMap;function Tn(t){throw new Qt(t)}function ql(t){let e=t[xr];if(e===void 0)return;(!e||typeof e!="object"||Array.isArray(e))&&Tn("owner_corrupted");let n=e;return(n.format!=="serve-owner-v1"||typeof n.ownerId!="string"||!n.ownerId||typeof n.claimId!="string"||!n.claimId||typeof n.host!="string"||!Number.isSafeInteger(n.attempt)||n.attempt<1||!Number.isSafeInteger(n.expiresAt)||!["idle","running"].includes(n.phase)||typeof n.released!="boolean")&&Tn("owner_corrupted"),n}function Rr(t,e,n){n.serveOwnerDeleted===!0&&Tn("owner_stale");let i=ql(n),o=e===void 0?void 0:kh.get(e);if(!i){e&&Tn("owner_stale");return}return e||Tn("owner_stale"),(!o||o.dir!==t||i.ownerId!==o.record.ownerId||i.claimId!==o.record.claimId||i.attempt!==o.record.attempt||i.host!==Dl()||i.released)&&Tn("owner_stale"),i}function xo(t,e,n){Rr(t,e,n??JSON.parse(wh(Zt(t),"utf8")))}function jl(t,e,n){let i=Rr(t,e,n);n[xr]={...i,expiresAt:Date.now()+e.leaseMs}}function Xs(t,e){let n=ql(e??JSON.parse(wh(Zt(t),"utf8")));n&&(!n.released||n.phase!=="idle")&&Tn("owner_stale")}async function $i(t,e){let n;for(let o=0;n===void 0;o++)try{n=await uc(t,{requireAtomicPublication:!0})}catch(s){if(o>=999||!(s instanceof Error)||!("code"in s)||s.code!=="SESSION_LOCKED")throw s;await new Promise(a=>setTimeout(a,5))}try{return await e()}finally{await n.release()}}async function xh(t,e,n=i=>i()){let i=e.leaseMs??3e4,o=e.ownerId??Sh();if(!Number.isSafeInteger(i)||i<Gb||i>Wb||!o||o.length>256)throw new TypeError("Invalid session ownership options");let s=await $i(t,async()=>{let c=JSON.parse(await ko(Zt(t),"utf8"));c.serveOwnerDeleted===!0&&Tn("owner_stale");let l=ql(c),f=Date.now();l?.host!==void 0&&l.host!==Dl()&&Tn("owner_busy"),l&&!l.released&&l.expiresAt>f&&Tn("owner_busy"),(l?.phase==="running"&&!(e.runtimeRecovery===!0&&c.serveRuntime!==void 0)||c.pendingRewrite===!0)&&Tn("reconciliation_required");let u=(l?.attempt??0)+1;Number.isSafeInteger(u)||Tn("owner_corrupted");let m={format:"serve-owner-v1",ownerId:o,claimId:Sh(),host:Dl(),attempt:u,expiresAt:f+i,phase:c.serveRuntime===void 0?"idle":"running",released:!1};return c[xr]=m,await li(Zt(t),JSON.stringify(c)+`
|
|
5
|
+
`),m}),a=c=>n(()=>$i(t,async()=>{let l=JSON.parse(await ko(Zt(t),"utf8")),f=Rr(t,d,l);l[xr]=c(f),await li(Zt(t),JSON.stringify(l)+`
|
|
6
|
+
`)})),d=Object.freeze({ownerId:o,attempt:s.attempt,leaseMs:i,assertCurrent(){xo(t,d)},assertIdle(){return n(()=>$i(t,async()=>{let c=JSON.parse(await ko(Zt(t),"utf8"));(Rr(t,d,c).phase!=="idle"||c.serveRuntime!==void 0||c.pendingRewrite===!0)&&Tn("reconciliation_required")}))},fence(c){return n(()=>$i(t,async()=>(d.assertCurrent(),{value:c()})))},write(c){return n(()=>$i(t,async()=>(d.assertCurrent(),await c())))},beginTurn(){return n(()=>$i(t,async()=>{let c=JSON.parse(await ko(Zt(t),"utf8")),l=Rr(t,d,c);c[xr]={...l,phase:"running",expiresAt:Date.now()+i},delete c.serveRuntime,await li(Zt(t),JSON.stringify(c)+`
|
|
7
|
+
`)}))},checkpoint(c){return n(()=>$i(t,async()=>{let l=JSON.parse(await ko(Zt(t),"utf8")),f=Rr(t,d,l);!c()||l.pendingRewrite===!0||l.historyTotal===void 0||(l[xr]={...f,phase:"idle",expiresAt:Date.now()+i},delete l.serveRuntime,await li(Zt(t),JSON.stringify(l)+`
|
|
8
|
+
`))}))},renew(){return a(c=>({...c,expiresAt:Date.now()+i}))},release(){return a(c=>({...c,released:!0}))}});return kh.set(d,{dir:t,record:s}),d}import{types as Fh}from"node:util";import Ki from"node:path";import{createHash as Vb}from"node:crypto";var Ro=r.string().min(1).max(256),Nl=r.string().regex(/^(0|[1-9][0-9]{0,18})$/),Ih=r.object({sourceId:Ro,generation:Nl,deletionGeneration:Nl,variant:Ro}).strict(),$b=r.object({source:Ih,executorId:Ro,workspaceId:Ro,workspaceRevision:Ro,authorizationRevision:Nl}).strict(),Rh=r.string().regex(/^[a-f0-9]{64}$/),Ul=r.object({format:r.literal("tansr-attachment-source/1"),scope:r.string().min(1).max(4096),historyDigest:Rh,checkpointDigest:Rh,snapshot:$b}).strict(),Ll=t=>JSON.parse(Buffer.from(nn(t)).toString("utf8")),Th=t=>Vb("sha256").update("tansr-attachment-source/1\0").update(he(t)).digest("hex");function Ah(t){return Object.freeze(Ih.parse(Ll(t)))}function Fl(t){return t===null?null:Ul.parse(Ll(t))}function ki(t){return he(t)}function Eh(t,e,n,i){return Ul.parse({format:"tansr-attachment-source/1",scope:t,historyDigest:io(e),checkpointDigest:Th(n),snapshot:i})}function Ch(t,e,n,i){return t.scope===e&&t.historyDigest===io(n)&&t.checkpointDigest===Th(i)}function _h(t){return{type:"attachment_source_checkpoint",version:1,checkpoint:Fl(t)}}function Hl(t){let e;for(let n of t){if(n.kind!=="event"||n.branchId!=="main"||n.visibility.model||n.visibility.defaultTranscript||!n.visibility.expandedTranscript||n.visibility.sdk||n.payload===null||typeof n.payload!="object"||n.payload.type!=="attachment_source_checkpoint")continue;e=r.object({type:r.literal("attachment_source_checkpoint"),version:r.literal(1),checkpoint:Ul.nullable()}).strict().parse(Ll(n.payload)).checkpoint}return e}var Ph=/^\d+$/;function Zs(t){let e=t.get("offset"),n=t.get("limit");if(e===null&&n===null)return{ok:!0,page:null};let i={};if(e!==null){if(!Ph.test(e))return{ok:!1,detail:"offset must be a non-negative integer"};i.offset=Number.parseInt(e,10)}if(n!==null){if(!Ph.test(n))return{ok:!1,detail:"limit must be a non-negative integer"};i.limit=Number.parseInt(n,10)}return{ok:!0,page:i}}function Kb(t){return t.blocks.flatMap(e=>e.t==="tool_call"?[e.id]:[])}function Qb(t){return t.blocks.flatMap(e=>e.t==="tool_result"?[e.callId]:[])}function Io(t,e,n){let i=t.length,o=Math.min(Math.max(0,Math.floor(e)),i),s=Math.min(i,o+Math.max(0,Math.floor(n))),a=new Set,d=0,c=s===0?0:null;for(let l=0;l<i;l++){let f=t[l];if(f.role==="assistant")for(let u of Kb(f))a.add(u);else for(let u of Qb(f)){if(!a.has(u))return null;a.delete(u)}if(a.size===0){let u=l+1;u<=o&&(d=u),c===null&&u>=s&&(c=u)}}return{start:d,end:c??i}}function Kn(t,e,n){let i=t.length,o=n??i;if(o===0||e>=i){let a=Math.min(e,i);return{messages:[],total:i,offset:a,nextOffset:a}}let s=Io(t,e,o)??{start:e,end:Math.min(i,e+o)};return{messages:t.slice(s.start,s.end),total:i,offset:s.start,nextOffset:s.end}}var ea=new WeakMap;function Mh(t){if(ea.has(t))throw new Error("Serve Store delete target already registered");ea.set(t,{})}function OT(t,e){let n=ea.get(t);if(!n)throw new Error("Serve Store does not support guarded deletion");if(typeof e!="function")throw new TypeError("Invalid Serve Store delete guard");if(n.guard!==void 0&&n.guard!==e)throw new Error("Serve Store delete guard already bound");n.guard=e}function Oh(t){return ea.get(t)?.guard}var et=class extends Error{code="session_store_corrupted";constructor(e,n,i){super(`Agent session store for "${e}" is corrupted: ${n}. Refusing to serve damaged history (delete the session directory to start over).`,i!==void 0?{cause:i}:void 0),this.name="AgentSessionStoreError"}};function Wt(t){return Jb("sha256").update(t,"utf8").digest("hex").slice(0,16)}async function Gl(t){try{return await Yb(t),!0}catch{return!1}}var Ql="TANSR_SESSION_STORE_CORE",qh=64;function Qi(t){for(let e of t){if(e.role!=="user")continue;let n=e.blocks.flatMap(i=>i.t==="text"?[i.text]:[]).join(" ").replace(/\s+/g," ").trim();if(n!=="")return n.length>qh?`${n.slice(0,qh)}…`:n}}var Hh=1024;function zh(t){if(t===null)return!0;if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return Object.keys(e).every(n=>n==="budget")&&(e.budget===void 0||Number.isSafeInteger(e.budget)&&e.budget>0)}function na(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return Object.keys(t).every(n=>["revision","model","thinking"].includes(n))&&Number.isSafeInteger(e.revision)&&e.revision>=0&&(e.model===null||typeof e.model=="string"&&e.model.length>0&&e.model.length<=256)&&zh(e.thinking)}function To(t){if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!["requestId","expectedRevision","changes"].includes(n))||typeof t.requestId!="string"||t.requestId.length<1||t.requestId.length>128||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!t.changes||typeof t.changes!="object"||Array.isArray(t.changes))return;let e=Object.keys(t.changes);if(!(e.length===0||e.some(n=>!["model","thinking"].includes(n))||"model"in t.changes&&(typeof t.changes.model!="string"||t.changes.model.length<1||t.changes.model.length>256)||"thinking"in t.changes&&!zh(t.changes.thinking)))return structuredClone(t)}function Ir(t){let e=t.serveConfiguration;if(e===void 0)return;let n=e;if(!n||n.format!=="serve-configuration-v1"||!na(n.current)||!Array.isArray(n.requests)||n.requests.length>Hh||n.current.revision!==n.requests.length||n.requests.some((i,o)=>!i||typeof i.requestId!="string"||!i.requestId||i.requestId.length>128||typeof i.digest!="string"||!/^[a-f0-9]{64}$/.test(i.digest)||!na(i.configuration)||i.configuration.revision!==o+1)||new Set(n.requests.map(i=>i.requestId)).size!==n.requests.length||n.requests.length>0&&he(n.requests.at(-1).configuration)!==he(n.current))throw new et(String(t.sessionId),"Invalid durable configuration");return structuredClone(n)}function $l(t,e){let n=ut(he(e)),i=t.requests.find(o=>o.requestId===e.requestId);return i?i.digest===n?{status:"replayed",configuration:structuredClone(i.configuration)}:{status:"rejected",reason:"request_conflict",configuration:structuredClone(t.current)}:t.current.revision!==e.expectedRevision?{status:"rejected",reason:"revision_conflict",configuration:structuredClone(t.current)}:t.requests.length>=Hh?{status:"rejected",reason:"request_limit",configuration:structuredClone(t.current)}:{status:"ready",configuration:structuredClone(t.current)}}function Zb(t,e){let n=Ir(t);if(n)return n.current;let i=structuredClone({...e,revision:0});if(!na(i))throw new TypeError("Invalid initial configuration");return t.serveConfiguration={format:"serve-configuration-v1",current:i,requests:[]},structuredClone(i)}function eS(t,e,n){let i=To(e);if(!i)return{status:"rejected",reason:"invalid_configuration"};let o=Ir(t);if(!o)throw new et(String(t.sessionId),"Configuration not initialized");let s=$l(o,i);if(s.status!=="ready")return s;if(!n())return{status:"rejected",reason:"turn_running"};let a={...o.current,...i.changes,revision:o.current.revision+1};return o.current=a,o.requests.push({requestId:i.requestId,digest:ut(he(i)),configuration:a}),t.serveConfiguration=o,{status:"changed",configuration:structuredClone(a)}}async function jh(t,e){let n=await Gh(t);return n!==null&&(ws(n),Ys(n,e)),n}async function Gh(t){try{let e=JSON.parse(await Xb(Zt(t),"utf8"));return typeof e!="object"||e===null||Array.isArray(e)?null:e}catch{return null}}function Dn(t){let e=typeof t.createdAt=="string"?t.createdAt:"",n=typeof t.updatedAt=="string"?t.updatedAt:e,i={sessionId:typeof t.sessionId=="string"?t.sessionId:"",createdAt:e,updatedAt:n};typeof t.title=="string"&&(i.title=t.title),typeof t.platformSessionId=="string"&&(i.platformSessionId=t.platformSessionId),typeof t.cwd=="string"&&(i.cwd=t.cwd);let o=tS(t.cwdHistory);o!==void 0&&(i.cwdHistory=o);let s=$h(t);s!==void 0&&(i.forkedFrom=s);let a=Vh(t);a!==void 0&&(i.retentionDays=a);let d=Wh(t);return d!==void 0&&(i.lastSeq=d,t.seqSealed===!0&&(i.seqSealed=!0)),i}function Wh(t){let e=t?.lastSeq;return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function Nh(t,e){if(!Number.isSafeInteger(e.lastSeq)||e.lastSeq<0)return!1;let n=Wh(t),i=n===void 0||e.lastSeq>n,o=!1;i&&(t.lastSeq=e.lastSeq,o=!0);let s=t.seqSealed===!0,a;return e.sealed===!0?a=n===void 0||e.lastSeq>=n?!0:s:a=i?!1:s,t.seqSealed===!0!==a&&(a?t.seqSealed=!0:delete t.seqSealed,o=!0),o}var ia="historyTotal";function Uh(t){let e=t?.[ia];if(typeof e!="object"||e===null||Array.isArray(e))return;let{messages:n,records:i,lastHash:o}=e;if(!(typeof n!="number"||!Number.isSafeInteger(n)||n<0)&&!(typeof i!="number"||!Number.isSafeInteger(i)||i<0)&&!(typeof o!="string"||o===""))return{messages:n,records:i,lastHash:o}}function Lh(t,e){if(e.cursor.lastHash===null){delete t[ia];return}let n={messages:e.persisted,records:e.cursor.recordCount,lastHash:e.cursor.lastHash};t[ia]=n}function Vh(t){let e=t?.retentionDays;return typeof e=="number"?ta(e):void 0}function $h(t){let e=t?.forkedFrom;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.sessionId=="string"&&typeof e.checkpointId=="string"){let n=e;return{sessionId:n.sessionId,checkpointId:n.checkpointId}}}function tS(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(typeof n!="object"||n===null)return;let{at:i,from:o,to:s}=n;if(typeof i!="string"||typeof o!="string"||typeof s!="string")return;e.push({at:i,from:o,to:s})}return e}var nS=1e5;function ta(t){return t!==void 0&&Number.isFinite(t)&&t>=0?t:void 0}async function Kh(t){let e=0,n;try{n=await Wl(t,{withFileTypes:!0})}catch{return 0}for(let i of n){let o=Ki.join(t,i.name);if(i.isDirectory())e+=await Kh(o);else if(i.isFile())try{e+=(await Vl(o)).size}catch{}}return e}function iS(t){let e={sessionId:t.sessionId,createdAt:t.createdAt,updatedAt:t.updatedAt};return t.title!==void 0&&(e.title=t.title),t.platformSessionId!==void 0&&(e.platformSessionId=t.platformSessionId),e}function rS(t,e){switch(e.type){case"store.segment_sealed":t("debug",Xe.storeSegmentSealed,{sessionId:e.session.sessionId,endUserKey:e.session.endUserKey,n:e.segment.n,firstSeq:e.segment.firstSeq,lastSeq:e.segment.lastSeq,records:e.segment.records,bytes:e.segment.bytes});return;case"store.segment_committed":t("info",Xe.storeSegmentCommitted,{sessionId:e.session.sessionId,endUserKey:e.session.endUserKey,n:e.segment.n,key:e.key,bytes:e.bytes,generation:e.generation});return;case"store.commit_failed":t(e.gaveUp?"error":"warn",Xe.storeCommitFailed,{sessionId:e.session.sessionId,endUserKey:e.session.endUserKey,n:e.segment?.n??null,kind:e.error.kind,attempts:e.attempts,gaveUp:e.gaveUp,...e.error.retryAfterMs!==void 0?{retryAfterMs:e.error.retryAfterMs}:{},message:e.error.message});return;case"store.hot_full":t("error",Xe.storeHotFull,{hotBytes:e.hotBytes,maxBytes:e.maxBytes});return;case"store.hot_recovered":t("info",Xe.storeHotRecovered,{hotBytes:e.hotBytes,maxBytes:e.maxBytes});return;case"store.evicted":t("debug",Xe.storeEvicted,{sessionId:e.session.sessionId,endUserKey:e.session.endUserKey,n:e.segment.n,bytes:e.bytes});return;case"store.orphan_gc":t("info",Xe.storeOrphanGc,{sessionId:e.session.sessionId,endUserKey:e.session.endUserKey,deleted:e.deleted.length});return;default:return}}var Kl=new WeakMap;function oS(t,e){if(Kl.has(t)||Fh.isProxy(t))throw new Ui("identity_mismatch");Kl.set(t,{...e,methods:["create","get","list","commit","delete"].map(n=>({key:n,value:Object.getOwnPropertyDescriptor(t,n)?.value}))})}function ti(t){if(!t||typeof t!="object"||Fh.isProxy(t))throw new Ui("identity_mismatch");let e=Kl.get(t);if(!e||e.methods.some(n=>{let i=Object.getOwnPropertyDescriptor(t,n.key);return!i||!("value"in i)||i.value!==n.value}))throw new Ui("identity_mismatch");if(e.cold&&!e.family)throw new Ui("unsupported_capability");return e}function Qh(t){ti(t)}function JT(t,e){if(ti(t).family!==e)throw new ct("family_mismatch")}function YT(t,e,n,i){let o=ti(t);if(!o.family||!Number.isSafeInteger(i)||i<1)throw new ct("family_mismatch");return o.readBounded(e,n,i)}function XT(t){return ti(t).storageRoot}function Jl(t,e,n){let i=ti(t);if(typeof e!="string"||e.length===0)throw new Ui("invalid_input");let o=fc(n,["title","platformSessionId","cwd","retentionDays"]);return i.create(e,o)}function Jh(t){return Yh(t)}function ZT(t,e){if(!t.cold||Ki.resolve(t.dir)!==e.directory)throw new ct("family_mismatch");return Yh(t,e)}function Yh(t,e){if(t.ownership!==void 0&&t.cold!==void 0)throw new TypeError("File session ownership requires the original shared hot store");let n=new Map,i=new Map,o=new Map,s=Ki.resolve(t.dir),a=e?{sdk2SessionFamily:e.marker}:{},d=async(O,I)=>{if(e&&I===null&&await Gl(O)&&(await Wl(O)).length>0)throw new ct("family_missing")},c=async O=>{await e?.checkRoot();let I=await jh(O,e);return await d(O,I),I},l=async O=>{await e?.checkRoot();let I=await Gh(O);return await d(O,I),I&&Ys(I,e),I},f=async(O,I=!1)=>{if(!e)return yc(O);await e.checkRoot();let B=Gt(O.storageRoot,O.sessionId);if(I?await jh(B,e):await c(B))return{sessionDir:B,meta:await gc(B),created:!1};await Dh(B,{recursive:!0});let j={schemaVersion:1,sessionId:O.sessionId,createdAt:new Date().toISOString(),cwd:O.cwd,...O.extra??{},sdk2SessionFamily:e.marker},ne=await Sp(B,j,"fresh");if(!await c(B))throw new ct("family_missing");return{sessionDir:B,meta:await gc(B),created:ne}},u=process.env[Ql]==="legacy"?"legacy":"core";if(t.recovery!==void 0&&u==="legacy")throw new Error("session recovery requires the core store policy");let m={segmentation:t.segmentation??{}},g=t.cold===void 0?void 0:qc({cold:t.cold,...t.index!==void 0?{index:t.index}:{},...t.policy!==void 0?{policy:t.policy}:{},...t.metrics!==void 0?{metrics:t.metrics}:{}});if(g!==void 0){let O=$n(t.logger);g.on(I=>{if(rS(O,I),I.type==="store.commit_failed"&&I.gaveUp&&t.onStoreError!==void 0)try{t.onStoreError(I.session.sessionId,I.error)}catch{}if(t.onStoreEvent!==void 0)try{t.onStoreEvent(I)}catch{}})}function h(O,I){let B=(n.get(O)??Promise.resolve()).then(async()=>(await e?.checkRoot(),I())),z=B.then(()=>{},()=>{});return n.set(O,z),z.then(()=>{n.get(O)===z&&n.delete(O)}),B}let p=O=>Ki.join(s,e?"offload-sessions":"agent-sessions",O),v=O=>p(Wt(O)),b=(O,I,B)=>g?.bind({sessionId:O,endUserKey:I,sessionDir:B}),R=O=>O===void 0?m:{...m,externalizeImages:!1,onSegmentSealed:O.onSegmentSealed},w=O=>O===void 0?{}:{segmentSource:O.segmentSource},x=(O,I)=>I instanceof Wn&&I.kind==="transient"?I:new et(O,Bn(I),I),T=O=>{let I=o.get(O);return I===void 0&&(I=new jc({storageRoot:O,readMeta:async B=>{let z=await l(B);return z===null||typeof z.sessionId!="string"?null:ks(z,Dn(z))}}),o.set(O,I)),I};function M(O,I,B,z){let j=i.get(O);if(j!==void 0)return i.delete(O),i.set(O,j),j;if(i.size>=nS){let U=i.keys().next();U.done||i.delete(U.value)}let ne=wc({sessionDir:z,sessionId:I,producer:"serve",policy:u,writerOptions:()=>R(b(I,B,z)),readOptions:()=>w(b(I,B,z)),onRotated:async({empty:U})=>{g?.unbind(z),U&&await g?.commitEmpty({sessionId:I,endUserKey:B,sessionDir:z})},...t.onStoreWarning!==void 0?{onWarning:t.onStoreWarning}:{}});return i.set(O,ne),ne}let W=(O,I)=>I instanceof vn?I.code==="SESSION_LOCKED"||I.code==="CURSOR_STALE"?I:new et(O,I.message,I):I instanceof Wn?x(O,I):I,$=(O,I)=>I instanceof vn&&(I.code==="SESSION_LOCKED"||I.code==="CURSOR_STALE")?I:x(O,I);async function D(O,I,B){let z=await c(O);return z===null?null:(I(z)&&(B!==void 0&&jl(O,B,z),Ys(z,e),await li(Zt(O),`${JSON.stringify(z,null,2)}
|
|
9
|
+
`)),z)}async function J(O,I,B){return t.ownership===void 0&&I===void 0?(xo(O.sessionDir),B()):O.withLock(B,()=>xo(O.sessionDir,I))}async function S(O,I){return(await k(O,I)).messages}async function k(O,I,B=!1){let z=(await c(O.sessionDir))?.serveOwner!==void 0;if(!z&&t.recovery!==void 0)try{let U=await O.withLock(()=>Pc(O,t.recovery));if(U.recovery!==void 0&&t.recovery.onRecovery===void 0){let le=U.recovery,ue={sessionId:I,droppedMessages:le.droppedMessages,recoveredMessages:le.recoveredMessages,synthesizedToolResults:le.synthesizedToolResults,reason:le.reason,fingerprint:le.fingerprint};t.logger!==void 0?$n(t.logger)("warn","store.recovery_degraded",ue):process.emitWarning(JSON.stringify(ue),{code:"SESSION_RECOVERY_DEGRADED"})}return{messages:U.messages,usageSnapshot:rl(U.journal.records),attachmentCheckpoint:xs(U.journal.records,U.recovery===void 0?U.messages:void 0),attachmentSourceCheckpoint:Hl(U.journal.records),memorySelectionCheckpoint:zc(U.journal.records),...U.recovery!==void 0?{recovery:U.recovery}:{}}}catch(U){throw O.resetTail(),$(I,U)}let j;try{j=z?await O.readAllConfirmed():await O.readAll(B?{repair:!1}:{})}catch(U){throw $(I,U)}if(j.integrityBreakAt!==void 0)throw new et(I,`journal hash chain broken at record index ${j.integrityBreakAt}`);let ne=Sr(j.records);if(ne.warnings.length>0)throw O.resetTail(),new et(I,ne.warnings.join("; "));try{return{messages:ne.messages,usageSnapshot:rl(j.records),attachmentCheckpoint:xs(j.records,ne.messages),attachmentSourceCheckpoint:Hl(j.records),memorySelectionCheckpoint:zc(j.records)}}catch(U){throw O.resetTail(),$(I,U)}}async function A(O,I,B){if(g===void 0)return!1;await e?.checkRoot();let z;try{z=Gt(O,B)}catch{return!1}if(await c(z)!==null)return!1;let j=await Gl(z);await Dh(z,{recursive:!0});let ne;try{ne=await g.restore({sessionId:B,endUserKey:I,sessionDir:z})}catch(ue){throw j||await zl(z,{recursive:!0,force:!0}).catch(()=>{}),x(B,ue)}if(ne===null)return j||await zl(z,{recursive:!0,force:!0}).catch(()=>{}),!1;let U=ne.meta;await f({storageRoot:O,sessionId:B,cwd:process.cwd(),extra:{...a,...U.title!==void 0?{title:U.title}:{}}},!0);let le=await D(z,ue=>(U.createdAt!==""&&(ue.createdAt=U.createdAt),ue.updatedAt=U.updatedAt!==""?U.updatedAt:ue.createdAt,U.platformSessionId!==void 0&&(ue.platformSessionId=U.platformSessionId),!0));if(le===null)throw new et(B,"meta.json unreadable right after cold-tier restore");return i.get(`${O}|${B}`)?.resetTail(),await T(O).upsert(Dn(le)),!0}function C(O,I){let B=p(O),z=`${B}|${I}`;return h(z,async()=>{let j=Gt(B,I);await c(j)!==null&&Xs(j);let ne=Oh(re);if(ne!==void 0){let U=await ne(Object.freeze({storeIdentity:re,endUserKey:O,sessionId:I}));if(U!==null){if(!U||typeof U.confirm!="function")throw new TypeError("Invalid Serve Store delete confirmation");let le=await c(j);if(le===null&&await A(B,O,I)&&(le=await c(j)),le===null)await U.confirm(null);else{let ue=M(z,I,O,j);await ue.withLock(async()=>{let ie=await c(j);if(ie===null||ie.sessionId!==I||ie.pendingRewrite===!0)throw new et(I,"Guarded deletion requires confirmed original metadata");let me=await ue.readAll({repair:!1});if(me.integrityBreakAt!==void 0||me.repairs.length>0)throw new et(I,"Guarded deletion requires intact original history");let q=Sr(me.records);if(q.warnings.length>0)throw new et(I,q.warnings.join("; "));let X=Uh(ie);if(Object.hasOwn(ie,ia)&&X===void 0||X!==void 0&&(X.records!==me.cursor.recordCount||X.lastHash!==me.cursor.lastHash||X.messages!==q.messages.length))throw new et(I,"Guarded deletion requires confirmed original history");await U.confirm(Object.freeze({meta:Object.freeze(Dn(ie)),sourceSnapshotDigest:rn(I,q.messages,0).sourceSnapshotDigest}))})}}}await c(j)!==null&&await M(z,I,O,j).withLock(async()=>{await D(j,U=>(Xs(j,U),U.serveOwnerDeleted=!0,!0))},()=>Xs(j)),i.delete(z),g!==void 0&&(g.unbind(j),await g.remove({sessionId:I,endUserKey:O})),await zl(j,{recursive:!0,force:!0}),await T(B).remove(I)})}async function F(O,I,B){let z=Wt(O),j=p(z),ne=`${j}|${I}`;return h(ne,async()=>{let U=Gt(j,I),le=await c(U);if(le===null&&await A(j,z,I)&&(le=await c(U)),le===null)return null;let ue=M(ne,I,z,U),ie=B===void 0?await k(ue,I):await ue.withLock(async()=>{let X=async Ue=>{try{return(await Vl(Ue)).size}catch($e){if($e.code==="ENOENT")return 0;throw $e}};if(await X(Ki.join(U,"manifest.json"))>262144)throw new ct("capacity_exceeded");let te=await vc(U),Se=await X(Ki.join(U,"journal.jsonl"));for(let Ue of te?.segments??[]){if(Ue.status!=="sealed"||Ue.bytes<=0)throw new ct("rollback_pending");Se+=Ue.bytes}if(!Number.isSafeInteger(Se)||Se>B)throw new ct("capacity_exceeded");if(le=await c(U),!le)throw new ct("family_missing");return k(ue,I,!0)}),me=le.serveRuntime;if(me!==void 0&&(t.ownership?.runtimeRecovery!==!0||!me||!me.checkpoint||typeof me.checkpoint!="object"||typeof me.checkpoint.query!="object"||me.checkpoint.query===null||me.checkpoint.query.version!==1||me.checkpoint.query.sessionId!==I||typeof me.checkpoint.query.turnId!="string"||typeof me.checkpoint.historyEpoch!="string"||!me.checkpoint.historyEpoch||!Number.isSafeInteger(me.checkpoint.turn)||me.checkpoint.turn<1||me.checkpoint.deadline!==void 0&&(!Number.isSafeInteger(me.checkpoint.deadline)||me.checkpoint.deadline<0)||me.historyDigest!==ut(Bt(ie.messages))))throw new et(I,"Runtime checkpoint history mismatch");let q=Ir(le)?.current;return{...q===void 0?{}:{configuration:q},...me===void 0?{}:{runtimeCheckpoint:{...me.checkpoint,query:{...me.checkpoint.query,messages:ie.messages}}},meta:Dn(le),...le.serveOwner===void 0?{}:{ownershipRequired:!0},messages:ie.messages,...ie.recovery!==void 0?{recovery:ie.recovery}:{},...ie.usageSnapshot!==void 0?{usageSnapshot:ie.usageSnapshot}:{},...ie.attachmentCheckpoint!==void 0?{attachmentCheckpoint:ie.attachmentCheckpoint}:{},...ie.attachmentSourceCheckpoint!==void 0?{attachmentSourceCheckpoint:ie.attachmentSourceCheckpoint}:{},...ie.memorySelectionCheckpoint!==void 0?{memorySelectionCheckpoint:ie.memorySelectionCheckpoint}:{}}})}let H=(O,I,B,z)=>{let j=v(O),ne=`${j}|${I}`;return h(ne,async()=>{let U=Gt(j,I);return J(M(ne,I,Wt(O),U),B,async()=>{let le=await c(U);if(!le)throw new et(I,"Configuration session not found");let ue=z(le);return ue.changed&&(jl(U,B,le),await li(Zt(U),`${JSON.stringify(le,null,2)}
|
|
10
|
+
`)),ue.value})})},Q=O=>{if(O.serveOwner?.phase!=="idle"||O.serveRuntime!==void 0||O.pendingRewrite===!0)throw new Qt("reconciliation_required")},re={...t.ownership===void 0?{}:{initializeConfiguration(O,I,B,z){let j=structuredClone({...B,revision:0});return na(j)?H(O,I,z,ne=>{let U=Ir(ne);return U?{value:U.current,changed:!1}:(Q(ne),{value:Zb(ne,j),changed:!0})}):Promise.reject(new TypeError("Invalid initial configuration"))},inspectConfiguration(O,I,B,z){let j=To(B);return j?H(O,I,z,ne=>{let U=Ir(ne);if(!U)throw new et(I,"Configuration not initialized");return{value:$l(U,j),changed:!1}}):Promise.resolve({status:"rejected",reason:"invalid_configuration"})},commitConfiguration(O,I,B,z,j){let ne=To(B);return ne?H(O,I,z,U=>{let le=Ir(U);if(!le)throw new et(I,"Configuration not initialized");let ue=$l(le,ne);if(ue.status!=="ready")return{value:ue,changed:!1};Q(U);let ie=eS(U,ne,j);return{value:ie,changed:ie.status==="changed"}}):Promise.resolve({status:"rejected",reason:"invalid_configuration"})}},...t.ownership?.runtimeRecovery===!0?{runtimeCheckpoints:!0}:{},...t.ownership===void 0?{}:{claimOwner:(O,I)=>h(`${v(O)}|${I}`,()=>xh(Gt(v(O),I),t.ownership,B=>h(`${v(O)}|${I}`,B)))},attachmentCheckpoints:!0,attachmentSourceCheckpoints:!0,memorySelectionCheckpoints:!0,async create(O,I){let B=Wt(O),z=p(B),j=I.sessionId??Bh(),ne=`${z}|${j}`;return h(ne,async()=>{let U=T(z);await U.warm();let le={...a,...I.title!==void 0?{title:I.title}:{},...typeof I.retentionDays=="number"?{retentionDays:I.retentionDays}:{}},{sessionDir:ue,created:ie}=await f({storageRoot:z,sessionId:j,cwd:I.cwd??process.cwd(),...Object.keys(le).length>0?{extra:le}:{}});if(!ie&&await Gl(bc(ue)))try{await M(ne,j,B,ue).withLock(async()=>{},()=>xo(ue,I.owner))}catch(me){throw $(j,me)}return J(M(ne,j,B,ue),I.owner,async()=>{let me=await D(ue,X=>{ws(X);let te=!1;return ie&&typeof X.updatedAt!="string"&&(X.updatedAt=typeof X.createdAt=="string"?X.createdAt:new Date().toISOString(),te=!0),I.platformSessionId!==void 0&&X.platformSessionId!==I.platformSessionId&&(X.platformSessionId=I.platformSessionId,te=!0),I.title!==void 0&&X.title!==I.title&&(X.title=I.title,te=!0),typeof I.retentionDays=="number"&&X.retentionDays!==I.retentionDays?(X.retentionDays=I.retentionDays,te=!0):I.retentionDays===null&&"retentionDays"in X&&(delete X.retentionDays,te=!0),te},I.owner);if(me===null)throw new et(j,"meta.json unreadable right after creation");let q=Dn(me);return await U.upsert(q),q})})},get:(O,I)=>F(O,I),async getMeta(O,I){let B=Wt(O),z=p(B),j;try{j=Gt(z,I)}catch{return null}let ne=await c(j);return ne===null&&g!==void 0&&await h(`${z}|${I}`,()=>A(z,B,I))&&(ne=await c(j)),ne===null||typeof ne.sessionId!="string"?null:Dn(ne)},async list(O,I){await e?.checkRoot();let B=Wt(O),z=await T(p(B)).entries(),j=z.filter(pc);if(e){for(let ne of j)if(!await c(Gt(p(B),ne.sessionId)))throw new ct("family_missing")}if(g!==void 0){let ne=new Set(z.map(U=>U.sessionId));for await(let U of g.listSessions(B))ne.has(U.sessionId)||j.push(iS(U))}return j.sort((ne,U)=>U.updatedAt.localeCompare(ne.updatedAt)),I?.limit!==void 0?j.slice(0,I.limit):j},async commit(O,I,B,z){let j=Wt(O),ne=p(j),U=`${ne}|${I}`,le=[...B],ue=z.attachmentCheckpoint===void 0?void 0:kc(z.attachmentCheckpoint),ie=z.attachmentSourceCheckpoint===void 0?void 0:_h(z.attachmentSourceCheckpoint),me=z.memorySelectionCheckpoint===void 0?void 0:nm(z.memorySelectionCheckpoint);return h(U,async()=>{let q=Qi(le),X=T(ne);await X.warm(),await A(ne,j,I);let{sessionDir:te}=await f({storageRoot:ne,sessionId:I,cwd:process.cwd(),extra:{...a,...q!==void 0?{title:q}:{}}}),Se=M(U,I,j,te);return J(Se,z.owner,async()=>{if(z.runtimeCheckpoint!==void 0&&(t.ownership?.runtimeRecovery!==!0||z.owner===void 0||z.runtimeCheckpoint.query.sessionId!==I||Bt(z.runtimeCheckpoint.query.messages)!==Bt(le)))throw new et(I,"Invalid runtime checkpoint");t.ownership?.runtimeRecovery===!0&&await D(te,Fe=>(delete Fe.serveRuntime,!0),z.owner);let Ue;try{Ue=await Se.commit({snapshot:le,rewritten:z.rewritten,...z.usageSnapshot!==void 0||ue!==void 0||ie!==void 0||me!==void 0?{trailingEvents:[...z.usageSnapshot===void 0?[]:[z.usageSnapshot],...ue===void 0?[]:[ue],...ie===void 0?[]:[ie],...me===void 0?[]:[me]]}:{}})}catch(Fe){throw W(I,Fe)}let $e=await D(te,Fe=>{if(Fe.updatedAt=new Date().toISOString(),z.lastSeq!==void 0&&Nh(Fe,{lastSeq:z.lastSeq,sealed:!1}),Lh(Fe,Ue),z.runtimeCheckpoint!==void 0){let{messages:lt,...kt}=z.runtimeCheckpoint.query;Fe.serveRuntime={checkpoint:{...z.runtimeCheckpoint,query:kt},historyDigest:ut(Bt(le))}}return!0},z.owner);$e!==null&&await X.upsert(Dn($e))})})},async recordUsageSnapshot(O,I,B,z){let j=Pm(structuredClone(B));if(j===void 0||j.snapshot.sessionId!==I)throw new et(I,"recordUsageSnapshot: invalid snapshot");let ne=Wt(O),U=p(ne),le=`${U}|${I}`;return h(le,async()=>{let ue=Gt(U,I);await Vl(Zt(ue)).then(()=>!1,X=>{if(typeof X=="object"&&X!==null&&"code"in X&&X.code==="ENOENT")return!0;throw X})&&await A(U,ne,I);let me=await l(ue);if(me===null||me.sessionId!==I)throw new et(I,"recordUsageSnapshot: session not found");let q=T(U);return await q.warm(),J(M(le,I,ne,ue),z,async()=>{let X;try{X=await M(le,I,ne,ue).appendInternalEvents([j])}catch(Se){throw W(I,Se)}let te=await D(ue,Se=>(Lh(Se,X),!0),z);if(te===null)throw new et(I,"recordUsageSnapshot: metadata disappeared");await q.upsert(Dn(te))})})},delete(O,I){return C(Wt(O),I)},async sweepRetention(O){let I={scanned:0,deleted:[],failures:[]},B=ie=>{let me=ta(ie.maxAgeDays)!==void 0?ie.maxAgeDays*864e5:void 0,q=ta(ie.maxPerEndUser),X=ta(ie.maxBytes);return{...me!==void 0?{maxAgeMs:me}:{},...q!==void 0?{maxPerEndUser:q}:{},...X!==void 0?{maxBytes:X}:{}}},z=ie=>ie.maxAgeMs===void 0&&ie.maxPerEndUser===void 0&&ie.maxBytes===void 0,j=B(O.policy);if(O.policyFor===void 0&&z(j))return I;let ne=O.keep??new Set,U=Ki.join(s,e?"offload-sessions":"agent-sessions"),le;try{le=(await Wl(U,{withFileTypes:!0})).filter(ie=>ie.isDirectory()).map(ie=>ie.name)}catch(ie){if(ie?.code==="ENOENT")return I;throw ie}let ue=async(ie,me,q)=>{try{await C(ie,me),I.deleted.push({endUserKey:ie,sessionId:me,reason:q})}catch(X){I.failures.push({endUserKey:ie,sessionId:me,message:Bn(X)})}};for(let ie of le.sort()){let me=O.policyFor?.(ie),{maxAgeMs:q,maxPerEndUser:X,maxBytes:te}=me!==void 0?B(me):j;if(q===void 0&&X===void 0&&te===void 0)continue;let Se=p(ie),Ue=await T(Se).entries(),$e=[];for(let Ge of Ue){if(I.scanned+=1,ne.has(Ge.sessionId))continue;let rt;try{rt=Gt(Se,Ge.sessionId)}catch{continue}let Tt=await c(rt),zt=typeof Tt?.updatedAt=="string"?Date.parse(Tt.updatedAt):Number.NaN,gn=Vh(Tt);$e.push({sessionId:Ge.sessionId,updatedAtMs:Number.isFinite(zt)?zt:void 0,maxAgeMs:gn!==void 0?gn*864e5:q})}let Fe=$e,lt=Fe.filter(Ge=>Ge.updatedAtMs!==void 0&&Ge.maxAgeMs!==void 0&&O.now-Ge.updatedAtMs>Ge.maxAgeMs);for(let Ge of lt)await ue(ie,Ge.sessionId,"max_age");Fe=Fe.filter(Ge=>!lt.includes(Ge));let kt=(Ge,rt)=>(rt.updatedAtMs??Number.NEGATIVE_INFINITY)-(Ge.updatedAtMs??Number.NEGATIVE_INFINITY);if(Fe.sort(kt),X!==void 0&&Fe.length>X){let Ge=Fe.slice(Math.floor(X));for(let rt of Ge)await ue(ie,rt.sessionId,"max_per_end_user");Fe=Fe.slice(0,Math.floor(X))}if(te!==void 0&&Fe.length>0){let Ge=[];for(let Tt of Fe)Ge.push({sessionId:Tt.sessionId,bytes:await Kh(Gt(Se,Tt.sessionId))});let rt=Ge.reduce((Tt,zt)=>Tt+zt.bytes,0);for(let Tt=Ge.length-1;Tt>=0&&rt>te;Tt--){let zt=Ge[Tt];await ue(ie,zt.sessionId,"max_bytes"),rt-=zt.bytes}}}return I},sessionDirOf(O,I){return Gt(v(O),I)},async getHistoryPage(O,I,B){if(!Number.isFinite(B.offset)||B.offset<0||!Number.isFinite(B.limit)||B.limit<0)throw new RangeError(`getHistoryPage: "offset" and "limit" must be non-negative finite numbers (got offset=${String(B.offset)}, limit=${String(B.limit)}).`);let z=Math.floor(B.offset),j=Math.floor(B.limit),ne=Wt(O),U=p(ne),le=`${U}|${I}`;return h(le,async()=>{let ue;try{ue=Gt(U,I)}catch{return null}let ie=await c(ue);if(ie===null){if(!await A(U,ne,I))return null;ie=await c(ue)}let me=$h(ie)!==void 0,q=Uh(ie),X=M(le,I,ne,ue);return ie?.serveOwner!==void 0?Kn(await S(X,I),z,j):t.recovery!==void 0?Kn(await S(X,I),z,j):X.withLock(async()=>{if(me)return Kn(await S(X,I),z,j);let te=Math.max(j,1);for(;;){let Se;try{Se=await X.readTail({minMessages:te})}catch(rt){throw $(I,rt)}if(Se.integrityBreakAt!==void 0)throw X.resetTail(),new et(I,`journal hash chain broken at record index ${Se.integrityBreakAt}`);let Ue=Sr(Se.records);if(Ue.warnings.length>0)throw X.resetTail(),new et(I,Ue.warnings.join("; "));let $e=Ue.messages;if(Se.fromSegment===1)return Kn($e,z,j);let Fe=q!==void 0&&q.lastHash===Se.cursor.lastHash&&q.records===Se.cursor.recordCount,lt;if(Fe)lt=q.messages;else if(Se.records.every(rt=>rt.producer==="serve"&&Sc(rt)))lt=Se.cursor.recordCount;else return Kn(await S(X,I),z,j);let kt=lt-$e.length;if(j===0||z>=lt)return{messages:[],total:lt,offset:Math.min(z,lt),nextOffset:Math.min(z,lt)};if(z<kt){te=lt-z;continue}let Ge=Io($e,z-kt,j);if(Ge===null){te=$e.length+1;continue}return{messages:$e.slice(Ge.start,Ge.end),total:lt,offset:kt+Ge.start,nextOffset:kt+Ge.end}}})})},async recordCwdChange(O,I,B,z){let j=v(O),ne=`${j}|${I}`;return h(ne,async()=>{let U=Gt(j,I);return J(M(ne,I,Wt(O),U),z,async()=>{let le=await D(U,ue=>{ue.cwd=B.to;let ie=Array.isArray(ue.cwdHistory)?ue.cwdHistory:[];return ue.cwdHistory=[...ie,{at:B.at,from:B.from,to:B.to}],!0},z);if(le===null)throw new et(I,"recordCwdChange: meta.json unreadable (session not found)");await T(j).upsert(Dn(le))})})},async recordSeqWatermark(O,I,B,z){let j=v(O),ne=`${j}|${I}`;return h(ne,async()=>{let U=Gt(j,I);return J(M(ne,I,Wt(O),U),z,async()=>{let le=await D(U,ue=>Nh(ue,B),z);if(le===null)throw new et(I,"recordSeqWatermark: meta.json unreadable (session not found)");await T(j).upsert(Dn(le))})})},async fork(O,I){if(e)throw new ct("family_mismatch");let B=v(O),z=I.newSessionId??Bh(),j=`${B}|${z}`;return h(j,async()=>{let ne=T(B);await ne.warm();let U=I.title??Qi(I.checkpoint.messages),le=await Hc({storageRoot:B,sourceSessionId:I.sourceSessionId,checkpoint:I.checkpoint,newSessionId:z,cwd:I.cwd,producer:"serve",...U!==void 0?{extra:{title:U}}:{}}),ue=await D(le.sessionDir,ie=>(ie.updatedAt=typeof ie.createdAt=="string"?ie.createdAt:new Date().toISOString(),!0));if(ue===null)throw new et(z,"meta.json unreadable right after fork");return i.delete(j),await ne.upsert(Dn(ue)),{sessionId:le.sessionId}})},async flush(O){return await Promise.all([...n.values()]),g===void 0?!0:g.flush(O)},readiness(){return g===void 0||g.ready?{ready:!0}:{ready:!1,reason:"store_hot_full"}}};return Mh(re),oS(re,{readBounded:F,cold:g!==void 0,...e?{family:e}:{},storageRoot:s,create(O,I){let B=Wt(O),z=p(B),j=I.sessionId,ne=Gt(z,j);return h(`${z}|${j}`,async()=>{ti(re);let U=new Date().toISOString(),le={...a,schemaVersion:1,sessionId:j,cwd:I.cwd??process.cwd(),createdAt:U,updatedAt:U,...I.title!==void 0?{title:I.title}:{},...I.platformSessionId!==void 0?{platformSessionId:I.platformSessionId}:{},...typeof I.retentionDays=="number"?{retentionDays:I.retentionDays}:{}};return mc({sessionDir:ne,raw:le,register:async ue=>{ti(re);let ie=T(z);await ie.warm();let me=Dn(ue);return await ie.upsert(ks(ue,me)),ti(re),me},publish:async ue=>{ti(re),await T(z).upsert(ue),ti(re)}})})}}),ac(re,{directory:(O,I)=>Gt(v(I.endUserId),O),read:(O,I)=>re.get(I.endUserId,O),...t.ownership?.runtimeRecovery===!0?{readRuntimeCheckpoint:async(O,I)=>(await re.get(I.endUserId,O))?.runtimeCheckpoint??null}:{},readConfirmed:(O,I)=>{let B=Wt(I.endUserId),z=p(B),j=`${z}|${O}`;return h(j,async()=>{try{let ne=await M(j,O,B,Gt(z,O)).readAllConfirmed(e?{allowCold:!0}:void 0),U=Sr(ne.records);if(U.warnings.length>0)throw new et(O,U.warnings.join("; "));return{messages:U.messages}}catch(ne){throw $(O,ne)}})}}),re}import{createHash as Xh,timingSafeEqual as sS}from"node:crypto";var Rt=class extends Error{constructor(n){super(n);this.code=n;this.name="AuthenticationUnavailableError"}code};function Zh(t,e){let n=t.authentication??(e?{}:void 0);if(n===void 0)return{authenticate:c=>t.authenticate(c),close(){}};let i=n.maxPending??128,o=n.timeoutMs??1e4;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(o)||o<1||o>2147483647)throw new RangeError("Invalid authentication limits");let s=0,a=!1,d=new Set;return{authenticate(c,l){if(a||c.aborted||l.destroyed||l.writableEnded)throw new Rt("source_unavailable");if(s>=i)throw new Rt("overloaded");s++;let f,u;try{f=t.authenticate(c),u=f!==null&&typeof f.then=="function"}catch(h){throw s--,h}if(!u){if(s--,a||c.aborted||l.destroyed||l.writableEnded)throw new Rt("source_unavailable");return f}let m=Promise.resolve(f),g=()=>{s--};return m.then(g,g),new Promise((h,p)=>{let v=!1,b=(x,T)=>{v||(v=!0,clearTimeout(w),d.delete(R),c.removeListener("aborted",R),l.removeListener("close",R),x?h(T):p(T))},R=()=>b(!1,new Rt("source_unavailable")),w=setTimeout(R,o);w.unref(),d.add(R),c.once("aborted",R),l.once("close",R),(a||c.aborted||l.destroyed||l.writableEnded)&&R(),m.then(x=>{a||c.aborted||l.destroyed||l.writableEnded?R():b(!0,x)},x=>b(!1,x))})},close(){a=!0;for(let c of[...d])c()}}}function Yl(t){return t===void 0?void 0:/^Bearer\s+(\S+)$/i.exec(t.trim())?.[1]}function Xl(t,e){let n=Xh("sha256").update(t,"utf8").digest(),i=Xh("sha256").update(e,"utf8").digest();return sS(n,i)}function ra(t,e){let n=Yl(t);return n===void 0?!1:Xl(n,e)}function xi(t,e,n){return new Promise(i=>{let o=[],s=0,a=!1,d=l=>{a||(a=!0,i(l))},c=l=>{if(s+=l.length,s>e){o.length=0,t.off("data",c),t.pause(),d({ok:!1,reason:"too_large"});return}o.push(l)};t.on("data",c),t.on("end",()=>{if(n!==void 0){try{d({ok:!0,value:n(Buffer.concat(o))})}catch{d({ok:!1,reason:"invalid_json"})}return}let l=Buffer.concat(o).toString("utf8");if(l.trim()===""){d({ok:!0,value:{}});return}try{d({ok:!0,value:JSON.parse(l)})}catch{d({ok:!1,reason:"invalid_json"})}}),t.on("error",()=>d({ok:!1,reason:"invalid_json"}))})}function Je(t,e,n){let i=JSON.stringify(n);t.writeHead(e,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(i)}),t.end(i)}function pe(t,e,n,i,o,s,a){let d=JSON.stringify({error:{code:n,message:We(i,o),...a!==void 0?{detail:a}:{}}});t.writeHead(e,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(d),...s??{}}),t.end(d)}var Zl=1e3;function Tr(t,e,n,i,o){let s=JSON.stringify({error:{code:n,message:We(i,o)}});if(e.writeHead(413,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(s),connection:"close"}),t.complete){e.end(s);return}e.write(s);let a=!1,d=()=>{a||(a=!0,clearTimeout(c),e.destroyed||e.end())},c=setTimeout(d,Zl);c.unref(),e.once("close",d)}function fi(t){try{return decodeURIComponent(t)}catch{return null}}function oa(t){if(t===void 0)return-1;let e=Array.isArray(t)?t[t.length-1]:t;if(e===void 0||e.trim()==="")return-1;if(/^\d+$/.test(e.trim()))return Number.parseInt(e.trim(),10)}function eu(t){return t.replace(/[\r\n]+/g," ")}function on(t){let e="";t.retryMs!==void 0&&(e+=`retry: ${t.retryMs}
|
|
11
|
+
`),t.event!==void 0&&(e+=`event: ${eu(t.event)}
|
|
12
|
+
`),t.id!==void 0&&(e+=`id: ${eu(t.id)}
|
|
13
|
+
`);let n=t.data.split(/\r\n|\r|\n/);for(let i of n)e+=`data: ${i}
|
|
14
|
+
`;return e+`
|
|
15
|
+
`}function sa(t){return`: ${eu(t)}
|
|
16
|
+
|
|
17
|
+
`}function Ao(t){return on({id:String(t.seq),event:t.type,data:JSON.stringify(t)})}var eg="v1",je={maxClientTools:32,toolDescriptionMaxChars:2048,toolParametersMaxBytes:32768,toolParametersMaxDepth:8,toolTimeoutDefaultMs:12e4,toolTimeoutMinMs:1e3,toolTimeoutCapMs:6e5,permissionTimeoutMs:12e4,questionGraceMs:6e4,retentionMs:18e5,idleTimeoutMs:864e5,maxSessionsPerEndUser:8,mediaMaxBodyBytes:20*1024*1024,blocksMaxItems:64,textBlockMaxChars:262144,receiptContentMaxItems:64,receiptErrorMessageMaxChars:4096,answerFreeTextMaxChars:16384,listLimitDefault:50,listLimitMax:200,excludeTokensMax:16,receiptTombstones:256,notifyMaxRetries:3,notifyTimeoutMs:5e3,notifyBackoffMs:500,orphanGraceMs:6e4,idleAfterGoneMs:3e5,maxSubscriberBufferBytes:2*1024*1024,slowSubscriberGraceMs:1e4,sweepIntervalMs:1e4,notifyDeferMs:2e3,notifyMaxInflight:32,notifyMaxQueue:1024,notifyBreakerFailureThreshold:5,notifyBreakerOpenMs:3e4},nu=/^[\x21-\x7E]{1,128}$/,iu=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,ru=/^[a-z][a-z0-9_]*$/,aa=/^image\/(png|jpeg|webp|gif)$/,Oe={unauthorized:"unauthorized",forbidden:"forbidden",sessionNotFound:"session_not_found",sessionEnded:"session_ended",sessionLimitExceeded:"session_limit_exceeded",resumeUnavailable:"resume_unavailable",createFailed:"create_failed",validationFailed:"validation_failed",payloadTooLarge:"payload_too_large",midturnBlocksRejected:"midturn_blocks_rejected",callNotFound:"call_not_found",callAlreadyResolved:"call_already_resolved",callExpired:"call_expired",requestNotFound:"request_not_found",requestAlreadyResolved:"request_already_resolved",requestExpired:"request_expired",digestMismatch:"digest_mismatch",methodNotAllowed:"method_not_allowed",invalidJson:"invalid_json",notFound:"not_found",storeCorrupted:"store_corrupted",internalError:"internal_error",draining:"draining",rateLimited:"rate_limited",overloaded:"overloaded",upstreamUnavailable:"upstream_unavailable",turnRunning:"turn_running",checkpointNotFound:"checkpoint_not_found",sessionMismatch:"session_mismatch",checkpointsNotWired:"checkpoints_not_wired",cwdNotAllowed:"cwd_not_allowed",cwdInvalid:"cwd_invalid",cwdUnavailable:"cwd_unavailable",cwdSwitchUnsupported:"cwd_switch_unsupported",forkSourceNotFound:"fork_source_not_found",checkpointImportInvalid:"checkpoint_import_invalid",capabilityDisabled:"capability_disabled",platformUnavailable:"platform_unavailable"},sn={toolRequest:"server.tool.request",toolCancel:"server.tool.cancel",permissionRequest:"server.permission.request",permissionClosed:"server.permission.closed",questionRequest:"server.question.request",questionClosed:"server.question.closed",platformWarning:"server.platform.warning"},aS=new Set(Object.values(sn));function Er(t){return aS.has(t)}var An="server.replay.gap",Ar={evicted:"evicted",aheadOfLog:"ahead_of_log"},dA=r.object({type:r.literal(An),sessionId:r.string(),requestedAfterSeq:r.number().int(),oldestRetainedSeq:r.number().int().optional(),reason:r.enum([Ar.evicted,Ar.aheadOfLog]).optional(),droppedEvents:r.number().int().nonnegative()}).strict(),da="ts",ca="x-tansr-signature",Eo=r.lazy(()=>r.object({type:r.enum(["string","number","boolean","array","object"]),description:r.string().max(je.toolDescriptionMaxChars).optional(),optional:r.boolean().optional(),items:Eo.optional(),properties:r.record(Eo).optional()}).strict());function tu(t){let e=0;if(t.items!==void 0&&(e=Math.max(e,tu(t.items))),t.properties!==void 0)for(let n of Object.values(t.properties))e=Math.max(e,tu(n));return e+1}var dS=r.enum(["irreversible","financial","external","affects-others"]),Co=r.object({name:r.string().regex(iu),description:r.string().min(1).max(je.toolDescriptionMaxChars),parameters:r.record(Eo).optional(),readOnly:r.boolean().optional(),effects:r.array(dS).max(4).refine(t=>new Set(t).size===t.length,{message:"effects must not repeat"}).optional(),timeoutMs:r.number().int().min(je.toolTimeoutMinMs).max(je.toolTimeoutCapMs).optional()}).strict().superRefine((t,e)=>{if(t.parameters===void 0)return;let n=JSON.stringify(t.parameters);if(Buffer.byteLength(n,"utf8")>je.toolParametersMaxBytes){e.addIssue({code:r.ZodIssueCode.custom,path:["parameters"],message:`parameters exceeds ${je.toolParametersMaxBytes} bytes`});return}for(let[i,o]of Object.entries(t.parameters))tu(o)>je.toolParametersMaxDepth&&e.addIssue({code:r.ZodIssueCode.custom,path:["parameters",i],message:`parameter nesting exceeds depth ${je.toolParametersMaxDepth}`})}),la=r.object({prompt:r.string().optional(),model:r.string().optional(),profile:r.string().optional(),labels:vs.optional(),budget:r.object({maxUsd:r.number().positive().optional(),maxTokens:r.number().int().positive().optional()}).optional(),tools:r.array(r.string().min(1)).optional(),endUser:r.object({id:r.string().regex(nu)}).optional(),resume:r.object({sessionId:r.string().min(1)}).optional(),clientTools:r.array(Co).max(je.maxClientTools).optional(),capabilitiesProfile:r.string().min(1).optional(),thinking:r.object({budget:r.number().int().positive().optional()}).optional(),cwd:r.string().min(1).optional(),fork:r.object({sessionId:r.string().min(1),checkpointId:r.string().min(1)}).optional()}),ou=r.discriminatedUnion("t",[r.object({t:r.literal("text"),text:r.string().min(1).max(je.textBlockMaxChars)}),r.object({t:r.literal("image"),mime:r.string().regex(aa),data:r.string().min(1)})]),ua=r.object({prompt:r.string().optional(),blocks:r.array(ou).min(1).max(je.blocksMaxItems).optional()}).superRefine((t,e)=>{let n=t.prompt!==void 0,i=t.blocks!==void 0;if(n===i){e.addIssue({code:r.ZodIssueCode.custom,message:'exactly one of "prompt" and "blocks" is required'});return}n&&t.prompt.trim()===""&&e.addIssue({code:r.ZodIssueCode.custom,path:["prompt"],message:"prompt must not be blank"})}),su=r.object({historyEpoch:r.string().min(1).max(128),turnId:r.string().min(1).max(128)}).strict(),tg=r.object({inputId:r.string().min(1).max(128),target:su,content:r.union([r.object({text:r.string().min(1).max(je.textBlockMaxChars)}).strict(),r.object({blocks:r.array(r.object({t:r.literal("text"),text:r.string().min(1).max(je.textBlockMaxChars)}).strict()).min(1).max(je.blocksMaxItems)}).strict()]),ack:r.enum(["memory","durable"]).optional()}).strict(),au=cp.superRefine((t,e)=>{t.t==="image"&&!aa.test(t.mime)&&e.addIssue({code:r.ZodIssueCode.custom,path:["mime"],message:"unsupported image mime"})}),Cr=r.discriminatedUnion("status",[r.object({status:r.literal("ok"),content:r.array(au).min(1).max(je.receiptContentMaxItems),isError:r.boolean().optional()}),r.object({status:r.literal("error"),message:r.string().min(1).max(je.receiptErrorMessageMaxChars)})]),du={expiredOnArrival:"expired_on_arrival"},fa=r.object({digest:r.string().min(1),verdict:r.enum(["allow","deny"]),reason:r.enum([du.expiredOnArrival]).optional()}),pa=r.object({answers:r.array(r.object({questionId:r.string().min(1),selectedOptionIds:r.array(r.string()),freeText:r.string().max(je.answerFreeTextMaxChars).optional()})).min(1)});function ma(t){if(t===null||t==="")return[];let e=t.split(",").map(n=>n.trim()).filter(n=>n!=="");if(e.length>je.excludeTokensMax)return null;for(let n of e)if(!ru.test(n))return null;return e}function _o(t,e){for(let n of e)if(t===n||t.startsWith(n+"."))return!0;return!1}var Ji=120,cu=4096,lu=r.union([r.boolean(),r.object({label:r.string().max(Ji).optional()})]),ha=r.object({instructions:r.string().max(cu).optional(),checkpoint:lu.optional()}),ga=r.object({label:r.string().max(Ji).optional()}),ya=r.object({checkpoint:r.boolean().optional()}),va=r.object({cwd:r.string().min(1)}),Po=32*1024*1024,ba="application/octet-stream",Sa="import",Mo=32*1024*1024,uu=/^(data:audio\/[a-z0-9.+-]+;base64,|https?:\/\/)/i,fu=["wav","mp3"],pu=16,mu=64,hu=2048,gu=2e4,wa=r.object({model:r.string().min(1).optional(),audio:r.string().regex(uu),language:r.string().min(2).max(pu).optional(),diarize:r.boolean().optional(),prompt:r.string().max(hu).optional()}),ka=r.object({model:r.string().min(1).optional(),input:r.string().max(gu).refine(t=>t.trim().length>0,{message:"input must not be blank"}),voice:r.string().min(1).max(mu).optional(),format:r.enum(fu).optional(),speed:r.number().positive().optional()}),ng=["transcriptions","speech"];var vu=15e3,bu=3e3,Su=20,cS=sa("hb");function Pr(t,e){return on({event:An,data:JSON.stringify({type:An,sessionId:t,requestedAfterSeq:-1,droppedEvents:e})})}var yu=class{#e;#n;#r;#s;#t=!1;#o;#i=[];#a=[];#c=0;#d;#f;#m=0;#p=!1;#w=0;#v=!1;#k=!1;#y=!1;#B=!1;#E=0;#z=0;#S=0;#g=0;constructor(e,n,i){this.#e=e,this.#n=n,this.#r=i.gapFrame,this.#s=i.beforeFlush}write(e){if(this.#y)return;if(this.#k){this.#p&&this.#_();return}let n=Buffer.byteLength(e,"utf8");if(this.#T(n)){if(this.#i.push(e),this.#a.push(n),this.#c+=n,this.#n.onQueued(n),this.#t){this.#i.length>1&&this.#c>this.#n.maxBufferBytes&&this.#U();return}if(this.#p){this.#_();return}if(this.#c>this.#n.maxBufferBytes){this.#N(),this.#t&&this.#i.length>1&&this.#c>this.#n.maxBufferBytes&&this.#U(),this.#p&&this.#i.length>0&&this.#_();return}this.#v||(this.#v=!0,this.#n.markDirty(this))}}replay(e){if(this.#y||this.#k)return;let n=e[Symbol.iterator]();if(this.#d!==void 0||this.#f!==void 0||this.#i.length>0){for(let i=n.next();i.done!==!0;i=n.next())if(this.write(i.value),this.#y||this.#k){n.return?.();return}return}this.#d=n,!this.#p&&!this.#v&&(this.#v=!0,this.#n.markDirty(this))}end(){if(!(this.#y||this.#k)){if(this.#k=!0,this.#s!==void 0){this.#N();return}if(this.#d!==void 0||this.#f!==void 0){this.#p||this.#j();return}for(;this.#i.length>0&&!this.#y;){let e=this.#Y();e!==void 0&&this.#u(e)}this.#y||this.#I()}}stats(){return{paused:this.#p,queuedBytes:this.#c,queuedFrames:this.#i.length,writes:this.#z,frames:this.#S,droppedFrames:this.#g,closed:this.#y,replaying:this.#d!==void 0||this.#f!==void 0}}writeNow(e){this.#y||this.#k||!this.#T(Buffer.byteLength(e,"utf8"))||(this.#S+=1,this.#n.onWrite(1),this.#u(e))}flush(){this.#v=!1,!(this.#y||this.#p)&&this.#N()}#N(){if(this.#y||this.#t||this.#p&&(!this.#k||this.#d!==void 0||this.#f!==void 0))return;if(this.#s===void 0){this.#j();return}this.#t=!0;let e;try{e=this.#s()}catch{this.#U();return}if(typeof e=="boolean"){this.#J(e);return}let n=this.#n.slowGraceMs;this.#o=setTimeout(()=>this.#U(),Number.isFinite(n)&&n>0?n:je.slowSubscriberGraceMs),this.#o.unref(),Promise.resolve(e).then(i=>this.#J(i),()=>this.#U())}#J(e){if(!this.#y){if(this.#o!==void 0&&clearTimeout(this.#o),this.#o=void 0,this.#t=!1,!e){this.#U();return}if(this.#k&&this.#d===void 0&&this.#f===void 0){for(;this.#i.length>0&&!this.#y;){let n=this.#Y();n!==void 0&&this.#u(n)}this.#y||this.#I();return}this.#j()}}#U(){this.#y||(this.#y=!0,this.#P(),!this.#e.writableEnded&&!this.#e.destroyed&&this.#e.end())}onDrain(){if(this.#y||!this.#p)return;this.#p=!1,this.#w=0,this.#n.onResumed(),(this.#i.length>0||this.#d!==void 0||this.#f!==void 0||this.#k)&&!this.#v&&(this.#v=!0,this.#n.markDirty(this))}onClose(){this.#y=!0,this.#P()}#j(){for(;!this.#p&&!this.#y;){let e=this.#C();if(e===void 0)break;this.#u(e)}this.#k&&!this.#y&&!this.#p&&this.#d===void 0&&this.#f===void 0&&this.#i.length===0&&this.#I()}#C(){if(this.#d!==void 0||this.#f!==void 0){let e=this.#D();if(e!==void 0)return e}if(this.#i.length!==0)return this.#Y()}#D(){let e=this.#n.maxBufferBytes,n=[],i=0;for(this.#f!==void 0&&(n.push(this.#f),i=this.#m,this.#f=void 0,this.#m=0);i<e&&this.#d!==void 0;){let o;try{o=this.#d.next()}catch{this.#d=void 0,this.#y=!0,this.#P(),this.#e.destroy();return}if(o.done===!0){this.#d=void 0;break}let s=Buffer.byteLength(o.value,"utf8");if(!this.#T(s))return;if(i>0&&i+s>e){this.#f=o.value,this.#m=s;break}n.push(o.value),i+=s}if(n.length!==0)return this.#S+=n.length,this.#n.onWrite(n.length),n.length===1?n[0]:n.join("")}#Y(){let e=this.#n.maxBufferBytes,n="",i=0;if(Number.isFinite(this.#n.maxFrameBytes)&&this.#E>0){if(n=this.#r?.(this.#E)??"",i=Buffer.byteLength(n,"utf8"),!this.#T(i))return;if(this.#E=0,i+(this.#a[0]??0)>e)return n}let o=this.#i,s=this.#a,a=0,d=0;for(;a<o.length;){let f=s[a];if(a>0&&i+d+f>e||(d+=f,a+=1,i+d>=e))break}let c;a===o.length?(c=o,this.#i=[],this.#a=[]):(c=o.splice(0,a),s.splice(0,a));let l=n+(c.length===1?c[0]:c.join(""));return this.#E>0&&(this.#r!==void 0&&(l=this.#r(this.#E)+l),this.#E=0),this.#S+=c.length,this.#n.onWrite(c.length),this.#n.onDequeued(d),this.#c-=d,l}#I(){!this.#e.writableEnded&&!this.#e.destroyed&&this.#e.end(),this.#y=!0,this.#P()}#u(e){let n=this.#e;if(n.writableEnded||n.destroyed){this.#y=!0,this.#P();return}this.#z+=1;let i=n.socket;i?.cork();let o=n.write(e);i?.uncork(),!o&&!this.#p&&(this.#p=!0,this.#w=this.#n.now(),this.#n.onPaused())}#T(e){return e<=this.#n.maxFrameBytes?!0:(this.#g+=1,this.#n.onDropped(1),this.#K(),!1)}#_(){let{maxBufferBytes:e,slowGraceMs:n,policy:i}=this.#n;if(i==="drop-oldest"){let a=0;for(;this.#c>e&&this.#i.length>0;){this.#i.shift();let d=this.#a.shift();this.#c-=d,this.#n.onDequeued(d),a+=1}a>0&&(this.#E+=a,this.#g+=a,this.#n.onDropped(a));return}let o=this.#c>e,s=Number.isFinite(n)&&n>0&&this.#n.now()-this.#w>=n;(o||s)&&this.#K()}#K(){let e=this.#i.length;e>0&&(this.#g+=e,this.#n.onDropped(e)),this.#n.onSlowDisconnect(),this.#y=!0,this.#P(),this.#e.destroy()}#P(){if(this.#B)return;this.#B=!0,this.#o!==void 0&&clearTimeout(this.#o),this.#o=void 0,this.#t=!1,this.#c>0&&this.#n.onDequeued(this.#c),this.#i=[],this.#a=[],this.#c=0;let e=this.#d;if(this.#d=void 0,this.#f=void 0,this.#m=0,e!==void 0)try{e.return?.()}catch{}this.#p&&(this.#p=!1,this.#n.onResumed()),this.#n.detach(this)}},_r=class{#e=new Set;#n=[];#r=!1;#s;#t;#o;#i;#a;#c;#d;#f=0;#m=0;#p=0;#w=0;#v=0;#k=0;constructor(e={}){this.#t=e.heartbeatMs??vu,this.#o=e.flushSliceMs??Su,this.#c=e.retryMs??bu,this.#i=e.retryJitterMs??0,this.#a=e.random??Math.random;let n=e.maxFrameBytes??1/0;if(n!==1/0&&(!Number.isSafeInteger(n)||n<1))throw new RangeError("maxFrameBytes must be a positive safe integer or Infinity");let i=e.now??Date.now;this.#d={maxBufferBytes:e.maxBufferBytes??je.maxSubscriberBufferBytes,maxFrameBytes:n,slowGraceMs:e.slowGraceMs??je.slowSubscriberGraceMs,policy:e.onSlowSubscriber??"disconnect",now:i,markDirty:o=>this.#B(o),onPaused:()=>{this.#f+=1},onResumed:()=>{this.#f-=1},onQueued:o=>{this.#m+=o},onDequeued:o=>{this.#m-=o},onWrite:o=>{this.#p+=1,this.#w+=o},onDropped:o=>{this.#v+=o},onSlowDisconnect:()=>{this.#k+=1},detach:o=>this.#z(o)}}get retryMs(){return this.#c}setRetryMs(e){if(!Number.isFinite(e)||e<0)throw new RangeError(`setRetryMs: expected a non-negative finite number, got ${e}`);this.#c=Math.floor(e)}attach(e,n={}){let i=new yu(e,this.#d,n);return this.#e.add(i),this.#e.size===1&&this.#S(),e.on("drain",()=>i.onDrain()),e.on("close",()=>i.onClose()),i.writeNow(on({retryMs:this.#y(),data:""})),i}stats(){return{activeSubscribers:this.#e.size,pausedSubscribers:this.#f,queuedBytes:this.#m,writes:this.#p,frames:this.#w,droppedFrames:this.#v,slowDisconnects:this.#k,heartbeatTimerActive:this.#s!==void 0,retryMs:this.#c}}#y(){return this.#i<=0?this.#c:this.#c+Math.round(this.#a()*this.#i)}#B(e){this.#n.push(e),this.#r||(this.#r=!0,setImmediate(this.#E))}#E=()=>{this.#r=!1;let e=this.#n;this.#n=[];let n=performance.now()+this.#o,i=0;for(;i<e.length&&(e[i].flush(),i+=1,!(performance.now()>=n)););i<e.length&&(this.#n=e.slice(i).concat(this.#n)),this.#n.length>0&&!this.#r&&(this.#r=!0,setImmediate(this.#E))};#z(e){this.#e.delete(e),this.#e.size===0&&this.#g()}#S(){this.#t<=0||this.#s!==void 0||(this.#s=setInterval(()=>this.#N(),this.#t),this.#s.unref())}#g(){this.#s!==void 0&&(clearInterval(this.#s),this.#s=void 0)}#N(){for(let e of this.#e)e.write(cS)}};function xa(...t){let e={size:0,bytes:0,dropped:0};for(let n of t)n!==void 0&&(e.size+=n.size,e.bytes+=n.bytes,e.dropped+=n.dropped);return e}var Ri=class{#e;#n;#r;#s=[];#t;#o=0;#i=0;#a=0;#c=0;#d;constructor(e,n={}){if(!Number.isInteger(e)||e<1)throw new RangeError(`eventBufferSize must be a positive integer, got ${e}`);let i=n.maxBytes??1/0;if(!(typeof i=="number"&&i>0))throw new RangeError(`eventBufferMaxBytes must be a positive number or Infinity, got ${String(i)}`);let o=n.maxEventBytes??1/0;if(o!==1/0&&(!Number.isSafeInteger(o)||o<1))throw new RangeError("maxEventBytes must be a positive safe integer or Infinity");this.#r=o,this.#e=e,this.#n=i,this.#t=i===1/0&&o===1/0?null:[]}append(e,n){let i=this.#t===null?0:n!==void 0&&n>=0?n:Number.isFinite(this.#r)?Buffer.byteLength(JSON.stringify(e),"utf8"):JSON.stringify(e).length;if(Number.isFinite(this.#r)&&(!Number.isSafeInteger(i)||i>this.#r||i>this.#n)){for(;this.#i>0;)this.#m();this.#c+=1,this.#d=e.seq;return}for(this.#i===this.#e&&this.#m();this.#i>0&&this.#a+i>this.#n;)this.#m();this.#f(e,i)}#f(e,n){let i=this.#s.length;if(this.#i<i){let o=(this.#o+this.#i)%i;this.#s[o]=e,this.#t!==null&&(this.#t[o]=n)}else this.#o===0?(this.#s.push(e),this.#t?.push(n)):(this.#s.splice(this.#o,0,e),this.#t?.splice(this.#o,0,n),this.#o+=1);this.#i+=1,this.#a+=n}#m(){let e=this.#s[this.#o];this.#d=e.seq,this.#c+=1,this.#s[this.#o]=void 0,this.#t!==null&&(this.#a-=this.#t[this.#o],this.#t[this.#o]=0),this.#o=(this.#o+1)%this.#s.length,this.#i-=1}eventsAfter(e){let n=[],i=this.#s.length;for(let o=0;o<this.#i;o++){let s=this.#s[(this.#o+o)%i];s.seq>e&&n.push(s)}return n}oldestSeq(){return this.#i===0?void 0:this.#s[this.#o].seq}hasGapAfter(e){return this.#d!==void 0&&e<this.#d}droppedCount(){return this.#c}size(){return this.#i}bytes(){return this.#a}stats(){return{size:this.#i,bytes:this.#a,dropped:this.#c}}};async function Ra(t,e){let n=[],i=t.length,o=t.map(c=>c.then(l=>{n.push({status:"fulfilled",value:l}),i-=1},l=>{n.push({status:"rejected",reason:l}),i-=1})),s=Promise.all(o);if(e===void 0||!Number.isFinite(e)||i===0)return await s,{timedOut:!1,pending:0,settled:n};let a,d=new Promise(c=>{a=setTimeout(()=>c("timeout"),Math.max(0,e)),a.unref()});try{return{timedOut:await Promise.race([s.then(()=>"settled"),d])==="timeout"&&i>0,pending:i,settled:n}}finally{clearTimeout(a)}}var lS=6e4;function*uS(t){for(let e of t)yield Ao(e)}function wu(t,e){if(t.replay!==void 0){t.replay(e);return}for(let n of e)t.write(n)}var Ia=class{#e=new Map;#n=new WeakSet;#r=new Set;#s=[];#t=0;#o=!1;#i;#a=0;#c=[];#d=0;#f;#m;#p;#w;#v;#k=0;#y=0;constructor(e){this.#i=e,this.#m=e.retentionMs??1/0,this.#p=e.maxRetainedSessions??1/0,this.#w=e.now??Date.now,this.#f=this.#m!==1/0||this.#p!==1/0;let n=e.sweepIntervalMs??lS;this.#m!==1/0&&n>0&&(this.#v=setInterval(()=>this.sweepNow(),n),this.#v.unref())}adopt(e){let n=e.sessionId;if(this.#o||this.#e.has(n)){try{e.close()}catch(o){this.#S(o)}throw this.#n.has(e)||(this.#n.add(e),this.#g(e,(async()=>{for await(let o of e.events);})())),new Error(this.#o?"session store is closed":`duplicate sessionId from factory: ${n}`)}let i={handle:e,buffer:new Ri(this.#i.eventBufferSize,{...this.#i.maxEventBytes!==void 0?{maxEventBytes:this.#i.maxEventBytes}:{},...this.#i.eventBufferMaxBytes!==void 0?{maxBytes:this.#i.eventBufferMaxBytes}:{}}),subscribers:new Set,ended:!1,pumpDone:Promise.resolve()};return this.#e.set(n,i),this.#n.add(e),this.#a+=1,i.pumpDone=this.#N(n,i),this.#g(e,i.pumpDone),n}get(e){let n=this.#e.get(e);return n===void 0?void 0:{ended:n.ended}}send(e,n){let i=this.#e.get(e);return i===void 0||i.ended?!1:i.handle.send(n)!=="ended"}interrupt(e){let n=this.#e.get(e);return n===void 0?!1:(n.handle.interrupt(),!0)}subscribe(e,n,i){let o=this.#e.get(e);if(o!==void 0){if(o.buffer.hasGapAfter(n)){let s=o.buffer.oldestSeq(),a={type:An,sessionId:e,requestedAfterSeq:n,...s!==void 0?{oldestRetainedSeq:s}:{},droppedEvents:o.buffer.droppedCount()};i.write(on({event:An,data:JSON.stringify(a)}))}return wu(i,uS(o.buffer.eventsAfter(n))),o.ended?(i.end(),()=>{}):(o.subscribers.add(i),()=>{o.subscribers.delete(i)})}}activeCount(){return this.#a}governanceStats(){return{retainedEnded:this.#e.size-this.#a,evictedByRetention:this.#k,evictedByCap:this.#y}}sweepNow(){if(this.#m===1/0)return;let e=this.#w();for(;;){let n=this.#E();if(n===void 0)break;let[i,o]=n;if(o.endedAt===void 0||e-o.endedAt<this.#m)break;this.#e.delete(i),this.#k+=1}this.#z()}#B(e){for(this.#c.push(e);this.#e.size-this.#a>this.#p;){let n=this.#E();if(n===void 0)break;this.#e.delete(n[0]),this.#y+=1}}#E(){for(;this.#d<this.#c.length;){let e=this.#c[this.#d],n=this.#e.get(e);if(n!==void 0&&n.ended)return[e,n];this.#d+=1}this.#z()}#z(){this.#d>1024&&this.#d*2>this.#c.length&&(this.#c=this.#c.slice(this.#d),this.#d=0)}ringStats(){let e=0,n=0,i=0;for(let o of this.#e.values()){let s=o.buffer.stats();e+=s.size,n+=s.bytes,i+=s.dropped}return{sessions:this.#e.size,size:e,bytes:n,dropped:i}}async closeAll(e={}){this.#o=!0,this.#v!==void 0&&(clearInterval(this.#v),this.#v=void 0);let n=[],i=[];for(let d of this.#e.values()){try{d.handle.close()}catch(c){i.push(c),this.#S(c)}n.push(d.pumpDone)}let{timedOut:o,pending:s,settled:a}=await Ra(n,e.timeoutMs);for(let d of a)d.status==="rejected"&&i.push(d.reason);if(i.length>0)throw new AggregateError(i,"Session close failed.");return{timedOut:o,pending:s}}async settleResources(){for(;this.#r.size>0;)await Promise.all([...this.#r]);if(this.#t>0)throw new AggregateError(this.#s,`Session resource cleanup failed (${this.#t}).`)}#S(e){this.#t+=1,this.#s.length<32&&this.#s.push(e)}#g(e,n){let i=(async()=>{try{await n}catch(o){this.#S(o)}try{await e.settleResources?.()}catch(o){this.#S(o)}})();this.#r.add(i),i.then(()=>this.#r.delete(i))}async#N(e,n){try{for await(let i of n.handle.events){let o=Number.isFinite(this.#i.maxEventBytes),s=n.subscribers.size>0||o?Ao(i):void 0;if(n.buffer.append(i,o&&s!==void 0?Buffer.byteLength(s,"utf8"):s?.length),s!==void 0)for(let a of[...n.subscribers])a.write(s)}}catch(i){this.#i.onPumpError?.(e,i)}finally{n.ended=!0,this.#a=Math.max(0,this.#a-1);for(let i of[...n.subscribers])i.end();n.subscribers.clear(),this.#f&&(n.endedAt=this.#w(),this.#B(e))}}};import{monitorEventLoopDelay as fS}from"node:perf_hooks";var pS=5e3,mS=1e3,hS=6e4,gS=20;function Ft(t){return{"retry-after":String(Math.max(1,Math.ceil(t/1e3)))}}function pi(t,e){let n=t.headers["content-length"];if(typeof n=="string"&&/^\d+$/.test(n)){let i=Number.parseInt(n,10);if(Number.isFinite(i))return Math.min(i,e)}return e}function ni(t,e){let n=Ft(e.retryAfterMs);if(e.reason==="rate_limited"){pe(t,429,Oe.rateLimited,ae.rateLimited,void 0,n);return}if(e.reason==="draining"){pe(t,503,Oe.draining,ae.draining,void 0,n);return}pe(t,503,Oe.overloaded,ae.overloaded,void 0,n)}function yS(t){let e=fS({resolution:gS});e.enable();let n=0,i=setInterval(()=>{n=e.count>0?e.percentile(99)/1e6:0,e.reset()},t);return i.unref(),{p99Ms:()=>n,close:()=>{clearInterval(i),e.disable()}}}function ig(t,e){let n={maxActiveSessions:t.maxActiveSessions??1/0,maxSseConnections:t.maxSseConnections??1/0,maxSseConnectionsPerEndUser:t.maxSseConnectionsPerEndUser??1/0,maxInflightBodyBytes:t.maxInflightBodyBytes??1/0,eventLoopDelayP99Ms:t.eventLoopDelayP99Ms??1/0},i=t.retryAfterMs??pS,o=t.rejectLogIntervalMs??hS,s=e.now??Date.now,a=e.logger,d,c=t.eldSampler;c===void 0&&t.eventLoopDelayP99Ms!==void 0&&(d=yS(t.eventLoopDelayWindowMs??mS),c=d.p99Ms);let l=0,f=new Map,u=0,m=!1,g=!1,h={max_active_sessions:0,max_sse_connections:0,max_sse_connections_per_end_user:0,max_inflight_body_bytes:0,event_loop_delay:0,draining:0,rate_limited:0},p=new Map,v=(w,x,T=i)=>{if(h[w]+=1,w!=="draining"&&a!==void 0){let M=s(),W=p.get(w);if(W===void 0||M-W>=o){p.set(w,M);try{a.error(We(ae.admissionRejected,{reason:w,detail:x}))}catch{}}}return{admitted:!1,reason:w,retryAfterMs:T}},b=()=>c?.(),R=()=>m?{reason:"draining"}:c!==void 0&&c()>n.eventLoopDelayP99Ms?{reason:"event_loop_delay"}:null;return{tryAdmitSession(){let w=R();if(w!==null)return v(w.reason,w.reason==="event_loop_delay"?`p99=${(b()??0).toFixed(1)}ms max=${n.eventLoopDelayP99Ms}ms`:"draining");let x=e.activeSessions();return x>=n.maxActiveSessions?v("max_active_sessions",`active=${x} max=${n.maxActiveSessions}`):{admitted:!0}},tryAdmitSse(w){if(l>=n.maxSseConnections)return v("max_sse_connections",`connections=${l} max=${n.maxSseConnections}`);if(w!==void 0){let x=f.get(w)??0;if(x>=n.maxSseConnectionsPerEndUser)return v("max_sse_connections_per_end_user",`connections=${x} max=${n.maxSseConnectionsPerEndUser}`);f.set(w,x+1)}return l+=1,{admitted:!0}},releaseSse(w){if(l=Math.max(0,l-1),w===void 0)return;let x=f.get(w);x!==void 0&&(x<=1?f.delete(w):f.set(w,x-1))},reserveBody(w){return u+w>n.maxInflightBodyBytes?v("max_inflight_body_bytes",`inflight=${u} request=${w} max=${n.maxInflightBodyBytes}`):(u+=w,{admitted:!0})},releaseBody(w){u=Math.max(0,u-w)},async rateLimit(w,x){if(t.rateLimit===void 0)return{admitted:!0};let T;try{T=await t.rateLimit(w,x)}catch(W){try{a?.error(We(ae.requestUnhandled,{method:"rateLimit",path:"/v2/sessions",message:W instanceof Error?W.message:String(W)}))}catch{}return{admitted:!0}}if(T==="allow")return{admitted:!0};let M=Number.isFinite(T.retryAfterMs)&&T.retryAfterMs>0?T.retryAfterMs:i;return v("rate_limited",`retryAfterMs=${M}`,M)},overloaded:R,readiness(){let w=[];return m&&w.push("draining"),c!==void 0&&c()>n.eventLoopDelayP99Ms&&w.push("event_loop_delay"),{ready:w.length===0,reasons:w}},beginDrain(){m=!0},get draining(){return m},retryAfterMs:i,stats(){let w=b();return{activeSessions:e.activeSessions(),sseConnections:l,inflightBodyBytes:u,...w!==void 0?{eventLoopDelayP99Ms:w}:{},draining:m,rejected:{...h},limits:{...n}}},close(){g||(g=!0,d?.close(),d=void 0)}}}import{monitorEventLoopDelay as qS}from"node:perf_hooks";import{randomUUID as _S}from"node:crypto";var Ta=["messages","inputs","input-capabilities","events","interrupt","history","tool-results","permission","questions","compact","checkpoints","cwd","audio"],rg=new RegExp(`^\\/v2\\/sessions\\/([^/]+)(?:\\/(${Ta.join("|")})(?:\\/([^/]+)(?:\\/(restore|export))?)?)?$`);function vS(t){let e=t.split("/").map(n=>n.startsWith(":")?"[^/]+":n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\/");return new RegExp(`^${e}$`)}function st(t,e,n){return{method:t,endpoint:e,action:n,pattern:vS(n)}}var Aa=[st("POST","SDK2-initialize","/v2/sessions/:id/initialize"),st("GET","SDK2-capabilities","/v2/sessions/:id/execution-capabilities"),st("GET","SDK2-boundary","/v2/sessions/:id/execution-boundary"),st("POST","SDK2-binding","/v2/sessions/:id/execution-bindings"),st("GET","SDK2-execution","/v2/sessions/:id/executions/:targetId"),st("POST","SDK2-executor","/v2/executors/connections"),st("POST","SDK2-heartbeat","/v2/executors/:id/heartbeats"),st("GET","SDK2-poll","/v2/executors/:id/operations"),st("POST","SDK2-receipt","/v2/executors/:id/receipts")],Yi=[st("POST","①","/v2/sessions"),st("GET","②","/v2/sessions"),st("GET","③","/v2/sessions/:id"),st("DELETE","④","/v2/sessions/:id"),st("POST","⑤","/v2/sessions/:id/messages"),st("GET","⑥","/v2/sessions/:id/events"),st("POST","⑦","/v2/sessions/:id/interrupt"),st("GET","⑧","/v2/sessions/:id/history"),st("POST","⑨","/v2/sessions/:id/tool-results/:targetId"),st("POST","⑩","/v2/sessions/:id/permission/:targetId"),st("POST","⑪","/v2/sessions/:id/questions/:targetId"),st("POST","⑫","/v2/sessions/:id/compact"),st("GET","⑬","/v2/sessions/:id/checkpoints"),st("POST","⑭","/v2/sessions/:id/checkpoints"),st("POST","⑱","/v2/sessions/:id/checkpoints/import"),st("POST","⑮","/v2/sessions/:id/checkpoints/:targetId/restore"),st("GET","⑰","/v2/sessions/:id/checkpoints/:targetId/export"),st("DELETE","⑯","/v2/sessions/:id/checkpoints/:targetId"),st("POST","⑲","/v2/sessions/:id/cwd"),st("POST","⑳","/v2/sessions/:id/audio/transcriptions"),st("POST","㉑","/v2/sessions/:id/audio/speech"),st("GET","INJ-capabilities","/v2/sessions/:id/input-capabilities"),st("POST","INJ-submit","/v2/sessions/:id/inputs"),st("GET","INJ-status","/v2/sessions/:id/inputs/:targetId")];function og(t){for(let e of[...Yi,...Aa])if(e.pattern.test(t))return e.action}var an="unified-v1",mi={session:"agent-session-v1",execution:"sdk2-ext-v1",archive:"sdk2-ext-v1","archive-sync":"archive-sync-v1",cache:"sdk2-cache-v1",terminal:"terminal-services-v1","terminal-observation":"terminal-observation-v1","terminal-profile":"terminal-profile-v1"};var Xi="/api/manifest",ku="/api/capabilities",Ii=t=>t[1]??"",bS=[{domain:"session",match:/^\/api\/capabilities\/sessions$/,rewrite:()=>"/v3/sdk2/session-capabilities"},{domain:"archive",match:/^\/api\/capabilities\/archive$/,rewrite:()=>"/v3/sdk2/capabilities"},{domain:"cache",match:/^\/api\/capabilities\/cache$/,rewrite:()=>"/v3/sdk2/cache/capabilities"},{domain:"terminal",match:/^\/api\/capabilities\/terminal$/,rewrite:()=>"/v3/terminal/capabilities"},{domain:"terminal-observation",match:/^\/api\/terminal\/observation(\/.*)?$/,rewrite:t=>`/v3/terminal-observation${Ii(t)}`},{domain:"terminal-profile",match:/^\/api\/terminal\/profile(\/.*)?$/,rewrite:t=>`/v3/terminal-profile${Ii(t)}`},{domain:"terminal",match:/^\/api\/terminal(\/.*)?$/,rewrite:t=>`/v3/terminal${Ii(t)}`},{domain:"cache",match:/^\/api\/cache(\/.*)?$/,rewrite:t=>`/v3/sdk2/cache${Ii(t)}`},{domain:"archive-sync",match:/^\/api\/archive\/sync(\/.*)?$/,rewrite:t=>`/v3/sdk2/archive-sync${Ii(t)}`},{domain:"archive",match:/^\/api\/archive\/bindings(\/.*)?$/,rewrite:t=>`/v3/sdk2/bindings${Ii(t)}`},{domain:"archive",match:/^\/api\/archive\/operations$/,rewrite:()=>"/v3/sdk2/operations"},{domain:"archive",match:/^\/api\/sessions\/([^/]+)\/binding-target$/,rewrite:t=>`/v3/sdk2/sessions/${t[1]}/binding-target`},{domain:"terminal",match:/^\/api\/sessions\/([^/]+)\/(memory(?:\/commands(?:\/[^/]+)?)?|configuration)$/,rewrite:t=>`/v3/terminal/sessions/${t[1]}/${t[2]}`},{domain:"execution",match:/^\/api\/sessions\/([^/]+)\/(initialize|execution-capabilities|execution-boundary|execution-bindings|executions\/[^/]+)$/,rewrite:(t,e)=>`${e.offloadSessions?"/v3/sdk2":"/v2"}/sessions/${t[1]}/${t[2]}`},{domain:"session",match:/^\/api\/sessions(\/.*)?$/,rewrite:(t,e)=>`${e.offloadSessions?"/v3/sdk2":"/v2"}/sessions${Ii(t)}`},{domain:"execution",match:/^\/api\/executors(\/.*)?$/,rewrite:(t,e)=>`${e.offloadSessions?"/v3/sdk2":"/v2"}/executors${Ii(t)}`},{domain:"session",match:/^\/api\/approvals\/([^/]+)\/credential$/,rewrite:t=>`/v1/approvals/${t[1]}/credential`}];function sg(t,e){for(let n of bS){let i=n.match.exec(t);if(i!==null)return{domain:n.domain,legacyPathname:n.rewrite(i,e)}}}function SS(t){let e=t.split("/").map(n=>n.startsWith(":")?"[^/]+":n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\/");return new RegExp(`^${e}$`)}var ag=t=>({template:t,pattern:SS(t)}),wS=[...new Set([...Yi,...Aa].map(t=>t.action.slice(3)))],dg=["/v3/sdk2/session-capabilities","/v3/sdk2/capabilities","/v3/sdk2/operations","/v3/sdk2/bindings","/v3/sdk2/bindings/:id/archive/status","/v3/sdk2/bindings/:id/archive/records","/v3/sdk2/bindings/:id/archive/acks","/v3/sdk2/bindings/:id/archive/ack-rebases","/v3/sdk2/bindings/:id/archive/artifacts/:targetId","/v3/sdk2/bindings/:id/material-responses","/v3/sdk2/bindings/:id/materials/:targetId/uploads/:uploadId/chunks","/v3/sdk2/bindings/:id/materials/:targetId/uploads/:uploadId","/v3/sdk2/bindings/:id/materials/:targetId","/v3/sdk2/bindings/:id/events","/v3/sdk2/bindings/:id/close","/v3/sdk2/bindings/:id","/v3/sdk2/archive-sync/:id","/v3/sdk2/cache/capabilities","/v3/sdk2/cache/bindings","/v3/sdk2/cache/operations","/v3/sdk2/cache/core/v1/bindings/:id/diagnostics","/v3/sdk2/cache/bindings/:id/diagnostics","/v3/sdk2/cache/bindings/:id/renew","/v3/sdk2/cache/bindings/:id/rebind","/v3/sdk2/cache/bindings/:id/rotate","/v3/sdk2/cache/bindings/:id/close","/v3/sdk2/cache/bindings/:id","/v3/sdk2/sessions/:id/binding-target",...wS.map(t=>`/v3/sdk2${t}`),"/v3/terminal/capabilities","/v3/terminal/bindings","/v3/terminal/executors/:id/events","/v3/terminal/executors/:id/output-batches","/v3/terminal/executors/:id/operations/:targetId","/v3/terminal/sessions/:id/tool-output","/v3/terminal/sessions/:id/tool-output-status","/v3/terminal/sessions/:id/configuration","/v3/terminal/sessions/:id/memory/commands/:targetId","/v3/terminal/sessions/:id/memory/commands","/v3/terminal/sessions/:id/memory","/v3/terminal-observation/sessions/:id/resources","/v3/terminal-observation/sessions/:id/output-correlations","/v3/terminal-profile/sessions/:id/catalog","/v3/terminal-profile/sessions/:id/usage"],kS=dg.map(ag),xS=["/v1/approvals/:id/credential"];function RS(t){return t.endsWith("/permission/:targetId")||t.endsWith("/questions/:targetId")?`${t.slice(0,-9)}:ticketId`:t}function xu(t){let e=IS(t);return e===void 0?void 0:RS(e)}function IS(t){if(t==="/v1/approvals/:id/credential")return"/api/approvals/:id/credential";if(t==="/v3/sdk2/session-capabilities")return"/api/capabilities/sessions";if(t==="/v3/sdk2/capabilities")return"/api/capabilities/archive";if(t==="/v3/sdk2/cache/capabilities")return"/api/capabilities/cache";if(t==="/v3/terminal/capabilities")return"/api/capabilities/terminal";if(t==="/v3/sdk2/operations")return"/api/archive/operations";if(t.startsWith("/v3/terminal-observation/"))return`/api/terminal/observation${t.slice(24)}`;if(t.startsWith("/v3/terminal-profile/"))return`/api/terminal/profile${t.slice(20)}`;if(t.startsWith("/v3/terminal/"))return`/api/terminal${t.slice(12)}`;if(t.startsWith("/v3/sdk2/cache/"))return`/api/cache${t.slice(14)}`;if(t.startsWith("/v3/sdk2/archive-sync/"))return`/api/archive/sync${t.slice(21)}`;if(t==="/v3/sdk2/bindings"||t.startsWith("/v3/sdk2/bindings/"))return`/api/archive/bindings${t.slice(17)}`;if(t.startsWith("/v3/sdk2/sessions")||t.startsWith("/v3/sdk2/executors"))return`/api${t.slice(8)}`;if(t.startsWith("/v2/"))return`/api${t.slice(3)}`}var TS="/api/sessions/:id/capabilities",AS=["/api/sessions/:id/memory/commands/:targetId","/api/sessions/:id/memory/commands","/api/sessions/:id/memory","/api/sessions/:id/configuration"],ES=[Xi,ku,TS,...AS,...new Set([...dg,...Yi.map(t=>t.action),...Aa.map(t=>t.action),...xS].map(xu).filter(t=>t!==void 0))],CS=ES.map(ag);function cg(t){for(let e of kS)if(e.pattern.test(t))return e.template}function lg(t){for(let e of CS)if(e.pattern.test(t))return e.template}var PS=/^\/v1\/sessions\/[^/]+\/(messages|events|abort)$/,MS=/^\/v1\/approvals\/[^/]+\/credential$/,En={healthz:"/healthz",readyz:"/readyz",metrics:"/metrics"};function Ea(t){if(t.startsWith("/api/"))return lg(t)??"other";if(t.startsWith("/v3/"))return cg(t)??"other";switch(t){case"/v1/sessions":case"/v1/status":case En.healthz:case En.readyz:case En.metrics:return t;default:break}let e=PS.exec(t);return e!==null?`/v1/sessions/:id/${e[1]}`:MS.test(t)?"/v1/approvals/:id/credential":og(t)??"other"}var Oo="x-request-id",OS=/^[A-Za-z0-9._-]{1,128}$/,BS=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function ug(t){if(t!==void 0)return Array.isArray(t)?t[0]:t}function Ca(t){let e=ug(t.headers[Oo])?.trim();if(e!==void 0&&OS.test(e))return e;let n=ug(t.headers.traceparent)?.trim().toLowerCase();if(n!==void 0){let i=BS.exec(n);if(i!==null&&i[1]!=="ff"&&!/^0{32}$/.test(i[2]))return i[2]}return _S()}var fg=new WeakMap,pg=new WeakMap;function mg(t,e,n){fg.set(t,n),pg.set(e,n)}function ii(t){return fg.get(t)}function hg(t){return pg.get(t)}var DS=Cp.filter(t=>t<=3e4),gg=new WeakMap;function Qn(t=wi){let e=gg.get(t);if(e!==void 0)return e;let n={registry:t,httpRequests:t.counter("tansr_serve_http_requests_total","HTTP requests by method, templated route and response status (0 = connection closed before headers).",["method","route","status"]),httpRequestDurationMs:t.histogram("tansr_serve_http_request_duration_ms","HTTP request wall time from arrival to response close, by templated route, in milliseconds.",DS,["route"]),rejections:t.counter("tansr_serve_rejections_total","Rejected requests by status class word (401/403/404/405/409/410/413/422/429, other 4xx, 5xx).",["code"]),sessionsActive:t.gauge("tansr_serve_sessions_active","Active (not ended) sessions by protocol face.",["face"]),sessionsPending:t.gauge("tansr_serve_sessions_pending","/v2 sessions reserved (create in flight) but not yet adopted."),sessionsRetainedEnded:t.gauge("tansr_serve_sessions_retained_ended","/v2 ended sessions still retained in memory for Last-Event-ID replay."),sseConnectionsActive:t.gauge("tansr_serve_sse_connections_active","Open SSE responses (text/event-stream) currently being written."),sseFramesWritten:t.counter("tansr_serve_sse_frames_written_total","SSE frames written to subscribers."),replayGaps:t.counter("tansr_serve_replay_gap_total","Subscriptions whose Last-Event-ID fell outside the replay window (gap frame sent)."),ringEvictions:t.counter("tansr_serve_ring_evictions_total","Events evicted from per-session replay ring buffers."),eventLoopDelayMs:t.gauge("tansr_serve_event_loop_delay_ms","Event loop delay over the last collection window by statistic (p50, p99, max), in milliseconds.",["stat"]),residentMemoryBytes:t.gauge("process_resident_memory_bytes","Resident set size of the process in bytes."),webhookDeliveries:t.counter("tansr_serve_webhook_deliveries_total","Turn-end webhook deliveries by result (delivered, failed after retries, dropped_queue_full, dropped_circuit_open).",["result"]),storeCommitErrors:t.counter("tansr_serve_store_commit_errors_total","Session store turn-end commit failures."),storeCreateErrors:t.counter("tansr_serve_store_create_errors_total","Session store create/record failures."),tokenMintFailures:t.counter("tansr_serve_token_mint_failures_total","Platform app_user token mint failures."),tokenInvalidations:t.counter("tansr_serve_token_invalidations_total","Cached platform app_user tokens judged invalid by an upstream 401 (by envelope detail.reason); each is followed by exactly one re-mint and retry.",["reason"]),pumpErrors:t.counter("tansr_serve_pump_errors_total","/v2 session event pump failures (event log append or fan-out threw); the session handle is closed each time."),upstreamInflight:t.gauge("tansr_serve_upstream_inflight","Upstream model requests in flight (response body not yet finished) by origin host[:port].",["origin"]),upstreamQueued:t.gauge("tansr_serve_upstream_queued","Upstream model requests waiting in the bulkhead or token-bucket queue by origin host[:port].",["origin"]),upstreamRejections:t.counter("tansr_serve_upstream_rejections_total","Upstream requests rejected before send by the governor, by origin and reason (saturated, queue_timeout, breaker_open, closed).",["origin","reason"]),upstreamBreakerState:t.gauge("tansr_serve_upstream_breaker_state","Upstream circuit breaker state by origin: 0 = closed (or no breaker), 1 = open, 2 = half_open.",["origin"]),upstreamRetriesBudgeted:t.counter("tansr_serve_upstream_retries_budgeted_total","Retries suppressed by the process-level retry budget (treated as terminal failures).")};return gg.set(t,n),n}function _a(t){if(!(t<400)){if(t>=500)return"5xx";switch(t){case 401:case 403:case 404:case 405:case 409:case 410:case 413:case 422:case 429:return String(t);default:return"4xx"}}}function yg(t){let e=t.stats?.(),n=e?.active??t.activeCount(),i=e?.retainedEnded??Math.max(0,t.entries().length-n);return{active:n,retainedEnded:i,...e?.pending!==void 0?{pending:e.pending}:{}}}function Pa(t){let e=t.trim().toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="::1"||e==="0:0:0:0:0:0:0:1"?!0:e.startsWith("::ffff:")?Pa(e.slice(7)):/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function jS(){let t;try{t=qS({resolution:20}),t.enable()}catch{t=void 0}return{sample:()=>{if(t===void 0)return{p50:0,p99:0,max:0};let e=i=>Number.isFinite(i)?i/1e6:0,n={p50:e(t.percentile(50)),p99:e(t.percentile(99)),max:e(t.max)};return t.reset(),n},dispose:()=>{t?.disable()}}}function NS(t,e){let n=t.getHeader("content-type");if(typeof n=="string")return n;if(Array.isArray(n))return n[0];let i=e.length>1?e[e.length-1]:void 0;if(!(i==null||typeof i!="object")){if(Array.isArray(i)){let o=i;for(let s=0;s<o.length;s+=1){let a=o[s];if(Array.isArray(a)){if(String(a[0]).toLowerCase()==="content-type")return String(a[1])}else if(typeof a=="string"&&a.toLowerCase()==="content-type")return String(o[s+1])}return}for(let[o,s]of Object.entries(i))if(o.toLowerCase()==="content-type")return Array.isArray(s)?String(s[0]):String(s)}}function US(t,e){return typeof t=="boolean"?{ready:t,reason:`probe_${e}`}:{ready:t.ready,reason:t.reason??`probe_${e}`}}function vg(t){let e=t.options??{},n=t.now??Date.now,i=e.metrics??wi,o=Qn(i);Es(wi);let s=Pa(t.host),a=e.exposeHealth??e.expose??s,d=e.exposeMetrics??e.expose??s,c=e.requestLogSampleRate,l=typeof c=="number"&&Number.isFinite(c)?Math.min(1,Math.max(0,c)):1,f=()=>l>=1||l>0&&Math.random()<l,u=jS(),m=new Set(e.readinessProbes??[]),g=new Set,h=0,p=0,v=!1,b=()=>u.sample(),R=()=>{let S=t.v1Active(),k=t.v2();o.sessionsActive.set(S,{face:"v1"}),o.sessionsActive.set(k?.active??0,{face:"v2"}),k?.pending!==void 0&&o.sessionsPending.set(k.pending),k?.retainedEnded!==void 0&&o.sessionsRetainedEnded.set(k.retainedEnded),o.sseConnectionsActive.set(h);let A=b();o.eventLoopDelayMs.set(A.p50,{stat:"p50"}),o.eventLoopDelayMs.set(A.p99,{stat:"p99"}),o.eventLoopDelayMs.set(A.max,{stat:"max"}),o.residentMemoryBytes.set(process.memoryUsage.rss());let C=t.notifierStats();C!==void 0&&(o.webhookDeliveries.set(C.delivered,{result:"delivered"}),o.webhookDeliveries.set(C.failed,{result:"failed"}),o.webhookDeliveries.set(C.droppedQueueFull,{result:"dropped_queue_full"}),o.webhookDeliveries.set(C.droppedCircuitOpen,{result:"dropped_circuit_open"}));let F=t.sseStats?.();F!==void 0&&o.sseFramesWritten.set(F.frames);let H=t.ringStats?.();H!==void 0&&o.ringEvictions.set(H.dropped);let Q=w();if(Q!==void 0){for(let re of Q.origins){let O={origin:re.origin};o.upstreamInflight.set(re.inflight,O),o.upstreamQueued.set(re.queued+re.tokenQueued,O),o.upstreamBreakerState.set(re.breakerStateCode,O);for(let[I,B]of Object.entries(re.rejected))o.upstreamRejections.set(B,{origin:re.origin,reason:I})}o.upstreamRetriesBudgeted.set(Q.totals.retriesBudgeted)}},w=()=>{if(t.governorStats!==void 0)try{return t.governorStats()}catch{return}},x=i.onCollect(R),T=()=>{let S=[];t.closing()&&S.push("closing");let k=0;for(let A of m){k+=1;try{let C=US(A(),k);C.ready||S.push(C.reason)}catch{S.push(`probe_${k}_threw`)}}return{ready:S.length===0,reasons:S}},M=()=>{let S=t.v1Active(),k=t.v2(),A=process.memoryUsage(),C=t.notifierStats(),F=t.ringStats?.(),H=w();return{uptimeMs:n()-t.startedAt,closing:t.closing(),sessions:{active:S+(k?.active??0),byFace:{v1:S,v2:k?.active??0},...k?.pending!==void 0?{pending:k.pending}:{},...k?.retainedEnded!==void 0?{retainedEnded:k.retainedEnded}:{}},sse:{connectionsActive:h,framesWritten:t.sseStats?.()?.frames??o.sseFramesWritten.get()},http:{inflight:g.size,requestsTotal:p},replay:{gapTotal:o.replayGaps.get(),ringEvictionsTotal:F?.dropped??o.ringEvictions.get(),...F!==void 0?{ringEvents:F.size,ringBytes:F.bytes}:{}},eventLoopDelayMs:b(),memory:{rssBytes:A.rss,heapUsedBytes:A.heapUsed},...C!==void 0?{notifier:C}:{},...H!==void 0?{upstream:H}:{},readiness:T()}},W=(S,k)=>{let A;if(k.startsWith("/v1/sessions/:id")||k.startsWith("/v2/sessions/:id")||k.startsWith("/api/sessions/:id"))A=3;else if(k.startsWith("/v3/sdk2/sessions/:id"))A=4;else return;let C=S.split("/")[A];if(C===void 0)return;let F=fi(C)??C;return F.length>128?`${F.slice(0,125)}...`:F},$=(S,k)=>{let A=S.method??"GET",C=(S.url??"/").split("?",1)[0],F=Ea(C),H={requestId:Ca(S),startedAt:n(),method:A,route:F,sse:!1};mg(S,k,H),g.add(H),k.headersSent||k.setHeader(Oo,H.requestId);let Q=W(C,F),re=()=>({requestId:H.requestId,method:A,route:F,...Q!==void 0?{sessionId:Q}:{},...H.endUserId!==void 0?{endUserId:H.endUserId}:{}}),O=k.writeHead,I=!1,B=ne=>{if(I)return;I=!0;let U=NS(k,ne);U!==void 0&&U.startsWith("text/event-stream")&&(H.sse=!0,h+=1,t.log("info",Xe.sseOpened,re()))};k.writeHead=function(...U){let le=O.apply(this,U);return B(U),le};let z=!1,j=()=>{if(z)return;z=!0,g.delete(H),p+=1,H.sse&&(h=Math.max(0,h-1));let ne=k.headersSent?k.statusCode:0,U=Math.max(0,n()-H.startedAt),le={method:A,route:F,status:String(ne)};o.httpRequests.inc(le),o.httpRequestDurationMs.observe(U,{route:F});let ue=_a(ne);ue!==void 0&&o.rejections.inc({code:ue}),H.sse&&t.log("info",Xe.sseClosed,{...re(),reason:k.writableEnded?"ended":"aborted",durationMs:U}),f()&&t.log("info",Xe.requestCompleted,{...re(),status:ne,durationMs:U,...H.sse?{sse:!0}:{}})};return k.once("close",j),H},D=(S,k,A,C)=>{let F=A===En.healthz||A===En.readyz,H=A===En.metrics;if(!(F&&a)&&!(H&&d))return!1;if(C!=="GET"&&C!=="HEAD")return pe(k,405,"method_not_allowed",ae.methodNotAllowed,{method:C,path:A},{allow:"GET"}),!0;if(A===En.healthz)return Je(k,200,{status:"ok"}),!0;if(A===En.readyz){let re=T();return Je(k,re.ready?200:503,re),!0}let Q=J();return k.writeHead(200,{"content-type":As,"content-length":Buffer.byteLength(Q),"cache-control":"no-store"}),k.end(C==="HEAD"?void 0:Q),!0},J=()=>Ts([wi,i]);return{metrics:o,registry:i,exposeHealth:a,exposeMetrics:d,trackRequest:$,handleEndpoint:D,stats:M,readiness:T,renderMetrics:J,addReadinessProbe:S=>(m.add(S),()=>{m.delete(S)}),sseActive:()=>h,close:()=>{v||(v=!0,x(),u.dispose())}}}var Bo="TANSR_READY ",bg=1,Sg=["stdout","stderr","none"];function Ru(t){let e={v:1,url:t.url,pid:t.pid,readyz:t.readyz};return`${Bo}${JSON.stringify(e)}
|
|
18
|
+
`}function wg(t){let e=t.replace(/\r?\n$/u,"");if(!e.startsWith(Bo))return;let n;try{n=JSON.parse(e.slice(Bo.length))}catch{return}if(typeof n!="object"||n===null)return;let i=n;if(!(typeof i.url!="string"||i.url===""))return{v:typeof i.v=="number"?i.v:1,url:i.url,pid:typeof i.pid=="number"?i.pid:-1,readyz:typeof i.readyz=="string"?i.readyz:"/readyz"}}function Ma(t,e){let n=t??"stdout";if(n==="none")return;let i=Ru(e);try{typeof n=="function"?n(i):n==="stderr"?process.stderr.write(i):process.stdout.write(i)}catch{}}import{createHash as LS,createHmac as kg,randomUUID as FS}from"node:crypto";var xg=["v1","v2"],Iu=["v2","v1"];function Tu(t){let e=[],n={};for(let i of t.versions){if(i==="v1"){e.push(`v1=${kg("sha256",t.secret).update(t.body,"utf8").digest("hex")}`);continue}let o=[no.canonicalPrefix,(t.method??"POST").toUpperCase(),t.path,String(t.timestampMs),t.nonce,LS("sha256").update(t.body,"utf8").digest("hex")].join(`
|
|
19
|
+
`);e.push(`${no.prefix}${kg("sha256",t.secret).update(o).digest("hex")}`),n[no.headers.timestamp]=String(t.timestampMs),n[no.headers.nonce]=t.nonce}return e.length>0&&(n[ca]=e.join(", ")),n}var Mr=class{#e;#n;#r;#s;#t;#o;#i;#a;#c;#d;#f;#m;#p;#w;#v=new Set;#k=[];#y=new AbortController;#B=!1;#E="closed";#z=0;#S=0;#g=0;#N=0;#J=0;#U=0;constructor(e){this.#e=e.url,this.#n=e.secret,this.#r=[...new Set(e.signatureVersions??Iu)],this.#s=(()=>{try{return new URL(e.url).pathname}catch{return""}})(),this.#t=e.maxRetries??je.notifyMaxRetries,this.#o=e.timeoutMs??je.notifyTimeoutMs,this.#i=e.backoffMs??je.notifyBackoffMs,this.#a=e.maxInflight??je.notifyMaxInflight,this.#c=e.maxQueue??je.notifyMaxQueue,this.#d=e.breakerFailureThreshold??je.notifyBreakerFailureThreshold,this.#f=e.breakerOpenMs??je.notifyBreakerOpenMs,this.#m=e.fetchImpl??fetch,this.#p=e.now??Date.now,this.#w=e.onDeliveryFailure}notify(e){if(!this.#B){if(!this.#j()){this.#N+=1,this.#T(e,0,"circuit_open");return}if(this.#k.length===0&&this.#v.size<this.#a){this.#D(e);return}if(this.#k.length>=this.#c){this.#g+=1,this.#T(e,0,"queue_full");return}this.#k.push(e)}}stats(){return{inflight:this.#v.size,queued:this.#k.length,breakerState:this.#C(),droppedQueueFull:this.#g,droppedCircuitOpen:this.#N,delivered:this.#J,failed:this.#U}}async close(){this.#B=!0,this.#y.abort(),this.#k.length=0,await Promise.all([...this.#v])}#j(){return this.#E==="closed"?!0:this.#E==="open"&&this.#p()>=this.#z?(this.#E="half_open",!0):!1}#C(){return this.#E==="open"&&this.#p()>=this.#z?"half_open":this.#E}#D(e){let n=this.#_(e).catch(()=>{});this.#v.add(n),n.finally(()=>{this.#v.delete(n),this.#Y()})}#Y(){for(;!this.#B&&this.#v.size<this.#a;){let e=this.#k.shift();if(e===void 0)return;this.#D(e)}}#I(){this.#J+=1,this.#S=0,this.#E="closed"}#u(){if(this.#U+=1,this.#S+=1,!(this.#E!=="closed"||this.#S>=this.#d))return;this.#E="open",this.#z=this.#p()+this.#f;let n=this.#k.splice(0);for(let i of n)this.#N+=1,this.#T(i,0,"circuit_open")}#T(e,n,i){try{this.#w?.({sessionId:e.sessionId,...e.turnId!==void 0?{turnId:e.turnId}:{},url:this.#e,attempts:n,reason:i})}catch{}}async#_(e){let n=JSON.stringify(e),i={"content-type":"application/json"};this.#n!==void 0&&Object.assign(i,Tu({secret:this.#n,body:n,versions:this.#r,path:this.#s,timestampMs:this.#p(),nonce:FS()}));let o="unknown";for(let s=1;s<=1+this.#t;s++){if(this.#B||s>1&&(await this.#K(this.#i*2**(s-2)),this.#B))return;try{let a=await this.#m(this.#e,{method:"POST",headers:i,body:n,signal:AbortSignal.any([this.#y.signal,AbortSignal.timeout(this.#o)])});if(await a.arrayBuffer().catch(()=>{}),a.ok){this.#I();return}o=`http_${a.status}`}catch(a){if(this.#B)return;o=a instanceof Error?`${a.name}: ${a.message}`:String(a)}}this.#T(e,1+this.#t,o),this.#u()}#K(e){return new Promise(n=>{let i=()=>{clearTimeout(o),n()},o=setTimeout(()=>{this.#y.signal.removeEventListener("abort",i),n()},e);o.unref(),this.#y.signal.addEventListener("abort",i,{once:!0})})}};var Or=class{#e;#n;#r;constructor(e,n={}){let{floorSeq:i,...o}=n;if(this.#e=new Ri(e,o),i!==void 0&&(!Number.isSafeInteger(i)||i<0))throw new RangeError(`floorSeq 必须为非负安全整数,收到 ${String(i)}`);this.#n=i??0,this.#r=this.#n-1}append(e,n){return this.#e.append(e,n),this.#r=e.seq,e.seq}readAfter(e,n){let i=this.#e.eventsAfter(e),o=n!==void 0&&n>=0&&i.length>n?i.slice(0,n):i,s=this.#e.oldestSeq();return{events:o,...s!==void 0?{oldestRetainedSeq:s}:{},dropped:this.#e.droppedCount(),gap:this.#e.hasGapAfter(e)||e>this.#r||e>=0&&e<this.#n-1}}lastSeq(){return this.#r}stats(){return this.#e.stats()}close(){}};function Ba(t){if(Er(t.type)){let e=t;return on({id:String(t.seq),event:t.type,data:JSON.stringify({...e.payload,[da]:e.ts})})}return on({id:String(t.seq),data:JSON.stringify(t)})}function*HS(t,e,n){for(let i of t)n&&i.seq<n()||!Er(i.type)&&_o(i.type,e)||(yield Ba(i))}var Au=class{id;endUserId;outcome;#e;#n;#r="issued";#s=!1;#t;#o;constructor(e,n,i,o){this.id=e,this.endUserId=n,this.#t=i,this.#o=o,this.outcome=new Promise((s,a)=>{this.#e=s,this.#n=a}),this.outcome.catch(()=>{})}run(e){if(this.#r!=="issued")throw new Error(`create ticket already ${this.#r} (sessionId ${this.id??"<new>"})`);this.#r="running";let n;try{n=e()}catch(i){n=Promise.reject(i)}return n.then(i=>this.#i(()=>this.#e(i)),i=>this.#i(()=>this.#n(i))),this.outcome}adopt(e){if(this.#r!=="running")throw new Error(`create ticket adopt outside run (state ${this.#r})`);let n=this.#t.adopt(e,{reserved:!0});return this.#s=!0,n}abandon(e){this.#r==="issued"&&this.#i(()=>this.#n(e))}#i(e){this.#r="settled",this.#o(this,this.#s),e()}},hi=class extends Error{constructor(){super("registry is closing; new sessions are not accepted"),this.name="RegistryClosingError"}},Oa=class{#e=new WeakSet;#n=new WeakMap;#r=new Set;#s=[];#t=new Set;#o=0;#i=new Map;#a=new Map;#c=new Map;#d=[];#f=0;#m=new Map;#p=new Map;#w=0;#v=0;#k;#y;#B;#E;#z;#S;#g;#N;#J;#U;#j;#C;#D;#Y;#I;#u;#T;#_;#K;#P=!1;#Q={evictedByRetention:0,evictedByCap:0,idleCloses:0,orphanInterrupts:0,orphanCloses:0,lifetimeCloses:0,turnCapCloses:0,hookErrors:0,deferredNotifies:0,deferredNotifySent:0,pumpErrors:0};constructor(e){this.#B=e.maxEventBytes,this.#k=e.eventBufferSize,this.#y=e.eventBufferMaxBytes,this.#E=e.eventLog,this.#z=e.retentionMs??je.retentionMs,this.#S=e.idleTimeoutMs??je.idleTimeoutMs,this.#g=e.maxSessionsPerEndUser??je.maxSessionsPerEndUser,this.#N=e.maxRetainedSessions??1/0,this.#J=e.orphanGraceMs??je.orphanGraceMs,this.#U=e.idleAfterGoneMs??je.idleAfterGoneMs,this.#j=e.maxSessionLifetimeMs??1/0,this.#C=e.maxTurnsPerSession??1/0,this.#D=e.onSubscribersGone,this.#Y=e.notifyDeferMs??je.notifyDeferMs,this.#I=e.now??Date.now,this.#u=e.onPumpError,this.#_=e.onSweep,this.#T=e.onTurnEndNotify;let n=e.sweepIntervalMs??je.sweepIntervalMs;n>0&&(this.#K=setInterval(()=>this.sweepNow(),n),this.#K.unref())}governanceStats(){return{retainedEnded:this.#ne(),...this.#Q}}stats(){return{active:this.#w,pending:this.#v,retainedEnded:this.#ne()}}#ne(){return this.#i.size-this.#w}ringStats(){let e=0,n=0,i=0;for(let o of this.#i.values()){let s=o.log.stats();e+=s.size,n+=s.bytes,i+=s.dropped}return{sessions:this.#i.size,size:e,bytes:n,dropped:i}}eventLogOf(e){return this.#i.get(e)?.log}get maxSessionsPerEndUser(){return this.#g}activeCountFor(e){return this.#a.get(e)?.active??0}pendingCountFor(e){return this.#a.get(e)?.pending??0}activeCount(){return this.#w}pendingCount(){return this.#v}tryReserve(e){if(this.#P)return!1;let n=this.#L(e);return n.active+n.pending>=this.#g?(this.#b(e,n),!1):(n.pending+=1,this.#v+=1,!0)}get closing(){return this.#P}pendingCreate(e){return this.#c.get(e)}beginCreate(e,n){if(this.#P)return{kind:"closing"};if(e!==void 0){let o=this.#i.get(e);if(o!==void 0){if(o.handle.endUserId!==n)return{kind:"forbidden"};if(!o.ended)return{kind:"live",handle:o.handle}}let s=this.#c.get(e);if(s!==void 0)return s.endUserId!==n?{kind:"forbidden"}:{kind:"joined",outcome:s.outcome}}if(!this.tryReserve(n))return{kind:"reserve_rejected",max:this.#g};let i=new Au(e,n,this,(o,s)=>this.#V(o,s));return e!==void 0&&this.#c.set(e,{endUserId:n,outcome:i.outcome}),{kind:"ticket",ticket:i}}#V(e,n){if(e.id!==void 0){let i=this.#c.get(e.id);i!==void 0&&i.outcome===e.outcome&&this.#c.delete(e.id)}n||this.release(e.endUserId)}release(e){let n=this.#a.get(e);n!==void 0&&(n.pending>0&&(n.pending-=1,this.#v=Math.max(0,this.#v-1)),this.#b(e,n))}adopt(e,n={}){let i=e.sessionId;if(this.#P)throw this.#ie(e),new hi;if(this.#i.has(i))throw this.#ie(e),new Error(`duplicate v2 sessionId from factory: ${i}`);let o=e.firstSeq?.()??0,s;try{s=this.#ee(e,o)}catch(l){throw this.#ie(e),l}let a=this.#L(e.endUserId);if(n.reserved===!0){if(a.pending<=0)throw this.#ie(e),this.#b(e.endUserId,a),new Error(`adopt: no pending reservation for endUser ${e.endUserId}`);a.pending-=1,this.#v=Math.max(0,this.#v-1)}let d=this.#I(),c={handle:e,log:s,logClosed:!1,replayWaiters:new Set,epochStartSeq:o,subscribers:new Set,ended:!1,lastActivityAt:d,turnEndDecided:!1,pumpDone:Promise.resolve(),adoptedAt:d,goneRunningDecided:!1,goneIdleDecided:!1,closeRequested:!1,turns:0};return this.#i.set(i,c),this.#m.set(i,c),a.ids.add(i),a.active+=1,this.#w+=1,c.pumpDone=this.#Te(i,c),i}get(e){let n=this.#i.get(e);if(n!==void 0)return{handle:n.handle,ended:n.ended}}entries(){return[...this.#i.values()].map(e=>({handle:e.handle,ended:e.ended}))}entriesFor(e){let n=this.#a.get(e);if(n===void 0)return[];let i=[];for(let o of n.ids){let s=this.#i.get(o);s!==void 0&&i.push({handle:s.handle,ended:s.ended})}return i}evictEnded(e){let n=this.#i.get(e);n!==void 0&&n.ended&&this.#q(e,n)}requestClose(e){let n=this.#i.get(e);if(!(n===void 0||n.closeRequested)){n.closeRequested=!0;try{n.handle.close()}catch(i){throw n.closeFailure="close_failed",this.#te(i,"close_failed"),i}}}resourceObservation(e){let n=this.#i.get(e);if(!n)return;let i=this.#n.get(n.handle),o=n.closeFailure??i?.errorCode??null,s=n.closeFailure||i?.state==="failed"?"failed":n.ended?i?.state==="completed"?"completed":i?.state==="unknown"?"unknown":"draining":n.closeRequested?"accepted":"active";return{epochStartSeq:String(n.epochStartSeq),state:s,closeRequested:n.closeRequested,executionEnded:n.ended,errorCode:o}}#L(e){let n=this.#a.get(e);return n===void 0&&(n={active:0,pending:0,ids:new Set},this.#a.set(e,n)),n}#b(e,n){n.active===0&&n.pending===0&&n.ids.size===0&&this.#a.delete(e)}#ee(e,n){return this.#E!==void 0?this.#E({sessionId:e.sessionId,endUserId:e.endUserId,...n>0?{epochStartSeq:n}:{}}):new Or(this.#k,{...this.#y!==void 0?{maxBytes:this.#y}:{},...this.#B!==void 0?{maxEventBytes:this.#B}:{},floorSeq:n})}#A(e,n){if(!n.logClosed){n.logClosed=!0;try{n.log.close()}catch(i){this.#u?.(e,i)}}}#q(e,n){n.replayWaiters.size>0&&this.#pe(n,new Error("Event publication was evicted")),this.#i.delete(e),this.#m.delete(e),this.#p.delete(e),this.#A(e,n);let i=n.handle.endUserId,o=this.#a.get(i);o!==void 0&&(o.ids.delete(e),this.#b(i,o))}#de(e,n){let i=this.#a.get(n.handle.endUserId);for(i!==void 0&&(i.active=Math.max(0,i.active-1)),this.#w=Math.max(0,this.#w-1),this.#d.push(e);this.#ne()>this.#N;){let o=this.#X();if(o===void 0)break;this.#q(o[0],o[1]),this.#Q.evictedByCap+=1}this.#ye()}#X(){for(;this.#f<this.#d.length;){let e=this.#d[this.#f],n=this.#i.get(e);if(n!==void 0&&n.ended)return[e,n];this.#f+=1}this.#ye()}#ye(){this.#f>1024&&this.#f*2>this.#d.length&&(this.#d=this.#d.slice(this.#f),this.#f=0)}touch(e){let n=this.#i.get(e);if(n===void 0)return;let i=this.#I();n.lastActivityAt=i,n.ended||(this.#m.delete(e),this.#m.set(e,n),n.goneSince!==void 0&&(n.goneSince=i,n.goneRunningDecided=!1,n.goneIdleDecided=!1,this.#p.delete(e),this.#p.set(e,n)))}#Re(e,n){n.ended||(n.goneSince=this.#I(),n.goneRunningDecided=!1,n.goneIdleDecided=!1,this.#p.delete(e),this.#p.set(e,n))}#Ie(e,n){n.goneSince=void 0,n.goneRunningDecided=!1,n.goneIdleDecided=!1,this.#p.delete(e),this.#m.delete(e),this.#m.set(e,n)}lastActivityAt(e){return this.#i.get(e)?.lastActivityAt}waitForReplayWatermark(e,n,i){if(e.owner===void 0)return Promise.resolve();let o=this.#i.get(e.sessionId);return!Number.isSafeInteger(n)||n<-1?Promise.reject(new Error("Invalid event publication watermark")):i?.aborted?Promise.reject(i.reason):this.#P?Promise.reject(new hi):!o||o.handle!==e?Promise.reject(new Error("Event publication is unavailable")):this.#ve(o)>=n?Promise.resolve():o.ended||o.logClosed?Promise.reject(new Error("Event publication ended before the requested watermark")):new Promise((s,a)=>{let d=()=>c.settle(i?.reason??new Error("Event publication wait aborted")),c={sequence:n,settle(l){o.replayWaiters.delete(c)&&(i?.removeEventListener("abort",d),l===void 0?s():a(l))}};o.replayWaiters.add(c),i?.addEventListener("abort",d,{once:!0})})}#pe(e,n){if(e.replayWaiters.size===0)return;let i=n===void 0?this.#ve(e):-1;for(let o of e.replayWaiters)(n!==void 0||i>=o.sequence)&&o.settle(n)}#ve(e,n=Math.max(e.epochStartSeq,e.handle.firstSeq?.()??e.epochStartSeq)){return Math.max(e.log.lastSeq(),n-1)}subscribe(e,n,i,o){let s=this.#i.get(e);if(s===void 0)return;let a=()=>{let h=s.handle.firstSeq?.()??s.epochStartSeq;return h>s.epochStartSeq?h:0},d=a(),c=s.log.readAfter(Math.max(n,d-1)),l=Math.max(s.epochStartSeq,d),f=this.#ve(s,l),u=n>f,m=(n>=0||d>0)&&n<l-1;if(c.gap||u||m){let h={type:An,sessionId:e,requestedAfterSeq:n,...c.oldestRetainedSeq!==void 0&&c.oldestRetainedSeq>=d?{oldestRetainedSeq:c.oldestRetainedSeq}:{},droppedEvents:c.dropped,reason:u?Ar.aheadOfLog:Ar.evicted};i.write(on({event:An,data:JSON.stringify(h)}))}if(wu(i,HS(c.events,o,a)),s.ended)return i.end(),()=>{};let g={raw:i,excludes:o};return s.subscribers.add(g),s.lastActivityAt=this.#I(),this.#Ie(e,s),s.handle.noteSubscribers(s.subscribers.size),()=>{s.subscribers.delete(g)&&(s.subscribers.size===0&&this.#Re(e,s),s.handle.noteSubscribers(s.subscribers.size))}}sweepNow(){let e=this.#I();for(;;){let i=this.#X();if(i===void 0)break;let[o,s]=i;if(s.endedAt===void 0||e-s.endedAt<this.#z)break;this.#q(o,s),this.#Q.evictedByRetention+=1}this.#ye();for(let[i,o]of this.#m){if(o.ended){this.#m.delete(i);continue}if(e-o.lastActivityAt<this.#S)break;o.closeRequested||o.subscribers.size>0||this.#ce(i,o)==="idle"&&this.#se(i,o,"idleCloses")}let n=Math.min(this.#J,this.#U);for(let[i,o]of this.#p){if(o.ended){this.#p.delete(i);continue}let s=o.goneSince;if(s===void 0)continue;let a=e-s;if(a<n)break;if(o.closeRequested)continue;let d=this.#ce(i,o);d==="running"&&!o.goneRunningDecided&&a>=this.#J?(o.goneRunningDecided=!0,this.#le(i,o,this.#me(o,"running",a,"interrupt"))):d==="idle"&&!o.goneIdleDecided&&a>=this.#U&&(o.goneIdleDecided=!0,this.#le(i,o,this.#me(o,"idle",a,"close")))}if(this.#j!==1/0)for(let[i,o]of this.#i){if(e-o.adoptedAt<this.#j)break;o.ended||o.closeRequested||this.#se(i,o,"lifetimeCloses")}if(this.#_!==void 0)try{let i=this.#_({activeSessionIds:new Set(this.#i.keys())});i instanceof Promise&&i.catch(o=>this.#u?.("",o))}catch(i){this.#u?.("",i)}}#ce(e,n){try{return n.handle.status()}catch(i){return this.#u?.(e,i),"ended"}}#se(e,n,i,o){if(!n.closeRequested){n.closeRequested=!0,this.#Q[i]+=1;try{n.handle.close(o)}catch(s){n.closeFailure="close_failed",this.#te(s,"close_failed"),this.#u?.(e,s)}}}#me(e,n,i,o){if(this.#D===void 0)return o;try{let s=this.#D({sessionId:e.handle.sessionId,endUserId:e.handle.endUserId,status:n,goneForMs:i,proposed:o});return s==="default"?o:s}catch(s){return this.#Q.hookErrors+=1,this.#u?.(e.handle.sessionId,s),o}}#le(e,n,i){if(i==="close"){this.#se(e,n,"orphanCloses",{source:"client_gone"});return}i==="interrupt"&&(this.#Q.orphanInterrupts+=1,this.#F(e,n,{source:"client_gone"}))}#F(e,n,i){try{n.handle.interrupt(i)}catch(o){this.#u?.(e,o)}}beginClosing(){this.#P=!0;for(let e of this.#i.values())this.#Ee(e),e.replayWaiters.size>0&&this.#pe(e,new hi)}runningCount(){let e=0;for(let[n,i]of this.#m)!i.ended&&this.#ce(n,i)==="running"&&(e+=1);return e}interruptRunning(){let e=0;for(let[n,i]of this.#m)i.ended||this.#ce(n,i)!=="running"||(this.#F(n,i),e+=1);return e}broadcastRetry(e){let n=on({retryMs:e,data:""}),i=0;for(let o of this.#m.values())if(!o.ended)for(let s of[...o.subscribers])s.raw.write(n),i+=1;return i}async closeAll(e={}){this.beginClosing(),this.#K!==void 0&&(clearInterval(this.#K),this.#K=void 0);let n=[],i=[];for(let d of this.#i.values()){d.closeRequested=!0;try{d.handle.close()}catch(c){d.closeFailure="close_failed",i.push(c),this.#te(c,"close_failed")}n.push(d.pumpDone)}let{timedOut:o,pending:s,settled:a}=await Ra(n,e.timeoutMs);for(let d of a)d.status==="rejected"&&i.push(d.reason);for(let[d,c]of this.#i)(!o||c.ended)&&this.#A(d,c);if(i.length>0)throw new AggregateError(i,"Session close failed.");return{timedOut:o,pending:s}}async settleResources(){for(;;){let e=[...this.#r];for(let n of this.#i.values())n.ended||e.push(n.pumpDone);for(let n of this.#c.values())e.push(n.outcome);if(e.length===0)break;await Promise.allSettled(e)}if(this.#o>0)throw new AggregateError(this.#s,`Session resource settlement failed: count=${this.#o}; omitted=${this.#o-this.#s.length}; codes=${[...this.#t].join(",")}`)}#te(e,n="settlement_failed"){this.#o++,this.#t.add(n),this.#s.push(e),this.#s.length>32&&this.#s.shift()}#he(e){if(this.#e.has(e))return;this.#e.add(e);let n={state:"pending",errorCode:null};this.#n.set(e,n);try{let i=e.settleResources;if(i===void 0){n.state="unknown",n.errorCode="settlement_unavailable",this.#te(void 0,"settlement_unavailable");return}let o=Promise.resolve().then(()=>i.call(e)).then(()=>{n.state="completed"},s=>{n.state="failed",n.errorCode="settlement_failed",this.#te(s)});this.#r.add(o),o.then(()=>{this.#r.delete(o)})}catch(i){n.state="failed",n.errorCode="settlement_failed",this.#te(i)}}#ie(e){try{e.close()}catch(n){this.#te(n,"close_failed")}finally{this.#he(e)}}async#Te(e,n){let i;try{for await(let o of n.handle.events){let s=()=>{let a=Er(o.type),d=[...n.subscribers].filter(l=>a||!_o(o.type,l.excludes)),c=d.length>0||Number.isFinite(this.#B)?Ba(o):void 0;if(n.log.append(o,Number.isFinite(this.#B)?c===void 0?void 0:Buffer.byteLength(c,"utf8"):c?.length),c!==void 0)for(let l of d)l.raw.write(c);this.#pe(n)};n.handle.owner===void 0?s():n.handle.owner.publishEvent!==void 0?await n.handle.owner.publishEvent(o,s):await n.handle.owner.fence(s),o.type==="turn.started"?(n.turnEndDecided=!1,this.#Ee(n),n.turns+=1,n.turns>this.#C&&!n.closeRequested&&(this.#F(e,n),this.#se(e,n,"turnCapCloses"))):(o.type==="turn.completed"||o.type==="turn.aborted")&&(this.#be(n,o),n.turns>=this.#C&&!n.closeRequested&&this.#se(e,n,"turnCapCloses"))}}catch(o){i=o,n.closeFailure="publication_failed",n.closeRequested=!0,this.#pe(n,o),this.#Q.pumpErrors+=1;try{n.handle.close()}catch{}this.#u?.(e,o)}finally{n.replayWaiters.size>0&&this.#pe(n,i??new Error("Event publication ended before the requested watermark")),this.#he(n.handle),n.ended=!0,n.endedAt=this.#I(),this.#Ee(n),this.#de(e,n);for(let o of[...n.subscribers])o.raw.end();n.subscribers.clear()}}#Ee(e){e.deferredNotify!==void 0&&(clearTimeout(e.deferredNotify),e.deferredNotify=void 0)}#be(e,n){if(!e.turnEndDecided&&(e.turnEndDecided=!0,!(this.#T===void 0||this.#P))){if(e.subscribers.size===0){this.#je(e,n);return}this.#Y<=0||(this.#Ee(e),this.#Q.deferredNotifies+=1,e.deferredNotify=setTimeout(()=>{e.deferredNotify=void 0,!(this.#P||e.ended||e.subscribers.size>0)&&(this.#Q.deferredNotifySent+=1,this.#je(e,n))},this.#Y),e.deferredNotify.unref())}}#je(e,n){if(this.#T===void 0)return;let i=n.turnId,o=n.type==="turn.completed"||n.type==="turn.aborted"?n.reason:void 0;this.#T({sessionId:e.handle.sessionId,endUserId:e.handle.endUserId,...i!==void 0?{turnId:i}:{},status:n.type==="turn.completed"?"completed":"aborted",...o!==void 0?{reason:o}:{},lastSeq:n.seq,ts:this.#I()})}};import{setMaxListeners as Zk}from"node:events";import{randomUUID as Fk}from"node:crypto";import{randomUUID as WS}from"node:crypto";import{types as VS}from"node:util";var Do=class extends Error{constructor(n){super(n);this.code=n;this.name="ArchiveHttpEventError"}code},zS=262317;function Zi(){let t=new Error("Archive event subscription aborted");return t.name="AbortError",t}async function Eu(t,e){if(e.aborted)throw t.catch(()=>{}),Zi();let n,i=new Promise((o,s)=>{n=()=>s(Zi()),e.addEventListener("abort",n,{once:!0})});try{return await Promise.race([t,i])}finally{n&&e.removeEventListener("abort",n)}}function GS(t,e){return e.aborted||t.destroyed?Promise.reject(Zi()):new Promise((n,i)=>{let o=()=>{t.removeListener("drain",s),t.removeListener("close",a),e.removeEventListener("abort",a)},s=()=>{o(),n()},a=()=>{o(),i(Zi())};t.once("drain",s),t.once("close",a),e.addEventListener("abort",a,{once:!0})})}async function Rg(t){let{req:e,res:n}=t,i=new AbortController,o=i.signal,s,a=()=>i.abort();e.once("aborted",a),n.once("close",a),(e.aborted||n.destroyed||n.writableEnded)&&i.abort();let d=async()=>{if(o.aborted||(await Eu(t.authorize(),o),o.aborted))throw Zi()};try{await d();let c=t.port.open({scope:t.scope,...t.lastEventId===void 0?{}:{lastEventId:t.lastEventId},signal:o}).then(l=>{if(o.aborted)throw l.close(),Zi();return s=l,l});for(s=await Eu(c,o),await d(),n.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store"}),n.flushHeaders();;){await d();let l=await Eu(s.next(),o);if(await d(),l===null){n.end();return}let f=s.encodeForSend(l);if(!(f instanceof Uint8Array)||f.byteLength<1||f.byteLength>zS)throw new Do("internal_error");n.write(f)||(await GS(n,o),await d())}}catch(c){throw n.headersSent&&!n.destroyed&&n.destroy(),c}finally{i.abort(),e.removeListener("aborted",a),n.removeListener("close",a),s?.close()}}var Cu={ackBytes:262144,requestEnvelopeBytes:1024,responseEnvelopeBytes:4096,requestBytes:263168,responseBytes:528384},ze={};ze.ArchiveAckRequest=r.object({protocol:r.literal("sdk2-ext-v1"),request:r.lazy(()=>ze.RequestIdentity),bindingId:r.lazy(()=>ze.Id),expectedRevision:r.lazy(()=>ze.Sequence),generations:r.lazy(()=>ze.Generations),sourceId:r.lazy(()=>ze.Id),sourceGeneration:r.lazy(()=>ze.Id),coverage:r.lazy(()=>ze.Coverage),attachments:r.array(r.lazy(()=>ze.ArchiveArtifactReceipt)).min(0).max(128).refine(t=>new Set(t.map(e=>JSON.stringify(e))).size===t.length),ackFormat:r.lazy(()=>ze.ArchiveAckFormat),payloads:r.array(r.lazy(()=>ze.ArchiveArtifactReceipt)).min(1).max(128).refine(t=>new Set(t.map(e=>JSON.stringify(e))).size===t.length)}).strict();ze.RequestIdentity=r.object({requestId:r.lazy(()=>ze.Id),operationEpoch:r.lazy(()=>ze.Id)}).strict();ze.Id=r.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._~-]*$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=128);ze.Sequence=r.string().regex(new RegExp("^(0|[1-9][0-9]{0,17}|[1-8][0-9]{18}|9[0-1][0-9]{17}|92[0-1][0-9]{16}|922[0-2][0-9]{15}|9223[0-2][0-9]{14}|92233[0-6][0-9]{13}|922337[0-1][0-9]{12}|92233720[0-2][0-9]{10}|922337203[0-5][0-9]{9}|9223372036[0-7][0-9]{8}|92233720368[0-4][0-9]{7}|922337203685[0-3][0-9]{6}|9223372036854[0-6][0-9]{5}|92233720368547[0-6][0-9]{4}|922337203685477[0-4][0-9]{3}|9223372036854775[0-7][0-9]{2}|922337203685477580[0-6]|9223372036854775807)$","u")).refine(t=>[...t].length<=19);ze.Generations=r.object({historyEpoch:r.lazy(()=>ze.LegacyId),deletionGeneration:r.lazy(()=>ze.Sequence),projectionRevision:r.lazy(()=>ze.Sequence)}).strict();ze.LegacyId=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);ze.Coverage=r.object({fromSequence:r.lazy(()=>ze.RecordSequence),throughSequence:r.lazy(()=>ze.RecordSequence),headDigest:r.lazy(()=>ze.Digest)}).strict();ze.RecordSequence=r.lazy(()=>ze.Sequence).refine(t=>t!=="0");ze.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));ze.ArchiveArtifactReceipt=r.object({artifactId:r.lazy(()=>ze.Id),sha256:r.lazy(()=>ze.Digest),state:r.literal("durably-stored")}).strict();ze.ArchiveAckFormat=r.literal("split-receipts-v1");ze.MutationReceipt=r.object({protocol:r.literal("sdk2-ext-v1"),request:r.lazy(()=>ze.RequestIdentity),bindingId:r.lazy(()=>ze.Id),operation:r.union([r.literal("binding-create"),r.literal("archive-ack"),r.literal("material-response"),r.literal("binding-close")]),semanticDigest:r.lazy(()=>ze.Digest),state:r.union([r.literal("accepted"),r.literal("completed"),r.literal("rejected")]),revision:r.lazy(()=>ze.Sequence),outcomeRef:r.lazy(()=>ze.Id)}).strict();ze.AckRebaseRequest=r.object({protocol:r.literal("sdk2-ext-v1"),bindingId:r.lazy(()=>ze.Id),previous:r.lazy(()=>ze.ArchiveAckRequest),request:r.lazy(()=>ze.RequestIdentity)}).strict();ze.AckRebaseReceipt=r.object({protocol:r.literal("sdk2-ext-v1"),bindingId:r.lazy(()=>ze.Id),previous:r.lazy(()=>ze.ArchiveAckRequest),request:r.lazy(()=>ze.RequestIdentity),next:r.lazy(()=>ze.ArchiveAckRequest),receipt:r.lazy(()=>ze.MutationReceipt)}).strict();function _u(t){let e=ze[t];if(!e)throw new Error("Unknown archive recovery contract");return e}var Ti="sdk2-ext-v1",Pu=262144,$S=611+512*6+38+8+6+8+128+4*Math.ceil(262144/3),ft=r.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._~-]*$/),qo=r.string().min(1).refine(t=>[...t].length<=512),dn=r.string().max(19).regex(/^(0|[1-9][0-9]*)$/).refine(t=>/^(0|[1-9][0-9]{0,18})$/.test(t)&&BigInt(t)<=9223372036854775807n),nr=r.string().regex(/^[a-f0-9]{64}$/),jo=r.object({historyEpoch:qo,deletionGeneration:dn,projectionRevision:dn}).strict(),No=r.object({sessionId:qo,generations:jo,sourceSnapshotDigest:nr}).strict(),tr=r.object({operationEpoch:ft,requestId:ft}).strict(),ir={protocol:r.literal(Ti),bindingId:ft},St=(t,e)=>r.number().int().min(t).max(e),Ig=r.object({artifactId:ft,sha256:nr,state:r.literal("durably-stored")}).strict(),KS=r.object({...ir,request:tr,ackFormat:r.literal("split-receipts-v1"),expectedRevision:dn,generations:jo,sourceId:ft,sourceGeneration:ft,coverage:r.object({fromSequence:dn.refine(t=>t!=="0"),throughSequence:dn.refine(t=>t!=="0"),headDigest:nr}).strict(),payloads:r.array(Ig).min(1).max(128),attachments:r.array(Ig).max(128)}).strict(),QS=r.object({...ir,materialRequestId:ft,target:No,sourceId:ft,sourceGeneration:ft,artifactId:ft,offset:St(0,1048576),bytes:St(0,65536),chunkSha256:nr,base64:r.string().max(87384).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict(),Tg=r.object({uploadId:ft}).strict(),JS=r.object({...ir,request:tr,materialRequestId:ft,target:No,sourceId:ft,sourceGeneration:ft,results:r.array(r.object({recordId:ft,digest:nr,payload:Tg,attachments:r.array(Tg).max(128)}).strict()).min(1).max(32)}).strict(),Pg=r.enum(["archive-transfer-v1","context-materials-v1"]),qa=t=>r.array(Pg).min(t).max(2).refine(e=>new Set(e).size===e.length).readonly(),Mg=r.object({controlBytes:St(1024,262144),recordBytes:St(1024,262144),pageRecords:St(1,128),pageBytes:St(1024,1048576),attachmentBytes:St(1024,33554432),chunkBytes:St(1024,262144),materialConcurrent:St(1,2),materialQueue:St(1,16),materialCandidates:St(1,32),materialBytes:St(1024,1048576),materialDeadlineMs:St(1e3,3e4),pendingRecords:St(1,4096),pendingBytes:St(1048576,67108864),inflightReserveBytes:St(1048576,16777216),offlineMs:St(1e3,864e5),eventRetentionMs:St(1e3,6e5),eventRetentionFrames:St(1,4096),eventRetentionBytes:St(1024,8388608),terminalReceiptRetentionMs:St(6e4,6048e5),epochLifetimeMs:St(6e4,864e5),materialChunkBytes:St(1,65536)}).strict().refine(t=>t.inflightReserveBytes<=t.pendingBytes),Mu=r.object({id:ft,issuedAt:r.string().datetime({offset:!0}),expiresAt:r.string().datetime({offset:!0}),state:r.literal("active")}).strict().refine(t=>Date.parse(t.expiresAt)>Date.parse(t.issuedAt)),YS=r.object({applicationScopeId:ft,endUserId:qo,authorizationRevision:dn}).strict(),Og=r.enum(["active","backpressured","closing","closed"]),XS=r.object({protocol:r.literal(Ti),availability:r.literal("legacy-complete"),capabilities:qa(1),limits:Mg,operationEpoch:Mu,archiveAckFormats:r.array(r.literal("split-receipts-v1")).max(1).readonly()}).strict().refine(t=>t.archiveAckFormats.length===(t.capabilities.includes("archive-transfer-v1")?1:0)),ZS=r.object({protocol:r.literal(Ti),target:No,revision:dn,bindingId:ft.nullable(),operationEpoch:Mu.nullable()}).strict(),Ag=r.object({...ir,scope:YS,target:No,revision:dn,state:Og,sourceId:ft,acceptedCapabilities:qa(1),rejectedCapabilities:r.array(r.object({capability:Pg,reason:r.enum(["unsupported_capability","not_authorized"])}).strict()).max(2).readonly(),availability:r.literal("legacy-complete"),operationEpoch:Mu.nullable(),limits:Mg,archiveAckFormat:r.literal("split-receipts-v1").nullable()}).strict().refine(t=>t.archiveAckFormat===(t.acceptedCapabilities.includes("archive-transfer-v1")?"split-receipts-v1":null)),ew=r.object({fromSequence:dn.refine(t=>t!=="0"),throughSequence:dn.refine(t=>t!=="0"),headDigest:nr}).strict(),tw=r.object({...ir,revision:dn,generations:jo,sourceId:ft,sourceGeneration:ft,publishedThroughSequence:dn.nullable(),acknowledgedCoverage:ew.nullable(),releasableThroughSequence:dn.nullable(),pendingBytes:St(0,67108864),pendingRecords:St(0,4096),sessionPersistence:r.literal("unchanged"),state:Og}).strict(),nw=r.object({protocol:r.literal(Ti),request:tr,target:No,expectedRevision:dn,requiredCapabilities:qa(1),optionalCapabilities:qa(0),archive:r.object({strategy:r.literal("single-authorized-source"),sourceId:ft,durability:r.literal("source-ack-with-durable-spool"),delivery:r.literal("required"),sessionAvailability:r.literal("legacy-complete"),ackFormat:r.literal("split-receipts-v1")}).strict()}).strict().refine(t=>t.requiredCapabilities.every(e=>!t.optionalCapabilities.includes(e))),iw=r.object({...ir,request:tr,expectedRevision:dn,generations:jo}).strict(),Eg=r.object({...ir,request:tr,operation:r.enum(["binding-create","archive-ack","binding-close"]),semanticDigest:nr,state:r.literal("completed"),revision:dn,outcomeRef:ft}).strict(),Bg={invalid_request:[400,"none"],protocol_version_mismatch:[400,"none"],unauthorized:[401,"none"],forbidden:[403,"none"],unsupported_capability:[422,"none"],stale_generation:[409,"none"],archive_gap:[409,"none"],source_unavailable:[503,"query-status"],invalid_coverage:[422,"none"],capacity_exceeded:[429,"same-request"],request_id_conflict:[409,"none"],request_expired:[410,"none"],receipt_expired:[410,"none"],payload_too_large:[413,"none"],material_rejected:[422,"none"],binding_closed:[409,"none"],internal_error:[500,"query-status"],epoch_unavailable:[503,"same-request"],binding_conflict:[409,"none"],stream_cursor_unknown:[409,"none"],stream_cursor_expired:[410,"none"],stream_gap:[409,"none"]};function Na(t){return Bg[t]}var ja=class extends Error{constructor(n){super(n);this.code=n;this.name="ArchiveHttpError"}code};function we(t){throw new ja(t)}function Dt(t,e){let n=t.safeParse(e);return n.success||we("invalid_request"),n.data}function er(t,e,n){try{let i=Si(nn(e,{maxBytes:n})),o=t.safeParse(i);if(o.success)return o.data}catch{}return we("internal_error")}function rw(t,e){try{(!t||typeof t!="object"||VS.isProxy(t)||Array.isArray(t)||![null,Object.prototype].includes(Object.getPrototypeOf(t)))&&we("internal_error");let n=Object.getOwnPropertyDescriptors(t),i={};for(let o of Reflect.ownKeys(n)){typeof o!="string"&&we("internal_error");let s=n[o];(!s.enumerable||!Object.hasOwn(s,"value"))&&we("internal_error"),i[o]=Si(nn(s.value))}return Ou(i,e),Dt(_u("AckRebaseReceipt"),i)}catch{return we("internal_error")}}function ow(t){if(t instanceof ja||t instanceof Do)return t.code;if(t instanceof gh)switch(t.code){case"stream_cursor_unknown":case"stream_cursor_expired":case"stream_gap":case"capacity_exceeded":return t.code;case"unavailable":case"reconciliation_required":return"source_unavailable";default:return"internal_error"}if(t instanceof Ol&&t.code==="dependency_held")return"source_unavailable";if(t instanceof Ss||t instanceof wp||t instanceof mh||t instanceof Ol)switch(t.code){case"invalid_input":return"invalid_request";case"capacity_exceeded":return"capacity_exceeded";case"operation_conflict":case"entry_conflict":return"request_id_conflict";case"stale_generation":return"stale_generation";case"epoch_expired":return"epoch_unavailable";case"request_expired":return"request_expired";case"binding_closed":return"binding_closed";case"revision_conflict":case"head_conflict":return"binding_conflict";case"archive_gap":return"archive_gap";case"artifact_unavailable":case"source_unavailable":case"entry_released":return"source_unavailable";case"unsupported_capability":return"unsupported_capability";default:return"internal_error"}return"internal_error"}function Ou(t,e){let n=JSON.stringify(t,(o,s)=>{if(typeof s=="number"&&(!Number.isSafeInteger(s)||s<0||Object.is(s,-0)))throw new TypeError("Invalid response integer");return s&&typeof s=="object"&&!Array.isArray(s)?Object.fromEntries(Object.entries(s).sort(([a],[d])=>a<d?-1:a>d?1:0)):s});if(n===void 0)throw new TypeError("Missing response");let i=Buffer.from(n);return i.length>e&&we("capacity_exceeded"),i}function ri(t,e,n,i=Pu){if(t.destroyed||t.writableEnded)return;let o=Ou(n,i);t.writeHead(e,{"content-type":"application/json; charset=utf-8","content-length":o.length,"cache-control":"no-store"}),t.end(o)}function Dg(t){try{return decodeURIComponent(t)}catch{return we("invalid_request")}}function gi(t,e,n=[]){let i=Object.create(null);for(let o of t.split("&")){let s=o.indexOf("=");(s<1||o.includes("+"))&&we("invalid_request");let a=o.slice(0,s),d=Dg(o.slice(s+1));(![...e,...n].includes(a)||Object.hasOwn(i,a)||d==="")&&we("invalid_request"),i[a]=d}return e.some(o=>!Object.hasOwn(i,o))&&we("invalid_request"),i.protocol!==Ti&&we("protocol_version_mismatch"),i}function Da(t,e,n){return/^(0|[1-9][0-9]*)$/.test(t)||we("invalid_request"),Dt(St(e,n),Number(t))}function Cg(t){return Dt(jo,{historyEpoch:t.historyEpoch,deletionGeneration:t.deletionGeneration,projectionRevision:t.projectionRevision})}function _g(t,e){return t.historyEpoch===e.historyEpoch&&t.deletionGeneration===e.deletionGeneration&&t.projectionRevision===e.projectionRevision}async function sw(t,e,n=!1){let i=t.headers["content-type"]??"";(!/^application\/json(?:\s*;\s*charset\s*=\s*(?:utf-8|"utf-8"))?\s*$/i.test(i)||t.headers["content-encoding"]!==void 0&&t.headers["content-encoding"].toLowerCase()!=="identity")&&we("invalid_request");let o=[],s=0;for await(let d of t){let c=Buffer.isBuffer(d)?d:Buffer.from(d);s+=c.length,s>e&&we("payload_too_large"),o.push(c)}let a;try{let d=Buffer.concat(o);if(n){let c=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(d);a=JSON.parse(c),Ou(a,e).equals(d)||we("invalid_request")}else a=Si(d,{maxBytes:e})}catch{return we("invalid_request")}return(!a||typeof a!="object"||Array.isArray(a))&&we("invalid_request"),a.protocol!==Ti&&we("protocol_version_mismatch"),a}function qg(t){let e=t.host.controlBytes??Pu;Dt(St(1024,Pu),e),Dt(ft,t.host.applicationScopeId);let n=0;return(i,o)=>{let s=i.url??"";if(!s.startsWith("/v3/sdk2/bindings")&&!s.startsWith("/v3/sdk2/operations")&&!s.startsWith("/v3/sdk2/capabilities")&&!s.startsWith("/v3/sdk2/sessions/"))return!1;let a=!1,d=!1,c=e,l=WS(),f=(async()=>{(n>=128||t.admission.overloaded())&&we("capacity_exceeded"),n++,a=!0,Buffer.byteLength(s)>8192&&we("payload_too_large"),s.includes("#")&&we("invalid_request");let u=s.indexOf("?"),m=u<0?s:s.slice(0,u),g=u<0?"":s.slice(u+1),h=m.split("/").slice(3).map(Dg),p=i.method??"GET";p!=="GET"&&p!=="POST"&&we("invalid_request"),p==="GET"&&(i.headers["transfer-encoding"]!==void 0||i.headers["content-length"]!==void 0&&i.headers["content-length"]!=="0")&&we("invalid_request"),p==="POST"&&u>=0&&we("invalid_request");let v=p==="POST"&&h.length===4&&h[0]==="bindings"&&h[2]==="archive"&&h[3]==="ack-rebases";v&&(c+=Cu.requestEnvelopeBytes),p==="POST"&&(t.admission.reserveBody(c).admitted||we("capacity_exceeded"),d=!0);let b=p==="POST"?await sw(i,c,v):void 0,R=async I=>{let B;try{B=await t.authenticate(i,o)}catch(z){return z instanceof Rt?we(z.code==="overloaded"?"capacity_exceeded":"source_unavailable"):we("unauthorized")}return(!B?.endUserId||I!==void 0&&B.endUserId!==I)&&we("unauthorized"),(i.aborted||o.destroyed||o.writableEnded)&&we("unauthorized"),B.endUserId},w=async()=>{let I=await R();return(await t.admission.rateLimit(i,I)).admitted||we("capacity_exceeded"),await R(I),I};if(h.length===1&&h[0]==="capabilities"&&p==="GET"){u>=0&&we("invalid_request");let I=await w(),B=t.host.capabilities;B||we("unsupported_capability");let z=await B.call(t.host,I);await R(I),t.host.capabilities!==B&&we("forbidden"),ri(o,200,er(XS,z,e),e);return}let x=h.length===3&&h[0]==="sessions"&&h[2]==="binding-target"&&p==="GET",T=h.length===1&&h[0]==="bindings"&&p==="POST",M;if(h.length===1&&h[0]==="operations"&&p==="GET"){let I=gi(g,["protocol","operation","operationEpoch","requestId"],["bindingId","sessionId"]);I.operation==="binding-create"?((I.bindingId!==void 0||I.sessionId===void 0)&&we("invalid_request"),M=I):(I.sessionId!==void 0||I.bindingId===void 0)&&we("invalid_request")}if(x||T||M){let I,B,z;x?(gi(g,["protocol"]),I=Dt(qo,h[1])):T?(B=Dt(nw,b),I=B.target.sessionId,l=B.request.requestId):(I=Dt(qo,M.sessionId),z=Dt(tr,{operationEpoch:M.operationEpoch,requestId:M.requestId}),l=z.requestId);let j=await w(),ne=t.host.resolveSession;ne||we("unsupported_capability");let U=ne.call(t.host,j,I);U||we("forbidden");let le=async()=>{await R(j),(t.host.resolveSession!==ne||ne.call(t.host,j,I)!==U)&&we("forbidden")};if(x){let ue=U.readTarget,ie=await ue.call(U);await le(),U.readTarget!==ue&&we("forbidden");let me=er(ZS,ie,e);me.target.sessionId!==I&&we("forbidden"),ri(o,200,me,e)}else if(B){let ue=U.create;ue||we("unsupported_capability");let ie=await ue.call(U,B);await le(),U.create!==ue&&we("forbidden");let me=er(Ag,ie,e);(me.target.sessionId!==I||me.scope.applicationScopeId!==t.host.applicationScopeId||me.scope.endUserId!==j)&&we("forbidden"),ri(o,201,me,e)}else{let ue=U.queryCreate;ue||we("unsupported_capability");let ie=await ue.call(U,z);await le(),U.queryCreate!==ue&&we("forbidden"),ie===null&&we("receipt_expired");let me=er(Eg,ie,e);(me.operation!=="binding-create"||me.request.operationEpoch!==z.operationEpoch||me.request.requestId!==z.requestId)&&we("internal_error"),ri(o,200,me,e)}return}let W=["historyEpoch","deletionGeneration","projectionRevision"],$,D,J,S=Object.create(null),k=b;if(h.length===1&&h[0]==="operations"&&p==="GET")S=gi(g,["protocol","operation","bindingId","operationEpoch","requestId"]),$=Dt(ft,S.bindingId),Dt(tr,{operationEpoch:S.operationEpoch,requestId:S.requestId}),["archive-ack","material-response","binding-close"].includes(S.operation)||we("unsupported_capability"),l=S.requestId,D="operation";else if(h[0]!=="bindings"&&we("invalid_request"),$=Dt(ft,h[1]),h.length===2&&p==="GET")gi(g,["protocol"]),D="view";else if(h.length===4&&h[2]==="archive"&&h[3]==="status"&&p==="GET")gi(g,["protocol"]),D="archive-status";else if(h.length===3&&h[2]==="close"&&p==="POST")k=Dt(iw,b),D="close";else if(h.length===3&&h[2]==="events"&&p==="GET"){S=gi(g,["protocol"]);let I=[];for(let B=0;B<i.rawHeaders.length;B+=2)i.rawHeaders[B].toLowerCase()==="last-event-id"&&I.push(i.rawHeaders[B+1]);I.length>1&&we("invalid_request"),I.length===1&&(J=Dt(ft,I[0])),D="events"}else if(h.length===4&&h[2]==="archive"&&h[3]==="records"&&p==="GET")S=gi(g,["protocol",...W,"limit","maxBytes"],["afterSequence"]),k={generations:Cg(S),afterSequence:S.afterSequence===void 0?null:Dt(dn,S.afterSequence),limit:Da(S.limit,1,128),maxBytes:Da(S.maxBytes,1024,1048576)},D="records";else if(h.length===5&&h[2]==="archive"&&h[3]==="artifacts"&&p==="GET")S=gi(g,["protocol",...W,"offset","maxBytes"]),k={generations:Cg(S),artifactId:Dt(ft,h[4]),offset:Da(S.offset,0,33554431),maxBytes:Da(S.maxBytes,1,262144)},D="artifact";else if(h.length===4&&h[2]==="archive"&&h[3]==="acks"&&p==="POST")k=Dt(KS,b),D="ack";else if(h.length===4&&h[2]==="archive"&&h[3]==="ack-rebases"&&p==="POST")k=Dt(_u("AckRebaseRequest"),b),D="ack-rebase";else if(h.length===3&&h[2]==="material-responses"&&p==="POST")k=Dt(JS,b),D="response";else if(h[2]==="materials"&&(h.length===4||h.length===6||h.length===7))if(Dt(ft,h[3]),h.length>4&&(h[4]!=="uploads"&&we("invalid_request"),Dt(ft,h[5])),h.length===7&&h[6]==="chunks"&&p==="POST")k=Dt(QS,b),D="upload";else if(p==="GET"&&h.length!==7)gi(g,["protocol"]),D=h.length===4?"status":"upload-status";else return we("invalid_request");else return we("unsupported_capability");if(p==="POST"){let I=k;(I.bindingId!==$||D==="upload"&&(I.materialRequestId!==h[3]||I.artifactId!==h[5]))&&we("invalid_request"),I.request&&(l=I.request.requestId)}if(D==="upload"){let I=k,B=Buffer.from(I.base64,"base64");(B.length!==I.bytes||B.toString("base64")!==I.base64||vp(B)!==I.chunkSha256)&&we("invalid_request")}let A={endUserId:await w()},C=t.host.resolve(A.endUserId,$);C||we("forbidden");let F=C.control.read();if((!F||F.registration.bindingId!==$||F.registration.scope.endUserId!==A.endUserId||F.registration.scope.applicationScopeId!==t.host.applicationScopeId)&&we("forbidden"),F.state==="unbound"&&we("binding_closed"),D==="view"||D==="archive-status"||D==="close"||D==="ack-rebase"){let I=async()=>{await R(A.endUserId),t.host.resolve(A.endUserId,$)!==C&&we("forbidden");let B=C.control.read();(!B||B.registration.bindingId!==$||B.registration.scope.endUserId!==A.endUserId||B.registration.scope.applicationScopeId!==t.host.applicationScopeId)&&we("forbidden")};if(D==="view"){let B=C.readView;B||we("unsupported_capability");let z=await B.call(C);await I(),C.readView!==B&&we("forbidden");let j=er(Ag,z,e);(j.bindingId!==$||j.scope.applicationScopeId!==t.host.applicationScopeId||j.scope.endUserId!==A.endUserId||j.target.sessionId!==F.registration.sessionId)&&we("forbidden"),ri(o,200,j,e)}else if(D==="archive-status"){F.acceptedCapabilities.includes("archive-transfer-v1")||we("unsupported_capability");let B=C.readArchiveStatus;B||we("unsupported_capability");let z=await B.call(C);await I(),C.readArchiveStatus!==B&&we("forbidden");let j=er(tw,z,e);(j.bindingId!==$||j.sourceId!==F.registration.sourceId||j.sourceGeneration!==F.registration.sourceGeneration)&&we("forbidden"),ri(o,200,j,e)}else if(D==="ack-rebase"){F.acceptedCapabilities.includes("archive-transfer-v1")||we("unsupported_capability");let B=C.rebaseAck;B||we("unsupported_capability");let z=k,j=await B.call(C,z);await I(),C.rebaseAck!==B&&we("forbidden");let ne=2*e+Cu.responseEnvelopeBytes,U=rw(j,ne),le=(ue,ie)=>nn(ue).toString()===nn(ie).toString();(U.bindingId!==$||!le(U.previous,z.previous)||!le(U.request,z.request)||!le(U.next.request,z.request)||BigInt(U.next.expectedRevision)<=BigInt(z.previous.expectedRevision)||!le({...U.next,request:z.previous.request,expectedRevision:z.previous.expectedRevision},z.previous)||U.receipt.operation!=="archive-ack"||!le(U.receipt.request,U.next.request)||U.receipt.bindingId!==$)&&we("internal_error"),ri(o,200,U,ne)}else{let B=C.close;B||we("unsupported_capability");let z=k,j=await B.call(C,z);await I(),C.close!==B&&we("forbidden");let ne=er(Eg,j,e);(ne.bindingId!==$||ne.operation!=="binding-close"||ne.request.operationEpoch!==z.request.operationEpoch||ne.request.requestId!==z.request.requestId)&&we("internal_error"),ri(o,200,ne,e)}return}if(D==="events"){let I=C.events;I||we("unsupported_capability");let B=A.endUserId;if(i.aborted||o.destroyed||o.writableEnded)return;t.admission.tryAdmitSse(B).admitted||we("capacity_exceeded"),o.once("close",()=>t.admission.releaseSse(B)),i.socket.setTimeout(0);let z=async()=>{let j;try{j=await t.authenticate(i,o)}catch(le){return le instanceof Rt?we(le.code==="overloaded"?"capacity_exceeded":"source_unavailable"):we("unauthorized")}(!j?.endUserId||j.endUserId!==B)&&we("unauthorized");let ne=t.host.resolve(B,$);(!ne||ne.events!==I||ne.control!==C.control)&&we("forbidden");let U=ne.control.read();(!U||U.registration.bindingId!==$||U.registration.scope.endUserId!==B||U.registration.scope.applicationScopeId!==t.host.applicationScopeId)&&we("forbidden"),U.state==="unbound"&&we("binding_closed")};await Rg({req:i,res:o,port:I,scope:{applicationScopeId:t.host.applicationScopeId,endUserId:B,bindingId:$},...J===void 0?{}:{lastEventId:J},authorize:z});return}let H=()=>{let I=C.materials;(!F.acceptedCapabilities.includes("context-materials-v1")||!I)&&we("unsupported_capability"),(I.bindingId!==$||!F.registration.relatedBindingIds.includes(I.storageBindingId))&&we("forbidden");let B=C.spool.bindingIdentity(I.storageBindingId);return(B.applicationScopeId!==t.host.applicationScopeId||B.endUserId!==A.endUserId)&&we("forbidden"),I};["records","artifact","ack"].includes(D)&&!F.acceptedCapabilities.includes("archive-transfer-v1")&&we("unsupported_capability");let Q,re=200,O=e;if(D==="records"){let I=k;_g(I.generations,F.target.generations)||we("stale_generation"),Q=C.journal.list(I),O=I.maxBytes}else if(D==="artifact"){let I=k;_g(I.generations,F.target.generations)||we("stale_generation");let B=C.journal.readArtifact(I);Q={protocol:Ti,bindingId:$,artifactId:B.artifact.artifactId,sourceId:B.artifact.sourceId,generations:I.generations,offset:B.offset,bytes:B.body.byteLength,totalBytes:B.artifact.bytes,sha256:B.artifact.sha256,chunkSha256:B.chunkSha256,base64:Buffer.from(B.body).toString("base64")},O=$S}else if(D==="ack")Q=C.acknowledger.acknowledge(k);else if(D==="upload")Q=H().uploadChunk(k);else if(D==="response")Q=H().respond(k),re=202;else if(D==="status")Q=H().status(h[3]);else if(D==="upload-status")Q=H().uploadStatus(h[3],h[5]);else{let I={operationEpoch:S.operationEpoch,requestId:S.requestId};Q=S.operation==="material-response"?H().queryResponse(I):C.control.query(S.operation,I)?.receipt,Q||we("receipt_expired")}if(!Q||typeof Q!="object"||Q.bindingId!==$)throw new Error("Mismatched host binding");ri(o,re,Q,O)})().catch(u=>{if(o.headersSent||o.destroyed||o.writableEnded)return;let m=ow(u),[g,h]=Bg[m];(g===429||g===503)&&o.setHeader("retry-after","5"),ri(o,g,{protocol:Ti,requestId:l,code:m,status:g,message:m,retryAction:h})}).finally(()=>{a&&n--,d&&t.admission.releaseBody(c)});return t.track(f),!0}}import{createHash as zr,randomUUID as Jo}from"node:crypto";var rr="TansrTerminalShellSandbox",Uo="058f31335cbb45a6ffe1b5ede8466013462c544c8108d687f41fa18447d51b96",ke={};ke.BackgroundRequest=r.union([r.object({contract:r.lazy(()=>ke.BackgroundContract),action:r.literal("launch"),command:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=8192),cwd:r.string().refine(t=>[...t].length<=4096),mode:r.union([r.literal("background"),r.literal("foreground-handoff")]),timeoutMs:r.number().int().safe().min(1).max(864e5),foregroundTimeoutMs:r.number().int().safe().min(1).max(12e4).optional()}).strict(),r.object({contract:r.lazy(()=>ke.BackgroundContract),action:r.literal("query"),identity:r.lazy(()=>ke.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>ke.BackgroundContract),action:r.literal("cancel"),identity:r.lazy(()=>ke.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>ke.BackgroundContract),action:r.literal("outputRead"),identity:r.lazy(()=>ke.BackgroundIdentity),artifact:r.lazy(()=>ke.ArtifactReference),offset:r.lazy(()=>ke.Sequence),length:r.number().int().safe().min(1).max(16384)}).strict(),r.object({contract:r.lazy(()=>ke.BackgroundContract),action:r.literal("artifactDelete"),identity:r.lazy(()=>ke.BackgroundIdentity),artifact:r.lazy(()=>ke.ArtifactReference)}).strict()]);ke.BackgroundContract=r.literal("terminal-services-v1");ke.BackgroundIdentity=r.object({taskId:r.lazy(()=>ke.Id),operationId:r.lazy(()=>ke.Id),requestDigest:r.lazy(()=>ke.Digest),runtimeInstanceId:r.lazy(()=>ke.Id),processInstanceId:r.lazy(()=>ke.Id)}).strict();ke.Id=r.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._~-]*$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=128);ke.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));ke.ArtifactReference=r.object({artifactId:r.lazy(()=>ke.Id),operationId:r.lazy(()=>ke.Id),requestDigest:r.lazy(()=>ke.Digest)}).strict();ke.Sequence=r.string().regex(new RegExp("^(0|[1-9][0-9]{0,17}|[1-8][0-9]{18}|9[0-1][0-9]{17}|92[0-1][0-9]{16}|922[0-2][0-9]{15}|9223[0-2][0-9]{14}|92233[0-6][0-9]{13}|922337[0-1][0-9]{12}|92233720[0-2][0-9]{10}|922337203[0-5][0-9]{9}|9223372036[0-7][0-9]{8}|92233720368[0-4][0-9]{7}|922337203685[0-3][0-9]{6}|9223372036854[0-6][0-9]{5}|92233720368547[0-6][0-9]{4}|922337203685477[0-4][0-9]{3}|9223372036854775[0-7][0-9]{2}|922337203685477580[0-6]|9223372036854775807)$","u")).refine(t=>[...t].length<=19);ke.BackgroundResponse=r.union([r.object({contract:r.lazy(()=>ke.BackgroundContract),action:r.literal("launch"),task:r.lazy(()=>ke.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>ke.BackgroundContract),action:r.literal("query"),task:r.lazy(()=>ke.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>ke.BackgroundContract),action:r.literal("cancel"),task:r.lazy(()=>ke.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>ke.BackgroundContract),action:r.literal("outputRead"),identity:r.lazy(()=>ke.BackgroundIdentity),artifact:r.lazy(()=>ke.ArtifactReference),offset:r.lazy(()=>ke.Sequence),base64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=21848),byteLength:r.number().int().safe().min(0).max(16384),payloadDigest:r.lazy(()=>ke.Digest),nextOffset:r.lazy(()=>ke.Sequence),complete:r.boolean(),gap:r.boolean()}).strict(),r.object({contract:r.lazy(()=>ke.BackgroundContract),action:r.literal("artifactDelete"),identity:r.lazy(()=>ke.BackgroundIdentity),artifact:r.lazy(()=>ke.ArtifactReference),status:r.union([r.literal("deleted"),r.literal("already_deleted")])}).strict()]);ke.BackgroundTaskState=r.object({identity:r.lazy(()=>ke.BackgroundIdentity),artifact:r.lazy(()=>ke.ArtifactReference),state:r.union([r.literal("running"),r.literal("completed"),r.literal("failed"),r.literal("cancelled"),r.literal("unknown")]),exitCode:r.union([r.number().int().safe().min(-2147483648).max(2147483647),r.null()]),signalName:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=64),r.null()]),totalBytes:r.union([r.lazy(()=>ke.Sequence),r.null()]),truncated:r.boolean()}).strict();ke.ExecutionInterpreter=r.object({id:r.lazy(()=>ke.Id),revision:r.lazy(()=>ke.Id),hostShell:r.union([r.literal("posix"),r.literal("powershell")])}).strict();ke.Contract=r.literal("terminal-shell-sandbox-v1");ke.Call=r.object({turnId:r.lazy(()=>ke.Id),toolCallId:r.lazy(()=>ke.Id)}).strict();ke.ApprovedCall=r.object({turnId:r.lazy(()=>ke.Id),toolCallId:r.lazy(()=>ke.Id),argsDigest:r.lazy(()=>ke.Digest)}).strict();ke.Escalation=r.object({previousDeniedOperationId:r.lazy(()=>ke.Id),approvedCall:r.lazy(()=>ke.ApprovedCall)}).strict();ke.Sandbox=r.object({mode:r.union([r.literal("off"),r.literal("on"),r.literal("required")]),capability:r.union([r.literal("none"),r.literal("partial"),r.literal("full")]),isolationDenied:r.boolean(),escalated:r.boolean()}).strict();ke.ExecResult=r.object({stdout:r.string().refine(t=>[...t].length<=65536),stderr:r.string().refine(t=>[...t].length<=65536),exitCode:r.union([r.string().regex(new RegExp("^(0|[1-9][0-9]*|-[1-9][0-9]*)$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=11),r.null()]),signalName:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32),r.null()]),durationMs:r.number().int().safe().min(0).max(9007199254740991),timedOut:r.boolean(),aborted:r.boolean()}).strict();ke.Request=r.union([r.object({contract:r.lazy(()=>ke.Contract),action:r.literal("exec"),call:r.lazy(()=>ke.Call),command:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768),cwd:r.string().refine(t=>[...t].length<=4096),timeoutMs:r.number().int().safe().min(1).max(12e4),maxOutputBytes:r.number().int().safe().min(1).max(65536),interpreter:r.lazy(()=>ke.ExecutionInterpreter),escalation:r.lazy(()=>ke.Escalation).optional()}).strict(),r.object({contract:r.lazy(()=>ke.Contract),action:r.literal("background"),request:r.lazy(()=>ke.BackgroundRequest),call:r.lazy(()=>ke.Call).optional(),escalation:r.lazy(()=>ke.Escalation).optional()}).strict()]);ke.Response=r.union([r.object({contract:r.lazy(()=>ke.Contract),action:r.literal("exec"),result:r.union([r.lazy(()=>ke.ExecResult),r.null()]),sandbox:r.lazy(()=>ke.Sandbox),output:r.union([r.lazy(()=>ke.Output),r.null()])}).strict(),r.object({contract:r.lazy(()=>ke.Contract),action:r.literal("background"),result:r.union([r.lazy(()=>ke.BackgroundResponse),r.null()]),sandbox:r.lazy(()=>ke.Sandbox)}).strict()]);ke.OutputChannel=r.object({totalBytes:r.number().int().safe().min(0).max(65536),payloadDigest:r.lazy(()=>ke.Digest)}).strict();ke.Output=r.object({previewTruncated:r.boolean(),stdout:r.lazy(()=>ke.OutputChannel),stderr:r.lazy(()=>ke.OutputChannel)}).strict();function Bu(t,e){if(!Object.hasOwn(ke,t))throw new TypeError("Unknown terminal shell sandbox contract type");return ke[t].parse(e)}function yi(){throw new TypeError("Invalid terminal shell sandbox semantics")}function Lo(t){let e=Bu("Request",t),n=e.action==="exec"||e.request.action==="launch";return(n&&e.call===void 0||!n&&(e.call!==void 0||e.escalation!==void 0))&&yi(),e.escalation&&(e.escalation.approvedCall.turnId!==e.call?.turnId||e.escalation.approvedCall.toolCallId!==e.call?.toolCallId)&&yi(),e}function jg(t,e){let n=Bu("Response",t),i=n.sandbox;if((i.escalated&&(i.mode!=="on"||i.capability==="none"||i.isolationDenied)||i.isolationDenied&&(i.mode==="off"||i.capability==="none")||n.result===null&&!i.isolationDenied)&&yi(),n.action==="exec"&&n.result?.exitCode!==null&&n.result!==null){let o=BigInt(n.result.exitCode);(o<-2147483648n||o>2147483647n)&&yi()}if(n.action==="exec"&&(n.result===null!=(n.output===null)&&yi(),n.result&&n.output)){let o=new TextEncoder().encode(n.result.stdout).byteLength,s=new TextEncoder().encode(n.result.stderr).byteLength,a=n.output.stdout.totalBytes+n.output.stderr.totalBytes;(o+s>4096||o>n.output.stdout.totalBytes||s>n.output.stderr.totalBytes||a>65536||n.output.previewTruncated!==o+s<a)&&yi()}return e&&((e.action!==n.action||i.escalated&&e.escalation===void 0)&&yi(),e.action==="exec"&&n.action==="exec"&&n.output&&n.output.stdout.totalBytes+n.output.stderr.totalBytes>e.maxOutputBytes&&yi(),e.action==="background"&&n.action==="background"&&n.result?.action!==void 0&&e.request.action!==n.result.action&&yi()),n}function or(t){return t.operation==="tool.invoke"&&t.args.name===rr&&t.args.definitionDigest===Uo}function Br(t){if(!or(t)||t.operation!=="tool.invoke")throw new Error("Invalid shell sandbox profile");return Lo(JSON.parse(t.args.argsJson))}function Ua(t,e){if(e.operation!=="tool.invoke")throw new Error("Invalid shell sandbox result");let n=JSON.parse(e.args.resultJson);if(n?.status!=="ok"||n.isError||n.content?.length!==1||n.content[0]?.t!=="text")throw new Error("Missing shell sandbox result");return jg(JSON.parse(n.content[0].text),t)}function Fo(t,e){if(t.action==="background"&&t.request.action!=="launch")throw new Error("Not a shell launch");let n=t.action==="exec"?t:t.request;if(!("command"in n))throw new Error("Not a shell launch");return he({sessionId:e.sessionId,scope:e.scope,binding:e.binding,turnId:t.call?.turnId,action:t.action,command:n.command,cwd:n.cwd,...t.action==="background"&&t.request.action==="launch"?{mode:t.request.mode}:{},interpreter:t.action==="exec"?t.interpreter:e.binding.target.interpreter})}function Ng(t,e,n,i){try{if(!n||!i||n.toolName!=="Shell"||i.status!=="completed"||!i.result||i.errorCode!==null||i.operationId!==n.operationId||i.digest!==n.digest||i.executorId!==n.binding.target.executorId||i.connectionId!==n.binding.target.connectionId)return!1;let o=Br(n.request);if(o.escalation!==void 0||o.call?.toolCallId===t.call?.toolCallId||Fo(o,n)!==Fo(t,e))return!1;let s=Ua(o,i.result);return s.sandbox.isolationDenied&&!s.sandbox.escalated}catch{return!1}}import{createHash as aw}from"node:crypto";var Ug="8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",Lg="2026-09-26.candidate-7",Ai="TansrTerminalBackground",Dr="03848c0c75af6e2e358ac64f81a61c79f595d8fc70442d06ae3c0576e39157b8",oi="TansrTerminalMemoryPublication",Ei="8532a582d40d2d8993a80db59412a89671670ed7f994eaf9bf972bd544a111b0",E={};E.Id=r.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._~-]*$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=128);E.LegacyId=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);E.Sequence=r.string().regex(new RegExp("^(0|[1-9][0-9]{0,17}|[1-8][0-9]{18}|9[0-1][0-9]{17}|92[0-1][0-9]{16}|922[0-2][0-9]{15}|9223[0-2][0-9]{14}|92233[0-6][0-9]{13}|922337[0-1][0-9]{12}|92233720[0-2][0-9]{10}|922337203[0-5][0-9]{9}|9223372036[0-7][0-9]{8}|92233720368[0-4][0-9]{7}|922337203685[0-3][0-9]{6}|9223372036854[0-6][0-9]{5}|92233720368547[0-6][0-9]{4}|922337203685477[0-4][0-9]{3}|9223372036854775[0-7][0-9]{2}|922337203685477580[0-6]|9223372036854775807)$","u")).refine(t=>[...t].length<=19);E.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));E.Scope=r.object({applicationScopeId:r.lazy(()=>E.Id),endUserId:r.lazy(()=>E.LegacyId),authorizationRevision:r.lazy(()=>E.Sequence)}).strict();E.ExecutionBinding=r.object({bindingId:r.lazy(()=>E.Id),revision:r.lazy(()=>E.Sequence),target:r.lazy(()=>E.ExecutionTarget)}).strict();E.ExecutionTarget=r.object({executorId:r.lazy(()=>E.Id),connectionId:r.lazy(()=>E.Id),connectionRevision:r.lazy(()=>E.Sequence),workspaceId:r.lazy(()=>E.Id),workspaceRevision:r.lazy(()=>E.Sequence),interpreter:r.lazy(()=>E.ExecutionInterpreter).optional()}).strict();E.ExecutionInterpreter=r.object({id:r.lazy(()=>E.Id),revision:r.lazy(()=>E.Id),hostShell:r.union([r.literal("posix"),r.literal("powershell")])}).strict();E.Contract=r.literal("terminal-services-v1");E.SchemaRevision=r.literal("2026-09-26.candidate-7");E.SessionContract=r.union([r.literal("sdk1"),r.literal("sdk2-offload-v1")]);E.Feature=r.union([r.literal("execution-stream-v1"),r.literal("execution-background-v1"),r.literal("memory-lifecycle-v1"),r.literal("session-configuration-v1")]);E.SessionReference=r.object({sessionContract:r.lazy(()=>E.SessionContract),sessionId:r.lazy(()=>E.LegacyId)}).strict();E.FeatureAvailability=r.object({feature:r.lazy(()=>E.Feature),supported:r.boolean(),installed:r.boolean(),authorization:r.union([r.literal("allowed"),r.literal("denied"),r.literal("unconfirmed")]),device:r.union([r.literal("available"),r.literal("unavailable"),r.literal("not-required"),r.literal("unconfirmed")])}).strict();E.Limits=r.object({maxControlBytes:r.number().int().safe().min(1).max(262144),maxBlockBytes:r.number().int().safe().min(1).max(16384),maxBatchBytes:r.number().int().safe().min(1).max(65536),maxPendingBytes:r.number().int().safe().min(1).max(2097152),maxRetainedBytes:r.number().int().safe().min(1).max(8388608)}).strict();E.CapabilitiesResponse=r.object({contract:r.lazy(()=>E.Contract),schemaRevision:r.lazy(()=>E.SchemaRevision),schemaSha256:r.lazy(()=>E.Digest),sessionContracts:r.array(r.lazy(()=>E.SessionContract)).min(1).max(2).refine(t=>new Set(t).size===t.length),features:r.array(r.lazy(()=>E.FeatureAvailability)).min(4).max(4),limits:r.lazy(()=>E.Limits)}).strict();E.BindingRequest=r.object({contract:r.lazy(()=>E.Contract),requestId:r.lazy(()=>E.Id),session:r.lazy(()=>E.SessionReference),executionBinding:r.union([r.lazy(()=>E.ExecutionBinding),r.null()]),required:r.array(r.lazy(()=>E.Feature)).min(0).max(4).refine(t=>new Set(t).size===t.length),optional:r.array(r.lazy(()=>E.Feature)).min(0).max(4).refine(t=>new Set(t).size===t.length)}).strict();E.BindingResponse=r.object({contract:r.lazy(()=>E.Contract),requestId:r.lazy(()=>E.Id),session:r.lazy(()=>E.SessionReference),scope:r.lazy(()=>E.Scope),executionBinding:r.union([r.lazy(()=>E.ExecutionBinding),r.null()]),accepted:r.array(r.lazy(()=>E.Feature)).min(0).max(4).refine(t=>new Set(t).size===t.length),unavailable:r.array(r.lazy(()=>E.FeatureAvailability)).min(0).max(4),outputAuthority:r.union([r.literal("session-events"),r.literal("tool-output")]),limits:r.lazy(()=>E.Limits)}).strict();E.OperationReference=r.object({operationId:r.lazy(()=>E.Id),requestDigest:r.lazy(()=>E.Digest)}).strict();E.OutputBlock=r.object({seq:r.lazy(()=>E.Sequence),byteOffset:r.lazy(()=>E.Sequence),channel:r.union([r.literal("stdout"),r.literal("stderr")]),encoding:r.union([r.literal("utf-8"),r.literal("binary")]),byteLength:r.number().int().safe().min(1).max(16384),payloadDigest:r.lazy(()=>E.Digest),base64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length>=4).refine(t=>[...t].length<=21848)}).strict();E.OutputSeal=r.object({lastSeq:r.union([r.lazy(()=>E.Sequence),r.null()]),totalBytes:r.lazy(()=>E.Sequence),payloadDigest:r.lazy(()=>E.Digest),truncated:r.boolean()}).strict();E.OutputBatchRequest=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),operation:r.lazy(()=>E.OperationReference),executorId:r.lazy(()=>E.Id),connectionId:r.lazy(()=>E.Id),blocks:r.array(r.lazy(()=>E.OutputBlock)).min(0).max(32),seal:r.union([r.lazy(()=>E.OutputSeal),r.null()])}).strict();E.OutputStatus=r.object({contract:r.lazy(()=>E.Contract),operation:r.lazy(()=>E.OperationReference),state:r.union([r.literal("available"),r.literal("receiving"),r.literal("complete"),r.literal("truncated"),r.literal("gap"),r.literal("unavailable")]),acceptedThrough:r.union([r.lazy(()=>E.Sequence),r.null()]),durableThrough:r.union([r.lazy(()=>E.Sequence),r.null()]),retainedFrom:r.union([r.lazy(()=>E.Sequence),r.null()]),nextByteOffset:r.union([r.lazy(()=>E.Sequence),r.null()]),seal:r.union([r.lazy(()=>E.OutputSeal),r.null()])}).strict();E.OutputEvent=r.union([r.object({contract:r.lazy(()=>E.Contract),type:r.literal("output.block"),operation:r.lazy(()=>E.OperationReference),block:r.lazy(()=>E.OutputBlock)}).strict(),r.object({contract:r.lazy(()=>E.Contract),type:r.literal("output.status"),status:r.lazy(()=>E.OutputStatus)}).strict()]);E.ExecutorEvent=r.object({contract:r.lazy(()=>E.Contract),eventId:r.lazy(()=>E.Sequence),type:r.union([r.literal("operations-available"),r.literal("operation-cancelled"),r.literal("reconcile-required")]),executorId:r.lazy(()=>E.Id),connectionId:r.lazy(()=>E.Id),operation:r.union([r.lazy(()=>E.OperationReference),r.null()])}).strict();E.OutputCorrelation=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),toolCallId:r.lazy(()=>E.LegacyId),operation:r.lazy(()=>E.OperationReference),outputAuthority:r.union([r.literal("session-events"),r.literal("tool-output")])}).strict();E.ErrorCode=r.union([r.literal("invalid_request"),r.literal("protocol_version_mismatch"),r.literal("unauthorized"),r.literal("forbidden"),r.literal("not_found"),r.literal("unsupported_capability"),r.literal("capability_unconfirmed"),r.literal("source_unavailable"),r.literal("stale_generation"),r.literal("binding_conflict"),r.literal("revision_conflict"),r.literal("busy"),r.literal("capacity_exceeded"),r.literal("payload_too_large"),r.literal("output_gap"),r.literal("integrity_mismatch"),r.literal("commit_unknown"),r.literal("context_transition_required"),r.literal("request_conflict"),r.literal("request_limit")]);E.ErrorResponse=r.object({contract:r.lazy(()=>E.Contract),requestId:r.lazy(()=>E.Id),code:r.lazy(()=>E.ErrorCode),status:r.union([r.literal(400),r.literal(401),r.literal(403),r.literal(404),r.literal(409),r.literal(413),r.literal(429),r.literal(503)]),retryAction:r.union([r.literal("none"),r.literal("discover"),r.literal("refresh"),r.literal("reconcile"),r.literal("backoff")])}).strict();E.ConfigurationRevision=r.number().int().safe().min(0).max(9007199254740991);E.Thinking=r.object({budget:r.number().int().safe().min(0).max(9007199254740991).optional()}).strict();E.SessionConfiguration=r.object({revision:r.lazy(()=>E.ConfigurationRevision),model:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512),r.null()]),thinking:r.union([r.lazy(()=>E.Thinking),r.null()])}).strict();E.ConfigurationChanges=r.object({model:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512).optional(),thinking:r.union([r.lazy(()=>E.Thinking),r.null()]).optional()}).strict();E.ConfigurationRequest=r.object({contract:r.lazy(()=>E.Contract),requestId:r.lazy(()=>E.Id),session:r.lazy(()=>E.SessionReference),expectedRevision:r.lazy(()=>E.ConfigurationRevision),changes:r.lazy(()=>E.ConfigurationChanges)}).strict();E.ConfigurationResponse=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),configuration:r.lazy(()=>E.SessionConfiguration)}).strict();E.ConfigurationCommitResponse=r.object({contract:r.lazy(()=>E.Contract),requestId:r.lazy(()=>E.Id),session:r.lazy(()=>E.SessionReference),status:r.union([r.literal("changed"),r.literal("replayed")]),configuration:r.lazy(()=>E.SessionConfiguration)}).strict();E.ExecutionStatus=r.object({protocol:r.literal("sdk2-ext-v1"),operation:r.lazy(()=>E.ExecutionOperation),status:r.union([r.literal("pending"),r.literal("completed"),r.literal("failed"),r.literal("unknown")]),receipt:r.union([r.lazy(()=>E.ExecutionReceiptRequest),r.null()])}).strict();E.ExecutionOperation=r.object({protocol:r.literal("sdk2-ext-v1"),operationId:r.lazy(()=>E.Id),sessionId:r.lazy(()=>E.LegacyId),scope:r.lazy(()=>E.Scope),binding:r.lazy(()=>E.ExecutionBinding),toolName:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),request:r.lazy(()=>E.ResourceRequest),digest:r.lazy(()=>E.Digest),expiresAt:r.string().datetime({offset:!0})}).strict();E.ResourceRequest=r.union([r.object({operation:r.literal("fs.inspect"),args:r.object({path:r.string().refine(t=>[...t].length<=4096),followLinks:r.boolean()}).strict()}).strict(),r.object({operation:r.literal("fs.read"),args:r.object({path:r.string().refine(t=>[...t].length<=4096),offset:r.number().int().safe().min(0).max(9007199254740991),length:r.number().int().safe().min(1).max(65536)}).strict()}).strict(),r.object({operation:r.literal("fs.write"),args:r.object({path:r.string().refine(t=>[...t].length<=4096),expectedHash:r.union([r.lazy(()=>E.Digest),r.null()]),bytesBase64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=174764)}).strict()}).strict(),r.object({operation:r.literal("fs.mkdir"),args:r.object({path:r.string().refine(t=>[...t].length<=4096)}).strict()}).strict(),r.object({operation:r.literal("fs.list"),args:r.object({path:r.string().refine(t=>[...t].length<=4096)}).strict()}).strict(),r.object({operation:r.literal("process.exec"),args:r.object({command:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768),cwd:r.string().refine(t=>[...t].length<=4096),timeoutMs:r.number().int().safe().min(1).max(12e4),maxOutputBytes:r.number().int().safe().min(1).max(65536),interpreter:r.lazy(()=>E.ExecutionInterpreter)}).strict()}).strict(),r.object({operation:r.literal("tool.invoke"),args:r.object({name:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),definitionDigest:r.lazy(()=>E.Digest),argsJson:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768)}).strict()}).strict()]);E.ExecutionReceiptRequest=r.object({protocol:r.literal("sdk2-ext-v1"),executorId:r.lazy(()=>E.Id),connectionId:r.lazy(()=>E.Id),operationId:r.lazy(()=>E.Id),digest:r.lazy(()=>E.Digest),status:r.union([r.literal("completed"),r.literal("failed"),r.literal("unknown")]),result:r.union([r.lazy(()=>E.ResourceResult),r.null()]),errorCode:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),r.null()])}).strict();E.ResourceResult=r.union([r.object({operation:r.literal("fs.inspect"),args:r.object({kind:r.union([r.literal("file"),r.literal("directory"),r.literal("symlink")]),size:r.number().int().safe().min(0).max(9007199254740991),mtimeMs:r.string().regex(new RegExp("^(0|[1-9][0-9]*)(\\.[0-9]+)?$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=32),realpath:r.string().refine(t=>[...t].length<=4096)}).strict()}).strict(),r.object({operation:r.literal("fs.read"),args:r.object({bytesBase64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=87384)}).strict()}).strict(),r.object({operation:r.literal("fs.write"),args:r.object({hash:r.lazy(()=>E.Digest)}).strict()}).strict(),r.object({operation:r.literal("fs.mkdir"),args:r.object({}).strict()}).strict(),r.object({operation:r.literal("fs.list"),args:r.object({entries:r.array(r.object({name:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=255),kind:r.union([r.literal("file"),r.literal("directory"),r.literal("symlink")])}).strict()).max(501)}).strict()}).strict(),r.object({operation:r.literal("process.exec"),args:r.object({stdout:r.string().refine(t=>[...t].length<=65536),stderr:r.string().refine(t=>[...t].length<=65536),exitCode:r.union([r.string().regex(new RegExp("^(0|[1-9][0-9]*|-[1-9][0-9]*)$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=11),r.null()]),signalName:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32),r.null()]),durationMs:r.number().int().safe().min(0).max(9007199254740991),timedOut:r.boolean(),aborted:r.boolean()}).strict()}).strict(),r.object({operation:r.literal("tool.invoke"),args:r.object({resultJson:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768)}).strict()}).strict()]);E.ExecutionState=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),execution:r.lazy(()=>E.ExecutionStatus)}).strict();E.BackgroundIdentity=r.object({taskId:r.lazy(()=>E.Id),operationId:r.lazy(()=>E.Id),requestDigest:r.lazy(()=>E.Digest),runtimeInstanceId:r.lazy(()=>E.Id),processInstanceId:r.lazy(()=>E.Id)}).strict();E.ArtifactReference=r.object({artifactId:r.lazy(()=>E.Id),operationId:r.lazy(()=>E.Id),requestDigest:r.lazy(()=>E.Digest)}).strict();E.BackgroundRequest=r.union([r.object({contract:r.lazy(()=>E.Contract),action:r.literal("launch"),command:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=8192),cwd:r.string().refine(t=>[...t].length<=4096),mode:r.union([r.literal("background"),r.literal("foreground-handoff")]),timeoutMs:r.number().int().safe().min(1).max(864e5),foregroundTimeoutMs:r.number().int().safe().min(1).max(12e4).optional()}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("query"),identity:r.lazy(()=>E.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("cancel"),identity:r.lazy(()=>E.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("outputRead"),identity:r.lazy(()=>E.BackgroundIdentity),artifact:r.lazy(()=>E.ArtifactReference),offset:r.lazy(()=>E.Sequence),length:r.number().int().safe().min(1).max(16384)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("artifactDelete"),identity:r.lazy(()=>E.BackgroundIdentity),artifact:r.lazy(()=>E.ArtifactReference)}).strict()]);E.BackgroundTaskState=r.object({identity:r.lazy(()=>E.BackgroundIdentity),artifact:r.lazy(()=>E.ArtifactReference),state:r.union([r.literal("running"),r.literal("completed"),r.literal("failed"),r.literal("cancelled"),r.literal("unknown")]),exitCode:r.union([r.number().int().safe().min(-2147483648).max(2147483647),r.null()]),signalName:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=64),r.null()]),totalBytes:r.union([r.lazy(()=>E.Sequence),r.null()]),truncated:r.boolean()}).strict();E.BackgroundResponse=r.union([r.object({contract:r.lazy(()=>E.Contract),action:r.literal("launch"),task:r.lazy(()=>E.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("query"),task:r.lazy(()=>E.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("cancel"),task:r.lazy(()=>E.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("outputRead"),identity:r.lazy(()=>E.BackgroundIdentity),artifact:r.lazy(()=>E.ArtifactReference),offset:r.lazy(()=>E.Sequence),base64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=21848),byteLength:r.number().int().safe().min(0).max(16384),payloadDigest:r.lazy(()=>E.Digest),nextOffset:r.lazy(()=>E.Sequence),complete:r.boolean(),gap:r.boolean()}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("artifactDelete"),identity:r.lazy(()=>E.BackgroundIdentity),artifact:r.lazy(()=>E.ArtifactReference),status:r.union([r.literal("deleted"),r.literal("already_deleted")])}).strict()]);E.MemoryIdentity=r.object({kind:r.union([r.literal("server-managed"),r.literal("client-managed"),r.literal("developer-managed")]),domain:r.lazy(()=>E.MemoryIdentifier),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),applicationScopeId:r.lazy(()=>E.Id),endUserId:r.lazy(()=>E.LegacyId)}).strict();E.MemoryCommand=r.union([r.object({kind:r.literal("pin"),text:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=4096)}).strict(),r.object({kind:r.literal("remember")}).strict(),r.object({kind:r.literal("forget"),topic:r.lazy(()=>E.MemoryIdentifier)}).strict()]);E.MemoryCommandRequest=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),requestId:r.lazy(()=>E.MemoryIdentifier),operationId:r.lazy(()=>E.MemoryIdentifier),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),expectedRevision:r.lazy(()=>E.Sequence),command:r.lazy(()=>E.MemoryCommand)}).strict();E.MemoryReceipt=r.object({requestId:r.lazy(()=>E.MemoryIdentifier),operationId:r.lazy(()=>E.MemoryIdentifier),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),expectedRevision:r.lazy(()=>E.Sequence),status:r.union([r.literal("pending"),r.literal("unknown"),r.literal("committed"),r.literal("failed")]),publishedRevision:r.lazy(()=>E.Sequence).optional(),errorCode:r.union([r.literal("operation_failed"),r.literal("commit_unknown")]).optional(),executionComplete:r.boolean(),durable:r.boolean(),consumed:r.boolean()}).strict();E.MemoryState=r.object({identity:r.lazy(()=>E.MemoryIdentity),revision:r.lazy(()=>E.Sequence),deletionGeneration:r.lazy(()=>E.Sequence),available:r.boolean()}).strict();E.MemoryStateResponse=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),memory:r.lazy(()=>E.MemoryState)}).strict();E.MemoryReceiptResponse=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),receipt:r.union([r.lazy(()=>E.MemoryReceipt),r.null()])}).strict();E.MemoryIdentifier=r.string().regex(new RegExp("^[^\\u0000-\\u001f\\u007f]+$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=256);E.MemoryPublicationEtag=r.string().regex(new RegExp("^[^\\u0000-\\u001f\\u007f]+$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=256);E.MemoryPublicationHead=r.object({etag:r.lazy(()=>E.MemoryPublicationEtag),byteLength:r.number().int().safe().min(1).max(4194304),sha256:r.lazy(()=>E.Digest)}).strict();E.MemoryPublicationTransfer=r.object({transferId:r.lazy(()=>E.Id),status:r.union([r.literal("staging"),r.literal("committed"),r.literal("conflict"),r.literal("unknown")]),receivedBytes:r.union([r.number().int().safe().min(0).max(4194304),r.null()]),etag:r.union([r.lazy(()=>E.MemoryPublicationEtag),r.null()])}).strict();E.MemoryPublicationRequest=r.union([r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("head")}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("read"),etag:r.lazy(()=>E.MemoryPublicationEtag),offset:r.number().int().safe().min(0).max(4194304),length:r.number().int().safe().min(1).max(12288)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("begin"),transferId:r.lazy(()=>E.Id),expectedEtag:r.union([r.lazy(()=>E.MemoryPublicationEtag),r.null()]),byteLength:r.number().int().safe().min(1).max(4194304),sha256:r.lazy(()=>E.Digest)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("chunk"),transferId:r.lazy(()=>E.Id),offset:r.number().int().safe().min(0).max(4194304),base64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=16384),byteLength:r.number().int().safe().min(1).max(12288),payloadDigest:r.lazy(()=>E.Digest)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("commit"),transferId:r.lazy(()=>E.Id)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("query"),transferId:r.lazy(()=>E.Id)}).strict()]);E.MemoryPublicationResponse=r.union([r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("head"),publication:r.union([r.lazy(()=>E.MemoryPublicationHead),r.null()])}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("read"),etag:r.lazy(()=>E.MemoryPublicationEtag),offset:r.number().int().safe().min(0).max(4194304),base64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=16384),byteLength:r.number().int().safe().min(0).max(12288),payloadDigest:r.lazy(()=>E.Digest),nextOffset:r.number().int().safe().min(0).max(4194304),complete:r.boolean()}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("begin"),transfer:r.lazy(()=>E.MemoryPublicationTransfer)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("chunk"),transfer:r.lazy(()=>E.MemoryPublicationTransfer)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("commit"),transfer:r.lazy(()=>E.MemoryPublicationTransfer)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("query"),transfer:r.lazy(()=>E.MemoryPublicationTransfer)}).strict()]);function yt(t,e){if(!Object.hasOwn(E,t))throw new TypeError("Unknown terminal contract type");return E[t].parse(e)}function La(t,e){return he(t)===he(e)}function qn(){throw new Error("Invalid terminal background response.")}function Fg(t){let e=t.timeoutMs??12e4,n=t.pollMs??1e3;if(!Number.isSafeInteger(e)||e<1||e>864e5||!Number.isSafeInteger(n)||n<1)throw new RangeError("Invalid background limits.");let i=new Map,o=new Set,s=!1,a=new fm({signal:t.signal,maxTasks:128}),d=h=>he([h.toolCallId,h.executionTarget]);async function c(h,p,v){if((p.waiting??0)>=4)throw new Error("Background control capacity exceeded.");let b=p.tail??Promise.resolve(),R,w=new Promise(x=>{R=x});p.tail=w,p.waiting=(p.waiting??0)+1;try{return await new Promise((x,T)=>{let M=()=>{v.removeEventListener("abort",M),T(v.reason)};v.addEventListener("abort",M,{once:!0}),b.then(()=>{v.removeEventListener("abort",M),x()}),v.aborted&&M()}),v.throwIfAborted(),await l(h,p,v)}finally{b.then(()=>{p.waiting=(p.waiting??1)-1,R()})}}async function l(h,p,v){if(s||!t.enabled())throw new Error("Background capability is no longer available.");if(!p.launch)throw new Error("Missing original background launch identity.");let b=await t.invoke(h,p.call.executionTarget,v,p.launch),R=yt("BackgroundResponse","response"in b?b.response:b);if(h.action==="launch"&&"response"in b&&(p.sandbox=Object.freeze({...b.sandbox})),h.action!=="launch"&&v.throwIfAborted(),R.action!==h.action&&qn(),h.action!=="launch"){let w="task"in R?R.task.identity:R.identity;La(w,h.identity)||qn(),"artifact"in h&&(!("artifact"in R)||!La(R.artifact,h.artifact))&&qn()}return R}async function f(h,p){if(!h.task)throw new Error("Background launch has not been confirmed.");let v=p.signal?AbortSignal.any([p.signal,t.signal]):t.signal,b=await c({contract:"terminal-services-v1",action:"outputRead",identity:h.task.identity,artifact:h.task.artifact,offset:String(p.offset),length:Math.min(p.length,16384)},h,v);b.action!=="outputRead"&&qn();let R=Buffer.from(b.base64,"base64");return(R.toString("base64")!==b.base64||R.length!==b.byteLength||R.length>Math.min(p.length,16384)||b.offset!==String(p.offset)||BigInt(b.nextOffset)!==p.offset+BigInt(R.length)||aw("sha256").update(R).digest("hex")!==b.payloadDigest||b.gap&&b.complete)&&qn(),{offset:p.offset,bytes:R,nextOffset:BigInt(b.nextOffset),complete:b.complete,gap:b.gap}}let u=h=>{if(t.signal.throwIfAborted(),s)throw new Error("Background runtime is closed.");let p=d(h);if(i.has(p)||i.size+o.size>=128)throw new Error("Background capacity exceeded.");let v={call:{...h,executionTarget:Object.freeze({...h.executionTarget})},chars:0,opened:!1,port:void 0};return v.port={get artifactRef(){if(!v.task)throw new Error("Background launch has not been confirmed.");return Object.freeze({...v.task.artifact})},get opened(){return v.opened&&v.task!==void 0},get totalChars(){return v.chars},get writeError(){return v.error},forceOpen(){v.opened=!0},append(b){v.chars+=b.length},async close(){i.delete(p)},read:b=>f(v,b),async remove(b){if(!v.task||v.task.state==="running"||v.task.state==="unknown")throw new Error("Output deletion requires a confirmed terminal process.");let R=await c({contract:"terminal-services-v1",action:"artifactDelete",identity:v.task.identity,artifact:v.task.artifact},v,AbortSignal.any([b,t.signal]));return R.action!=="artifactDelete"&&qn(),R.status}},i.set(p,v),v.port};async function m(h,p,v=!1){let b=i.get(d(h));if(!b)throw new Error("Missing original background output port.");a.assertCapacity(),b.launch={...h,executionTarget:Object.freeze({...h.executionTarget})},b.call=b.launch;let R;try{R=await c({contract:"terminal-services-v1",action:"launch",command:h.command,cwd:h.cwd,mode:p===void 0?"background":"foreground-handoff",timeoutMs:e,...p===void 0?{}:{foregroundTimeoutMs:Math.min(p,12e4)}},b,h.signal)}catch(j){throw i.delete(d(h)),j}R.action!=="launch"&&qn();let w=lm(R.task.identity);(R.task.artifact.operationId!==w.operationId||R.task.artifact.requestDigest!==w.requestDigest||R.task.state==="unknown")&&qn(),b.task=R.task,i.delete(d(h)),R.task.truncated&&(b.error="Background output is incomplete.");let x=!1,T,M=0n,W,$,D=Date.now(),J=new Promise(j=>{$=j}),S=v&&p!==void 0?D+p:void 0,k=p===void 0?n:Math.min(n,Math.max(1,Math.floor(p/4))),A=S!==void 0,C=new AbortController,F=j=>{if(x)return;x=!0,C.abort(),o.delete(H);let ne=j===void 0||j.state==="unknown";$({exitCode:ne?null:j.exitCode,signalName:ne?null:j.signalName,durationMs:Date.now()-D,...ne?{outcomeUnknown:!0}:{},...j?.state==="failed"?{executionFailed:!0}:{},...j?.state==="cancelled"?{cancelled:!0}:{}})},H={close:()=>F()};o.add(H);let Q=j=>{(!La(j.identity,w)||!La(j.artifact,b.task?.artifact))&&qn(),j.truncated&&(b.error="Background output is incomplete."),b.task=j},re=AbortSignal.any([C.signal,t.signal]),O=async(j,ne)=>{let U=await c({contract:"terminal-services-v1",action:j,identity:w},b,AbortSignal.any([ne,t.signal]));return(U.action!==j||!("task"in U))&&qn(),Q(U.task),U.task.state==="unknown"&&F(U.task),{state:U.task.state,exitCode:U.task.exitCode,signalName:U.task.signalName}},I=()=>{x||W||(W=c({contract:"terminal-services-v1",action:"cancel",identity:w},b,re).then(j=>{j.action!=="cancel"&&qn(),Q(j.task),j.task.state==="unknown"&&F(j.task)}).catch(()=>F()).finally(()=>{W=void 0}))},B={identity:w,pid:void 0,startedAt:D,...b.sandbox?{sandbox:b.sandbox}:{},get lastOutputAt(){return T},get settled(){return x},exit:J,kill:I,control:{query:j=>O("query",j),cancel:j=>O("cancel",j)},killSync:()=>F()};h.signal.aborted&&I();let z=new TextDecoder;return(async()=>{try{for(;!x;){re.throwIfAborted();let j=b.task;if(j.state==="unknown"){F(j);break}for(let U=0;U<16&&j.totalBytes!==null&&M<BigInt(j.totalBytes);U++){let le=await f(b,{offset:M,length:16384,signal:re});if(le.gap||le.bytes.length===0){b.error="Background output gap.";break}M=le.nextOffset,T=Date.now();let ue=z.decode(le.bytes,{stream:!0});ue&&h.onChunk?.(ue,"stdout")}if(j.state!=="running"){if(j.totalBytes!==null&&M<BigInt(j.totalBytes)&&!b.error)continue;let U=z.decode();U&&h.onChunk?.(U,"stdout"),F(j);break}if(!A){let U=S!==void 0&&Date.now()<S?k:n;await new Promise((le,ue)=>{let ie=setTimeout(()=>{re.removeEventListener("abort",me),le()},U);ie.unref();let me=()=>{clearTimeout(ie),re.removeEventListener("abort",me),ue(re.reason)};re.addEventListener("abort",me,{once:!0}),re.aborted&&me()})}A=!1;let ne=await c({contract:"terminal-services-v1",action:"query",identity:w},b,re);ne.action!=="query"&&qn(),Q(ne.task)}}catch{F()}})(),B}return{runtime:{enabled:t.enabled,createOutput:u,launch:m,registry:a,timeoutHandoff:!0},registry:a,async exec(h){if(!h.executionTarget||!h.toolCallId)throw new Error("Missing bound execution identity.");let p=await m({...h,executionTarget:h.executionTarget,toolCallId:h.toolCallId},h.timeoutMs,h.timeoutHandoff!==void 0),v=await um(h,p);return"sandbox"in p&&p.sandbox?{...v,sandbox:p.sandbox}:v},close(){s=!0;for(let h of o)h.close();i.clear()}}}import Hg from"node:path";var jE=Hg.resolve(Hg.sep,".tansr-sdk-no-discovery");function dw(t){let e=[];for(let[n,i]of Object.entries(t)){if(!Em.test(n)||n.includes("__"))throw new pt("invalid_options",`mcp: server name "${n}" is invalid; use 1-64 characters starting with a letter/digit (letters, digits, hyphens, underscores; double underscore "__" is reserved as the tool-name separator).`);let o=Cm.safeParse(i);if(!o.success){let s=o.error.issues[0],a=s!==void 0&&s.path.length>0?` at "${s.path.join(".")}"`:"";throw new pt("invalid_options",`mcp: server "${n}" has an invalid config${a}: ${s?.message??"invalid shape"}. Expected { transport: 'stdio', command, args?, env?, cwd? } or { transport: 'http', url, headers? } (plus optional enabled/load/toolAllowlist).`)}e.push({name:n,config:o.data})}return e}var qr=class{#e;#n;#r=null;#s=!1;#t;#o=!1;#i;get cleanupEvidence(){return(this.#i?.cleanupEvidence??[]).map(e=>({resource:"mcp",level:e}))}constructor(e){this.#e=dw(e.servers),this.#n=e}manager(){return this.#s?Promise.reject(new pt("invalid_options","This McpHost has been disposed; create a new host, or pass { servers } for a session-scoped host.")):(this.#r??=_m({registry:new Vn,toolDefs:[]},this.#e,{...this.#n.connectTimeoutMs!==void 0?{connectTimeoutMs:this.#n.connectTimeoutMs}:{},...this.#n.requestTimeoutMs!==void 0?{requestTimeoutMs:this.#n.requestTimeoutMs}:{},...this.#n.toolTimeoutMs!==void 0?{toolTimeoutMs:this.#n.toolTimeoutMs}:{},...this.#n.killGraceMs!==void 0?{killGraceMs:this.#n.killGraceMs}:{},...this.#n.clientInfo!==void 0?{clientInfo:this.#n.clientInfo}:{},...this.#n.baseEnv!==void 0?{baseEnv:this.#n.baseEnv}:{},...this.#n.fetchImpl!==void 0?{fetchImpl:this.#n.fetchImpl}:{},...this.#n.onEvent!==void 0?{onEvent:this.#n.onEvent}:{},...this.#n.connectFactory!==void 0?{connectFactory:this.#n.connectFactory}:{}}).then(e=>(this.#i=e,e),e=>{throw e instanceof Im&&(this.#i=e.cleanup),e}),this.#r)}dispose(){return this.#t!==void 0&&!this.#o?this.#t:(this.#s=!0,this.#o=!1,this.#t=(async()=>{await this.#r?.catch(()=>{}),await this.#i?.settleClose()})().catch(e=>{throw this.#o=!0,e}),this.#t.catch(()=>{}),this.#t)}};async function Fa(t,e){let n=await t.manager(),i=n.forToolset(e);for(let o of n.snapshot())o.loadMode==="eager"&&o.state==="ready"&&await i.expand(o.name);return n.catalog.length===0?{segment:null}:(e.registry.register(el(i)),e.toolDefs.push(bm),{segment:Tm(n.catalog),discoverToolFactory:o=>el(n.forToolset(o))})}function Ho(t,e){let n=t.systemPromptPolicy??"fallback",o=!!t.systemPrompt&&(e===void 0||n==="prepend"),s=e?.map(a=>({...a}))??[];return{system:[...o?[{text:t.systemPrompt,cacheable:!0}]:[],...s],info:{policy:n,source:o?s.length>0?"platform+sdk":"platform":e!==void 0?"sdk":"none"}}}var lw="Skill",uw="TodoWrite";function Ci(t,e,n){let{cwd:i,hooks:o}=n;return{decide(s,a){let d=a?.executionTarget,c=d?.kind==="device"?`/workspace/${d.workspaceId??"__unbound__"}`:i,l=d===void 0?{}:{executionTarget:d},f=e.get(s.name),u=f?.isReadOnly??!1,m=f!==void 0?{description:f.description,...f.effects!==void 0?{effects:f.effects}:{}}:void 0,g=a?.suppressClassifierSoften===!0,h=$p(a),p=Kp(a),v=!1,b=t.decide({toolName:s.name,args:s.args,isReadOnly:u,cwd:c,...l}),R=s.name===gm&&b.decision==="ask"&&b.source==="mode"&&b.matchedRule===void 0,w=!R&&s.name===lw&&(b.decision==="ask"||b.decision==="deny")&&b.source==="mode"&&b.matchedRule===void 0&&u,x=!R&&!w&&s.name===vm&&(b.decision==="ask"||b.decision==="deny")&&b.source==="mode"&&b.matchedRule===void 0&&u,T=!R&&!w&&!x&&s.name===uw&&(b.decision==="ask"||b.decision==="deny")&&b.source==="mode"&&b.matchedRule===void 0&&u,M=R?{decision:"allow",source:"policy"}:w?{decision:"allow",source:"policy",matchedRule:"skill(default-allow)"}:x?{decision:"allow",source:"policy",matchedRule:"mcp-discover(default-allow)"}:T?{decision:"allow",source:"policy",matchedRule:"todo-write(default-allow)"}:{decision:b.decision,source:b.source,...b.matchedRule!==void 0?{matchedRule:b.matchedRule}:{},...b.sourceLayer!==void 0?{sourceLayer:b.sourceLayer}:{},...b.reason!==void 0?{reason:b.reason}:{}},W=($,D)=>{if(!Vp($,v)||p)return $;let J=t.consultClassifier({...a?.signal!==void 0?{signal:a.signal}:{},toolName:s.name,args:D,isReadOnly:u,cwd:c,...l,...g?{suppressClassifierSoften:!0}:{},...m!==void 0?{toolMeta:m}:{}},{decision:$.decision,source:$.source,...$.matchedRule!==void 0?{matchedRule:$.matchedRule}:{}}),S=k=>k.decision==="ask"?k.source==="classifier"?{...$,source:"classifier",...k.reason!==void 0?{reason:k.reason}:{},...k.adjudication!==void 0?{classifierAdjudication:k.adjudication}:{}}:k.adjudication!==void 0?{...$,classifierAdjudication:k.adjudication}:$:{decision:k.decision,source:k.source,...k.matchedRule!==void 0?{matchedRule:k.matchedRule}:{},...k.sourceLayer!==void 0?{sourceLayer:k.sourceLayer}:{},...k.reason!==void 0?{reason:k.reason}:{},...k.adjudication!==void 0?{classifierAdjudication:k.adjudication}:{},...k.decision==="allow"&&$.updatedArgs!==void 0?{updatedArgs:$.updatedArgs}:{}};return J instanceof Promise?J.then(S):S(J)};return M.decision==="deny"||h||o===void 0||!o.hasHooks("PreToolUse",s.name)?W(M,s.args):(async()=>{let D=(await o.run({event:"PreToolUse",tool_name:s.name,tool_input:s.args,tool_use_id:s.id})).preToolUse??{},J=D.decision;v=J==="ask";let S=J!==void 0&&Cc[J]>Cc[M.decision]?{decision:J,source:"hook"}:{...M};if(D.updatedInput!==void 0&&S.decision!=="deny"){let k=t.decide({toolName:s.name,args:D.updatedInput,isReadOnly:u,cwd:c,...l});return S=Wp(S,k),S.decision==="deny"?S:W({...S,updatedArgs:D.updatedInput},D.updatedInput)}return W(S,s.args)})()}}}var zg="tansr-platform";function fw(t){return t==="forbidden"?" The app platform capability webSearch is disabled; the app developer can enable it in console → app → capabilities.":t==="websearch_not_configured"?" Web search is not configured on this platform yet (no active search provider); tell the user instead of retrying.":t==="websearch_quota_exceeded"?" The daily web-search quota for this account is exhausted; retry after the daily reset (UTC+8).":t==="rate_limited"?" Too many requests right now; wait briefly before retrying.":t==="insufficient_balance"?" The app account balance is insufficient; the app developer needs to top up.":t==="upstream_error"?" All search providers failed for this request (nothing was billed); a later retry may succeed.":""}function Ha(t){let e=t.baseUrl.replace(/\/+$/,""),n=t.fetchImpl??fetch,i=t.token;return{name:zg,async search(o,s){let a;try{a=await n(`${e}/t1/websearch`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",[On]:i},body:JSON.stringify({query:o.query,max_results:o.maxResults}),signal:s.signal})}catch(l){if(s.signal.aborted)throw l;let f=l instanceof Error?l.message:String(l);throw new Error(`web search request failed to reach the tansr platform: ${f}`)}let d=null;try{d=await a.json()}catch{d=null}if(!a.ok){let l=d??{},f=typeof l.error?.code=="string"?l.error.code:`http_${a.status}`,u=typeof l.error?.message=="string"?l.error.message:"request rejected";throw new Error(`platform web search failed (${f}): ${u}.${fw(f)}`)}let c=d??{};if(!Array.isArray(c.results))throw new Error("platform web search returned an unexpected response (no results array).");return c.results.map(l=>{let f=l??{};return typeof f.title!="string"||typeof f.url!="string"?null:{title:f.title,url:f.url,snippet:typeof f.snippet=="string"?f.snippet:""}}).filter(l=>l!==null)}}}function bn(t){let e=th(t.inputSchema),{$schema:n,...i}=e;return{name:t.name,description:t.description,inputSchema:i}}function jr(t,e,n){try{let{client:i,resolved:o}=Xm(t,e,{...n!==void 0?{onProviderSelected:n}:{}});return{client:i,model:{provider:o.providerId,model:o.modelName},...o.capability.maxContext!==void 0?{contextWindowTokens:o.capability.maxContext}:{},...o.capability.maxOutput!==void 0?{maxOutputTokens:o.capability.maxOutput}:{}}}catch(i){let o=i instanceof Error?i.message:String(i);throw new pt("assembly_failed",`Failed to assemble model client for "${e}": ${o}`,{cause:i})}}import{createHash as yw}from"node:crypto";var jn=class extends pt{failure;constructor(e,n){super("assembly_failed",`App config request failed (${e.reason}${e.status===void 0?"":`, HTTP ${e.status}`}).`,n),this.name="AppConfigRequestError",this.failure=Object.freeze({stage:e.stage,reason:e.reason,retry:e.retry,...e.status===void 0?{}:{status:e.status}})}};function ju(t){let e={stage:"app_config",status:t};return t===401?{...e,reason:"authentication",retry:"renew_credentials"}:t===403?{...e,reason:"authorization",retry:"check_permissions"}:t===429?{...e,reason:"rate_limit",retry:"retry_later"}:t>=500?{...e,reason:"unavailable",retry:"retry_later"}:{...e,reason:"invalid_config",retry:"check_configuration"}}function Nr(t){let e=new Set;for(let n=0;n<6&&t!==null&&typeof t=="object"&&!e.has(t);n++){if(e.add(t),t instanceof jn)return{...t.failure};let i=t;if(i.stage==="login"||i.stage==="mint"||i.stage==="request"){let o=typeof i.status=="number"&&Number.isInteger(i.status)&&i.status>=400&&i.status<=599?i.status:void 0,s={stage:"credential_refresh",...o===void 0?{}:{status:o}};if(i.code==="rejected"){let a=o===void 0?{reason:"authentication",retry:"sign_in"}:ju(o);return{...a,...s,retry:o===401?"sign_in":a.retry}}if(i.code==="network")return{...s,reason:"network",retry:"retry"};if(i.code==="timeout")return{...s,reason:"timeout",retry:"retry"};if(i.code==="invalid_response"||i.code==="target_rejected")return{...s,reason:"invalid_config",retry:"check_configuration"};if(i.code==="closed")return{...s,reason:"cancelled",retry:"none"}}if(i.name==="TimeoutError")return{stage:"app_config",reason:"timeout",retry:"retry"};if(i.name==="AbortError")return{stage:"app_config",reason:"cancelled",retry:"none"};t=i.cause}return{stage:"app_config",reason:"unknown",retry:"retry"}}function za(t){let e=Nr(t),n=e.stage==="turn_start"?"start":e.stage==="credential_refresh"?"credentials":"config";return`${vr(`sdk.prompt_failure.${n}`)} ${vr(`sdk.prompt_failure.${e.reason}`)} ${vr(`sdk.prompt_retry.${e.retry}`)}`.trim()}var Vg=new WeakMap;function Ga(t){return Vg.get(t)}function zo(t,e){return e===void 0?yw("sha256").update(JSON.stringify(t)).digest("hex"):e.replace(/^W\//,"").replace(/^"|"$/g,"")}var vw=[hs,gs,sp,ap,dp];function $g(t,e){let n=e??fetch;return(o,s)=>{let a=new Headers(s?.headers??(o instanceof Request?o.headers:void 0));for(let d of vw)a.delete(d);return a.set(On,t),n(o,{...s,headers:a})}}var bw="session_archived";function Nu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Wa(t,e,n,i,o=Gi){try{let s=await n(`${t}${ys.heartbeat}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",[On]:e,[fo]:o.join(",")},body:JSON.stringify({client:"sdk",...i!==void 0?{sessionId:i}:{}})});if(s.status===410){let c=null;try{c=await s.json()}catch{return{features:void 0,bundleEtag:void 0}}let l=Nu(c)&&Nu(c.error)?c.error:null;if(l!==null&&l.code===bw){let f=Nu(l.detail)?l.detail.sessionId:void 0;return{features:void 0,bundleEtag:void 0,archived:{sessionId:typeof f=="string"&&f!==""?f:i}}}return{features:void 0,bundleEtag:void 0}}if(!s.ok)return{features:void 0,bundleEtag:void 0};let d=await s.json()??{};return{features:Array.isArray(d.features)?d.features.filter(c=>typeof c=="string"):void 0,bundleEtag:typeof d.bundleEtag=="string"&&d.bundleEtag!==""?d.bundleEtag:void 0}}catch{return{features:void 0,bundleEtag:void 0}}}function Kg(t){if(t===null)return;let e=t.toLowerCase();if(/(^|,)\s*(no-store|no-cache)\s*(,|$)/.test(e))return 0;let n=/(?:^|,)\s*max-age\s*=\s*"?(\d+)"?/.exec(e);if(n===null)return;let i=Number.parseInt(n[1],10);return Number.isFinite(i)?i*1e3:void 0}async function si(t,e,n,i,o=Gi,s=!1){let a=`${t}${ys.config}`,d;try{d=await n(a,{method:"GET",headers:{accept:"application/json",[On]:e,[fo]:o.join(","),...i!==void 0?{"if-none-match":i}:{}}})}catch(m){let g=Nr(m);throw new jn(g.reason==="unknown"?{stage:"app_config",reason:"network",retry:"retry"}:g,{cause:m})}let c=d.headers.get("etag")??void 0,l=Kg(d.headers.get("cache-control"));if(d.status===304&&i!==void 0)return await d.arrayBuffer().catch(()=>{}),{bundle:null,status:304,etag:c,maxAgeMs:l};if(!d.ok)throw d.body?.cancel().catch(()=>{}),new jn(ju(d.status));let f;try{f=await d.json()}catch(m){throw new jn({stage:"app_config",reason:"invalid_config",retry:"check_configuration"},{cause:m})}let u=po(f);if(u===null||s&&(typeof f!="object"||f===null||!Object.hasOwn(f,"capabilities")||u.capabilitiesIssues!==null))throw new jn({stage:"app_config",reason:"invalid_config",retry:"check_configuration"});return{bundle:u,status:d.status,etag:c,maxAgeMs:l}}function Va(t,e){return Sw(t,e)}async function Sw(t,e){let n=t.baseUrl.replace(/\/+$/,""),i=t.fetchImpl??fetch,o,s,a,d;if(t.bundleCache!==void 0){let h=t.sessionId?.(),p=await t.bundleCache.resolve({baseUrl:n,token:t.token,fetchImpl:i,...t.appId!==void 0?{appId:t.appId}:{},...h!==void 0?{sessionId:h}:{}});o=p.bundle,d=p.etag,s=p.features,a=p.registryConfig,p.archivedSessionId!==void 0&&t.onSessionArchived?.(p.archivedSessionId)}else{let h=Wa(n,t.token,i,t.sessionId?.()),p=await si(n,t.token,i);if(p.bundle===null)throw new pt("assembly_failed",`App config bundle request to ${n}${ys.config} returned 304 without a conditional request. Check that "baseUrl" points to the tansr API.`);o=p.bundle,d=p.etag;let v=await h;s=v.features,v.archived!==void 0&&t.onSessionArchived?.(v.archived.sessionId)}if(o.capabilitiesIssues!==null&&t.onWarn!==void 0){let h=o.capabilitiesIssues[0],p=h!==void 0?` (first issue: ${h.path.length>0?h.path.join("."):"<root>"}: ${h.message})`:"";t.onWarn({code:"capabilities_unparsed",message:`The app's platform bundle "capabilities" section could not be parsed${p}; all capability bits were forced off (zero-capability profile) instead of falling back to the platform defaults. Check console → app → capabilities, or upgrade @tansr/sdk if the platform changed the section shape.`,detail:{issues:o.capabilitiesIssues}})}let c=$g(t.token,t.fetchImpl),l=e?.gatewayCache===void 0?void 0:t.sessionId?.();if(e?.gatewayCache!==void 0&&!l)throw new pt("assembly_failed","Gateway cache requires a current platform session.");let f=e?.gatewayCache===void 0?void 0:await e.gatewayCache({baseUrl:n,runtimeSessionId:l??"",configurationRevision:zo(o,d),fetchImpl:c});if(f!==void 0&&(!l||f.runtimeSessionId!==l))throw new pt("assembly_failed","Gateway cache must bind the current platform session.");let u=new ul(a??kr(o,n),{env:{[gl]:Wi},fetchImpl:c,twp:{...f!==void 0?{gatewayCache:f}:{},...t.sessionId!==void 0?{sessionId:t.sessionId}:{},features:()=>s,...t.onWarn!==void 0?{onWarn:t.onWarn}:{}}}),g={...jr(u,t.model??"main",t.onProviderSelected),registry:u,capabilities:o.capabilities,platformModels:o.platformModels,pricingUpdates:yl(o),platform:o.platform,adjudicator:o.adjudicator,app:o.app,...o.systemPrompt!==void 0?{systemPrompt:o.systemPrompt}:{},...o.systemPromptPolicy!==void 0?{systemPromptPolicy:o.systemPromptPolicy}:{},plan:o.plan,contextScheme:o.contextScheme,governance:o.governance};return e?.gatewayCache!==void 0&&Vg.set(g,{revision:zo(o,d),...d===void 0?{}:{etag:d}}),g}function Go(t,e){let n=Sm({...e,agents:Fs,toolset:{registry:t.registry,toolDefs:t.toolDefs}});t.registry.register(n),t.toolDefs.push(bn(n))}function $a(t,e){let n=t.baseUrl.replace(/\/+$/,""),i=t.fetchImpl??fetch,o={...t.initial},s=e?.initial.etag??t.etag,a=e?.initial.revision,d=!1;return async c=>{c.throwIfAborted();let l=(u,m)=>{let g=new Headers(m?.headers);g.set("cache-control","no-cache");let h=m?.signal??(u instanceof Request?u.signal:void 0);return i(u,{...m,headers:g,cache:"no-cache",signal:h?AbortSignal.any([c,h]):c})},f=await si(n,t.token,l,s);if(c.throwIfAborted(),e){let u=f.bundle===null?a:zo(f.bundle,f.etag);if(u!==a||d||e.refreshRequired?.()){d=!0,await e.refreshConfiguration(c),c.throwIfAborted();let m=await si(n,t.token,l,f.etag??s);if((m.bundle!==null||m.etag!==void 0)&&zo(m.bundle,m.etag)!==u)throw new Error("Application configuration changed during cache refresh");if(c.throwIfAborted(),u===void 0)throw new Error("Application configuration revision unavailable");e.confirmConfiguration?.(u),d=!1}a=u}return f.bundle!==null?(o={...f.bundle.systemPrompt!==void 0?{systemPrompt:f.bundle.systemPrompt}:{},...f.bundle.systemPromptPolicy!==void 0?{systemPromptPolicy:f.bundle.systemPromptPolicy}:{}},s=f.etag):s=f.etag??s,{...o}}}import{randomUUID as Mw}from"node:crypto";function Ka(t){let e=new AbortController,n=[],i,o=!1,s="aborted_streaming",a=t.prepareTimeoutMs??3e4;if(!(a>0)||!Number.isFinite(a))throw new TypeError("prepareTimeoutMs must be finite and positive");let d,c=new Promise(g=>{d=g}),l=Mw(),f=0,u=g=>({...g,sessionId:t.sessionId,turnId:l,seq:f++,ts:Date.now(),v:"v0",source:t.errorScope??"sdk"});return{events:(async function*(){let g=!0,h,p=setTimeout(()=>{s="timeout",e.abort(s)},a);p.unref?.();try{try{let v=new Promise((R,w)=>{h=()=>w(e.signal.reason),e.signal.addEventListener("abort",h,{once:!0}),e.signal.aborted&&h()}),b=await Promise.race([Promise.resolve().then(()=>(e.signal.throwIfAborted(),t.prepare(e.signal))),v]);e.signal.throwIfAborted(),g=!1,i=t.start(b.map(R=>({...R})));for(let R of n)i.enqueueUserInput(R);n.length=0}catch(v){if(yield u({type:"turn.started"}),!e.signal.aborted||e.signal.reason==="timeout"){let b=g?e.signal.aborted?new jn({stage:"app_config",reason:"timeout",retry:"retry"}):v:new jn({stage:"turn_start",reason:"unknown",retry:"retry"});yield u({type:"turn.error",scope:t.errorScope??"sdk",message:(t.errorMessage??za)(b),recoverable:!1,errorKind:g?"application_prompt_refresh_failed":"turn_start_failed",detail:{...Nr(b)}})}yield u({type:"turn.aborted",reason:e.signal.aborted?s:"model_error"});return}finally{clearTimeout(p),h!==void 0&&e.signal.removeEventListener("abort",h),d()}yield*t.eventsFor?.(i)??i.events}finally{o=!0}})(),enqueueUserInput(g){o||e.signal.aborted||(i!==void 0?i.enqueueUserInput(g):n.push(g))},abort(g){o||(i!==void 0?i.abort(g):(s=g??"aborted_streaming",e.abort(s)))},state:()=>i?.state()??(o?"terminated":"assembling"),counters:()=>i?.counters()??{modelTurns:0,toolRounds:0,consecutiveErrors:0,queueInjections:0},messages:()=>i?.messages()??structuredClone([...t.history]),inputTarget:()=>i?.inputTarget?.()??{turnId:l,open:!1},inputReceipts:()=>i?.inputReceipts?.()??[],reserveUserInput:g=>i?.reserveUserInput?.(g)??{status:"closed",code:"turn_closed"},compactNow:async g=>(await c,i?.compactNow?.(g)??{status:"rejected",reason:i===void 0?"turn_ended":"not_configured"})}}async function Uu(t){let e=t.baseUrl.replace(/\/+$/,""),n=t.fetchImpl??fetch,i;try{let s=eh(t.face,t.payload);if(s.kind==="rejected")return{kind:"response",status:s.status,body:{error:s.error}};i=await n(`${e}/t1/${t.face}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",[On]:t.token},body:s.body,...t.signal!==void 0?{signal:t.signal}:{}})}catch(s){return{kind:"transport_error",message:s instanceof Error?s.message:String(s)}}let o=null;try{o=await i.json()}catch{o=null}return{kind:"response",status:i.status,body:o}}function Lu(t,e){let n=t??{},i=typeof n.error?.code=="string"?n.error.code:`http_${e}`,o=typeof n.error?.message=="string"?n.error.message:"request rejected",s=Rm(n.error?.detail);return{code:i,message:o,...s?{detail:s}:{}}}var zP=Object.freeze({maxEvents:1e3,maxBytes:2*1024*1024});var Wo=["unauthorized"];var Vo=["check_unavailable"];function $o(t){return Wo.includes(t)}function Ko(t){return typeof t=="string"&&Vo.includes(t)}var Qo="nonchat-operations-v1",zu={embeddings:"/t1/embeddings",rerank:"/t1/rerank","document.parse":"/t1/document/parse/tasks","document.extract":"/t1/document/extract/tasks","document.redact":"/t1/document/redact/tasks","music.generate":"/t1/music/generate/tasks","music.upload":"/t1/music/uploads/tasks","music.cover":"/t1/music/cover/tasks","music.lyrics":"/t1/music/lyrics/tasks","music.style":"/t1/music/style/tasks","music.separate":"/t1/music/separate/tasks","sound.generate":"/t1/sound/tasks","voice.create":"/t1/voices/tasks","voice.refresh":"/t1/voices/refresh/tasks","voice.delete":"/t1/voices/delete/tasks"},Ja=r.string().min(1).max(256).optional(),Gu=r.string().min(1).max(32768).refine(t=>!/[\uD800-\uDFFF]/u.test(t)&&Buffer.byteLength(t,"utf8")<=32768),uy=r.array(Gu).min(1).max(128).refine(t=>t.reduce((e,n)=>e+Buffer.byteLength(n,"utf8"),0)<=1024*1024),fy=r.number().int().min(0).max(Number.MAX_SAFE_INTEGER),py=r.object({inputTokens:fy}).strict(),EM=r.object({model:Ja,input:uy,dimensions:r.number().int().min(1).max(3072).optional(),encodingFormat:r.literal("float").optional()}).strict(),CM=r.object({model:Ja,query:Gu,documents:uy,topN:r.number().int().min(1).max(128).optional(),returnDocuments:r.boolean().optional()}).strict().refine(t=>t.topN===void 0||t.topN<=t.documents.length),Yw=r.object({data:r.array(r.object({index:r.number().int().min(0).max(127),embedding:r.array(r.number().finite()).min(1).max(3072)}).strict()).min(1).max(128),usage:py}).strict().refine(t=>t.data.every((e,n)=>e.index===n&&e.embedding.length===t.data[0]?.embedding.length)),Xw=r.object({results:r.array(r.object({index:r.number().int().min(0).max(127),relevanceScore:r.number().finite().min(0).max(1),document:Gu.optional()}).strict()).min(1).max(128),usage:py}).strict().refine(t=>new Set(t.results.map(e=>e.index)).size===t.results.length&&t.results.every((e,n)=>n===0||e.relevanceScore<=t.results[n-1].relevanceScore)),Wu={model:r.string().min(1).max(200).optional(),document:r.union([r.object({url:r.string().min(1).max(4096).startsWith("https://")}).strict(),r.object({uploadRef:r.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/)}).strict()]),pages:r.array(r.number().int().min(1).max(Number.MAX_SAFE_INTEGER)).min(1).max(100).refine(t=>new Set(t).size===t.length).optional()},_M=r.object({...Wu,operation:r.literal("parse")}).strict(),PM=r.object({...Wu,operation:r.literal("extract"),fields:r.array(r.object({name:r.string().min(1).max(128).regex(/^[^\u0000-\u001f\u007f]+$/),type:r.enum(["string","number","boolean"])}).strict()).min(1).max(64)}).strict(),MM=r.object({...Wu,operation:r.literal("redact")}).strict(),sr={model:r.string().min(1).max(200).optional()},Lr=r.string().min(1).max(1e4).regex(/\S/),my=r.string().min(1).max(1e3).regex(/\S/),hy=r.string().min(1).max(200).regex(/\S/),gy=r.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/),Zw=r.object({...sr,operation:r.literal("music.upload"),url:r.string().min(1).max(4096).url().regex(/^[^\u0000-\u0020\u007f]+$/).refine(t=>{try{let e=new URL(t);return e.protocol==="https:"&&!e.username&&!e.password&&!t.includes("#")}catch{return!1}})}).strict(),OM=r.object({...sr,operation:r.literal("music.generate"),prompt:Lr.optional(),lyrics:Lr.optional(),style:my.optional(),title:hy.optional(),instrumental:r.boolean().optional(),gender:r.enum(["male","female"]).optional(),format:r.enum(["mp3","wav"]).optional()}).strict(),BM=r.object({...sr,operation:r.literal("music.cover"),sourceResourceId:gy,lyrics:Lr.optional(),style:my,title:hy,negativeStyle:r.string().max(1e3).optional()}).strict(),DM=r.object({...sr,operation:r.literal("music.lyrics"),prompt:Lr}).strict(),qM=r.object({...sr,operation:r.literal("music.style"),text:Lr}).strict(),jM=r.object({...sr,operation:r.literal("music.separate"),sourceResourceId:gy}).strict(),NM=r.object({...sr,operation:r.literal("sound.generate"),prompt:Lr,duration:r.number().int().min(1).max(600).optional()}).strict(),UM=r.object({model:Ja,targetModel:r.string().min(1).max(128),samples:r.array(r.object({url:r.string().min(1).max(4096)}).strict()).length(1),name:r.string().min(1).max(64).optional()}).strict(),LM=r.object({model:Ja,voiceRef:r.string().regex(/^voice_[a-f0-9-]{36}$/)}).strict();var ek=r.object({protocol:r.literal(Qo),taskId:r.string().min(1).max(96).regex(/^[A-Za-z0-9_.:-]+$/),requestId:r.string().min(1),operation:r.enum(["realtime.session",...Object.keys(zu)]),model:r.string(),status:r.enum(["preparing","accepted","running","succeeded","failed","unknown"]),pollIntervalMs:r.number().int().min(1e3),retainedUntil:r.string().datetime({offset:!0}),resultAvailable:r.boolean(),result:r.unknown().optional(),meter:r.record(fy).optional(),errorCode:r.string().optional(),billing:r.object({state:r.enum(["unreserved","reserved","settled","refunded","unknown"]),cost:r.string().nullable()}).strict()}).strict().refine(t=>t.resultAvailable===(t.result!==void 0)),tk=r.object({protocol:r.literal(Qo),models:r.array(r.object({model:r.string().min(1),displayName:r.string(),kind:r.string().min(1),operations:r.array(r.string().min(1)),availability:r.literal("requires-input-validation")}).strict())}).strict(),nk=r.string().regex(/^voice_[a-f0-9-]{36}$/),Ur=r.string().datetime({precision:3}).refine(t=>Number(t.slice(0,4))>=1e3&&Number.isFinite(Date.parse(t))&&new Date(t).toISOString()===t),Vu=r.object({id:nk,state:r.enum(["creating","ready","failed","unknown","deleting","deleted","expired"]),targetModel:r.string().min(1).max(256).regex(/^[a-zA-Z0-9_.:@/-]+$/),createdAt:Ur,updatedAt:Ur,expiresAt:Ur.nullable()}).strict().refine(t=>t.updatedAt>=t.createdAt&&(t.expiresAt===null||t.expiresAt>=t.createdAt)),yy=r.object({data:r.array(Vu).max(50).refine(t=>new Set(t.map(e=>e.id)).size===t.length)}).strict(),vy=r.string().length(39).regex(/^nc_[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),by=r.string().length(42).regex(/^music_[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),$u=r.object({id:by,taskId:vy,state:r.enum(["creating","ready","failed","unknown","deleting","deleted","expired"]),createdAt:Ur,updatedAt:Ur,expiresAt:Ur.nullable()}).strict().refine(t=>t.id===`music_${t.taskId.slice(3)}`&&t.updatedAt>=t.createdAt&&(t.expiresAt===null||t.expiresAt>=t.createdAt)),Sy=r.object({data:r.array($u).max(50).refine(t=>new Set(t.map(e=>e.id)).size===t.length)}).strict(),Hu=r.string().min(9).max(2048).startsWith("https://"),ik=r.object({model:r.string().min(1).max(128).optional(),prompt:r.string().min(1).max(1e4),negativePrompt:r.string().min(1).max(500).optional(),duration:r.number().int().min(2).max(30).optional(),ratio:r.string().regex(/^(adaptive|\d{1,2}:\d{1,2})$/).optional(),seed:r.number().int().min(0).max(2147483647).optional(),imageUrls:r.array(r.string().min(1).max(28e6)).min(1).max(2).optional(),audioUrl:r.string().min(1).max(2048).optional(),resolution:r.enum(["480p","540p","720p","768p","1080p"]).optional(),inputs:r.array(r.discriminatedUnion("kind",[r.object({kind:r.literal("image"),role:r.enum(["firstFrame","lastFrame","reference"]),url:Hu}).strict(),r.object({kind:r.literal("video"),role:r.enum(["reference","source"]),url:Hu}).strict(),r.object({kind:r.literal("audio"),role:r.literal("soundtrack"),url:Hu}).strict()])).min(1).max(12).optional()}).strict().refine(t=>t.inputs===void 0||t.imageUrls===void 0&&t.audioUrl===void 0);var Ku=r.string().regex(/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/),rk=r.object({model:r.string().min(1).max(128).optional(),operation:r.enum(["transcribe","translate"]),input:r.object({codec:r.literal("pcm16"),sampleRate:r.union([r.literal(8e3),r.literal(16e3),r.literal(24e3)]),channels:r.literal(1)}).strict(),targetLanguage:r.string().min(2).max(32).optional(),maxDurationSeconds:r.number().int().min(1).max(600),maxAmount:r.string().regex(/^(?:0|[1-9][0-9]*)(?:\.[0-9]{1,6})?$/).optional()}).strict(),ok=r.object({sessionId:Ku,connectPath:r.string(),connectTicket:r.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>Buffer.from(t,"base64url").toString("base64url")===t),expiresAt:r.string().datetime({offset:!0})}).strict().refine(t=>t.connectPath===`/t1/realtime/sessions/${t.sessionId}/connect`),sk=r.object({protocol:r.literal(Qo),sessionId:Ku,taskId:r.string().min(1).max(96).regex(/^[A-Za-z0-9_.:-]+$/),model:r.string(),status:r.enum(["creating","ready","failed","unknown","deleting","deleted","expired"]),phase:r.string(),createdAt:r.string().datetime({offset:!0}),updatedAt:r.string().datetime({offset:!0}),billing:r.object({state:r.enum(["settled","refunded","reserved","unknown"]),cost:r.string().nullable()}).strict(),errorCode:r.string().optional()}).strict();var ak=20*1024*1024,wy=27962028,dk={"application/pdf":["pdf"],"image/png":["png"],"image/jpeg":["jpg","jpeg"],"image/bmp":["bmp"],"image/tiff":["tif","tiff"]},ky=r.object({fileName:r.string().min(1).max(200).regex(/^[^\\/\u0000-\u001f\u007f]+$/),mime:r.enum(["application/pdf","image/png","image/jpeg","image/bmp","image/tiff"]),dataBase64:r.string().min(1).max(wy)}).strict().refine(t=>{if(t.dataBase64.length===0||t.dataBase64.length>wy)return!1;let e=t.fileName.split(".").at(-1)?.toLowerCase();if(!e||!dk[t.mime]?.includes(e))return!1;let n=Buffer.from(t.dataBase64,"base64");if(n.length===0||n.length>ak||n.toString("base64")!==t.dataBase64)return!1;let i=(...o)=>o.every((s,a)=>n[a]===s);return t.mime==="application/pdf"?i(37,80,68,70,45):t.mime==="image/png"?i(137,80,78,71,13,10,26,10):t.mime==="image/jpeg"?i(255,216,255):t.mime==="image/bmp"?i(66,77):i(73,73,42,0)||i(77,77,0,42)}),xy=r.string().length(45).regex(/^document_[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),Ry=r.object({uploadRef:xy,expiresAt:r.string().datetime({precision:3}).refine(t=>Number(t.slice(0,4))>=1e3&&Number.isFinite(Date.parse(t))&&new Date(t).toISOString()===t)}).strict();var rO=17*1024*1024,oO=8*1024*1024;import{createHash as Iy}from"node:crypto";var _i=6e4,lk=16,uk=1e5,fk=5e3,pk=36e5,Qu="app_user",Xa=class{#e=new Map;#n;constructor(e){this.#n=Math.max(1,e)}get size(){return this.#e.size}get(e){let n=this.#e.get(e);if(n!==void 0)return this.#e.delete(e),this.#e.set(e,n),n}peek(e){return this.#e.get(e)}set(e,n){for(this.#e.delete(e),this.#e.set(e,n);this.#e.size>this.#n;){let i=this.#e.keys().next();if(i.done)break;this.#e.delete(i.value)}}clear(){this.#e.clear()}};function mk(t){return Iy("sha256").update(t,"utf8").digest("hex")}function Ya(t=Gi){return Iy("sha256").update(t.join(","),"utf8").digest("hex").slice(0,8)}function Ju(t,e,n,i){return`${t}\0${e??""}\0${n}\0${i}`}function Yu(t){let e=t.trim().replace(/^W\//,"");return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function ar(t={}){let e=t.now??Date.now,n=Math.max(0,t.ttlMs??_i),i=new Xa(t.maxEntries??lk),o=new Xa(t.maxFeatureEntries??uk),s=new Map,a=new Map,d={hits:0,misses:0,revalidations:0,notModified:0,inflightDedup:0,featureHits:0,featureMisses:0,etagInvalidations:0},c=g=>{let h=i.peek(g);h!==void 0&&(h.expiresAt=0)},l=(g,h)=>{if(h===void 0)return;let p=i.peek(g);p===void 0||p.etag===void 0||Yu(p.etag)!==Yu(h)&&(p.expiresAt<=e()||(p.expiresAt=0,d.etagInvalidations+=1))},f=g=>Math.min(pk,g===void 0?n:Math.min(g,n)),u=(g,h,p,v,b)=>{let R=i.get(h);if(R!==void 0&&R.expiresAt>e())return d.hits+=1,Promise.resolve(R);let w=s.get(h);if(w!==void 0)return d.inflightDedup+=1,w;let x=(async()=>{R===void 0?d.misses+=1:d.revalidations+=1;let T=await si(g,p,v,R?.etag,b),M=f(T.maxAgeMs);if(T.bundle===null){if(R===void 0){let $=await si(g,p,v,void 0,b);if($.bundle===null)throw new Error("bundle cache: unconditional request returned 304");let D={bundle:$.bundle,registryConfig:kr($.bundle,g),etag:$.etag,expiresAt:e()+f($.maxAgeMs)};return i.set(h,D),D}return d.notModified+=1,R.expiresAt=e()+M,T.etag!==void 0&&(R.etag=T.etag),i.set(h,R),R}let W={bundle:T.bundle,registryConfig:kr(T.bundle,g),etag:T.etag,expiresAt:e()+M};return i.set(h,W),W})().finally(()=>s.delete(h));return s.set(h,x),x},m=(g,h,p,v,b,R)=>{let w=`${g}\0${mk(p)}\0${Ya(R)}`,x=o.get(w);if(x!==void 0&&x.expiresAt>e())return d.featureHits+=1,Promise.resolve({features:x.features});let T=a.get(w);if(T!==void 0)return d.inflightDedup+=1,T;d.featureMisses+=1;let M=(async()=>{let W=await Wa(g,p,v,b,R),$=W.features,D=$===void 0?Math.min(fk,n):n;return o.set(w,{features:$,expiresAt:e()+D}),l(h,W.bundleEtag),{features:$,...W.archived!==void 0?{archived:W.archived}:{}}})().finally(()=>a.delete(w));return a.set(w,M),M};return{async resolve(g){let h=g.baseUrl.replace(/\/+$/,""),p=g.fetchImpl??t.fetchImpl??fetch,v=Ju(h,g.appId,g.scope??Qu,Ya(g.clientFeatures)),[b,R]=await Promise.all([u(h,v,g.token,p,g.clientFeatures),m(h,v,g.token,p,g.sessionId,g.clientFeatures)]),w=R.archived!==void 0&&g.sessionId!==void 0&&(R.archived.sessionId===void 0||R.archived.sessionId===g.sessionId)?g.sessionId:void 0;return{bundle:b.bundle,registryConfig:b.registryConfig,etag:b.etag,features:R.features,...w!==void 0?{archivedSessionId:w}:{}}},invalidate(g){if(g===void 0){i.clear(),o.clear();return}c(Ju(g.baseUrl.replace(/\/+$/,""),g.appId,g.scope??Qu,Ya(g.clientFeatures)))},stats(){return{entries:i.size,hits:d.hits,misses:d.misses,revalidations:d.revalidations,notModified:d.notModified,inflightDedup:d.inflightDedup,featureEntries:o.size,featureHits:d.featureHits,featureMisses:d.featureMisses,etagInvalidations:d.etagInvalidations}}}}var ye={};ye.ClientPlatform=r.object({platform:r.union([r.literal("windows"),r.literal("linux"),r.literal("macos"),r.literal("android"),r.literal("ios"),r.literal("harmony")]),arch:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=64),language:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=64),runtimeVersion:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),adapterVersion:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128)}).strict();ye.ExecutionTarget=r.object({executorId:r.lazy(()=>ye.Id),connectionId:r.lazy(()=>ye.Id),connectionRevision:r.lazy(()=>ye.Sequence),workspaceId:r.lazy(()=>ye.Id),workspaceRevision:r.lazy(()=>ye.Sequence),interpreter:r.lazy(()=>ye.ExecutionInterpreter).optional()}).strict();ye.ExecutionBinding=r.object({bindingId:r.lazy(()=>ye.Id),revision:r.lazy(()=>ye.Sequence),target:r.lazy(()=>ye.ExecutionTarget)}).strict();ye.EffectiveTool=r.object({name:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),executionKind:r.union([r.literal("managed-service"),r.literal("bound-device")]),available:r.boolean(),unavailableReason:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),r.null()])}).strict();ye.ExecutionBoundaryApplication=r.object({authorizationRevision:r.lazy(()=>ye.Sequence),policyTools:r.array(r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128)).max(128).refine(t=>new Set(t).size===t.length),platformCapabilities:r.array(r.union([r.literal("imageGen"),r.literal("videoGen"),r.literal("webSearch"),r.literal("speechToText"),r.literal("textToSpeech")])).max(5).refine(t=>new Set(t).size===t.length),executionProfile:r.union([r.literal("legacy"),r.literal("bound-device-v1")])}).strict();ye.ExecutionBoundaryExecutor=r.object({executorId:r.lazy(()=>ye.Id),connectionId:r.lazy(()=>ye.Id),connectionRevision:r.lazy(()=>ye.Sequence),platform:r.lazy(()=>ye.ClientPlatform),operations:r.array(r.union([r.literal("fs.inspect"),r.literal("fs.read"),r.literal("fs.write"),r.literal("fs.mkdir"),r.literal("fs.list"),r.literal("process.exec"),r.literal("tool.invoke")])).max(7).refine(t=>new Set(t).size===t.length),workspaces:r.array(r.object({workspaceId:r.lazy(()=>ye.Id),revision:r.lazy(()=>ye.Sequence)}).strict()).max(32)}).strict();ye.ExecutionBoundary=r.object({protocol:r.literal("sdk2-ext-v1"),sessionId:r.lazy(()=>ye.LegacyId),revision:r.lazy(()=>ye.Digest),clientPlatform:r.union([r.lazy(()=>ye.ClientPlatform),r.null()]),application:r.lazy(()=>ye.ExecutionBoundaryApplication),requestedTools:r.union([r.array(r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128)).max(128).refine(t=>new Set(t).size===t.length),r.null()]),executor:r.union([r.lazy(()=>ye.ExecutionBoundaryExecutor),r.null()]),effectiveTools:r.array(r.lazy(()=>ye.EffectiveTool)).max(128),binding:r.union([r.lazy(()=>ye.ExecutionBinding),r.null()])}).strict();ye.SessionInitializeRequest=r.object({protocol:r.literal("sdk2-ext-v1"),sessionId:r.lazy(()=>ye.LegacyId),platform:r.lazy(()=>ye.ClientPlatform),requestedTools:r.array(r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128)).max(128).optional()}).strict();ye.SessionExecutionCapabilities=r.object({protocol:r.literal("sdk2-ext-v1"),sessionId:r.lazy(()=>ye.LegacyId),platform:r.union([r.lazy(()=>ye.ClientPlatform),r.null()]),capabilityRevision:r.lazy(()=>ye.Digest),effectiveTools:r.array(r.lazy(()=>ye.EffectiveTool)).max(128),binding:r.union([r.lazy(()=>ye.ExecutionBinding),r.null()])}).strict();ye.ExecutorRegistrationRequest=r.object({protocol:r.literal("sdk2-ext-v1"),executorId:r.lazy(()=>ye.Id),platform:r.lazy(()=>ye.ClientPlatform),workspaces:r.array(r.object({workspaceId:r.lazy(()=>ye.Id),revision:r.lazy(()=>ye.Sequence)}).strict()).max(32),operations:r.array(r.union([r.literal("fs.inspect"),r.literal("fs.read"),r.literal("fs.write"),r.literal("fs.mkdir"),r.literal("fs.list"),r.literal("process.exec"),r.literal("tool.invoke")])).max(7).refine(t=>new Set(t).size===t.length),tools:r.array(r.object({name:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),definitionDigest:r.lazy(()=>ye.Digest)}).strict()).max(64).optional(),interpreter:r.lazy(()=>ye.ExecutionInterpreter).optional()}).strict();ye.ExecutorConnection=r.object({protocol:r.literal("sdk2-ext-v1"),executorId:r.lazy(()=>ye.Id),connectionId:r.lazy(()=>ye.Id),connectionRevision:r.lazy(()=>ye.Sequence),expiresAt:r.string().datetime({offset:!0}),heartbeatAfterMs:r.number().int().safe().min(1e3).max(3e4)}).strict();ye.ExecutorHeartbeatRequest=r.object({protocol:r.literal("sdk2-ext-v1"),executorId:r.lazy(()=>ye.Id),connectionId:r.lazy(()=>ye.Id)}).strict();ye.ExecutionBindingRequest=r.object({protocol:r.literal("sdk2-ext-v1"),sessionId:r.lazy(()=>ye.LegacyId),executorId:r.lazy(()=>ye.Id),connectionId:r.lazy(()=>ye.Id),workspaceId:r.lazy(()=>ye.Id),expectedCapabilityRevision:r.lazy(()=>ye.Digest)}).strict();ye.ResourceRequest=r.union([r.object({operation:r.literal("fs.inspect"),args:r.object({path:r.string().refine(t=>[...t].length<=4096),followLinks:r.boolean()}).strict()}).strict(),r.object({operation:r.literal("fs.read"),args:r.object({path:r.string().refine(t=>[...t].length<=4096),offset:r.number().int().safe().min(0).max(9007199254740991),length:r.number().int().safe().min(1).max(65536)}).strict()}).strict(),r.object({operation:r.literal("fs.write"),args:r.object({path:r.string().refine(t=>[...t].length<=4096),expectedHash:r.union([r.lazy(()=>ye.Digest),r.null()]),bytesBase64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=174764)}).strict()}).strict(),r.object({operation:r.literal("fs.mkdir"),args:r.object({path:r.string().refine(t=>[...t].length<=4096)}).strict()}).strict(),r.object({operation:r.literal("fs.list"),args:r.object({path:r.string().refine(t=>[...t].length<=4096)}).strict()}).strict(),r.object({operation:r.literal("process.exec"),args:r.object({command:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768),cwd:r.string().refine(t=>[...t].length<=4096),timeoutMs:r.number().int().safe().min(1).max(12e4),maxOutputBytes:r.number().int().safe().min(1).max(65536),interpreter:r.lazy(()=>ye.ExecutionInterpreter)}).strict()}).strict(),r.object({operation:r.literal("tool.invoke"),args:r.object({name:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),definitionDigest:r.lazy(()=>ye.Digest),argsJson:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768)}).strict()}).strict()]);ye.ResourceResult=r.union([r.object({operation:r.literal("fs.inspect"),args:r.object({kind:r.union([r.literal("file"),r.literal("directory"),r.literal("symlink")]),size:r.number().int().safe().min(0).max(9007199254740991),mtimeMs:r.string().regex(new RegExp("^(0|[1-9][0-9]*)(\\.[0-9]+)?$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=32),realpath:r.string().refine(t=>[...t].length<=4096)}).strict()}).strict(),r.object({operation:r.literal("fs.read"),args:r.object({bytesBase64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=87384)}).strict()}).strict(),r.object({operation:r.literal("fs.write"),args:r.object({hash:r.lazy(()=>ye.Digest)}).strict()}).strict(),r.object({operation:r.literal("fs.mkdir"),args:r.object({}).strict()}).strict(),r.object({operation:r.literal("fs.list"),args:r.object({entries:r.array(r.object({name:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=255),kind:r.union([r.literal("file"),r.literal("directory"),r.literal("symlink")])}).strict()).max(501)}).strict()}).strict(),r.object({operation:r.literal("process.exec"),args:r.object({stdout:r.string().refine(t=>[...t].length<=65536),stderr:r.string().refine(t=>[...t].length<=65536),exitCode:r.union([r.string().regex(new RegExp("^(0|[1-9][0-9]*|-[1-9][0-9]*)$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=11),r.null()]),signalName:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32),r.null()]),durationMs:r.number().int().safe().min(0).max(9007199254740991),timedOut:r.boolean(),aborted:r.boolean()}).strict()}).strict(),r.object({operation:r.literal("tool.invoke"),args:r.object({resultJson:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768)}).strict()}).strict()]);ye.ExecutionOperation=r.object({protocol:r.literal("sdk2-ext-v1"),operationId:r.lazy(()=>ye.Id),sessionId:r.lazy(()=>ye.LegacyId),scope:r.lazy(()=>ye.Scope),binding:r.lazy(()=>ye.ExecutionBinding),toolName:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),request:r.lazy(()=>ye.ResourceRequest),digest:r.lazy(()=>ye.Digest),expiresAt:r.string().datetime({offset:!0})}).strict();ye.ExecutionBatch=r.object({protocol:r.literal("sdk2-ext-v1"),executorId:r.lazy(()=>ye.Id),connectionId:r.lazy(()=>ye.Id),operations:r.array(r.lazy(()=>ye.ExecutionOperation)).max(16)}).strict();ye.ExecutionReceiptRequest=r.object({protocol:r.literal("sdk2-ext-v1"),executorId:r.lazy(()=>ye.Id),connectionId:r.lazy(()=>ye.Id),operationId:r.lazy(()=>ye.Id),digest:r.lazy(()=>ye.Digest),status:r.union([r.literal("completed"),r.literal("failed"),r.literal("unknown")]),result:r.union([r.lazy(()=>ye.ResourceResult),r.null()]),errorCode:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),r.null()])}).strict();ye.ExecutionStatus=r.object({protocol:r.literal("sdk2-ext-v1"),operation:r.lazy(()=>ye.ExecutionOperation),status:r.union([r.literal("pending"),r.literal("completed"),r.literal("failed"),r.literal("unknown")]),receipt:r.union([r.lazy(()=>ye.ExecutionReceiptRequest),r.null()])}).strict();ye.Id=r.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._~-]*$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=128);ye.Sequence=r.string().regex(new RegExp("^(0|[1-9][0-9]{0,17}|[1-8][0-9]{18}|9[0-1][0-9]{17}|92[0-1][0-9]{16}|922[0-2][0-9]{15}|9223[0-2][0-9]{14}|92233[0-6][0-9]{13}|922337[0-1][0-9]{12}|92233720[0-2][0-9]{10}|922337203[0-5][0-9]{9}|9223372036[0-7][0-9]{8}|92233720368[0-4][0-9]{7}|922337203685[0-3][0-9]{6}|9223372036854[0-6][0-9]{5}|92233720368547[0-6][0-9]{4}|922337203685477[0-4][0-9]{3}|9223372036854775[0-7][0-9]{2}|922337203685477580[0-6]|9223372036854775807)$","u")).refine(t=>[...t].length<=19);ye.ExecutionInterpreter=r.object({id:r.lazy(()=>ye.Id),revision:r.lazy(()=>ye.Id),hostShell:r.union([r.literal("posix"),r.literal("powershell")])}).strict();ye.LegacyId=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);ye.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));ye.Scope=r.object({applicationScopeId:r.lazy(()=>ye.Id),endUserId:r.lazy(()=>ye.LegacyId),authorizationRevision:r.lazy(()=>ye.Sequence)}).strict();function _t(t,e){return ye[t].parse(e)}var Fr=262144,wk=8*1048576,kk=4096,Za=class{constructor(e){this.storage=e}storage;#e=new Map;#n=0;#r(e,n){return{bindingId:this.storage.bindingId,operationKey:`execution-${e}-${n}`}}#s(e){let n=this.#e.get(e);n&&(this.#n-=n.body.length,this.#e.delete(e))}#t(e,n,i,o){let s=this.#r(e,n),a=o?o.operations.get(s.operationKey)??null:this.storage.spool.status(s);if(a===null||a.state==="reserved")return this.#s(s.operationKey),null;let d=o?o.entries.get(s.operationKey):this.storage.spool.readEntry({bindingId:s.bindingId,entryId:s.operationKey,offset:0,maxBytes:Fr});if(!d||!d.complete||d.body===null||d.bodyState!=="retained")throw this.#s(s.operationKey),new Error("Execution fact unavailable");let c=this.#e.get(s.operationKey),l=Buffer.from(d.body);if(c?.commitDigest===a.receipt.commitDigest&&c.body.equals(l))return structuredClone(c.value);this.#s(s.operationKey);let f=_t(i,JSON.parse(l.toString("utf8")));return!(i==="ExecutionReceiptRequest"&&f.status==="unknown")&&this.#e.size<kk&&this.#n+l.length<=wk&&(this.#e.set(s.operationKey,{commitDigest:a.receipt.commitDigest,body:l,value:structuredClone(f)}),this.#n+=l.length),f}operation(e){return this.#t("request",e,"ExecutionOperation")}receipt(e){return this.#t("result",e,"ExecutionReceiptRequest")}reconciledReceipt(e){return this.#o(e)}#o(e,n){let i=this.#t("reconciliation",e,"ExecutionReceiptRequest",n);if(i===null)return null;let o=this.#t("result",e,"ExecutionReceiptRequest",n),s=this.#t("request",e,"ExecutionOperation",n),a=this.#r("reconciliation",e),d=n?n.operations.get(a.operationKey):this.storage.spool.status(a);if(o?.status!=="unknown"||!s||!d||i.status==="unknown"||d.reservation.intentDigest!==ut(he(o))||i.operationId!==s.operationId||i.digest!==s.digest||i.executorId!==s.binding.target.executorId||i.connectionId!==s.binding.target.connectionId)throw new Error("Execution reconciliation identity mismatch");return i}reconcile(e,n){let i=_t("ExecutionReceiptRequest",e.receipt),o=this.receipt(i.operationId),s=this.operation(i.operationId);if(o?.status!=="unknown"||!s||i.status==="unknown"||e.unknownReceiptDigest!==ut(he(o))||e.operationDigest!==s.digest||i.digest!==s.digest||i.executorId!==s.binding.target.executorId||i.connectionId!==s.binding.target.connectionId)throw new Error("Execution reconciliation identity mismatch");let a=this.reconciledReceipt(i.operationId),d=he({source:"trusted-host",evidenceId:e.evidenceId,authorizationRevision:n,operationDigest:s.digest,unknownReceiptDigest:e.unknownReceiptDigest}),c=Buffer.from(he(i));if(c.length>Fr||Buffer.byteLength(d)>1024)throw new Error("Execution reconciliation exceeds bound");if(a!==null)return he(a)===he(i);let l=this.#r("reconciliation",i.operationId);return this.storage.spool.reserve({...l,intentDigest:e.unknownReceiptDigest,originalMax:{bytes:Fr+1152,records:1},terminalReserve:{bytes:1,records:1}}),this.storage.spool.commit({...l,intentDigest:e.unknownReceiptDigest,entries:[{entryId:l.operationKey,basket:"original",metadata:d,body:c}]}),!0}recoverableOperations(e){let n=sc(this.storage.spool,{bindingId:this.storage.bindingId,operationKeyPrefix:"execution-",maxBodyBytes:Fr}),i=n===null?void 0:{operations:new Map(n.operations.map(d=>[d.reservation.operationKey,d])),entries:new Map(n.entries.map(d=>[d.entryId,d]))},o=n?.entries??this.storage.spool.snapshot().inventory.entries.filter(d=>d.bindingId===this.storage.bindingId),s=new Set(o.filter(d=>d.entryId.startsWith("execution-request-")).map(d=>d.entryId));if(s.size>8192)throw new RangeError("Execution recovery inventory exceeds bound");let a=[];for(let d of s){let c=d.slice(18),l=this.#t("request",c,"ExecutionOperation",i);if(!l)throw new Error("Execution request unavailable");if(l.sessionId===e.sessionId){if(l.scope.applicationScopeId!==e.applicationScopeId||l.scope.endUserId!==e.endUserId)throw new Error("Execution fact scope mismatch");l.toolName==="MemoryPublication"&&a.push({operation:l,receipt:this.#o(c,i)??this.#t("result",c,"ExecutionReceiptRequest",i)})}}return a}hasUnreconciled(e,n){let i=sc(this.storage.spool,{bindingId:this.storage.bindingId,operationKeyPrefix:"execution-",maxBodyBytes:Fr}),o=i===null?void 0:{operations:new Map(i.operations.map(d=>[d.reservation.operationKey,d])),entries:new Map(i.entries.map(d=>[d.entryId,d]))},s=i===null?this.storage.spool.snapshot().inventory:{reservations:i.operations.filter(d=>d.state==="reserved").map(d=>d.reservation),entries:i.entries.map(d=>({bindingId:this.storage.bindingId,entryId:d.entryId}))};return[...new Set([...s.reservations.filter(d=>d.bindingId===this.storage.bindingId).map(d=>d.operationKey),...s.entries.filter(d=>d.bindingId===this.storage.bindingId).map(d=>d.entryId)].filter(d=>d.startsWith("execution-result-")))].some(d=>{let c=d.slice(17),l=this.#t("request",c,"ExecutionOperation",o);if(l===null||l.scope.applicationScopeId!==e.applicationScopeId||l.scope.endUserId!==e.endUserId)return!0;if(l.sessionId!==e.sessionId)return!1;let f=this.#o(c,o)??this.#t("result",c,"ExecutionReceiptRequest",o);return n&&(["fs.inspect","fs.read","fs.list"].includes(l.request.operation)||f===null&&n.activeOperationIds.has(c))?!1:f===null||f.status==="unknown"})}prepare(e){let{spool:n}=this.storage,i={...this.#r("result",e.operationId),intentDigest:e.digest,originalMax:{bytes:1,records:1},terminalReserve:{bytes:Fr+128,records:1}},o=Buffer.from(he(e)),s=this.#r("request",e.operationId),a={...s,intentDigest:e.digest,originalMax:{bytes:o.length+128,records:1},terminalReserve:{bytes:1,records:1}},d={entryId:s.operationKey,basket:"original",metadata:"{}",body:o};if(n.prepareOperation!==void 0){n.prepareOperation({pending:i,request:a,entry:d});return}n.reserve(i),n.reserve(a),n.commit({...s,intentDigest:e.digest,entries:[d]})}accept(e){let n=this.receipt(e.operationId);if(n!==null){if(ut(he(n))!==ut(he(e)))throw new Error("Conflicting execution receipt");return}let i=this.#r("result",e.operationId);this.storage.spool.commit({...i,intentDigest:e.digest,entries:[{entryId:i.operationKey,basket:"terminal",metadata:"{}",body:Buffer.from(he(e))}]})}};import{randomUUID as xk}from"node:crypto";function Jn(t,e){return he(t)===he(e)}function Hr(t){if(!/^[a-zA-Z0-9_-]{1,128}$/.test(t))throw new TypeError("Invalid execution operation id");return`operation:${t}`}function Xu(t,e){return t.sessionId===e.sessionId&&t.scope.applicationScopeId===e.applicationScopeId&&t.scope.endUserId===e.endUserId}function Pi(t,e){let n=t.executions[Hr(e)];if(n&&(n.generation!==t.generation||!Xu(n.operation,t.scope)))throw new Error("Execution fact scope mismatch");return n}function ed(t,e){if(e.operationId!==t.operation.operationId||e.digest!==t.operation.digest||e.executorId!==t.operation.binding.target.executorId||e.connectionId!==t.operation.binding.target.connectionId)throw new Error("Execution receipt identity mismatch");if(Buffer.byteLength(he(e))>262144)throw new RangeError("Execution receipt exceeds bound")}function f1(t,e){let n={transactional:!0,scope:Object.freeze({...t}),acceptsOwner:e.acceptsOwner,operation:i=>e.read(o=>structuredClone(Pi(o,i)?.operation??null)),receipt:i=>e.read(o=>structuredClone(Pi(o,i)?.receipt??null)),reconciledReceipt:i=>e.read(o=>{let s=Pi(o,i);if(s?.reconciled&&(s.receipt?.status!=="unknown"||s.reconciled.status==="unknown"||s.observation?.unknownReceiptDigest!==ut(he(s.receipt))))throw new Error("Execution reconciliation identity mismatch");return structuredClone(s?.reconciled??null)}),recoverableOperations:i=>e.read(o=>{if(!Jn(i,t))throw new Error("Execution fact scope mismatch");let s=Object.values(o.executions);if(s.length>8192)throw new RangeError("Execution recovery inventory exceeds bound");return s.filter(a=>a.operation.toolName==="MemoryPublication").map(a=>{if(Pi(o,a.operation.operationId)!==a)throw new Error("Execution fact unavailable");if(a.receipt&&ed(a,a.receipt),a.reconciled&&(ed(a,a.reconciled),a.receipt?.status!=="unknown"||a.reconciled.status==="unknown"||a.observation?.unknownReceiptDigest!==ut(he(a.receipt))))throw new Error("Execution reconciliation identity mismatch");return structuredClone({operation:a.operation,receipt:a.reconciled??a.receipt??null})})}),hasUnreconciled:(i,o)=>e.read(s=>{if(!Jn(i,t))throw new Error("Execution fact scope mismatch");return Object.values(s.serviceExecutions??{}).some(a=>(Zu(s,a),!a.receipt&&o?.activeOperationIds.has(a.operation.operationId)&&a.claimId===s.owner?.claimId&&a.attempt===s.owner.attempt?!1:Ey(a)))||Object.values(s.executions).some(a=>{if(!Xu(a.operation,t)||a.generation!==s.generation)throw new Error("Execution fact scope mismatch");let d=a.reconciled??a.receipt;return o&&(["fs.inspect","fs.read","fs.list"].includes(a.operation.request.operation)||!d&&o.activeOperationIds.has(a.operation.operationId))?!1:!d||d.status==="unknown"})}),async prepare(i){let o=_t("ExecutionOperation",structuredClone(i));if(!Xu(o,t)||Buffer.byteLength(he(o))>262144)throw new Error("Execution request scope or bound mismatch");await e.write(s=>{if(!s.owner)throw new Error("Execution ownership missing");let a=Pi(s,o.operationId);if(a){if(!Jn(a.operation,o)||a.claimId!==s.owner.claimId||a.attempt!==s.owner.attempt)throw new Error("Conflicting execution preparation");return}s.executions[Hr(o.operationId)]={operation:o,generation:s.generation,claimId:s.owner.claimId,attempt:s.owner.attempt}})},async dispatch(i){await e.write((o,s)=>{let a=Pi(o,i.operationId);if(!a||!Jn(a.operation,i)||a.receipt||a.claimId!==o.owner?.claimId||a.attempt!==o.owner.attempt||Date.parse(i.expiresAt)<=s)throw new Error("Stale execution dispatch");a.dispatchedAt??=s})},async accept(i){let o=_t("ExecutionReceiptRequest",structuredClone(i));await e.write(s=>{let a=Pi(s,o.operationId);if(!a)throw new Error("Execution request missing");if(ed(a,o),a.receipt&&!Jn(a.receipt,o))throw new Error("Conflicting execution receipt");a.receipt=o})},async reconcile(i,o){let s=_t("ExecutionReceiptRequest",structuredClone(i.receipt));return e.write(a=>{let d=Pi(a,s.operationId);if(!d||d.receipt?.status!=="unknown"||s.status==="unknown"||i.operationDigest!==d.operation.digest||i.unknownReceiptDigest!==ut(he(d.receipt)))throw new Error("Execution reconciliation identity mismatch");ed(d,s);let c={evidenceId:i.evidenceId,unknownReceiptDigest:i.unknownReceiptDigest,authorizationRevision:o};if(Buffer.byteLength(he(c))>1024)throw new RangeError("Execution reconciliation exceeds bound");return d.reconciled?Jn(d.reconciled,s):(d.reconciled=s,d.observation=c,!0)})}};return Object.assign(n,{services:Rk(t,e)}),Object.freeze(n)}var td=262144;function Ty(t){return ut(`tansr.service.execution.v1\0${he(t)}`)}function Ay(t,e){let{digest:n,...i}=t;if(Hr(t.operationId),!Jn(t.scope,e)||!t.callId||!t.toolName||t.target.kind!=="controlled-service"||!t.target.authorizationRevision||!/^[a-f0-9]{64}$/.test(t.argumentsDigest)||n!==Ty(i)||Buffer.byteLength(he(t))>4096)throw new Error("Service execution identity mismatch")}function nd(t,e){if(e.operationId!==t.operation.operationId||e.digest!==t.operation.digest||!["completed","cancelled","unknown"].includes(e.status)||e.resultJson!==null&&typeof e.resultJson!="string"||e.status==="cancelled"&&e.resultJson!==null||e.status==="completed"&&t.dispatchedAt===void 0||e.resultDigest!==void 0&&!/^[a-f0-9]{64}$/.test(e.resultDigest)||Buffer.byteLength(Bt(e))>td)throw new Error("Service receipt identity or bound mismatch");if(e.resultJson!==null){let n=JSON.parse(e.resultJson);if(!n||!Array.isArray(n.content)||e.resultDigest!==ut(e.resultJson))throw new Error("Service result digest mismatch")}}function Zu(t,e){if(Ay(e.operation,t.scope),e.generation!==t.generation||!e.claimId||!Number.isSafeInteger(e.attempt)||e.attempt<1||e.dispatchedAt!==void 0&&(!Number.isSafeInteger(e.dispatchedAt)||e.dispatchedAt<0))throw new Error("Service execution scope mismatch");if(e.receipt&&nd(e,e.receipt),e.reconciled&&(nd(e,e.reconciled),e.reconciled.status==="unknown"||e.receipt&&e.receipt.status!=="unknown"||e.observation?.unknownReceiptDigest!==ut(he(e.receipt??null))))throw new Error("Service reconciliation identity mismatch")}function Ey(t){let e=t.reconciled??t.receipt;return!e||e.status==="unknown"}function p1(t){if(t.serviceExecutions===void 0)return{count:0,reserved:0,unsettled:!1};if(!t.serviceExecutions||typeof t.serviceExecutions!="object"||Array.isArray(t.serviceExecutions))throw new Error("Invalid service execution facts");let e=0,n=!1,i=Object.entries(t.serviceExecutions);for(let[o,s]of i){if(Zu(t,s),o!==Hr(s.operation.operationId))throw new Error("Service fact key mismatch");s.receipt||(e+=td),Ey(s)&&(e+=td+1024,n=!0)}return{count:i.length,reserved:e,unsettled:n}}function Rk(t,e){let n=(i,o)=>{let s=i.serviceExecutions?.[Hr(o)];return s&&Zu(i,s),s};return Object.freeze({version:"service-facts-v1",read:i=>e.read(o=>structuredClone(n(o,i)??null)),async prepare(i){let o=structuredClone(i);Ay(o,t),await e.write(s=>{if(!s.owner)throw new Error("Service execution ownership missing");let a=n(s,o.operationId);if(a){if(!Jn(a.operation,o)||a.claimId!==s.owner.claimId||a.attempt!==s.owner.attempt)throw new Error("Conflicting service preparation");return}s.serviceExecutions??={},s.serviceExecutions[Hr(o.operationId)]={operation:o,generation:s.generation,claimId:s.owner.claimId,attempt:s.owner.attempt}})},async dispatch(i){await e.write((o,s)=>{let a=n(o,i.operationId);if(!a||!Jn(a.operation,i)||a.receipt||a.dispatchedAt!==void 0||a.claimId!==o.owner?.claimId||a.attempt!==o.owner.attempt)throw new Error("Stale service dispatch");a.dispatchedAt=s})},async settle(i){let o=structuredClone(i);await e.write(s=>{let a=n(s,o.operationId);if(!a||a.claimId!==s.owner?.claimId||a.attempt!==s.owner.attempt)throw new Error("Stale service completion");if(nd(a,o),a.receipt&&!Jn(a.receipt,o))throw new Error("Conflicting service receipt");a.receipt=o})},async reconcile(i){let o=structuredClone(i);await e.write(s=>{let a=n(s,o.receipt.operationId);if(!a||o.receipt.status==="unknown"||a.receipt&&a.receipt.status!=="unknown"||o.unknownReceiptDigest!==ut(he(a.receipt??null))||!/^[A-Za-z0-9][A-Za-z0-9._~:-]{0,127}$/.test(o.evidenceId))throw new Error("Service observation identity mismatch");if(nd(a,o.receipt),a.reconciled&&!Jn(a.reconciled,o.receipt))throw new Error("Conflicting service reconciliation");a.reconciled=o.receipt,a.observation={evidenceId:o.evidenceId,unknownReceiptDigest:o.unknownReceiptDigest}})}})}async function ef(t,e){let{facts:n,owner:i,signal:o,activeOperationIds:s}=t,a=n.services;if(!a||!n.acceptsOwner(i))throw new Error("Transactional service facts unavailable");o.throwIfAborted();let d={operationId:xk(),callId:t.callId,toolName:t.toolName,scope:n.scope,target:structuredClone(t.target),argumentsDigest:ut(Bt(t.args))},c={...d,digest:Ty(d)};await i.write(async()=>{if(o.throwIfAborted(),await n.hasUnreconciled(n.scope,{activeOperationIds:new Set([...s,...t.otherActiveOperationIds?.()??[]])}))throw new Error("Service execution requires reconciliation");await a.prepare(c)}),s.add(c.operationId);let l=!1,f=!1,u=(m,g,h)=>{let p=g===null?null:Bt(g);return{operationId:c.operationId,digest:c.digest,status:m,resultJson:p,...p===null?{}:{resultDigest:ut(p)},...h===void 0?{}:{reason:h}}};try{await t.beforeDispatch?.(),o.throwIfAborted(),await i.write(async()=>{o.throwIfAborted(),await a.dispatch(c)}),o.throwIfAborted(),i.assertCurrent(),l=!0;let m=await e(),g=u(m?.isError===!0?"unknown":"completed",m);if(Buffer.byteLength(Bt(g))>td&&(g.status="unknown",g.resultJson=null,g.reason="result_too_large"),f=!0,await i.write(()=>a.settle(g)),g.reason==="result_too_large")throw new RangeError("Service result exceeds durable receipt bound");return o.throwIfAborted(),m}catch(m){throw f||await i.write(()=>a.settle(u(l?"unknown":"cancelled",null,o.aborted?"aborted":"execution_error"))),m}finally{s.delete(c.operationId)}}import{createHash as Bk,randomUUID as Dk}from"node:crypto";import{createHash as Ik,randomUUID as Tk}from"node:crypto";import{realpathSync as Ak}from"node:fs";import Ct from"node:path";import Ek from"node:os";var Py=9223372036854775807n,cr=4*1024*1024,Cy=1024*1024,_y=256,Sn=r.string().regex(/^(0|[1-9][0-9]{0,18})$/).refine(t=>BigInt(t)<=Py),nf=t=>r.string().refine(e=>[...e].length<=t),qt=nf(256).refine(t=>t.length>0&&!/[\u0000-\u001f\u007f]/.test(t)),rf=r.object({kind:r.enum(["server-managed","client-managed","developer-managed"]),domain:qt,sourceId:qt,sourceGeneration:Sn,applicationScopeId:qt,endUserId:nf(512).refine(t=>t.length>0)}).strict(),My=new WeakMap;function of(t){return My.get(t)}var Ck=r.discriminatedUnion("kind",[r.object({kind:r.literal("pin"),text:nf(4096).refine(t=>t.length>0)}).strict(),r.object({kind:r.literal("remember")}).strict(),r.object({kind:r.literal("forget"),topic:qt}).strict()]),_k=r.object({requestId:qt,operationId:qt,sourceId:qt,sourceGeneration:Sn,expectedRevision:Sn,command:Ck}).strict(),Pk=r.object({requestId:qt,operationId:qt,sourceId:qt,sourceGeneration:Sn,expectedRevision:Sn,status:r.enum(["pending","unknown","committed","failed"]),publishedRevision:Sn.optional(),errorCode:r.enum(["operation_failed","commit_unknown"]).optional(),executionComplete:r.boolean(),durable:r.boolean(),consumed:r.boolean()}).strict(),Mk=r.object({text:r.string(),sha256:r.string().regex(/^[a-f0-9]{64}$/),modifiedAt:r.number().int().nonnegative(),provenance:r.array(qt).max(256),deletionGeneration:Sn}).strict(),Oy=r.object({turn:r.number().int().optional(),text:r.string().max(32768),queuedAt:qt,owner:qt.optional()}).strict(),tf=r.object({version:r.literal(1),identity:rf,epoch:Sn,revision:Sn,deletionGeneration:Sn,files:r.record(Mk),indexValid:r.boolean(),invites:r.array(Oy).max(256),consolidation:r.string().nullable(),tombstones:r.record(Sn),receipts:r.record(r.object({digest:r.string(),receipt:Pk}).strict()),activeOperation:qt.nullable(),lease:r.object({owner:qt,fence:Sn}).strict().nullable(),fence:Sn}).strict(),at=class extends Error{constructor(n){super(n);this.code=n;this.name="MemoryManagementError"}code};function Ae(t){throw new at(t)}var Yn=t=>Ik("sha256").update(t).digest("hex"),en=t=>structuredClone(t),dr=t=>(BigInt(t)>=Py&&Ae("capacity_exceeded"),(BigInt(t)+1n).toString()),pn=t=>Yn(t),vi=(t,e)=>Bt(t)===Bt(e);function Ok(){let t=Ek.tmpdir();try{return Ak.native(t)}catch{return t}}function lr(t){return Yn(Bt({...rf.parse(t),sourceGeneration:void 0}))}async function w1(t){(!Ct.isAbsolute(t)||t===":memory:")&&Ae("invalid_request");let{DatabaseSync:e}=await import("node:sqlite"),n=new e(t);try{n.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS memory_publication (domain_key TEXT PRIMARY KEY, etag TEXT NOT NULL, body TEXT NOT NULL) STRICT;")}catch(s){throw n.close(),s}let i=n.prepare("SELECT etag,body FROM memory_publication WHERE domain_key=?"),o=!1;return{atomicDurablePublication:!0,async read(s){o&&Ae("source_unavailable");let a=i.get(s);return a!==void 0&&Yn(a.body)!==a.etag&&Ae("integrity_mismatch"),a===void 0?null:{...a}},async compareAndSwap(s,a,d){o&&Ae("source_unavailable"),Buffer.byteLength(d)>cr&&Ae("capacity_exceeded"),n.exec("BEGIN IMMEDIATE");try{(i.get(s)?.etag??null)!==a&&Ae("revision_conflict"),n.prepare("INSERT INTO memory_publication(domain_key,etag,body) VALUES(?,?,?) ON CONFLICT(domain_key) DO UPDATE SET etag=excluded.etag,body=excluded.body").run(s,Yn(d),d),n.exec("COMMIT")}catch(c){try{n.exec("ROLLBACK")}catch{}throw c}},close(){o||(n.close(),o=!0)}}}function k1(t,e){return(e.atomicDurablePublication!==!0||t.capabilities.consistency!=="strong"||!t.capabilities.conditionalPut||t.capabilities.maxObjectBytes<cr)&&Ae("unsupported_capability"),{atomicDurablePublication:!0,async read(n){let i=`memory/${n}/manifest.json`,o=await t.head(i);if(o===null)return null;(!o.etag||o.bytes>cr)&&Ae("integrity_mismatch");let s=(await t.get(i)).getReader(),a=[],d=0;try{for(;;){let f=await s.read();if(f.done)break;d+=f.value.byteLength,d>cr&&Ae("capacity_exceeded"),a.push(f.value)}}finally{await s.cancel().catch(()=>{}),s.releaseLock()}let c=Buffer.concat(a);return(await t.head(i))?.etag!==o.etag&&Ae("revision_conflict"),(c.length!==o.bytes||Yn(c)!==o.sha256)&&Ae("integrity_mismatch"),{etag:o.etag,body:c.toString("utf8")}},async compareAndSwap(n,i,o){let s=Buffer.from(o);s.length>cr&&Ae("capacity_exceeded");try{await t.put(`memory/${n}/manifest.json`,new ReadableStream({start(a){a.enqueue(s),a.close()}}),{bytes:s.length,contentType:"application/json",sha256:Yn(s)},i===null?{ifNoneMatch:"*"}:{ifMatch:i})}catch(a){throw a?.kind==="precondition_failed"&&Ae("revision_conflict"),a}}}}var id=class t{identity;#e;#n;#r="0";#s=new WeakMap;#t=new WeakMap;constructor(e){this.#e=e,this.identity=Object.freeze(rf.parse(e.identity)),this.#n=lr(this.identity)}static async open(e){e.store.atomicDurablePublication!==!0&&Ae("unsupported_capability");let n=new t(e);n.assertCurrent();let i=await e.store.read(n.#n);if(n.assertCurrent(),i===null){e.mode!=="create"&&Ae("source_unavailable");let o={version:1,identity:en(n.identity),epoch:"0",revision:"0",deletionGeneration:"0",files:{},indexValid:!1,invites:[],consolidation:null,tombstones:{},receipts:{},activeOperation:null,lease:null,fence:"0"};n.#o(o.deletionGeneration),await e.store.compareAndSwap(n.#n,null,Bt(o))}else e.mode==="create"&&Ae("revision_conflict");return await n.#i(),n}assertCurrent(){this.#e.assertCurrent()}#o(e){let n=this.#e.minimumDeletionGeneration?.();BigInt(e)<BigInt(this.#r)&&Ae("stale_generation"),n!==void 0&&BigInt(e)<BigInt(Sn.parse(n))&&Ae("stale_generation")}async#i(){this.assertCurrent();let e=await this.#e.store.read(this.#n);this.assertCurrent(),e===null&&Ae("source_unavailable"),Buffer.byteLength(e.body)>cr&&Ae("capacity_exceeded");let n;try{n=tf.parse(JSON.parse(e.body))}catch{return Ae("integrity_mismatch")}vi(n.identity,this.identity)||Ae("stale_generation"),this.#o(n.deletionGeneration);for(let i of Object.values(n.files))(Yn(i.text)!==i.sha256||Buffer.byteLength(i.text)>Cy)&&Ae("integrity_mismatch");return(Object.keys(n.files).length>256||Object.keys(n.receipts).length>_y||Object.keys(n.tombstones).length>512)&&Ae("capacity_exceeded"),this.#r=n.deletionGeneration,{state:n,etag:e.etag}}async#a(e,n){this.assertCurrent(),n.epoch=dr(e.state.epoch),this.#o(n.deletionGeneration),tf.parse(n);let i=Bt(n);Buffer.byteLength(i)>cr&&Ae("capacity_exceeded"),await this.#e.store.compareAndSwap(this.#n,e.etag,i),this.assertCurrent(),this.#o(n.deletionGeneration),this.#r=n.deletionGeneration}async read(){let{state:e}=await this.#i();return{identity:this.identity,revision:e.revision,deletionGeneration:e.deletionGeneration,available:!0}}async status(e,n){qt.parse(e),n!==void 0&&qt.parse(n);let{state:i}=await this.#i(),o=i.receipts[pn(e)];return o?(n!==void 0&&o.receipt.requestId!==n&&Ae("request_conflict"),en(o.receipt)):null}async consume(e){let n=await this.#i(),i=en(n.state),o=i.receipts[pn(e)];return(!o||o.receipt.status!=="committed")&&Ae("invalid_request"),(i.activeOperation!==null||i.lease!==null)&&Ae("busy"),o.receipt.consumed||(o.receipt.consumed=!0,await this.#a(n,i)),en(o.receipt)}async prepareReconciliation(e,n){qt.parse(e),qt.parse(n);let i=await this.#i(),o=i.state.receipts[pn(e)];if(!o||(o.receipt.requestId!==n&&Ae("request_conflict"),!["pending","unknown"].includes(o.receipt.status)))return null;i.state.activeOperation!==e&&Ae("integrity_mismatch");let s=Object.freeze({operationId:e,requestId:n,publicationEpoch:i.state.epoch,fence:i.state.fence});return this.#s.set(s,i),s}async reconcileFailed(e,n={}){let i=this.#s.get(e);i||Ae("forbidden"),n.signal?.throwIfAborted(),await n.beforeCommit?.(),n.signal?.throwIfAborted();let o=await this.#i(),s=o.state.receipts[pn(e.operationId)];(o.etag!==i.etag||o.state.epoch!==e.publicationEpoch||o.state.fence!==e.fence||o.state.activeOperation!==e.operationId||s?.receipt.requestId!==e.requestId)&&Ae("stale_generation");let a=en(o.state),d=a.receipts[pn(e.operationId)].receipt;a.fence=dr(a.fence),a.activeOperation=null,a.lease=null,d.status="failed",d.errorCode="operation_failed",d.durable=!1;try{return await this.#a(o,a),this.#s.delete(e),en(d)}catch(c){if(c instanceof at&&c.code==="revision_conflict")throw c;let l=await this.status(e.operationId,e.requestId).catch(()=>null);return l?.status==="failed"?l:{...d,status:"unknown",errorCode:"commit_unknown"}}}async prepareLeaseReconciliation(){let e=await this.#i();if(e.state.activeOperation!==null&&Ae("busy"),e.state.lease===null)return null;let n=Object.freeze({...e.state.lease,publicationEpoch:e.state.epoch});return this.#t.set(n,e),n}async reconcileLease(e,n={}){let i=this.#t.get(e);i||Ae("forbidden"),n.signal?.throwIfAborted(),await n.beforeCommit?.(),n.signal?.throwIfAborted();let o=await this.#i();(o.etag!==i.etag||o.state.epoch!==e.publicationEpoch||o.state.activeOperation!==null||!vi(o.state.lease,{owner:e.owner,fence:e.fence}))&&Ae("stale_generation");let s=en(o.state);s.fence=dr(s.fence),s.lease=null;try{await this.#a(o,s),this.#t.delete(e)}catch(a){if(a instanceof at&&a.code==="revision_conflict")throw a;Ae("commit_unknown")}}async createHost(e={}){return this.#d(e)}async execute(e,n,i={},o={}){let s=_k.parse(e);(s.sourceId!==this.identity.sourceId||s.sourceGeneration!==this.identity.sourceGeneration)&&Ae("stale_generation");let a=async()=>{o.signal?.throwIfAborted(),await o.beforeCommit?.(),o.signal?.throwIfAborted(),this.assertCurrent()};await a();let d=await this.#i(),c=en(d.state),l=Yn(Bt(s)),f=c.receipts[pn(s.operationId)];if(f)return f.digest!==l&&Ae("request_conflict"),en(f.receipt);Object.values(c.receipts).some(v=>v.receipt.requestId===s.requestId)&&Ae("request_conflict"),c.revision!==s.expectedRevision&&Ae("revision_conflict"),(c.activeOperation!==null||c.lease!==null)&&Ae("busy"),Object.keys(c.receipts).length>=_y&&Ae("capacity_exceeded");let u={requestId:s.requestId,operationId:s.operationId,sourceId:s.sourceId,sourceGeneration:s.sourceGeneration,expectedRevision:s.expectedRevision,status:"pending",executionComplete:!1,durable:!1,consumed:!1};c.receipts[pn(s.operationId)]={digest:l,receipt:u},c.activeOperation=s.operationId;try{await this.#a(d,c)}catch(v){if(v instanceof at&&v.code==="revision_conflict")throw v;return{...u,status:"unknown",errorCode:"commit_unknown"}}let m;try{m=await this.#i()}catch{return{...u,status:"unknown",errorCode:"commit_unknown"}}let g=m.state.receipts[pn(s.operationId)];if((!g||g.digest!==l)&&Ae("integrity_mismatch"),g.receipt.status==="committed"||g.receipt.status==="failed")return en(g.receipt);(m.state.activeOperation!==s.operationId||m.state.fence!==c.fence)&&Ae("stale_generation");let h=en(m.state),p=!0;try{o.signal?.throwIfAborted();let v=await this.#d({...i,provenance:()=>{let R=i.provenance?.();return{deletionGeneration:R?.deletionGeneration??h.deletionGeneration,origins:[...R?.origins??[],"operation:"+pn(s.operationId)]}}},{state:h,assertActive:()=>{p||Ae("stale_generation"),o.signal?.throwIfAborted()},verifyCurrent:async()=>{let R=await this.#i();(R.etag!==m.etag||R.state.activeOperation!==s.operationId)&&Ae("stale_generation")}});await n(v),v.assertCurrent(),s.command.kind==="forget"&&this.#c(h,v,s.command.topic),h.revision=dr(h.revision),h.activeOperation=null,h.lease=null;let b=h.receipts[pn(s.operationId)].receipt;b.status="committed",b.executionComplete=!0,b.durable=!0,b.publishedRevision=h.revision,await a();try{return await this.#a(m,h),en(b)}catch{let R=await this.status(s.operationId,s.requestId).catch(()=>null);return R?.status==="committed"||R?.status==="failed"?R:{...u,status:"unknown",executionComplete:!0,errorCode:"commit_unknown"}}}catch{let v=en(m.state),b=v.receipts[pn(s.operationId)].receipt;b.status="failed",b.executionComplete=!0,b.errorCode="operation_failed",v.activeOperation=null;try{return await this.#a(m,v),en(b)}catch{let R=await this.status(s.operationId,s.requestId).catch(()=>null);return R?.status==="committed"||R?.status==="failed"?R:{...u,status:"unknown",errorCode:"commit_unknown"}}}finally{p=!1}}#c(e,n,i){(!/^[^/\\\u0000]+\.md$/i.test(i)||["memory.md","pending-anchors.md"].includes(i.toLowerCase()))&&Ae("invalid_request");let o=Ct.relative(n.rootDir,Ct.join(n.memoryDir,i)).split(Ct.sep).join("/"),s=process.platform==="win32"?o.toLowerCase():o,a=Ct.relative(n.rootDir,Ct.join(n.memoryDir,"MEMORY.md")).split(Ct.sep).join("/"),d=process.platform==="win32"?a.toLowerCase():a,c=Ct.relative(n.rootDir,Ct.join(n.memoryDir,"pending-anchors.md")).split(Ct.sep).join("/"),l=process.platform==="win32"?c.toLowerCase():c,f=new Set([s,d]),u=!0;for(;u;){u=!1;for(let[m,g]of Object.entries(e.files))!f.has(m)&&g.provenance.some(h=>f.has(h))&&(f.add(m),u=!0)}e.deletionGeneration=dr(e.deletionGeneration);for(let m of f)delete e.files[m],m!==d&&m!==l&&(e.tombstones[pn(m)]=e.deletionGeneration);e.indexValid=!1,e.invites=[],e.consolidation=null,Object.keys(e.tombstones).length>512&&Ae("capacity_exceeded")}async#d(e,n){let i=e.rootDir??Ct.join(Ok(),"tansr-memory-world",this.#n),o=e.memoryDir??Ct.join(i,"memory");(!Ct.isAbsolute(i)||!Ct.isAbsolute(o)||Ct.resolve(i)!==i||Ct.resolve(o)!==o||!o.startsWith(i+Ct.sep))&&Ae("invalid_request");let s=n?.state??(await this.#i()).state,a=s.deletionGeneration,d=en(s.invites),c=null,l=new Set,f=()=>{this.assertCurrent(),this.#o(a),n?.assertActive()},u=k=>{f(),(!Ct.isAbsolute(k)||/\u0000/.test(k))&&Ae("forbidden");let A=Ct.relative(i,Ct.resolve(k));(A.startsWith("..")||Ct.isAbsolute(A))&&Ae("forbidden");let C=A.split(Ct.sep).join("/"),F=process.platform==="win32"?C.toLowerCase():C;return[C,F].some(H=>H.split("/").some(Q=>Object.hasOwn(Object.prototype,Q)))&&Ae("forbidden"),F},m=u(o),g=u(Ct.join(o,"MEMORY.md")),h=m+"/pending-anchors.md",p=k=>{let A=u(k),C=A.slice(m.length+1);return(A===""||A===m)&&Ae("forbidden"),qt.parse(A),A.startsWith(m+"/")&&Np.includes(C.toLowerCase())&&Ae("forbidden"),A},v=async()=>{f(),await n?.verifyCurrent();let k=n?.state??(await this.#i()).state;return k.deletionGeneration!==a&&Ae("stale_generation"),!n&&k.activeOperation!==null&&Ae("busy"),c!==null&&!vi(k.lease,c)&&Ae("stale_generation"),k.lease!==null&&(!c||!vi(k.lease,c))&&Ae("busy"),k},b=async(k,A=!1)=>{if(f(),n){await v();let Q=k(n.state);return tf.parse(n.state),Q}let C=await this.#i();C.state.deletionGeneration!==a&&Ae("stale_generation"),c!==null&&!vi(C.state.lease,c)&&Ae("stale_generation"),(C.state.activeOperation!==null||C.state.lease!==null&&(!c||!vi(C.state.lease,c)))&&Ae("busy");let F=en(C.state),H=k(F);return A&&(F.revision=dr(F.revision)),await this.#a(C,F),H},R=async k=>{let A=p(k),C=await v();if(A===g&&!C.indexValid)throw Object.assign(new Error("Memory index unavailable"),{code:"ENOENT"});let F=C.files[A];if(!F)throw Object.assign(new Error("Memory file absent"),{code:"ENOENT"});return l.add(A),F.provenance.forEach(H=>l.add(H)),Buffer.from(F.text)},w=async(k,A,C)=>{let F=p(k);(A.length>Cy||!A.equals(Buffer.from(A.toString("utf8"))))&&Ae("invalid_request");let H=e.provenance?.();(!H||H.deletionGeneration!==a||H.origins.length===0)&&Ae("stale_generation");let Q=[...new Set([...H.origins,...l])];Q.forEach(re=>qt.parse(re)),await b(re=>{Object.keys(re.files).some(I=>I!==F&&(I.startsWith(F+"/")||F.startsWith(I+"/")))&&Ae("invalid_request"),C!==void 0&&(re.files[F]?.sha256??null)!==C&&Ae("revision_conflict"),(re.tombstones[pn(F)]||Q.some(I=>re.tombstones[pn(I)]!==void 0))&&Ae("stale_generation");let O={text:A.toString("utf8"),sha256:Yn(A),modifiedAt:Date.now(),provenance:Q,deletionGeneration:a};re.files[F]=O,re.indexValid=F===g,F!==g&&delete re.files[g],Object.keys(re.files).length>256&&Ae("capacity_exceeded")},!0)},x=async k=>{let A=u(k),C=await v(),F=A===""||A===m||Object.keys(C.files).some(Q=>Q.startsWith(A+"/")),H=C.files[A];if(!F&&(!H||A===g&&!C.indexValid))throw Object.assign(new Error("Memory file absent"),{code:"ENOENT"});return{size:F?0:Buffer.byteLength(H.text),mtimeMs:H?.modifiedAt??0,isFile:()=>!F,isDirectory:()=>F,isSymbolicLink:()=>!1}},T={stat:x,lstat:x,realpath:async k=>(await x(k),Ct.resolve(k)),readFile:R,readFilePrefix:async(k,A)=>(await R(k)).subarray(0,A),readFileRange:async(k,A,C)=>(await R(k)).subarray(A,A+C),writeFile:(k,A)=>w(k,A),compareAndWrite:(k,A,C)=>w(k,C,A),appendFile:async(k,A)=>{let C=null,F=await R(k).then(H=>(C=Yn(H),H)).catch(H=>{if(H.code==="ENOENT")return Buffer.alloc(0);throw H});await w(k,Buffer.concat([F,A]),C)},mkdir:async k=>{u(k),await v()},readdir:async k=>{let A=u(k),C=await v(),F=A?A+"/":"",H=new Map;A===""&&H.set(m.split("/")[0],!0);for(let Q of Object.keys(C.files))if(Q.startsWith(F)&&!(Q===g&&!C.indexValid)){let re=Q.slice(F.length),O=re.split("/")[0];H.set(O,re.includes("/"))}return[...H].map(([Q,re])=>({name:Q,isFile:()=>!re,isDirectory:()=>re,isSymbolicLink:()=>!1}))}},M=async()=>{if(c)return null;let k;try{await b(C=>{C.lease!==null&&Ae("busy"),C.fence=dr(C.fence),k={owner:Tk(),fence:C.fence},C.lease=k})}catch(C){if(C instanceof at&&["busy","revision_conflict"].includes(C.code))return null;throw C}c=k;let A=!1;return{release:async()=>{A||(await b(C=>{vi(C.lease,c)||Ae("stale_generation"),C.lease=null}),c=null,A=!0)}}},W=k=>Nm(k.files[h]?.text??""),$=(k,A,C=[])=>{if(!A.length){delete k.files[h];return}let F=Um(A),H=[...new Set([...k.files[h]?.provenance??[],...C])];H.forEach(Q=>qt.parse(Q)),k.files[h]={text:F,sha256:Yn(F),modifiedAt:Date.now(),provenance:H,deletionGeneration:a}},D={acquireLock:M,pendingInvitesLocation:`memory:${this.identity.sourceId}:pending-invites`,readInitialPendingInvites:()=>(f(),en(d)),persistPendingInvites:async(k,A)=>{await b(C=>{let F=A.map(Q=>Oy.parse({...Q,owner:k})),H=new Set(F.map(Q=>Q.queuedAt+"\0"+Q.text));C.invites=[...C.invites.filter(Q=>Q.owner!==k&&!H.has(Q.queuedAt+"\0"+Q.text)),...F],C.invites.length>256&&Ae("capacity_exceeded")})},readIndexSnapshot:async k=>{let A=await v();if(!A.indexValid||!A.files[g])return null;let C=A.files[g];if(!(Buffer.byteLength(C.text)>k))return l.add(g),C.provenance.forEach(F=>l.add(F)),C.text}},J={acquireLock:M,readConsolidationMeta:async()=>{let k=(await v()).consolidation;return k===null?null:ol(k)},writeConsolidationMeta:async k=>{ol(JSON.stringify(k))||Ae("invalid_request"),await b(A=>{A.consolidation=JSON.stringify(k)})},readPendingAnchors:async()=>{let k=await v(),A=W(k);return A.length&&(l.add(h),k.files[h]?.provenance.forEach(C=>l.add(C))),A.length===0?null:{content:A.map(C=>`- [${C.date}] ${C.text}`).join(`
|
|
20
|
+
`),keys:new Set(A.map(C=>sl(C.text)))}},clearPendingAnchors:async k=>{await b(A=>{$(A,W(A).filter(C=>!k.has(sl(C.text))))},!0)}},S={authority:this,rootDir:i,memoryDir:o,fs:T,source:{fs:T,pathStyle:process.platform==="win32"?"win32":"posix"},extractionHost:D,consolidationHost:J,provenance:e.provenance,assertCurrent:f,refresh:async()=>{f(),await n?.verifyCurrent();let k=n?.state??(await this.#i()).state;(k.activeOperation!==null&&!n||k.lease!==null&&(!c||!vi(k.lease,c)))&&Ae("busy"),c!==null&&!vi(k.lease,c)&&Ae("stale_generation"),a!==k.deletionGeneration&&Ae("stale_generation"),d=en(k.invites)},appendPendingAnchors:async k=>b(A=>{let C=e.provenance?.();C!==void 0&&C.deletionGeneration!==a&&Ae("stale_generation");let F=[...new Set([...C?.origins??[],...l])];F.some(Q=>A.tombstones[pn(Q)]!==void 0)&&Ae("stale_generation");let H=Fm(W(A),k,new Date().toISOString().slice(0,10));return $(A,H.entries,F),H.added},!0)};return My.set(S,a),S}};var By=4*1024*1024,rd=12288,od=t=>Bk("sha256").update(t).digest("hex"),It=t=>{throw new at(t)};function Dy(t){let e=lr(t.identity),n={contract:"terminal-services-v1",sourceId:t.identity.sourceId,sourceGeneration:t.identity.sourceGeneration,domainKey:e},i=u=>{t.signal.throwIfAborted(),t.assertCurrent(),u!==e&&It("forbidden")};async function o(u){i(u.domainKey);let m=yt("MemoryPublicationRequest",u),g=yt("MemoryPublicationResponse",await t.invoke(m,t.signal));return i(u.domainKey),(g.action!==u.action||g.sourceId!==n.sourceId||g.sourceGeneration!==n.sourceGeneration||g.domainKey!==n.domainKey)&&It("integrity_mismatch"),g}async function s(){let u=await o({...n,action:"head"});return u.action!=="head"?It("integrity_mismatch"):(u.publication!==null&&(u.publication.byteLength<1||u.publication.byteLength>By)&&It("capacity_exceeded"),u.publication)}let a=(u,m,g)=>{if(!("transfer"in u)||u.transfer.transferId!==m)return It("integrity_mismatch");let h=u.transfer;return h.receivedBytes!==null&&(h.receivedBytes<0||h.receivedBytes>g)&&It("integrity_mismatch"),h.status==="conflict"&&It("revision_conflict"),h.status==="unknown"&&It("commit_unknown"),h.status==="committed"&&(h.receivedBytes!==g||h.etag===null)&&It("integrity_mismatch"),h},d=new Map,c=u=>JSON.stringify([u.expectedEtag,u.sha256]),l=u=>{yt("MemoryPublicationRequest",{...n,action:"begin",...u});let m=c(u),g=d.get(m);g&&(g.transferId!==u.transferId||g.expectedEtag!==u.expectedEtag||g.byteLength!==u.byteLength||g.sha256!==u.sha256)&&It("request_conflict"),!g&&d.size>=128&&It("capacity_exceeded"),d.set(m,{...u})};async function f(u){i(u);let m=await s();if(m===null)return null;let g=[],h=0;for(;h<m.byteLength;){let R=Math.min(rd,m.byteLength-h),w=await o({...n,action:"read",etag:m.etag,offset:h,length:R});if(w.action!=="read")return It("integrity_mismatch");let x=Buffer.from(w.base64,"base64");(w.etag!==m.etag||w.offset!==h||x.toString("base64")!==w.base64||x.length!==w.byteLength||x.length!==R||od(x)!==w.payloadDigest||w.nextOffset!==h+x.length||w.complete!==(h+x.length===m.byteLength))&&It("integrity_mismatch"),g.push(x),h+=x.length}let p=await s();if(p===null||p.etag!==m.etag)return It("revision_conflict");(p.byteLength!==m.byteLength||p.sha256!==m.sha256)&&It("integrity_mismatch");let v=Buffer.concat(g);(v.length!==m.byteLength||od(v)!==m.sha256)&&It("integrity_mismatch");let b;try{b=new TextDecoder("utf-8",{fatal:!0}).decode(v)}catch{return It("integrity_mismatch")}return{etag:m.etag,body:b}}return{atomicDurablePublication:!0,pendingTransfers:()=>[...d.values()].map(u=>({...u})),restorePendingTransfer:l,async read(u){for(let m=0;m<3;m++)try{return await f(u)}catch(g){if(!(g instanceof at)||g.code!=="revision_conflict"||m===2)throw g}return It("revision_conflict")},async compareAndSwap(u,m,g){i(u);let h=Buffer.from(g);(h.length<1||h.length>By)&&It("capacity_exceeded");let p=od(h),v=c({expectedEtag:m,sha256:p}),b=d.get(v),R=b??{transferId:Dk(),expectedEtag:m,byteLength:h.length,sha256:p};R.byteLength!==h.length&&It("integrity_mismatch"),l(R);let{transferId:w}=R,x=T=>{let M=a(T,w,h.length);return M.status==="committed"&&(M.etag!==p&&It("integrity_mismatch"),d.delete(v)),M};try{let T=x(await o(b?{...n,action:"query",transferId:w}:{...n,action:"begin",...R}));if(T.status==="committed")return;if(T.receivedBytes===null||T.receivedBytes!==h.length&&T.receivedBytes%rd!==0)return It("integrity_mismatch");for(let W=T.receivedBytes;W<h.length;W+=rd){let $=h.subarray(W,Math.min(W+rd,h.length)),D=x(await o({...n,action:"chunk",transferId:w,offset:W,base64:$.toString("base64"),byteLength:$.length,payloadDigest:od($)}));(D.status!=="staging"||D.receivedBytes!==W+$.length)&&It("integrity_mismatch")}x(await o({...n,action:"commit",transferId:w})).status!=="committed"&&It("commit_unknown")}catch(T){if(T instanceof at&&T.code==="revision_conflict")throw d.delete(v),T;if(T instanceof at&&T.code==="integrity_mismatch")throw T;try{if(x(await o({...n,action:"query",transferId:w})).status==="committed")return}catch(M){if(M instanceof at&&(M.code==="revision_conflict"||M.code==="integrity_mismatch"))throw M}return It("commit_unknown")}}}}import{createHash as jy}from"node:crypto";var qy=t=>jy("sha256").update(t).digest("hex"),sf=(t,e)=>he(t)===he(e),bi=()=>{throw new at("integrity_mismatch")};function af(t,e){if(t.length>8192)throw new at("capacity_exceeded");let n=lr(e.identity),i=new Map;for(let s of t){let a=_t("ExecutionOperation",s.operation);if(a.toolName!=="MemoryPublication")continue;let d=e.allowPriorAuthority?.(a)===!0;if(!d&&s.receipt!==null&&s.receipt.status!=="unknown"&&(!sf(a.binding,e.binding)||a.scope.authorizationRevision!==e.authorizationRevision))continue;let{digest:c,...l}=a;if((qy("tansr.sdk2.execution.v1\0"+he(l))!==c||a.sessionId!==e.sessionId||a.scope.applicationScopeId!==e.identity.applicationScopeId||a.scope.endUserId!==e.identity.endUserId||!d&&(a.scope.authorizationRevision!==e.authorizationRevision||!sf(a.binding,e.binding))||a.request.operation!=="tool.invoke"||a.request.args.name!==oi||a.request.args.definitionDigest!==Ei)&&bi(),a.request.operation!=="tool.invoke")return bi();let f=yt("MemoryPublicationRequest",JSON.parse(a.request.args.argsJson));if((f.sourceId!==e.identity.sourceId||f.sourceGeneration!==e.identity.sourceGeneration||f.domainKey!==n)&&bi(),!["begin","chunk","commit"].includes(f.action)||!("transferId"in f))continue;s.receipt!==null&&(s.receipt.operationId!==a.operationId||s.receipt.digest!==a.digest||s.receipt.executorId!==a.binding.target.executorId||s.receipt.connectionId!==a.binding.target.connectionId)&&bi();let u=i.get(f.transferId);if(u===void 0&&(u={chunks:new Map,commits:!1,unresolved:[]},i.set(f.transferId,u)),(s.receipt===null||s.receipt.status==="unknown")&&u.unresolved.push(a.operationId),f.action==="begin")u.begin&&!sf(u.begin,f)&&bi(),u.begin=f;else if(f.action==="chunk"){let m=Buffer.from(f.base64,"base64"),g=u.chunks.get(f.offset);(m.toString("base64")!==f.base64||m.length!==f.byteLength||qy(m)!==f.payloadDigest||g!==void 0&&!Buffer.from(g).equals(m))&&bi(),u.chunks.set(f.offset,m)}else f.action==="commit"&&(u.commits=!0)}let o=[];for(let[s,a]of i){if(a.unresolved.length===0)continue;let d=a.begin??bi(),c=[...a.chunks].sort(([u],[m])=>u-m),l=jy("sha256"),f=0;for(let[u,m]of c)(u!==f||f+m.length>d.byteLength)&&bi(),f+=m.length,l.update(m);a.commits&&(f!==d.byteLength||l.digest("hex")!==d.sha256)&&bi(),o.push({transfer:{transferId:s,expectedEtag:d.expectedEtag,byteLength:d.byteLength,sha256:d.sha256},unresolvedOperationIds:a.unresolved})}return o}var qk=pl.shape.platform.strict();function sd(t){return qk.parse(t),{imageGen:t.imageGen,videoGen:t.videoGen,webSearch:t.webSearch,speechToText:t.speechToText,textToSpeech:t.textToSpeech}}var Oi="sdk2-ext-v1",jk=16,Nk=1e4,Uk={Read:["fs.inspect","fs.read"],Write:["fs.inspect","fs.read","fs.mkdir","fs.write"],Edit:["fs.inspect","fs.read","fs.write"],List:["fs.inspect","fs.list"],Shell:["fs.inspect","process.exec"],Glob:["fs.inspect","fs.list"],Grep:["fs.inspect","fs.list","fs.read"]},Ny={Read:"read",Write:"write",Edit:"edit",List:"list",Glob:"glob",Grep:"grep",Shell:"shell",TodoWrite:"todoWrite",AskUser:"askUser",WebFetch:"webFetch",WebSearch:"webSearch",Http:"http",Task:"agent",SpawnAgent:"agent",AgentFollowup:"agent"},Uy={ImageGen:"imageGen",VideoGen:"videoGen",SpeechToText:"speechToText",TextToSpeech:"textToSpeech"},Ve=class extends Error{constructor(n,i=Na(n)[0]){super(n);this.code=n;this.status=i}code;status};function V(t,e){throw new Ve(t,e)}function mt(t,e){return he(t)===he(e)}function Nn(t){let e=JSON.parse(he(t)),n=i=>{if(i!==null&&typeof i=="object"){for(let o of Object.values(i))n(o);Object.freeze(i)}};return n(e),e}function ur(t){return(t.startsWith("/")||/[\\:\u0000-\u001f\u007f]/.test(t)||t.split("/").some(e=>e==="."||e===".."))&&V("invalid_request",400),t}function Lk(t){return zr("sha256").update("tansr.sdk2.client-tool.v1\0").update(Bt(Co.parse(t))).digest("hex")}function fr(t){Buffer.byteLength(t)>32768&&V("payload_too_large");let e;try{e=JSON.parse(t)}catch{V("invalid_request")}let n=(i,o)=>{if((o>32||typeof i=="number"&&!Number.isFinite(i))&&V("invalid_request"),i!==null&&typeof i=="object")for(let s of Object.values(i))n(s,o+1)};return n(e,0),(e===null||typeof e!="object"||Array.isArray(e))&&V("invalid_request"),e}function ad(t){let e=Cr.safeParse(fr(t));return e.success||V("invalid_request"),e.data}function dd(t,e,n){if(t.operation!==e.operation&&V("invalid_request",400),e.operation==="tool.invoke"){let i=ad(e.args.resultJson);if(or(t)){(!n||n.toolName!=="Shell")&&V("invalid_request");let o,s;try{o=Br(t),s=Ua(o,e)}catch{V("invalid_request")}o.action==="exec"&&s.action==="exec"&&s.result!==null?dd({operation:"process.exec",args:{command:o.command,cwd:o.cwd,timeoutMs:o.timeoutMs,maxOutputBytes:o.maxOutputBytes,interpreter:o.interpreter}},{operation:"process.exec",args:s.result},n):o.action==="background"&&s.action==="background"&&s.result!==null&&dd({operation:"tool.invoke",args:{name:Ai,definitionDigest:Dr,argsJson:JSON.stringify(o.request)}},{operation:"tool.invoke",args:{resultJson:JSON.stringify({status:"ok",content:[{t:"text",text:JSON.stringify(s.result)}]})}},n)}if(t.operation==="tool.invoke"&&t.args.name===oi&&t.args.definitionDigest===Ei&&((!n||n.toolName!=="MemoryPublication")&&V("invalid_request"),i.status==="ok")){(i.isError||i.content.length!==1||i.content[0]?.t!=="text")&&V("invalid_request");let o,s;try{o=yt("MemoryPublicationRequest",fr(t.args.argsJson)),s=yt("MemoryPublicationResponse",JSON.parse(i.content[0].text))}catch{V("invalid_request")}if((o.action!==s.action||o.sourceId!==s.sourceId||o.sourceGeneration!==s.sourceGeneration||o.domainKey!==s.domainKey||"transferId"in o&&(!("transfer"in s)||o.transferId!==s.transfer.transferId))&&V("binding_conflict"),o.action==="read"&&s.action==="read"){let a=Buffer.from(s.base64,"base64");(s.etag!==o.etag||s.offset!==o.offset||a.toString("base64")!==s.base64||a.length!==s.byteLength||a.length>o.length||s.nextOffset!==o.offset+a.length||zr("sha256").update(a).digest("hex")!==s.payloadDigest)&&V("invalid_request")}}if(t.operation==="tool.invoke"&&t.args.name===Ai&&t.args.definitionDigest===Dr){(!n||n.toolName!=="Shell"||i.status!=="ok"||i.isError||i.content.length!==1||i.content[0]?.t!=="text")&&V("invalid_request");let o,s;try{o=yt("BackgroundRequest",fr(t.args.argsJson)),s=yt("BackgroundResponse",JSON.parse(i.content[0].text))}catch{V("invalid_request")}s.action!==o.action&&V("binding_conflict");let a="task"in s?s.task.identity:s.identity,d="task"in s?s.task.artifact:s.artifact;if((d.operationId!==a.operationId||d.requestDigest!==a.requestDigest)&&V("binding_conflict"),o.action==="launch"?(a.operationId!==n.operationId||a.requestDigest!==n.digest)&&V("binding_conflict"):(!mt(o.identity,a)||"artifact"in o&&!mt(o.artifact,d))&&V("binding_conflict"),o.action==="outputRead"&&s.action==="outputRead"){let c=Buffer.from(s.base64,"base64");(s.offset!==o.offset||c.toString("base64")!==s.base64||c.length!==s.byteLength||c.length>o.length||BigInt(s.nextOffset)!==BigInt(o.offset)+BigInt(c.length)||zr("sha256").update(c).digest("hex")!==s.payloadDigest||s.complete&&s.gap)&&V("invalid_request")}}}if(t.operation==="fs.read"&&e.operation==="fs.read"){let i=Buffer.from(e.args.bytesBase64,"base64");(i.toString("base64")!==e.args.bytesBase64||i.length>t.args.length)&&V("invalid_request",400)}if(t.operation==="fs.write"&&e.operation==="fs.write"&&e.args.hash!==zr("sha256").update(Buffer.from(t.args.bytesBase64,"base64")).digest("hex")&&V("invalid_request",400),e.operation==="fs.inspect"&&(ur(e.args.realpath),Number.isFinite(Number(e.args.mtimeMs))||V("invalid_request",400)),e.operation==="fs.list"){let i=new Set;for(let o of e.args.entries)ur(o.name),(o.name.includes("/")||i.has(o.name))&&V("invalid_request",400),i.add(o.name)}if(t.operation==="process.exec"&&e.operation==="process.exec"){let i=e.args.exitCode===null?null:Number(e.args.exitCode);(i!==null&&(!Number.isInteger(i)||i<-2147483648||i>2147483647)||Buffer.byteLength(e.args.stdout)+Buffer.byteLength(e.args.stderr)>t.args.maxOutputBytes)&&V("invalid_request",400)}}function Ly(t,e){return JSON.stringify([t,e])}function Mi(t,e){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new TypeError("Execution capacity must be a positive safe integer");return n}var Yo=class{constructor(e){this.options=e;if(e.shellSandbox!==void 0&&typeof e.shellSandbox!="boolean")throw new TypeError("Invalid shell sandbox option");if("spoolFor"in e=="factsFor"in e)throw new TypeError("Configure exactly one execution fact backend");_t("Scope",{applicationScopeId:e.applicationScopeId,endUserId:"validation",authorizationRevision:"0"}),Mi(e.maxConnections,256),Mi(e.maxConnectionsPerEndUser,16),Mi(e.maxSessions,512),Mi(e.maxSessionsPerEndUser,je.maxSessionsPerEndUser),this.now=e.now??Date.now}options;#e=0n;#n=new Map;sessions=new Map;connections=new Map;now;cleanup=new Set;cleanupErrors=[];#r=new Set;trackClose(e){let n=e.catch(i=>{this.cleanupErrors.push(i)});this.cleanup.add(n),n.finally(()=>this.cleanup.delete(n))}async settle(){for(;this.cleanup.size;)await Promise.all([...this.cleanup]);if(this.cleanupErrors.length)throw new AggregateError(this.cleanupErrors,"Execution resources did not close")}observeChanges(e){return this.#r.size>=64&&V("capacity_exceeded",429),this.#r.add(e),()=>{this.#r.delete(e)}}changed(e){if(this.#r.size===0)return;let n=Nn(e);for(let i of this.#r)try{i(n)}catch{}}connection(e,n,i){let o=this.connections.get(Ly(e,n));return(!o||o.user!==e||o.connection.connectionId!==i||Date.parse(o.connection.expiresAt)<=this.now())&&V("stale_generation"),o}register(e,n,i){n.executorId!==i.executorId&&V("forbidden",403),i=_t("ExecutorRegistrationRequest",JSON.parse(he(i))),new Set(i.workspaces.map(f=>f.workspaceId)).size!==i.workspaces.length&&V("invalid_request",400);let o=i.tools??[];(new Set(o.map(f=>f.name)).size!==o.length||new Set(i.operations).size!==i.operations.length||o.length>0&&!i.operations.includes("tool.invoke"))&&V("invalid_request");for(let[f,u]of this.connections)Date.parse(u.connection.expiresAt)<=this.now()&&this.connections.delete(f);let s=Ly(e,i.executorId),a=this.connections.get(s),d=Mi(this.options.maxConnections,256),c=Mi(this.options.maxConnectionsPerEndUser,16);!a&&(this.connections.size>=d||[...this.connections.values()].filter(f=>f.user===e).length>=c)&&V("capacity_exceeded",429),this.#e>=9223372036854775807n&&V("capacity_exceeded",429);let l={protocol:Oi,executorId:i.executorId,connectionId:Jo(),connectionRevision:String(++this.#e),expiresAt:new Date(this.now()+6e4).toISOString(),heartbeatAfterMs:15e3};return this.connections.set(s,{user:e,registration:i,connection:l}),this.changed({kind:"connection-changed",user:e,executorId:i.executorId}),l}heartbeat(e,n,i,o){n.executorId!==i&&V("forbidden",403);let s=this.connection(e,i,o);return s.connection={...s.connection,expiresAt:new Date(this.now()+6e4).toISOString()},this.changed({kind:"connection-changed",user:e,executorId:i}),s.connection}open(e,n,i,o){(this.sessions.has(n)||this.#n.has(n))&&V("binding_conflict");let s=Mi(this.options.maxSessions,512),a=Mi(this.options.maxSessionsPerEndUser,je.maxSessionsPerEndUser),d=[...this.sessions.values()].filter(c=>c.user===e).length+[...this.#n.values()].filter(c=>c===e).length;(this.sessions.size+this.#n.size>=s||d>=a)&&V("capacity_exceeded",429),this.#n.set(n,e);try{let c;if("factsFor"in this.options)c=this.options.factsFor({endUserId:e,sessionId:n}),(c.transactional!==!0||!mt(c.scope,{applicationScopeId:this.options.applicationScopeId,endUserId:e,sessionId:n}))&&V("forbidden",403);else{let f=this.options.spoolFor({endUserId:e,sessionId:n});mt(f.spool.bindingIdentity(f.bindingId),{applicationScopeId:this.options.applicationScopeId,endUserId:e})||V("forbidden",403),c=new Za(f)}let l=new df(this,e,n,i,c,o);return this.sessions.set(n,l),l}finally{this.#n.delete(n)}}session(e,n){let i=this.sessions.get(n);return(!i||i.user!==e)&&V("source_unavailable"),i}async poll(e,n,i,o){n.executorId!==i&&V("forbidden",403),this.connection(e,i,o);let s=[];for(let a of this.sessions.values()){if(a.user!==e)continue;await a.refresh(new AbortController().signal);let d=await a.pollOperation(i,o);if(d!==void 0&&s.push(d),s.length)break}return{protocol:Oi,executorId:i,connectionId:o,operations:s}}async receipt(e,n,i){n.executorId!==i.executorId&&V("forbidden",403);for(let o of this.sessions.values()){if(o.user!==e)continue;let s=await o.store.operation(i.operationId);if(s&&s.sessionId===o.sessionId&&s.scope.endUserId===e&&s.scope.applicationScopeId===this.options.applicationScopeId)return o.accept(i,s)}return V("source_unavailable")}},df=class{constructor(e,n,i,o,s,a){this.host=e;this.user=n;this.sessionId=i;this.bridge=o;this.store=s;this.allowedTools=a;let d=e.options.toolsFor?.(Object.freeze({applicationScopeId:e.options.applicationScopeId,endUserId:n,sessionId:i}))??[];(!Array.isArray(d)||d.length>128)&&V("invalid_request",400);for(let f of d){(!f||!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(f.name)||typeof f.execute!="function"||f.name in Ny||f.name in Uy||f.name.startsWith("mcp__")||["Skill","McpDiscover","SearchMemory","ShellOutput","ShellTask","MemoryPublication",Ai,oi,rr].includes(f.name)||this.#a.has(f.name))&&V("binding_conflict");let u=Object.freeze({...f,execute:f.execute.bind(f)});this.#a.set(u.name,{tool:u,def:Nn(bn(u))})}let c=e.options.skillsFor?.({endUserId:n,sessionId:i});this.#c=c===void 0?void 0:{registry:new al(c.registry.list()),execution:c.execution},this.#d=this.#c===void 0?void 0:cl(this.#c.registry),this.#f=e.options.mcpFor?.({endUserId:n,sessionId:i}),this.#ee=Fg({enabled:()=>this.backgroundEnabled(),signal:this.#K.signal,...e.options.backgroundRuntimeMs===void 0?{}:{timeoutMs:e.options.backgroundRuntimeMs},invoke:(f,u,m,g)=>this.#se(f,u,m,g)});let l={exec:async f=>{if(this.backgroundEnabled())return this.#ee.exec(f);let u=this.binding,m=this.policy.authorizationRevision,g=f.executionTarget;(!u||!g||g.bindingId!==u.bindingId||g.bindingRevision!==u.revision||g.executorId!==u.target.executorId||g.workspaceId!==u.target.workspaceId||g.workspaceRevision!==u.target.workspaceRevision||g.authorizationRevision!==m||!u.target.interpreter||!g.interpreter||!mt(g.interpreter,u.target.interpreter))&&V("stale_generation");let h=this.root(),p=f.cwd===h?"":f.cwd.startsWith(`${h}/`)?f.cwd.slice(h.length+1):V("forbidden",403),v=await this.#ie("Shell",{operation:"process.exec",args:{command:f.command,cwd:ur(p),timeoutMs:Math.min(12e4,f.timeoutMs),maxOutputBytes:65536,interpreter:u.target.interpreter}},f.signal,u,m,3e4,!1,void 0,!1,!1,f.toolCallId);v.operation!=="process.exec"&&V("invalid_request",400),f.onChunk?.(v.args.stdout,"stdout"),f.onChunk?.(v.args.stderr,"stderr");let{stdout:b,stderr:R,...w}=v.args,x=w.exitCode===null?null:Number(w.exitCode);return x!==null&&(!Number.isSafeInteger(x)||x<-2147483648||x>2147483647)&&V("invalid_request",400),{...w,exitCode:x,signalName:w.signalName}}};this.#t=[Gc(),co,lo,Kc,Vc,$c,Qc({executor:l,outputStorage:"memory",boundBackground:this.#ee.runtime,boundSandbox:{enabled:()=>this.shellSandboxEnabled(),exec:f=>this.#pe(f),launch:async f=>{let u=await this.#ee.runtime.launch(f);return(!("sandbox"in u)||!u.sandbox)&&V("invalid_request"),u}}}),pm(this.#ee.registry),mm(this.#ee.registry)]}host;user;sessionId;bridge;store;allowedTools;#e;bindOwner(e){if(this.#e!==void 0)throw new Error("Execution ownership already bound");e.transactional===!0!=(this.transactional!==void 0)&&V("unsupported_capability"),this.transactional&&!this.transactional.acceptsOwner(e)&&V("forbidden",403),this.#e=e}get transactional(){return"transactional"in this.store?this.store:void 0}ownershipStable(){return this.pending.size===0&&this.#s.size===0&&(this.transactional!==void 0||!this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId}))}async#n(e){return this.#e===void 0?{value:e()}:this.#e.fence(e)}async#r(e){return this.transactional?((!this.#e||!this.transactional.acceptsOwner(this.#e))&&V("forbidden",403),this.#e.write(async()=>e())):(await this.#n(e)).value}async pollOperation(e,n){if(this.pending.size!==0)return this.transactional?this.#r(async()=>{for(let i of this.pending.values())if(i.binding.target.executorId===e&&i.binding.target.connectionId===n&&this.isCurrent(i))return await this.transactional.dispatch(i),i}):(await this.#n(()=>{for(let i of this.pending.values())if(i.binding.target.executorId===e&&i.binding.target.connectionId===n&&this.isCurrent(i))return i})).value}platform=null;binding=null;policy={authorizationRevision:"0",tools:[]};attachmentSource=null;attachmentSourceRevision=0;requested;pending=new Map;#s=new Set;#t;#o=[];#i=new Map;#a=new Map;#c;#d;#f;#m;#p=null;#w=new Vn;#v=[];#k=!1;#y;#B=new WeakMap;#E=new Map;#z;#S;#g=!0;#N=()=>!1;#J;#U;#j=Promise.resolve();#C=0;#D;#Y=!1;#I=!1;#u;#T;#_=new Map;#K=new AbortController;#P;#Q=new Map;#ne=new Set;#V=!1;#L=!1;#b;#ee;#A=new Map;#q;#de=new Map;attach(e){this.#N=e}attachAttachmentSourceConfirmation(e){if(this.#U!==void 0)throw new Error("Attachment source confirmation already attached");this.#U=e}attachChildrenIdle(e){if(this.#J!==void 0)throw new Error("Child activity is already attached");this.#J=e}async#X(){(!this.#N()||this.#J!==void 0&&!await this.#J()||!this.#N())&&V("binding_conflict")}bindApplicationCapabilities(e){this.#T=e}close(){if(!this.#g)return;let e=[...this.pending.values()];this.#g=!1,this.#K.abort(),this.#ee.close(),this.#b=void 0,this.#P=void 0,this.#Q.clear(),this.#ne.clear(),this.#A.clear(),this.#de.clear(),this.pending.clear(),this.host.sessions.get(this.sessionId)===this&&this.host.sessions.delete(this.sessionId);for(let n of e)this.host.changed({kind:"operation-cancelled",user:this.user,sessionId:this.sessionId,operation:n});this.host.changed({kind:"session-closed",user:this.user,sessionId:this.sessionId}),this.#m!==void 0&&this.host.trackClose(this.#m.dispose())}serviceTools(){return[...Array.from(this.#a.values(),e=>e.tool),...this.#c?.execution==="managed-service"&&this.#d?[this.#d]:[],...this.#w.names().map(e=>this.#w.get(e))]}systemSegments(){let e=this.#c&&this.available("Skill")?dl(this.#c.registry.list()):null;return[...e?[e]:[],...this.#p&&this.available("McpDiscover")?[this.#p]:[]]}async prepareMcp(e,n,i=!1){this.transactional&&!this.transactional.services||!this.#g||this.#k||!this.#f||!this.#u?.tools.mcp||!i&&!this.platform||!this.policy.tools.some(o=>(o==="McpDiscover"||o.startsWith("mcp__"))&&(n===void 0||n.includes(o))&&(this.allowedTools===void 0||this.allowedTools.includes(o)))||(this.#z??=(async()=>{let o,s=async()=>(o=await this.attachMcp(),null);this.transactional?(this.#e||V("forbidden",403),await ef({facts:this.transactional,owner:this.#e,callId:`mcp-initialize-${Jo()}`,toolName:"McpDiscover",target:{kind:"controlled-service",executorId:"managed-service",bindingId:this.sessionId,bindingRevision:"0",authorizationRevision:this.policy.authorizationRevision},args:this.#f,signal:AbortSignal.any([e,this.#K.signal]),activeOperationIds:this.#s,otherActiveOperationIds:()=>this.pending.keys()},s)):await s(),e.throwIfAborted(),(!this.#g||o===void 0)&&V("source_unavailable"),this.#p=o.segment,this.#y=o.discoverToolFactory,this.#k=!0})(),await this.#z,e.throwIfAborted(),this.#g||V("source_unavailable"))}async attachMcp(){return this.#f||V("unsupported_capability"),this.#m??=new qr({servers:this.#f.servers,baseEnv:{},connectFactory:Am({client:oo({env:{}}),allowedUrls:this.#f.allowedUrls,authorize:async(e,n,i)=>{if(i==="DELETE")return;(!this.#g||this.#T===void 0)&&V("forbidden");let o=n??new AbortController().signal,s=await this.#T(o),a=await this.host.options.readPolicy(this.user,o);o.throwIfAborted(),this.#e?.assertCurrent();let d=this.#S===void 0?this.requested:this.#S.requested;(!this.#g||!this.policyCurrent(a)||!s.tools.mcp||a.authorizationRevision!==this.policy.authorizationRevision||!mt(a.tools,this.policy.tools)||!a.tools.some(c=>(c==="McpDiscover"||c.startsWith("mcp__"))&&(d===void 0||d.includes(c))&&(this.allowedTools===void 0||this.allowedTools.includes(c))))&&V("forbidden")}})}),Fa(this.#m,{registry:this.#w,toolDefs:this.#v})}childMcpDiscover(e){this.#y===void 0&&V("unsupported_capability");let n={registry:new Vn,toolDefs:[]},i=this.#y(n),o=new Set;this.#B.set(e.registry,o);let s=new Set(this.policy.tools.filter(a=>(!this.requested||this.requested.includes(a))&&(!this.allowedTools||this.allowedTools.includes(a))));return{...i,execute:async(a,d)=>{let c=await i.execute(a,d);for(let l of n.toolDefs){let f=n.registry.get(l.name);if(!s.has(f.name))continue;let u=e.registry.get(f.name);u!==void 0&&u!==f||(u===void 0&&e.registry.register(f),e.toolDefs.some(m=>m.name===f.name)||e.toolDefs.push(l),o.add(f),this.#E.set(f.name,f))}return c}}}isChildMcpTool(e,n){return this.#B.get(e)?.has(n)===!0}root(){return`/workspace/${this.binding?.target.workspaceId??"unbound"}`}refresh(e,n=!0){if(e.aborted)return Promise.reject(e.reason);if(!this.#g||this.#D?.signal.aborted)return Promise.reject(new Ve("source_unavailable"));if(this.#C>=jk)return Promise.reject(new Ve("capacity_exceeded",429));this.#C++;let i=new AbortController,o=AbortSignal.any([e,this.#K.signal,i.signal]),s=setTimeout(()=>i.abort(new Ve("source_unavailable")),Nk),a,d=new Promise((f,u)=>{a=()=>u(o.reason),o.addEventListener("abort",a,{once:!0}),o.aborted&&a()}),c=this.#j.then(()=>{o.throwIfAborted(),(!this.#g||this.#D!==void 0)&&V("source_unavailable");let f=this.refreshNow(o,n),u={work:f,signal:o};this.#D=u;let m=()=>{this.#D===u&&(this.#D=void 0)};return f.then(m,m),f}),l=Promise.race([c,d]);return this.#j=l.catch(()=>{}),l.finally(()=>{clearTimeout(s),o.removeEventListener("abort",a),this.#C--})}policyCurrent(e=this.policy){return e.expiresAt===void 0||Number.isSafeInteger(e.expiresAt)&&e.expiresAt>this.host.now()}async refreshNow(e,n){let i=this.policy,o=this.#u;try{this.#e?.assertCurrent(),e.throwIfAborted(),this.#T===void 0&&V("unsupported_capability");let s=await this.#T(e);e.throwIfAborted();let a=await this.host.options.readPolicy(this.user,e);e.throwIfAborted(),this.#e?.assertCurrent(),this.policyCurrent(a)||V("source_unavailable"),_t("Scope",{applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,authorizationRevision:a.authorizationRevision}),(!Array.isArray(a.tools)||a.tools.length>128||a.tools.some(u=>typeof u!="string")||BigInt(a.authorizationRevision)>9223372036854775807n||BigInt(a.authorizationRevision)<BigInt(this.policy.authorizationRevision))&&V("stale_generation"),this.#Y&&a.authorizationRevision===this.policy.authorizationRevision&&!mt(a.tools,this.policy.tools)&&V("stale_generation");let d=!1,c=this.binding,l=null;if(c!==null&&this.host.options.readAttachmentSource!==void 0)try{let u=Promise.resolve(this.host.options.readAttachmentSource({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId,binding:Nn(c),authorizationRevision:a.authorizationRevision},e));this.host.trackClose(u.then(()=>{},()=>{}));let m=await u;e.throwIfAborted(),(this.binding!==c||!this.#g||this.policy!==i)&&V("stale_generation"),this.host.connection(this.user,c.target.executorId,c.target.connectionId),m!==null&&(l=Object.freeze({source:Ah(m),executorId:c.target.executorId,workspaceId:c.target.workspaceId,workspaceRevision:c.target.workspaceRevision,authorizationRevision:a.authorizationRevision}))}catch{e.throwIfAborted()}if(c?.target.interpreter&&this.host.options.confirmInterpreter){let u=c.target,m=await this.host.options.confirmInterpreter({endUserId:this.user,executorId:u.executorId,workspaceId:u.workspaceId,interpreter:Object.freeze({...u.interpreter})},e);e.throwIfAborted(),d=m===!0&&this.#g&&this.binding===c}this.#e?.assertCurrent(),e.throwIfAborted(),(!this.#g||this.binding!==c||this.policy!==i)&&V("stale_generation"),this.policyCurrent(a)||V("source_unavailable");let f=ki(l)!==ki(this.attachmentSource);f&&this.attachmentSourceRevision===Number.MAX_SAFE_INTEGER&&V("capacity_exceeded"),this.policy={authorizationRevision:a.authorizationRevision,tools:[...a.tools],...a.expiresAt===void 0?{}:{expiresAt:a.expiresAt}},this.#Y=!0,this.#u=s,this.#I=d,f&&this.attachmentSourceRevision++,this.attachmentSource=l,n&&this.#S===void 0&&await this.prepareMcp(e,this.requested),this.#e?.assertCurrent(),e.throwIfAborted(),this.policyCurrent()||V("source_unavailable"),(!mt(i,this.policy)||!mt(o??null,this.#u??null))&&this.host.changed({kind:"policy-changed",user:this.user,sessionId:this.sessionId})}catch(s){throw this.#I=!1,this.attachmentSource!==null&&this.attachmentSourceRevision<Number.MAX_SAFE_INTEGER&&this.attachmentSourceRevision++,this.attachmentSource=null,s}}registerClientTool(e,n){(e.name===rr||e.name===Ai||e.name===oi||e.name==="MemoryPublication"||this.#a.has(e.name)||this.#i.has(e.name)||this.#t.some(i=>i.name===e.name))&&V("binding_conflict"),this.#i.set(e.name,{...n,digest:Lk(e)})}deviceTools(){return[...this.#t,...Array.from(this.#i.values(),e=>e.tool),...this.#c?.execution==="device"&&this.#d?[this.#d]:[]]}isClientTool(e){return this.#i.has(e)}isShellAuxiliary(e){return e==="ShellOutput"||e==="ShellTask"}definition(e){return this.#a.get(e.name)?.def??this.#i.get(e.name)?.def??this.#v.find(n=>n.name===e.name)??(e===this.#d?bn(e):void 0)}operations(e){return this.isShellAuxiliary(e)?["tool.invoke"]:e==="Shell"&&this.#ye()?["fs.inspect","tool.invoke"]:this.#i.has(e)?["tool.invoke"]:e==="Skill"&&this.#c?.execution==="device"?["fs.inspect","fs.read"]:Uk[e]}shellSandboxEnabled(e=!0){return this.host.options.shellSandbox!==!0||!this.available("Shell",e)||!this.binding?!1:!e||this.#ye()}#ye(){if(this.host.options.shellSandbox!==!0||!this.binding)return!1;try{let e=this.host.connection(this.user,this.binding.target.executorId,this.binding.target.connectionId);return e.registration.operations.includes("tool.invoke")&&(e.registration.tools??[]).some(n=>n.name===rr&&n.definitionDigest===Uo)}catch{return!1}}attachShellOutputReader(e){if(this.#q!==void 0||typeof e!="function")throw new Error("Shell output reader is already attached");this.#q=e}readOutputCorrelations(e){return this.#e?.assertCurrent(),this.#g||V("source_unavailable"),Nn([...this.#de.values()].filter(n=>e===void 0||n.toolCallId===e))}#Re(e){return(!e.turnId||!e.toolCallId)&&V("invalid_request"),{turnId:e.turnId,toolCallId:e.toolCallId}}#Ie(e){let n=this.binding,i=this.policy.authorizationRevision,o=e.executionTarget;(!this.shellSandboxEnabled()||!n||!o||o.kind!=="device"||o.bindingId!==n.bindingId||o.bindingRevision!==n.revision||o.executorId!==n.target.executorId||o.workspaceId!==n.target.workspaceId||o.workspaceRevision!==n.target.workspaceRevision||o.authorizationRevision!==i||!n.target.interpreter||!mt(o.interpreter,n.target.interpreter))&&V("stale_generation");let s=this.root(),a=e.cwd===s?"":e.cwd.startsWith(`${s}/`)?e.cwd.slice(s.length+1):V("forbidden");return{binding:n,revision:i,cwd:ur(a)}}async#pe(e){let{binding:n,revision:i,cwd:o}=this.#Ie(e);if(this.backgroundEnabled()){let m=await this.#ee.exec(e);return m.sandbox||V("invalid_request"),m}let{response:s,operation:a}=await this.#ve({contract:"terminal-shell-sandbox-v1",action:"exec",call:this.#Re(e),command:e.command,cwd:o,timeoutMs:Math.min(12e4,e.timeoutMs),maxOutputBytes:65536,interpreter:n.target.interpreter},e.signal,n,i,e,!1);if(s.action!=="exec"&&V("invalid_request"),s.result===null)return{exitCode:null,signalName:null,durationMs:0,timedOut:!1,aborted:!1,sandbox:s.sandbox};let d=s.output;d||V("invalid_request");let c={stdout:s.result.stdout,stderr:s.result.stderr};if(d.previewTruncated){this.#q||V("source_unavailable");try{c=await this.#q(a,e.signal)}catch{V("source_unavailable")}}e.signal.throwIfAborted(),this.#e?.assertCurrent(),(!this.shellSandboxEnabled()||!mt(this.binding,a.binding)||this.policy.authorizationRevision!==a.scope.authorizationRevision)&&V("stale_generation");for(let m of["stdout","stderr"]){typeof c[m]!="string"&&V("invalid_request");let g=Buffer.from(c[m],"utf8");(!c[m].startsWith(s.result[m])||g.length>65536||g.length!==d[m].totalBytes||zr("sha256").update(g).digest("hex")!==d[m].payloadDigest)&&V("source_unavailable")}e.onChunk?.(c.stdout,"stdout"),e.onChunk?.(c.stderr,"stderr");let{stdout:l,stderr:f,...u}=s.result;return{...u,exitCode:u.exitCode===null?null:Number(u.exitCode),signalName:u.signalName,sandbox:s.sandbox}}async#ve(e,n,i,o,s,a){this.shellSandboxEnabled()||V("unsupported_capability");let d=e.action==="exec"||e.request.action==="launch",c=Lo(e),l={sessionId:this.sessionId,scope:{applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,authorizationRevision:o},binding:i};if(d&&s.escalationApproval!==void 0){Op(s.escalationApproval,s);let g=this.#A.get(Fo(c,l));(!g||!Ng(c,l,await this.store.operation(g),await this.store.receipt(g)))&&V("forbidden"),c=Lo({...c,escalation:{previousDeniedOperationId:g,approvedCall:{turnId:s.escalationApproval.turnId,toolCallId:s.escalationApproval.toolCallId,argsDigest:s.escalationApproval.argsDigest}}})}let f,u=await this.#ie("Shell",{operation:"tool.invoke",args:{name:rr,definitionDigest:Uo,argsJson:JSON.stringify(c)}},n,i,o,c.action==="exec"?c.timeoutMs+5e3:3e4,a,g=>{f=g},!1,!0,a?void 0:s.toolCallId),m=Ua(c,u);if(d&&f&&c.escalation===void 0&&m.sandbox.isolationDenied)for(this.#A.set(Fo(c,f),f.operationId);this.#A.size>1024;)this.#A.delete(this.#A.keys().next().value);return f||V("source_unavailable"),{response:m,operation:f}}backgroundSupported(){if(!this.available("Shell")||!this.binding)return!1;try{let e=this.host.connection(this.user,this.binding.target.executorId,this.binding.target.connectionId);return this.shellSandboxEnabled()||e.registration.operations.includes("tool.invoke")&&(e.registration.tools??[]).some(n=>n.name===Ai&&n.definitionDigest===Dr)}catch{return!1}}backgroundEnabled(){return this.#b!==void 0&&mt(this.#b.binding,this.binding)&&this.#b.authorizationRevision===this.policy.authorizationRevision&&this.backgroundSupported()}configureBackground(e){e&&(!this.binding||!this.backgroundSupported())&&V("unsupported_capability"),this.#b=e?{binding:Nn(this.binding),authorizationRevision:this.policy.authorizationRevision}:void 0}#ce(e){return e.operation==="tool.invoke"&&e.args.name===Ai&&e.args.definitionDigest===Dr}async#se(e,n,i,o){let s=this.binding,a=this.policy.authorizationRevision;(!this.backgroundEnabled()||!s||n.kind!=="device"||n.bindingId!==s.bindingId||n.bindingRevision!==s.revision||n.executorId!==s.target.executorId||n.workspaceId!==s.target.workspaceId||n.workspaceRevision!==s.target.workspaceRevision||n.authorizationRevision!==a||!mt(n.interpreter,s.target.interpreter))&&V("stale_generation");let d=yt("BackgroundRequest",e);if(d.action==="launch"){let p=this.root(),v=d.cwd===p?"":d.cwd.startsWith(`${p}/`)?d.cwd.slice(p.length+1):V("forbidden");d={...d,cwd:ur(v)}}let c=d.action==="launch"?void 0:await this.store.operation(d.identity.operationId);if(d.action!=="launch"&&(!c||c.sessionId!==this.sessionId||c.scope.endUserId!==this.user||c.scope.applicationScopeId!==this.host.options.applicationScopeId||!mt(c.binding,s))&&V("binding_conflict"),d.action==="launch"?this.shellSandboxEnabled():or(c.request)){this.shellSandboxEnabled()||V("unsupported_capability");let{response:p}=await this.#ve({contract:"terminal-shell-sandbox-v1",action:"background",request:d,...d.action==="launch"?{call:this.#Re(o)}:{}},i,s,a,o,!0);if(p.action!=="background"&&V("invalid_request"),p.result===null)throw new cm(p.sandbox);return{response:p.result,sandbox:p.sandbox}}(o.escalationApproval!==void 0||o.turnId!==void 0&&this.host.options.shellSandbox===!0)&&V("unsupported_capability");let f=JSON.stringify(d);fr(f);let u,m=await this.#ie("Shell",{operation:"tool.invoke",args:{name:Ai,definitionDigest:Dr,argsJson:f}},i,s,a,3e4,!0,p=>{u=p});m.operation!=="tool.invoke"&&V("invalid_request");let g=ad(m.args.resultJson);(g.status!=="ok"||g.isError||g.content.length!==1||g.content[0]?.t!=="text")&&V("source_unavailable");let h=yt("BackgroundResponse",JSON.parse(g.content[0].text));return h.action!==d.action&&V("invalid_request"),h.action==="launch"&&(!u||h.task.identity.operationId!==u.operationId||h.task.identity.requestDigest!==u.digest||h.task.artifact.operationId!==u.operationId||h.task.artifact.requestDigest!==u.digest)&&V("binding_conflict"),h}async createMemoryPublicationStore(e,n){(e.kind!=="client-managed"||e.applicationScopeId!==this.host.options.applicationScopeId||e.endUserId!==this.user||!this.binding||!this.platform||!n.enabled())&&V("forbidden");let i=lr(e),o=Nn(this.binding);this.#P&&(!mt(this.#P.identity,e)||!mt(this.#P.binding,o))&&V("binding_conflict"),this.#P={identity:Nn(e),domainKey:i,binding:o,authorizationRevision:this.policy.authorizationRevision,enabled:n.enabled},this.memoryPublicationAvailable()||(this.#P=void 0,V("unsupported_capability"));let s=Dy({identity:e,signal:AbortSignal.any([n.signal,this.#K.signal]),assertCurrent:()=>{this.memoryPublicationAvailable()||V("source_unavailable")},invoke:(d,c)=>this.#he(d,c)});this.store.recoverableOperations===void 0&&V("unsupported_capability");let a=await this.store.recoverableOperations({applicationScopeId:e.applicationScopeId,endUserId:e.endUserId,sessionId:this.sessionId});n.signal.throwIfAborted(),this.memoryPublicationAvailable()||V("source_unavailable");for(let d of af(a,{identity:e,sessionId:this.sessionId,binding:o,authorizationRevision:this.policy.authorizationRevision,allowPriorAuthority:c=>this.#L&&this.#ne.has(c.operationId)})){s.restorePendingTransfer(d.transfer);for(let c of d.unresolvedOperationIds)this.#Q.set(d.transfer.transferId,c)}return s}async restoreMemoryPublicationBinding(e){this.assertReady(),(this.#e===void 0||this.#e.assertIdle===void 0||this.#V||this.#L||this.store.recoverableOperations===void 0||e.identity.kind!=="client-managed"||e.identity.applicationScopeId!==this.host.options.applicationScopeId||e.identity.endUserId!==this.user||typeof e.authorizeRecovery!="function")&&V("forbidden");let n=()=>{e.signal.throwIfAborted(),this.#e?.assertCurrent(),(!this.#g||!e.enabled()||!this.#N()||this.pending.size!==0||this.#s.size!==0)&&V("binding_conflict")};this.#V=!0;let i=this.binding,o=this.#P;try{n(),await this.#e.assertIdle(),await this.#X(),await this.refresh(e.signal),n();let s=this.policy.authorizationRevision,a=await this.store.recoverableOperations({applicationScopeId:e.identity.applicationScopeId,endUserId:e.identity.endUserId,sessionId:this.sessionId}),d=a.find(h=>h.operation.toolName==="MemoryPublication"&&(h.receipt===null||h.receipt.status==="unknown"));d||V("binding_conflict");let c=d.operation;af(a,{identity:e.identity,sessionId:this.sessionId,binding:c.binding,authorizationRevision:c.scope.authorizationRevision}).length===0&&V("binding_conflict");let f=this.host.connection(this.user,e.executorId,e.connectionId),u=f.registration.workspaces.find(h=>h.workspaceId===e.workspaceId);u||V("forbidden");let m={bindingId:Jo(),revision:String(BigInt(i?.revision??c.binding.revision)+1n),target:{executorId:e.executorId,connectionId:e.connectionId,connectionRevision:f.connection.connectionRevision,workspaceId:u.workspaceId,workspaceRevision:u.revision}},g=await e.authorizeRecovery(Nn({identity:e.identity,original:a,currentBinding:m,currentAuthorizationRevision:s}));n(),await this.refresh(e.signal,!1),n(),await this.#e.assertIdle(),await this.#X(),(!g||typeof g.evidenceId!="string"||!/^[^\u0000-\u001f\u007f]{1,256}$/.test(g.evidenceId))&&V("forbidden"),await this.#e.write(async()=>{n();let h=await this.store.recoverableOperations({applicationScopeId:e.identity.applicationScopeId,endUserId:e.identity.endUserId,sessionId:this.sessionId});(!mt(h,a)||s!==this.policy.authorizationRevision||this.binding!==i||this.host.connection(this.user,e.executorId,e.connectionId)!==f)&&V("stale_generation")}),n(),this.binding=m,this.#P=void 0,this.#L=!0;for(let h of a)h.operation.toolName==="MemoryPublication"&&this.#ne.add(h.operation.operationId);return await this.createMemoryPublicationStore(e.identity,{signal:e.signal,enabled:e.enabled})}catch(s){throw this.binding=this.#g?i:null,this.#P=this.#g?o:void 0,this.#L=!1,this.#ne.clear(),s}finally{this.#V=!1}}assertModelRequestsAllowed(){(this.#V||this.#L)&&V("binding_conflict")}memoryPublicationSupported(){if(!this.#g||!this.platform||!this.binding||!this.policyCurrent())return!1;try{this.#e?.assertCurrent();let e=this.binding,n=this.host.connection(this.user,e.target.executorId,e.target.connectionId);return n.connection.connectionRevision===e.target.connectionRevision&&n.registration.workspaces.some(i=>i.workspaceId===e.target.workspaceId&&i.revision===e.target.workspaceRevision)&&n.registration.operations.includes("tool.invoke")&&(n.registration.tools??[]).some(i=>i.name===oi&&i.definitionDigest===Ei)}catch{return!1}}#me;bindMemorySearch(e){if(this.#me)throw new Error("Memory search already bound");this.#me=e}memoryPublicationAvailable(){let e=this.#P;if(!e||!this.#g||!this.platform||!this.policyCurrent()||!e.enabled()||!mt(e.binding,this.binding)||e.authorizationRevision!==this.policy.authorizationRevision)return!1;try{this.#e?.assertCurrent();let n=this.host.connection(this.user,e.binding.target.executorId,e.binding.target.connectionId);return n.connection.connectionRevision===e.binding.target.connectionRevision&&n.registration.workspaces.some(i=>i.workspaceId===e.binding.target.workspaceId&&i.revision===e.binding.target.workspaceRevision)&&n.registration.operations.includes("tool.invoke")&&(n.registration.tools??[]).some(i=>i.name===oi&&i.definitionDigest===Ei)}catch{return!1}}#le(e){if(!(e.operation!=="tool.invoke"||e.args.name!==oi||e.args.definitionDigest!==Ei))try{return yt("MemoryPublicationRequest",fr(e.args.argsJson))}catch{return}}#F(e){let n=this.#le(e),i=this.#P;return this.memoryPublicationAvailable()&&n!==void 0&&i!==void 0&&n.sourceId===i.identity.sourceId&&n.sourceGeneration===i.identity.sourceGeneration&&n.domainKey===i.domainKey}async#te(e){let n=this.#le(e);if(!this.#F(e)||!n||!["head","read","query"].includes(n.action))return!1;for(let[i,o]of this.#Q){if(n.action==="query"&&n.transferId!==i)continue;let s=await this.store.operation(o);if(!s||s.sessionId!==this.sessionId||s.scope.endUserId!==this.user||s.scope.applicationScopeId!==this.host.options.applicationScopeId||!this.#ne.has(o)&&(!mt(s.binding,this.binding)||s.scope.authorizationRevision!==this.policy.authorizationRevision)||!this.#F(s.request))continue;let a=this.#le(s.request);if(!a||!["begin","chunk","commit"].includes(a.action)||!("transferId"in a)||a.transferId!==i)continue;let d=await this.store.reconciledReceipt(o)??await this.store.receipt(o);if(!d||d.status==="unknown")return!0}return!1}async#he(e,n){let i={operation:"tool.invoke",args:{name:oi,definitionDigest:Ei,argsJson:JSON.stringify(e)}};this.#F(i)||V("source_unavailable"),this.#L&&!["head","read","query"].includes(e.action)&&V("forbidden");let o;try{let s=await this.#ie("MemoryPublication",i,n,this.binding,this.policy.authorizationRevision,3e4,!1,c=>{o=c},!0);s.operation!=="tool.invoke"&&V("invalid_request");let a=ad(s.args.resultJson);if(e.action==="read"&&a.status==="error"&&a.message==="revision_conflict")throw new at("revision_conflict");(a.status!=="ok"||a.isError||a.content.length!==1||a.content[0]?.t!=="text")&&V("source_unavailable");let d=yt("MemoryPublicationResponse",JSON.parse(a.content[0].text));return(d.action!==e.action||d.sourceId!==e.sourceId||d.sourceGeneration!==e.sourceGeneration||d.domainKey!==e.domainKey||"transferId"in e&&(!("transfer"in d)||d.transfer.transferId!==e.transferId))&&V("binding_conflict"),d}catch(s){throw["begin","chunk","commit"].includes(e.action)&&"transferId"in e&&o&&this.#Q.set(e.transferId,o.operationId),s}}async invokeClientTool(e,n,i){let o=this.#i.get(e.name),s=i.executionTarget,a=this.binding;(!o||!s||!a||s.kind!=="device"||s.bindingId!==a.bindingId||s.bindingRevision!==a.revision||s.executorId!==a.target.executorId||s.workspaceId!==a.target.workspaceId||s.workspaceRevision!==a.target.workspaceRevision||s.authorizationRevision!==this.policy.authorizationRevision)&&V("stale_generation");let d=JSON.stringify(n);fr(d);let c=await this.execute(e.name,{operation:"tool.invoke",args:{name:e.name,definitionDigest:o.digest,argsJson:d}},i.signal,a,s.authorizationRevision,o.tool.timeoutMs);c.operation!=="tool.invoke"&&V("invalid_request");let l=ad(c.args.resultJson);return l.status==="ok"?{content:l.content,...l.isError===!0?{isError:!0}:{}}:{content:[{t:"text",text:l.message}],isError:!0}}available(e,n=!0){if(e==="SearchMemory")return this.#g&&this.policyCurrent()&&this.#me?.()===!0&&(this.requested===void 0||this.requested.includes(e));if(this.isShellAuxiliary(e))return this.backgroundEnabled();if(this.sharedDispatchUnsupported(e)||e==="Shell"&&(!this.binding?.target.interpreter||n&&!this.#I)||!this.#g||!this.policyCurrent()||!this.platform||!this.policy.tools.includes(e)||this.requested&&!this.requested.includes(e)||this.allowedTools&&!this.allowedTools.includes(e)&&!this.#i.has(e))return!1;let i=Ny[e],o=Uy[e],s=this.#u,a=this.#i.get(e),d=e==="Skill"&&this.#d!==void 0,c=this.#w.has(e)||this.#E.has(e),l=this.operations(e)!==void 0,f=s?.execution?.version==="bound-device-v1"?s.execution.boundDevice.tools:void 0,u=l?(d?f?.skills:a?f?.customTools:i?f?.[i]:!1)===!0:s&&(d?s.tools.skills:c?s.tools.mcp:this.#a.has(e)?s.tools.customTools:i?s.tools[i]:o?s.platform[o]:!1);if(!s||!u||e==="WebSearch"&&!s.platform.webSearch)return!1;let m=this.operations(e);if(!m)return[...this.#o,...this.serviceTools()].some(g=>g.name===e)||this.#E.has(e);if(!this.binding)return!1;try{let g=this.binding.target;if(!n)return!0;let h=this.host.connection(this.user,g.executorId,g.connectionId);return h.connection.connectionRevision===g.connectionRevision&&h.registration.workspaces.some(p=>p.workspaceId===g.workspaceId&&p.revision===g.workspaceRevision)&&m.every(p=>h.registration.operations.includes(p))&&(e!=="Shell"||mt(h.registration.interpreter,g.interpreter))&&(!a||(h.registration.tools??[]).some(p=>p.name===e&&p.definitionDigest===a.digest))}catch{return!1}}filterTools(e){return e.filter(n=>this.available(n.name))}capabilities(e=this.platform){let n=this.effectiveTools(),i={protocol:Oi,sessionId:this.sessionId,effectiveTools:n,binding:this.binding};return{...i,platform:e,capabilityRevision:ut(he({...i,initialized:this.platform!==null,requestedTools:this.requested??null,authorizationRevision:this.policy.authorizationRevision}))}}executionBoundary(e=this.platform){let n=null,i=this.binding;if(i!==null)try{let a=this.host.connection(this.user,i.target.executorId,i.target.connectionId);n={executorId:i.target.executorId,connectionId:i.target.connectionId,connectionRevision:i.target.connectionRevision,platform:a.registration.platform,operations:[...a.registration.operations],workspaces:a.registration.workspaces.map(d=>({...d}))}}catch{}let o={authorizationRevision:this.policy.authorizationRevision,policyTools:[...this.policy.tools],platformCapabilities:this.#u===void 0?[]:Object.entries(sd(this.#u.platform)).filter(([,a])=>a===!0).map(([a])=>a),executionProfile:this.#u?.execution?.version??"legacy"},s={protocol:Oi,sessionId:this.sessionId,clientPlatform:e,application:o,requestedTools:this.requested===void 0?null:[...this.requested],executor:n,effectiveTools:this.effectiveTools(),binding:i};return{...s,revision:ut(he(s))}}effectiveTools(){let e=[...this.#o,...this.deviceTools(),...this.serviceTools()].map(n=>n.name);if(this.transactional)for(let n of this.policy.tools)this.sharedDispatchUnsupported(n)&&!e.includes(n)&&e.push(n);return e.map(n=>({name:n,executionKind:this.operations(n)?"bound-device":"managed-service",available:this.available(n),unavailableReason:this.sharedDispatchUnsupported(n)?"transactional_dispatch_unavailable":this.available(n)?null:n==="Shell"?"executor_shell_unconfirmed":"capability_unconfirmed"}))}sharedDispatchUnsupported(e){return this.transactional!==void 0&&this.transactional.services===void 0&&this.serviceDispatchRequired(e)}serviceDispatchRequired(e){return this.operations(e)===void 0&&(this.#a.has(e)||["Http","WebFetch","WebSearch","ImageGen","VideoGen","SpeechToText","TextToSpeech","McpDiscover"].includes(e)||e.startsWith("mcp__"))}assertReady(){(!this.#g||this.platform===null)&&V("unsupported_capability"),(this.#S!==void 0||this.#V)&&V("binding_conflict")}async initialize(e){e.sessionId!==this.sessionId&&V("invalid_request",400),(!this.#g||this.#S!==void 0||this.#V||this.#L)&&V("binding_conflict");let n=e.requestedTools??this.requested;if(n?.some(i=>this.sharedDispatchUnsupported(i))&&V("unsupported_capability"),this.platform!==null&&mt(n??null,this.requested??null))return await this.refresh(new AbortController().signal,!1),(!this.#g||this.#S!==void 0||!mt(n??null,this.requested??null))&&V("binding_conflict"),this.capabilities(e.platform);this.#S={requested:n};try{return await this.#X(),await this.refresh(new AbortController().signal,!1),await this.prepareMcp(new AbortController().signal,n,!0),await this.#X(),this.#g||V("binding_conflict"),this.platform??=e.platform,this.requested=n,this.capabilities(e.platform)}finally{this.#S=void 0}}async bind(e){this.assertReady(),(e.sessionId!==this.sessionId||!this.platform)&&V("invalid_request",400),await this.#X(),await this.refresh(new AbortController().signal),await this.#X(),await this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId})&&V("binding_conflict"),e.expectedCapabilityRevision!==this.capabilities().capabilityRevision&&V("stale_generation");let n=this.host.connection(this.user,e.executorId,e.connectionId),i=n.registration.workspaces.find(a=>a.workspaceId===e.workspaceId);i||V("binding_conflict");let o=n.registration.interpreter,s=o&&await this.host.options.confirmInterpreter?.({endUserId:this.user,executorId:e.executorId,workspaceId:i.workspaceId,interpreter:Object.freeze({...o})},new AbortController().signal)===!0?{...o}:void 0;if(await this.#X(),this.assertReady(),(!this.#g||!this.#N()||this.host.connection(this.user,e.executorId,e.connectionId)!==n||e.expectedCapabilityRevision!==this.capabilities().capabilityRevision)&&V("stale_generation"),await this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId})&&V("binding_conflict"),this.binding={bindingId:Jo(),revision:String(BigInt(this.binding?.revision??"0")+1n),target:{executorId:e.executorId,connectionId:e.connectionId,connectionRevision:n.connection.connectionRevision,workspaceId:i.workspaceId,workspaceRevision:i.revision,...s?{interpreter:s}:{}}},this.#I=s!==void 0,this.#U!==void 0){let a=this.binding;try{await this.#U()}catch(d){throw this.binding===a&&(this.binding=null),this.attachmentSource=null,d}(!this.#g||this.binding!==a||this.host.connection(this.user,e.executorId,e.connectionId)!==n)&&V("stale_generation")}return this.capabilities()}boundary(e){return this.#o=Object.freeze([...e]),{resolve:n=>{let i=this.deviceTools().includes(n),o=this.#o.includes(n);if(!i&&o&&this.deviceTools().some(l=>l.name===n.name)||!i&&!o&&!this.serviceTools().includes(n)&&this.#E.get(n.name)!==n||!this.available(n.name))return;let s=this.binding,a=this.policy.authorizationRevision,d=he(s),c={target:{kind:i?"device":"controlled-service",executorId:i?s.target.executorId:"managed-service",bindingId:i?s.bindingId:this.sessionId,bindingRevision:i?s.revision:"0",authorizationRevision:a,...i?{workspaceId:s.target.workspaceId,workspaceRevision:s.target.workspaceRevision,...s.target.interpreter?{interpreter:s.target.interpreter}:{}}:{}},assertCurrent:async()=>{await this.refresh(new AbortController().signal),this.#e?.assertCurrent(),(!this.available(n.name)||a!==this.policy.authorizationRevision||i&&he(this.binding)!==d)&&V("stale_generation")},...i?{cwd:this.root(),fsForCall:(l,f,u)=>mp({root:this.root(),callId:l,toolName:f,signal:u,execute:async m=>{let{kind:g,...h}=m,p=await this.execute(f,{operation:g,args:h},u,s,a);return p.operation==="fs.inspect"?{...p.args,mtimeMs:Number(p.args.mtimeMs)}:((p.operation==="process.exec"||p.operation==="tool.invoke")&&V("invalid_request",400),p.args)}})}:{}};return this.transactional&&!i&&this.serviceDispatchRequired(n.name)&&(c.executeService=(l,f,u)=>((!this.#e||!this.transactional)&&V("forbidden",403),ef({facts:this.transactional,owner:this.#e,callId:l.id,toolName:n.name,target:c.target,args:l.args,signal:AbortSignal.any([f,this.#K.signal]),activeOperationIds:this.#s,otherActiveOperationIds:()=>this.pending.keys(),beforeDispatch:()=>c.assertCurrent()},u))),c},registerBuiltin:n=>{this.#o.some(i=>i===n)||(this.#o=Object.freeze([...this.#o,n]))}}}isCurrent(e){try{this.#e?.assertCurrent()}catch{return!1}return this.operationAvailable(e)&&(!this.#ce(e.request)||this.backgroundEnabled())&&mt(e.binding,this.binding)&&e.scope.authorizationRevision===this.policy.authorizationRevision&&Date.parse(e.expiresAt)>this.host.now()}operationAvailable(e,n=!0){if(or(e.request)){if(!this.shellSandboxEnabled(n))return!1;try{if(n&&Br(e.request).action==="background"&&!this.backgroundEnabled())return!1}catch{return!1}}return e.toolName==="MemoryPublication"?this.#F(e.request):this.available(e.toolName,n)}async execute(e,n,i,o=this.binding,s=this.policy.authorizationRevision,a=3e4){return this.#ie(e,n,i,o,s,a,!1)}async#ie(e,n,i,o,s,a,d,c,l=!1,f=!1,u){!l&&(this.#V||this.#L)&&V("forbidden"),await this.refresh(i),(!mt(this.binding,o)||s!==this.policy.authorizationRevision)&&V("stale_generation"),(!(l?e==="MemoryPublication"&&this.#F(n):this.available(e))||!this.binding||!d&&!l&&!f&&!this.operations(e)?.includes(n.operation))&&V("forbidden",403),d&&(e!=="Shell"||!this.backgroundEnabled()||!(f?or(n):this.#ce(n)))&&V("forbidden"),f&&(e!=="Shell"||!this.shellSandboxEnabled()||!or(n))&&V("forbidden"),_t("ResourceRequest",n),n.operation==="tool.invoke"?(!d&&!l&&!f&&(n.args.name!==e||n.args.definitionDigest!==this.#i.get(e)?.digest)&&V("forbidden"),fr(n.args.argsJson)):n.operation==="process.exec"?((!this.binding.target.interpreter||!mt(n.args.interpreter,this.binding.target.interpreter))&&V("stale_generation"),ur(n.args.cwd)):ur(n.args.path);let m=l&&await this.#te(n);!m&&await this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId},{activeOperationIds:new Set([...this.#s,...[...this.pending.values()].filter(M=>this.isCurrent(M)).map(M=>M.operationId)])})&&V("binding_conflict"),this.pending.size>=64&&V("capacity_exceeded",429);let g=this.host.now()+(n.operation==="process.exec"?n.args.timeoutMs+5e3:a),h={protocol:Oi,operationId:Jo(),sessionId:this.sessionId,scope:{applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,authorizationRevision:this.policy.authorizationRevision},binding:this.binding,toolName:e,request:n,expiresAt:new Date(g).toISOString()},p={...h,digest:zr("sha256").update("tansr.sdk2.execution.v1\0").update(he(h)).digest("hex")};c?.(p);let v=M=>this.bridge.registerToolCall(p.operationId,e,{},g,i,g-this.host.now(),M).then(W=>({value:W}),W=>({error:W})),b,R=!1;if(this.transactional?(await this.#r(async()=>{i.throwIfAborted(),!(m&&await this.#te(n))&&await this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId},{activeOperationIds:new Set([...this.#s,...this.pending.keys()])})&&V("binding_conflict"),await this.store.prepare(p)}),R=!0,b={value:v(()=>{i.throwIfAborted(),this.pending.set(p.operationId,p)})}):b=await this.#n(()=>v(()=>{i.throwIfAborted(),this.store.prepare(p),R=!0,this.pending.set(p.operationId,p)})),R&&!d&&u)for(this.#de.set(p.operationId,Nn({toolCallId:u,operation:{operationId:p.operationId,requestDigest:p.digest},binding:p.binding}));this.#de.size>1024;)this.#de.delete(this.#de.keys().next().value);this.pending.has(p.operationId)&&this.host.changed({kind:"operation-available",user:this.user,sessionId:this.sessionId,operation:p});let w=await b.value.finally(()=>{this.pending.delete(p.operationId)&&this.host.changed({kind:i.aborted||this.host.now()>=g?"operation-cancelled":"operation-removed",user:this.user,sessionId:this.sessionId,operation:p})});if("error"in w)throw w.error;let x=w.value,T=await this.store.receipt(p.operationId);if(T?.status==="failed"&&T.errorCode&&["ENOENT","EACCES","ESTALE","EFBIG","ENOTSUP","EEXIST","ENOTDIR"].includes(T.errorCode))throw Object.assign(new Error(T.errorCode),{code:T.errorCode});return(x.isError||x.content[0]?.t!=="text")&&V("source_unavailable"),(T?.status!=="completed"||!T.result)&&V("source_unavailable"),T.result}status(e){if(this.transactional)throw new Error("Shared execution facts require readStatus");let n=this.store,i=n.operation(e);(!i||i.sessionId!==this.sessionId||i.scope.endUserId!==this.user)&&V("source_unavailable");let o=n.reconciledReceipt(e)??n.receipt(e);return{protocol:Oi,operation:i,status:o?.status??(this.pending.has(e)&&this.isCurrent(i)?"pending":"unknown"),receipt:o}}async readStatus(e){if(!this.transactional)return this.status(e);let n=await this.store.operation(e);(!n||n.sessionId!==this.sessionId||n.scope.endUserId!==this.user)&&V("source_unavailable");let i=await this.store.reconciledReceipt(e)??await this.store.receipt(e);return{protocol:Oi,operation:n,status:i?.status??"unknown",receipt:i}}async readOperation(e){this.#e?.assertCurrent();let n=await this.store.operation(e);return this.#e?.assertCurrent(),(!this.#g||this.host.sessions.get(this.sessionId)!==this||!n||n.sessionId!==this.sessionId||n.scope.endUserId!==this.user||n.scope.applicationScopeId!==this.host.options.applicationScopeId)&&V("source_unavailable"),Nn(n)}reconcileStatus(e){let n=this.#_.get(e);if(n)return n;let i=Promise.resolve().then(async()=>{let o=await this.readStatus(e),s=this.host.options.reconcileObservation;if(o.receipt?.status!=="unknown"||!s)return o;let a=o.receipt,d=Nn({operation:o.operation,unknownReceipt:a,unknownReceiptDigest:ut(he(a)),currentAuthorizationRevision:this.policy.authorizationRevision}),c=await s(d,this.#K.signal);if((!this.#g||this.host.sessions.get(this.sessionId)!==this)&&V("source_unavailable"),(!mt(await this.store.operation(e),d.operation)||!mt(await this.store.receipt(e),a))&&V("binding_conflict"),c===null)return this.readStatus(e);let l=Nn(c);(l.operationDigest!==d.operation.digest||l.unknownReceiptDigest!==d.unknownReceiptDigest||typeof l.evidenceId!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~:-]{0,127}$/.test(l.evidenceId))&&V("binding_conflict");let f=_t("ExecutionReceiptRequest",l.receipt);return(f.operationId!==e||f.digest!==d.operation.digest||f.executorId!==d.operation.binding.target.executorId||f.connectionId!==d.operation.binding.target.connectionId||f.status==="unknown")&&V("binding_conflict"),(f.status==="completed"?f.result===null||f.errorCode!==null:f.result!==null||f.errorCode===null)&&V("invalid_request",400),f.result!==null&&dd(d.operation.request,f.result,d.operation),await this.#r(()=>this.store.reconcile(l,d.currentAuthorizationRevision))||V("binding_conflict"),this.readStatus(e)}).finally(()=>{this.#_.get(e)===i&&this.#_.delete(e)});return this.#_.set(e,i),i}async accept(e,n){this.pending.has(n.operationId)&&await this.refresh(new AbortController().signal),(!this.#g||this.host.sessions.get(this.sessionId)!==this||n.sessionId!==this.sessionId||n.scope.applicationScopeId!==this.host.options.applicationScopeId||n.scope.endUserId!==this.user)&&V("source_unavailable"),(e.digest!==n.digest||e.executorId!==n.binding.target.executorId||e.connectionId!==n.binding.target.connectionId)&&V("binding_conflict");let i=!0;try{this.host.connection(this.user,e.executorId,e.connectionId)}catch(a){if(!(a instanceof Ve)||a.code!=="stale_generation")throw a;i=!1}let o=this.pending.has(n.operationId);!i&&o&&V("stale_generation"),!mt(n.binding,this.binding)&&(this.binding!==null||o)&&V("stale_generation"),o&&(n.scope.authorizationRevision!==this.policy.authorizationRevision&&V("stale_generation"),this.operationAvailable(n,i)||V("forbidden")),(e.status==="completed"?e.result===null||e.errorCode!==null||e.result.operation!==n.request.operation:e.result!==null)&&V("invalid_request",400),e.result!==null&&dd(n.request,e.result,n);let s=await this.store.receipt(e.operationId);return s&&!mt(s,e)&&V("binding_conflict"),await this.#r(()=>this.store.accept(e)),o&&this.bridge.submitToolResult(e.operationId,e.status==="completed"?{status:"ok",content:[{t:"text",text:"{}"}]}:{status:"error",message:e.errorCode??"source_unavailable"}),this.pending.delete(e.operationId)&&this.host.changed({kind:"operation-removed",user:this.user,sessionId:this.sessionId,operation:n}),{protocol:Oi,operation:n,status:e.status,receipt:e}}};var Hk=128,zk=16,Gk=1e4,Fy=new WeakMap;async function cf(t,e,n,i){if(e.aborted||n.destroyed)throw new Ve("source_unavailable");let o=Fy.get(t);o||(o={total:0,users:new Map},Fy.set(t,o));let s=o.users.get(i)??0;if(o.total>=Hk||s>=zk)throw new Ve("capacity_exceeded",429);o.total++,o.users.set(i,s+1);let a=()=>{o.total--;let g=o.users.get(i)-1;g===0?o.users.delete(i):o.users.set(i,g)},d;try{d=Promise.resolve(t.options.authorize(e,i))}catch(g){throw a(),g}d.then(a,a);let c=!1,l,f=()=>{c=!0,l(new Ve("source_unavailable"))},u=new Promise((g,h)=>{l=h}),m=setTimeout(f,Gk);m.unref(),e.once("aborted",f),n.once("close",f),(e.aborted||n.destroyed)&&f();try{let g=await Promise.race([d,u]);if(c||e.aborted||n.destroyed)throw new Ve("source_unavailable");return g}finally{clearTimeout(m),e.removeListener("aborted",f),n.removeListener("close",f)}}function ai(t,e,n){let i=he(n);t.writeHead(e,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(i),"cache-control":"no-store"}),t.end(i)}async function Hy(t){let{host:e,req:n,res:i,pathname:o,method:s,endUserId:a}=t,d=m=>{let g=e.sessions.get(m);if(t.sessionFamily===void 0&&g!==void 0&&g.user!==a)throw new Ve("forbidden",403);return e.session(a,m)},c=/^\/v2\/executors\/([^/]+)\/(heartbeats|operations|receipts)$/.exec(o),l=/^\/v2\/sessions\/([^/]+)\/(initialize|execution-capabilities|execution-boundary|execution-bindings|executions)(?:\/([^/]+))?$/.exec(o),f=o==="/v2/executors/connections",u=c!==null||l!==null||f;try{let m=await cf(e,n,i,a);if(!u){if(!m.controller&&s!=="GET"||/\/(tool-results|cwd)(?:\/|$)/.test(o))throw new Ve("forbidden",403);let R=/^\/v2\/sessions\/([^/]+)\/(messages|inputs)$/.exec(o);R&&s==="POST"&&d(decodeURIComponent(R[1])).assertReady();let w=/^\/v2\/sessions\/([^/]+)\/audio\/(transcriptions|speech)$/.exec(o);if(w&&s==="POST"){let x=d(decodeURIComponent(w[1]));if(await x.refresh(new AbortController().signal),!x.available(w[2]==="transcriptions"?"SpeechToText":"TextToSpeech"))throw new Ve("forbidden")}return!1}let g=c?.[2]==="operations"||l?.[2]==="execution-capabilities"||l?.[2]==="execution-boundary"||l?.[2]==="executions"?"GET":"POST";if(s!==g)throw new Ve("invalid_request",400);let h=new URL(n.url??"/","http://serve.invalid").searchParams;if(s==="GET"&&(h.get("protocol")!=="sdk2-ext-v1"||[...h.keys()].some(R=>R!=="protocol"&&!(c&&R==="connectionId"))||[...new Set(h.keys())].some(R=>h.getAll(R).length!==1)))throw new Ve("invalid_request",400);let p;if(s==="POST"){if(!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(n.headers["content-type"]??"")||n.headers["content-encoding"])throw new Ve("invalid_request",400);let R=await t.readBody();if(R==="rejected")return!0;if(!R.ok)throw R.reason==="too_large"?(i.setHeader("connection","close"),i.once("finish",()=>n.destroy()),new Ve("payload_too_large")):new Ve("invalid_request",400);p=R.value}if(f)return ai(i,201,e.register(a,m,_t("ExecutorRegistrationRequest",p))),!0;if(c){let R=decodeURIComponent(c[1]);if(c[2]==="operations")ai(i,200,await e.poll(a,m,R,_t("Id",h.get("connectionId"))));else if(c[2]==="heartbeats"){let w=_t("ExecutorHeartbeatRequest",p);if(w.executorId!==R)throw new Ve("invalid_request",400);ai(i,200,e.heartbeat(a,m,R,w.connectionId))}else{let w=_t("ExecutionReceiptRequest",p);if(w.executorId!==R)throw new Ve("invalid_request",400);let x=await e.receipt(a,m,w);(x.status==="unknown"||x.status==="failed")&&t.log?.("warn","execution.result",{endUserId:a,sessionId:x.operation.sessionId,operationId:w.operationId,status:x.status,code:w.errorCode??x.status}),ai(i,200,x)}return!0}if(!m.controller)throw new Ve("forbidden",403);let v=decodeURIComponent(l[1]),b=d(v);if(l[2]!=="executions"&&l[3]!==void 0)throw new Ve("invalid_request",400);switch(l[2]){case"initialize":ai(i,200,await b.initialize(_t("SessionInitializeRequest",p)));break;case"execution-capabilities":await b.refresh(new AbortController().signal),ai(i,200,b.capabilities());break;case"execution-boundary":await b.refresh(new AbortController().signal),ai(i,200,b.executionBoundary());break;case"execution-bindings":ai(i,200,await b.bind(_t("ExecutionBindingRequest",p)));break;case"executions":{let R=decodeURIComponent(l[3]??"");_t("Id",R),await b.refresh(new AbortController().signal);let w=await b.reconcileStatus(R);w.status==="unknown"&&t.log?.("warn","execution.result",{endUserId:a,sessionId:v,operationId:R,status:"unknown",code:"unknown"}),ai(i,200,w);break}}return!0}catch(m){if(i.destroyed||i.writableEnded)return!0;let g=m instanceof Ve,h=m instanceof URIError||m instanceof Error&&m.name==="ZodError",p=g?m.code:h?"invalid_request":"source_unavailable";t.log?.("warn","execution.rejected",{endUserId:a,code:p});let[v,b]=Na(p);if(v===429)for(let[R,w]of Object.entries(Ft(t.retryAfterMs??5e3)))i.setHeader(R,w);if(!u){let R=p==="forbidden"?ae.v2Forbidden:p==="source_unavailable"?ae.internalError:ae.v2ValidationFailed;return pe(i,v,p,R,{detail:p},{"cache-control":"no-store"}),!0}return ai(i,v,{protocol:"sdk2-ext-v1",requestId:Fk(),code:p,status:v,message:p,retryAction:b}),!0}}import{types as Xo}from"node:util";import{randomUUID as Jy}from"node:crypto";import{randomUUID as cd}from"node:crypto";function zy(t,e){return t.sessionId===e.sessionId&&t.sourceSnapshotDigest===e.sourceSnapshotDigest&&t.localHistoryGeneration===e.localHistoryGeneration}var ld=class{runtime;#e;#n;#r=new Map;#s;#t;#o;constructor(e,n,i){this.runtime=e,this.#e=n,this.#n=i}get busy(){return this.#s!==void 0||this.#t!==void 0||this.#o!==void 0}ready(){return!this.busy&&this.runtime.run.status().status==="completed"&&this.runtime.rewrite.status().status==="completed"}assertReady(){if(!this.ready())throw new Error("Archive lifecycle reconciliation required");this.runtime.capture.assertReady()}async settle(){this.#o!==void 0&&await this.#o.catch(()=>{});let[e,n]=await Promise.all([this.runtime.run.settle(),this.runtime.rewrite.settle()]);if(e.status!=="completed"||n.status!=="completed"||this.#r.size>0)throw new AggregateError([...this.#r.values()],"Archive lifecycle reconciliation required")}async finishTurn(e,n,i,o,s=!1){this.#s=e;try{await this.runtime.run.settle();let a=this.#e.read(),d=s?this.#e.latestCommit?.():void 0;if(s&&(d==null||a.confirmedCommit===null||a.confirmedCommit.commitId!==d.commitId||!zy(d.observation,a.observation)))throw new Error("Archive unchanged history requires its original confirmed Store receipt");d&&this.runtime.targetFor(n,d),e.continuation={input:{history:n,rewritten:i,commitId:d?.commitId??cd(),observation:d?.observation??this.#c(n)},source:a.observation,unadmitted:e.ticket.status().stage==="planned",publish:o,...d?{unchangedReceipt:d}:{}},e.continuation.unadmitted&&await e.ticket.finalizeUnadmittedInput(),await this.#i(e),this.#s=void 0}catch(a){this.#r.has(e)||this.#r.set(e,a)}}#i(e){let n=e.continuation;return n.work!==void 0?n.work:e.ticket.status().capture!=="confirmed"||e.ticket.status().query!=="confirmed"?Promise.reject(new Error("Archive original capture/query remains unresolved")):zy(this.#e.read().observation,n.source)?(n.work=Promise.resolve().then(async()=>{n.unchangedReceipt===void 0&&n.publish();let i=n.unchangedReceipt===void 0?this.#n(n.input):{receipt:n.unchangedReceipt,completion:n.unchangedReceipt.completion};n.receipt=i.receipt;let o;try{this.#a(e)}catch(s){o=s}if(await i.completion,o!==void 0)throw o;if((await this.runtime.run.settle()).status!=="completed")throw new Error("Archive run reconciliation required")}),n.work):Promise.reject(new Error("Archive original continuation source changed"))}#a(e){let n=e.continuation,i=n.receipt;e.ticket.commitHistory({commitId:i.commitId,storeIdentity:i.storeIdentity,target:this.runtime.targetFor(n.input.history,i),localHistoryGeneration:i.observation.localHistoryGeneration,outcome:i.outcome})}beginRewrite(e,n){this.assertReady();let i=this.runtime.rewrite.prepare({rewriteId:cd(),reason:e,sourceLease:{signal:n.signal,assertCurrent:n.assertCurrent}}),o,s=new Promise(c=>{o=c}),a;i.bindWork({ended:s,settle:()=>a??=n.resources.settle({timeoutMs:1/0})});let d={ticket:i,signal:n.signal,original:n.history,source:this.#e.read().observation,ended:o};return this.#t=d,d}async persistRewrite(e,n){let i=this.#c(n),o=this.runtime.targetFor(n);e.ended(),e.ticket.stage({target:o,localHistoryGeneration:i.localHistoryGeneration}),e.signal.throwIfAborted();let s={history:n,rewritten:!0,commitId:cd(),observation:i};return e.commitInput={commitId:s.commitId,storeIdentity:this.#e.storeIdentity,target:o,localHistoryGeneration:i.localHistoryGeneration,start:()=>{let a=this.#n(s);return e.receipt=a.receipt,e.completion=a.completion,a.receipt.outcome}},e.ticket.commitHistory(e.commitInput),await e.completion,await this.runtime.rewrite.settle(),e.signal.throwIfAborted(),a=>e.ticket.publish({apply:a,assertPublished:()=>{let d=this.#e.read().observation;if(d.sourceSnapshotDigest!==i.sourceSnapshotDigest||d.localHistoryGeneration!==i.localHistoryGeneration)throw new Error("Archive rewrite publication mismatch")}})}async endRewrite(e){try{if(e.ended(),e.receipt!==void 0&&e.completion!==void 0&&e.ticket.status().publication==="not-started"&&e.ticket.status().compensation!=="confirmed"&&(await e.completion.catch(()=>{}),await this.runtime.rewrite.settle(),e.compensationInput??={commitId:cd(),storeIdentity:this.#e.storeIdentity,target:this.runtime.targetFor(e.original),localHistoryGeneration:e.source.localHistoryGeneration,start:()=>{let n=this.#n({history:e.original,rewritten:!0,commitId:e.compensationInput.commitId,observation:e.source});return e.compensationCompletion=n.completion,n.receipt.outcome}},e.ticket.compensateHistory(e.compensationInput),await e.compensationCompletion),e.ticket.status().legacyStore==="not-started"&&e.ticket.status().publication==="not-started"&&e.ticket.concludeUnchanged(),(await this.runtime.rewrite.settle()).status!=="completed")throw new Error("Archive rewrite reconciliation required");this.#t===e&&(this.#t=void 0)}catch(n){throw this.#r.has(e)||this.#r.set(e,n),n}}retry(){if(this.#o!==void 0)return this.#o;let e=(async()=>{let n=this.#s,i=this.#t;if(n!==void 0){let s=n.continuation;if(s===void 0)return!1;s.work===void 0?(s.unadmitted?await n.ticket.retryUnadmittedInput():await this.runtime.capture.awaitReady(),await this.#i(n)):(await s.work.catch(()=>{}),s.receipt!==void 0&&n.ticket.status().stage!=="settled"&&this.#a(n))}await this.runtime.run.retryOriginal();let o=await this.runtime.rewrite.retryOriginal();return i!==void 0&&o.status!=="completed"&&(i.commitInput!==void 0&&i.receipt===void 0&&(i.ticket.commitHistory(i.commitInput),await i.completion),await this.endRewrite(i),o=await this.runtime.rewrite.retryOriginal()),o.status!=="completed"||(await this.runtime.run.settle()).status!=="completed"?!1:(n!==void 0&&this.#r.delete(n),i!==void 0&&this.#r.delete(i),this.#s=void 0,this.#t=void 0,!0)})().finally(()=>{this.#o=void 0});return this.#o=e,e}#c(e){let n=this.#e.read().observation;return rn(n.sessionId,e,n.localHistoryGeneration+1)}};var Gy=/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/;function Wk(t){let e=he(t);if(Buffer.byteLength(e)>262144)throw new Error("Archive lineage capacity exceeded");let n=JSON.parse(e);Mn(n,["format","storeCommitId","sourceSnapshotDigest","workId","baselineSequence","retentionRevision","origins"]);let i=o=>typeof o=="string"&&/^(0|[1-9][0-9]{0,18})$/.test(o)&&BigInt(o)<=9223372036854775807n;if(n.format!=="serve-archive-lineage-v1"||typeof n.storeCommitId!="string"||!Gy.test(n.storeCommitId)||typeof n.workId!="string"||!n.workId||Buffer.byteLength(n.workId)>256||n.workId.includes("\0")||typeof n.sourceSnapshotDigest!="string"||!/^[a-f0-9]{64}$/.test(n.sourceSnapshotDigest)||!i(n.baselineSequence)||!i(n.retentionRevision)||!Array.isArray(n.origins)||n.origins.length>4096)throw new Error("Invalid archive lineage");for(let o of n.origins){if(Mn(o,["recordIds","throughSequence"]),!Array.isArray(o.recordIds)||o.recordIds.length>128||new Set(o.recordIds).size!==o.recordIds.length||o.recordIds.some(s=>typeof s!="string"||!Gy.test(s))||o.throughSequence!==null&&(!i(o.throughSequence)||o.throughSequence==="0"))throw new Error("Invalid archive message origin");Object.freeze(o.recordIds),Object.freeze(o)}return Object.freeze(n.origins),Object.freeze(n)}function lf(t,e,n,i,o){if(o.length!==t.history.length)throw new Error("Archive lineage snapshot length changed");return Wk({format:"serve-archive-lineage-v1",storeCommitId:t.commitId,sourceSnapshotDigest:t.observation.sourceSnapshotDigest,workId:e,baselineSequence:n,retentionRevision:i,origins:o})}function Wy(t,e,n,i,o){return $y(t,e,n,i,o)}function Vy(t,e,n){return $y(t,e,void 0,n,!0)}function $y(t,e,n,i,o){let s=n===void 0?[]:[n];return t.initialIndices.map((a,d)=>{if(a.length){let c=new Set,l=null;for(let f of a){let u=e[f]??{recordIds:s,throughSequence:null};for(let m of u.recordIds)c.add(m);u.throughSequence!==null&&BigInt(u.throughSequence)>BigInt(l??"0")&&(l=u.throughSequence)}return{recordIds:[...c],throughSequence:l}}return{recordIds:s,throughSequence:o||t.messages[d]?.role==="user"?i?.sequence??null:null}})}var wt={turnRunning:"server.v2.error.turn_running",checkpointNotFound:"server.v2.error.checkpoint_not_found",sessionMismatch:"server.v2.error.session_mismatch",checkpointsNotWired:"server.v2.error.checkpoints_not_wired",cwdNotAllowed:"server.v2.error.cwd_not_allowed",cwdInvalid:"server.v2.error.cwd_invalid",cwdUnavailable:"server.v2.error.cwd_unavailable",cwdMismatchOnResume:"server.v2.warning.cwd_mismatch_on_resume",cwdMismatchOnResumeStored:"server.v2.warning.cwd_mismatch_on_resume_stored",cwdMismatchOnRestore:"server.v2.warning.cwd_mismatch_on_restore",usageSnapshotStale:"server.v2.warning.usage_snapshot_stale",recoveryDegraded:"server.v2.warning.recovery_degraded",compactHookBlocked:"server.v2.compaction.hook_blocked",cwdSwitchUnsupported:"server.v2.error.cwd_switch_unsupported",forkSourceNotFound:"server.v2.error.fork_source_not_found",checkpointImportInvalid:"server.v2.error.checkpoint_import_invalid",storeCommitFailed:"server.v2.persistence.store_commit_failed",storeCreateFailed:"server.v2.persistence.store_create_failed"},Ky=Object.values(wt);function Qy(t){return t instanceof Error?t.message:String(t)}async function ud(t){let{manager:e,compaction:n,view:i,hooks:o,signal:s}=t,a=[],d=t.sessionCapture===void 0?void 0:await wr({capture:t.governanceCapture??t.sessionCapture,messages:i.messages,signal:s,isCurrent:t.isCurrent??(()=>!1),...t.onPending===void 0?{}:{onPending:t.onPending}}),c,l=!1,f=u=>{let m=Hi({messages:[],transform:{ops:[],usage:u},usageAttribution:{model:n.model??t.model,contextWindowTokens:t.contextWindowTokens}}).events;t.onAbandonedUsage?.(m)};try{let u=[];if(o?.preCompact!==void 0)try{let T=await o.preCompact({signal:s,trigger:"manual",...t.instructions!==void 0?{customInstructions:t.instructions}:{}});if(T.blocked===!0)return a.push({type:"turn.error",scope:"hooks",message:We(wt.compactHookBlocked,{reason:T.blockReason??"-"}),recoverable:!0}),{status:"rejected",reason:"hook_blocked",events:a};u=T.additionalContexts??[]}catch(T){a.push({type:"turn.error",scope:"hooks",message:Qy(T),recoverable:!0})}let m=[...t.instructions!==void 0?[t.instructions]:[],...u].filter(T=>T.trim().length>0),g=m.length>0?m.join(`
|
|
21
|
+
|
|
22
|
+
`):void 0,h=n.model??t.model;d?.assertSourceCurrent();let p=await e.compact({view:i,model:h,trigger:"manual",signal:s,maxTokens:Math.min(n.maxOutputTokens??2e4,e.thresholds.compactOutputBudget),...g!==void 0?{instructions:g}:{},...t.beforeCompact!==void 0?{beforeCompact:t.beforeCompact}:{},...d===void 0?{}:{publication:d},onUsage:T=>{l?f(T):c=T}});if(d?.assertSourceCurrent(),!p.ok){let T=p.usage??c;return a.push(...Hi({messages:[...i.messages],transform:{ops:[],failure:p,...T!==void 0?{usage:T}:{}},usageAttribution:{model:h,contextWindowTokens:t.contextWindowTokens}}).events),a.push({type:"turn.error",scope:"compaction",message:p.message,recoverable:!0}),c=void 0,{status:"failed",outcome:p,events:a}}let v=[...i.messages],b=e.compactionObserver,R=p.compactionUsage??c,w={messages:v,transform:{ops:[Ic(p,i.messages)],...R!==void 0?{usage:R}:{},outcome:p,invalidations:"strategy"},usageAttribution:{model:h,...t.contextWindowTokens!==void 0?{contextWindowTokens:t.contextWindowTokens}:{}},...b!==void 0?{observation:{observer:b,trigger:"manual"}}:{}},x;if(d===void 0)x=Hi(w);else{let T=Rc({...w,afterPublishBeforeNotifications:()=>{t.publishHistory(M),d.accept()}}),M=Object.freeze(structuredClone([...T.nextMessages]));t.beforePublish!==void 0&&await t.beforePublish(M,p.messages);let W=()=>T.commit(()=>(d.assertSourceCurrent(),t.publishHistory!==void 0));x=t.commitPrepared===void 0?W():Bl(M,W,t.commitPrepared)}if(a.push(...x.events),c=void 0,o?.postCompact!==void 0)try{await o.postCompact({signal:s,trigger:"manual",summaryText:p.summaryText,removedCount:p.removedIndices.length})}catch(T){a.push({type:"turn.error",scope:"hooks",message:Qy(T),recoverable:!0})}return{status:"compacted",outcome:p,messages:v,events:a}}catch(u){throw c!==void 0&&f(c),u}finally{l=!0}}function Vk(){let t=[],e=!1,n=null,i=()=>{if(n!==null){let o=n;n=null,o()}};return{push(o){e||(t.push(o),i())},end(){e=!0,i()},iterable:{async*[Symbol.asyncIterator](){for(;;){for(;t.length>0;)yield t.shift();if(e)return;await new Promise(o=>{n=o})}}}}}var di=class{#e=null;#n=null;#r=null;#s=Vk();#t;#o;#i;#a;#c;#d;#f;#m;#p;#w;#v;#k;#y;#B;#E;#z=!1;#S;#g;#N;#J;#U;#j;#C;#D;#Y;#I;#u;#T;#_=!1;#K;#P;#Q;#ne;#V;#L;#b;#ee;#A=null;#q=[];#de;#X;#ye;#Re;#Ie;#pe;#ve;#ce;#se;#me;#le;#F;#te;#he=null;#ie;#Te;#Ee;#be;#je;#Ze;#Pe;#Ne=null;#M=null;#l;#Ue;#ge;#ae=!1;#Z;#Le="0";#Me=[];#Oe=new WeakMap;#et;#Fe=!1;#O;#G;#$=null;#ke;#He;#x;#ze=!1;#Ve;#Be;#tt;#H=0;#xe=0;#ue=new AbortController;#re=new Fp;#Ce=new Set;#h=Object.freeze([]);#De=[];#fe;#$e;#nt=void 0;#R=!1;#W=!1;#dt=!1;#ct=!1;#lt=!1;#oe=0;#Ke=[];#Qe=!1;#Ge=!1;#_e;#ut=0;#it=!1;constructor(e){this.#B=e.client,this.#y=this.#Je(e.client),this.#U=this.#y;let n=this.#y,i=()=>this.#L?.model===void 0?this.#y:n;if(this.#E=Gn({async*stream(s,a){yield*i().stream(s,a)}},e.client),this.#O=e.sessionCapture,this.#G=e.contextMaterials,this.#t=e.executor,this.#o=e.cwd,this.#a=e.system,this.#c=e.applicationPromptInfo,this.#d=e.prepareSystem,this.#v=e.runtimeCostSnapshot,this.#k=e.tools,this.#j=e.model,this.#C=e.contextWindowTokens,this.#D=e.maxOutputTokens,this.#Y=e.maxTokens??Fi,this.#I=e.thinking,this.#u=e.sessionId??Jy(),this.#T=new Ac(this.#u),this.#K=e.maxTurnsPerQuery,this.#P=e.temperature,this.#Q=e.stopSequences===void 0?void 0:[...e.stopSequences],this.#ne=e.maxToolRounds,this.#V=e.maxConsecutiveErrors,this.#L=e.compaction===void 0?void 0:Hp(e.compaction,e.compactionManagerOptions),this.#de=e.reminders,this.#X=e.budget,this.#ye=e.toolResultBudget,this.#Re=e.onEvent,this.#Ie=e.queryHooks,this.#pe=e.onClosed,this.#ve=e.requestMeasurement,this.#ce=e.sessionEvents,this.#se=e.onTurnStart,this.#me=e.onInputsConsumed,this.#le=e.onTurnEnd,this.#Ee=e.getMemorySelectionCheckpoint,this.#F=e.attachmentPersistence?.scope,this.#te=e.attachmentPersistence?.verifySource===!0,this.#je=e.runQueryImpl??_s,this.#Ze=e.timeouts,e.maxTurnWallClockMs!==void 0&&!(e.maxTurnWallClockMs>0))throw new TypeError(`maxTurnWallClockMs 必须为正数,收到 ${e.maxTurnWallClockMs}`);this.#Pe=e.maxTurnWallClockMs;let o=e.initialSeq??0;if(!Number.isSafeInteger(o)||o<0)throw new TypeError(`initialSeq 必须为非负安全整数,收到 ${String(e.initialSeq)}`);if(this.#fe=o,this.#$e=o,this.#_e=o,e.initialHistory!==void 0&&(this.#h=Object.freeze(structuredClone(e.initialHistory))),this.#b=this.#rt(),e.attachmentPersistence?.checkpoint!==void 0){let s=e.attachmentPersistence,a=!1;if(this.#te&&s.invalidateReferences!==!0&&s.sourceCheckpoint!==void 0){let c=Fl(s.sourceCheckpoint),l=Li(s.checkpoint,{scope:this.#F,messages:this.#h});c!==null&&Ch(c,this.#F,this.#h,l)&&(this.#ie=c,a=!0)}let d={scope:this.#F,messages:this.#h,...a?{deferReferences:!0}:e.attachmentPersistence.invalidateReferences===!0||this.#te?{invalidateReferences:!0}:{}};if(this.#b===void 0)this.#ie=void 0,this.#be=Li(e.attachmentPersistence.checkpoint,{...d,...this.#te?{invalidateReferences:!0}:{}});else if(!this.#b.restoreAttachmentCheckpoint(e.attachmentPersistence.checkpoint,d))throw new TypeError("Attachment checkpoint does not match this session")}this.pushBody({type:"session.created",cwd:e.cwd},"server")}#rt(e=!1){if(this.#L===void 0||this.#C===void 0)return;let{manager:n,...i}=this.#L,o=zp(i,void 0,{client:this.#E,contextWindowTokens:this.#C}),s=Ip(this.#de);if(s!==void 0&&o.registerPostCompactInvalidation(s),e&&this.#F!==void 0&&this.#b!==void 0){let a={scope:this.#F,messages:this.#h};if(!o.restoreAttachmentCheckpoint(this.#b.exportAttachmentCheckpoint(a),a))throw new TypeError("Attachment budget cannot be transferred");o.runPostCompactInvalidations()}return o}attachmentCheckpoint(e=this.#h,n=!1){if(this.#F===void 0)return;let i={scope:this.#F,messages:e},o=this.#b?.exportAttachmentCheckpoint(i)??(this.#be===void 0?void 0:Li(this.#be,{...i,invalidateReferences:this.#be.historyDigest!==io(e)}));return o!==void 0&&n&&(o=Li(o,{...i,invalidateReferences:!0})),this.#b===void 0&&(this.#be=o),this.#m===void 0&&o?.injectedBytes===0&&o.rejectedCount===0&&o.entries.length===0?void 0:o}invalidateAttachmentReferences(){this.#ie=void 0,this.#b?.runPostCompactInvalidations(),this.#be!==void 0&&this.#F!==void 0&&(this.#be=Li(this.#be,{scope:this.#F,messages:this.#h,invalidateReferences:!0}))}attachmentSourceCheckpoint(e=this.#h){if(!this.#te)return;let n=this.attachmentCheckpoint(e);return this.#he===null||n===void 0?null:Eh(this.#F,e,n,this.#he)}updateAttachmentSource(e){this.#te&&(ki(e)!==ki(this.#he)&&this.invalidateAttachmentReferences(),this.#he=e)}confirmAttachmentSource(e){if(!this.#te)return Promise.resolve();if(this.status()!=="idle")return Promise.reject(new Error("Attachment source confirmation requires idle session"));let n=new AbortController;this.#Te=n;let i=this.#h,o=this.#H,s=AbortSignal.any([this.#ue.signal,n.signal]),a=Promise.resolve().then(async()=>{await In(this.#Xe(),s),this.#ke!==void 0&&await In(this.#ke(),s);let d=e(s);this.#re.track(d.then(()=>{},()=>{}));let c=await In(d,s);if(s.aborted||this.#R||this.#h!==i||this.#H!==o||this.#M!==null)throw new Error("Attachment source confirmation changed");let l=this.#ie;this.#ie=void 0,(c===null||l===void 0||this.#oe!==0||ki(c)!==ki(l.snapshot)||!this.#b?.activateRestoredAttachmentReferences({scope:this.#F,messages:i}))&&this.invalidateAttachmentReferences(),this.#he=c}).catch(d=>{throw this.#he=null,this.invalidateAttachmentReferences(),d}).finally(()=>{if(this.#Te===n&&(this.#Te=void 0),this.#$===a&&(this.#$=null),this.#R)this.#Se();else if(this.#l!==void 0)this.#Ae();else if(this.#M===null&&this.#q.length>0){let d=this.#q;this.#q=[],this.#we(d)}});return this.#$=a,a}memorySelectionCheckpoint(){return this.#Ee?.()}get sessionId(){return this.#u}applicationPrompt(){let e=this.#c?.get(this.#a);return e===void 0?void 0:{policy:e.policy,source:e.source}}contextState(){let e={model:{provider:this.#j.provider,model:this.#j.model},alias:null,contextWindowTokens:this.#C??null};return{selected:e,active:this.#M===null?null:structuredClone(e),lastObserved:structuredClone(this.#e),lastUsage:structuredClone(this.#n),fallback:structuredClone(this.#r),budget:Ds({system:this.#a,tools:this.#k,messages:this.#M?.messages()??this.#h},{contextWindowTokens:this.#C,maxOutputTokens:this.#D,requestedOutputTokens:this.#Y,thinkingBudgetTokens:this.#I?.budget,thresholds:this.#L?.thresholds,resolvedThresholds:this.#b?.thresholds,estimator:this.#b?.requestEstimator??this.#L?.estimator,settingsSource:this.#L?"configured":this.#C===void 0?"unknown":"model"}),sampledAt:Date.now(),history:this.#M===null?"committed":"live",transition:{status:"idle",target:null}}}#Je(e){let n=()=>{this.#f?.assertCurrent(),this.#N?.()};return Gn({async*stream(i,o){n(),yield*e.stream(i,o)}},e)}#ft(){let e=this.#L;return!this.#z||e===void 0||e.client!==void 0||e.model!==void 0||this.#D===void 0?e:{...e,maxOutputTokens:Math.min(e.maxOutputTokens??1/0,this.#D)}}#Ye(){if(this.#R||this.#W||this.#ae)return{status:"rejected",reason:"session_ended"};if(this.status()!=="idle"||this.#Ce.size>0||!this.#re.isSettled()||this.#ge!==void 0||this.#p!==void 0||this.#Te!==void 0)return{status:"rejected",reason:"turn_running"};this.#f?.assertCurrent(),ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ui(this.#x?.storeIdentity,this.#u,this.#l?.runtime),this.#l?.assertReady(),this.#O?.assertReady()}modelBinding(){return{client:this.#U,model:{...this.#j},...this.#C===void 0?{}:{contextWindowTokens:this.#C},...this.#D===void 0?{}:{maxOutputTokens:this.#D}}}currentCostSnapshot(){return this.#v?.()}retainCostPersistence(e){this.#re.track(e)}thinking(){return this.#I===void 0?void 0:{...this.#I}}bindConfigurationReadiness(e){if(this.#g||this.status()!=="idle")throw new Error("Configuration readiness already bound or active");this.#g=e}bindModelRequestGuard(e){if(this.#N||this.status()!=="idle")throw new Error("Model request guard already bound or active");this.#N=e}bindModelClientWrapper(e,n){if(this.#J||this.status()!=="idle")throw new Error("Model client wrapper already bound or active");this.#J=e,this.#U=this.#Je(n??this.#B)}#ot(e,n){let i=p=>p===void 0||Number.isSafeInteger(p)&&p>0;if(e!==void 0&&(!e||typeof e.client?.stream!="function"||typeof e.model?.provider!="string"||!e.model.provider.trim()||typeof e.model.model!="string"||!e.model.model.trim()||!i(e.contextWindowTokens)||!i(e.maxOutputTokens))||n!==void 0&&(!n||typeof n!="object"||!i(n.budget)))return{status:"rejected",reason:"invalid_configuration"};let o=e===void 0?this.#B:this.#J?.(e.client)??e.client,s={...e?.model??this.#j},a=e===void 0?this.#C:e.contextWindowTokens,d=e===void 0?this.#D:e.maxOutputTokens,c=n===void 0?void 0:{...n.budget===void 0?{}:{budget:n.budget}},l=o!==this.#B||he(s)!==he(this.#j)||a!==this.#C||d!==this.#D;if(!l&&he(c??null)===he(this.#I??null)){let p=this.#H;return{status:"ready",isCurrent:()=>!this.#R&&this.#H===p,publish(){}}}if(l&&(this.#b!==void 0&&(a===void 0||this.#b.thresholds.contextWindow>a)||this.#b===void 0&&this.#L!==void 0&&a!==void 0))return{status:"rejected",reason:"context_transition_required"};let f=Ds({system:this.#a,tools:this.#k,messages:this.#h},{contextWindowTokens:a,maxOutputTokens:d,requestedOutputTokens:this.#Y,thinkingBudgetTokens:c?.budget,thresholds:this.#L?.thresholds,resolvedThresholds:this.#b?.thresholds,estimator:this.#b?.requestEstimator??this.#L?.estimator});if(this.#h.length>0&&(f.fits===!1||this.#C!==void 0&&a===void 0))return{status:"rejected",reason:"context_transition_required"};let u=this.#H,m=l?this.#Je(o):this.#y,g=e===void 0?this.#U:this.#Je(e.client),h=()=>!this.#R&&!this.#W&&this.#H===u&&!this.#ae&&this.#M===null&&this.#A===null&&!this.#_;return{status:"ready",isCurrent:h,publish:()=>{if(!(this.#R||this.#W)){if(this.#f?.assertCurrent(),!h())throw new Error("Configuration publication lost its safe point");l&&(this.#b?.bindRequestModel(s,m),this.#L?.model===void 0&&Gn(this.#E,o),this.#y=m,this.#U=g,this.#B=o,this.#j=s,this.#C=a,this.#D=d,this.#z=!0),(l||he(c??null)!==he(this.#I??null))&&(this.#I=c,this.#H++)}}}}setModel(e){let n=this.#Ye();if(n)return n;let i={...this.#j},o=this.#ot(e,this.#I);return o.status==="rejected"?o:(o.publish(),{status:"changed",from:i,to:{...this.#j}})}setThinking(e){let n=this.#Ye();if(n)return n;let i=this.thinking()??null,o=this.#ot(void 0,e);return o.status==="rejected"?o:(o.publish(),{status:"changed",from:i,to:this.thinking()??null})}configurationRejection(){return this.#Ye()}async configure(e,n={}){let i=this.#Ye();if(i)return i;let o;this.#S=new Promise(s=>{o=s});try{if(this.#g&&!await this.#g())return{status:"rejected",reason:"turn_running"};if(this.#R||this.#W)return{status:"rejected",reason:"session_ended"};let s=n.signal===void 0?this.#ue.signal:AbortSignal.any([this.#ue.signal,n.signal]);return s.throwIfAborted(),await e((a,d)=>this.#ot(a,d),s)}finally{if(this.#S=void 0,o(),this.#R)this.#Se();else if(this.#l)this.#Ae();else if(this.#q.length){let s=this.#q;this.#q=[],this.#we(s)}}}get events(){return this.#s.iterable}get callbackErrors(){return this.#ut}send(e){return this.#ae||(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ui(this.#x?.storeIdentity,this.#u,this.#l?.runtime),this.#R||this.#W)?"ended":this.#S||this.#_||this.#$!==null||this.#l?.busy?(this.#q.push(e),"queued"):this.#M!==null?(this.#De.push(e),this.#M.enqueueUserInput(e),"queued"):this.#A!==null?(this.#q.push(e),"queued"):(Rs(this.#G),this.#we([e]),"started")}sendMessage(e){return this.#ae||(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ui(this.#x?.storeIdentity,this.#u,this.#l?.runtime),this.#R||this.#W)?"ended":this.#S!==void 0||this.#M!==null||this.#A!==null||this.#_||this.#$!==null||this.#l?.busy?"midturn":(Rs(this.#G),this.#we([structuredClone(e)]),"started")}inputCapabilities(){return this.#T.inputCapabilities()}getInputTarget(){return this.#T.getInputTarget()}submitInput(e){return this.#T.submitInput(e)}getInputStatus(e,n){return this.#T.getInputStatus(e,n)}status(){return this.#W||this.#R?"ended":this.#S!==void 0||this.#M!==null||this.#A!==null||this.#_||this.#$!==null||this.#l?.busy?"running":"idle"}trackHistoryDeletionSettlement(){this.#dt=!0,this.#pt()}historyDeletionReady(){return this.#W&&this.#lt}#pt(){!this.#dt||!this.#W||this.#ct||(this.#ct=!0,Promise.resolve().then(()=>this.settleResources()).then(()=>{this.#lt=!0},()=>{}))}lastSeq(){return this.#fe-1}firstSeq(){return this.#$e}bindOnEnded(e){this.#nt=e}bindOwner(e){if(this.#f!==void 0||this.#M!==null)throw new Error("Session ownership already active");this.#f=e;let n=this.#d;this.#d=async i=>(await e.beginTurn(),i.throwIfAborted(),n===void 0?this.#a:n(i))}bindRuntimeRecovery(e,n){if(!this.#f||this.#M||this.#m||this.#O!==void 0&&!Rp(this.#O))throw new Error("Runtime recovery unavailable");if(this.#b!==void 0&&this.#F===void 0)throw new Qt("reconciliation_required");if(this.#Ie!==void 0||this.#ce!==void 0||this.#G!==void 0&&!kp(this.#G)||this.#se!==void 0||this.#me!==void 0)throw new Qt("reconciliation_required");if(this.#X!==void 0&&this.#v===void 0)throw new Error("Runtime recovery requires the original cost tracker");if(n!==void 0){if(n.deadline===void 0!=(this.#Pe===void 0))throw new Qt("reconciliation_required");let i=JSON.parse(n.query.configuration),o=this.#X===void 0?void 0:{maxUsd:this.#X.maxUsd,maxTotalTokens:this.#X.maxTotalTokens,onExceeded:this.#X.onExceeded};if(JSON.stringify(i.model)!==JSON.stringify(this.#j)||JSON.stringify(i.tools)!==JSON.stringify(this.#k)||JSON.stringify(i.budget)!==JSON.stringify(o)||!Array.isArray(i.system)||!i.system.every(s=>s!==null&&typeof s=="object"&&typeof s.text=="string"))throw new Qt("reconciliation_required");this.#a=structuredClone(i.system)}this.#m=e,this.#p=n}resumeRuntime(){if(!this.#p||!this.#m||this.#M||this.#R)throw new Error("Runtime recovery unavailable");this.#we([])}prepareArchiveRuntimeRecovery(){if(!this.#p||!this.#m||this.#l||this.#M||this.#R||this.#oe!==0)throw new Error("Archive runtime recovery unavailable");let e=Js(this.#p);if(e.query.sessionId!==this.#u||he(e.query.messages)!==he(this.#h))throw new Qt("reconciliation_required");this.#h=structuredClone(e.archive.messages),this.#H=e.archive.history.observation.localHistoryGeneration,this.#xe=e.archive.history.observation.localHistoryGeneration}resumeArchiveRuntime(e){if(!this.#l||!this.#p||he(e)!==he(this.#p))throw new Qt("reconciliation_required");Js(e),this.resumeRuntime()}historySnapshot(){return{lastSeq:this.#_e,messages:[...this.#h]}}interrupt(e){this.#Te!==void 0&&(this.#Te.abort(),this.#q=[],this.invalidateAttachmentReferences()),this.#M?.abort(e?.source),this.#A?.ac.abort()}pushBody(e,n="server"){this.#mt({...e,sessionId:this.#u,seq:this.#fe++,ts:Date.now(),v:"v0",source:n})}pushControl(e,n){let i=this.#fe++;return this.#s.push({type:e,sessionId:this.#u,seq:i,ts:Date.now(),payload:n}),i}async settleResources(){if(this.#S&&await this.#S,this.#$!==null&&await this.#$.catch(()=>{}),await this.#Xe(),await this.#l?.settle(),this.#Fe)throw this.#et}async#Xe(){for(;this.#Ce.size>0||this.#A!==null||this.#ge!==void 0;)await Promise.allSettled([...this.#Ce,...this.#A===null?[]:[this.#A.promise],...this.#ge===void 0?[]:[this.#ge]]);if(this.#O===void 0)await this.#re.settle();else{let n=(await Promise.allSettled([this.#re.settle(),this.#O.settle()])).flatMap(i=>i.status==="rejected"?[i.reason]:[]);if(n.length>0)throw new AggregateError(n,"Session capture resource settlement failed")}}close(e){if(!this.#R){if(this.#R=!0,this.#l?.runtime.stopAdmission(),this.#ue.abort(),this.#H+=1,this.#M!==null){this.#M.abort(e?.source);return}if(this.#A!==null){this.#A.ac.abort();return}this.#S||this.#_||this.#ge!==void 0||this.#Se()}}get model(){return this.#j}bindBeforeCompact(e){this.#ee=e}bindArchivePersistenceBarrier(e){if(this.#ke!==e){if(this.#ke!==void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive persistence barrier must be bound before execution");this.#ke=e}}bindArchiveSourceReadCheck(e){if(this.#He!==e){if(this.#He!==void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive source read check must be bound before execution");this.#He=e}}withArchiveSourceObservation(e){let n=this.#h,i=this.#H,o=this.#b;return El(this,()=>rn(this.#u,this.#h,this.#xe),()=>{if(this.#R||this.#W||this.#S!==void 0||this.#M!==null||this.#A!==null||this.#_||this.#$!==null||this.#ge!==void 0||this.#l?.busy||this.#Ce.size>0||!this.#re.isSettled()||this.#Fe||this.#h!==n||this.#H!==i||this.#b!==o||this.#He!==void 0&&this.#He()!==!0)throw new Error("Archive source observation requires an idle, settled session")},e)}archiveHistoryObservation(){return rn(this.#u,this.#h,this.#xe)}assertArchiveContextMaterialsAvailable(){if(this.#b===void 0)throw new Error("Archive context materials require the original context manager")}bindArchiveHistoryPort(e,n,i){if(!(this.#x===e&&this.#Ve===n)){if(this.#x!==void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive history port must be bound before execution");this.#x=e,this.#Ve=n,this.#tt=i}}bindArchiveColdHistory(e){if(this.#Be!==e){if(this.#Be!==void 0||this.#x===void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive cold history initializer must be bound before execution");this.#Be=e}}bindArchiveHistoryCommit(e){if(this.#Ue!==e){if(this.#Ue!==void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive commit must be bound before execution");this.#Ue=e}}bindArchiveLineage(e){if(this.#Z)throw new Error("Archive lineage already installed");if(this.status()!=="idle"||!this.#x)throw new Error("Archive lineage requires original idle history");let n=this.#x.read();if(!n.confirmedCommit)throw new Error("Archive lineage requires confirmed Store");let i=e.read(n.confirmedCommit.commitId,n.observation.sourceSnapshotDigest,this.#h.length);this.#Z=e,this.#Le=i?.baselineSequence??e.head()?.sequence??"0",this.#Me=i?.origins??this.#h.map(()=>({recordIds:[],throughSequence:this.#Le==="0"?null:this.#Le})),i||e.write(lf({history:this.#h,rewritten:!1,commitId:n.confirmedCommit.commitId,observation:n.observation},"installation",this.#Le,e.retentionRevision(),this.#Me)),this.#Oe.set(this.#h,{origins:this.#Me,workId:i?.workId??"installation"})}archiveHistoryLineage(){if(!this.#Z||!this.#x||this.status()!=="idle")throw new Error("Archive lineage unavailable");let e=this.#x.read();if(!e.confirmedCommit)throw new Error("Archive Store is unconfirmed");let n=this.#Z.read(e.confirmedCommit.commitId,e.observation.sourceSnapshotDigest,this.#h.length);if(!n)throw new Error("Archive lineage unsupported");return n}#gt=e=>{if(this.#Z){let n=this.#Oe.get(e.history)??{workId:e.commitId,origins:e.history.map(()=>({recordIds:[],throughSequence:this.#Z.head()?.sequence??null}))};this.#Z.write(lf(e,n.workId,this.#Le,this.#Z.retentionRevision(),n.origins)),this.#Me=n.origins,this.#Oe.set(e.history,n)}return this.#Ue(e)};ownsArchiveHistoryCommit(){return this.#l!==void 0}async retryArchiveLifecycle(){if(this.#l===void 0||this.#_||this.#A!==null||this.#ge!==void 0)return!1;try{return await this.#l.retry()}finally{this.#Ae()}}withArchiveBinding(e){return this.#st(e)}withArchiveCommittedRead(e){try{if(this.withArchiveSourceObservation(()=>{}),this.#l===void 0||this.#x===void 0)throw new Error("Archive committed read requires installed history");return this.#st(e,void 0,!0)}catch(n){return Promise.reject(n)}}withArchiveColdBinding(e,n){return e===void 0?Promise.reject(new Error("Archive cold binding requires a confirmation")):this.#st(n,e)}#st(e,n,i=!1){if(this.status()!=="idle")return Promise.reject(new Error("Archive binding requires an idle session"));let o=this.#ue.signal,s=!0,a=Promise.resolve().then(async()=>{if(i||(await In(this.#Xe(),o),this.#ke!==void 0&&await In(this.#ke(),o)),o.aborted||this.#R||this.#W)throw new Error("Archive binding cancelled");!i&&n===void 0&&this.#Ve!==void 0&&(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime,!0),this.#ze=!0,await In(this.#Ve(),o));let d=c=>{if(o.aborted||this.#R||this.#W||this.#S!==void 0||this.#M!==null||this.#A!==null)throw new Error("Archive binding cancelled");let l=this.#h,f=this.#H,u=this.#b,m=rn(this.#u,l,f),g=!1,h=this.#l,p=this.#O,v=this.#G,b=()=>{if(g&&(this.#l!==h||this.#O!==p||this.#G!==v)||!s||o.aborted||this.#R||this.#W||this.#h!==l||this.#H!==f||this.#b!==u||this.#M!==null||rn(this.#u,this.#h,f).sourceSnapshotDigest!==m.sourceSnapshotDigest)throw new Error("Archive binding source changed")};b();let R={observation:m,signal:o,assertCurrent:b,...this.#x===void 0?{}:{historyPort:this.#x}};if(c!==void 0){if(this.#Be===void 0)throw new Error("Archive cold history initializer unavailable");this.#Be(c),this.#ze=!0,b()}let w=()=>{let x=Tl(e(R));if(i)return(async()=>{let M=await x.value;if(b(),Object.keys(x).some(W=>W!=="value"))throw new Error("Archive committed read cannot install state");return M})();x.installation!==void 0&&Pl(x.installation,{lease:R,storeIdentity:this.#x?.storeIdentity,contextMaterials:x.contextMaterials??this.#G});let T=x.installation!==void 0&&this.#l!==void 0;if(x.lifecycle!==void 0){if(!T&&(this.#l!==void 0||this.#O!==void 0)||x.capture!==void 0||this.#Ue===void 0||this.#x===void 0)throw new Error("Complete archive lifecycle requires exclusive factory ownership");if(x.contextMaterials!==void 0&&this.#G!==void 0&&x.contextMaterials!==this.#G)throw new Error("Archive binding cannot replace existing ownership");if(b(),T){if(g=!0,xl(x.lifecycle,{lease:R,storeIdentity:this.#x.storeIdentity})!==this.#l.runtime)throw new Error("Archive installation runtime ownership changed")}else{let M=Rl(x.lifecycle,{lease:R,storeIdentity:this.#x.storeIdentity});this.#l=new ld(M,this.#x,this.#gt),this.#O=M.capture,x.contextMaterials!==void 0&&(this.#G=x.contextMaterials)}return x.installation!==void 0&&(h=this.#l,p=this.#O,v=this.#G,g=!0,kl(x.lifecycle,{lease:R,storeIdentity:this.#x.storeIdentity,runtime:this.#l.runtime}),Ml(x.installation,x.lifecycle,R,this.#G),b()),x.value}if(b(),x.capture!==void 0&&this.#O!==void 0&&x.capture!==this.#O||x.contextMaterials!==void 0&&this.#G!==void 0&&x.contextMaterials!==this.#G)throw new Error("Archive binding cannot replace existing ownership");return Al(x.capture),b(),x.capture!==void 0&&(this.#O=x.capture),x.contextMaterials!==void 0&&(this.#G=x.contextMaterials),x.value};return c===void 0?w():_l(c,R,w)};if(n===void 0)return d();if(this.#x===void 0||this.#Be===void 0)throw new Error("Archive cold binding requires original factory history");return In(Cl(n,{storeIdentity:this.#x.storeIdentity,sessionId:this.#u},(c,l)=>d(l)),o)}).finally(()=>{if(s=!1,this.#$===a&&(this.#$=null),So(this.#x?.storeIdentity,this.#u,this.#l?.runtime)){this.#R&&this.#Se();return}if(this.#l!==void 0){this.#Ae();return}let d=this.#q;this.#q=[],this.#R?this.#Se():d.length>0&&this.#M===null&&this.#we(d)});return this.#$=a,a}withArchiveDetachment(e){if(this.status()!=="idle"||this.#x===void 0||this.#tt===void 0)return Promise.reject(new Error("Archive detachment requires an idle registered session"));wl(this.#x.storeIdentity,this.#u);let n=this.#ue.signal,i=!0,o=Promise.resolve().then(async()=>{if(await In(this.#Xe(),n),this.#ke!==void 0&&await In(this.#ke(),n),this.#l!==void 0&&await In(this.#l.settle(),n),this.#G!==void 0&&(await In(this.#G.settle(),n)).status!=="completed")throw new Error("Archive retirement requires settled materials");if(this.#O!==void 0&&xc(this.#O),this.#Fe)throw new Error("Archive retirement requires settled inputs");let s=this.#h,a=this.#H,d=this.#b,c=this.#l,l=this.#O,f=this.#G,u=this.#x;if(c===void 0?l!==void 0||f!==void 0:l!==c.runtime.capture)throw new Error("Archive detachment cannot remove foreign resources");let m=this.#tt,g=rn(this.#u,s,a),h=()=>{if(!i||n.aborted||this.#R||this.#W||this.#S!==void 0||this.#M!==null||this.#A!==null||this.#h!==s||this.#H!==a||this.#b!==d||this.#l!==c||this.#O!==l||this.#G!==f||this.#x!==u||rn(this.#u,this.#h,a).sourceSnapshotDigest!==g.sourceSnapshotDigest)throw new Error("Archive detachment source changed")};return Il({observation:g,signal:n,assertCurrent:h,historyPort:u},{runtime:c?.runtime??null,contextMaterials:f,prepareDetach:()=>{h(),m.detach(),m.assertDetached()},detachOwnedState:()=>{this.#l=void 0,this.#O=void 0,this.#G=void 0,this.#ze=!1,this.#x=void 0},assertDetached:()=>{if(this.#l!==void 0||this.#O!==void 0||this.#G!==void 0||this.#ze||this.#x!==void 0)throw new Error("Archive detachment is incomplete")}},e)}).finally(()=>{if(i=!1,this.#$===o&&(this.#$=null),So(this.#x?.storeIdentity,this.#u,this.#l?.runtime))return;if(this.#l!==void 0){this.#Ae();return}let s=this.#q;this.#q=[],this.#R?this.#Se():s.length>0&&this.#M===null&&this.#we(s)});return this.#$=o,o}bindSessionCapture(e){if(this.#O!==e){if(this.#O!==void 0||this.#oe!==0||this.#A!==null||this.#$!==null||this.#R)throw new Error("Session capture must be bound once before execution");this.#O=e}}bindContextMaterials(e){if(this.#G!==e){if(this.#G!==void 0||this.#oe!==0||this.#A!==null||this.#$!==null||this.#R)throw new Error("Context materials must be bound once before execution");this.#G=e}}awaitCaptureReady(){return this.#O?.awaitReady(this.#ue.signal)}prepareHistoryRestore(){let e=this.#O;if(e!==void 0)return e.awaitReady(this.#ue.signal).then(()=>{let n=this.#h,i=this.#H,o=this.#b;return wr({capture:e,messages:n,signal:this.#ue.signal,isCurrent:()=>!this.#R&&!this.#W&&this.#M===null&&this.#A===null&&this.#h===n&&this.#H===i&&this.#b===o,onPending:s=>this.#re.track(s.then(()=>{},()=>{}))})})}compactIdle(e={}){if(this.#ae)return Promise.reject(new Error("Archive deletion blocks compaction"));if(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ui(this.#x?.storeIdentity,this.#u,this.#l?.runtime),this.#R||this.#W)return Promise.resolve({status:"rejected",reason:"session_ended"});if(this.#S||this.#M!==null||this.#_||this.#l?.busy||this.#$!==null)return Promise.resolve({status:"rejected",reason:"turn_running"});if(this.#A!==null)return this.#A.promise;let n=this.#ft(),i=this.#b;if(n===void 0||i===void 0)return Promise.resolve({status:"rejected",reason:"not_configured"});if(this.#h.length===0)return Promise.resolve({status:"rejected",reason:"empty_history"});let o=new AbortController,s=this.#l===void 0?this.#re.register(i):()=>{},d=(async()=>(await this.#f?.beginTurn(),this.#yt(o,n,i,e)))().finally(()=>{if(s(),this.#A=null,this.#l!==void 0){this.#Ae();return}let c=this.#q;this.#q=[],this.#R?this.#Se():c.length>0&&this.#M===null&&this.#we(c)});return this.#A={promise:d,ac:o},this.#re.track(this.#O===void 0?d.then(()=>{}):d.then(()=>{},()=>{})),d}async#yt(e,n,i,o){let s=this.#H,a=this.#h,d=this.#a,c=this.#O,l=this.#l,f=this.#Z?Pp(a):void 0,u=l?.beginRewrite("compaction",{signal:AbortSignal.any([e.signal,this.#ue.signal]),history:a,resources:i,assertCurrent:()=>{if(e.signal.throwIfAborted(),this.#ue.signal.throwIfAborted(),this.#h!==a||this.#H!==s||this.#b!==i||this.#a!==d)throw new Error("Archive compaction source changed")}}),m;try{let g=this.#ee,h=g!==void 0&&o.checkpoint!==!1?v=>g(v,{trigger:"manual",...o.checkpoint!==void 0?{checkpoint:o.checkpoint}:{}}):void 0,p=await ud({manager:i,compaction:n,view:{system:d,messages:a,tools:this.#k},model:this.#j,...this.#C!==void 0?{contextWindowTokens:this.#C}:{},...o.instructions!==void 0?{instructions:o.instructions}:{},...h!==void 0?{beforeCompact:h}:{},hooks:this.#ht([]),signal:e.signal,onAbandonedUsage:v=>{for(let b of v)this.pushBody(b,"server")},...c===void 0?{}:{sessionCapture:c,...u===void 0?{}:{governanceCapture:u.ticket.governanceCapture,beforePublish:async(v,b)=>{if(f&&this.#Z){let R=f(b);if(rn(this.#u,R.messages,0).sourceSnapshotDigest!==rn(this.#u,v,0).sourceSnapshotDigest)throw new Error("Archive compaction lineage changed");this.#Oe.set(v,{origins:Vy(R,this.#Me,this.#Z.head()),workId:u.ticket.rewriteId})}m=await l.persistRewrite(u,v)},commitPrepared:((v,b)=>{let R;return m(()=>{R=b()}),R})},isCurrent:()=>!this.#R&&!this.#W&&this.#H===s&&this.#h===a&&this.#a===d&&this.#b===i,publishHistory:v=>{this.#h=v,this.#H+=1,this.#xe+=1},onPending:v=>this.#re.track(v.then(()=>{},()=>{}))}}).catch(v=>{if(c!==void 0&&(this.#R||this.#W))return{status:"rejected",reason:"session_ended",events:[]};throw v});if(this.#R||this.#W){for(let v of p.events)v.type==="cost.usage.updated"&&this.pushBody(v,"server");return{status:"rejected",reason:"session_ended"}}if(p.status==="compacted"){c===void 0&&(this.#h=Object.freeze(structuredClone(p.messages)),this.#H+=1,this.#xe+=1);for(let v of p.events)this.pushBody(v,"server");return this.#_e=this.#fe-1,{status:"compacted",outcome:p.outcome,...p.outcome.checkpointId!==void 0?{checkpointId:p.outcome.checkpointId}:{}}}for(let v of p.events)this.pushBody(v,"server");return p.status==="failed"?{status:"failed",outcome:p.outcome}:{status:"rejected",reason:p.reason}}finally{u!==void 0&&await l.endRewrite(u)}}withArchiveRestore(e,n=!1,i){if(this.#ae&&!n)throw new Error("Archive deletion blocks checkpoint restoration");ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ui(this.#x?.storeIdentity,this.#u,this.#l?.runtime);let o=this.#l;if(o===void 0)return;if(this.status()!=="idle")return Promise.reject(new Error("Archive restore requires an idle session"));let s=this.#h,a=this.#H,d=this.#b,c=this.#ue.signal,l=()=>!this.#R&&!this.#W&&this.#h===s&&this.#H===a&&this.#b===d,f=o.beginRewrite("restore",{signal:c,history:s,resources:new br,assertCurrent:()=>{if(c.throwIfAborted(),!l())throw new Error("Archive restore source changed")}}),u=(async()=>{try{let m=await wr({capture:f.ticket.governanceCapture,messages:s,signal:c,isCurrent:l});return await e(async(g,h)=>{m.assertSourceCurrent();let p=Object.freeze(structuredClone([...g]));i&&this.#Oe.set(p,{origins:i,workId:h});let v=this.#rt(!0),b=await o.persistRewrite(f,p);return m.assertSourceCurrent(),b(()=>{this.#h=p,this.#H++,this.#xe++,this.#T.reset(),this.#b=v,this.#F!==void 0&&this.#b===void 0&&this.invalidateAttachmentReferences(),m.accept()}),this.pushBody({type:"session.restored",checkpointId:h,fromMessages:s.length,toMessages:g.length},"server"),this.#_e=this.#fe-1,{status:"restored",fromMessages:s.length,toMessages:g.length}})}finally{await o.endRewrite(f)}})().finally(()=>{this.#ge=void 0,this.#Ae()});return this.#ge=u,u}beginArchiveDeletion(){if(!this.#ae){if(this.status()!=="idle"||!this.#l)throw new Error("Archive deletion requires an idle captured session");this.#$e=Math.max(this.#$e,this.#fe),this.#ae=!0,this.#q=[]}}clearArchiveHistoryForDeletion(e){return this.#ae?this.withArchiveRestore(n=>n([],e),!0)??Promise.reject(new Error("Archive deletion requires original lifecycle")):Promise.reject(new Error("Archive deletion has no admission barrier"))}removeArchiveHistoryForDeletion(e,n){if(!this.#ae||!this.#Z)return Promise.reject(new Error("Archive partial deletion has no barrier"));let i=this.archiveHistoryLineage(),o=[...n];return new Set(o).size!==o.length||o.some((s,a)=>!Number.isSafeInteger(s)||s<0||s>=this.#h.length||a>0&&s<=o[a-1])?Promise.reject(new Error("Invalid archive retained indices")):this.withArchiveRestore(s=>s(o.map(a=>this.#h[a]),e),!0,o.map(s=>i.origins[s]))??Promise.reject(new Error("Archive partial deletion requires original lifecycle"))}completeArchivePartialDeletion(){if(!this.#ae||!this.#Z||!this.#l?.ready()||this.status()!=="idle")throw new Error("Archive deletion is not settled");this.archiveHistoryLineage(),this.#ae=!1}restoreHistory(e,n,i){if(this.#ae)throw new Error("Archive deletion blocks history restoration");if(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ui(this.#x?.storeIdentity,this.#u,this.#l?.runtime),this.#R||this.#W)return{status:"rejected",reason:"session_ended"};if(this.#S!==void 0||this.#M!==null||this.#A!==null||this.#_||this.#l?.busy||this.#$!==null)return{status:"rejected",reason:"turn_running"};if(this.#O?.assertReady(),this.#O!==void 0&&i===void 0)throw new Error("Captured restore requires prepared original history");i?.assertSourceCurrent();let o=Object.freeze(structuredClone([...e])),s=this.#rt(!0);i?.assertSourceCurrent();let a=this.#h.length;return this.#h=o,this.#H+=1,this.#xe+=1,this.#T.reset(),this.#b=s,this.#F!==void 0&&this.#b===void 0&&this.invalidateAttachmentReferences(),i?.accept(),this.pushBody({type:"session.restored",checkpointId:n,fromMessages:a,toMessages:e.length},"server"),this.#_e=this.#fe-1,{status:"restored",fromMessages:a,toMessages:e.length}}get cwd(){return this.#o}bindCwdRebinder(e){this.#i=e}setCwd(e){if(this.#R||this.#W)return{status:"rejected",reason:"session_ended"};if(this.#S!==void 0||this.#M!==null||this.#A!==null||this.#_||this.#l?.busy||this.#$!==null)return{status:"rejected",reason:"turn_running"};this.#O?.assertReady();let n=this.#o;if(e===n)return{status:"changed",from:n,to:e};let i=this.#i;return i===void 0?{status:"rejected",reason:"unsupported"}:(this.#t=i(e,this.#t),this.#F!==void 0&&this.invalidateAttachmentReferences(),this.#o=e,this.#H+=1,this.pushBody({type:"session.cwd_changed",from:n,to:e},"server"),{status:"changed",from:n,to:e})}#Se(){if(!this.#W){if(this.#W=!0,this.pushBody({type:"session.ended"},"server"),this.#s.end(),this.#nt!==void 0)try{this.#nt(this.#fe-1)}catch(e){this.#qe("onEnded",e)}if(this.#pe!==void 0)try{let e=Promise.resolve(this.#pe()).catch(n=>{throw this.#qe("onClosed",n),n});this.#re.track(e)}catch(e){this.#qe("onClosed",e),this.#re.track(Promise.reject(e))}this.#pt()}}#vt(e){this.#mt({...e,seq:this.#fe++})}#mt(e){if(e.type==="cost.usage.updated"&&e.agentId===void 0&&e.toolUseId===void 0&&typeof e.provider=="string"&&(e.purpose===void 0||e.purpose==="main")){let i={provider:e.provider,model:e.model};this.#e={model:i,observedAt:e.ts,evidence:"usage"},this.#n={model:i,observedAt:e.ts,usage:structuredClone(e.usage)}}e.type==="cost.provider.switched"&&(this.#r={from:e.from,to:e.to,observedAt:e.ts});let n;if(this.#Re!==void 0)try{this.#Re(e)}catch(i){n={err:i}}this.#s.push(e),n!==void 0&&this.#qe("onEvent",n.err)}#qe(e,n){if(this.#ut+=1,!(this.#it||this.#W)){this.#it=!0;try{this.pushBody({type:"turn.error",scope:"server",message:Xy(Yy.callbackFailed,{callback:e,message:fd(n)},`Assembly callback ${e} threw (${fd(n)}); the session continues.`),recoverable:!0,errorKind:"callback_error"},"server")}finally{this.#it=!1}}}#We(e,n){try{n()}catch(i){this.#qe(e,i)}}#ht(e){if(this.#Ie!==void 0)try{return this.#Ie(e)}catch(n){this.#qe("queryHooks",n);return}}#Ae(){if(this.#R&&this.#M===null&&this.#A===null&&this.#ge===void 0&&!this.#_){this.#Se();return}if(So(this.#x?.storeIdentity,this.#u,this.#l?.runtime)||this.#S!==void 0||this.#M!==null||this.#A!==null||this.#ge!==void 0||this.#$!==null||this.#_||!this.#l?.ready()||this.#q.length===0)return;let e=[...this.#q];try{this.#we(e),this.#q.splice(0,e.length),this.#Fe=!1,this.#et=void 0}catch(n){this.#Fe=!0,this.#et=n}}#we(e){let n=this.#p;if(this.#w=n?.deadline??(this.#Pe===void 0?void 0:(this.#f?.now?.()??Date.now())+this.#Pe),this.#ae)throw new Error("Archive deletion blocks new runs");if(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ui(this.#x?.storeIdentity,this.#u,this.#l?.runtime),n?.archive){if(!this.#l)throw new Qt("reconciliation_required");Js(n)}else this.#l?.assertReady();let i=this.#O===void 0?void 0:this.#h.length,o=n?.query.messages??[...this.#h,...e.map(p=>typeof p=="string"?{role:"user",blocks:[{t:"text",text:p}]}:p)],s=e.map(p=>typeof p=="string"?p:p.blocks.flatMap(v=>v.t==="text"?[v.text]:[]).join(`
|
|
23
|
+
`));this.#De=[],this.#oe=n?.turn??this.#oe+1,this.#Ke=[],this.#Qe=!1,this.#Ge=n?.archive!==void 0&&he(n.query.messages.slice(0,this.#h.length))!==he(this.#h);let a=this.#oe;if(n===void 0&&this.#l===void 0&&this.#se!==void 0){let p=this.#se;this.#We("onTurnStart",()=>p(a,s))}let d=this.#ht(s),c={client:this.#y,executor:this.#t,system:this.#a,tools:this.#k,model:this.#j,maxTokens:this.#Y,...this.#D!==void 0?{maxOutputTokens:this.#D}:{},maxTokensEscalation:{ceilingTokens:Ep},...this.#I!==void 0?{thinking:this.#I}:{},sessionId:this.#u,initialMessages:o,...this.#m===void 0?{}:{recovery:{scope:this.#F??this.#u,...n===void 0?{}:{resume:n.query},...n===void 0||this.#d===void 0?{}:{prepare:async p=>{await this.#d(p)}},checkpoint:p=>{let v=this.#T.historyEpoch(),b=this.#oe,R=this.#l===void 0?void 0:this.#x?.read().confirmedCommit;if(this.#l&&!R)throw new Qt("reconciliation_required");return this.#m({query:p,historyEpoch:v,turn:b,...R===void 0?{}:{archive:{version:1,history:n?.archive?.history??R,messages:structuredClone(this.#h),queryDigest:ut(he(p)),historyEpoch:v,turn:b}},...this.#w===void 0?{}:{deadline:this.#w}},this.#v?.())},leaveCheckpoint:()=>this.#f.beginTurn()}},...this.#Z?{observeHistorySources:!0}:{},...this.#O===void 0?{}:{sessionCapture:this.#O,sessionCaptureInputStart:i},...this.#G!==void 0?{contextMaterials:this.#G}:{},...this.#me!==void 0?{onInputsConsumed:p=>{this.#We("onInputsConsumed",()=>this.#me?.(p.map(v=>v.text)))}}:{},...this.#C!==void 0?{contextWindowTokens:this.#C}:{},...this.#L!==void 0&&this.#b!==void 0?{...this.#v===void 0?{}:{onReportedUsage:p=>{if(p.purpose!=="compaction")return;let v=Hi({messages:[],transform:{ops:[],usage:p.usage},usageAttribution:{model:{model:p.model,provider:p.provider},contextWindowTokens:this.#C}});for(let b of v.events)this.pushBody(b,"server")}},compaction:{...this.#ft(),manager:this.#b,...this.#ee!==void 0?{beforeCompact:this.#ee}:{}}}:{},...this.#K!==void 0?{maxTurns:this.#K}:{},...this.#P===void 0?{}:{temperature:this.#P},...this.#Q===void 0?{}:{stopSequences:[...this.#Q]},...this.#ne===void 0?{}:{maxToolRounds:this.#ne},...this.#V===void 0?{}:{maxConsecutiveErrors:this.#V},...this.#de!==void 0?{reminders:this.#de}:{},...this.#ce!==void 0?{sessionEvents:this.#ce}:{},...this.#X!==void 0?{budget:this.#X}:{},...this.#ye!==void 0?{toolResultBudget:this.#ye}:{},...d!==void 0?{hooks:d}:{},...this.#ve!==void 0?{requestMeasurement:this.#ve}:{},...this.#Ze!==void 0?{queryTimeouts:this.#Ze}:{}},l,f,u=p=>{let v=n?.archive?this.#l.runtime.run.resumeRun(n.query.capture):this.#l?.runtime.run.planRun({turnId:Jy(),onAdmitted:()=>{this.#se!==void 0&&this.#We("onTurnStart",()=>this.#se(a,s))}}),b=this.#je(v===void 0?p:{...p,turnId:v.turnId});if(this.#ze){let R=this.#re.registerWithReceipt(b);l=R.markEventsEnded,v!==void 0&&(v.bindQuery({handle:b,receipt:R.receipt}),f={ticket:v,query:b,events:n?.archive?b.events:v.armUnadmittedInput({capture:this.#O,inputStart:i})})}else l=this.#re.register(b);return b},m,g=n!==void 0||this.#d===void 0?u(c):Ka({sessionId:this.#u,history:this.#h,prepare:async p=>(m=await this.#d(p),m),start:p=>{n!==void 0&&(p=this.#a),p.length===this.#a.length&&p.every((R,w)=>{let x=this.#a[w];return x?.text===R.text&&x.cacheable===R.cacheable&&x.label===R.label})||this.#b?.invalidateRequestBasis();let b=m===void 0?void 0:this.#c?.get(m);return b!==void 0&&this.#c.set(p,b),this.#a=p,u({...c,system:p})},...this.#l===void 0?{}:{eventsFor:p=>f?.query===p?f.events:p.events},errorScope:"server"});this.#M=g,this.#T.bind(g),n!==void 0&&(this.#T.restoreIdentity(n.historyEpoch,n.query.inputs),this.#p=void 0),this.#bt(g);let h=this.#St(g,a,()=>f,()=>l?.()).catch(p=>this.#wt(g,p)).finally(()=>l?.());this.#Ce.add(h),this.#re.track(h),h.then(()=>{this.#Ce.delete(h)},()=>{this.#Ce.delete(h)})}#bt(e){if(this.#at(),this.#Pe===void 0)return;let n=this.#f?.now?.()??Date.now(),i=Math.max(0,(this.#w??n+this.#Pe)-n);if(i===0){e.abort("timeout");return}let o=setTimeout(()=>{this.#Ne=null,this.#M===e&&e.abort("timeout")},i);o.unref?.(),this.#Ne=o}#at(){this.#Ne!==null&&clearTimeout(this.#Ne),this.#Ne=null}async#St(e,n,i,o){let s=!1,a=!1,d;try{let c=i();for await(let l of c?.query===e?c.events:e.events)this.#l!==void 0&&(l.type==="turn.completed"||l.type==="turn.aborted")&&(this.#_=!0),l.type==="turn.completed"&&(a=l.reason==="completed"||l.reason==="structured_output"),l.type==="turn.aborted"&&l.reason==="hook_stopped"&&(s=e.counters().modelTurns===0),l.type==="tool.proposed"&&this.#Ke.push(l.name),l.type==="turn.aborted"&&(this.#Qe=!0,d=l.reason),(l.type==="session.compacted"||l.type==="session.microcompacted")&&(this.#Ge=!0),this.#vt(l)}finally{this.#l!==void 0&&o(),this.#at(),this.#_=!0,this.#T.finish(e);let c=e.counters().queueInjections,l=a?this.#De.slice(c):[];if(this.#l!==void 0){let f=i();this.#M=null,this.#De=[],this.#q.unshift(...l);try{if(f!==void 0){let u=this.#Z&&!s?Mp(f.query):void 0;if(this.#Z&&!s&&!u)throw new Error("Archive query source snapshot unavailable");let m=s?this.#h:Object.freeze(u?[...u.messages]:e.messages());if(this.#Z&&u){let h=f.ticket.status();if(!h.captureRunKey)throw new Error("Archive captured run source unavailable");let p=this.#Z.turnRecord(h.captureRunKey,h.turnId),v=Wy(u,this.#Me,p,this.#Z.head(),this.#Ge);this.#Oe.set(m,{origins:v,workId:h.captureRunKey})}let g={turn:n,history:m,toolNames:[...this.#Ke],aborted:this.#Qe,...d===void 0?{}:{abortReason:d},isCurrentTurn:()=>this.#oe===n,system:this.#a,rewritten:this.#Ge};await this.#l.finishTurn(f,m,g.rewritten,()=>{this.#h=m,this.#H++,this.#xe++,this.#_e=this.#fe-1,!s&&this.#le!==void 0&&this.#We("onTurnEnd",()=>{this.#F!==void 0&&(g.attachmentCheckpoint=this.attachmentCheckpoint(m)),g.attachmentSourceCheckpoint=this.attachmentSourceCheckpoint(m),g.memorySelectionCheckpoint=this.memorySelectionCheckpoint(),this.#le(g)})},s)}}finally{this.#_=!1,this.#Ae()}}else{if(!s&&(this.#h=Object.freeze(e.messages()),this.#H+=1,this.#xe+=1,this.#_e=this.#fe-1,this.#le!==void 0)){let u=this.#le,m={turn:n,history:this.#h,toolNames:[...this.#Ke],aborted:this.#Qe,...d===void 0?{}:{abortReason:d},isCurrentTurn:()=>this.#oe===n,system:this.#a,rewritten:this.#Ge};this.#We("onTurnEnd",()=>{this.#F!==void 0&&(m.attachmentCheckpoint=this.attachmentCheckpoint(m.history)),m.attachmentSourceCheckpoint=this.attachmentSourceCheckpoint(m.history),m.memorySelectionCheckpoint=this.memorySelectionCheckpoint(),u(m)})}this.#M=null,this.#De=[],this.#_=!1;let f=[...l,...this.#q.splice(0)];this.#R?this.#Se():f.length>0&&this.#we(f)}}}#wt(e,n){this.#W||this.pushBody({type:"turn.error",scope:"server",message:Xy(Yy.pumpFailed,{message:fd(n)},`Internal error in the session driver (${fd(n)}); this turn was terminated.`),recoverable:!1,errorKind:"internal_error"},"server"),this.#M===e&&(this.#_=!1,this.#T.finish(e),this.#M=null,this.#De=[],this.#at()),this.#R&&!this.#W&&this.#Se()}},Yy={callbackFailed:"server.v2.session.callback_failed",pumpFailed:"server.v2.session.pump_failed",promptRefreshFailed:"server.v2.session.prompt_refresh_failed"};function Xy(t,e,n){let i=We(t,e);return i===t?n:i}function fd(t){let e=t instanceof Error?t.message:String(t);return lp(e).slice(0,400)}var uf=new WeakMap;function WB(t,e,n){md(t,e);let i={import:Object.freeze({}),restore:Object.freeze({checkpoint:!1})},o=Object.freeze({...n,handle:e});return uf.set(i.import,o),uf.set(i.restore,o),i}function Zo(t,e){let n=uf.get(t);return n&&(n.handle!==e&&jt(),n.assertCurrent()),n}var mf=new WeakMap,pd=new WeakMap,hd=new WeakMap,$k=["withArchiveBinding","withArchiveColdBinding","withArchiveDetachment","archiveHistoryObservation","assertArchiveContextMaterialsAvailable","historySnapshot","bindArchiveHistoryPort","bindArchiveHistoryCommit","bindArchivePersistenceBarrier","bindArchiveColdHistory","prepareArchiveRuntimeRecovery","resumeArchiveRuntime","send","close","status","settleResources"],Kk=$k.map(t=>({key:t,value:di.prototype[t]})),Qk=di.prototype.status;function jt(){throw new Error("Serve archive factory identity or lifecycle mismatch")}function pr(t){(!t||Xo.isProxy(t))&&jt();let e=mf.get(t),n=Object.getOwnPropertyDescriptor(t,"create");return(!e||!n||!("value"in n)||n.value!==e.create)&&jt(),Qh(e.store),e}function es(t){t.inCallback&&(t.reentered=!0,jt())}function ff(t,e,n=[]){es(t),t.inCallback=!0,t.reentered=!1;try{let i=Reflect.apply(e,void 0,n);i!==void 0&&(bp(i),jt()),t.reentered&&jt()}finally{t.inCallback=!1}}function pf(t){(typeof t!="function"||Xo.isProxy(t))&&jt()}function Zy(t,e){let n=t;for(;n!==null;){Xo.isProxy(n)&&jt();let i=Object.getOwnPropertyDescriptor(n,e);if(i!==void 0)return"value"in i||jt(),i.value;n=Object.getPrototypeOf(n)}}function ev(t,e){e!==void 0&&mf.set(t,{factory:t,create:t.create,store:e,inCallback:!1,reentered:!1})}function tv(t,e){let n=mf.get(t);n!==void 0&&es(n);let i=pd.get(e);return i&&i.owner!==pr(t)&&jt(),i}function gd(t){(!t||Xo.isProxy(t)||Kk.some(({key:e,value:n})=>Zy(t,e)!==n))&&jt(),Reflect.apply(Qk,t,[])}function nv(t,e,n,i,o){let s=pd.get(e);(!s||s.owner!==pr(t))&&jt(),gd(i),(n.sessionId!==o.sessionId||n.endUserId!==e.endUserId)&&jt(),hd.set(n,{owner:s.owner,driver:i,handle:n,registration:Object.freeze({...o}),request:s,close:n.close,attempted:!1})}async function VB(t,e,n){let i=pr(t);es(i),(!n||Xo.isProxy(n))&&jt();let o=Object.getOwnPropertyDescriptors(n);for(let g of Reflect.ownKeys(o))(typeof g!="string"||!["mode","assertCurrent","onRegistered"].includes(g)||!("value"in o[g])||!o[g].enumerable)&&jt();let s=o.mode?.value,a=o.assertCurrent?.value,d=o.onRegistered?.value;s!=="fresh"&&s!=="resume"&&jt(),pf(a),d!==void 0&&pf(d);let c=Mn(e,["endUserId"],["prompt","model","profile","labels","budget","tools","clientTools","capabilitiesProfile","resume","thinking","sessionId","cwd","fork"]),{prompt:l,...f}=c;l!==void 0&&typeof l!="string"&&jt();let u=JSON.parse(he(f));(u.fork!==void 0||s==="fresh"!=(u.resume===void 0)||typeof u.endUserId!="string"||u.endUserId.length===0)&&jt();let m={owner:i,mode:s,prompt:l,assertCurrent(){pr(t),ff(i,a),pr(t)},registered(g){this.assertCurrent(),d!==void 0&&ff(i,d,[Object.freeze({...g})]),this.assertCurrent()}};pd.set(u,m);try{return m.assertCurrent(),await Reflect.apply(i.create,t,[u])}finally{pd.delete(u)}}function md(t,e){let n=pr(t),i=hd.get(e);return(!i||i.owner!==n||Zy(e,"close")!==i.close)&&jt(),gd(i.driver),Object.freeze({driver:i.driver,store:n.store,registration:i.registration})}function $B(t,e,n){let i=pr(t);es(i),pf(n),md(t,e);let o=hd.get(e);(o.attempted||o.adoption!==void 0)&&jt(),o.adoption=n}function iv(t){let e=hd.get(t);if(!e)return;let n=e.owner;es(n),e.attempted&&jt(),e.attempted=!0;try{md(n.factory,t),e.adoption||jt(),e.request.assertCurrent(),ff(n,e.adoption),md(n.factory,t),e.request.prompt!==void 0&&e.driver.send(e.request.prompt)}catch(i){try{Reflect.apply(e.close,t,[])}catch(o){throw new AggregateError([i,o],"Archive adoption and original handle close failed")}throw i}}var Jk="<system-reminder>",Yk="</system-reminder>";function rv(t){return t.t==="text"&&t.text.startsWith(Jk)&&t.text.endsWith(Yk)}function Gr(t){let e=[];for(let n of t){if(n.role!=="user"||!n.blocks.some(rv)){e.push(n);continue}let i=n.blocks.filter(o=>!rv(o));i.length!==0&&e.push({...n,blocks:i})}return e}var Ze=class extends Error{code;retryAfterMs;params;detail;constructor(e,n,i={}){super(n),this.name="AgentSessionCreateError",this.code=e,this.retryAfterMs=i.retryAfterMs,this.params=i.params,this.detail=i.detail}};import{randomUUID as Xk}from"node:crypto";var Wr=255;function ts(t){if(!Number.isInteger(t)||t<0||t>Wr)throw new RangeError(`sessionIdShard must be an integer in [0, ${Wr}], got ${String(t)}`)}function hf(t){return ts(t),t.toString(16).padStart(2,"0")}function yd(t,e=Xk){return hf(t)+e().slice(2)}function ov(t){if(t.length<2)return;let e=t.slice(0,2);if(/^[0-9a-fA-F]{2}$/.test(e))return Number.parseInt(e,16)}var vd=class extends Error{cause;constructor(e){super(e instanceof Error?e.message:String(e)),this.name="AdoptFailure",this.cause=e}};function ex(t){switch(t){case"not_found":return 404;case"already_resolved":case"digest_mismatch":return 409;case"expired":return 410}}function gf(t){let{options:e,registry:n,admission:i}=t,o=t.sessionFamily??"sdk1",s=t.sessionFamily?{contract:t.sessionFamily,availability:"source-required"}:{},a=_=>Vi(_)===o,d=t.authenticate??(_=>e.authenticate(_)),c=e.mediaMaxBodyBytes??je.mediaMaxBodyBytes,l=e.sessionIdShard;l!==void 0&&ts(l);let f=async(_,y,P,K=!1)=>{let ee=pi(_,P),G=i.reserveBody(ee);return G.admitted?(y.once("close",()=>i.releaseBody(ee)),xi(_,P,K?Y=>Si(Y,{maxBytes:P}):void 0)):(ni(y,G),"rejected")},u=(_,y,P,K)=>{P==="too_large"?Tr(_,y,Oe.payloadTooLarge,ae.v2PayloadTooLarge,{maxBytes:K}):pe(y,400,Oe.invalidJson,ae.invalidJson)},m=_=>{pe(_,503,Oe.draining,ae.draining,void 0,Ft(i.retryAfterMs))},g=(_,y)=>{pe(_,400,Oe.validationFailed,ae.v2ValidationFailed,{detail:y})},h=(_,y)=>{pe(_,404,Oe.sessionNotFound,ae.sessionNotFound,{sessionId:y})},p=_=>{pe(_,403,Oe.forbidden,ae.v2Forbidden)},v=$n(t.logger),b=(_,y,P)=>{v("error",Xe.storeError,{op:_,code:Oe.storeCorrupted,message:Bn(y),...P!==void 0?{sessionId:P}:{}})},R=(_,y,P,K)=>{v("warn",Xe.sessionRejected,{status:_,code:y,message:Bn(P),...K!==void 0?{sessionId:K}:{}})},w=(_,y,P,K,ee)=>{v("warn",Xe.upstreamRejected,{face:_,sessionId:y,...P!==void 0?{upstreamStatus:P}:{},upstreamCode:K,message:ee,status:503})},x=(_,y,P)=>{if(t.sessionFamily&&y instanceof Wn&&y.kind==="transient"){pe(_,503,"source_unavailable",ae.v2StoreCorrupted);return}b("read",y,P),pe(_,500,Oe.storeCorrupted,ae.v2StoreCorrupted)},T=(_,y,P)=>{let K=P instanceof Error?P.message:String(P);try{t.logger?.error(We(ae.requestUnhandled,{method:y,path:_,message:K}))}catch{}},M=(_,y)=>{try{t.logger?.log?.("warn",Xe.sessionIdHintIgnored,{hintedSessionId:_,sessionId:y,shard:l})}catch{}},W=(_,y,P)=>{try{let K=_.detail??{},ee=G=>{let Y=K[G];return typeof Y=="string"||typeof Y=="number"||typeof Y=="boolean"?Y:void 0};t.logger?.log?.("warn",Xe.sessionRejected,{status:y,code:P,scope:"plan",platformCode:typeof _.params?.code=="string"?_.params.code:void 0,tier:ee("tier"),cap:ee("cap"),hardCap:ee("hardCap"),current:ee("current"),limit:ee("limit"),used:ee("used"),retryAfterMs:_.retryAfterMs,upgradeUrl:ee("upgradeUrl")})}catch{}},$=(_,y,P,K)=>{T(y,P,K);try{if(_.destroyed||_.writableEnded)return;if(!_.headersSent){pe(_,500,Oe.internalError,ae.internalError);return}_.end()}catch{_.destroy()}},D=(_,y,P,K)=>{pe(_,405,Oe.methodNotAllowed,ae.methodNotAllowed,{method:y,path:P},{allow:K})},J=(_,y,P)=>{let K=n.get(y);return K===void 0||!a(K.handle)?"absent":K.handle.endUserId!==P?(p(_),"forbidden"):K},S=async(_,y,P)=>{if(y.destroyed)return!1;let K=new AbortController;Zk(Math.max(10,P.length),K.signal);let ee=()=>K.abort();y.once("close",ee);try{await Promise.all(P.map(({handle:G,lastSeq:Y})=>n.waitForReplayWatermark(G,Y,K.signal)));for(let{handle:G}of P){let Y=n.get(G.sessionId);if(!Y||Y.handle!==G)throw new Error("Event publication identity changed");!Y.ended&&G.status()!=="ended"&&G.owner?.assertCurrent()}return!y.destroyed}catch(G){return K.signal.aborted||(G instanceof hi?m(y):(T(new URL(_.url??"/","http://local").pathname,_.method??"GET",G),pe(y,500,Oe.internalError,ae.internalError))),!1}finally{K.abort(),y.removeListener("close",ee)}},k=_=>{let y=_.handle,P=n.lastActivityAt(y.sessionId)??y.createdAt,K=y.title(),ee=y.mediaState?.();return{...s,sessionId:y.sessionId,endUserId:y.endUserId,status:_.ended?"ended":y.status(),live:!_.ended,lastSeq:y.lastSeq(),createdAt:new Date(y.createdAt).toISOString(),lastActivityAt:new Date(P).toISOString(),...K!==void 0?{title:K}:{},...y.contextState?{context:y.contextState()}:{},...ee?{media:ee}:{}}},A=_=>{let y=_?.lastSeq;return typeof y=="number"&&Number.isSafeInteger(y)&&y>=0?y:0},C=(_,y,P)=>_.getMeta(y,P).then(A),F=(_,y)=>({...s,sessionId:_.sessionId,endUserId:y,status:"ended",live:!1,lastSeq:A(_),createdAt:_.createdAt,lastActivityAt:_.updatedAt,..._.title!==void 0?{title:_.title}:{}}),H=async(_,y,P)=>{let K=await f(_,y,t.maxBodyBytes);if(K==="rejected")return;if(!K.ok){u(_,y,K.reason,t.maxBodyBytes);return}let ee=la.safeParse(K.value);if(!ee.success){g(y,ee.error.issues[0]?.message??"invalid body");return}let G=ee.data,Y;if(G.endUser!==void 0&&G.endUser.id!==P){p(y);return}if(t.sessionFamily&&!G.resume){let Pe=K.value.requestId;if(typeof Pe!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(Pe)||G.fork||!t.prepareCreate){g(y,"offload creation requires requestId");return}try{Y=t.prepareCreate(P,Pe,G)}catch(_e){if(_e instanceof ct){pe(y,_e.code==="rollback_pending"?503:409,_e.code,ae.v2CreateFailed);return}throw _e}if(Y.resume){let{prompt:_e,...L}=G;G={...L,resume:{sessionId:Y.sessionId}}}}if(G.fork!==void 0){if(G.resume!==void 0){g(y,'"fork" and "resume" are mutually exclusive');return}let Pe=n.get(G.fork.sessionId);if(Pe&&!a(Pe.handle)){h(y,G.fork.sessionId);return}if(Pe!==void 0&&Pe.handle.endUserId!==P){p(y);return}}let ve=G.resume?.sessionId;if(ve!==void 0){let Pe=n.get(ve);if(Pe&&!a(Pe.handle)){h(y,ve);return}if(Pe!==void 0){if(Pe.handle.endUserId!==P){p(y);return}if(!Pe.ended){await O(_,y,Pe.handle,()=>Y?.assertCurrent());return}}if(e.store===void 0){pe(y,409,Oe.resumeUnavailable,ae.v2ResumeUnavailable);return}}let fe=await i.rateLimit(_,P);if(!fe.admitted){ni(y,fe);return}let xe=i.tryAdmitSession();if(!xe.admitted){ni(y,xe);return}let be=n.beginCreate(ve??Y?.sessionId,P);if(be.kind==="ticket"){let Pe=be.ticket,_e=Pe.run(()=>Q(Pe,G,Y)),L;try{L=await _e,Y?.assertCurrent()}catch(se){I(y,se,ve);return}let N=L.handle.lastSeq();if(!await S(_,y,[{handle:L.handle,lastSeq:N}]))return;Y?.assertCurrent(),Je(y,201,{...s,sessionId:L.handle.sessionId,resumed:L.resumed,lastSeq:N});return}switch(be.kind){case"live":if(!a(be.handle)){h(y,ve??"");return}try{Y?.assertCurrent()}catch(Pe){I(y,Pe,ve,!1);return}await O(_,y,be.handle,()=>Y?.assertCurrent());return;case"joined":{try{let Pe=await be.outcome;if(Y?.assertCurrent(),!a(Pe.handle)){h(y,ve??"");return}await O(_,y,Pe.handle,()=>Y?.assertCurrent())}catch(Pe){I(y,Pe,ve,!1)}return}case"forbidden":p(y);return;case"closing":m(y);return;case"reserve_rejected":pe(y,429,Oe.sessionLimitExceeded,ae.v2SessionLimit,{max:be.max},Ft(i.retryAfterMs));return}},Q=async(_,y,P)=>{let ee={endUserId:_.endUserId,...y.prompt!==void 0&&y.prompt!==""?{prompt:y.prompt}:{},...y.model!==void 0&&y.model!==""?{model:y.model}:{},...y.profile!==void 0&&y.profile!==""?{profile:y.profile}:{},...y.labels!==void 0?{labels:y.labels}:{},...y.budget!==void 0?{budget:y.budget}:{},...y.tools!==void 0?{tools:y.tools}:{},...y.clientTools!==void 0?{clientTools:y.clientTools}:{},...y.capabilitiesProfile!==void 0?{capabilitiesProfile:y.capabilitiesProfile}:{},...y.resume!==void 0?{resume:y.resume}:{},...y.thinking!==void 0?{thinking:y.thinking}:{},...y.cwd!==void 0?{cwd:y.cwd}:{},...y.fork!==void 0?{fork:y.fork}:{},...l!==void 0&&y.resume===void 0?{sessionId:yd(l)}:{}};P&&!P.resume&&(ee.sessionId=P.sessionId),P?.apply(ee);let G=_.id,Y=await e.createSession.create(ee);if(!a(Y.handle))throw Y.handle.close(),await Y.handle.settleResources?.(),new Error("Session family mismatch");ee.sessionId!==void 0&&Y.handle.sessionId!==ee.sessionId&&M(ee.sessionId,Y.handle.sessionId),G!==void 0&&n.evictEnded(G);try{_.adopt(Y.handle),iv(Y.handle)}catch(ve){throw ve instanceof hi?ve:(T("/v2/sessions","POST",ve),new vd(ve))}return Y},re=_=>({...s,sessionId:_.sessionId,resumed:!1,lastSeq:_.lastSeq()}),O=async(_,y,P,K)=>{let ee=re(P);await S(_,y,[{handle:P,lastSeq:ee.lastSeq}])&&(K(),Je(y,200,ee))},I=(_,y,P,K=!0)=>{if(t.sessionFamily&&y instanceof ct){pe(_,y.code==="rollback_pending"?503:409,y.code,ae.v2CreateFailed);return}if(y instanceof Ze){if(y.code==="session_not_found"){h(_,P??"");return}if(y.code==="resume_unavailable"){pe(_,409,Oe.resumeUnavailable,ae.v2ResumeUnavailable);return}if(y.code==="store_corrupted"){K&&b("create",y,P),pe(_,500,Oe.storeCorrupted,ae.v2StoreCorrupted);return}let ee=Ft(y.retryAfterMs??i.retryAfterMs);if(y.code==="upstream_unavailable"){K&&R(503,Oe.upstreamUnavailable,y,P),pe(_,503,Oe.upstreamUnavailable,ae.v2UpstreamUnavailable,void 0,ee);return}if(y.code==="overloaded"){pe(_,503,Oe.overloaded,ae.overloaded,void 0,ee);return}if(y.code==="plan_limited"){W(y,429,Oe.rateLimited),pe(_,429,Oe.rateLimited,ae.v2PlanConcurrencyLimited,void 0,ee,{scope:"plan"});return}if(y.code==="plan_denied"){let G=typeof y.params?.code=="string"?y.params.code:"plan_required";W(y,403,G),pe(_,403,G,ae.v2PlanDenied,{code:G},void 0,{scope:"plan"});return}if(y.code==="cwd_not_allowed"){pe(_,400,Oe.cwdNotAllowed,wt.cwdNotAllowed,{detail:y.message,...y.params??{}});return}if(y.code==="cwd_invalid"){pe(_,400,Oe.cwdInvalid,wt.cwdInvalid,{reason:"invalid",detail:y.message,...y.params??{}});return}if(y.code==="cwd_unavailable"){let G=y.params?.reason;pe(_,409,Oe.cwdUnavailable,wt.cwdUnavailable,{cwd:y.message,...y.params??{}},void 0,typeof G=="string"?{cwd:y.params?.cwd??y.message,reason:G}:void 0);return}if(y.code==="fork_source_not_found"){pe(_,404,Oe.forkSourceNotFound,wt.forkSourceNotFound,{sessionId:"",checkpointId:"",...y.params??{}});return}if(y.code==="checkpoints_not_wired"){pe(_,409,Oe.checkpointsNotWired,wt.checkpointsNotWired);return}g(_,y.message);return}if(y instanceof hi){m(_);return}if(y instanceof vd){pe(_,500,Oe.internalError,ae.internalError);return}K&&R(400,Oe.createFailed,y,P),pe(_,400,Oe.createFailed,ae.v2CreateFailed)},B=async(_,y,P)=>{let K=new URL(_.url??"/","http://local").searchParams,ee=K.get("limit"),G=K.get("offset"),Y=je.listLimitDefault,ve=0;if(ee!==null){if(!/^\d+$/.test(ee)){g(y,"limit must be a positive integer");return}if(Y=Number.parseInt(ee,10),Y<1||Y>je.listLimitMax){g(y,`limit must be within 1..${je.listLimitMax}`);return}}if(G!==null){if(!/^\d+$/.test(G)){g(y,"offset must be a non-negative integer");return}ve=Number.parseInt(G,10)}let fe=new Map;if(e.store!==void 0){let L;try{L=await e.store.list(P)}catch(N){x(y,N);return}for(let N of L)fe.set(N.sessionId,F(N,P))}let xe=new Map;for(let L of n.entriesFor(P))a(L.handle)&&(fe.set(L.handle.sessionId,k(L)),xe.set(L.handle.sessionId,L.handle));if(t.filterSessionReads){let L=new Set(await t.filterSessionReads(P,[...fe.keys()]));for(let N of fe.keys())L.has(N)||fe.delete(N)}let be=[...fe.values()].sort((L,N)=>N.lastActivityAt.localeCompare(L.lastActivityAt)),Pe=be.slice(ve,ve+Y),_e=Pe.flatMap(L=>{let N=xe.get(L.sessionId);return N?[{handle:N,lastSeq:L.lastSeq}]:[]});if(await S(_,y,_e))if(t.filterSessionReads){let L=new Set(await t.filterSessionReads(P,[...fe.keys()]));Je(y,200,{sessions:Pe.filter(N=>L.has(N.sessionId)),total:be.filter(N=>L.has(N.sessionId)).length})}else Je(y,200,{sessions:Pe,total:be.length})},z=(_,y)=>{try{return y()}catch(P){if(P instanceof xp)return pe(_,503,Oe.overloaded,ae.materialRequired,void 0,Ft(i.retryAfterMs),{scope:"context.materials",reason:P.code}),null;if(!(P instanceof Ss)||P.code!=="capacity_exceeded")throw P;return pe(_,503,Oe.overloaded,ae.overloaded,void 0,Ft(i.retryAfterMs),{scope:"archive",reason:"capacity_exceeded"}),null}},j=async(_,y,P,K)=>{let ee=J(y,P,K);if(ee==="forbidden")return;if(ee==="absent"){h(y,P);return}let G=await f(_,y,c);if(G==="rejected")return;if(!G.ok){u(_,y,G.reason,c);return}let Y=ua.safeParse(G.value);if(!Y.success){g(y,Y.error.issues[0]?.message??"invalid body");return}if(ee.ended){pe(y,409,Oe.sessionEnded,ae.sessionEnded,{sessionId:P});return}if(Y.data.prompt!==void 0){let xe=z(y,()=>ee.handle.send(Y.data.prompt));if(xe===null)return;if(xe==="ended"){pe(y,409,Oe.sessionEnded,ae.sessionEnded,{sessionId:P});return}n.touch(P),Je(y,202,{sessionId:P,accepted:!0});return}let ve={role:"user",blocks:(Y.data.blocks??[]).map(xe=>xe.t==="text"?{t:"text",text:xe.text}:{t:"image",mime:xe.mime,data:xe.data})},fe=z(y,()=>ee.handle.sendMessage(ve));if(fe!==null){if(fe==="midturn"){pe(y,422,Oe.midturnBlocksRejected,ae.v2MidturnBlocks);return}if(fe==="ended"){pe(y,409,Oe.sessionEnded,ae.sessionEnded,{sessionId:P});return}n.touch(P),Je(y,202,{sessionId:P,accepted:!0})}},ne=async(_,y,P,K,ee,G)=>{let Y=J(y,P,K);if(Y==="forbidden")return;if(Y==="absent"){h(y,P);return}let ve=Y.handle;if(ee==="input-capabilities"){Je(y,200,ve.inputCapabilities?.()??{version:1,text:!1,textBlocks:!1,image:!1,memoryAck:!1,durableAck:!1,receiptRetention:"current-and-last-turn",target:null});return}if(G!==void 0){let Pe=new URL(_.url??"/","http://local").searchParams,_e=su.safeParse({historyEpoch:Pe.get("historyEpoch"),turnId:Pe.get("turnId")});if(!_e.success){g(y,_e.error.issues[0]?.message??"invalid target");return}let L=ve.getInputStatus?.(G,_e.data)??null;Je(y,L===null?404:200,L===null?{outcome:"rejected",code:"input_not_found"}:{receipt:L});return}let fe=await f(_,y,c);if(fe==="rejected")return;if(!fe.ok){u(_,y,fe.reason,c);return}let xe=tg.safeParse(fe.value);if(!xe.success){g(y,xe.error.issues[0]?.message??"invalid input");return}if(ve.submitInput===void 0){Je(y,422,{outcome:"rejected",code:"input_unsupported"});return}let be=await ve.submitInput({inputId:xe.data.inputId,target:xe.data.target,content:xe.data.content,...xe.data.ack!==void 0?{ack:xe.data.ack}:{}});be.outcome==="accepted"&&n.touch(P),Je(y,be.outcome==="accepted"?202:be.outcome==="closed"?409:be.code==="injection_limit"?429:be.code==="input_conflict"?409:422,be)},U=(_,y,P,K)=>{let ee=i.tryAdmitSse(K);if(!ee.admitted){ni(y,ee);return}y.once("close",()=>i.releaseSse(K)),t.sseKeepAliveMs>0&&_.socket.setKeepAlive(!0,t.sseKeepAliveMs),_.socket.setTimeout(0);let G=J(y,P,K);if(G==="forbidden")return;if(G==="absent"){h(y,P);return}let Y=oa(_.headers["last-event-id"]);if(Y===void 0){g(y,"invalid Last-Event-ID");return}let ve=new URL(_.url??"/","http://local").searchParams,fe=ma(ve.get("exclude"));if(fe===null){g(y,"invalid exclude tokens");return}y.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no"});let xe=G.handle.firstSeq?.()??0,be=()=>(G.handle.firstSeq?.()??0)===xe,Pe=t.sse.attach(y,{gapFrame:L=>Pr(P,L),beforeFlush:()=>{if(!be())return!1;let L=d(_,y);return t.filterSessionReads?Promise.resolve(L).then(async N=>N?.endUserId===K&&(await t.filterSessionReads(K,[P])).includes(P)&&be()):L!==null&&"then"in L?Promise.resolve(L).then(N=>N?.endUserId===K&&be()):L?.endUserId===K&&be()}}),_e=n.subscribe(P,Y,Pe,fe);y.on("close",()=>{_e?.()})},le=async(_,y,P,K)=>{let ee=new URL(_.url??"/","http://local").searchParams.getAll("include");if(ee.length>1||ee.length===1&&ee[0]!=="applicationPrompt"){g(y,"include must be applicationPrompt and occur once");return}let G=J(y,P,K);if(G==="forbidden")return;if(G!=="absent"){let fe=k(G);if(!await S(_,y,[{handle:G.handle,lastSeq:fe.lastSeq}]))return;let xe=t.readHistoryOrigin?{historyOrigin:await t.readHistoryOrigin(K,P)}:{},be=ee.length===1&&!G.ended&&G.handle.status()!=="ended"?G.handle.applicationPrompt?.():void 0,_e=be!=null&&Object.keys(be).length===2&&(be.policy==="fallback"||be.policy==="prepend")&&["none","platform","sdk","platform+sdk"].includes(be.source)&&!(be.policy==="fallback"&&be.source==="platform+sdk")?{applicationPrompt:{policy:be.policy,source:be.source}}:{};if(t.filterSessionReads&&!(await t.filterSessionReads(K,[P])).includes(P)){h(y,P);return}Je(y,200,{...fe,...xe,..._e});return}let Y;try{Y=await e.store?.getMeta(K,P)}catch(fe){x(y,fe,P);return}if(Y==null){h(y,P);return}let ve=t.readHistoryOrigin?{historyOrigin:await t.readHistoryOrigin(K,P)}:{};Je(y,200,{...F(Y,K),...ve})},ue=async(_,y,P,K)=>{let ee=J(y,P,K);if(ee==="forbidden")return;let G=Zs(new URL(_.url??"/","http://local").searchParams);if(!G.ok){g(y,G.detail);return}let Y=G.page,{offset:ve=0,limit:fe}=Y??{};if(ee!=="absent"){let L=ee.handle.historySnapshot();if(Y===null){Je(y,200,{sessionId:P,lastSeq:L.lastSeq,messages:Gr(L.messages)});return}let N=Kn(L.messages,ve,fe);Je(y,200,{sessionId:P,lastSeq:L.lastSeq,messages:Gr(N.messages),total:N.total,offset:N.offset,nextOffset:N.nextOffset});return}let xe=e.store;if(Y!==null&&fe!==void 0&&xe?.getHistoryPage!==void 0){let L;try{L=await xe.getHistoryPage(K,P,{offset:ve,limit:fe})}catch(se){x(y,se,P);return}if(L===null){h(y,P);return}let N;try{N=await C(xe,K,P)}catch(se){x(y,se,P);return}Je(y,200,{sessionId:P,lastSeq:N,messages:Gr(L.messages),total:L.total,offset:L.offset,nextOffset:L.nextOffset});return}if(xe===void 0){h(y,P);return}let be;try{be=await xe.getHistory(K,P)}catch(L){x(y,L,P);return}if(be===null){h(y,P);return}let Pe;try{Pe=await C(xe,K,P)}catch(L){x(y,L,P);return}if(Y===null){Je(y,200,{sessionId:P,lastSeq:Pe,messages:Gr(be)});return}let _e=Kn(be,ve,fe);Je(y,200,{sessionId:P,lastSeq:Pe,messages:Gr(_e.messages),total:_e.total,offset:_e.offset,nextOffset:_e.nextOffset})},ie=_=>{pe(_,409,Oe.turnRunning,wt.turnRunning)},me=_=>{pe(_,409,Oe.checkpointsNotWired,wt.checkpointsNotWired)},q=(_,y)=>{pe(_,404,Oe.checkpointNotFound,wt.checkpointNotFound,{checkpointId:y})},X=(_,y)=>{pe(_,409,Oe.sessionEnded,ae.sessionEnded,{sessionId:y})},te=(_,y)=>{if(y instanceof et){x(_,y);return}throw y},Se=async(_,y,P,K)=>{let ee=J(y,P,K);if(ee==="forbidden")return;if(ee==="absent"){h(y,P);return}let G=await f(_,y,t.maxBodyBytes);if(G==="rejected")return;if(!G.ok){u(_,y,G.reason,t.maxBodyBytes);return}let Y=ha.safeParse(G.value);if(!Y.success){g(y,Y.error.issues[0]?.message??"invalid body");return}if(ee.ended){X(y,P);return}if(ee.handle.compact===void 0){Je(y,200,{status:"rejected",reason:"not_configured"});return}let ve;try{ve=await ee.handle.compact(Y.data)}catch(fe){te(y,fe);return}if(n.touch(P),ve.status==="rejected"&&ve.reason==="turn_running"){ie(y);return}if(ve.status==="rejected"&&ve.reason==="session_ended"){X(y,P);return}if(ve.status==="rejected"&&ve.reason==="checkpoints_not_wired"){me(y);return}Je(y,200,ve)},Ue=async(_,y,P)=>{let K=J(_,y,P);if(K==="forbidden")return;if(K==="absent"){h(_,y);return}if(K.handle.listCheckpoints===void 0){me(_);return}let ee;try{ee=await K.handle.listCheckpoints()}catch(G){te(_,G);return}if(ee.status==="rejected"){me(_);return}Je(_,200,{checkpoints:ee.checkpoints})},$e=async(_,y,P,K)=>{let ee=J(y,P,K);if(ee==="forbidden")return;if(ee==="absent"){h(y,P);return}let G=await f(_,y,t.maxBodyBytes);if(G==="rejected")return;if(!G.ok){u(_,y,G.reason,t.maxBodyBytes);return}let Y=ga.safeParse(G.value);if(!Y.success){g(y,Y.error.issues[0]?.message??"invalid body");return}if(ee.ended){X(y,P);return}if(ee.handle.checkpoint===void 0){me(y);return}let ve;try{ve=await ee.handle.checkpoint(Y.data)}catch(fe){te(y,fe);return}if(n.touch(P),ve.status==="created"){Je(y,201,ve.checkpoint);return}ve.reason==="turn_running"?ie(y):ve.reason==="session_ended"?X(y,P):me(y)},Fe=async(_,y,P,K,ee)=>{let G=J(y,P,K);if(G==="forbidden")return;if(G==="absent"){h(y,P);return}let Y=await f(_,y,t.maxBodyBytes);if(Y==="rejected")return;if(!Y.ok){u(_,y,Y.reason,t.maxBodyBytes);return}let ve=ya.safeParse(Y.value);if(!ve.success){g(y,ve.error.issues[0]?.message??"invalid body");return}if(G.ended){X(y,P);return}if(G.handle.restore===void 0){me(y);return}let fe;try{fe=await G.handle.restore(ee,ve.data)}catch(xe){te(y,xe);return}if(n.touch(P),fe.status==="restored"){Je(y,200,fe);return}switch(fe.reason){case"turn_running":ie(y);return;case"session_ended":X(y,P);return;case"not_found":q(y,ee);return;case"session_mismatch":pe(y,409,Oe.sessionMismatch,wt.sessionMismatch,{checkpointId:ee});return;case"checkpoints_not_wired":me(y);return}},lt=async(_,y,P,K)=>{let ee=J(_,y,P);if(ee==="forbidden")return;if(ee==="absent"){h(_,y);return}if(ee.handle.deleteCheckpoint===void 0){me(_);return}let G;try{G=await ee.handle.deleteCheckpoint(K)}catch(Y){te(_,Y);return}if(G==="deleted"){_.writeHead(204),_.end();return}G==="not_found"?q(_,K):me(_)},kt=async(_,y,P,K)=>{let ee=J(y,P,K);if(ee==="forbidden")return;if(ee==="absent"){h(y,P);return}let G=await f(_,y,t.maxBodyBytes);if(G==="rejected")return;if(!G.ok){u(_,y,G.reason,t.maxBodyBytes);return}let Y=va.safeParse(G.value);if(!Y.success){g(y,Y.error.issues[0]?.message??"invalid body");return}if(ee.ended){X(y,P);return}let ve=()=>{pe(y,409,Oe.cwdSwitchUnsupported,wt.cwdSwitchUnsupported)};if(ee.handle.setCwd===void 0){ve();return}let fe;try{fe=await ee.handle.setCwd(Y.data.cwd)}catch(be){te(y,be);return}if(n.touch(P),fe.status==="changed"){Je(y,200,{cwd:fe.cwd,from:fe.from});return}let xe=fe.detail??fe.reason;switch(fe.reason){case"turn_running":ie(y);return;case"session_ended":X(y,P);return;case"not_allowed":pe(y,400,Oe.cwdNotAllowed,wt.cwdNotAllowed,{detail:xe});return;case"not_absolute":case"not_found":case"not_directory":pe(y,400,Oe.cwdInvalid,wt.cwdInvalid,{reason:fe.reason,detail:xe});return;case"unsupported":ve();return}},Ge=async(_,y,P,K,ee)=>{let G=J(y,P,K);if(G==="forbidden")return;if(G==="absent"){h(y,P);return}let Y=G.handle.platformAudio;if(Y===void 0){pe(y,409,Oe.platformUnavailable,ae.v2PlatformUnavailable);return}if(G.ended){X(y,P);return}let ve=ee==="transcriptions"?"speechToText":"textToSpeech";if(!Y.capabilities[ve]){pe(y,403,Oe.capabilityDisabled,ae.v2PlatformCapabilityDisabled,{bit:ve});return}let fe=await f(_,y,Mo);if(fe==="rejected")return;if(!fe.ok){u(_,y,fe.reason,Mo);return}let xe=ee==="transcriptions"?wa.safeParse(fe.value):ka.safeParse(fe.value);if(!xe.success){g(y,xe.error.issues[0]?.message??"invalid body");return}let be=new AbortController;y.once("close",()=>{y.writableEnded||be.abort()});let Pe=ee==="transcriptions"?"asr":"tts",_e=await Y.request(Pe,xe.data,be.signal);if(n.touch(P),_e.kind==="transport_error"){w(Pe,P,void 0,"transport_error",_e.message),pe(y,503,Oe.upstreamUnavailable,ae.v2UpstreamUnavailable,void 0,Ft(i.retryAfterMs));return}if(_e.status<200||_e.status>=300){let{code:se,message:ge,detail:qe}=Lu(_e.body,_e.status);if(_e.status===401||_e.status===403||_e.status>=500){w(Pe,P,_e.status,se,ge),pe(y,503,Oe.upstreamUnavailable,ae.v2UpstreamUnavailable,void 0,Ft(i.retryAfterMs));return}pe(y,_e.status,se,ae.v2PlatformAudioRejected,{code:se,message:ge},void 0,qe);return}let L=xe.data.model??"(default)",N=ee==="transcriptions"?go(_e.body,L):vo(_e.body,L);if(N===null){pe(y,503,Oe.upstreamUnavailable,ae.v2PlatformAudioUnexpected,void 0,Ft(i.retryAfterMs));return}Je(y,200,N)},rt=async(_,y,P)=>{let K=pi(_,P),ee=i.reserveBody(K);return ee.admitted?(y.once("close",()=>i.releaseBody(K)),new Promise(G=>{let Y=[],ve=0,fe=!1,xe=Pe=>{fe||(fe=!0,G(Pe))},be=Pe=>{if(ve+=Pe.length,ve>P){Y.length=0,_.off("data",be),_.pause(),xe("too_large");return}Y.push(Pe)};_.on("data",be),_.on("end",()=>xe(new Uint8Array(Buffer.concat(Y)))),_.on("error",()=>xe(new Uint8Array))})):(ni(y,ee),"rejected")},Tt=async(_,y,P,K)=>{let ee=J(_,y,P);if(ee==="forbidden")return;if(ee==="absent"){h(_,y);return}if(ee.handle.exportCheckpoint===void 0){me(_);return}let G;try{G=await ee.handle.exportCheckpoint(K)}catch(Y){te(_,Y);return}if(G.status==="rejected"){G.reason==="not_found"?q(_,K):me(_);return}_.writeHead(200,{"content-type":ba,"content-length":G.bytes.byteLength,"content-disposition":`attachment; filename="${y}-${K}.tansr-checkpoint.json"`}),_.end(Buffer.from(G.bytes.buffer,G.bytes.byteOffset,G.bytes.byteLength))},zt=async(_,y,P,K)=>{let ee=J(y,P,K);if(ee==="forbidden")return;if(ee==="absent"){h(y,P);return}if(ee.handle.importCheckpoint===void 0){me(y);return}if(ee.ended){X(y,P);return}let G=await rt(_,y,Po);if(G==="rejected")return;if(G==="too_large"){Tr(_,y,Oe.payloadTooLarge,ae.v2PayloadTooLarge,{maxBytes:Po});return}let Y=new URL(_.url??"/","http://local").searchParams.get("label");if(Y!==null&&Y.length>Ji){g(y,`label must be at most ${Ji} characters`);return}let ve;try{ve=await ee.handle.importCheckpoint(G,Y!==null&&Y!==""?{label:Y}:{})}catch(fe){te(y,fe);return}if(n.touch(P),ve.status==="imported"){Je(y,201,ve.checkpoint);return}if(ve.reason==="invalid"){pe(y,400,Oe.checkpointImportInvalid,wt.checkpointImportInvalid,{detail:ve.detail});return}ve.reason==="session_ended"?X(y,P):me(y)},gn=(_,y,P)=>{let K=J(_,y,P);if(K!=="forbidden"){if(K==="absent"){h(_,y);return}K.handle.interrupt(),n.touch(y),Je(_,202,{sessionId:y,accepted:!0})}},wn=async(_,y,P)=>{let K=J(_,y,P);if(K==="forbidden")return;if(K!=="absent"){n.requestClose(y),Je(_,202,{sessionId:y,accepted:!0});return}let ee;try{ee=await e.store?.getMeta(P,y)}catch(G){x(_,G,y);return}if(ee==null){h(_,y);return}Je(_,202,{sessionId:y,accepted:!0})},Nt=async(_,y,P,K,ee,G)=>{let Y=J(y,P,K);if(Y==="forbidden")return;if(Y==="absent"){h(y,P);return}let ve=ee==="tool-results"?c:t.maxBodyBytes,fe=await f(_,y,ve);if(fe==="rejected")return;if(!fe.ok){u(_,y,fe.reason,ve);return}let xe,be;if(ee==="tool-results"){be="call";let _e=Cr.safeParse(fe.value);if(!_e.success){g(y,_e.error.issues[0]?.message??"invalid receipt");return}xe=Y.handle.submitToolResult(G,_e.data)}else if(ee==="permission"){be="request";let _e=fa.safeParse(fe.value);if(!_e.success){g(y,_e.error.issues[0]?.message??"invalid receipt");return}xe=Y.handle.submitPermission(G,_e.data)}else{be="request";let _e=pa.safeParse(fe.value);if(!_e.success){g(y,_e.error.issues[0]?.message??"invalid receipt");return}xe=Y.handle.submitQuestionAnswers(G,_e.data)}if(n.touch(P),xe==="accepted"){Je(y,200,{accepted:!0});return}if(xe==="invalid"){g(y,"receipt does not match the pending request");return}let Pe=xe==="digest_mismatch"?Oe.digestMismatch:`${be}_${xe}`;pe(y,ex(xe),Pe,ae.v2ReceiptRejected,{code:Pe})},yn=async(_,y,P,K)=>{let ee;try{ee=await d(_,y)}catch(fe){if(y.destroyed||y.writableEnded)return;if(fe instanceof Rt){pe(y,503,fe.code,fe.code==="overloaded"?ae.overloaded:ae.internalError,{},Ft(i.retryAfterMs));return}ee=null}if(_.aborted||y.destroyed||y.writableEnded)return;if(ee===null){pe(y,401,Oe.unauthorized,ae.unauthorized);return}let G=ee.endUserId;if(P==="/v3/sdk2/session-capabilities"){if(K!=="GET"){D(y,K,P,"GET");return}if(_.headers["transfer-encoding"]!==void 0||_.headers["content-length"]!==void 0&&_.headers["content-length"]!=="0"){pe(y,400,"invalid_request",ae.v2ValidationFailed);return}let fe=new URL(_.url??"","http://serve").searchParams;if([...fe.keys()].some(be=>be!=="protocol")||fe.getAll("protocol").length>1){pe(y,400,"invalid_request",ae.v2ValidationFailed);return}if(fe.getAll("protocol").length!==1||fe.get("protocol")!=="sdk2-ext-v1"){pe(y,400,"protocol_version_mismatch",ae.v2ValidationFailed);return}let xe=nn({protocol:"sdk2-ext-v1",contracts:t.sessionContracts??[{contract:"sdk1",availability:"legacy-complete"}]},{maxBytes:262144});y.writeHead(200,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),y.end(xe);return}let Y=e.createSession.execution??e.createSession.transactionalExecution;if(Y!==void 0&&await Hy({host:Y,req:_,res:y,pathname:P,method:K,endUserId:G,log:v,retryAfterMs:i.retryAfterMs,...t.sessionFamily===void 0?{}:{sessionFamily:t.sessionFamily},readBody:()=>f(_,y,Math.min(t.maxBodyBytes,262144),!0)}))return;if(P==="/v2/sessions"){if(K==="POST"){await H(_,y,G);return}if(K==="GET"){await B(_,y,G);return}D(y,K,P,"POST, GET");return}let ve=rg.exec(P);if(ve!==null){let fe=fi(ve[1]),xe=ve[3]!==void 0?fi(ve[3]):void 0;if(fe===null||xe===null){pe(y,404,Oe.notFound,ae.notFound,{path:P});return}if(K==="GET"&&t.filterSessionReads&&!(await t.filterSessionReads(G,[fe])).includes(fe)){h(y,fe);return}let be=ve[2],Pe=ve[4];if(be==="inputs"||be==="input-capabilities"){let _e=be==="input-capabilities"||xe!==void 0?"GET":"POST";if(Pe!==void 0||be==="input-capabilities"&&xe!==void 0){pe(y,404,Oe.notFound,ae.notFound,{path:P});return}if(K!==_e){D(y,K,P,_e);return}await ne(_,y,fe,G,be,xe);return}if(be==="audio"){if(xe!=="transcriptions"&&xe!=="speech"||Pe!==void 0){pe(y,404,Oe.notFound,ae.notFound,{path:P});return}if(K!=="POST"){D(y,K,P,"POST");return}await Ge(_,y,fe,G,xe);return}if(be==="cwd"){if(xe!==void 0){pe(y,404,Oe.notFound,ae.notFound,{path:P});return}if(K!=="POST"){D(y,K,P,"POST");return}await kt(_,y,fe,G);return}if(be==="compact"||be==="checkpoints"){if(be==="compact"){if(xe!==void 0){pe(y,404,Oe.notFound,ae.notFound,{path:P});return}if(K!=="POST"){D(y,K,P,"POST");return}await Se(_,y,fe,G);return}if(xe===void 0){if(K==="GET"){await Ue(y,fe,G);return}if(K==="POST"){await $e(_,y,fe,G);return}D(y,K,P,"GET, POST");return}if(xe===Sa&&Pe===void 0){if(K!=="POST"){D(y,K,P,"POST");return}await zt(_,y,fe,G);return}if(Pe==="restore"){if(K!=="POST"){D(y,K,P,"POST");return}await Fe(_,y,fe,G,xe);return}if(Pe==="export"){if(K!=="GET"){D(y,K,P,"GET");return}await Tt(y,fe,G,xe);return}if(K!=="DELETE"){D(y,K,P,"DELETE");return}await lt(y,fe,G,xe);return}if(Pe!==void 0){pe(y,404,Oe.notFound,ae.notFound,{path:P});return}if(be===void 0){if(xe!==void 0){pe(y,404,Oe.notFound,ae.notFound,{path:P});return}if(K==="GET"){await le(_,y,fe,G);return}if(K==="DELETE"){await wn(y,fe,G);return}D(y,K,P,"GET, DELETE");return}if(be==="tool-results"||be==="permission"||be==="questions"){if(xe===void 0){pe(y,404,Oe.notFound,ae.notFound,{path:P});return}if(K!=="POST"){D(y,K,P,"POST");return}await Nt(_,y,fe,G,be,xe);return}if(xe!==void 0){pe(y,404,Oe.notFound,ae.notFound,{path:P});return}if(be==="events"||be==="history"){if(K!=="GET"){D(y,K,P,"GET");return}be==="events"?U(_,y,fe,G):await ue(_,y,fe,G);return}if(K!=="POST"){D(y,K,P,"POST");return}be==="messages"?await j(_,y,fe,G):gn(y,fe,G);return}pe(y,404,Oe.notFound,ae.notFound,{path:P})};return(_,y,P,K)=>{if(P!=="/v3/sdk2/session-capabilities"){if(t.sessionFamily)if(P==="/v3/sdk2/executors"||P.startsWith("/v3/sdk2/executors/"))P="/v2"+P.slice(8);else{if(P!=="/v3/sdk2/sessions"&&!P.startsWith("/v3/sdk2/sessions/")||/^\/v3\/sdk2\/sessions\/[^/]+\/binding-target$/.test(P))return!1;P="/v2/sessions"+P.slice(17)}else if(P!=="/v2"&&!P.startsWith("/v2/"))return!1}let ee=yn(_,y,P,K);return t.trackRequestWork?.(ee),ee.catch(G=>{$(y,P,K,G)}),!0}}var Vr=class extends Error{reason;constructor(e){super(e==="queue_full"?"concurrency gate queue is full":"concurrency gate queue wait timed out"),this.name="GateRejectedError",this.reason=e}},bd=class{#e;#n;#r;#s=[];#t=0;#o=0;#i=0;constructor(e){this.#e=Math.max(1,e.maxConcurrent),this.#n=Math.max(0,e.maxQueued),this.#r=e.queueTimeoutMs}acquire(){return this.#t<this.#e?(this.#t+=1,Promise.resolve(this.#a())):this.#s.length>=this.#n?(this.#o+=1,Promise.reject(new Vr("queue_full"))):new Promise((e,n)=>{let i={resolve:e,reject:n,timer:void 0};Number.isFinite(this.#r)&&(i.timer=setTimeout(()=>{let o=this.#s.indexOf(i);o!==-1&&(this.#s.splice(o,1),this.#i+=1,n(new Vr("queue_timeout")))},this.#r)),this.#s.push(i)})}stats(){return{active:this.#t,queued:this.#s.length,rejectedQueueFull:this.#o,rejectedQueueTimeout:this.#i}}#a(){let e=!1;return()=>{if(e)return;e=!0;let n=this.#s.shift();if(n===void 0){this.#t-=1;return}n.timer!==void 0&&clearTimeout(n.timer),n.resolve(this.#a())}}},$r=class{#e=new Map;#n;#r=0;constructor(e){this.#n=Math.max(1,e)}get size(){return this.#e.size}get(e){let n=this.#e.get(e);if(n!==void 0)return this.#e.delete(e),this.#e.set(e,n),n}peek(e){return this.#e.get(e)}has(e){return this.#e.has(e)}set(e,n){for(this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,n);this.#e.size>this.#n;){let i=this.#e.keys().next();if(i.done)break;this.#e.delete(i.value),this.#r+=1}}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}keys(){return this.#e.keys()}stats(){return{size:this.#e.size,evicted:this.#r}}},Sd=class{#e;#n;#r;constructor(e){this.#e=new $r(e.maxEntries),this.#n=e.ttlMs,this.#r=e.now??Date.now}has(e){let n=this.#e.peek(e);return n===void 0?!1:n<=this.#r()?(this.#e.delete(e),!1):!0}add(e){return this.#e.set(e,this.#r()+this.#n),this}get size(){return this.#e.size}stats(){return this.#e.stats()}};var tn={memorySourceUnavailable:"server.v2.warning.memory_source_unavailable",backgroundUsageStoreRequired:"server.v2.error.background_usage_store_required",executionPermissionTarget:"server.v2.execution.permission_target",executionInitializeRequired:"server.v2.execution.initialize_required",unknownCapabilitiesProfile:"cli.serve.v2.error.unknown_capabilities_profile",clientToolConflict:"cli.serve.v2.error.client_tool_conflict",mintFailed:"cli.serve.v2.error.mint_failed",platformProfileUnsupported:"server.v2.error.platform_profile_unsupported",capabilityDisabled:"cli.serve.v2.error.capability_disabled",appPlatformMismatch:"server.v2.warning.app_platform_mismatch",profileNarrowedCapabilities:"server.v2.warning.profile_narrowed_capabilities"},sv=Object.values(tn);var av="/v1/app-tokens",tx=16*1024,nx=3e5,ix=32,rx=1024,ox=1e4,sx=.15,dv=5e3,ax=6e4,dx=1e5,cx=36e5,lx=1e4,yf=new Set(["adjudicator_evidence_drifted","adjudicator_budget_exhausted","adjudicator_breaker_tripped","adjudicator_unavailable","adjudicator_posture_overridden","adjudicator_budget_unenforced"]),ux=6e5,cv=Vo[0],lv="unknown",Cn=class extends Error{kind;status;retryAfterMs;code;detail;constructor(e,n,i={}){super(n,i.cause!==void 0?{cause:i.cause}:void 0),this.name="AppTokenMintError",this.kind=e,this.status=i.status,this.retryAfterMs=i.retryAfterMs,this.code=i.code,this.detail=i.detail}};function fx(t,e){if(t===null)return;let n=t.trim(),i;if(/^\d+$/.test(n))i=Number.parseInt(n,10)*1e3;else{let o=Date.parse(n);if(Number.isNaN(o))return;i=o-e}if(!(!Number.isFinite(i)||i<=0))return Math.min(i,ux)}function uv(t){if(typeof t!="object"||t===null)return"unknown";let e=t;return e.error!==void 0&&e.error!==null?String(e.error.code??"unknown"):String(e.code??"unknown")}function fv(t){if(typeof t!="object"||t===null)return;let e=t.error?.detail;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}async function px(t){let e;try{e=await t.clone().json()}catch{return}let n=uv(e);if(!$o(n))return;let o=fv(e)?.reason,s=typeof o=="string"&&o!==""?o:lv;if(!Ko(s))return{code:n,reason:s}}function mx(t,e){return!(e?.body!==void 0&&e.body!==null&&typeof ReadableStream<"u"&&e.body instanceof ReadableStream||t instanceof Request&&t.body!==null&&(e?.body===void 0||e.body===null))}function wd(t){let e=t.apiBaseUrl.replace(/\/+$/,""),n=t.fetchImpl??fetch,i=t.now??Date.now,o=t.random??Math.random,s=Math.min(86400,Math.max(60,t.ttlSeconds??3600)),a=Math.min(nx,s*1e3/2),d=Math.min(.99,Math.max(0,t.expiryJitterRatio??sx)),c=Math.max(0,t.negativeCacheInitialMs??dv),l=Math.max(c,t.negativeCacheMaxMs??ax),f=t.maxCachedTokens??dx,u=Gm(t.appKey),m=Qn(t.metrics),g=new bd({maxConcurrent:t.maxConcurrentMints??ix,maxQueued:t.maxQueuedMints??rx,queueTimeoutMs:t.mintQueueTimeoutMs??ox}),h=new $r(f),p=new $r(f),v=new Map,b={mints:0,hits:0,negativeHits:0,staleServed:0,failures:{rate_limited:0,unavailable:0,network:0,rejected:0,saturated:0},invalidations:{}},R=(D,J)=>We(tn.mintFailed,{status:D,code:J}),w=D=>{let J=h.get(D);if(J!==void 0){if(J.expiresAtMs<=i()){h.delete(D);return}return J}},x=(D,J)=>{if(b.failures[J.kind]+=1,J.kind==="saturated")return;m.tokenMintFailures.inc();let S=p.peek(D),k=S===void 0?c:Math.min(l,S.backoffMs*2),A=Math.max(k,Math.min(J.retryAfterMs??0,l));p.set(D,{until:i()+A,backoffMs:k,kind:J.kind,status:J.status,message:J.message,code:J.code,detail:J.detail})},T=async D=>{b.mints+=1;let J=JSON.stringify({endUserId:D,ttlSeconds:s}),S;try{S=await n(`${e}${av}`,{method:"POST",headers:{"content-type":"application/json",[hs]:t.appId,[gs]:t.appKey,...Wm({signingKey:u,method:"POST",pathWithQuery:av,body:J,now:i})},body:J})}catch(Q){throw new Cn("network",R("network",Q instanceof Error?Q.message:String(Q)),{cause:Q})}let k=await S.json().catch(()=>null);if(!S.ok){let Q=uv(k),re=fv(k),O=fx(S.headers.get("retry-after"),i()),I=S.status===429?"rate_limited":S.status>=500?"unavailable":"rejected";throw new Cn(I,R(String(S.status),Q),{status:S.status,...O!==void 0?{retryAfterMs:O}:{},code:Q,...re!==void 0?{detail:re}:{}})}let A=typeof k=="object"&&k!==null?k:{};if(typeof A.token!="string"||A.token==="")throw new Cn("unavailable",R(String(S.status),"malformed_response"),{status:S.status});let C=typeof A.expiresAt=="string"&&!Number.isNaN(Date.parse(A.expiresAt))?Date.parse(A.expiresAt):i()+s*1e3,F=Math.max(0,C-i()),H=i()+F*(1-o()*d);return h.set(D,{token:A.token,expiresAtMs:H}),p.delete(D),A.token},M=async D=>{let J;try{J=await g.acquire()}catch(S){let k=S instanceof Vr?S.reason:"queue_full",A=new Cn("saturated",R("saturated",k),{retryAfterMs:dv});throw x(D,A),A}try{let S=w(D);return S!==void 0&&S.expiresAtMs-i()>a?S.token:await T(D)}catch(S){let k=S instanceof Cn?S:new Cn("network",R("network",S instanceof Error?S.message:String(S)),{cause:S});x(D,k);let A=w(D);if(A!==void 0)return b.staleServed+=1,A.token;throw k}finally{J()}},W=D=>{let J=w(D);if(J!==void 0&&J.expiresAtMs-i()>a)return b.hits+=1,Promise.resolve(J.token);let S=p.peek(D);if(S!==void 0&&S.until>i())return b.negativeHits+=1,J!==void 0?(b.staleServed+=1,Promise.resolve(J.token)):Promise.reject(new Cn(S.kind,S.message,{...S.status!==void 0?{status:S.status}:{},retryAfterMs:Math.max(1,S.until-i()),...S.code!==void 0?{code:S.code}:{},...S.detail!==void 0?{detail:S.detail}:{}}));let k=v.get(D);if(k!==void 0)return k;let A=M(D).finally(()=>v.delete(D));return v.set(D,A),A};return{tokenFor:W,invalidate:(D,J={})=>{let S=h.peek(D);if(S===void 0||J.token!==void 0&&S.token!==J.token)return!1;h.delete(D);let k=J.reason??lv;return b.invalidations[k]=(b.invalidations[k]??0)+1,!0},async warm(D){let J={minted:0,cached:0,failed:0},S=await Promise.allSettled([...D].map(async k=>{let A=w(k),C=A!==void 0&&A.expiresAtMs-i()>a;return await W(k),C}));for(let k of S)k.status==="rejected"?J.failed+=1:k.value?J.cached+=1:J.minted+=1;return J},stats(){let D=g.stats();return{inflight:D.active,queued:D.queued,mints:b.mints,hits:b.hits,negativeHits:b.negativeHits,staleServed:b.staleServed,failures:{...b.failures},cached:h.size,evicted:h.stats().evicted,invalidations:{...b.invalidations}}}}}function hx(t){if(t===void 0)return n=>{console.warn(`[tansr-serve] platform warning ${n.code} (endUser=${n.endUserId}): ${n.message}`)};let e=$n(t);return n=>{e("warn",Xe.platformWarning,{endUserId:n.endUserId,sessionId:n.sessionId,code:n.code,message:n.message})}}function gx(t){if(t.bundleCache!==void 0)return t.bundleCache;let e=t.bundleCacheTtlMs??_i;if(!(e<=0))return ar({ttlMs:e,...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{},...t.now!==void 0?{now:t.now}:{}})}function pv(t){return hv(t)}function mv(t,e){return hv(t,e)}function hv(t,e){let n=new Sd({ttlMs:cx,maxEntries:lx,...t.now!==void 0?{now:t.now}:{}}),i=hx(t.logger),o=t.onPlatformWarning??(c=>{let l=`${c.endUserId}\0${c.code}`;n.has(l)||(n.add(l),i(c))}),s=gx(t),a=Qn(t.metrics),d=t.fetchImpl??fetch;return async c=>{let l=await t.minter.tokenFor(c.endUserId),f=c.platformSessionId??zi(),u=(async(k,A)=>{let C=await t.minter.tokenFor(c.endUserId),F=O=>{let I=new Headers(A?.headers??(k instanceof Request?k.headers:void 0));return I.set(On,O),d(k,{...A,headers:I})},H=await F(C);if(H.status!==401)return H;let Q=await px(H);if(Q===void 0||(a.tokenInvalidations.inc({reason:Q.reason}),t.minter.invalidate===void 0)||(t.minter.invalidate(c.endUserId,{token:C,reason:Q.reason}),!mx(k,A)))return H;let re;try{re=await t.minter.tokenFor(c.endUserId)}catch{return H}return re===C?H:F(re)}),m=e?.gatewayCache?.({endUserId:c.endUserId,sessionId:c.sessionId}),g=await Va({token:l,baseUrl:t.apiBaseUrl,...c.model!==void 0?{model:c.model}:{},fetchImpl:u,sessionId:()=>f,onSessionArchived:k=>{if(k!==void 0&&k!==f)return;s?.invalidate();let A=f,C=m===void 0?void 0:e?.archivedRuntime?.({endUserId:c.endUserId,sessionId:c.sessionId,previous:A});if(m!==void 0&&C===void 0)throw new Et("session_archived",void 0,410);f=c.onSessionArchived?.(A,C)??C??zi();let F={code:"platform_session_archived",message:`platform session "${A}" was archived by the platform (410 session_archived); a new platform session "${f}" starts with the next exchange (no retry against the archived id).`};o({endUserId:c.endUserId,sessionId:c.sessionId,...F}),c.onWarning?.(F)},...s!==void 0?{bundleCache:s}:{},...t.appId!==void 0?{appId:t.appId}:{},onWarn:k=>{o({endUserId:c.endUserId,sessionId:c.sessionId,code:k.code,message:k.message}),c.onWarning?.({code:k.code,message:k.message})}},m===void 0?{}:{gatewayCache:m}),h=Ga(g),p=$a({baseUrl:t.apiBaseUrl,token:l,fetchImpl:u,initial:{...g.systemPrompt!==void 0?{systemPrompt:g.systemPrompt}:{},...g.systemPromptPolicy!==void 0?{systemPromptPolicy:g.systemPromptPolicy}:{}}},h&&e?.refreshCacheConfiguration?{initial:h,refreshRequired:()=>e.cacheConfigurationRefreshRequired?.({endUserId:c.endUserId,sessionId:c.sessionId})??!1,confirmConfiguration:k=>e.confirmCacheConfiguration?.({endUserId:c.endUserId,sessionId:c.sessionId},k),refreshConfiguration:k=>e.refreshCacheConfiguration({endUserId:c.endUserId,sessionId:c.sessionId},k)}:void 0),v,b,R=async(k,A)=>{k.throwIfAborted();let C=(H,Q)=>u(H,{...Q,cache:"no-cache",headers:{...Object.fromEntries(new Headers(Q?.headers)),"cache-control":"no-cache"},signal:Q?.signal?AbortSignal.any([Q.signal,k]):k}),F=await si(t.apiBaseUrl.replace(/\/+$/,""),l,C,A,void 0,!0);return k.throwIfAborted(),F},w=async k=>{let A=await R(k,b);if(A.bundle!==null&&(v=A.bundle.capabilities),b=A.etag??b,v===void 0)throw new Error("Application capabilities are unconfirmed");return v},x,T,M=async k=>{let A=await R(k,T);if(A.bundle!==null){let C=A.bundle.models.map(({handle:Q,displayName:re,manufacturer:O,family:I,adapterDiagnostics:B})=>({handle:Q,displayName:re,manufacturer:O,family:I,...B===void 0?{}:{adapterDiagnostics:structuredClone(B)}})),F=new Set(C.map(Q=>Q.handle)),H=Object.fromEntries(Object.entries(A.bundle.aliases).flatMap(([Q,re])=>{let O=F.has(re)?re:re.startsWith("tansr/")?re.slice(6):void 0;return O!==void 0&&F.has(O)?[[Q,O]]:[]}));x={models:C,aliases:H,capabilities:A.bundle.capabilities},T=A.etag}else T=A.etag??T;if(x===void 0)throw new Error("Platform catalog is unconfirmed");return structuredClone(x)},W=async k=>{k.throwIfAborted();let A=await u(`${t.apiBaseUrl.replace(/\/+$/,"")}/v1/my-usage?window=1d`,{method:"GET",headers:{accept:"application/json","cache-control":"no-cache"},cache:"no-cache",signal:k});if(k.throwIfAborted(),!A.ok)throw A.body?.cancel().catch(()=>{}),new Error("Platform usage is unavailable");let{bytes:C,truncated:F}=await Jc(A,tx,k);if(F)throw new Error("Platform usage response exceeded the size limit");let H;try{H=JSON.parse(new TextDecoder().decode(C))}catch{throw new Error("Platform usage is unconfirmed")}let Q=hl.safeParse(H);if(k.throwIfAborted(),!Q.success||Q.data.endUserId!==c.endUserId||Q.data.window!=="1d")throw new Error("Platform usage is unconfirmed");return Q.data},$;g.pricingUpdates.length>0&&($=il(),$.refreshPricing(g.pricingUpdates,"refreshed"));let D=g.adjudicator,J=k=>{o({endUserId:c.endUserId,sessionId:c.sessionId,...k}),!yf.has(k.code)&&c.onWarning?.(k)},S=rm(g.contextScheme,k=>o({endUserId:c.endUserId,sessionId:c.sessionId,code:im,message:`${k.reason}: ${k.detail}`}));return(k,A)=>{let C=jr(g.registry,k,A);return{client:C.client,model:C.model,...C.contextWindowTokens!==void 0?{contextWindowTokens:C.contextWindowTokens}:{},...C.maxOutputTokens!==void 0?{maxOutputTokens:C.maxOutputTokens}:{},...$!==void 0?{pricing:$}:{},...S!==void 0?{compactionManagerOptions:S}:{},...g.governance.sessionRetentionDays!==void 0?{sessionRetentionDays:g.governance.sessionRetentionDays}:{},resolveSubagentModel:(F,H)=>{try{let Q=g.registry.resolveAlias(F);return{provider:Q.providerId,model:Q.modelName}}catch{return H}},capabilities:g.capabilities,...g.systemPrompt!==void 0?{systemPrompt:g.systemPrompt}:{},...g.systemPromptPolicy!==void 0?{systemPromptPolicy:g.systemPromptPolicy}:{},refreshApplicationPrompt:p,refreshApplicationCapabilities:w,readPlatformCatalog:M,readPlatformUsage:W,platform:g.platform,platformTools:{baseUrl:t.apiBaseUrl,fetchImpl:u,platformModels:g.platformModels},onAdjudicationWarning:J,...D!==null?{assembleAdjudicator:F=>bl({registry:g.registry,mainModel:C.model,adjudicator:D,app:{...g.app,endUser:c.endUserId},posture:F.posture,...F.postureExplicit!==void 0?{postureExplicit:F.postureExplicit}:{},pricing:g.pricingUpdates,...F.callBudget!==void 0?{callBudget:F.callBudget}:{},onWarn:J})}:{}}}}}function Kr(t){if(t.governor!==void 0){let e=t.governor;return t.fetchImpl!==void 0?e.wrapFetch(t.fetchImpl):e.fetch}return t.fetchImpl}function kd(t){return async e=>{try{return await t(e)}catch(n){throw vf(n)}}}var yx=new Set(["plan_concurrency_exceeded","plan_end_users_exceeded"]),vx=new Set(["plan_required","plan_tier_insufficient"]),bx=3e4;function vf(t){if(!(t instanceof Cn))return t;let e=t.retryAfterMs!==void 0?{retryAfterMs:t.retryAfterMs}:{};if(t.code!==void 0&&yx.has(t.code))return new Ze("plan_limited",t.message,{retryAfterMs:t.retryAfterMs??bx,params:{code:t.code},...t.detail!==void 0?{detail:t.detail}:{}});if(t.code!==void 0&&vx.has(t.code))return new Ze("plan_denied",t.message,{params:{code:t.code},...t.detail!==void 0?{detail:t.detail}:{}});switch(t.kind){case"rate_limited":case"unavailable":case"network":return new Ze("upstream_unavailable",t.message,e);case"saturated":return new Ze("overloaded",t.message,e);case"rejected":return t}}import{randomUUID as Sx}from"node:crypto";function gv(t,e,n){if(t.destroyed||t.writableEnded)return;let i=nc(n);t.writeHead(e,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":i.length}),t.end(i)}async function yv(t){if(t.headers["content-type"]?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new Et("invalid_request",void 0,400);let e=[],n=0;for await(let i of t){let o=Buffer.isBuffer(i)?i:Buffer.from(i);if(n+=o.length,n>65536)throw new Et("payload_too_large",void 0,413);e.push(o)}try{return ic(Buffer.concat(e))}catch{throw new Et("invalid_request",void 0,400)}}function bf(t,e,n=[]){let i=t.searchParams;for(let o of i.keys())if(![...e,...n].includes(o)||i.getAll(o).length!==1)throw new Et("invalid_request",void 0,400);if(e.some(o=>!i.has(o))||i.get("protocol")!==ll)throw new Et("invalid_request",void 0,400);return i}function vv(t){let e=0;return(n,i,o,s)=>{if(!o.startsWith("/v3/sdk2/cache/"))return!1;let a=0,d=!1,c=(async()=>{if(e>=128||t.admission.overloaded())throw new Et("capacity_exceeded",void 0,503);e++,d=!0;let l;try{l=await t.authenticate(n,i)}catch(v){if(v instanceof Rt)throw new Et("capacity_exceeded",void 0,503,"same-request");l=null}if(n.aborted||i.destroyed||i.writableEnded)return;if(!l||!l.endUserId)throw new Et("unauthorized",void 0,401);if(!(await t.admission.rateLimit(n,l.endUserId)).admitted)throw new Et("capacity_exceeded",void 0,429);if(s==="POST"){let v=pi(n,65536);if(!t.admission.reserveBody(v).admitted)throw new Et("capacity_exceeded",void 0,503);a=v}let u=l.endUserId,m=new URL(n.url??"/","http://serve.invalid"),g=o.slice(14),h,p=/^\/core\/v1\/bindings\/([A-Za-z0-9][A-Za-z0-9._~-]{0,127})\/diagnostics$/.exec(g);if(s==="GET"&&p){let v=m.searchParams;if([...v.keys()].some(R=>!["protocol","limit","after"].includes(R)||v.getAll(R).length!==1)||v.get("protocol")!=="sdk2-cache-core-v1")throw new Et("invalid_request",void 0,400);let b=v.get("limit")??"100";if(!/^[1-9][0-9]{0,2}$/.test(b)||Number(b)>100)throw new Et("invalid_request",void 0,400);h=await t.link.coreDiagnostics(u,p[1],v.get("after"),Number(b))}else if(s==="GET"&&g==="/capabilities"){if(m.search)throw new Et("invalid_request",void 0,400);h=await t.link.capabilities(u)}else if(s==="POST"&&g==="/bindings"){if(m.search)throw new Et("invalid_request",void 0,400);h=await t.link.execute(u,"open",await yv(n))}else if(s==="GET"&&g==="/operations"){let v=bf(m,["protocol","operation","operationEpoch","requestId"],["bindingId"]),b=v.get("operation");if(b!=="open"&&b!=="renew"&&b!=="rebind"&&b!=="rotate"&&b!=="close")throw new Et("invalid_request",void 0,400);h=await t.link.query(u,b,{operationEpoch:v.get("operationEpoch"),requestId:v.get("requestId")},v.get("bindingId"))}else{let v=/^\/bindings\/([A-Za-z0-9][A-Za-z0-9._~-]{0,127})(?:\/(renew|rebind|rotate|close|diagnostics))?$/.exec(g);if(!v)throw new Et("mapping_unavailable",void 0,404);let b=v[1],R=v[2];if(s==="GET"&&R===void 0)bf(m,["protocol"]),h=await t.link.read(u,b);else if(s==="GET"&&R==="diagnostics"){let w=bf(m,["protocol"],["after","limit"]),x=w.get("limit")??"100";if(!/^[1-9][0-9]{0,2}$/.test(x)||Number(x)>100)throw new Et("invalid_request",void 0,400);h=await t.link.diagnostics(u,b,w.get("after"),Number(x))}else if(s==="POST"&&(R==="renew"||R==="rebind"||R==="rotate"||R==="close")){if(m.search)throw new Et("invalid_request",void 0,400);let w=await yv(n);if(!w||typeof w!="object"||w.bindingId!==b)throw new Et("invalid_request",void 0,400);h=await t.link.execute(u,R,w)}else throw new Et("invalid_request",void 0,400)}gv(i,200,h)})().catch(l=>{if(i.destroyed||i.writableEnded)return;let f=l instanceof Et,u=f?l.status??503:l instanceof Jd?400:503,m=f?l.code:l instanceof Jd?"invalid_request":"result_unknown",g={protocol:ll,requestId:Sx(),code:m,status:u,retryAction:f?l.retryAction:m==="result_unknown"?"query-status":"none",fallback:"none",message:m},h=Vm.safeParse(g);(u===429||u===503)&&i.setHeader("retry-after","5"),gv(i,h.success?u:503,h.success?h.data:{...g,code:"result_unknown",message:"result_unknown",status:503,retryAction:"query-status"})}).finally(()=>{d&&e--,a>0&&t.admission.releaseBody(a)});return t.track(c),!0}}import{types as wx}from"node:util";var kx=new Set(["receive","confirm","pending","head","coverage","identity","operation","records","body-chunk","sync-page","retention","retention-page","apply-retention","reconcile"]),xx=new Set(["head","coverage","identity","records","body-chunk","sync-page","retention","retention-page"]),Rx=new Set(["invalid_input","identity_mismatch","integrity_mismatch","capacity_exceeded","pending_ack","receipt_mismatch","context_changed","reentrant","closed","storage_error","reconciliation_required"]),Sf=class extends Error{constructor(n){super(n);this.code=n}code};function vt(t,e="invalid_input"){if(!t)throw new Sf(e)}function wf(t,e){let n=0,i=0,o=new Set,s=d=>(i+=Buffer.byteLength(d),vt(i<=e,"capacity_exceeded"),d),a=(d,c)=>{if(vt(c<=32&&++n<=1e5),d===null||typeof d=="boolean")return s(String(d));if(typeof d=="number")return vt(Number.isSafeInteger(d)&&d>=0&&!Object.is(d,-0)),s(String(d));if(typeof d=="string")return vt(Buffer.from(d).toString("utf8")===d),s(JSON.stringify(d));vt(d&&typeof d=="object"&&!wx.isProxy(d)&&!o.has(d)),o.add(d);try{let l=Object.getOwnPropertyDescriptors(d);if(Array.isArray(d)){let m=l.length?.value;vt(Number.isSafeInteger(m)&&m<=1e5&&Reflect.ownKeys(l).length===m+1);let g=[s("[")];for(let h=0;h<m;h++){let p=l[h];vt(p&&Object.hasOwn(p,"value")&&p.enumerable),h&&g.push(s(",")),g.push(a(p.value,c+1))}return g.push(s("]")),g.join("")}vt(Object.getPrototypeOf(d)===Object.prototype||Object.getPrototypeOf(d)===null);let f=Reflect.ownKeys(l);vt(f.every(m=>typeof m=="string"&&/^[\x21-\x7e]+$/.test(m)));let u=[s("{")];for(let[m,g]of f.sort().entries()){let h=l[g];vt(Object.hasOwn(h,"value")&&h.enumerable),m&&u.push(s(",")),u.push(s(JSON.stringify(g)+":"),a(h.value,c+1))}return u.push(s("}")),u.join("")}finally{o.delete(d)}};return Buffer.from(a(t,0))}function Ix(t,e){let n=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t),i=JSON.parse(n);return vt(wf(i,e).equals(t)),i}function xd(t,e){return JSON.parse(wf(t,e).toString("utf8"))}function bv(t,e,n){if(t.destroyed||t.writableEnded)return;let i=wf(n,1638400);t.writeHead(e,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":i.length}),t.end(i)}function Sv(t){vt(/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(t.host.applicationScopeId));let e=0;return(n,i)=>{let o=n.url??"";if(!o.startsWith("/v3/sdk2/archive-sync/"))return!1;let s=!1,a=!1,d=0,c=null,l="unknown",f=(async()=>{vt(e<32&&!t.admission.overloaded(),"capacity_exceeded"),e++,s=!0,vt(n.method==="POST"&&/^\/v3\/sdk2\/archive-sync\/[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(o)),vt(n.headers["content-type"]?.split(";")[0]==="application/json");let u=o.slice(22),m=await t.authenticate(n,i);vt(m?.endUserId,"context_changed"),vt((await t.admission.rateLimit(n,m.endUserId)).admitted,"capacity_exceeded");let g=t.host.resolve(m.endUserId,u),h=g?null:t.host.resolveReadOnly?.(m.endUserId,u),p=g??h?.binding;vt(p,"identity_mismatch"),c=xd(p.identity,65536);let v=h?xd(h.grant,65536):null;v&&(Mn(v,["actor","owner","grantRevision"]),Mn(v.actor,["applicationScopeId","endUserId","authorizationRevision"]),Mn(v.owner,["scope","bindingId","target","sourceId","sourceGeneration"]),Mn(v.owner.target,["sessionId","generations"]),Mn(v.owner.target.generations,["historyEpoch","deletionGeneration","projectionRevision"]),vt(v.actor.endUserId===m.endUserId&&v.actor.applicationScopeId===t.host.applicationScopeId&&/^[0-9]{1,19}$/.test(v.actor.authorizationRevision)&&/^[0-9]{1,19}$/.test(v.grantRevision)&&he(v.owner)===he(c),"identity_mismatch")),vt(p.identity.bindingId===u&&(v!==null||p.identity.scope.endUserId===m.endUserId)&&p.identity.scope.applicationScopeId===t.host.applicationScopeId,"identity_mismatch"),vt(Number.isSafeInteger(p.maxRequestBytes)&&p.maxRequestBytes>0&&p.maxRequestBytes<=94371840),vt(Number.isSafeInteger(p.maxResponseBytes)&&p.maxResponseBytes>0&&p.maxResponseBytes<=1572864),d=p.maxRequestBytes+65536,vt(t.admission.reserveBody(d).admitted,"capacity_exceeded"),a=!0;let b=async()=>{let T=await t.authenticate(n,i),M=v?t.host.resolveReadOnly?.(m.endUserId,u):null;vt(!n.aborted&&!i.destroyed&&T?.endUserId===m.endUserId&&(v?M?.binding===p&&he(xd(M.grant,65536))===he(v):t.host.resolve(m.endUserId,u)===p)&&he(p.identity)===he(c),"context_changed")};await b();let R=await xi(n,d,T=>Ix(T,d));vt(R.ok,R.ok===!1&&R.reason==="too_large"?"capacity_exceeded":"invalid_input");let w=Mn(R.value,["format","identity","method","value"]);vt(w.format==="archive-sync-v1"&&he(w.identity)===he(c),"identity_mismatch"),vt(typeof w.method=="string"&&kx.has(w.method)),l=w.method,vt(!v||xx.has(l),"context_changed"),await b();let x=await p.dispatch(l,w.value);await b(),bv(i,200,{format:"archive-sync-v1",identity:c,method:l,value:xd(x,p.maxResponseBytes)})})().catch(u=>{let m=u&&typeof u=="object"?Object.getOwnPropertyDescriptor(u,"code"):void 0,g=typeof m?.value=="string"&&Rx.has(m.value)?m.value:"storage_error";bv(i,g==="context_changed"||g==="identity_mismatch"?403:g==="capacity_exceeded"?429:g==="invalid_input"?400:409,{format:"archive-sync-v1",identity:c,method:l,error:{code:g}})}).finally(()=>{s&&e--,a&&t.admission.releaseBody(d)});return t.track(f),!0}}import{randomUUID as BR}from"node:crypto";import{createHash as Tx}from"node:crypto";import{types as Ax}from"node:util";var pq=Object.freeze(["session","execution","archive","archive-sync","cache","terminal","terminal-observation","terminal-profile"]),Ex=Object.freeze({executionBoundDevice:"bound-device",inputAccepts:"input",audioTranscribe:"speechToText",audioSpeak:"textToSpeech",archiveTransfer:"archive-transfer-v1",archiveMaterials:"context-materials-v1",cacheFeature:"private-logical-cache-v1",terminalStream:"execution-stream-v1",terminalConfiguration:"session-configuration-v1",terminalMemory:"memory-lifecycle-v1"}),Ee=(t,e,n,i,o=null)=>Object.freeze({name:t,domain:e,kind:n,lifecycle:i,requires:o}),it=Ex,Cx=Object.freeze([Ee("session.create","session","write","independent"),Ee("session.list","session","read","independent"),Ee("session.get","session","read","session"),Ee("session.close","session","write","session"),Ee("session.message.send","session","write","session"),Ee("session.events.observe","session","stream","session"),Ee("session.interrupt","session","write","session"),Ee("session.history.read","session","read","session"),Ee("session.tool.result","session","write","session"),Ee("session.permission.decide","session","write","session"),Ee("session.question.answer","session","write","session"),Ee("session.compact","session","write","session"),Ee("session.checkpoint.list","session","read","session"),Ee("session.checkpoint.create","session","write","session"),Ee("session.checkpoint.import","session","write","session"),Ee("session.checkpoint.restore","session","write","session"),Ee("session.checkpoint.export","session","read","session"),Ee("session.checkpoint.delete","session","write","session"),Ee("session.cwd.set","session","write","session"),Ee("session.audio.transcribe","session","write","session",it.audioTranscribe),Ee("session.audio.speak","session","write","session",it.audioSpeak),Ee("session.input.capabilities","session","read","session"),Ee("session.input.submit","session","write","session",it.inputAccepts),Ee("session.input.status","session","read","session"),Ee("approval.credential.submit","session","write","independent"),Ee("execution.initialize","execution","write","session"),Ee("execution.capabilities","execution","read","session"),Ee("execution.boundary","execution","read","session"),Ee("execution.binding.create","execution","write","session",it.executionBoundDevice),Ee("execution.status","execution","read","session"),Ee("executor.register","execution","write","independent"),Ee("executor.heartbeat","execution","write","independent"),Ee("executor.operations.poll","execution","read","independent"),Ee("executor.receipt.submit","execution","write","independent"),Ee("archive.capabilities","archive","read","independent"),Ee("archive.binding.target","archive","read","independent"),Ee("archive.binding.create","archive","write","independent"),Ee("archive.binding.get","archive","read","independent"),Ee("archive.binding.close","archive","write","independent"),Ee("archive.status","archive","read","independent",it.archiveTransfer),Ee("archive.events.observe","archive","stream","independent"),Ee("archive.records.read","archive","read","independent",it.archiveTransfer),Ee("archive.artifact.read","archive","read","independent",it.archiveTransfer),Ee("archive.ack.commit","archive","write","independent",it.archiveTransfer),Ee("archive.ack.rebase","archive","write","independent",it.archiveTransfer),Ee("archive.operation.query","archive","read","independent"),Ee("archive.sync","archive-sync","write","independent"),Ee("material.response.submit","archive","write","independent",it.archiveMaterials),Ee("material.status","archive","read","independent",it.archiveMaterials),Ee("material.upload.status","archive","read","independent",it.archiveMaterials),Ee("material.upload.chunk","archive","write","independent",it.archiveMaterials),Ee("cache.capabilities","cache","read","independent"),Ee("cache.binding.open","cache","write","independent",it.cacheFeature),Ee("cache.binding.get","cache","read","independent",it.cacheFeature),Ee("cache.binding.renew","cache","write","independent",it.cacheFeature),Ee("cache.binding.rebind","cache","write","independent",it.cacheFeature),Ee("cache.binding.rotate","cache","write","independent",it.cacheFeature),Ee("cache.binding.close","cache","write","independent",it.cacheFeature),Ee("cache.operation.query","cache","read","independent",it.cacheFeature),Ee("cache.diagnostics","cache","read","independent",it.cacheFeature),Ee("cache.core.diagnostics","cache","read","independent",it.cacheFeature),Ee("terminal.capabilities","terminal","read","independent"),Ee("terminal.binding.create","terminal","write","session"),Ee("terminal.executor.events.observe","terminal","stream","independent",it.terminalStream),Ee("terminal.output.batch","terminal","write","session",it.terminalStream),Ee("terminal.execution.state","terminal","read","session",it.terminalStream),Ee("terminal.output.observe","terminal","stream","session",it.terminalStream),Ee("terminal.output.status","terminal","read","session",it.terminalStream),Ee("terminal.configuration.read","terminal","read","session",it.terminalConfiguration),Ee("terminal.configuration.commit","terminal","write","session",it.terminalConfiguration),Ee("terminal.memory.read","terminal","read","session",it.terminalMemory),Ee("terminal.memory.command","terminal","write","session",it.terminalMemory),Ee("terminal.memory.receipt","terminal","read","session",it.terminalMemory),Ee("terminal.observation.resources","terminal-observation","read","session"),Ee("terminal.observation.correlations","terminal-observation","read","session"),Ee("terminal.profile.catalog","terminal-profile","read","session"),Ee("terminal.profile.usage","terminal-profile","read","session")]),_x="tansr.unified.closure.v1";var Px=t=>t!==null&&(t.state==="ended"||t.state==="closing");function Mx(t){let{installed:e}=t;return{session:e.session!==null&&t.session!==null,execution:e.execution&&t.execution!==null,archive:e.archive&&t.archive!==null,"archive-sync":e["archive-sync"],cache:e.cache&&t.cache!==null,terminal:e.terminal&&t.terminal!==null,"terminal-observation":e["terminal-observation"],"terminal-profile":e["terminal-profile"]}}function Ox(t){let e=new Set,n=new Set;t.input!==null&&t.input.accepts.some(s=>Lx.includes(s))&&n.add(it.inputAccepts),t.audio?.speechToText===!0&&n.add(it.audioTranscribe),t.audio?.textToSpeech===!0&&n.add(it.audioSpeak);let i=new Set;t.execution?.effectiveTools.some(s=>s.executionKind==="bound-device"&&s.available)===!0&&i.add(it.executionBoundDevice);let o=new Set;for(let[s,a]of Object.entries(t.terminal?.features??{}))a==="installed"&&o.add(s);return{session:n,execution:i,archive:new Set(t.archive?.capabilities??[]),"archive-sync":e,cache:new Set(t.cache?.features??[]),terminal:o,"terminal-observation":e,"terminal-profile":e}}function Bx(t){let{installed:e}=t;return{session:{installed:e.session!==null,revision:t.session?.family??null},execution:{installed:e.execution,revision:t.execution?.boundaryRevision??null},archive:{installed:e.archive,revision:t.archive?.epochId??null},"archive-sync":{installed:e["archive-sync"],revision:null},cache:{installed:e.cache,revision:t.cache?.protocol??null},terminal:{installed:e.terminal,revision:t.terminal?.schemaRevision??null},"terminal-observation":{installed:e["terminal-observation"],revision:null},"terminal-profile":{installed:e["terminal-profile"],revision:null}}}function Dx(t,e,n,i){return!n[t.domain]||t.domain==="session"&&t.name.startsWith("session.input.")&&e.input===null||t.domain==="session"&&t.name.startsWith("session.audio.")&&e.audio==null?"unavailable":t.requires!==null&&!i[t.domain].has(t.requires)||t.kind==="write"&&(t.lifecycle==="session"&&Px(e.session)||t.domain==="archive"&&e.archive!==null&&e.archive.epochId===null)?"disabled":"enabled"}var qx=262144,jx=t=>new Uint8Array(Tx("sha256").update(t).digest());function Nx(t){let e=bs({authorizationRevision:t.authorizationRevision,domains:t.domains,operations:t.operations},{maxBytes:qx,isProxy:Ax.isProxy});return yp(gp(_x,e,jx))}function wv(t){let e=Mx(t),n=Ox(t),i=Bx(t),o={};for(let a of Cx)o[a.name]=Dx(a,t,e,n);let s=t.authorizationRevision;return{contract:an,closureId:Nx({authorizationRevision:s,domains:i,operations:o}),authorizationRevision:s,domains:i,operations:o}}function kv(t,e){return t===void 0||t===e.closureId?{ok:!0}:{ok:!1,code:"closure_stale",status:412,retryAction:"rediscover",closureId:e.closureId}}function Ux(t){return t.supported?t.installed?t.authorization!=="allowed"||t.device==="unavailable"||t.device==="unconfirmed"?"unconfirmed":"installed":"supported":"unconfirmed"}function xv(t){let e={};for(let n of t)e[n.feature]=Ux(n);return e}var Lx=["text","textBlocks","image"];function Rv(t){let e=["text","textBlocks","image"];return{version:t.version,accepts:e.filter(n=>t[n]===!0)}}import{randomUUID as Hx}from"node:crypto";var Rd={invalid_request:{status:400,retryAction:"none"},protocol_mismatch:{status:400,retryAction:"none"},unauthorized:{status:401,retryAction:"none"},forbidden:{status:403,retryAction:"none"},not_found:{status:404,retryAction:"none"},method_not_allowed:{status:405,retryAction:"none"},gone:{status:410,retryAction:"none"},conflict:{status:409,retryAction:"none"},stale_generation:{status:409,retryAction:"rebind"},gap:{status:409,retryAction:"none"},capability_unavailable:{status:404,retryAction:"none"},capacity_exceeded:{status:429,retryAction:"same-request"},payload_too_large:{status:413,retryAction:"none"},upstream_unavailable:{status:503,retryAction:"same-request"},result_unknown:{status:503,retryAction:"query-status"},rejected:{status:422,retryAction:"none"},internal_error:{status:500,retryAction:"none"}};var Id={"agent-session-v1":{call_already_resolved:"conflict",call_expired:"gone",call_not_found:"not_found",capability_disabled:"capability_unavailable",checkpoint_import_invalid:"invalid_request",checkpoint_not_found:"not_found",checkpoints_not_wired:"capability_unavailable",create_failed:"internal_error",cwd_invalid:"invalid_request",cwd_not_allowed:"forbidden",cwd_switch_unsupported:"capability_unavailable",cwd_unavailable:"conflict",digest_mismatch:"conflict",draining:"capacity_exceeded",forbidden:"forbidden",fork_source_not_found:"not_found",internal_error:"internal_error",invalid_json:"invalid_request",method_not_allowed:"method_not_allowed",midturn_blocks_rejected:"invalid_request",not_found:"not_found",overloaded:"capacity_exceeded",payload_too_large:"payload_too_large",platform_unavailable:"capability_unavailable",rate_limited:"capacity_exceeded",request_already_resolved:"conflict",request_expired:"gone",request_not_found:"not_found",resume_unavailable:"conflict",session_ended:"gone",session_limit_exceeded:"capacity_exceeded",session_mismatch:"conflict",session_not_found:"not_found",store_corrupted:"internal_error",turn_running:"conflict",unauthorized:"unauthorized",upstream_unavailable:"upstream_unavailable",validation_failed:"invalid_request"},"sdk2-ext-v1":{archive_gap:"gap",binding_closed:"gone",binding_conflict:"conflict",capability_unconfirmed:"upstream_unavailable",capacity_exceeded:"capacity_exceeded",epoch_unavailable:"upstream_unavailable",forbidden:"forbidden",internal_error:"internal_error",invalid_coverage:"invalid_request",invalid_request:"invalid_request",material_rejected:"rejected",payload_too_large:"payload_too_large",protocol_version_mismatch:"protocol_mismatch",receipt_expired:"gone",request_expired:"gone",request_id_conflict:"conflict",source_unavailable:"upstream_unavailable",stale_generation:"stale_generation",stream_cursor_expired:"gone",stream_cursor_unknown:"gap",stream_gap:"gap",unauthorized:"unauthorized",unsupported_capability:"capability_unavailable"},"sdk2-cache-v1":{capacity_exceeded:"capacity_exceeded",epoch_unavailable:"upstream_unavailable",forbidden:"forbidden",invalid_request:"invalid_request",mapping_expired:"gone",mapping_unavailable:"not_found",payload_too_large:"payload_too_large",projection_stale:"stale_generation",protocol_version_mismatch:"protocol_mismatch",receipt_expired:"gone",request_id_conflict:"conflict",result_unknown:"result_unknown",stale_generation:"stale_generation",stale_revision:"conflict",ticket_expired:"gone",unauthorized:"unauthorized",unsupported_capability:"capability_unavailable"},"terminal-services-v1":{binding_conflict:"conflict",busy:"conflict",capability_unconfirmed:"upstream_unavailable",capacity_exceeded:"capacity_exceeded",commit_unknown:"result_unknown",context_transition_required:"stale_generation",forbidden:"forbidden",integrity_mismatch:"conflict",invalid_request:"invalid_request",not_found:"not_found",output_gap:"gap",payload_too_large:"payload_too_large",protocol_version_mismatch:"protocol_mismatch",request_conflict:"conflict",request_limit:"capacity_exceeded",revision_conflict:"conflict",source_unavailable:"upstream_unavailable",stale_generation:"stale_generation",unauthorized:"unauthorized",unsupported_capability:"capability_unavailable"}},Iv={"agent-session-v1":{},"sdk2-ext-v1":{none:"none","query-status":"query-status",rebind:"rebind","same-request":"same-request"},"sdk2-cache-v1":{none:"none","query-status":"query-status","refresh-projection":"refresh","same-request":"same-request"},"terminal-services-v1":{backoff:"same-request",discover:"rediscover",none:"none",reconcile:"query-status",refresh:"refresh"}};var Fx=Object.keys(Id);function Tv(t){return Object.hasOwn(Id,t)}function Ad(t,e){let n=Id[t];return Object.hasOwn(n,e)?n[e]??null:null}function Av(t){let e=new Set;for(let n of Fx){let i=Ad(n,t);i!==null&&e.add(i)}return e.size===1?[...e][0]??null:null}function Td(t,e){let n=Iv[t];return Object.hasOwn(n,e)?n[e]??null:null}function kf(t,e,n){let i=n??null,o=Ad(t,e);if(o===null)return{code:"internal_error",status:500,retryAction:(i===null?null:Td(t,i))??"none",domainCode:e,domainRetryAction:i};let s=Rd[o],a=i===null?null:Td(t,i);return{code:o,status:s.status,retryAction:a??s.retryAction,domainCode:e,domainRetryAction:i}}function zx(t){let e=mi[t];return Tv(e)?e:t==="terminal-observation"||t==="terminal-profile"?"terminal-services-v1":null}var Gx={invalid_request:[400,422],conflict:[409,412],gap:[409,410],capability_unavailable:[404,403],capacity_exceeded:[429,503]};function Ev(t,e,n){let i=Gx[t];return i!==void 0&&i.includes(n)?n:e}function Wx(t,e,n,i){if(Ad(t,e)!==null){let a=kf(t,e,n);return{code:a.code,status:Ev(a.code,a.status,i),retryAction:a.retryAction}}let o=Av(e);if(o!==null){let a=Rd[o],d=n===null?null:Td(t,n);return{code:o,status:Ev(o,a.status,i),retryAction:d??a.retryAction}}let s=kf(t,e,n);return{code:s.code,status:i,retryAction:s.retryAction}}function Ed(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Vx(t){if(!Ed(t)||t.contract===an)return null;let e=t.error;return Ed(e)&&typeof e.code=="string"?{code:e.code,message:typeof e.message=="string"?e.message:null,retryAction:null,requestId:null,fallback:void 0,retryAfterMs:void 0,detail:Ed(e.detail)?e.detail:null}:typeof t.code=="string"?{code:t.code,message:typeof t.message=="string"?t.message:null,retryAction:typeof t.retryAction=="string"?t.retryAction:null,requestId:typeof t.requestId=="string"?t.requestId:null,fallback:typeof t.fallback=="string"?t.fallback:void 0,retryAfterMs:typeof t.retryAfterMs=="number"?t.retryAfterMs:void 0,detail:null}:null}var $x=/\/v[123](?:\/\S*)?(?!\S)/g;function Kx(t,e){let n=new Set([e]);for(let[o,s]of[["/v3/sdk2/sessions","/v2/sessions"],["/v3/sdk2/executors","/v2/executors"]])(e===o||e.startsWith(`${o}/`))&&n.add(`${s}${e.slice(o.length)}`),(e===s||e.startsWith(`${s}/`))&&n.add(`${o}${e.slice(s.length)}`);let i=o=>n.has(o)?t:xu(o)??t;return{path:i,text:o=>o.replace($x,s=>i(s))}}var Qx=new Set(["domainCode","domainStatus","domainRetryAction","fallback","retryAfterMs"]);function Jx(t){let e=Vx(t.body);if(e===null)return null;let n=Kx(t.apiPathname,t.legacyPathname),i=Wx(t.family,e.code,e.retryAction,t.status),o={domainCode:e.code,domainStatus:t.status,domainRetryAction:e.retryAction,...e.fallback!==void 0?{fallback:e.fallback}:{},...e.retryAfterMs!==void 0?{retryAfterMs:e.retryAfterMs}:{}};if(e.detail!==null)for(let[s,a]of Object.entries(e.detail))Qx.has(s)||(o[s]=s==="path"&&typeof a=="string"?n.path(a):a);return{contract:an,traceId:t.traceId,requestId:e.requestId,code:i.code,status:i.status,retryAction:i.retryAction,message:n.text(e.message??e.code),detail:o}}var Yx=/^application\/json(?:\s*;.*)?$/i,Cv=1024*1024;function Xx(t){let e={};if(t==null)return e;if(Array.isArray(t)){let n=t;for(let i=0;i<n.length;i+=1){let o=n[i];Array.isArray(o)?e[String(o[0]).toLowerCase()]=o[1]:(e[String(o).toLowerCase()]=n[i+1],i+=1)}return e}for(let[n,i]of Object.entries(t))i!==void 0&&(e[n.toLowerCase()]=i);return e}function Zx(t){let e=typeof t[0]=="number"?t[0]:Number(t[0]),n=typeof t[1]=="string"?t[1]:void 0,i=typeof t[1]=="string"?t[2]:t[1];return{status:e,statusMessage:n,headers:Xx(i)}}function _v(t){if(t!==void 0)return Array.isArray(t)?t.length>0?String(t[0]):void 0:String(t)}function eR(t,e){return t==null?null:Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength):typeof t=="string"?Buffer.from(t,typeof e=="string"?e:"utf8"):null}function Pv(t,e,n){let i=zx(n.domain);if(i===null)return;let o=(t.url??"").split("?",1)[0],s=n.legacyPathname,a=e.writeHead,d=e.write,c=e.end,l="idle",f=null,u=[],m=0,g=w=>{if(w.status<400)return!1;let T=_v(w.headers["content-type"])??_v(e.getHeader("content-type"));return T!==void 0&&Yx.test(T)},h=(w,x,T)=>{w.statusMessage===void 0?a.call(e,x,T):a.call(e,x,w.statusMessage,T)},p=(w,x)=>{let T=f;l="passthrough";let M=Buffer.concat(u);u.length=0,!e.destroyed&&(h(T,T.status,T.headers),w?c.call(e,M,x):d.call(e,M,x))},v=(w,x)=>{let T=f,M;try{M=JSON.parse(Buffer.concat(u).toString("utf8"))}catch{return w?(p(!0,x),!0):!1}let W=Ed(M)?Jx({family:i,status:T.status,body:M,apiPathname:o,legacyPathname:s,traceId:ii(t)?.requestId??Hx()}):null;if(W===null)return w?(p(!0,x),!0):!1;l="passthrough",u.length=0;let $=Buffer.from(JSON.stringify(W),"utf8"),D={...T.headers,"content-length":$.length};return W.status===401&&D["www-authenticate"]===void 0&&e.getHeader("www-authenticate")===void 0&&(D["www-authenticate"]="Bearer"),e.destroyed||(h(T,W.status,D),w?c.call(e,$,x):d.call(e,$,x)),!0},b=(w,x)=>{let T=eR(w,x);T!==null&&(u.push(T),m+=T.length)},R=()=>{let w={status:e.statusCode,statusMessage:void 0,headers:{}};g(w)?(l="buffering",f=w):l="passthrough"};e.writeHead=function(...x){if(l==="passthrough")return a.apply(this,x);let T=Zx(x);return l==="buffering"?(f=T,this):g(T)?(l="buffering",f=T,this):(l="passthrough",a.apply(this,x))},e.write=function(x,T,M){if(l==="idle"&&R(),l!=="buffering")return d.call(this,x,T,M);let W=typeof T=="function"?T:M;return b(x,T),m>Cv?(p(!1,W),!0):(!v(!1,W)&&typeof W=="function"&&process.nextTick(W),!0)},e.end=function(x,T,M){if(l==="idle"&&R(),l!=="buffering")return c.call(this,x,T,M);let W=[x,T,M].find($=>typeof $=="function");return typeof x!="function"&&b(x,T),m>Cv?p(!0,W):v(!0,W),this}}var is="tansr-event-envelope",Pd="unified-v1",Iq=Object.freeze(["contract","eventId","domain","type","cursorSet","terminalStatus","raw"]);function tR(t){let e=t.headers[is],n=Array.isArray(e)?e.length===1?e[0]:void 0:e;return e===void 0?"absent":n===Pd?"unified-v1":"invalid"}var Mv=Object.freeze({eventCursor:null,archiveCoverage:null,outputWatermark:null,materialConsumed:null,ackReceipt:null});function ns(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Cd(t){return typeof t=="string"?t:null}function nR(t,e,n,i){let o=i===null?Mv:{...Mv,eventCursor:i},s=null,a=ns(n.payload)?n.payload:void 0;switch(t){case"session":e==="turn.completed"||e==="session.ended"?s="completed":(e==="turn.aborted"||e==="turn.error"&&n.recoverable===!1)&&(s="aborted");break;case"archive":if(e==="archive.status"&&a!==void 0&&ns(a.acknowledgedCoverage))o={...o,archiveCoverage:a.acknowledgedCoverage};else if(e==="material.status"&&a!==void 0){let d=a.state;d==="received"?s="accepted":d==="core-consumed"?(s="completed",o={...o,materialConsumed:Cd(a.materialRequestId)}):d==="rejected"&&(s="aborted")}else e==="binding.status"&&a!==void 0&&a.state==="closed"&&(s="completed");break;case"terminal":e==="operation-cancelled"?s="aborted":e==="output.block"&&ns(n.block)?o={...o,outputWatermark:Cd(n.block.seq)}:e==="output.status"&&ns(n.status)&&n.status.state==="complete"&&(s="completed");break;default:break}return{cursorSet:o,terminalStatus:s}}var _d=10,Bv=13;function iR(t){let e=[],n=0;for(let i=0;i<t.length;i+=1){let o=t.charCodeAt(i);if(o===_d)e.push({text:t.slice(n,i),eol:`
|
|
24
|
+
`}),n=i+1;else if(o===Bv){let s=t.charCodeAt(i+1)===_d;e.push({text:t.slice(n,i),eol:s?`\r
|
|
25
|
+
`:"\r"}),s&&(i+=1),n=i+1}}return n<t.length&&e.push({text:t.slice(n),eol:""}),e}function rR(t){if(t.startsWith(":"))return"comment";let e=t.indexOf(":");if(e<0)return{field:t,value:""};let n=t.slice(e+1);return{field:t.slice(0,e),value:n.startsWith(" ")?n.slice(1):n}}function oR(t,e){let n=iR(t.toString("utf8")),i,o,s=new Set,a=[];for(let v=0;v<n.length;v+=1){let b=n[v];if(b.text==="")continue;let R=rR(b.text);R!=="comment"&&(R.field==="data"?(s.add(v),a.push(R.value)):R.field==="event"?i=R.value:R.field==="id"&&!R.value.includes("\0")&&(o=R.value))}if(s.size===0)return t;let d=a.join(`
|
|
26
|
+
`),c;try{c=JSON.parse(d)}catch{return t}if(!ns(c))return t;let l=i??Cd(c.type)??Cd(c.eventType),f=o??null,u=nR(e,l,c,f),m=`{"contract":${JSON.stringify(an)},"eventId":${JSON.stringify(f)},"domain":${JSON.stringify(e)},"type":${JSON.stringify(l)},"cursorSet":${JSON.stringify(u.cursorSet)},"terminalStatus":${JSON.stringify(u.terminalStatus)},"raw":${d}}`,g=Math.min(...s),h=n[g].eol===""?`
|
|
27
|
+
`:n[g].eol,p="";for(let v=0;v<n.length;v+=1){let b=n[v];if(v===g)for(let R of m.split(`
|
|
28
|
+
`))p+=`data: ${R}${h}`;else s.has(v)||(p+=b.text+b.eol)}return Buffer.from(p,"utf8")}var sR=1<<20,Qr=Buffer.alloc(0),xf=class{#e;#n;#r=Qr;#s=0;#t=0;#o=!1;constructor(e){this.#e=e.domain,this.#n=e.maxCarryBytes??sR}get carryBytes(){return this.#r.length}push(e){if(e.length===0)return Qr;let n=this.#r.length===0?e:Buffer.concat([this.#r,e]),i=[],o=0,s=this.#s,a=this.#t;for(;a<n.length;){let c=n[a],l;if(c===_d)l=a+1;else if(c===Bv){if(a+1>=n.length)break;l=n[a+1]===_d?a+2:a+1}else{a+=1;continue}let f=a===s;if(s=l,a=l,f){let u=n.subarray(o,l);i.push(this.#o?u:oR(u,this.#e)),this.#o=!1,o=l}}let d=n.subarray(o);if(this.#o||d.length>this.#n){this.#o=!0;let c=n.length-a,l=d.length-c;l>0&&i.push(d.subarray(0,l)),this.#r=c>0?Buffer.from(d.subarray(l)):Qr,this.#s=s-o-l,this.#t=0}else this.#r=d.length===0?Qr:Buffer.from(d),this.#s=s-o,this.#t=a-o;return i.length===0?Qr:i.length===1?i[0]:Buffer.concat(i)}flush(){let e=this.#r;return this.#r=Qr,this.#s=0,this.#t=0,this.#o=!1,e}};function Ov(t,e){if(typeof t=="string")return Buffer.from(t,e??"utf8");if(Buffer.isBuffer(t))return t;if(t instanceof Uint8Array)return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function aR(t,e){let n=typeof e[1]=="string"?e[2]:e[1];if(Array.isArray(n))for(let o=0;o<n.length;o+=1){let s=n[o];if(Array.isArray(s)){if(String(s[0]).toLowerCase()==="content-type")return String(s[1])}else if(typeof s=="string"&&s.toLowerCase()==="content-type")return String(n[o+1])}else if(n!=null&&typeof n=="object"){for(let[o,s]of Object.entries(n))if(o.toLowerCase()==="content-type")return Array.isArray(s)?String(s[0]):String(s)}let i=t.getHeader("content-type");if(typeof i=="string")return i;if(Array.isArray(i))return i[0]}function dR(t){return t!==void 0&&/^\s*text\/event-stream(?:\s*;|\s*$)/i.test(t)}function cR(t,e){let n=t.writeHead,i=t.write,o=t.end,s=!1,a,d=c=>{s||t.headersSent||(s=!0,dR(aR(t,c))&&(t.setHeader(is,Pd),a=new xf({domain:e})))};t.writeHead=function(...l){return d(l),n.apply(this,l)},t.write=function(l,f,u){s||d([]);let m=i;if(a===void 0)return m.call(this,l,f,u);let g=typeof f=="string"?f:void 0,h=typeof f=="function"?f:u,p=Ov(l,g);if(p===void 0)return m.call(this,l,f,u);let v=a.push(p);return v.length===0?(h!==void 0&&process.nextTick(h),!this.writableNeedDrain):h===void 0?m.call(this,v):m.call(this,v,h)},t.end=function(l,f,u){s||d([]);let m=o;if(a===void 0)return m.call(this,l,f,u);let g=typeof l=="function"?void 0:l,h=typeof l=="function"?l:typeof f=="function"?f:u,p=typeof f=="string"?f:void 0,v=[];if(g!=null){let R=Ov(g,p);if(R===void 0)return m.call(this,l,f,u);v.push(a.push(R))}v.push(a.flush()),a=void 0;let b=Buffer.concat(v);return b.length===0?h===void 0?m.call(this):m.call(this,h):h===void 0?m.call(this,b):m.call(this,b,h)}}function Dv(t,e,n){let i=tR(t);return i==="unified-v1"&&cR(e,n),i}var mn={format:"tansr-api-manifest-v1",contract:"unified-v1",revision:7,schemaHash:"b60e77ffcbf08d985a993dbdbd4cf610f12f7c7e70f090aee5ff8d523f70bb57",families:[{id:"agent-session-v1",domains:["session"],status:"frozen",rfc:"doc/98-Agent会话服务v2契约冻结件.md",source:"packages/server/src/v2/contract.ts",sha256:"6e1876edc476322e2fc3613958f5b44700bb80ea23550fa794f5729220674f3e",golden:{"packages/cli/test/fixtures/agent-v2-frames/frames.json":"5d3a40dcfea3709a06b78dd9a0066f68194efff96ebc4defc79476a589161d50","packages/protocol/schemas/kernel-event.schema.json":"54b587ade59bf20a3d55647a160c3d857dbf2fa73730d82cf7811b7ee4097501"},generated:[],legacyEntries:["/v2/sessions","/v2/sessions/:id/**"],apiEntries:["/api/sessions","/api/sessions/:id/**","/api/capabilities/sessions"],clients:[{client:"node",repo:"tansr-cli",lock:"source",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"contract/session-compatibility.json",lock:"route-vectors",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",file:"core/src/test/resources/contract/vendored.json",lock:"MANIFEST-revision-9",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",file:"Tests/TansrCoreTests/Fixtures/contract/vendored.json",lock:"MANIFEST-revision-9",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",file:"tests/fixtures/PROVENANCE.json",lock:"sourceCommit-ad43a96d",observed:"2026-10-01",drift:!1}],requestIdPath:null,sessionManifestRevision:9,sessionManifestSha256:"6e1876edc476322e2fc3613958f5b44700bb80ea23550fa794f5729220674f3e"},{id:"sdk2-ext-v1",domains:["archive","execution"],status:"final",rfc:"doc/rfc/RFC-SDK2-1-兼容SDK1的扩展协议.md",source:"doc/rfc/sdk2-ext-v1.schema.json",sha256:"969273844ca9196f19dd71b292b65a49307d63be0d20a0caf557e105ba6d8605",golden:{"scripts/sdk2/fixtures/sdk2-wire-v1.json":"d911959c91182834af396e09c523a14f223a65871588561dff5faf1d0ba27930"},generated:["packages/api-client/src/sdk2/wire-schema-generated.ts","packages/api-client/src/sdk2/wire-types-generated.ts","packages/api-client/src/sdk2/wire-limits-generated.ts","packages/server/src/v2/execution-contract.generated.ts"],legacyEntries:["/v3/sdk2/capabilities","/v3/sdk2/session-capabilities","/v3/sdk2/sessions/:id/binding-target","/v3/sdk2/bindings","/v3/sdk2/bindings/:id/**","/v3/sdk2/operations","/v3/sdk2/sessions/**","/v3/sdk2/executors/**","/v2/sessions/:id/initialize","/v2/sessions/:id/execution-capabilities","/v2/sessions/:id/execution-boundary","/v2/sessions/:id/execution-bindings","/v2/sessions/:id/executions/:targetId","/v2/executors/connections","/v2/executors/:id/heartbeats","/v2/executors/:id/operations","/v2/executors/:id/receipts"],apiEntries:["/api/capabilities/archive","/api/capabilities/sessions","/api/sessions/:id/binding-target","/api/archive/bindings","/api/archive/bindings/:id/**","/api/archive/operations","/api/executors/**","/api/sessions/:id/initialize","/api/sessions/:id/execution-capabilities","/api/sessions/:id/execution-boundary","/api/sessions/:id/execution-bindings","/api/sessions/:id/executions/:targetId"],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Protocol/WireContract.cs",lock:"969273844ca9196f19dd71b292b65a49307d63be0d20a0caf557e105ba6d8605",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",file:"core/src/main/kotlin/com/tansr/sdk/sdk2/Sdk2NamedSchema.kt",lock:"969273844ca9196f19dd71b292b65a49307d63be0d20a0caf557e105ba6d8605",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",file:"Sources/TansrCore/SDK2/Sdk2SchemaResource.swift",lock:"969273844ca9196f19dd71b292b65a49307d63be0d20a0caf557e105ba6d8605",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",file:"tansr/src/main/ets/core/sdk2/client/SchemaGenerated.ets",lock:"969273844ca9196f19dd71b292b65a49307d63be0d20a0caf557e105ba6d8605",observed:"2026-10-01",drift:!1}],requestIdPath:["request","requestId"]},{id:"sdk2-archive-recovery-v1",domains:["archive"],status:"additive",rfc:"doc/rfc/RFC-SDK2-ACK-recovery-v1.md",source:"doc/rfc/sdk2-archive-recovery-v1.schema.json",sha256:"f530de1096b4f5d56ea688b7f2cec9ae66deb7d3719db85ab1f48287d3bd7ad4",golden:{"doc/rfc/sdk2-archive-recovery-v1.golden.json":"614adf2088585a6213d010acde29598d40757d0f2d7b4608f1670ccbde3a5553","doc/rfc/sdk2-archive-recovery-v1.sqlite.sql":"a6fcfef2458cb0dcf9788af2385573c85b238dc875dee7ffc144f27dcc28028b"},generated:["packages/api-client/src/sdk2/archive-recovery-schema-generated.ts","packages/api-client/src/sdk2/archive-recovery-types-generated.ts","packages/server/src/sdk2/archive-recovery-contract.generated.ts"],legacyEntries:["/v3/sdk2/bindings/:id/archive/ack-rebases"],apiEntries:["/api/archive/bindings/:id/archive/ack-rebases"],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Archive/Recovery",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",lock:"absent",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",lock:"absent",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",lock:"absent",observed:"2026-10-01",drift:!1}],requestIdPath:["request","requestId"]},{id:"archive-sync-v1",domains:["archive-sync"],status:"additive",rfc:"doc/rfc/SDK2-档案同步与保留扩展.md",source:"doc/rfc/archive-sync-v1.schema.json",sha256:"7468fb72c80ce8d0bbe298219c894578020f249d7532c63cad91e8dad4a412bb",golden:{},generated:[],legacyEntries:["/v3/sdk2/archive-sync/:id"],apiEntries:["/api/archive/sync/:id"],clients:[{client:"node",repo:"tansr-cli",file:"packages/api-client/src/sdk2/receiver-sync-client.ts",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Archive/Replication/ArchiveSyncClient.cs",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",file:"core/src/main/kotlin/com/tansr/sdk/sdk2/receiver/Sdk2ArchiveSyncClient.kt",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",file:"Sources/TansrCore/SDK2/Sdk2ArchiveSync.swift",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",file:"tansr/src/main/ets/core/sdk2/client/ArchiveSync.ets",lock:"hand-written",observed:"2026-10-01",drift:!1}],requestIdPath:null},{id:"sdk2-cache-v1",domains:["cache"],status:"drafted",rfc:"doc/rfc/RFC-SDK2-缓存连续性.md",source:"doc/rfc/sdk2-cache-v1.schema.json",sha256:"88e7941861fab1a6380b9226e3a42adb8c872efdf720dc36e92ffa42da43d818",golden:{},generated:[],legacyEntries:["/v3/sdk2/cache/capabilities","/v3/sdk2/cache/bindings","/v3/sdk2/cache/bindings/:id/**","/v3/sdk2/cache/operations"],apiEntries:["/api/capabilities/cache","/api/cache/bindings","/api/cache/bindings/:id/**","/api/cache/operations"],clients:[{client:"node",repo:"tansr-cli",file:"packages/providers/src/twp/cache-wire.ts",lock:"88e7941861fab1a6380b9226e3a42adb8c872efdf720dc36e92ffa42da43d818",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Cache/CacheClient.cs",lock:"hand-written-internal",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",lock:"absent",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",lock:"absent",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",lock:"absent",observed:"2026-10-01",drift:!1}],requestIdPath:["request","requestId"]},{id:"sdk2-cache-core-v1",domains:["cache"],status:"additive",rfc:"doc/rfc/sdk2-cache-core-v1.md",source:"doc/rfc/sdk2-cache-core-v1.schema.json",sha256:"5b052117919f3ef751310a36db3a2c1dac96daeda2f10a4bb78028edc0d5cbff",golden:{},generated:[],legacyEntries:["/v3/sdk2/cache/core/v1/bindings/:id/diagnostics"],apiEntries:["/api/cache/core/v1/bindings/:id/diagnostics"],clients:[{client:"node",repo:"tansr-cli",file:"packages/providers/src/twp/cache-core-wire.ts",lock:"5b052117919f3ef751310a36db3a2c1dac96daeda2f10a4bb78028edc0d5cbff",observed:"2026-10-01",drift:!1}],requestIdPath:["request","requestId"]},{id:"terminal-services-v1",domains:["terminal"],status:"candidate",rfc:"doc/rfc/RFC-SERVE-NET-1-终端增量工具与记忆协议.md",source:"doc/rfc/terminal-services-v1.schema.json",sha256:"8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",golden:{"doc/rfc/terminal-services-v1.golden.json":"a19ee430360ca883723bb5836e8966e51e83f9831c57b1da3c1368cd3ef5e66a"},generated:["packages/api-client/src/terminal/wire-schema-generated.ts","packages/api-client/src/terminal/wire-types-generated.ts","packages/server/src/v2/terminal-contract.generated.ts"],legacyEntries:["/v3/terminal/capabilities","/v3/terminal/bindings","/v3/terminal/executors/:id/**","/v3/terminal/sessions/:id/**"],apiEntries:["/api/capabilities/terminal","/api/terminal/bindings","/api/terminal/executors/:id/**","/api/terminal/sessions/:id/**"],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Terminal/Contract/manifest.json",lock:"8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",file:"core/src/main/resources/terminal/terminal-services-v1.schema.json",lock:"8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",file:"Sources/TansrCore/Terminal/TerminalSchemaResource.swift",lock:"8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",file:"tansr/src/main/ets/core/terminal/SchemaGenerated.ets",lock:"8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",observed:"2026-10-01",drift:!1}],requestIdPath:["requestId"]},{id:"terminal-observation-v1",domains:["terminal-observation"],status:"additive",rfc:"doc/rfc/RFC-SERVE-NET-1-终端增量工具与记忆协议.md",source:"doc/rfc/terminal-observation-v1.schema.json",sha256:"b6668463458e78b2cfe23baa72d9d9ac6263a248467dd8aeb60387fc2f67c28a",golden:{"doc/rfc/terminal-observation-v1.golden.json":"2148eb11fb4538736cd244b17e5ba135bc26919081105fd1018ff884ab364e1a"},generated:["packages/api-client/src/terminal/observation-wire-schema-generated.ts","packages/api-client/src/terminal/observation-wire-types-generated.ts","packages/server/src/v2/terminal-observation-contract.generated.ts"],legacyEntries:["/v3/terminal-observation/sessions/:id/resources","/v3/terminal-observation/sessions/:id/output-correlations"],apiEntries:["/api/terminal/observation/sessions/:id/resources","/api/terminal/observation/sessions/:id/output-correlations"],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Terminal/TerminalObservationClient.cs",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",lock:"absent",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",lock:"absent",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",lock:"absent",observed:"2026-10-01",drift:!1}],requestIdPath:["requestId"]},{id:"terminal-profile-v1",domains:["terminal-profile"],status:"additive",rfc:"doc/rfc/RFC-SERVE-NET-1-终端增量工具与记忆协议.md",source:"doc/rfc/terminal-profile-v1.schema.json",sha256:"560ad136f0619a2a0592151d56e10871c3799ca438163c4e2872381bf5f5159a",golden:{"doc/rfc/terminal-profile-v1.golden.json":"6ecfea5872a8cb2052d35cb908839c7ab07c11d77f65dc7e9a230494a2cf8ea4"},generated:["packages/api-client/src/terminal/profile-wire-schema-generated.ts","packages/api-client/src/terminal/profile-wire-types-generated.ts","packages/server/src/v2/terminal-profile-contract.generated.ts"],legacyEntries:["/v3/terminal-profile/sessions/:id/catalog","/v3/terminal-profile/sessions/:id/usage"],apiEntries:["/api/terminal/profile/sessions/:id/catalog","/api/terminal/profile/sessions/:id/usage"],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Terminal/TerminalProfileClient.cs",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",lock:"absent",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",lock:"absent",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",lock:"absent",observed:"2026-10-01",drift:!1}],requestIdPath:["requestId"]},{id:"terminal-shell-sandbox-v1",domains:["terminal"],status:"additive",rfc:"doc/rfc/RFC-SERVE-NET-1-终端增量工具与记忆协议.md",source:"doc/rfc/terminal-shell-sandbox-v1.schema.json",sha256:"be3ebcf6dc650844319a18a15f6abbefb9316f704410b591f9ba6dcab7620fe1",golden:{"doc/rfc/terminal-shell-sandbox-v1.golden.json":"ad76d8eae6970835a0995475ce4cb6e0a58ded5bc7b4e50bf01a3e5dc0212563"},generated:["packages/api-client/src/terminal/shell-sandbox-schema-generated.ts","packages/api-client/src/terminal/shell-sandbox-types-generated.ts","packages/server/src/v2/terminal-shell-sandbox-contract.generated.ts","packages/server/src/v2/terminal-shell-sandbox-codec.generated.ts"],legacyEntries:[],apiEntries:[],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",lock:"hand-written",observed:"2026-10-01",drift:!1}],requestIdPath:null},{id:"unified-v1",domains:["discovery"],status:"candidate",rfc:"doc/rfc/RFC-UAPI-1-统一信封与canonical单模块.md",source:"doc/rfc/unified-v1.schema.json",sha256:"fd07962916f7662ecc69c3f8c8d2b79aa5b99f542cbfd310a50f56777e51f117",golden:{"doc/rfc/unified-v1.golden.json":"42531a3937563d8c0d719c5970629b25bbabf3a8ea8436550db5bfddf9d206fd"},generated:[],legacyEntries:[],apiEntries:["/api/manifest","/api/capabilities","/api/sessions/:id/capabilities"],clients:[{client:"node",repo:"tansr-cli",file:"packages/api-client/src/api/operations-generated.ts",lock:"generated",observed:"2026-10-01",drift:!1},{client:"go",repo:"tansr-go",file:"contract/PROVENANCE.json",lock:"manifest-sha256",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"contract/manifest.json",lock:"manifest-sha256",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",file:"contract/api-contract.lock.json",lock:"manifest-sha256",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",file:"contract/api-contract.lock.json",lock:"manifest-sha256",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",file:"contract/api-contract.lock.json",lock:"manifest-sha256",observed:"2026-10-01",drift:!1}],requestIdPath:null}],operations:[{name:"discovery.manifest",domain:"discovery",family:null,method:"GET",apiPath:"/api/manifest",aliases:[],legacyPath:null,legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:null,query:[],notes:"门面自答:本 manifest + runtime.installed(已装配域);无领域 schema",etagPath:null,expectedRevision:null},{name:"discovery.capabilities",domain:"discovery",family:null,method:"GET",apiPath:"/api/capabilities",aliases:[],legacyPath:null,legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:null,query:[],notes:"门面自答:域可用性 / 族与 schemaHash / 会话族 preferred+available(部署级;不含 URL 导航字段,RFC-SDK2-1 §10.5)",etagPath:null,expectedRevision:null},{name:"discovery.session.capabilities",domain:"discovery",family:null,method:"GET",apiPath:"/api/sessions/:id/capabilities",aliases:[],legacyPath:null,legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:null,query:[],notes:"会话级能力闭合围栏(方案 §3.6 / RFC-UAPI-1 §1.4):{ contract, closureId, authorizationRevision, domains, operations } + 响应头 tansr-closure-id;写操作可携 tansr-closure-id 作前置(412 closure_stale)",etagPath:null,expectedRevision:null},{name:"session.capabilities",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/capabilities/sessions",aliases:[],legacyPath:"/v3/sdk2/session-capabilities",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:null,query:["protocol"],notes:"会话族发现 { protocol, contracts[{ contract, availability }] } 内联于 v2/routes.ts,无命名 schema",etagPath:null,expectedRevision:null},{name:"session.create",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions",aliases:[],legacyPath:"/v2/sessions",legacyOffloadPath:"/v3/sdk2/sessions",kind:"write",sse:!1,request:"agent-session-v1#CreateSessionBodySchema",response:null,query:[],notes:"201 { sessionId, resumed, lastSeq, ...familyView } 无命名响应 schema;attach / resume / fork 同端点",etagPath:null,expectedRevision:null},{name:"session.list",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions",aliases:[],legacyPath:"/v2/sessions",legacyOffloadPath:"/v3/sdk2/sessions",kind:"read",sse:!1,request:null,response:null,query:["limit","offset"],notes:"响应 { sessions: V2SessionMetaView[], total } 无命名 schema",etagPath:null,expectedRevision:null},{name:"session.get",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id",aliases:[],legacyPath:"/v2/sessions/:id",legacyOffloadPath:"/v3/sdk2/sessions/:id",kind:"read",sse:!1,request:null,response:"agent-session-v1#V2SessionMetaView",query:["include"],notes:null,etagPath:null,expectedRevision:null},{name:"session.close",domain:"session",family:"agent-session-v1",method:"DELETE",apiPath:"/api/sessions/:id",aliases:[],legacyPath:"/v2/sessions/:id",legacyOffloadPath:"/v3/sdk2/sessions/:id",kind:"write",sse:!1,request:null,response:null,query:[],notes:"202 { sessionId, accepted: true };休眠会话幂等 202",etagPath:null,expectedRevision:null},{name:"session.message.send",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/messages",aliases:[],legacyPath:"/v2/sessions/:id/messages",legacyOffloadPath:"/v3/sdk2/sessions/:id/messages",kind:"write",sse:!1,request:"agent-session-v1#MessagesBodySchema",response:null,query:[],notes:"202 { sessionId, accepted: true };事件经 session.events.observe",etagPath:null,expectedRevision:null},{name:"session.events.observe",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/events",aliases:[],legacyPath:"/v2/sessions/:id/events",legacyOffloadPath:"/v3/sdk2/sessions/:id/events",kind:"stream",sse:!0,request:null,response:null,query:["exclude"],notes:"Last-Event-ID 续订;帧 = KernelEvent(golden kernel-event.schema.json)+ 控制帧 CONTROL_FRAME",etagPath:null,expectedRevision:null},{name:"session.interrupt",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/interrupt",aliases:[],legacyPath:"/v2/sessions/:id/interrupt",legacyOffloadPath:"/v3/sdk2/sessions/:id/interrupt",kind:"write",sse:!1,request:null,response:null,query:[],notes:"202 { sessionId, accepted: true }",etagPath:null,expectedRevision:null},{name:"session.history.read",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/history",aliases:[],legacyPath:"/v2/sessions/:id/history",legacyOffloadPath:"/v3/sdk2/sessions/:id/history",kind:"read",sse:!1,request:null,response:null,query:["offset","limit"],notes:"响应 { sessionId, lastSeq, messages[, total, offset] } 无命名 schema",etagPath:null,expectedRevision:null},{name:"session.tool.result",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/tool-results/:targetId",aliases:[],legacyPath:"/v2/sessions/:id/tool-results/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/tool-results/:targetId",kind:"write",sse:!1,request:"agent-session-v1#ToolResultReceiptSchema",response:null,query:[],notes:":targetId = toolCallId(doc/98 ⑨ :callId);200 { accepted: true }",etagPath:null,expectedRevision:null},{name:"session.permission.decide",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/permission/:ticketId",aliases:[],legacyPath:"/v2/sessions/:id/permission/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/permission/:targetId",kind:"write",sse:!1,request:"agent-session-v1#PermissionReceiptSchema",response:null,query:[],notes:"wire 仍为 requestId(/v2 ⑩⑪ 服务端签发票据);统一层按 RFC-UAPI-1 §3 消歧命名 :ticketId(D26 代拍 2026-10-03:/api 观测模板同口径),内部 /v2 / /v3 模板占位为 :targetId",etagPath:null,expectedRevision:null},{name:"session.question.answer",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/questions/:ticketId",aliases:[],legacyPath:"/v2/sessions/:id/questions/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/questions/:targetId",kind:"write",sse:!1,request:"agent-session-v1#QuestionReceiptSchema",response:null,query:[],notes:"wire 仍为 requestId(/v2 ⑩⑪ 服务端签发票据);统一层按 RFC-UAPI-1 §3 消歧命名 :ticketId(D26 代拍 2026-10-03:/api 观测模板同口径),内部 /v2 / /v3 模板占位为 :targetId",etagPath:null,expectedRevision:null},{name:"session.compact",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/compact",aliases:[],legacyPath:"/v2/sessions/:id/compact",legacyOffloadPath:"/v3/sdk2/sessions/:id/compact",kind:"write",sse:!1,request:"agent-session-v1#CompactBodySchema",response:"agent-session-v1#V2CompactResult",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"session.checkpoint.list",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/checkpoints",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints",kind:"read",sse:!1,request:null,response:"agent-session-v1#V2CheckpointList",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"session.checkpoint.create",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/checkpoints",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints",kind:"write",sse:!1,request:"agent-session-v1#CheckpointBodySchema",response:"agent-session-v1#V2CheckpointMeta",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"session.checkpoint.import",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/checkpoints/import",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints/import",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints/import",kind:"write",sse:!1,request:null,response:"agent-session-v1#V2CheckpointMeta",query:["label"],notes:"体 = checkpoint.export 原字节(application/octet-stream,≤ 32 MiB),非 JSON schema;201",etagPath:null,expectedRevision:null},{name:"session.checkpoint.restore",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/checkpoints/:targetId/restore",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints/:targetId/restore",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints/:targetId/restore",kind:"write",sse:!1,request:"agent-session-v1#RestoreBodySchema",response:"agent-session-v1#V2RestoreResult",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"session.checkpoint.export",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/checkpoints/:targetId/export",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints/:targetId/export",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints/:targetId/export",kind:"read",sse:!1,request:null,response:null,query:[],notes:'200 application/octet-stream:{ format: "tansr-checkpoint/1", checkpoint, attachments },非 JSON schema',etagPath:null,expectedRevision:null},{name:"session.checkpoint.delete",domain:"session",family:"agent-session-v1",method:"DELETE",apiPath:"/api/sessions/:id/checkpoints/:targetId",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints/:targetId",kind:"write",sse:!1,request:null,response:null,query:[],notes:"204 无体",etagPath:null,expectedRevision:null},{name:"session.cwd.set",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/cwd",aliases:[],legacyPath:"/v2/sessions/:id/cwd",legacyOffloadPath:"/v3/sdk2/sessions/:id/cwd",kind:"write",sse:!1,request:"agent-session-v1#SetCwdBodySchema",response:"agent-session-v1#V2SetCwdResult",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"session.audio.transcribe",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/audio/transcriptions",aliases:[],legacyPath:"/v2/sessions/:id/audio/transcriptions",legacyOffloadPath:"/v3/sdk2/sessions/:id/audio/transcriptions",kind:"write",sse:!1,request:"agent-session-v1#AudioTranscriptionsBodySchema",response:null,query:[],notes:"响应为平台转写结果透传(doc/123 §3.1),无本仓命名 schema",etagPath:null,expectedRevision:null},{name:"session.audio.speak",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/audio/speech",aliases:[],legacyPath:"/v2/sessions/:id/audio/speech",legacyOffloadPath:"/v3/sdk2/sessions/:id/audio/speech",kind:"write",sse:!1,request:"agent-session-v1#AudioSpeechBodySchema",response:null,query:[],notes:"响应为平台合成结果透传(doc/123 §3.2),无本仓命名 schema",etagPath:null,expectedRevision:null},{name:"session.input.capabilities",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/input-capabilities",aliases:[],legacyPath:"/v2/sessions/:id/input-capabilities",legacyOffloadPath:"/v3/sdk2/sessions/:id/input-capabilities",kind:"read",sse:!1,request:null,response:null,query:[],notes:"响应 = kernel SessionInputCapabilities(字段见 CAPABILITIES session.input.*),contract.ts 无命名 schema",etagPath:null,expectedRevision:null},{name:"session.input.submit",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/inputs",aliases:[],legacyPath:"/v2/sessions/:id/inputs",legacyOffloadPath:"/v3/sdk2/sessions/:id/inputs",kind:"write",sse:!1,request:"agent-session-v1#SubmitInputBodySchema",response:null,query:[],notes:"响应 = kernel SessionInputResult(accepted 携 SessionInputReceipt),contract.ts 无命名 schema",etagPath:null,expectedRevision:null},{name:"session.input.status",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/inputs/:targetId",aliases:[],legacyPath:"/v2/sessions/:id/inputs/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/inputs/:targetId",kind:"read",sse:!1,request:null,response:null,query:["historyEpoch","turnId"],notes:":targetId = inputId;响应 = kernel SessionInputReceipt,contract.ts 无命名 schema",etagPath:null,expectedRevision:null},{name:"approval.credential.submit",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/approvals/:id/credential",aliases:[],legacyPath:"/v1/approvals/:id/credential",legacyOffloadPath:null,kind:"write",sse:!1,request:null,response:null,query:[],notes:':id = challengeId;体 { digest, verdict: approve|deny, approver }(RFC-K11 §3.2,无命名 schema);200 { challengeId, result: "accepted" };拒绝经统一信封:unknown_challenge → not_found 404、expired → gone 410、digest_mismatch / already_resolved → conflict 409(detail.submitCode 留原 SubmitCode);approvals 缝未接线 → 404 capability_unavailable',etagPath:null,expectedRevision:null},{name:"execution.initialize",domain:"execution",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/sessions/:id/initialize",aliases:[],legacyPath:"/v2/sessions/:id/initialize",legacyOffloadPath:"/v3/sdk2/sessions/:id/initialize",kind:"write",sse:!1,request:"sdk2-ext-v1#SessionInitializeRequest",response:"sdk2-ext-v1#SessionExecutionCapabilities",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"execution.capabilities",domain:"execution",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/sessions/:id/execution-capabilities",aliases:[],legacyPath:"/v2/sessions/:id/execution-capabilities",legacyOffloadPath:"/v3/sdk2/sessions/:id/execution-capabilities",kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#SessionExecutionCapabilities",query:["protocol"],notes:null,etagPath:null,expectedRevision:null},{name:"execution.boundary",domain:"execution",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/sessions/:id/execution-boundary",aliases:[],legacyPath:"/v2/sessions/:id/execution-boundary",legacyOffloadPath:"/v3/sdk2/sessions/:id/execution-boundary",kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#ExecutionBoundary",query:["protocol"],notes:null,etagPath:null,expectedRevision:null},{name:"execution.binding.create",domain:"execution",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/sessions/:id/execution-bindings",aliases:[],legacyPath:"/v2/sessions/:id/execution-bindings",legacyOffloadPath:"/v3/sdk2/sessions/:id/execution-bindings",kind:"write",sse:!1,request:"sdk2-ext-v1#ExecutionBindingRequest",response:"sdk2-ext-v1#SessionExecutionCapabilities",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"execution.status",domain:"execution",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/sessions/:id/executions/:targetId",aliases:[],legacyPath:"/v2/sessions/:id/executions/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/executions/:targetId",kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#ExecutionStatus",query:["protocol"],notes:":targetId = operationId",etagPath:null,expectedRevision:null},{name:"executor.register",domain:"execution",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/executors/connections",aliases:[],legacyPath:"/v2/executors/connections",legacyOffloadPath:"/v3/sdk2/executors/connections",kind:"write",sse:!1,request:"sdk2-ext-v1#ExecutorRegistrationRequest",response:"sdk2-ext-v1#ExecutorConnection",query:[],notes:"201",etagPath:null,expectedRevision:null},{name:"executor.heartbeat",domain:"execution",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/executors/:id/heartbeats",aliases:[],legacyPath:"/v2/executors/:id/heartbeats",legacyOffloadPath:"/v3/sdk2/executors/:id/heartbeats",kind:"write",sse:!1,request:"sdk2-ext-v1#ExecutorHeartbeatRequest",response:"sdk2-ext-v1#ExecutorConnection",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"executor.operations.poll",domain:"execution",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/executors/:id/operations",aliases:[],legacyPath:"/v2/executors/:id/operations",legacyOffloadPath:"/v3/sdk2/executors/:id/operations",kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#ExecutionBatch",query:["protocol","connectionId"],notes:null,etagPath:null,expectedRevision:null},{name:"executor.receipt.submit",domain:"execution",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/executors/:id/receipts",aliases:[],legacyPath:"/v2/executors/:id/receipts",legacyOffloadPath:"/v3/sdk2/executors/:id/receipts",kind:"write",sse:!1,request:"sdk2-ext-v1#ExecutionReceiptRequest",response:"sdk2-ext-v1#ExecutionStatus",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"archive.capabilities",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/capabilities/archive",aliases:[],legacyPath:"/v3/sdk2/capabilities",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#CapabilitiesResponse",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"archive.binding.target",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/sessions/:id/binding-target",aliases:[],legacyPath:"/v3/sdk2/sessions/:id/binding-target",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#BindingTargetRequest",response:"sdk2-ext-v1#BindingTargetView",query:["protocol"],notes:null,etagPath:["revision"],expectedRevision:null},{name:"archive.binding.create",domain:"archive",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/archive/bindings",aliases:[],legacyPath:"/v3/sdk2/bindings",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-ext-v1#BindingCreateRequest",response:"sdk2-ext-v1#BindingView",query:[],notes:"201",etagPath:["revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"archive.binding.get",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id",aliases:[],legacyPath:"/v3/sdk2/bindings/:id",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#BindingView",query:["protocol"],notes:null,etagPath:["revision"],expectedRevision:null},{name:"archive.binding.close",domain:"archive",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/archive/bindings/:id/close",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/close",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-ext-v1#BindingCloseRequest",response:"sdk2-ext-v1#MutationReceipt",query:[],notes:null,etagPath:["revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"archive.status",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/archive/status",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/archive/status",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#ArchiveStatus",query:["protocol"],notes:null,etagPath:["revision"],expectedRevision:null},{name:"archive.events.observe",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/events",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/events",legacyOffloadPath:null,kind:"stream",sse:!0,request:null,response:"sdk2-ext-v1#EventFrame",query:["protocol"],notes:"Last-Event-ID 续订(独立重放日志 / 游标)",etagPath:null,expectedRevision:null},{name:"archive.records.read",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/archive/records",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/archive/records",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#ArchiveReadRequest",response:"sdk2-ext-v1#ArchivePage",query:["protocol","historyEpoch","deletionGeneration","projectionRevision","limit","maxBytes","afterSequence"],notes:null,etagPath:null,expectedRevision:null},{name:"archive.artifact.read",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/archive/artifacts/:targetId",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/archive/artifacts/:targetId",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#ArtifactReadRequest",response:"sdk2-ext-v1#ArtifactChunk",query:["protocol","historyEpoch","deletionGeneration","projectionRevision","offset","maxBytes"],notes:":targetId = artifactId",etagPath:null,expectedRevision:null},{name:"archive.ack.commit",domain:"archive",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/archive/bindings/:id/archive/acks",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/archive/acks",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-ext-v1#ArchiveAckRequest",response:"sdk2-ext-v1#MutationReceipt",query:[],notes:null,etagPath:["revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"archive.ack.rebase",domain:"archive",family:"sdk2-archive-recovery-v1",method:"POST",apiPath:"/api/archive/bindings/:id/archive/ack-rebases",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/archive/ack-rebases",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-archive-recovery-v1#AckRebaseRequest",response:"sdk2-archive-recovery-v1#AckRebaseReceipt",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"archive.operation.query",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/operations",aliases:[],legacyPath:"/v3/sdk2/operations",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#OperationStatusRequest",response:"sdk2-ext-v1#MutationReceipt",query:["protocol","operation","operationEpoch","requestId","bindingId","sessionId"],notes:"operation ∈ binding-create(携 sessionId)| archive-ack | material-response | binding-close(携 bindingId);material-response 回 MaterialReceipt",etagPath:null,expectedRevision:null},{name:"archive.sync",domain:"archive-sync",family:"archive-sync-v1",method:"POST",apiPath:"/api/archive/sync/:id",aliases:[],legacyPath:"/v3/sdk2/archive-sync/:id",legacyOffloadPath:null,kind:"write",sse:!1,request:"archive-sync-v1#Request",response:"archive-sync-v1#Response",query:[],notes:"单入口多方法:method 词表 archive-sync-v1#Method(= sdk2/archive-sync.ts methods);value 形随方法;错误形 archive-sync-v1#ErrorResponse(不在统一错误矩阵,经 /api 原样透传);:id = bindingId",etagPath:null,expectedRevision:null},{name:"material.response.submit",domain:"archive",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/archive/bindings/:id/material-responses",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/material-responses",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-ext-v1#MaterialResponseRequest",response:"sdk2-ext-v1#MaterialReceipt",query:[],notes:"202",etagPath:null,expectedRevision:null},{name:"material.status",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/materials/:targetId",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/materials/:targetId",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#MaterialStatusRequest",response:"sdk2-ext-v1#MaterialReceipt",query:["protocol"],notes:":targetId = materialRequestId",etagPath:null,expectedRevision:null},{name:"material.upload.status",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/materials/:targetId/uploads/:uploadId",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/materials/:targetId/uploads/:uploadId",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#MaterialUploadStatusRequest",response:"sdk2-ext-v1#MaterialUploadStatus",query:["protocol"],notes:":uploadId = artifactId",etagPath:null,expectedRevision:null},{name:"material.upload.chunk",domain:"archive",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/archive/bindings/:id/materials/:targetId/uploads/:uploadId/chunks",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/materials/:targetId/uploads/:uploadId/chunks",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-ext-v1#MaterialUploadChunkRequest",response:"sdk2-ext-v1#MaterialUploadStatus",query:[],notes:":uploadId = artifactId",etagPath:null,expectedRevision:null},{name:"cache.capabilities",domain:"cache",family:"sdk2-cache-v1",method:"GET",apiPath:"/api/capabilities/cache",aliases:[],legacyPath:"/v3/sdk2/cache/capabilities",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"sdk2-cache-v1#CapabilitiesResponse",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"cache.binding.open",domain:"cache",family:"sdk2-cache-v1",method:"POST",apiPath:"/api/cache/bindings",aliases:[],legacyPath:"/v3/sdk2/cache/bindings",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-cache-v1#OpenRequest",response:"sdk2-cache-v1#OpenResponse",query:[],notes:null,etagPath:["binding","revision"],expectedRevision:null},{name:"cache.binding.get",domain:"cache",family:"sdk2-cache-v1",method:"GET",apiPath:"/api/cache/bindings/:id",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-cache-v1#BindingQuery",response:"sdk2-cache-v1#BindingView",query:["protocol"],notes:null,etagPath:["revision"],expectedRevision:null},{name:"cache.binding.renew",domain:"cache",family:"sdk2-cache-v1",method:"POST",apiPath:"/api/cache/bindings/:id/renew",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id/renew",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-cache-v1#RenewRequest",response:"sdk2-cache-v1#MutationReceipt",query:[],notes:null,etagPath:["binding","revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"cache.binding.rebind",domain:"cache",family:"sdk2-cache-v1",method:"POST",apiPath:"/api/cache/bindings/:id/rebind",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id/rebind",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-cache-v1#RebindRequest",response:"sdk2-cache-v1#MutationReceipt",query:[],notes:null,etagPath:["binding","revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"cache.binding.rotate",domain:"cache",family:"sdk2-cache-v1",method:"POST",apiPath:"/api/cache/bindings/:id/rotate",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id/rotate",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-cache-v1#RotateRequest",response:"sdk2-cache-v1#MutationReceipt",query:[],notes:null,etagPath:["binding","revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"cache.binding.close",domain:"cache",family:"sdk2-cache-v1",method:"POST",apiPath:"/api/cache/bindings/:id/close",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id/close",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-cache-v1#CloseRequest",response:"sdk2-cache-v1#MutationReceipt",query:[],notes:null,etagPath:["binding","revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"cache.operation.query",domain:"cache",family:"sdk2-cache-v1",method:"GET",apiPath:"/api/cache/operations",aliases:[],legacyPath:"/v3/sdk2/cache/operations",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-cache-v1#OperationQuery",response:"sdk2-cache-v1#MutationReceipt",query:["protocol","operation","operationEpoch","requestId","bindingId"],notes:"operation ∈ open | renew | rebind | rotate | close",etagPath:null,expectedRevision:null},{name:"cache.diagnostics",domain:"cache",family:"sdk2-cache-v1",method:"GET",apiPath:"/api/cache/bindings/:id/diagnostics",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id/diagnostics",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-cache-v1#DiagnosticQuery",response:"sdk2-cache-v1#DiagnosticPage",query:["protocol","after","limit"],notes:null,etagPath:null,expectedRevision:null},{name:"cache.core.diagnostics",domain:"cache",family:"sdk2-cache-core-v1",method:"GET",apiPath:"/api/cache/core/v1/bindings/:id/diagnostics",aliases:[],legacyPath:"/v3/sdk2/cache/core/v1/bindings/:id/diagnostics",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"sdk2-cache-core-v1#Diagnostics",query:["protocol","limit","after"],notes:"protocol = sdk2-cache-core-v1",etagPath:null,expectedRevision:null},{name:"terminal.capabilities",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/capabilities/terminal",aliases:[],legacyPath:"/v3/terminal/capabilities",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#CapabilitiesResponse",query:["contract"],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.binding.create",domain:"terminal",family:"terminal-services-v1",method:"POST",apiPath:"/api/terminal/bindings",aliases:[],legacyPath:"/v3/terminal/bindings",legacyOffloadPath:null,kind:"write",sse:!1,request:"terminal-services-v1#BindingRequest",response:"terminal-services-v1#BindingResponse",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.executor.events.observe",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/executors/:id/events",aliases:[],legacyPath:"/v3/terminal/executors/:id/events",legacyOffloadPath:null,kind:"stream",sse:!0,request:null,response:"terminal-services-v1#ExecutorEvent",query:["contract","sessionContract","connectionId"],notes:":id = executorId;Last-Event-ID = Sequence 游标",etagPath:null,expectedRevision:null},{name:"terminal.output.batch",domain:"terminal",family:"terminal-services-v1",method:"POST",apiPath:"/api/terminal/executors/:id/output-batches",aliases:[],legacyPath:"/v3/terminal/executors/:id/output-batches",legacyOffloadPath:null,kind:"write",sse:!1,request:"terminal-services-v1#OutputBatchRequest",response:"terminal-services-v1#OutputStatus",query:[],notes:":id = executorId",etagPath:null,expectedRevision:null},{name:"terminal.execution.state",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/executors/:id/operations/:targetId",aliases:[],legacyPath:"/v3/terminal/executors/:id/operations/:targetId",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#ExecutionState",query:["contract","sessionContract","sessionId","requestDigest","connectionId"],notes:":id = executorId;:targetId = operationId",etagPath:null,expectedRevision:null},{name:"terminal.output.observe",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/sessions/:id/tool-output",aliases:[],legacyPath:"/v3/terminal/sessions/:id/tool-output",legacyOffloadPath:null,kind:"stream",sse:!0,request:null,response:"terminal-services-v1#OutputEvent",query:["contract","sessionContract","operationId","requestDigest","afterSeq"],notes:"输出水位以 afterSeq 续订,不接受 Last-Event-ID",etagPath:null,expectedRevision:null},{name:"terminal.output.status",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/sessions/:id/tool-output-status",aliases:[],legacyPath:"/v3/terminal/sessions/:id/tool-output-status",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#OutputStatus",query:["contract","sessionContract","operationId","requestDigest"],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.configuration.read",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/sessions/:id/configuration",aliases:["/api/sessions/:id/configuration"],legacyPath:"/v3/terminal/sessions/:id/configuration",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#ConfigurationResponse",query:["contract","sessionContract"],notes:null,etagPath:["configuration","revision"],expectedRevision:null},{name:"terminal.configuration.commit",domain:"terminal",family:"terminal-services-v1",method:"POST",apiPath:"/api/terminal/sessions/:id/configuration",aliases:["/api/sessions/:id/configuration"],legacyPath:"/v3/terminal/sessions/:id/configuration",legacyOffloadPath:null,kind:"write",sse:!1,request:"terminal-services-v1#ConfigurationRequest",response:"terminal-services-v1#ConfigurationCommitResponse",query:[],notes:null,etagPath:["configuration","revision"],expectedRevision:{path:["expectedRevision"],kind:"integer"}},{name:"terminal.memory.read",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/sessions/:id/memory",aliases:["/api/sessions/:id/memory"],legacyPath:"/v3/terminal/sessions/:id/memory",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#MemoryStateResponse",query:["contract","sessionContract"],notes:null,etagPath:["memory","revision"],expectedRevision:null},{name:"terminal.memory.command",domain:"terminal",family:"terminal-services-v1",method:"POST",apiPath:"/api/terminal/sessions/:id/memory/commands",aliases:["/api/sessions/:id/memory/commands"],legacyPath:"/v3/terminal/sessions/:id/memory/commands",legacyOffloadPath:null,kind:"write",sse:!1,request:"terminal-services-v1#MemoryCommandRequest",response:"terminal-services-v1#MemoryReceiptResponse",query:[],notes:null,etagPath:null,expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"terminal.memory.receipt",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/sessions/:id/memory/commands/:targetId",aliases:["/api/sessions/:id/memory/commands/:targetId"],legacyPath:"/v3/terminal/sessions/:id/memory/commands/:targetId",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#MemoryReceiptResponse",query:["contract","sessionContract","requestId"],notes:":targetId = operationId",etagPath:null,expectedRevision:null},{name:"terminal.observation.resources",domain:"terminal-observation",family:"terminal-observation-v1",method:"GET",apiPath:"/api/terminal/observation/sessions/:id/resources",aliases:[],legacyPath:"/v3/terminal-observation/sessions/:id/resources",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-observation-v1#ResourcesResponse",query:["contract","sessionContract"],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.observation.correlations",domain:"terminal-observation",family:"terminal-observation-v1",method:"GET",apiPath:"/api/terminal/observation/sessions/:id/output-correlations",aliases:[],legacyPath:"/v3/terminal-observation/sessions/:id/output-correlations",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-observation-v1#CorrelationsResponse",query:["contract","sessionContract","toolCallId"],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.profile.catalog",domain:"terminal-profile",family:"terminal-profile-v1",method:"GET",apiPath:"/api/terminal/profile/sessions/:id/catalog",aliases:[],legacyPath:"/v3/terminal-profile/sessions/:id/catalog",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-profile-v1#CatalogResponse",query:["contract","sessionContract"],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.profile.usage",domain:"terminal-profile",family:"terminal-profile-v1",method:"GET",apiPath:"/api/terminal/profile/sessions/:id/usage",aliases:[],legacyPath:"/v3/terminal-profile/sessions/:id/usage",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-profile-v1#UsageResponse",query:["contract","sessionContract"],notes:null,etagPath:null,expectedRevision:null}],capabilities:[{id:"archive.limit.controlBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:262144,default:262144}},{id:"archive.limit.recordBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:262144,default:262144}},{id:"archive.limit.pageRecords",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:128,default:128}},{id:"archive.limit.pageBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:1048576,default:1048576}},{id:"archive.limit.attachmentBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:33554432,default:33554432}},{id:"archive.limit.chunkBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:262144,default:262144}},{id:"archive.limit.materialConcurrent",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:2,default:2}},{id:"archive.limit.materialQueue",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:16,default:16}},{id:"archive.limit.materialCandidates",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:32,default:32}},{id:"archive.limit.materialBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:1048576,default:1048576}},{id:"archive.limit.materialDeadlineMs",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1e3,max:3e4,default:3e4}},{id:"archive.limit.pendingRecords",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:4096,default:4096}},{id:"archive.limit.pendingBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1048576,max:67108864,default:67108864}},{id:"archive.limit.inflightReserveBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1048576,max:16777216,default:16777216}},{id:"archive.limit.offlineMs",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1e3,max:864e5,default:864e5}},{id:"archive.limit.eventRetentionMs",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1e3,max:6e5,default:6e5}},{id:"archive.limit.eventRetentionFrames",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:4096,default:4096}},{id:"archive.limit.eventRetentionBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:8388608,default:8388608}},{id:"archive.limit.terminalReceiptRetentionMs",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:6e4,max:6048e5,default:6048e5}},{id:"archive.limit.epochLifetimeMs",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:6e4,max:864e5,default:36e5}},{id:"archive.limit.materialChunkBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:65536,default:65536}},{id:"archive.capability.archive-transfer-v1",domain:"archive",family:"sdk2-ext-v1",kind:"capability",source:"doc/rfc/sdk2-ext-v1.schema.json#Capability",value:"archive-transfer-v1"},{id:"archive.capability.context-materials-v1",domain:"archive",family:"sdk2-ext-v1",kind:"capability",source:"doc/rfc/sdk2-ext-v1.schema.json#Capability",value:"context-materials-v1"},{id:"cache.feature.private-logical-cache-v1",domain:"cache",family:"sdk2-cache-v1",kind:"feature",source:"doc/rfc/sdk2-cache-v1.schema.json#Feature",value:"private-logical-cache-v1"},{id:"cache.feature.trusted-core-projection-v1",domain:"cache",family:"sdk2-cache-core-v1",kind:"feature",source:"doc/rfc/sdk2-cache-core-v1.schema.json#Capabilities",value:"trusted-core-projection-v1"},{id:"cache.feature.bounded-diagnostics-v1",domain:"cache",family:"sdk2-cache-core-v1",kind:"feature",source:"doc/rfc/sdk2-cache-core-v1.schema.json#Capabilities",value:"bounded-diagnostics-v1"},{id:"terminal.feature.execution-stream-v1",domain:"terminal",family:"terminal-services-v1",kind:"feature",source:"doc/rfc/terminal-services-v1.schema.json#Feature",value:"execution-stream-v1"},{id:"terminal.feature.execution-background-v1",domain:"terminal",family:"terminal-services-v1",kind:"feature",source:"doc/rfc/terminal-services-v1.schema.json#Feature",value:"execution-background-v1"},{id:"terminal.feature.memory-lifecycle-v1",domain:"terminal",family:"terminal-services-v1",kind:"feature",source:"doc/rfc/terminal-services-v1.schema.json#Feature",value:"memory-lifecycle-v1"},{id:"terminal.feature.session-configuration-v1",domain:"terminal",family:"terminal-services-v1",kind:"feature",source:"doc/rfc/terminal-services-v1.schema.json#Feature",value:"session-configuration-v1"},{id:"session.input.version",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"1"},{id:"session.input.text",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"boolean"},{id:"session.input.textBlocks",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"boolean"},{id:"session.input.image",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"false"},{id:"session.input.memoryAck",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"boolean"},{id:"session.input.durableAck",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"false"},{id:"session.input.receiptRetention",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"'current-and-last-turn'"},{id:"session.input.target",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"SessionInputTarget | null"}],platformApi:[{id:"sdk-cross-repo-contract-v1",doc:"doc/89-SDK跨仓契约v1.md",host:"tansr-api",entries:["/t1/*","/v1/app-tokens","/v1/my-usage"],vendored:"packages/sdk/contract/openapi.json"},{id:"sdk2-cache-v1",doc:"doc/rfc/RFC-SDK2-缓存连续性.md",host:"tansr-api",entries:["/t1/cache/v1/*"],vendored:null},{id:"sdk2-cache-core-v1",doc:"doc/rfc/sdk2-cache-core-v1.md",host:"tansr-api",entries:["/t1/cache/core/v1/*"],vendored:null}]};import{createHash as lR,randomUUID as uR}from"node:crypto";import{Readable as fR}from"node:stream";var mr="idempotency-key",Md="if-match",pR="etag",Af="deadline",mR=/^[\x21-\x7e]{1,128}$/,hR=/^"(0|[1-9][0-9]{0,18})"$/,gR=/^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:[Zz]|[+-]\d{2}:\d{2})$/,rs=1024*1024,Uv=/^application\/json(?:\s*;.*)?$/i,Rf=Object.freeze({perUser:je.receiptTombstones,total:4096,ttlMs:10*6e4}),yR=new Set(["binding_conflict","stale_revision","revision_conflict"]),vR=Object.freeze(Object.fromEntries(mn.operations.flatMap(t=>{let e=t.etagPath,n=t.expectedRevision;return e===null&&n===null?[]:[[t.name,Object.freeze({...e===null?{}:{etag:e},...n===null?{}:{expected:n}})]]}))),bR=Object.freeze(Object.fromEntries(mn.families.map(t=>[t.id,t.requestIdPath]))),SR=new Set(["sdk2-ext-v1","sdk2-archive-recovery-v1","archive-sync-v1","sdk2-cache-v1","sdk2-cache-core-v1","terminal-services-v1","terminal-observation-v1","terminal-profile-v1"]),wR=mn.operations.flatMap(t=>[t.apiPath,...t.aliases].map(e=>({name:t.name,kind:t.kind,family:t.family,method:t.method,pattern:new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/:[A-Za-z]+/g,"[^/]+")}$`)})));function kR(t,e){return wR.find(n=>n.method===t&&n.pattern.test(e))}var Ef=class{#e=new Map;#n=new Map;#r;#s;constructor(e={}){this.#r={perUser:e.perUser??Rf.perUser,total:e.total??Rf.total,ttlMs:e.ttlMs??Rf.ttlMs},this.#s=e.now??Date.now}get size(){return this.#e.size}#t(e,n){this.#e.delete(e);let i=(this.#n.get(n.owner)??1)-1;i<=0?this.#n.delete(n.owner):this.#n.set(n.owner,i),n.state==="pending"&&(n.state="unretained",n.settle())}#o(){let e=this.#s();for(let[n,i]of this.#e)i.state!=="pending"&&i.expiresAt<=e&&this.#t(n,i)}lookup(e){let n=this.#e.get(e);if(n!==void 0){if(n.state!=="pending"&&n.expiresAt<=this.#s()){this.#t(e,n);return}return n}}begin(e,n,i){this.#o();let o=this.#n.get(n)??0;if(o>=this.#r.perUser){let c=[...this.#e].find(([,l])=>l.owner===n&&l.state!=="pending");if(c===void 0)return null;this.#t(c[0],c[1])}if(this.#e.size>=this.#r.total){let c=[...this.#e].find(([,l])=>l.state!=="pending");if(c===void 0)return null;this.#t(c[0],c[1])}let s=()=>{},a=new Promise(c=>{s=c}),d={owner:n,fingerprint:i,expiresAt:Number.POSITIVE_INFINITY,state:"pending",receipt:null,settled:a,settle:s};return this.#e.set(e,d),this.#n.set(n,o+1),d}complete(e,n,i){if(this.#e.get(e)!==n){n.state==="pending"&&(n.state="unretained",n.settle());return}n.receipt=i,n.state=i===null?"unretained":"stored",n.expiresAt=this.#s()+this.#r.ttlMs,n.settle()}abandon(e,n){this.#e.get(e)===n?this.#t(e,n):n.state==="pending"&&(n.state="unretained",n.settle())}},xR=new Ef;function Jr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function os(t,e){let n=t.headers[e];return Array.isArray(n)?n.join(", "):n}function RR(t){return ii(t)?.requestId??uR()}function Cf(t,e){let n=t;for(let i of e){if(!Jr(n))return;n=n[i]}return n}function IR(t){if(typeof t=="number")return Number.isSafeInteger(t)&&t>=0?`"${t}"`:void 0;if(typeof t=="string"&&/^(0|[1-9][0-9]{0,18})$/.test(t))return`"${t}"`}function TR(t){let e=hR.exec(t.trim());return e===null?null:e[1]}function AR(t){let e=t.trim();if(!gR.test(e))return null;let n=Date.parse(e.toUpperCase());return Number.isFinite(n)?n:null}function Bi(t,e,n){if(e.destroyed||e.writableEnded)return;let i=Buffer.from(JSON.stringify({contract:an,traceId:RR(t),requestId:n.requestId,code:n.code,status:n.status,retryAction:n.retryAction,message:n.message,detail:n.detail}),"utf8");e.writeHead(n.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":i.length,...n.headers??{}}),e.end(i)}var Yr=class extends Error{constructor(){super("request body exceeds header processing limit"),this.name="BodyTooLargeError"}};function If(t){let e=[];for(;t.readableLength>0;){let n=t.read();if(n===null)break;e.push(Buffer.isBuffer(n)?n:Buffer.from(n))}return Buffer.concat(e)}function ER(t,e){return new Promise((n,i)=>{let o=[],s=0,a=fR.prototype.push,d=t,c=!1,l=()=>{c&&(delete d.push,c=!1)},f=p=>(s+=p.length,s>e?!1:(o.push(p),!0));if(t.complete){let p=If(t);if(p.length>0&&t.unshift(p),p.length>e){i(new Yr);return}n({bytes:p,refeed:v=>{v.equals(p)||(If(t),v.length>0&&t.unshift(v))}});return}let u=If(t);if(u.length>0&&!f(u)){i(new Yr);return}let m=()=>{l(),t.removeListener("error",g),t.removeListener("close",h),n({bytes:Buffer.concat(o),refeed:p=>{p.length>0&&a.call(t,p),a.call(t,null)}})},g=p=>{l(),i(p)},h=()=>{l(),i(new Error("request closed before body was received"))};t.once("error",g),t.once("close",h),c=!0,d.push=function(v,b){if(v==null)return m(),!1;let R=Buffer.isBuffer(v)?v:v instanceof Uint8Array?Buffer.from(v.buffer,v.byteOffset,v.byteLength):Buffer.from(String(v),b);return f(R)?!0:(l(),t.removeListener("error",g),t.removeListener("close",h),i(new Yr),!1)}})}function CR(t){let e={};if(t==null)return e;if(Array.isArray(t)){let n=t;for(let i=0;i<n.length;i+=1){let o=n[i];Array.isArray(o)?e[String(o[0]).toLowerCase()]=o[1]:(e[String(o).toLowerCase()]=n[i+1],i+=1)}return e}for(let[n,i]of Object.entries(t))i!==void 0&&(e[n.toLowerCase()]=i);return e}function qv(t){if(t!==void 0)return Array.isArray(t)?t.length>0?String(t[0]):void 0:String(t)}function jv(t,e){return t==null?null:Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength):typeof t=="string"?Buffer.from(t,typeof e=="string"?e:"utf8"):null}var _R=new Set(["x-request-id","date","connection","keep-alive","transfer-encoding","content-length","set-cookie"]);function PR(t){return t<500&&t!==408&&t!==429}function Tf(t,e,n){let i=e.writeHead,o=e.write,s=e.end,a="idle",d=null,c=[],l=0,f=!1,u=w=>{f||(f=!0,e.removeListener("close",m),n.onFinal(w))},m=()=>u(null);e.once("close",m);let g=w=>{let T=qv(w["content-type"])??qv(e.getHeader("content-type"));return T!==void 0&&Uv.test(T)},h=(w,x)=>{let T=d;T.statusMessage===void 0?i.call(e,w,x):i.call(e,w,T.statusMessage,x)},p=(w,x)=>{let T=d;a="passthrough";let M=Buffer.concat(c);c.length=0,u(null),!e.destroyed&&(h(T.status,T.headers),w?s.call(e,M,x):o.call(e,M,x))},v=w=>{let x=d;a="passthrough";let T=Buffer.concat(c);c.length=0;let M=x.status,W={...x.headers},$;try{$=JSON.parse(T.toString("utf8"))}catch{$=void 0}if($!==void 0&&(n.ifMatch&&M>=400&&Jr($)&&$.contract===an&&Jr($.detail)&&typeof $.detail.domainCode=="string"&&yR.has($.detail.domainCode)&&(M=412,T=Buffer.from(JSON.stringify({...$,code:"precondition_failed",status:M,retryAction:"refresh",detail:{...$.detail,reason:"if_match_stale"}}),"utf8"),W["content-length"]=T.length),n.etagPath!==void 0&&M>=200&&M<300)){let D=IR(Cf($,n.etagPath));D!==void 0&&(W[pR]=D)}if(e.destroyed){u(null);return}if(PR(M)){let D={},J={...Object.fromEntries(Object.entries(e.getHeaders()).map(([S,k])=>[S.toLowerCase(),k])),...W};for(let[S,k]of Object.entries(J))_R.has(S)||k===void 0||(D[S]=Array.isArray(k)?k.map(String):String(k));u({status:M,headers:D,body:T})}else u(null);h(M,W),s.call(e,T,w)},b=(w,x)=>{let T=jv(w,x);T!==null&&(c.push(T),l+=T.length)},R=(w,x=!1)=>(d=w,a=x||g(w.headers)?"buffering":"passthrough",a);e.writeHead=function(...x){if(a==="passthrough")return i.apply(this,x);let T=typeof x[0]=="number"?x[0]:Number(x[0]),M=typeof x[1]=="string"?x[1]:void 0,W=typeof x[1]=="string"?x[2]:x[1],$={status:T,statusMessage:M,headers:CR(W)};return a==="buffering"?(d=$,this):R($)==="passthrough"?(u(null),i.apply(this,x)):this},e.write=function(x,T,M){if(a==="idle"&&R({status:e.statusCode,statusMessage:void 0,headers:{}})==="passthrough"&&u(null),a!=="buffering")return o.call(this,x,T,M);let W=typeof T=="function"?T:M;return b(x,T),l>rs?(p(!1,W),!0):(typeof W=="function"&&process.nextTick(W),!0)},e.end=function(x,T,M){if(a==="idle"){let $=typeof x=="function"||(jv(x,T)?.length??0)===0;R({status:e.statusCode,statusMessage:void 0,headers:{}},$)==="passthrough"&&u(null)}if(a!=="buffering")return s.call(this,x,T,M);let W=[x,T,M].find($=>typeof $=="function");return typeof x!="function"&&b(x,T),l>rs?p(!0,W):v(W),this}}var Nv=new WeakSet;function MR(t){return{idempotencyKey:os(t,mr),ifMatch:os(t,Md),deadline:os(t,Af)}}function OR(t,e,n,i,o){let s=lR("sha256");return s.update(t),s.update("\0"),s.update(e),s.update("\0"),s.update(os(n,"content-type")??""),s.update("\0"),s.update(i??""),s.update("\0"),s.update(o),s.digest("hex")}function Lv(t,e,n,i,o,s={}){if(Nv.has(t))return!1;Nv.add(t);let a=s.receipts??xR,d=s.now??Date.now,c=t.url??"",l=c.split("?",1)[0],f=kR(i,l),u=f===void 0?void 0:vR[f.name],m=MR(t),g=f?.family??mi[n.domain],h=f===void 0?i!=="GET"&&i!=="HEAD":f.kind==="write";if(m.idempotencyKey===void 0&&m.ifMatch===void 0&&m.deadline===void 0)return u?.etag!==void 0&&Tf(t,e,{ifMatch:!1,etagPath:u.etag,onFinal:()=>{}}),!1;let p=m.idempotencyKey!==void 0&&mR.test(m.idempotencyKey)?m.idempotencyKey:null,v=async w=>{await o.authenticated(t,e)!==null&&Bi(t,e,{...w,requestId:p})},b=(w,x,T,M=400)=>v({code:"invalid_request",status:M,retryAction:"none",message:T,detail:{reason:w,header:x}}),R=async()=>{if(m.idempotencyKey!==void 0){if(p===null)return b("idempotency_key_invalid",mr,"Idempotency-Key must be 1-128 printable ASCII characters");if(!h)return b("idempotency_key_not_applicable",mr,"Idempotency-Key applies to write operations only")}let w=null;if(m.ifMatch!==void 0){if(w=TR(m.ifMatch),w===null)return b("if_match_invalid",Md,"If-Match must be a single strong entity-tag derived from the resource revision");if(!h||u?.expected===void 0)return b("if_match_not_applicable",Md,"If-Match applies to write operations on versioned resources only")}if(m.deadline!==void 0){let C=AR(m.deadline);if(C===null)return b("deadline_invalid",Af,"deadline must be an RFC-3339 date-time");if(C<=d())return b("deadline_exceeded",Af,"request deadline has already passed",408)}if(p===null&&w===null){u?.etag!==void 0&&Tf(t,e,{ifMatch:!1,etagPath:u.etag,onFinal:()=>{}}),o.next();return}let x=null;if(p!==null&&(x=await o.authenticated(t,e),x===null)||t.destroyed||e.destroyed||e.writableEnded)return;let T;try{T=await ER(t,rs)}catch(C){return e.destroyed||e.writableEnded||t.destroyed?void 0:C instanceof Yr?v({code:"payload_too_large",status:413,retryAction:"none",message:"request body exceeds the header processing limit",detail:{reason:"header_body_limit",limitBytes:rs},headers:{connection:"close"}}):void 0}if(t.destroyed||e.destroyed||e.writableEnded)return;let M=null,W=null;if(p!==null){let C=OR(i,c,t,m.ifMatch,T.bytes);M=`${x}\0${f?.name??`${i} ${l}`}\0${mn.revision}\0${p}`;let F=a.lookup(M);if(F!==void 0){if(F.fingerprint!==C)return Bi(t,e,{code:"conflict",status:409,retryAction:"none",requestId:p,message:"Idempotency-Key was already used for a different request",detail:{domainCode:"request_id_conflict",reason:"idempotency_key_reused",header:mr}});if(F.state==="pending"){let H=()=>{},Q=new Promise(re=>{H=re,e.once("close",H)});try{await Promise.race([F.settled,Q])}finally{e.removeListener("close",H)}if(e.destroyed||e.writableEnded)return}if(F.state==="stored"&&F.receipt!==null){let H=F.receipt,Q=H.status===204||H.status===304;e.writeHead(H.status,{...H.headers,...Q?{}:{"content-length":H.body.length}}),e.end(Q?void 0:H.body);return}return Bi(t,e,{code:"result_unknown",status:503,retryAction:"query-status",requestId:p,message:"the original request with this Idempotency-Key was executed but its receipt was not retained; query its status instead of replaying",detail:{reason:"receipt_not_retained",header:mr}})}if(W=a.begin(M,x,C),W===null)return Bi(t,e,{code:"result_unknown",status:503,retryAction:"query-status",requestId:p,message:"idempotency receipt window is full of in-flight requests; query status before replaying",detail:{reason:"receipt_window_full",header:mr},headers:{"retry-after":"1"}})}let $=()=>{M!==null&&W!==null&&a.abandon(M,W)},D=T.bytes,J=os(t,"content-type");if(J!==void 0&&Uv.test(J)&&D.length>0&&(p!==null||w!==null)){let C;try{C=JSON.parse(D.toString("utf8"))}catch{C=void 0}if(Jr(C)){let F=!1,H=bR[g]??null;if(p!==null&&H!==null){let Q=H.length===1?C:Cf(C,H.slice(0,-1)),re=H[H.length-1];if(Jr(Q)){if(Q[re]===void 0)Q[re]=p,F=!0;else if(Q[re]!==p)return $(),Bi(t,e,{code:"conflict",status:409,retryAction:"none",requestId:p,message:"Idempotency-Key differs from the requestId carried in the body",detail:{domainCode:"request_id_conflict",reason:"idempotency_key_mismatch",header:mr}})}}if(w!==null&&u?.expected!==void 0){let{path:Q,kind:re}=u.expected,O=Q.length===1?C:Cf(C,Q.slice(0,-1)),I=Q[Q.length-1],B=re==="integer"?Number(w):w;if(Jr(O)){if(O[I]===void 0)O[I]=B,F=!0;else if(O[I]!==B)return $(),Bi(t,e,{code:"precondition_failed",status:412,retryAction:"refresh",requestId:p,message:"If-Match differs from the expectedRevision carried in the body",detail:{domainCode:"revision_conflict",reason:"if_match_body_mismatch",header:Md}})}}if(F){try{D=SR.has(g)?Buffer.from(bs(C,{maxBytes:rs})):Buffer.from(JSON.stringify(C),"utf8")}catch{return $(),Bi(t,e,{code:"invalid_request",status:400,retryAction:"none",requestId:p,message:"request body cannot be re-encoded after header mapping",detail:{reason:"header_body_not_canonical"}})}t.headers["content-length"]!==void 0&&(t.headers["content-length"]=String(D.length))}}}if(t.destroyed||e.destroyed||e.writableEnded){$();return}T.refeed(D);let k=M,A=W;Tf(t,e,{ifMatch:w!==null,etagPath:u?.etag,onFinal:C=>{k!==null&&A!==null&&a.complete(k,A,C)}}),o.next()};return o.track(R().catch(w=>{if(!(e.destroyed||e.writableEnded)){if(e.headersSent){e.destroy();return}Bi(t,e,{code:"internal_error",status:500,retryAction:"none",requestId:p,message:w instanceof Error?w.message:"request header processing failed",detail:{reason:"header_processing_failed"}})}})),!0}var _f="tansr-session-family",Xr="tansr-closure-id",DR=/^\/api\/sessions\/([^/]+)\/capabilities$/,qR=/^\/api\/sessions\/([^/]+)(?:\/|$)/,jR=mn.operations.flatMap(t=>[t.apiPath,...t.aliases].map(e=>({method:t.method,pattern:new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/:[A-Za-z]+/g,"[^/]+")}$`),name:t.name})));function NR(t,e){return jR.find(n=>n.method===t&&n.pattern.test(e))?.name}var UR={unauthorized:401,not_found:404,method_not_allowed:405,invalid_request:400,capability_unavailable:404,capacity_exceeded:503,precondition_failed:412,upstream_unavailable:503},LR={unauthorized:"none",not_found:"none",method_not_allowed:"none",invalid_request:"none",capability_unavailable:"none",capacity_exceeded:"same-request",precondition_failed:"rediscover",upstream_unavailable:"same-request"};function Hv(t){return mn.families.find(e=>e.id===t)}function zv(t){if(t==="discovery")return`sha256:${mn.schemaHash}`;let e=Hv(mi[t]);return e===void 0?"none":`sha256:${e.sha256}`}function Od(t,e){t.setHeader("tansr-contract",an),t.setHeader("tansr-manifest-revision",String(mn.revision)),t.setHeader("tansr-domain",e),t.setHeader("tansr-schema-hash",zv(e))}function FR(t){return ii(t)?.requestId??BR()}function Pf(t,e,n,i={}){if(t.destroyed||t.writableEnded)return;let o=Buffer.from(JSON.stringify(n),"utf8");t.writeHead(e,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length,...i}),t.end(o)}function _n(t,e,n,i,o={},s={}){let a=s.status??UR[n];Pf(e,a,{contract:an,traceId:FR(t),requestId:null,code:n,status:a,retryAction:LR[n],message:i,...s.detail!==void 0?{detail:s.detail}:{}},o)}function Fv(t){return t.headers["transfer-encoding"]!==void 0||t.headers["content-length"]!==void 0&&t.headers["content-length"]!=="0"}function Gv(t){let{authenticate:e,delegate:n,installed:i,track:o,sessionFamilies:s}=t,a=()=>{let w=t.retryAfterMs?.()??5e3;return{"retry-after":String(Math.max(1,Math.ceil(w/1e3)))}},d=async(w,x)=>{let T;try{T=await e(w,x)}catch(M){if(x.destroyed||x.writableEnded)return null;if(M instanceof Rt)return _n(w,x,"capacity_exceeded","authentication source unavailable",a()),null;T=null}return w.aborted||x.destroyed||x.writableEnded?null:T===null||typeof T.endUserId!="string"||T.endUserId===""?(_n(w,x,"unauthorized","authentication required",{"www-authenticate":"Bearer"}),null):T.endUserId},c=()=>{let w={};for(let x of Object.keys(mi)){let T=Hv(mi[x]),M=i[x];w[x]={installed:x==="session"?M!==null:M===!0,...x==="session"?{family:{preferred:M,available:s}}:{},contract:mi[x],status:T?.status??"unregistered",schemaHash:zv(x)}}return{contract:an,manifestRevision:mn.revision,schemaHash:`sha256:${mn.schemaHash}`,domains:w}},l=w=>{let x=w.headers[_f],T=Array.isArray(x)?x[0]:x;return T===void 0?{family:i.session}:T!=="sdk1"&&T!=="sdk2-offload-v1"?{family:null,error:"invalid"}:s.includes(T)?{family:T}:{family:null,error:"not_installed"}},f=()=>({...mn,runtime:{installed:i}}),u=async(w,x,T,M)=>{if(M!=="GET"){if(await d(w,x)===null)return;_n(w,x,"method_not_allowed",`${M} not allowed`,{allow:"GET"});return}if((w.url??"").includes("?")||Fv(w)){if(await d(w,x)===null)return;_n(w,x,"invalid_request","discovery endpoints accept no query string or body");return}await d(w,x)!==null&&Pf(x,200,T===Xi?f():c())},m=async(w,x,T,M,W)=>{await d(w,x)!==null&&_n(w,x,T,M,{},W===void 0?{}:{detail:W})},g=w=>w==="session"?i.session!==null:i[w]===!0,h=async(w,x,T,M)=>{if(t.sessionClosure===void 0||i.session===null){_n(w,x,"capability_unavailable","session capability closure is not installed on this serve",{},{detail:{reason:"not_installed"}});return}let W;try{W=decodeURIComponent(T)}catch{_n(w,x,"not_found","no such api resource");return}let $;try{$=await t.sessionClosure(W,M,w)}catch{if(x.destroyed||x.writableEnded)return;_n(w,x,"upstream_unavailable","capability closure source unavailable",a());return}if(!(w.aborted||x.destroyed||x.writableEnded)){if($===null){_n(w,x,"not_found","no such api resource");return}return $}},p=async(w,x,T,M)=>{let W=await d(w,x);if(W===null)return;if(M!=="GET"){_n(w,x,"method_not_allowed",`${M} not allowed`,{allow:"GET"});return}if((w.url??"").includes("?")||Fv(w)){_n(w,x,"invalid_request","capabilities accept no query string or body");return}let $=await h(w,x,T,W);$!==void 0&&Pf(x,200,$,{[Xr]:$.closureId})},v=(w,x,T,M)=>{if(Lv(w,x,T,M,{authenticated:d,track:o,next:()=>v(w,x,T,M)}))return;if(Dv(w,x,T.domain)==="invalid"){o(m(w,x,"invalid_request",`${is} must be ${Pd}`,{header:is}));return}Pv(w,x,T);let W=w.url??"",$=W.indexOf("?");w.url=$<0?T.legacyPathname:`${T.legacyPathname}${W.slice($)}`,!n(w,x,T.legacyPathname,M)&&o(m(w,x,"capability_unavailable",`${T.domain} does not serve this resource`,{reason:"not_installed"}))},b=async(w,x,T,M,W,$,D)=>{let J=await d(w,x);if(J===null)return;let S=await h(w,x,$,J);if(S===void 0)return;let k=kv(D,S);if(!k.ok){_n(w,x,"precondition_failed","capability closure is stale; rediscover before retrying",{[Xr]:k.closureId},{detail:{domainCode:k.code,closureId:k.closureId}});return}let A=NR(W,M),C=A===void 0?void 0:S.operations[A];if(C==="disabled"||C==="unavailable"){_n(w,x,"capability_unavailable",`${A} is ${C} for this session`,{[Xr]:S.closureId},{status:C==="disabled"?403:404,detail:{reason:"outside_closure",operation:A,state:C,closureId:S.closureId}});return}v(w,x,T,W)},R=w=>{let x=w.headers[Xr];return Array.isArray(x)?x[0]:x};return(w,x,T,M)=>{if(T!=="/api"&&!T.startsWith("/api/"))return!1;if(T===Xi||T===ku)return Od(x,"discovery"),o(u(w,x,T,M)),!0;let W=DR.exec(T);if(W!==null)return Od(x,"discovery"),o(p(w,x,W[1],M)),!0;let $=l(w),D=sg(T,{offloadSessions:$.family==="sdk2-offload-v1"});if(D===void 0)return Od(x,"discovery"),o(m(w,x,"not_found","no such api resource")),!0;if(Od(x,D.domain),!g(D.domain))return o(m(w,x,"capability_unavailable",`${D.domain} is not installed on this serve`,{reason:"not_installed"})),!0;if((D.domain==="session"||D.domain==="execution")&&$.error!==void 0)return o($.error==="invalid"?m(w,x,"invalid_request",`${_f} must be sdk1 or sdk2-offload-v1`):m(w,x,"capability_unavailable","requested session family is not installed on this serve",{reason:"not_installed",header:_f})),!0;let J=R(w);if(J!==void 0){let S=qR.exec(T);return S===null||M==="GET"||M==="HEAD"?(o(m(w,x,"invalid_request",`${Xr} applies to session-scoped write operations only`,{header:Xr})),!0):(o(b(w,x,D,T,M,S[1],J)),!0)}return v(w,x,D,M),!0}}import{randomUUID as HR}from"node:crypto";var Mf=["readwrite","readonly","off"],$v="readwrite",zR="2026-10-02T00:19:00Z",GR=`@${Math.floor(Date.parse(zR)/1e3)}`,WR=`<${Xi}>; rel="deprecation"`,VR="legacy_prefix_retired",$R=4096;function Kv(t){return typeof t=="string"&&Mf.includes(t)}function Qv(t){let e=Date.parse(t);if(!Number.isFinite(e))throw new TypeError(`legacyPrefixSunset: not a date: ${JSON.stringify(t)}`);return new Date(e).toUTCString()}function KR(t){let e=t.split("/").map(n=>n.startsWith(":")?"[^/]+":n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\/");return new RegExp(`^${e}$`)}var Jv=mn.operations.flatMap(t=>{let e=[t.legacyPath,t.legacyOffloadPath],n=[];for(let i of e)typeof i=="string"&&!i.startsWith("/v1/")&&i!=="/v1"&&n.push(i);return n.map(i=>({name:t.name,apiPath:t.apiPath,kind:t.kind,route:i,method:t.method,pattern:KR(i)}))}).sort((t,e)=>Wv(t.route)-Wv(e.route));function Wv(t){return t.split("/").filter(e=>e.startsWith(":")).length}function Yv(t){return t==="/v2"||t.startsWith("/v2/")||t==="/v3"||t.startsWith("/v3/")}function QR(t,e){for(let n of Jv)if(n.method===e&&n.pattern.test(t))return{name:n.name,apiPath:n.apiPath,kind:n.kind,route:n.route}}function JR(t){for(let e of Jv)if(e.pattern.test(t))return e.route}var YR=[/^\/v2\/sessions\/([^/]+)(?:\/|$)/,/^\/v3\/sdk2\/sessions\/([^/]+)(?:\/|$)/,/^\/api\/sessions\/([^/]+)(?:\/|$)/];function Vv(t){for(let e of YR){let n=e.exec(t);if(n!==null)return n[1]}}function XR(t){return ii(t)?.requestId??HR()}function ZR(t,e,n,i){if(t.destroyed||t.writableEnded)return;let o=Buffer.from(JSON.stringify(n),"utf8");t.writeHead(e,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length,...i}),t.end(o)}function Xv(t){let{mode:e,sunset:n,log:i}=t,o=Object.freeze({deprecation:GR,link:WR,...n===void 0?{}:{sunset:n}}),s=new Map,a=new Set,d=(l,f)=>{let u=s.get(l);if(u!==void 0&&s.delete(l),s.set(l,f),s.size>$R){let m=s.keys().next();m.done||s.delete(m.value)}return u},c=l=>{for(let[f,u]of Object.entries(o))l.setHeader(f,u)};return{mode:e,deprecationHeaders:()=>o,observeApi(l){let f=Vv(l);if(f===void 0)return;d(f,"api")==="legacy"&&i("warn",Xe.apiLegacyPrefixMixed,{route:eI(l),family:"api",from:"legacy",to:"api"})},handleLegacy(l,f,u,m){let g=u.startsWith("/v3")?"v3":"v2",h=QR(u,m),p=h?.route??JR(u)??"other",v=Vv(u);if(v!==void 0&&d(v,"legacy")==="api"&&i("warn",Xe.apiLegacyPrefixMixed,{route:p,family:g,from:"api",to:"legacy"}),c(f),e==="readwrite"||e==="readonly"&&(h===void 0||h.kind!=="write"))return!1;let b=e==="off"?404:410,R=e==="off"?"not_found":"gone";return a.has(`${m} ${p}`)||(a.add(`${m} ${p}`),i("warn",Xe.apiLegacyPrefixRejected,{route:p,method:m,mode:e,status:b})),ZR(f,b,{contract:an,traceId:XR(l),requestId:null,code:R,status:b,retryAction:"rediscover",message:h===void 0?`legacy prefix retired: use the /api facade (${Xi})`:`legacy prefix retired: use ${h.name} (${m} ${h.apiPath}) via the /api facade`,detail:{domainCode:VR,mode:e,route:p,...h===void 0?{}:{operation:h.name,apiPath:h.apiPath}}},{...o,"tansr-contract":an}),!0}}}function eI(t){return`/api/sessions/:id${t.replace(/^\/api\/sessions\/[^/]+/,"").length>0?"/…":""}`}var tI=5e3;async function Of(t,e,n){if(e.aborted)throw e.reason;return await new Promise((i,o)=>{let s=c=>{clearTimeout(d),e.removeEventListener("abort",a),c()},a=()=>s(()=>o(e.reason??new DOMException("Timed out","TimeoutError"))),d=setTimeout(a,n);e.addEventListener("abort",a,{once:!0}),Promise.resolve(t).then(c=>s(()=>i(c)),c=>s(()=>o(c)))})}function nI(t){if(t.ended)return"ended";if(t.closeRequested)return"closing";let e=t.handle.status();return e==="ended"?"ended":e==="running"?"running":"idle"}function iI(t){if(typeof t!="object"||t===null)return null;let e=t;return typeof e.protocol!="string"||!Array.isArray(e.features)?null:{protocol:e.protocol,features:e.features.filter(n=>typeof n=="string")}}function Zv(t){let{registry:e,installed:n}=t,i=t.timeoutMs??tI,o=t.now??Date.now;return async(s,a,d)=>{let c=e.get(s);if(c===void 0||c.handle.endUserId!==a)return null;let l=c.handle,f=Vi(l),u=AbortSignal.timeout(i),m=null,g=null;if(t.execution!==void 0&&n.execution){let M=await Of(t.execution.options.readPolicy(a,u),u,i);if(M.expiresAt!==void 0&&(!Number.isSafeInteger(M.expiresAt)||M.expiresAt<=o()))throw new Error("policy source expired");m=M.authorizationRevision;try{let W=t.execution.session(a,s).executionBoundary();g={boundaryRevision:W.revision,effectiveTools:W.effectiveTools}}catch{g=null}}let h=null;if(t.archive?.capabilities!==void 0&&n.archive){let M=await Of(t.archive.capabilities(a),u,i);h={epochId:M.operationEpoch.id,capabilities:M.capabilities}}let p=null;if(t.terminal!==void 0&&n.terminal)try{let M=t.terminal.sessionFeatures(a,{sessionContract:f,sessionId:s});p={schemaRevision:t.terminal.capabilities().schemaRevision,features:xv(M)}}catch{p=null}let v=l.inputCapabilities?.(),b=v===void 0?null:Rv(v),R=l.platformAudio,w=R===void 0?null:{speechToText:R.capabilities.speechToText===!0,textToSpeech:R.capabilities.textToSpeech===!0},x=null;t.cache!==void 0&&n.cache&&(x=iI(await Of(t.cache.capabilities(a),u,i)));let T=e.get(s);return T===void 0||T.handle!==l?null:wv({installed:n,authorizationRevision:m,session:{family:f,state:nI(T)},execution:g,archive:h,terminal:p,input:b,audio:w,cache:x})}}import{lstatSync as Bf,realpathSync as eb}from"node:fs";import Jt from"node:path";var tb=new WeakMap;function Bd(t,e){tb.set(t,e)}function hr(t){return tb.get(t)}var nb=new WeakMap;function Zr(t,e){nb.set(t,e)}function Un(t){return nb.get(t)}var Df=new WeakMap;function ib(t,e){if(Df.has(t))throw new Error("Memory command runner already bound");Df.set(t,e)}function rb(t){return Df.get(t)}function ob(t){let e=t,n=qf(t),i=t.config.management;if(!i||!t.config.host||of(t.config.host)===void 0)return n;let o=!1,s=!1,a=!1,d,c,l,f,u=new br,m=()=>l||(l=(async()=>{if(s)throw new at("source_unavailable");try{await n.verifyAvailable()}catch(v){if(!(v instanceof at)||v.code!=="stale_generation")throw v;let b=e.config.host,R=of(b),w=await i.read();if(R===void 0||BigInt(w.deletionGeneration)<=BigInt(R))throw v;if(a&&d===n||!(await n.settleResources({timeoutMs:0})).every(T=>T.status==="completed"))throw new at("busy");let x=await i.createHost({rootDir:b.rootDir,memoryDir:b.memoryDir,...b.provenance===void 0?{}:{provenance:b.provenance}});if(await x.refresh(),s||!e.config.enabled())throw new at("source_unavailable");if(a&&d===n)throw new at("busy");if(await n.retireDeletedSource(),s||!e.config.enabled())throw new at("source_unavailable");x.assertCurrent(),e={...e,config:{...e.config,host:x}},n=qf(e),o&&n.start()}if(c){let v=c;c=void 0,n.onTurnStart(v)}})().finally(()=>{l=void 0}),u.track(l,"tool_executor",{reportFailure:!1}),l),g={...n.searchTool,execute:async(p,v)=>(await m(),n.searchTool.execute(p,v))},h=async p=>{let v=performance.now(),b=p?.timeoutMs??3e4,R=()=>({...p,timeoutMs:Math.max(0,b-(performance.now()-v))}),w=[];for(;;){let x=await u.settle(R()),T=n,W=[...await T.settleResources(R()),x];if(T===n&&l===void 0||W.some($=>$.status!=="completed"))return[...w,...W];w.push(...W.filter($=>$.failureCount>0))}};return{searchTool:g,management:i,assertAvailable:()=>n.assertAvailable(),verifyAvailable:m,executeManagedCommand:async(p,v)=>(await m(),n.executeManagedCommand(p,v)),status:()=>n.status(),start:()=>{o=!0,n.start()},prepare:async p=>{await m();let v=n,b=await v.prepare(p);return d=v,b},onTurnStart:p=>{a=!0,d===n?n.onTurnStart(p):c=[...p]},onTurnEnd:p=>{a=!1,d=void 0,c=void 0,n.onTurnEnd(p)},noteBalanceLow:()=>n.noteBalanceLow(),observeTouched:p=>n.observeTouched(p),compactionObserver:{onCompactionFinished:p=>n.compactionObserver.onCompactionFinished?.(p)},prepareReminders:async p=>{await m(),await n.prepareReminders(p)},drainReminders:()=>n.drainReminders(),drainSelections:()=>n.drainSelections(),pin:async p=>(await m(),n.pin(p)),remember:()=>n.remember(),rememberAndWait:async()=>{await m(),await n.rememberAndWait()},readyForModelChange:async()=>!s&&(await h({timeoutMs:0})).every(p=>p.status==="completed"),close:()=>f??=(async()=>{s=!0,await l?.catch(()=>{}),await n.close()})(),settleResources:h}}function qf(t){let e=t.config;if(!["server-managed","client-managed","developer-managed"].includes(e.kind)||!e.domain.trim()||!Jt.isAbsolute(e.rootDir)||!Jt.isAbsolute(e.memoryDir)||typeof e.enabled!="function"||typeof e.balance!="function")throw new TypeError("Invalid trusted memory domain");if(e.kind!=="server-managed"&&e.host===void 0)throw new TypeError("Managed memory requires a trusted prepared host");if(e.host!==void 0&&(e.host.authority.identity.kind!==e.kind||e.host.authority.identity.domain!==e.domain))throw new TypeError("Memory host identity does not match");if(e.management!==void 0&&(e.host===void 0||e.host.authority!==e.management||e.management.identity.kind!==e.kind||e.management.identity.domain!==e.domain))throw new TypeError("Memory management must share the configured source authority");let n=Jt.resolve(e.rootDir),i=Jt.resolve(e.memoryDir);if(e.host!==void 0&&(e.host.rootDir!==n||e.host.memoryDir!==i))throw new TypeError("Memory host namespace does not match");let o=q=>process.platform==="win32"?q.toLowerCase():q,s=(q,X)=>o(X)===o(q)||o(X).startsWith(o(q+Jt.sep));if(!s(n,i)||o(n)===o(i)||e.host===void 0&&(o(eb(n))!==o(n)||!Bf(n).isDirectory()))throw new TypeError("Memory domain requires an explicit real root and child directory");let a=[e.projectAgentsPath,e.userAgentsPath].filter(q=>q!==void 0);if(a.some(q=>!Jt.isAbsolute(q)||!s(n,Jt.resolve(q))||s(i,Jt.resolve(q))))throw new TypeError("Promotion targets must be explicit paths within the trusted root, outside auto-memory");let d=!1,c=!1,l,f=new br,u=new Set,m=()=>{if(c||!e.enabled())throw new Error("Memory source unavailable");e.host?.assertCurrent()},g=async()=>{m(),await e.host?.refresh(),m()},h=q=>a.some(X=>o(Jt.resolve(X))===o(q)),p=(q,X=!1)=>{if(m(),!Jt.isAbsolute(q))throw new Error("Memory path must be absolute");let te=Jt.resolve(q);if(!(s(i,te)||h(te)||X&&s(n,te)&&(s(te,i)||a.some($e=>s(te,Jt.resolve($e))))))throw new Error("Memory path outside trusted domain");if(e.host!==void 0)return te;let Ue=n;for(let $e of Jt.relative(n,te).split(Jt.sep).filter(Boolean)){Ue=Jt.join(Ue,$e);try{if(Bf(Ue).isSymbolicLink())throw new Error("Memory links are not permitted")}catch(Fe){if(Fe.code!=="ENOENT")throw Fe}}if(o(eb(n))!==o(n))throw new Error("Memory root changed");return te};if(p(i,!0),e.host===void 0&&!Bf(i).isDirectory())throw new TypeError("Memory directory must already exist");let v=e.host?.fs??pp,b={...v.compareAndWrite===void 0?{}:{compareAndWrite:async(q,X,te)=>v.compareAndWrite(p(q),X,te)},stat:async q=>v.stat(p(q,!0)),lstat:async q=>v.lstat(p(q,!0)),realpath:async q=>v.realpath(p(q,!0)),readFile:async q=>v.readFile(p(q)),readFilePrefix:async(q,X)=>v.readFilePrefix(p(q),X),...v.readFileRange===void 0?{}:{readFileRange:async(q,X,te)=>v.readFileRange(p(q),X,te)},writeFile:async(q,X)=>v.writeFile(p(q),X),appendFile:async(q,X)=>v.appendFile(p(q),X),mkdir:async(q,X)=>v.mkdir(p(q,!0),X),readdir:async q=>{let X=await v.readdir(p(q,!0));if(X.length>500||X.some(te=>te.isSymbolicLink()))throw new Error("Memory directory cannot be admitted");return X}},R={...e.host?.source,pathStyle:process.platform==="win32"?"win32":"posix",fs:b},w=e.host?.extractionHost??Hm(i),x=e.host?.consolidationHost??zm(i),T=q=>{p(Jt.join(i,q)),p(Jt.join(i,"lock"))},M=new ro({homedir:n,memoryWriteCarveOut:{dirs:[i]}}),W=new Vn;for(let q of[Wc,co,lo])W.register({...q,execute:async(X,te)=>{let Se=X&&typeof X=="object"?X.file_path:void 0;if(typeof Se!="string")return{isError:!0,content:[{t:"text",text:"A memory file path is required."}]};try{return p(Se),await q.execute(X,{...te,fs:b,cwd:n})}catch{return{isError:!0,content:[{t:"text",text:"Memory access denied or unavailable."}]}}}});let $=Ci(M,W,{cwd:n}),D={decide:async(q,X)=>{try{m();let te=q.args&&typeof q.args=="object"?q.args.file_path:void 0;if(typeof te!="string")throw new Error("Missing path");return p(te),h(Jt.resolve(te))&&["Write","Edit"].includes(q.name)?{decision:"ask",source:"policy",reason:"Memory promotion requires approval"}:await $.decide(q,X)}catch{return{decision:"deny",source:"policy",reason:"Memory source unavailable or outside scope"}}}},J=()=>{m();let q=t.modelTier(),X=q.client;return{...q,client:Gn({async*stream(te,Se){await g(),yield*X.stream(te,Se)}},X)}},S=(q,X)=>{try{e.onObservation?.(q,X)}catch{}},k=W.names().map(q=>bn(W.get(q))),A={memoryDir:i,cwd:n,modelTier:J,registry:W,tools:k,permissionGate:D,...t.budget===void 0?{}:{budget:t.budget},onUsage:t.onUsage,...t.onDecision?{onDecision:t.onDecision}:{},...t.requestMeasurement?{requestMeasurement:t.requestMeasurement}:{}},C=Om({...A,interactive:!0,sessionId:()=>t.sessionId,balance:e.balance,...e.extraction,host:{pendingInvitesLocation:w.pendingInvitesLocation,readInitialPendingInvites:()=>(T("pending-invites.json"),w.readInitialPendingInvites()),persistPendingInvites:async(q,X)=>{T("pending-invites.json"),await w.persistPendingInvites(q,X)},acquireLock:async q=>(T("lock"),w.acquireLock(q)),readIndexSnapshot:async q=>(T("MEMORY.md"),w.readIndexSnapshot(q))},writePlanePreflight:Mm(M,i,n),probeWrite:q=>S("write.extract",q),probeInvite:q=>S("invite",q),probeExtraction:q=>S("extraction",q),notifySaved:q=>S("saved",{count:q})}),F=Bm({...A,interactive:!0,sessionId:t.sessionId,balance:e.balance,system:t.system,host:{acquireLock:async q=>(T("lock"),x.acquireLock(q)),readConsolidationMeta:async()=>(T("consolidation.json"),x.readConsolidationMeta()),writeConsolidationMeta:async q=>{T("consolidation.json"),await x.writeConsolidationMeta(q)},readPendingAnchors:async()=>(T("pending-anchors.md"),x.readPendingAnchors()),clearPendingAnchors:async q=>{T("pending-anchors.md"),await x.clearPendingAnchors(q)}},probeWrite:q=>S("write.consolidate",q),notifyConsolidated:q=>S("consolidated",{count:q})}),H=!1,Q=e.projectAgentsPath!==void 0&&e.userAgentsPath!==void 0&&t.askUser!==void 0?Dm({...A,sessionId:t.sessionId,system:t.system,history:t.history,projectAgentsPath:e.projectAgentsPath,userAgentsPath:e.userAgentsPath,askUser:t.askUser,notifyReport:q=>S("promotion.report",{text:q}),probePromotion:q=>S("promotion",q),onOutcome:q=>{H=q.kind==="completed"}}):void 0,re=qs({dir:i,roots:[n],source:R}),O=e.recallSelector?js({dir:i,source:R,...t.budget===void 0?{}:{budget:t.budget},onBudgetWarning:q=>S("budget.warning",{reason:q}),excludeFiles:["pending-anchors.md"],modelTier:J,onUsage:(q,X)=>t.onUsage({model:X.model,provider:X.provider,usage:q})}):void 0,I=om({forceEngine:"js"}),B={source:"local",async search(q,X){m();let te=sm(),Se=[];if(q.kind!==void 0&&q.kind!=="memory")return{hits:Se};for await(let Ue of I.search({root:i,pattern:am(q.query),caseInsensitive:!0,collectLines:!0,contextLines:2,glob:"*.md"},{signal:X,stats:te,fs:b})){if(m(),["pending-anchors.md","quarantine.md"].includes(Jt.basename(Ue.abs)))continue;let $e=Ue.lines.slice(0,30);if(Se.push({kind:"memory",key:Ue.rel,title:Ue.rel,occurredAt:"",lineStart:$e[0]?.line??1,lineEnd:$e.at(-1)?.line??1,score:1,text:$e.map(Fe=>Fe.text).join(`
|
|
29
|
+
`).slice(0,4096)}),Se.length>=q.limit)break}return{hits:Se,truncated:te.limitHit||Se.length>=q.limit}}},z=dm({projectKey:e.domain,searcher:B,enabled:()=>!c&&e.enabled()});z.description="Search the authorized memory source. Returns bounded memory snippets from the configured domain only; never falls back to host files.";let j=new Ap,ne=()=>{if(m(),d)throw new Error("Memory is closing")},U=()=>{if(ne(),!Q)throw new Error("Memory promotion requires explicit targets and approval bridge");if(Q.promotionInFlight())throw new Error("Memory busy");H=!1,Q.run()},le=q=>{let X=(async()=>{ne(),T("lock");let te=await w.acquireLock({staleMs:6e5});if(!te)throw new Error("Memory busy");try{return ne(),await q()}finally{let Se=te.release();f.track(Se,"tool_executor"),await Se}})();return f.track(X,"tool_executor",{reportFailure:!1}),X},ue=async q=>(await Promise.all([f.settle(q),C.settleResources(q),F.settleResources(q),Q?.settleResources(q),re.settleResources?.(q),O?.settleResources?.(q)])).filter(te=>te!==void 0),ie=(q=!1)=>l??=(async()=>{d=!0,await Promise.all([...u].map(te=>te.close())),await f.settle({timeoutMs:1/0}),!q&&e.enabled()&&C.handleSessionClose(),await Promise.all([C.drain(),F.drain(),Q?.drain()]),re.dispose?.(),O?.dispose();let X=await ue({timeoutMs:1/0});if(c=!0,X.some(te=>te.status!=="completed"))throw new Error("Memory cleanup did not complete")})();return{searchTool:z,assertAvailable:m,verifyAvailable:g,...e.management===void 0?{}:{management:e.management},executeManagedCommand:(q,X)=>{let te=(async()=>{if(ne(),e.management===void 0||e.host===void 0)throw new Error("Memory management is not configured");let Se=[],Ue=await e.management.execute(q,async $e=>{ne(),X?.signal?.throwIfAborted();let Fe=qf({...t,config:{...e,host:$e,rootDir:$e.rootDir,memoryDir:$e.memoryDir,onObservation:(kt,Ge)=>Se.push({kind:kt,value:Ge})}});u.add(Fe);let lt=()=>{f.track(Fe.close(),"tool_executor")};X?.signal?.addEventListener("abort",lt,{once:!0});try{X?.signal?.throwIfAborted(),q.command.kind==="pin"?await Fe.pin(q.command.text):q.command.kind==="remember"&&await Fe.rememberAndWait(),X?.signal?.throwIfAborted()}finally{try{await Fe.close()}finally{X?.signal?.removeEventListener("abort",lt),u.delete(Fe)}}},{rootDir:n,memoryDir:i,...e.host.provenance===void 0?{}:{provenance:e.host.provenance}},{...X?.signal===void 0?{}:{signal:X.signal},beforeCommit:async()=>{ne(),await X?.beforeCommit?.(),ne()}});if(Ue.status==="committed"){re.invalidate?.({dir:i,roots:[n],source:R}),O?.invalidateSource({dir:i,source:R});for(let $e of Se)S($e.kind,$e.value)}return S("management",{operationId:q.operationId,status:Ue.status,durable:Ue.durable}),Ue})();return f.track(te,"tool_executor",{reportFailure:!1}),te},status:()=>({kind:e.kind,domain:e.domain,enabled:!c&&e.enabled(),extractionInFlight:C.extractionInFlight(),consolidationInFlight:F.consolidationInFlight(),promotionInFlight:Q?.promotionInFlight()??!1,closing:d}),start:()=>{m(),F.start()},prepare:async q=>{m(),q.throwIfAborted(),await g();let X=await qp(i,{source:R,signal:q});return m(),[{text:Dp,cacheable:!0},...X.content===null?[]:[{text:`${Bp}
|
|
30
|
+
|
|
31
|
+
${X.content}`,cacheable:!1}]]},onTurnStart:q=>{C.noteTurnStart(),e.enabled()&&O?.prefetch(q.join(`
|
|
32
|
+
`))},onTurnEnd:q=>{!e.enabled()||d||(C.noteInviteParse(qm(jm(q.history)),q.turn),C.handleTurnEnd(q))},noteBalanceLow:()=>{C.noteBalanceLow(),F.noteBalanceLow()},observeTouched:q=>{e.enabled()&&re.observeTouched(q)},compactionObserver:{onCompactionFinished:q=>{q.agentId===void 0&&q.mechanism===void 0&&q.outcome?.ok===!0&&C.noteCompactionSummary(q.outcome.summaryText)}},prepareReminders:async q=>{m(),await re.prepareReminders?.(q)},drainReminders:()=>e.enabled()?re.drainReminderEntries?.()??[]:[],drainSelections:()=>e.enabled()?O?.drainReminderEntries?.()??[]:[],pin:async q=>le(async()=>{if(Up(q).length>0)throw new Error("Memory pin contains protected secret material");let X=j.pin(q,0,te=>te.length);if(!X)throw new Error("Invalid memory pin");return T("pending-anchors.md"),{added:e.host===void 0?await Lm(i,[X.entry]):await e.host.appendPendingAnchors([X.entry])}}),remember:U,rememberAndWait:async()=>{U();let q=await Q.settleResources({timeoutMs:1/0});if(m(),q.status!=="completed"||!H)throw new Error("Memory promotion did not complete")},readyForModelChange:async()=>!d&&(await ue({timeoutMs:0})).every(q=>q.status==="completed"),close:()=>ie(),retireDeletedSource:()=>ie(!0),settleResources:ue}}var Di=Object.freeze(["execution-stream-v1","execution-background-v1","memory-lifecycle-v1","session-configuration-v1"]),qi=Object.freeze({maxControlBytes:262144,maxBlockBytes:16384,maxBatchBytes:65536,maxPendingBytes:2097152,maxRetainedBytes:8388608}),He=class extends Error{constructor(n){super(n);this.code=n;this.name="TerminalCapabilityError"}code};function Xn(t){throw new He(t)}function jf(t,e){try{return yt(t,e)}catch{return Xn("invalid_request")}}function rI(t){let e=new Set(t.map(n=>n.feature));return(e.size!==Di.length||Di.some(n=>!e.has(n))||t.some(n=>n.installed&&!n.supported))&&Xn("invalid_request"),t}function oI(t){(t.maxBlockBytes>t.maxBatchBytes||t.maxBatchBytes>t.maxPendingBytes||t.maxBatchBytes>t.maxRetainedBytes)&&Xn("invalid_request")}function ss(t){let e=jf("CapabilitiesResponse",{...t,contract:"terminal-services-v1",schemaRevision:Lg,schemaSha256:Ug});return rI(e.features),oI(e.limits),e}function Dd(t,e){let n=jf("BindingRequest",t),i=ss({sessionContracts:[e.session.sessionContract],features:e.features,limits:e.limits});(n.required.some(d=>n.optional.includes(d))||n.required.length+n.optional.length===0)&&Xn("invalid_request"),he(n.session)!==he(e.session)&&Xn("not_found"),he(n.executionBinding)!==he(e.executionBinding)&&Xn("stale_generation");let s=[],a=[];for(let d of[...n.required,...n.optional]){let c=i.features.find(l=>l.feature===d);if(!c.supported||!c.installed){n.required.includes(d)&&Xn("unsupported_capability"),a.push(c);continue}c.authorization==="denied"&&Xn("forbidden"),(c.authorization==="unconfirmed"||c.device==="unconfirmed")&&Xn("capability_unconfirmed"),c.device==="unavailable"&&Xn("source_unavailable"),(d==="execution-stream-v1"||d==="execution-background-v1")&&e.executionBinding===null&&Xn("stale_generation"),s.push(d)}return jf("BindingResponse",{contract:n.contract,requestId:n.requestId,session:e.session,scope:e.scope,executionBinding:e.executionBinding,accepted:s,unavailable:a,outputAuthority:s.includes("execution-stream-v1")?"tool-output":"session-events",limits:e.limits})}import{createHash as sb}from"node:crypto";var ab=9223372036854775807n,sI=65536,db=8*1024*1024,cb=4096,as=class extends Error{constructor(n){super(n);this.code=n;this.name="TerminalOutputError"}code};function hn(t){throw new as(t)}function Nf(t,e){try{return yt(t,e)}catch{return hn("invalid_request")}}function aI(t,e){return t.seq===e.seq&&t.byteOffset===e.byteOffset&&t.channel===e.channel&&t.encoding===e.encoding&&t.byteLength===e.byteLength&&t.payloadDigest===e.payloadDigest&&t.base64===e.base64}function dI(t,e){return t.lastSeq===e.lastSeq&&t.totalBytes===e.totalBytes&&t.payloadDigest===e.payloadDigest&&t.truncated===e.truncated}var qd=class{#e;#n;#r;#s=new Map;#t=new Map;#o=0;#i=0n;#a=0n;#c=sb("sha256");#d=null;#f=!1;constructor(e,n={}){let i=Nf("OutputBatchRequest",{contract:"terminal-services-v1",...e,blocks:[],seal:null});this.#e=Object.freeze({session:Object.freeze({...i.session}),operation:Object.freeze({...i.operation}),executorId:i.executorId,connectionId:i.connectionId}),this.#n=n.maxRetainedBytes??db,this.#r=n.maxRetainedBlocks??cb,(!Number.isSafeInteger(this.#n)||this.#n<1||this.#n>db||!Number.isSafeInteger(this.#r)||this.#r<1||this.#r>cb)&&hn("invalid_request")}status(){let e=this.#s.keys().next().value;return Object.freeze({contract:"terminal-services-v1",operation:this.#e.operation,state:this.#f?"gap":this.#d?this.#d.truncated?"truncated":"complete":this.#i?"receiving":"available",acceptedThrough:this.#i?String(this.#i-1n):null,durableThrough:null,retainedFrom:e===void 0?null:String(e),nextByteOffset:String(this.#a),seal:this.#d})}receive(e){let n=Nf("OutputBatchRequest",e),i=this.#e;(n.session.sessionContract!==i.session.sessionContract||n.session.sessionId!==i.session.sessionId||n.operation.operationId!==i.operation.operationId||n.operation.requestDigest!==i.operation.requestDigest||n.executorId!==i.executorId||n.connectionId!==i.connectionId)&&hn("binding_conflict"),n.blocks.reduce((m,g)=>m+g.byteLength,0)>sI&&hn("payload_too_large");let o=new Map(this.#s),s=new Map(this.#t),a=this.#c.copy(),d=this.#i,c=this.#a,l=this.#o,f=this.#d,u=this.#f;for(let m of n.blocks){let g=Buffer.from(m.base64,"base64");(g.toString("base64")!==m.base64||g.length!==m.byteLength||sb("sha256").update(g).digest("hex")!==m.payloadDigest)&&hn("integrity_mismatch");let h=BigInt(m.seq);if(h<d){let b=o.get(h);b||hn("output_gap"),aI(b,m)||hn("revision_conflict");continue}f&&hn("revision_conflict"),h!==d&&hn("output_gap"),BigInt(m.byteOffset)!==c&&hn("integrity_mismatch");let p=s.get(m.channel);p!==void 0&&p!==m.encoding&&hn("revision_conflict"),s.set(m.channel,m.encoding);let v=c+BigInt(g.length);(d>ab||v>ab)&&hn("capacity_exceeded"),a.update(g),o.set(h,Object.freeze({...m})),d++,c=v,l+=g.length}for(n.seal&&(f?dI(f,n.seal)||hn("revision_conflict"):((n.seal.lastSeq!==(d?String(d-1n):null)||n.seal.totalBytes!==String(c)||n.seal.payloadDigest!==a.copy().digest("hex"))&&hn("integrity_mismatch"),f=Object.freeze({...n.seal})));o.size>this.#r||l>this.#n;){let m=o.entries().next().value;o.delete(m[0]),l-=m[1].byteLength,u=!0}return this.#s=o,this.#t=s,this.#c=a,this.#i=d,this.#a=c,this.#o=l,this.#d=f,this.#f=u,this.status()}observe(e=null){let n=e===null?-1n:BigInt(Nf("Sequence",e));(n>=this.#i||n+1n<(this.#s.keys().next().value??this.#i))&&hn("output_gap");let i=Object.freeze([...this.#s].filter(([o])=>o>n).map(([,o])=>o));return Object.freeze({blocks:i,status:this.status()})}};function Zn(t,e){return he(t)===he(e)}function jd(t){let e=t.request;if(e.operation==="process.exec")return e.args.maxOutputBytes;try{let n=Br(e);return n.action==="exec"?n.maxOutputBytes:void 0}catch{return}}function tt(t){throw new He(t)}function Ln(t,e){try{return yt(t,e)}catch{return tt("invalid_request")}}function Fn(t,e){let n=t??e;return(!Number.isSafeInteger(n)||n<1)&&tt("invalid_request"),n}function ds(t,e){return JSON.stringify([t,e.sessionContract,e.sessionId])}function Nd(t,e){return Object.freeze({contract:"terminal-services-v1",operation:Object.freeze({...t}),state:"unavailable",acceptedThrough:e?.acceptedThrough??null,durableThrough:null,retainedFrom:null,nextByteOffset:e?.nextByteOffset??null,seal:e?.seal??null})}function cs(t){let e=t?.code;return["forbidden","stale_generation","source_unavailable","capacity_exceeded","binding_conflict","output_gap"].includes(e??"")?e:"source_unavailable"}var Ud=class{#e;#n;#r=new Map;#s=new WeakSet;#t=new Map;#o=new Set;#i;#a;#c;#d;#f;#m;#p;#w;#v;#k;#y;#B;#E;#z=0;#S=0;#g=0n;#N=!1;constructor(e){this.#e=e.host,this.#n=e,this.#a=Fn(e.maxBindings,256),this.#c=Fn(e.maxOperations,256),this.#d=Fn(e.maxOperationsPerSession,64),this.#f=Fn(e.maxSubscriptions,64),this.#m=Fn(e.maxSubscriptionsPerSession,8),this.#p=Fn(e.maxSubscriptionsPerExecutor,8),this.#w=Fn(e.maxRetainedBytes,64*1048576),this.#v=Fn(e.maxRetainedBlocks,16384),this.#k=Fn(e.maxRetainedBytesPerSession,Math.min(this.#w,16*1048576)),this.#y=Fn(e.maxRetainedBlocksPerSession,Math.min(this.#v,8192)),this.#B=Fn(e.maxRetainedBytesPerOperation,qi.maxRetainedBytes),this.#E=Fn(e.retentionMs,3e5),(this.#B>qi.maxRetainedBytes||this.#B>this.#k||this.#k>this.#w||this.#y>this.#v)&&tt("invalid_request"),this.capabilities(),this.#i=this.#e.observeChanges(n=>this.#q(n))}capabilities(){return ss({sessionContracts:this.#n.sessionContracts,limits:qi,features:this.#J("unconfirmed","unconfirmed")})}#J(e,n){return Di.map(i=>({feature:i,supported:i==="execution-stream-v1",installed:i==="execution-stream-v1",authorization:i==="execution-stream-v1"?e:"unconfirmed",device:i==="execution-stream-v1"?n:"unconfirmed"}))}#U(){this.#N&&tt("source_unavailable")}async#j(e,n,i){this.#U(),i.throwIfAborted();let o=Ln("SessionReference",n);this.#n.sessionContracts.includes(o.sessionContract)||tt("not_found");let s=await this.#n.resolveSession(e,o);return i.throwIfAborted(),this.#U(),s!==this.#e.session(e,o.sessionId)&&tt("not_found"),await s.refresh(i,!1),i.throwIfAborted(),s!==this.#e.session(e,o.sessionId)&&tt("source_unavailable"),s}#C(e,n,i=!0,o=!0){this.#U();let s=this.#r.get(ds(e,n));(!s||!(s.response.accepted.includes("execution-stream-v1")||!o&&s.response.accepted.includes("execution-background-v1")))&&tt("unsupported_capability");let a=this.#e.session(e,n.sessionId),d=s.response.executionBinding?.target;return(a!==s.session||!d||!Zn(a.binding,s.response.executionBinding)||a.policy.authorizationRevision!==s.response.scope.authorizationRevision)&&tt("stale_generation"),this.#e.connection(e,d.executorId,d.connectionId),i&&!a.available("Shell")&&tt("forbidden"),s}#D(e,n){!e.controller&&e.executorId!==n.response.executionBinding.target.executorId&&tt("forbidden")}async bind(e,n,i,o=new AbortController().signal){n.controller||tt("forbidden");let s=Ln("BindingRequest",i),a=await this.#j(e,s.session,o),d=a.binding,c="unavailable";d&&(this.#e.connection(e,d.target.executorId,d.target.connectionId),c="available");let l=Dd(s,{session:s.session,scope:{applicationScopeId:this.#e.options.applicationScopeId,endUserId:e,authorizationRevision:a.policy.authorizationRevision},executionBinding:d,features:this.#n.sessionFeatures?.(e,a)??this.#J(a.available("Shell")?"allowed":"denied",c),limits:qi}),f=ds(e,l.session),u=this.#r.get(f);return!u&&this.#r.size>=this.#a&&tt("capacity_exceeded"),u&&(!Zn(u.response.scope,l.scope)||!Zn(u.response.executionBinding,l.executionBinding)||!Zn(u.response.accepted,l.accepted))&&this.#A(f,"stale_generation"),a.configureBackground(l.accepted.includes("execution-background-v1")),this.#r.set(f,{user:e,response:Ln("BindingResponse",l),session:a}),this.#e.options.shellSandbox===!0&&!this.#s.has(a)&&(a.attachShellOutputReader((m,g)=>this.readCompletedOutput(e,l.session,m,g)),this.#s.add(a)),Ln("BindingResponse",l)}checkExecutor(e,n,i,o){this.#U(),n.executorId!==i&&tt("forbidden"),this.#Y(e,i,o)}#Y(e,n,i){this.#e.connection(e,n,i),[...this.#r.values()].some(o=>o.user===e&&o.response.accepted.includes("execution-stream-v1")&&o.response.executionBinding?.target.executorId===n&&o.response.executionBinding.target.connectionId===i)||tt("unsupported_capability")}async#I(e,n,i,o,s,a=!0){i=Ln("SessionReference",i);let d=Ln("OperationReference",o),c=await this.#j(e,i,s),l=this.#C(e,i,a,a);this.#D(n,l);let f=await c.readOperation(d.operationId);return s.throwIfAborted(),this.#C(e,i,a,a),this.#D(n,l),(f.digest!==d.requestDigest||!Zn(f.binding,l.response.executionBinding)||!Zn(f.scope,l.response.scope))&&tt("stale_generation"),a&&jd(f)===void 0&&tt("unsupported_capability"),!a&&!c.operationAvailable(f)&&tt("forbidden"),{binding:l,operation:f}}async executionState(e,n,i,o,s,a,d=new AbortController().signal){n.executorId!==i&&tt("forbidden"),this.#e.connection(e,i,o);let c=await this.#I(e,n,s,a,d,!1);(c.operation.binding.target.executorId!==i||c.operation.binding.target.connectionId!==o)&&tt("stale_generation");let l=await c.binding.session.reconcileStatus(c.operation.operationId);return d.throwIfAborted(),this.#e.connection(e,i,o),this.#C(e,c.binding.response.session,!1,!1),(!Zn(l.operation,c.operation)||!c.binding.session.operationAvailable(c.operation))&&tt("stale_generation"),{contract:"terminal-services-v1",session:{...c.binding.response.session},execution:JSON.parse(JSON.stringify(l))}}#u(e,n){return JSON.stringify([ds(e.user,e.response.session),n])}async readCompletedOutput(e,n,i,o){let s={operationId:i.operationId,requestDigest:i.digest},a=new AbortController,d=AbortSignal.any([o,a.signal]),c=setTimeout(()=>a.abort(),1e4);c.unref();let l,f,u,m=new Promise((p,v)=>{f=p,u=v}),g=()=>u(new He("source_unavailable"));d.addEventListener("abort",g,{once:!0}),m.catch(()=>{});let h=()=>{try{d.throwIfAborted();let p=this.#C(e,n),v=this.#t.get(this.#u(p,i.operationId));v?.window||tt("source_unavailable");let b=v.window.status();if((b.state==="gap"||b.state==="truncated"||b.state==="unavailable")&&tt("output_gap"),b.state!=="complete")return;let R=jd(i);(R===void 0||!b.seal||b.seal.truncated||BigInt(b.seal.totalBytes)>BigInt(R))&&tt("integrity_mismatch");let w=v.window.observe(null).blocks,x=[],T=[];for(let D of w)(D.channel==="stdout"?x:T).push(Buffer.from(D.base64,"base64"));let M=Buffer.concat(x),W=Buffer.concat(T);BigInt(M.length+W.length)!==BigInt(b.seal.totalBytes)&&tt("integrity_mismatch");let $=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});f({stdout:$.decode(M),stderr:$.decode(W)})}catch(p){u(p)}};try{let p=await this.#I(e,{controller:!0},n,s,d);Zn(p.operation,i)||tt("integrity_mismatch"),l=await this.subscribeOutput(e,{controller:!0},n,s,null,{event:b=>{b.type==="output.status"&&h()},close:b=>u(new He(b))},d),h();let v=await m;return await this.#I(e,{controller:!0},n,s,d),v}finally{clearTimeout(c),l?.close(),d.removeEventListener("abort",g),a.abort()}}async readOutputCorrelations(e,n,i,o,s=new AbortController().signal){let a=Ln("SessionReference",i);o!==void 0&&Ln("LegacyId",o);let d=await this.#j(e,a,s),c=this.#C(e,a);return this.#D(n,c),d.readOutputCorrelations(o).filter(l=>Zn(l.binding,c.response.executionBinding)).map(l=>Ln("OutputCorrelation",{contract:"terminal-services-v1",session:a,toolCallId:l.toolCallId,operation:l.operation,outputAuthority:c.response.outputAuthority}))}async receive(e,n,i,o=new AbortController().signal){let s=Ln("OutputBatchRequest",i);n.executorId!==s.executorId&&tt("forbidden");let{binding:a,operation:d}=await this.#I(e,n,s.session,s.operation,o);(s.executorId!==d.binding.target.executorId||s.connectionId!==d.binding.target.connectionId)&&tt("stale_generation");let c=jd(d);c===void 0&&tt("unsupported_capability");let l=BigInt(c);(s.blocks.some(b=>BigInt(b.byteOffset)+BigInt(b.byteLength)>l)||s.seal&&BigInt(s.seal.totalBytes)>l)&&tt("payload_too_large"),this.#e.connection(e,s.executorId,s.connectionId),this.#T();let f=this.#u(a,d.operationId),u=this.#t.get(f);u?.window||tt("source_unavailable");let m=u.window.receive(s),g=m.retainedFrom===null?m.acceptedThrough:m.retainedFrom==="0"?null:String(BigInt(m.retainedFrom)-1n),h=u.window.observe(g).blocks;this.#z-=u.retainedBytes,this.#S-=u.retainedBlocks,u.retainedBytes=h.reduce((b,R)=>b+R.byteLength,0),u.retainedBlocks=h.length,this.#z+=u.retainedBytes,this.#S+=u.retainedBlocks,u.status=m,this.#t.delete(f),this.#t.set(f,u);let p=0,v=0;for(let b of this.#t.values())b.bindingKey===u.bindingKey&&(p+=b.retainedBytes,v+=b.retainedBlocks);for(let[b,R]of this.#t){if(p<=this.#k&&v<=this.#y)break;b!==f&&R.bindingKey===u.bindingKey&&R.window&&(p-=R.retainedBytes,v-=R.retainedBlocks,this.#_(R))}for(let[b,R]of this.#t){if(this.#z<=this.#w&&this.#S<=this.#v)break;b!==f&&R.window&&this.#_(R)}(v>this.#y||this.#S>this.#v)&&this.#_(u);for(let b of this.#o)b.kind==="output"&&b.bindingKey===u.bindingKey&&b.reference?.operationId===d.operationId&&this.#ne(b,u);return u.status}async outputStatus(e,n,i,o,s=new AbortController().signal){let a=await this.#I(e,n,i,o,s);return this.#T(),this.#t.get(this.#u(a.binding,a.operation.operationId))?.status??Nd({operationId:a.operation.operationId,requestDigest:a.operation.digest})}async observe(e,n,i,o,s=null,a=new AbortController().signal){let d=await this.#I(e,n,i,o,a);this.#T(),s!==null&&Ln("Sequence",s);let c=this.#t.get(this.#u(d.binding,d.operation.operationId));return c?.window?.observe(s)??Object.freeze({blocks:Object.freeze([]),status:c?.status??Nd({operationId:d.operation.operationId,requestDigest:d.operation.digest})})}#T(){for(let[e,n]of this.#t)n.expiresAt<=this.#e.now()&&(this.#_(n),this.#t.delete(e))}#_(e){this.#z-=e.retainedBytes,this.#S-=e.retainedBlocks,e.retainedBytes=0,e.retainedBlocks=0,e.window=null,e.status=Nd(e.reference,e.status);for(let n of this.#o)n.kind==="output"&&n.bindingKey===e.bindingKey&&n.reference?.operationId===e.reference.operationId&&this.#ne(n,e)}#K(e,n){if(jd(n)===void 0||!Zn(n.binding,e.response.executionBinding)||!Zn(n.scope,e.response.scope))return;let i=this.#u(e,n.operationId);if(this.#t.has(i))return;this.#T();let o=ds(e.user,e.response.session);if(this.#t.size>=this.#c||[...this.#t.values()].filter(d=>d.bindingKey===o).length>=this.#d)return;let s=Object.freeze({operationId:n.operationId,requestDigest:n.digest}),a=new qd({session:e.response.session,operation:s,executorId:n.binding.target.executorId,connectionId:n.binding.target.connectionId},{maxRetainedBytes:this.#B});this.#t.set(i,{bindingKey:o,reference:s,window:a,status:a.status(),retainedBytes:0,retainedBlocks:0,expiresAt:Date.parse(n.expiresAt)+this.#E})}#P(e,n){if(!e.closed)try{e.listener.event(n)}catch{this.#V(e,"source_unavailable")}}#Q(e,n,i=null){if(this.#g>9223372036854775807n){this.#V(e,"capacity_exceeded");return}this.#P(e,Object.freeze({contract:"terminal-services-v1",eventId:String(this.#g++),type:n,executorId:e.executorId,connectionId:e.connectionId,operation:i?Object.freeze({operationId:i.operationId,requestDigest:i.digest}):null}))}#ne(e,n,i=!1){try{let o=n.window?.observe(e.afterSeq),s=e.listener;if(i&&s.replay){let a=o?.blocks??[],d=n.reference,c=n.status;a.length&&(e.afterSeq=a.at(-1).seq),s.replay((function*(){for(let l of a)yield Object.freeze({contract:"terminal-services-v1",type:"output.block",operation:d,block:l});yield Object.freeze({contract:"terminal-services-v1",type:"output.status",status:c})})());return}for(let a of o?.blocks??[]){if(this.#P(e,Object.freeze({contract:"terminal-services-v1",type:"output.block",operation:n.reference,block:a})),e.closed)return;e.afterSeq=a.seq}this.#P(e,Object.freeze({contract:"terminal-services-v1",type:"output.status",status:n.status}))}catch(o){this.#V(e,cs(o))}}#V(e,n){if(!e.closed&&(e.closed=!0,this.#o.delete(e),e.stop.abort(),e.timer&&clearTimeout(e.timer),e.signal.removeEventListener("abort",e.abort),n))try{e.listener.close(n)}catch{}}#L(e){e.timer&&clearTimeout(e.timer);let n=this.#e.connection(e.user,e.executorId,e.connectionId);e.timer=setTimeout(()=>this.#V(e,"stale_generation"),Math.max(1,Date.parse(n.connection.expiresAt)-this.#e.now())),e.timer.unref()}async#b(e,n,i){e.closed&&tt("source_unavailable");try{if(e.kind==="executor")this.checkExecutor(e.user,n,e.executorId,e.connectionId);else{let s=this.#r.get(e.bindingKey);s||tt("stale_generation"),this.#D(n,s)}}catch(s){throw this.#V(e,cs(s)),s}e.authority={...n};let o=async()=>{let s=i?AbortSignal.any([e.stop.signal,e.signal,i]):AbortSignal.any([e.stop.signal,e.signal]);if(e.kind==="executor"){this.checkExecutor(e.user,e.authority,e.executorId,e.connectionId);for(let a of this.#r.values())a.user===e.user&&a.response.executionBinding?.target.executorId===e.executorId&&a.response.executionBinding.target.connectionId===e.connectionId&&a.response.accepted.includes("execution-stream-v1")&&(await this.#j(e.user,a.response.session,s),this.#C(e.user,a.response.session,!1));this.checkExecutor(e.user,e.authority,e.executorId,e.connectionId)}else{let a=this.#r.get(e.bindingKey);a||tt("stale_generation"),await this.#I(e.user,e.authority,a.response.session,e.reference,s),this.#D(e.authority,a)}s.throwIfAborted(),e.closed&&tt("source_unavailable"),this.#L(e)};return e.checking||(e.checking=o().catch(s=>{throw this.#V(e,cs(s)),s}).finally(()=>{e.checking=void 0})),e.checking}#ee(e){return(this.#o.size>=this.#f||[...this.#o].filter(n=>n.user===e.user&&n.executorId===e.executorId&&n.connectionId===e.connectionId).length>=this.#p||e.bindingKey&&[...this.#o].filter(n=>n.bindingKey===e.bindingKey).length>=this.#m)&&tt("capacity_exceeded"),this.#o.add(e),e.signal.addEventListener("abort",e.abort,{once:!0}),e.signal.aborted?e.abort():this.#L(e),Object.freeze({close:()=>this.#V(e),check:(n,i)=>this.#b(e,n,i)})}async subscribeExecutor(e,n,i,o,s,a=new AbortController().signal){this.checkExecutor(e,n,i,o),a.throwIfAborted();let d={kind:"executor",user:e,authority:{...n},executorId:i,connectionId:o,afterSeq:null,listener:s,signal:a,stop:new AbortController,closed:!1,abort:()=>this.#V(d)},c=this.#ee(d);try{return await c.check(n),this.#Q(d,"reconcile-required"),c}catch(l){throw c.close(),l}}async subscribeOutput(e,n,i,o,s,a,d=new AbortController().signal){let c=await this.#I(e,n,i,o,d),l=c.binding;i=l.response.session,o={operationId:c.operation.operationId,requestDigest:c.operation.digest},s!==null&&Ln("Sequence",s),this.#T();let f=l.response.executionBinding.target,u={kind:"output",user:e,authority:{...n},executorId:f.executorId,connectionId:f.connectionId,bindingKey:ds(e,i),reference:Object.freeze({...o}),afterSeq:s,listener:a,signal:d,stop:new AbortController,closed:!1,abort:()=>this.#V(u)},m=this.#ee(u),g=this.#t.get(this.#u(l,o.operationId));return g?this.#ne(u,g,!0):this.#P(u,Object.freeze({contract:"terminal-services-v1",type:"output.status",status:Nd(o)})),m}#A(e,n){this.#r.get(e)?.session.configureBackground(!1),this.#r.delete(e);for(let[i,o]of this.#t)o.bindingKey===e&&(this.#z-=o.retainedBytes,this.#S-=o.retainedBlocks,this.#t.delete(i));for(let i of this.#o)i.bindingKey===e&&this.#V(i,n)}#q(e){if(!this.#N){for(let[n,i]of this.#r)if(!(i.user!==e.user||e.sessionId&&i.response.session.sessionId!==e.sessionId)){if(e.kind==="session-closed"){this.#A(n,"source_unavailable");continue}if(i.response.accepted.some(o=>o==="execution-stream-v1"||o==="execution-background-v1")){try{this.#C(i.user,i.response.session,!1,!1)}catch(o){this.#A(n,cs(o));continue}i.response.accepted.includes("execution-stream-v1")&&e.kind==="operation-available"&&e.operation&&this.#K(i,e.operation)}}for(let n of this.#o)if(!(n.user!==e.user||e.executorId&&n.executorId!==e.executorId)){try{if(n.kind==="executor")this.checkExecutor(n.user,n.authority,n.executorId,n.connectionId);else{let i=this.#r.get(n.bindingKey);i||tt("stale_generation"),this.#C(n.user,i.response.session,!1),this.#D(n.authority,i)}this.#L(n)}catch(i){this.#V(n,cs(i));continue}n.kind!=="executor"||!e.operation||e.operation.binding.target.executorId!==n.executorId||e.operation.binding.target.connectionId!==n.connectionId||(e.kind==="operation-available"?this.#Q(n,"operations-available",e.operation):e.kind==="operation-cancelled"?this.#Q(n,"operation-cancelled",e.operation):e.kind==="operation-removed"&&this.#Q(n,"reconcile-required",e.operation))}}}close(){if(!this.#N){this.#N=!0,this.#i();for(let e of this.#o)this.#V(e,"source_unavailable");for(let e of this.#r.values())e.session.configureBackground(!1);this.#t.clear(),this.#r.clear(),this.#z=0,this.#S=0}}};function lb(t){let e=new Map,n=new Map,i=!1;function o(u,m){if(i)throw new He("source_unavailable");if(!t.families.has(m.sessionContract))throw new He("unsupported_capability");let g=t.registry.get(m.sessionId);if(!g||g.handle.endUserId!==u||Vi(g.handle)!==m.sessionContract)throw new He("not_found");if(g.ended)throw new He("stale_generation");return g.handle}function s(u,m){if(i)throw new He("source_unavailable");if(!t.families.has(m.sessionContract))throw new He("unsupported_capability");let g=t.registry.get(m.sessionId);if(!g||g.handle.endUserId!==u||Vi(g.handle)!==m.sessionContract)throw new He("not_found");return{handle:g.handle,registry:t.registry}}function a(u,m,g){if(u.endUserId!==m)throw new He("forbidden");let h=Un(g)?.management?.identity;if(h&&(h.applicationScopeId!==u.applicationScopeId||h.endUserId!==u.endUserId))throw new He("forbidden");return u}function d(u,m,g,h){if(!t.scopeFor)throw new He("capability_unconfirmed");h.throwIfAborted();let p=t.scopeFor({endUserId:u,...m}),v;try{v=yt("Scope",p)}catch{throw new He("capability_unconfirmed")}return h.throwIfAborted(),a(v,u,g)}function c(u,m,g,h){let p=d(u,m,g,h);if(o(u,m)!==g)throw new He("stale_generation");return p}function l(u){return Di.map(m=>{let g=m==="session-configuration-v1"?u.configuration?.()!==void 0&&u.configure!==void 0:m==="memory-lifecycle-v1"&&Un(u)?.management!==void 0;return{feature:m,supported:g,installed:g,authorization:g?"allowed":"unconfirmed",device:g?"not-required":"unconfirmed"}})}let f=new Map;for(let[u,m]of t.families){if(m.execution&&m.transactionalExecution)throw new TypeError("Conflicting terminal execution backends");let g=m.execution??m.transactionalExecution;if(!g)continue;e.set(u,g);let h=(p,v)=>{let b=o(p,{sessionContract:u,sessionId:v.sessionId}),R="unavailable";if(v.binding)try{g.connection(p,v.binding.target.executorId,v.binding.target.connectionId),R="available"}catch{}let w=hr(b),x=v.deviceTools().some(T=>v.available(T.name))||w?.capability()===!0;return Di.map(T=>{let M=T==="execution-stream-v1"||T==="execution-background-v1"&&v.backgroundSupported()||T==="memory-lifecycle-v1"&&(w!==void 0||Un(b)?.management!==void 0)||T==="session-configuration-v1"&&b.configuration?.()!==void 0&&b.configure!==void 0;return{feature:T,supported:M,installed:M,authorization:T==="execution-stream-v1"?x?"allowed":"denied":T==="execution-background-v1"?v.available("Shell")?"allowed":"denied":T==="memory-lifecycle-v1"&&w?w.capability()?"allowed":"unconfirmed":M?"allowed":"unconfirmed",device:T==="execution-stream-v1"||T==="execution-background-v1"||T==="memory-lifecycle-v1"&&w?R:M?"not-required":"unconfirmed"}})};f.set(u,h),n.set(u,new Ud({host:g,sessionContracts:[u],resolveSession(p,v){return o(p,v),g.session(p,v.sessionId)},sessionFeatures:h}))}return{resolve:o,resolveObservation:s,sessionFeatures(u,m){let g=o(u,m),h=e.get(m.sessionContract),p=f.get(m.sessionContract);return!h||!p?l(g):p(u,h.session(u,m.sessionId))},async checkObservation(u,m,g){g.throwIfAborted();let{handle:h}=s(u,m),p=()=>{if(g.throwIfAborted(),s(u,m).handle!==h)throw new He("stale_generation");!t.registry.get(m.sessionId).ended&&h.status()!=="ended"&&h.owner?.assertCurrent()};if(p(),t.filterObservationReads&&!await t.filterObservationReads(u,m))throw new He("not_found");p();let v=e.get(m.sessionContract);if(v){let b=await v.options.readPolicy(u,g);if(p(),b.expiresAt!==void 0&&(!Number.isSafeInteger(b.expiresAt)||b.expiresAt<=v.now()))throw new He("source_unavailable");let R;try{R=yt("Scope",{applicationScopeId:v.options.applicationScopeId,endUserId:u,authorizationRevision:b.authorizationRevision})}catch{throw new He("capability_unconfirmed")}a(R,u,h);let w=v.sessions.get(m.sessionId);if(w&&(w.user!==u||BigInt(R.authorizationRevision)<BigInt(w.policy.authorizationRevision)))throw new He("stale_generation")}else d(u,m,h,g);if(p(),t.filterObservationReads&&!await t.filterObservationReads(u,m))throw new He("not_found");p()},async check(u,m,g){let h=o(u,m),p=e.get(m.sessionContract);if(p?await p.session(u,m.sessionId).refresh(g,!1):(await h.owner?.assertCurrent(),c(u,m,h,g)),g.throwIfAborted(),h!==o(u,m))throw new He("stale_generation")},async bindControl(u,m,g,h){if(!m.controller)throw new He("forbidden");if(!t.scopeFor||g.executionBinding!==null)throw new He("capability_unconfirmed");let p=o(u,g.session);await p.owner?.assertCurrent(),h.throwIfAborted();let v=c(u,g.session,p,h);return Dd(g,{session:g.session,scope:v,executionBinding:null,features:l(p),limits:qi})},serviceFor:u=>n.get(u),async authorize(u,m,g,h){if(i)throw new He("source_unavailable");if(!t.families.has(h))throw new He("unsupported_capability");let p=e.get(h);return p?cf(p,u,m,g):{controller:!0}},capabilities(){let u=Di.map(m=>({feature:m,supported:(m==="execution-stream-v1"||m==="execution-background-v1")&&n.size>0||(m==="session-configuration-v1"||m==="memory-lifecycle-v1")&&[...t.families.values()].some(g=>g.terminalCapabilities?.includes(m)),installed:(m==="execution-stream-v1"||m==="execution-background-v1")&&n.size>0||(m==="session-configuration-v1"||m==="memory-lifecycle-v1")&&[...t.families.values()].some(g=>g.terminalCapabilities?.includes(m)),authorization:"unconfirmed",device:"unconfirmed"}));return ss({sessionContracts:[...t.families.keys()],features:u,limits:qi})},close(){if(!i){i=!0;for(let u of n.values())u.close();n.clear(),e.clear()}}}}import{randomUUID as cI}from"node:crypto";var ub="terminal-services-v1",ls=262144,lI=128;function Pt(t){throw new He(t)}function Mt(t,e){try{return yt(t,e)}catch{return Pt("invalid_request")}}function ci(t,e,n=[]){let i=new URL(t.url??"/","http://serve.invalid").searchParams;return[...i.keys()].some(o=>![...e,...n].includes(o)||i.getAll(o).length!==1)&&Pt("invalid_request"),e.includes("contract")&&i.get("contract")!==ub&&Pt("protocol_version_mismatch"),e.some(o=>!i.has(o))&&Pt("invalid_request"),i}function uI(t){switch(t){case"unauthorized":return[401,"none"];case"forbidden":return[403,"none"];case"not_found":return[404,"none"];case"invalid_request":case"protocol_version_mismatch":return[400,"none"];case"payload_too_large":return[413,"none"];case"capacity_exceeded":case"request_limit":return[429,"backoff"];case"source_unavailable":return[503,"backoff"];case"unsupported_capability":case"capability_unconfirmed":return[409,"discover"];case"stale_generation":case"binding_conflict":case"revision_conflict":case"context_transition_required":return[409,"refresh"];case"busy":return[409,"backoff"];case"output_gap":case"integrity_mismatch":case"commit_unknown":case"request_conflict":return[409,"reconcile"]}}function gr(t,e,n,i=200){if(t.destroyed||t.writableEnded)return;let o=nn(Mt(e,n),{maxBytes:ls});t.writeHead(i,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length}),t.end(o)}function fI(t){return t instanceof He||t instanceof as?t.code:t instanceof Ve?t.code==="request_expired"?"stale_generation":t.code:t instanceof URIError||t instanceof Error&&t.name==="ZodError"?"invalid_request":t instanceof Rt&&t.code==="overloaded"?"capacity_exceeded":"source_unavailable"}function fb(t){let e=t.revalidateMs??1e4;if(!Number.isSafeInteger(e)||e<1||e>1e4)throw new RangeError("Invalid terminal revalidation interval");let n=Math.min(t.maxBodyBytes,ls),i=0;async function o(l,f){let u;try{u=await t.authenticate(l,f)}catch(m){if(m instanceof Rt)throw m;return Pt("unauthorized")}return u?.endUserId||Pt("unauthorized"),(l.aborted||f.destroyed||f.writableEnded)&&Pt("source_unavailable"),u.endUserId}async function s(l,f){(!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(l.headers["content-type"]??"")||l.headers["content-encoding"])&&Pt("invalid_request");let u=pi(l,n);t.admission.reserveBody(u).admitted||Pt("capacity_exceeded");try{let m=await xi(l,n,g=>Si(g,{maxBytes:n}));return m.ok||(m.reason==="too_large"&&f.setHeader("connection","close"),Pt(m.reason==="too_large"?"payload_too_large":"invalid_request")),m.value}finally{t.admission.releaseBody(u)}}function a(l){return t.serviceFor(l)??Pt("unsupported_capability")}async function d(l,f,u,m,g){t.admission.tryAdmitSse(u).admitted||Pt("capacity_exceeded");let p=new AbortController,v,b,R,w,x=!1,T=[],M=0,W,$,D=C=>{let F="eventId"in C,H=Mt(F?"ExecutorEvent":"OutputEvent",C);return on({event:C.type,...F?{id:C.eventId}:{},data:Buffer.from(nn(H,{maxBytes:ls})).toString("utf8")})},J=C=>{w||(w=C,p.abort(),v?.close(),f.headersSent&&!f.destroyed&&f.destroy())},S=()=>{x||(x=!0,R&&clearInterval(R),p.abort(),v?.close(),T=[],M=0,$=void 0,t.admission.releaseSse(u),l.removeListener("aborted",k))},k=()=>{J("source_unavailable"),S()};l.once("aborted",k),f.once("close",S);let A=()=>W||(W=(async()=>{if(p.signal.aborted||await o(l,f)!==u)return!1;let C=await t.authorize(l,f,u,m);return await v.check(C,p.signal),!p.signal.aborted})().catch(()=>!1).then(C=>(C||J("forbidden"),C)).finally(()=>{W=void 0}),W);try{let C=await t.authorize(l,f,u,m);v=await g(C,Q=>{if(p.signal.aborted)return;let re=D(Q);if(b)b.write(re);else{if(M+=Buffer.byteLength(re),T.length>=32||M>ls){J("capacity_exceeded");return}T.push(re)}},Q=>{if($!==void 0||b!==void 0){J("invalid_request");return}$=Q},J,p.signal),(w||p.signal.aborted||f.destroyed)&&(v.close(),Pt(w??"source_unavailable")),t.sseKeepAliveMs>0&&l.socket.setKeepAlive(!0,t.sseKeepAliveMs),l.socket.setTimeout(0),f.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no"}),b=t.sse.attach(f,{beforeFlush:A,gapFrame:()=>(J("output_gap"),"")});let F=$,H=T;if(b.replay((function*(){for(let Q of F??[])yield D(Q);yield*H})()),T=[],M=0,$=void 0,x||p.signal.aborted||f.destroyed){S();return}R=setInterval(()=>{A()},e),R.unref()}catch(C){throw S(),C}}async function c(l,f,u,m,g){let h=await o(l,f);t.admission.overloaded()&&Pt("source_unavailable"),m==="GET"&&(l.headers["transfer-encoding"]!==void 0||l.headers["content-length"]!==void 0&&l.headers["content-length"]!=="0")&&Pt("invalid_request");let p=/^\/v3\/terminal\/executors\/([^/]+)\/(events|output-batches)$/.exec(u),v=/^\/v3\/terminal\/executors\/([^/]+)\/operations\/([^/]+)$/.exec(u),b=/^\/v3\/terminal\/sessions\/([^/]+)\/(tool-output|tool-output-status)$/.exec(u),R=u==="/v3/terminal/capabilities",w=u==="/v3/terminal/bindings";if(!p&&!v&&!b&&!R&&!w){let J;if(await t.control?.({req:l,res:f,pathname:u,method:m,endUserId:h,signal:g,readBody:()=>J??=s(l,f),authorize:async S=>{g.throwIfAborted(),await o(l,f)!==h&&Pt("unauthorized");let k=await t.authorize(l,f,h,S);return g.throwIfAborted(),k},reply:(S,k,A)=>gr(f,S,k,A)}))return;Pt("not_found")}let x=w||p?.[2]==="output-batches"?"POST":"GET";if(m!==x&&Pt("invalid_request"),R){ci(l,["contract"]),gr(f,"CapabilitiesResponse",t.capabilities());return}if(v){let J=ci(l,["contract","sessionContract","sessionId","requestDigest","connectionId"]),S=Mt("SessionReference",{sessionContract:J.get("sessionContract"),sessionId:J.get("sessionId")}),k=Mt("OperationReference",{operationId:decodeURIComponent(v[2]),requestDigest:J.get("requestDigest")}),A=Mt("Id",decodeURIComponent(v[1])),C=Mt("Id",J.get("connectionId")),F=await t.authorize(l,f,h,S.sessionContract);gr(f,"ExecutionState",await a(S.sessionContract).executionState(h,F,A,C,S,k,g));return}if(m==="POST"){ci(l,[]);let J=await s(l,f);if(await o(l,f)!==h&&Pt("unauthorized"),w){let S=Mt("BindingRequest",J),k=S.session.sessionContract,A=t.serviceFor(k),C=await t.authorize(l,f,h,k),F=A?await A.bind(h,C,S,g):await t.bindControl?.(h,C,S,g);F||Pt("unsupported_capability"),gr(f,"BindingResponse",F)}else{let S=Mt("OutputBatchRequest",J),k=S.session.sessionContract;S.executorId!==decodeURIComponent(p[1])&&Pt("invalid_request");let A=a(k),C=await t.authorize(l,f,h,k);gr(f,"OutputStatus",await A.receive(h,C,S,g))}return}if(p){let J=ci(l,["contract","sessionContract","connectionId"]),S=Mt("SessionContract",J.get("sessionContract")),k=a(S),A=Mt("Id",decodeURIComponent(p[1])),C=Mt("Id",J.get("connectionId")),F=l.headers["last-event-id"];F!==void 0&&Mt("Sequence",F),await d(l,f,h,S,(H,Q,re,O,I)=>k.subscribeExecutor(h,H,A,C,{event:Q,close:O},I));return}let T=b[2]==="tool-output",M=ci(l,["contract","sessionContract","operationId","requestDigest"],T?["afterSeq"]:[]);l.headers["last-event-id"]!==void 0&&Pt("invalid_request");let W=Mt("SessionReference",{sessionContract:M.get("sessionContract"),sessionId:decodeURIComponent(b[1])}),$=a(W.sessionContract),D=Mt("OperationReference",{operationId:M.get("operationId"),requestDigest:M.get("requestDigest")});if(T){let J=M.has("afterSeq")?Mt("Sequence",M.get("afterSeq")):null;await d(l,f,h,W.sessionContract,(S,k,A,C,F)=>$.subscribeOutput(h,S,W,D,J,{event:k,replay:A,close:C},F))}else gr(f,"OutputStatus",await $.outputStatus(h,await t.authorize(l,f,h,W.sessionContract),W,D,g))}return(l,f,u,m)=>{if(u!=="/v3/terminal"&&!u.startsWith("/v3/terminal/"))return!1;let g=i<lI;g&&i++;let h=new AbortController,p=()=>h.abort();l.once("aborted",p),f.once("close",p);let v=(async()=>{g||Pt("capacity_exceeded"),await c(l,f,u,m,h.signal)})().catch(b=>{if(f.destroyed||f.writableEnded)return;if(f.headersSent){f.destroy();return}let R=fI(b),[w,x]=uI(R);if(w===429||w===503)for(let[M,W]of Object.entries(Ft(t.admission.retryAfterMs)))f.setHeader(M,W);let T={contract:ub,requestId:cI(),code:R,status:w,retryAction:x};if(w===413&&!l.complete){let M=nn(Mt("ErrorResponse",T),{maxBytes:ls});f.writeHead(w,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":M.length,connection:"close"}),f.write(M);let W=setTimeout(()=>{f.destroyed||f.end()},Zl);W.unref(),f.once("close",()=>clearTimeout(W))}else gr(f,"ErrorResponse",T,w)}).finally(()=>{g&&i--,l.removeListener("aborted",p),f.removeListener("close",p)});return t.trackRequestWork(v),!0}}function Ht(t){throw new He(t)}function pI(t){let e=t.reason;switch(e){case"turn_running":return Ht("busy");case"session_ended":return Ht("stale_generation");case"invalid_configuration":return Ht("invalid_request");case"unsupported":return Ht("unsupported_capability");case"context_transition_required":case"revision_conflict":case"request_conflict":case"request_limit":return Ht(e)}}function pb(t){return async e=>{let n=/^\/v3\/terminal\/sessions\/([^/]+)\/memory(?:\/commands(?:\/([^/]+))?)?$/.exec(e.pathname);if(n)return mI(e,t,n);let i=/^\/v3\/terminal\/sessions\/([^/]+)\/configuration$/.exec(e.pathname);if(!i)return!1;e.method!=="GET"&&e.method!=="POST"&&Ht("invalid_request");let o,s,a=decodeURIComponent(i[1]);if(e.method==="GET"){let f=ci(e.req,["contract","sessionContract"]);o=Mt("SessionReference",{sessionContract:f.get("sessionContract"),sessionId:a})}else ci(e.req,[]),s=Mt("ConfigurationRequest",await e.readBody()),(s.session.sessionId!==a||Object.keys(s.changes).length===0)&&Ht("invalid_request"),o=s.session;(await e.authorize(o.sessionContract)).controller||Ht("forbidden"),e.signal.throwIfAborted();let c=t.resolve(e.endUserId,o);await t.check(e.endUserId,o,e.signal),c!==t.resolve(e.endUserId,o)&&Ht("stale_generation"),e.signal.throwIfAborted();let l=c.configuration?.();if((!l||!c.configure)&&Ht("unsupported_capability"),s===void 0)e.reply("ConfigurationResponse",{contract:"terminal-services-v1",session:o,configuration:l});else{let f=await c.configure({requestId:s.requestId,expectedRevision:s.expectedRevision,changes:s.changes},{signal:e.signal,beforeCommit:async()=>{(await e.authorize(o.sessionContract)).controller||Ht("forbidden"),await t.check(e.endUserId,o,e.signal),c!==t.resolve(e.endUserId,o)&&Ht("stale_generation"),e.signal.throwIfAborted()}});f.status==="rejected"&&pI(f),e.reply("ConfigurationCommitResponse",{contract:s.contract,requestId:s.requestId,session:o,status:f.status,configuration:f.configuration})}return!0}}async function mI(t,e,n){try{let i=decodeURIComponent(n[1]),o=t.pathname.endsWith("/memory/commands"),s=n[2]===void 0?void 0:decodeURIComponent(n[2]);t.method!==(o?"POST":"GET")&&Ht("invalid_request");let a,d,c;if(o)ci(t.req,[]),d=Mt("MemoryCommandRequest",await t.readBody()),d.session.sessionId!==i&&Ht("invalid_request"),a=d.session;else{let h=ci(t.req,["contract","sessionContract",...s?["requestId"]:[]]);a=Mt("SessionReference",{sessionContract:h.get("sessionContract"),sessionId:i}),s!==void 0&&(Mt("MemoryIdentifier",s),c=Mt("MemoryIdentifier",h.get("requestId")))}let l=e.resolve(t.endUserId,a),f=async()=>{(await t.authorize(a.sessionContract)).controller||Ht("forbidden"),await e.check(t.endUserId,a,t.signal),l!==e.resolve(t.endUserId,a)&&Ht("stale_generation"),t.signal.throwIfAborted()};await f(),(d!==void 0||Un(l)?.management===void 0)&&await hr(l)?.prepare(t.signal),await f();let u=Un(l),m=u?.management;(!u||!m)&&Ht("unsupported_capability");let g=()=>{(Un(l)!==u||u.management!==m)&&Ht("stale_generation"),u.status().enabled||Ht("source_unavailable"),m.assertCurrent()};if(g(),m.identity.endUserId!==t.endUserId&&Ht("forbidden"),d!==void 0){let h=rb(l);h||Ht("unsupported_capability");let{contract:p,session:v,...b}=d,R=await h(b,{signal:t.signal,beforeCommit:f});await m.read(),await f(),g(),t.reply("MemoryReceiptResponse",{contract:"terminal-services-v1",session:a,receipt:R})}else if(s!==void 0){let h=await m.status(s,c);await f(),g(),t.reply("MemoryReceiptResponse",{contract:"terminal-services-v1",session:a,receipt:h})}else{let h=await m.read();await f(),g(),t.reply("MemoryStateResponse",{contract:"terminal-services-v1",session:a,memory:h})}return!0}catch(i){throw i instanceof at?new He(i.code):i}}import{randomUUID as hI}from"node:crypto";var nt={};nt.OutputCorrelation=r.object({contract:r.lazy(()=>nt.LegacyContract),session:r.lazy(()=>nt.SessionReference),toolCallId:r.lazy(()=>nt.LegacyId),operation:r.lazy(()=>nt.OperationReference),outputAuthority:r.union([r.literal("session-events"),r.literal("tool-output")])}).strict();nt.Contract=r.literal("terminal-observation-v1");nt.SessionReference=r.object({sessionContract:r.lazy(()=>nt.SessionContract),sessionId:r.lazy(()=>nt.LegacyId)}).strict();nt.SessionContract=r.union([r.literal("sdk1"),r.literal("sdk2-offload-v1")]);nt.LegacyId=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);nt.OperationReference=r.object({operationId:r.lazy(()=>nt.Id),requestDigest:r.lazy(()=>nt.Digest)}).strict();nt.Id=r.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._~-]*$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=128);nt.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));nt.ErrorCode=r.union([r.literal("invalid_request"),r.literal("protocol_version_mismatch"),r.literal("unauthorized"),r.literal("forbidden"),r.literal("not_found"),r.literal("unsupported_capability"),r.literal("capability_unconfirmed"),r.literal("source_unavailable"),r.literal("stale_generation"),r.literal("binding_conflict"),r.literal("revision_conflict"),r.literal("busy"),r.literal("capacity_exceeded"),r.literal("payload_too_large"),r.literal("output_gap"),r.literal("integrity_mismatch"),r.literal("commit_unknown"),r.literal("context_transition_required"),r.literal("request_conflict"),r.literal("request_limit")]);nt.Sequence=r.string().regex(new RegExp("^(0|[1-9][0-9]{0,17}|[1-8][0-9]{18}|9[0-1][0-9]{17}|92[0-1][0-9]{16}|922[0-2][0-9]{15}|9223[0-2][0-9]{14}|92233[0-6][0-9]{13}|922337[0-1][0-9]{12}|92233720[0-2][0-9]{10}|922337203[0-5][0-9]{9}|9223372036[0-7][0-9]{8}|92233720368[0-4][0-9]{7}|922337203685[0-3][0-9]{6}|9223372036854[0-6][0-9]{5}|92233720368547[0-6][0-9]{4}|922337203685477[0-4][0-9]{3}|9223372036854775[0-7][0-9]{2}|922337203685477580[0-6]|9223372036854775807)$","u")).refine(t=>[...t].length<=19);nt.ResourceState=r.union([r.literal("active"),r.literal("accepted"),r.literal("draining"),r.literal("completed"),r.literal("failed"),r.literal("unknown")]);nt.ResourceError=r.union([r.literal("close_failed"),r.literal("publication_failed"),r.literal("settlement_failed"),r.literal("settlement_unavailable")]);nt.ResourcesResponse=r.object({contract:r.lazy(()=>nt.Contract),session:r.lazy(()=>nt.SessionReference),epochStartSeq:r.lazy(()=>nt.Sequence),state:r.lazy(()=>nt.ResourceState),closeRequested:r.boolean(),executionEnded:r.boolean(),errorCode:r.union([r.lazy(()=>nt.ResourceError),r.null()])}).strict();nt.CorrelationsResponse=r.object({contract:r.lazy(()=>nt.Contract),session:r.lazy(()=>nt.SessionReference),correlations:r.array(r.lazy(()=>nt.OutputCorrelation)).max(32),truncated:r.boolean()}).strict();nt.ErrorResponse=r.object({contract:r.lazy(()=>nt.Contract),requestId:r.lazy(()=>nt.Id),code:r.lazy(()=>nt.ErrorCode),status:r.union([r.literal(400),r.literal(401),r.literal(403),r.literal(404),r.literal(409),r.literal(413),r.literal(429),r.literal(503)]),retryAction:r.union([r.literal("none"),r.literal("discover"),r.literal("refresh"),r.literal("reconcile"),r.literal("backoff")])}).strict();nt.LegacyContract=r.literal("terminal-services-v1");function mb(t,e){if(!Object.hasOwn(nt,t))throw new TypeError("Unknown terminal observation type");return nt[t].parse(e)}var Ld="terminal-observation-v1",gI=262144;function un(t){throw new He(t)}function Lf(t,e){try{return mb(t,e)}catch{return un("invalid_request")}}function Uf(t,e,n,i=200){if(t.destroyed||t.writableEnded)return;let o=nn(Lf(e,n),{maxBytes:gI});t.writeHead(i,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length}),t.end(o)}function yI(t){return t instanceof He?t.code:t instanceof Ve?t.code==="request_expired"?"stale_generation":t.code:t instanceof URIError?"invalid_request":t instanceof Rt&&t.code==="overloaded"?"capacity_exceeded":"source_unavailable"}function vI(t){switch(t){case"unauthorized":return[401,"none"];case"forbidden":return[403,"none"];case"not_found":return[404,"none"];case"invalid_request":case"protocol_version_mismatch":return[400,"none"];case"payload_too_large":return[413,"none"];case"capacity_exceeded":case"request_limit":return[429,"backoff"];case"source_unavailable":return[503,"backoff"];case"unsupported_capability":case"capability_unconfirmed":return[409,"discover"];case"stale_generation":case"binding_conflict":case"revision_conflict":case"context_transition_required":return[409,"refresh"];case"busy":return[409,"backoff"];case"output_gap":case"integrity_mismatch":case"commit_unknown":case"request_conflict":return[409,"reconcile"]}}function hb(t){let e=0,n=new Map;async function i(s,a,d){let c;try{c=await t.authenticate(s,a)}catch(l){if(l instanceof Rt)throw l;return un("unauthorized")}return d.throwIfAborted(),c?.endUserId||un("unauthorized"),c.endUserId}async function o(s,a,d,c,l){let f=await i(s,a,l),u=n.get(f)??0;t.admission.overloaded()?.reason==="event_loop_delay"&&un("source_unavailable"),u>=16&&un("capacity_exceeded"),n.set(f,u+1);try{let m=/^\/v3\/terminal-observation\/sessions\/([^/]+)\/(resources|output-correlations)$/.exec(d);m||un("not_found"),(c!=="GET"||s.headers["transfer-encoding"]!==void 0||s.headers["content-length"]!==void 0&&s.headers["content-length"]!=="0"||s.headers["content-encoding"])&&un("invalid_request");let g=new URL(s.url??"/","http://serve.invalid").searchParams,h=["contract","sessionContract",...m[2]==="output-correlations"?["toolCallId"]:[]];[...g.keys()].some(T=>!h.includes(T)||g.getAll(T).length!==1)&&un("invalid_request"),g.get("contract")!==Ld&&un("protocol_version_mismatch");let p=Lf("SessionReference",{sessionContract:g.get("sessionContract"),sessionId:decodeURIComponent(m[1])}),v=g.has("toolCallId")?Lf("LegacyId",g.get("toolCallId")):void 0,b=await t.authorize(s,a,f,p.sessionContract);l.throwIfAborted(),b.controller||un("forbidden");let R=t.resolve(f,p);await t.check(f,p,l),l.throwIfAborted();let w=m[2]==="output-correlations"?await t.readOutputCorrelations(f,b,p,v,l):void 0;await i(s,a,l)!==f&&un("unauthorized");let x=await t.authorize(s,a,f,p.sessionContract);if(l.throwIfAborted(),x.controller||un("forbidden"),await t.check(f,p,l),l.throwIfAborted(),(R.handle!==t.resolve(f,p).handle||R.registry.get(p.sessionId)?.handle!==R.handle)&&un("stale_generation"),w)w.some(T=>T.session.sessionContract!==p.sessionContract||T.session.sessionId!==p.sessionId||v!==void 0&&T.toolCallId!==v)&&un("integrity_mismatch"),Uf(a,"CorrelationsResponse",{contract:Ld,session:p,correlations:w.slice(-32),truncated:w.length>32});else{let T=R.registry.resourceObservation(p.sessionId);T||un("not_found"),Uf(a,"ResourcesResponse",{contract:Ld,session:p,...T})}}finally{let m=n.get(f)-1;m===0?n.delete(f):n.set(f,m)}}return(s,a,d,c)=>{if(d!=="/v3/terminal-observation"&&!d.startsWith("/v3/terminal-observation/"))return!1;let l=new AbortController,f=()=>l.abort();s.once("aborted",f),a.once("close",f);let u,m=new Promise((w,x)=>{u=x}),g=()=>u(new He("source_unavailable"));l.signal.addEventListener("abort",g,{once:!0});let h=setTimeout(f,1e4);h.unref(),(s.aborted||a.destroyed||a.writableEnded)&&f();let p=e<128;p&&e++;let v=(async()=>{p||un("capacity_exceeded"),await o(s,a,d,c,l.signal)})(),b=v.then(()=>{},()=>{}).finally(()=>{p&&e--});t.trackRequestWork(b);let R=Promise.race([v,m]).catch(w=>{if(a.destroyed||a.writableEnded)return;if(a.headersSent){a.destroy();return}let x=yI(w),[T,M]=vI(x);if(T===429||T===503)for(let[W,$]of Object.entries(Ft(t.admission.retryAfterMs)))a.setHeader(W,$);Uf(a,"ErrorResponse",{contract:Ld,requestId:hI(),code:x,status:T,retryAction:M},T)}).finally(()=>{clearTimeout(h),s.removeListener("aborted",f),a.removeListener("close",f),l.signal.removeEventListener("abort",g)});return t.trackRequestWork(R),!0}}import{randomUUID as bI}from"node:crypto";var Ne={};Ne.Contract=r.literal("terminal-profile-v1");Ne.Text=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);Ne.NullableText=r.union([r.lazy(()=>Ne.Text),r.null()]);Ne.Id=r.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._~-]*$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=128);Ne.SessionContract=r.union([r.literal("sdk1"),r.literal("sdk2-offload-v1")]);Ne.SessionReference=r.object({sessionContract:r.lazy(()=>Ne.SessionContract),sessionId:r.lazy(()=>Ne.Text)}).strict();Ne.Model=r.object({handle:r.lazy(()=>Ne.Text),displayName:r.lazy(()=>Ne.Text),manufacturer:r.lazy(()=>Ne.NullableText),family:r.lazy(()=>Ne.NullableText)}).strict();Ne.Aliases=r.record(r.lazy(()=>Ne.Text),r.lazy(()=>Ne.Text)).refine(t=>Object.keys(t).length<=1024);Ne.Catalog=r.object({models:r.array(r.lazy(()=>Ne.Model)).max(1024),aliases:r.lazy(()=>Ne.Aliases),capabilities:r.lazy(()=>Ne.Capabilities)}).strict();Ne.Quota=r.object({state:r.literal("not_exposed"),enforcement:r.literal("gateway")}).strict();Ne.Counter=r.number().int().safe().min(0).max(9007199254740991);Ne.Usage=r.object({window:r.literal("1d"),endUserId:r.lazy(()=>Ne.Text),requests:r.lazy(()=>Ne.Counter),inTokens:r.lazy(()=>Ne.Counter),outTokens:r.lazy(()=>Ne.Counter),cacheRTokens:r.lazy(()=>Ne.Counter),cacheWTokens:r.lazy(()=>Ne.Counter)}).strict();Ne.CatalogResponse=r.object({contract:r.lazy(()=>Ne.Contract),session:r.lazy(()=>Ne.SessionReference),models:r.array(r.lazy(()=>Ne.Model)).max(1024),aliases:r.lazy(()=>Ne.Aliases),quota:r.lazy(()=>Ne.Quota),capabilities:r.lazy(()=>Ne.Capabilities)}).strict();Ne.UsageResponse=r.object({contract:r.lazy(()=>Ne.Contract),session:r.lazy(()=>Ne.SessionReference),usage:r.lazy(()=>Ne.Usage),quota:r.lazy(()=>Ne.Quota)}).strict();Ne.ErrorCode=r.union([r.literal("invalid_request"),r.literal("protocol_version_mismatch"),r.literal("unauthorized"),r.literal("forbidden"),r.literal("not_found"),r.literal("unsupported_capability"),r.literal("capability_unconfirmed"),r.literal("source_unavailable"),r.literal("stale_generation"),r.literal("binding_conflict"),r.literal("revision_conflict"),r.literal("busy"),r.literal("capacity_exceeded"),r.literal("payload_too_large"),r.literal("output_gap"),r.literal("integrity_mismatch"),r.literal("commit_unknown"),r.literal("context_transition_required"),r.literal("request_conflict"),r.literal("request_limit")]);Ne.ErrorResponse=r.object({contract:r.lazy(()=>Ne.Contract),requestId:r.lazy(()=>Ne.Id),code:r.lazy(()=>Ne.ErrorCode),status:r.union([r.literal(400),r.literal(401),r.literal(403),r.literal(404),r.literal(409),r.literal(413),r.literal(429),r.literal(503)]),retryAction:r.union([r.literal("none"),r.literal("discover"),r.literal("refresh"),r.literal("reconcile"),r.literal("backoff")])}).strict();Ne.CapabilityTools=r.object({read:r.boolean(),write:r.boolean(),edit:r.boolean(),glob:r.boolean(),grep:r.boolean(),list:r.boolean(),shell:r.boolean(),process:r.boolean(),webFetch:r.boolean(),webSearch:r.boolean(),http:r.boolean(),todoWrite:r.boolean(),askUser:r.boolean(),agent:r.boolean(),skills:r.boolean(),mcp:r.boolean(),customTools:r.boolean()}).strict();Ne.CapabilityPlatform=r.object({imageGen:r.boolean(),videoGen:r.boolean(),webSearch:r.boolean(),speechToText:r.boolean(),textToSpeech:r.boolean()}).strict();Ne.BoundDeviceTools=r.object({read:r.boolean().optional(),write:r.boolean().optional(),edit:r.boolean().optional(),glob:r.boolean().optional(),grep:r.boolean().optional(),list:r.boolean().optional(),shell:r.boolean().optional(),process:r.boolean().optional(),skills:r.boolean().optional(),mcp:r.boolean().optional(),customTools:r.boolean().optional()}).strict();Ne.ExecutionCapabilities=r.object({version:r.literal("bound-device-v1"),boundDevice:r.object({tools:r.lazy(()=>Ne.BoundDeviceTools)}).strict()}).strict();Ne.Capabilities=r.object({tools:r.lazy(()=>Ne.CapabilityTools),platform:r.lazy(()=>Ne.CapabilityPlatform),execution:r.lazy(()=>Ne.ExecutionCapabilities).optional()}).strict();function Fd(t,e){if(!Object.hasOwn(Ne,t))throw new TypeError("Unknown terminal profile type");return Ne[t].parse(e)}var Hd="terminal-profile-v1",SI=262144;function cn(t){throw new He(t)}function gb(t,e){try{return Fd(t,e)}catch{return cn("invalid_request")}}function Ff(t,e,n,i=200){if(t.destroyed||t.writableEnded)return;let o=nn(gb(e,n),{maxBytes:SI});t.writeHead(i,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length}),t.end(o)}function wI(t){return t instanceof He?t.code:t instanceof Ve?t.code==="request_expired"?"stale_generation":t.code:t instanceof URIError?"invalid_request":t instanceof Rt&&t.code==="overloaded"?"capacity_exceeded":"source_unavailable"}function kI(t){switch(t){case"unauthorized":return[401,"none"];case"forbidden":return[403,"none"];case"not_found":return[404,"none"];case"invalid_request":case"protocol_version_mismatch":return[400,"none"];case"payload_too_large":return[413,"none"];case"capacity_exceeded":case"request_limit":return[429,"backoff"];case"source_unavailable":return[503,"backoff"];case"unsupported_capability":case"capability_unconfirmed":return[409,"discover"];case"stale_generation":case"binding_conflict":case"revision_conflict":case"context_transition_required":return[409,"refresh"];case"busy":return[409,"backoff"];case"output_gap":case"integrity_mismatch":case"commit_unknown":case"request_conflict":return[409,"reconcile"]}}function yb(t){let e=0,n=new Map;async function i(s,a,d){let c;try{c=await t.authenticate(s,a)}catch(l){if(l instanceof Rt)throw l;return cn("unauthorized")}return d.throwIfAborted(),c?.endUserId||cn("unauthorized"),c.endUserId}async function o(s,a,d,c,l){let f=await i(s,a,l),u=n.get(f)??0;t.admission.overloaded()?.reason==="event_loop_delay"&&cn("source_unavailable"),u>=16&&cn("capacity_exceeded"),n.set(f,u+1);try{let m=/^\/v3\/terminal-profile\/sessions\/([^/]+)\/(catalog|usage)$/.exec(d);m||cn("not_found"),(c!=="GET"||s.headers["transfer-encoding"]!==void 0||s.headers["content-length"]!==void 0&&s.headers["content-length"]!=="0"||s.headers["content-encoding"])&&cn("invalid_request");let g=new URL(s.url??"/","http://serve.invalid").searchParams,h=["contract","sessionContract"];[...g.keys()].some(M=>!h.includes(M)||g.getAll(M).length!==1)&&cn("invalid_request"),g.get("contract")!==Hd&&cn("protocol_version_mismatch");let p=gb("SessionReference",{sessionContract:g.get("sessionContract"),sessionId:decodeURIComponent(m[1])}),v=await t.authorize(s,a,f,p.sessionContract);l.throwIfAborted(),v.controller||cn("forbidden");let b=t.resolve(f,p);await t.check(f,p,l),l.throwIfAborted();let R=m[2]==="catalog"?await t.readCatalog(f,p,l):void 0,w=m[2]==="usage"?await t.readUsage(f,p,l):void 0;await i(s,a,l)!==f&&cn("unauthorized");let x=await t.authorize(s,a,f,p.sessionContract);l.throwIfAborted(),x.controller||cn("forbidden"),await t.check(f,p,l),l.throwIfAborted(),(b.handle!==t.resolve(f,p).handle||b.registry.get(p.sessionId)?.handle!==b.handle)&&cn("stale_generation");let T={state:"not_exposed",enforcement:"gateway"};if(R!==void 0){let M=Fd("Catalog",{...R,capabilities:{...R.capabilities,platform:sd(R.capabilities.platform)}}),W=new Set(M.models.map($=>$.handle));(W.size!==M.models.length||Object.values(M.aliases).some($=>!W.has($)))&&cn("integrity_mismatch"),Ff(a,"CatalogResponse",{contract:Hd,session:p,...M,quota:T})}else if(w!==void 0){let M=Fd("Usage",w);(M.endUserId!==f||M.endUserId!==b.handle.endUserId)&&cn("integrity_mismatch"),Ff(a,"UsageResponse",{contract:Hd,session:p,usage:M,quota:T})}else cn("unsupported_capability")}finally{let m=n.get(f)-1;m===0?n.delete(f):n.set(f,m)}}return(s,a,d,c)=>{if(d!=="/v3/terminal-profile"&&!d.startsWith("/v3/terminal-profile/"))return!1;let l=new AbortController,f=()=>l.abort();s.once("aborted",f),a.once("close",f);let u,m=new Promise((w,x)=>{u=x}),g=()=>u(new He("source_unavailable"));l.signal.addEventListener("abort",g,{once:!0});let h=setTimeout(f,1e4);h.unref(),(s.aborted||a.destroyed||a.writableEnded)&&f();let p=e<128;p&&e++;let v=(async()=>{p||cn("capacity_exceeded"),await o(s,a,d,c,l.signal)})(),b=v.then(()=>{},()=>{}).finally(()=>{p&&e--});t.trackRequestWork(b);let R=Promise.race([v,m]).catch(w=>{if(a.destroyed||a.writableEnded)return;if(a.headersSent){a.destroy();return}let x=wI(w),[T,M]=kI(x);if(T===429||T===503)for(let[W,$]of Object.entries(Ft(t.admission.retryAfterMs)))a.setHeader(W,$);Ff(a,"ErrorResponse",{contract:Hd,requestId:bI(),code:x,status:T,retryAction:M},T)}).finally(()=>{clearTimeout(h),s.removeListener("aborted",f),a.removeListener("close",f),l.signal.removeEventListener("abort",g)});return t.trackRequestWork(R),!0}}var vb=new WeakMap;function bb(t,e){vb.set(t,e)}function Hf(t){let e=vb.get(t)?.();if(e===void 0)throw new He("unsupported_capability");return e}var xI="127.0.0.1",Sb=1024,RI=15e3,II=1024*1024,TI=3e4,AI=3e4,EI=1e4,CI=3e4,_I=5e3,PI=5e3,zf=50,wb=5e3,MI=/^\/v1\/sessions\/([^/]+)\/(messages|events|abort)$/,kb=/^\/v1\/approvals\/([^/]+)\/credential$/,xb={unknown_challenge:404,expired:410,digest_mismatch:409,already_resolved:409},OI={unknown_challenge:"request_not_found",expired:"request_expired",digest_mismatch:"digest_mismatch",already_resolved:"request_already_resolved"};async function Rb(t){return zd(t)}async function VN(t,e){if(t.v2===void 0)throw new TypeError("Cache routes require v2 end-user authentication");return zd(t,e)}async function $N(t,e,n,i){if(t.v2===void 0)throw new TypeError("Archive routes require v2 end-user authentication");return zd(t,n,e,i)}async function KN(t,e,n){if(t.v2===void 0)throw new TypeError("Archive sync requires v2 end-user authentication");return zd(t,void 0,n,{disableV1:!0},e)}async function zd(t,e,n,i,o){if(typeof t.token!="string"||t.token.trim()==="")throw new Error("startServer: token must be a non-empty string");if(t.terminal!==void 0&&(t.terminal.contract!=="terminal-services-v1"||t.v2===void 0))throw new TypeError("Terminal services require the explicit contract and v2 authentication");if(t.terminal?.revalidateMs!==void 0&&(!Number.isSafeInteger(t.terminal.revalidateMs)||t.terminal.revalidateMs<1||t.terminal.revalidateMs>1e4))throw new RangeError("Invalid terminal revalidation interval");if(t.terminal?.scopeFor!==void 0&&typeof t.terminal.scopeFor!="function")throw new TypeError("Terminal scopeFor must be a trusted function");let s=t.token,a=t.host??xI,d=t.heartbeatMs??RI;if(t.v2?.createSession.execution!==void 0&&t.v2.createSession.transactionalExecution!==void 0)throw new TypeError("Conflicting execution backends");let c=t.v2?.createSession.execution??t.v2?.createSession.transactionalExecution,l=(t.disableV1??t.v2!==void 0)||i?.disableV1===!0||c!==void 0,f=c!==void 0||n!==void 0||e!==void 0||o!==void 0||t.terminal!==void 0,u={...t.sse??{},...f?{maxFrameBytes:t.sse?.maxFrameBytes??2*1024*1024}:{}};if(t.terminal!==void 0){for(let L of[u.maxFrameBytes??2097152,u.maxBufferBytes??2097152])if(!Number.isSafeInteger(L)||L<1||L>2097152)throw new RangeError("Terminal SSE budgets must be finite and no greater than 2 MiB")}let m=t.v2===void 0?void 0:Zh(t.v2,f),g=t.eventBufferMaxBytes??(f?4*1024*1024:void 0),h=new _r({...u,heartbeatMs:u.heartbeatMs??d}),p=t.maxBodyBytes??II,v=t.version??"0.0.0-dev",b=t.logger,R=$n(b),w=Date.now(),x=!1,T=new Set,M=L=>{T.add(L);let N=()=>{T.delete(L)};L.then(N,N)},W=new Ia({eventBufferSize:t.eventBufferSize??Sb,...g!==void 0?{eventBufferMaxBytes:g}:{},...u.maxFrameBytes!==void 0?{maxEventBytes:u.maxFrameBytes}:{},...t.v1?.governance??{},...t.v1?.now!==void 0?{now:t.v1.now}:{},onPumpError:(L,N)=>{b?.error(We(ae.createFailed,{message:`[${L}] ${N instanceof Error?N.message:String(N)}`}))}}),$=0,D,J=ig(t.admission??{},{activeSessions:()=>W.activeCount()+$+(D?.activeCount()??0)+(D?.pendingCount()??0),...b!==void 0?{logger:b}:{}}),S=t.sse?.keepAliveMs??AI,k=t.sse?.drainRetryMs??EI,A=new Set,C,F,H;if(t.v2!==void 0){let L=t.v2.onTurnEndNotify;if(L!==void 0){let qe=Kr({governor:t.governor});C=new Mr({...qe!==void 0?{fetchImpl:qe}:{},...L,onDeliveryFailure:Me=>{R("error",Xe.notifyDeliveryFailed,{sessionId:Me.sessionId,...Me.turnId!==void 0?{turnId:Me.turnId}:{},attempts:Me.attempts,reason:Me.reason},We(ae.v2NotifyFailed,{sessionId:Me.sessionId,attempts:Me.attempts,reason:Me.reason})),L.onDeliveryFailure?.(Me)}})}let N=C,se=t.v2.createSession,ge=se.sweepRetention?.bind(se);D=new Oa({eventBufferSize:t.eventBufferSize??Sb,...g!==void 0?{eventBufferMaxBytes:g}:{},...u.maxFrameBytes!==void 0?{maxEventBytes:u.maxFrameBytes}:{},...t.v2.eventLog!==void 0?{eventLog:t.v2.eventLog}:{},...t.v2.governance??{},...f?{maxRetainedSessions:t.v2.governance?.maxRetainedSessions??256}:{},...t.v2.now!==void 0?{now:t.v2.now}:{},...t.v2.onSubscribersGone!==void 0?{onSubscribersGone:t.v2.onSubscribersGone}:{},...N!==void 0?{onTurnEndNotify:qe=>N.notify(qe)}:{},...ge!==void 0?{onSweep:ge}:{},onPumpError:(qe,Me)=>{Qn(t.observability?.metrics).pumpErrors.inc(),b?.error(We(ae.createFailed,{message:`[v2:${qe}] ${Me instanceof Error?Me.message:String(Me)}`}))}}),H=i?.offload?.only?void 0:gf({...!i?.offload&&i?.filterSessionReads?{filterSessionReads:i.filterSessionReads}:{},options:t.v2,authenticate:m.authenticate,registry:D,admission:J,maxBodyBytes:p,sse:h,sseKeepAliveMs:S,trackRequestWork:M,...b!==void 0?{logger:b}:{}}),i?.offload&&(F=gf({sessionFamily:"sdk2-offload-v1",options:i.offload.options,prepareCreate:i.offload.prepareCreate,sessionContracts:[...i.offload.only?[]:[{contract:"sdk1",availability:"legacy-complete"}],{contract:"sdk2-offload-v1",availability:"source-required"}],...i.offload.readHistoryOrigin?{readHistoryOrigin:i.offload.readHistoryOrigin}:{},...i.filterSessionReads?{filterSessionReads:i.filterSessionReads}:{},authenticate:m.authenticate,registry:D,admission:J,maxBodyBytes:p,sse:h,sseKeepAliveMs:S,trackRequestWork:M,...b!==void 0?{logger:b}:{}}))}let Q=new Map;t.v2&&!i?.offload?.only&&Q.set("sdk1",t.v2.createSession),i?.offload&&Q.set("sdk2-offload-v1",i.offload.options.createSession);let re=t.terminal!==void 0&&D!==void 0?lb({registry:D,families:Q,scopeFor:t.terminal.scopeFor,...i?.filterSessionReads?{filterObservationReads:async(L,N)=>i.offload&&N.sessionContract!=="sdk2-offload-v1"?!0:(await i.filterSessionReads(L,[N.sessionId])).includes(N.sessionId)}:{}}):void 0,O=re===void 0?void 0:fb({...re,control:pb(re),authenticate:m.authenticate,admission:J,sse:h,maxBodyBytes:p,sseKeepAliveMs:S,trackRequestWork:M,...t.terminal?.revalidateMs===void 0?{}:{revalidateMs:t.terminal.revalidateMs}}),I=re===void 0?void 0:hb({authenticate:m.authenticate,authorize:re.authorize,resolve:re.resolveObservation,check:re.checkObservation,admission:J,trackRequestWork:M,readOutputCorrelations:(L,N,se,ge,qe)=>{let Me=re.serviceFor(se.sessionContract);if(!Me)throw new He("unsupported_capability");return Me.readOutputCorrelations(L,N,se,ge,qe)}}),B=re===void 0?void 0:yb({authenticate:m.authenticate,authorize:re.authorize,resolve:re.resolveObservation,check:re.checkObservation,admission:J,trackRequestWork:M,readCatalog:(L,N,se)=>{let ge=Hf(re.resolveObservation(L,N).handle).readPlatformCatalog;if(ge===void 0)throw new He("unsupported_capability");return ge(se)},readUsage:(L,N,se)=>{let ge=Hf(re.resolveObservation(L,N).handle).readPlatformUsage;if(ge===void 0)throw new He("unsupported_capability");return ge(se)}}),z=e!==void 0&&t.v2!==void 0?vv({link:e,admission:J,authenticate:m.authenticate,track:M}):void 0,j=n!==void 0&&t.v2!==void 0?qg({host:n,admission:J,authenticate:m.authenticate,track:M}):void 0,ne=o!==void 0&&t.v2!==void 0?Sv({host:o,admission:J,authenticate:m.authenticate,track:M}):void 0,U=(L,N,se,ge)=>!!(I?.(L,N,se,ge)||B?.(L,N,se,ge)||O?.(L,N,se,ge)||z?.(L,N,se,ge)||ne?.(L,N)||F!==void 0&&F(L,N,se,ge)||j?.(L,N)||H!==void 0&&H(L,N,se,ge)),le={session:F!==void 0?"sdk2-offload-v1":H!==void 0?"sdk1":null,execution:c!==void 0&&(F!==void 0||H!==void 0),archive:j!==void 0,"archive-sync":ne!==void 0,cache:z!==void 0,terminal:O!==void 0,"terminal-observation":I!==void 0,"terminal-profile":B!==void 0},ue=(L,N,se,ge)=>U(L,N,se,ge)||Nt(L,N,se,ge),ie=t.v2===void 0?void 0:Gv({authenticate:m.authenticate,delegate:ue,sessionFamilies:[...H!==void 0?["sdk1"]:[],...F!==void 0?["sdk2-offload-v1"]:[]],installed:le,track:M,retryAfterMs:()=>J.retryAfterMs,...D===void 0?{}:{sessionClosure:Zv({registry:D,installed:le,...c===void 0?{}:{execution:c},...n===void 0?{}:{archive:n},...re===void 0?{}:{terminal:re},...e===void 0?{}:{cache:e}})}});if(t.legacyPrefixes!==void 0&&!Kv(t.legacyPrefixes))throw new TypeError(`legacyPrefixes must be one of readwrite | readonly | off, got ${JSON.stringify(t.legacyPrefixes)}`);let me=t.v2===void 0?void 0:Xv({mode:t.legacyPrefixes??$v,...t.legacyPrefixSunset===void 0?{}:{sunset:Qv(t.legacyPrefixSunset)},log:R}),q=D,X=C,te=vg({host:a,options:t.observability,startedAt:w,log:R,v1Active:()=>W.activeCount(),v2:()=>q===void 0?void 0:yg(q),notifierStats:()=>X?.stats(),sseStats:()=>h.stats(),ringStats:()=>xa(W.ringStats(),q?.ringStats()),...t.governor!==void 0?{governorStats:()=>t.governor?.stats()}:{},closing:()=>x});te.addReadinessProbe(()=>{let L=J.readiness();return L.ready?!0:{ready:!1,reason:L.reasons.join(",")||"admission"}});let Se=i?.offload?.options.store;Se?.readiness!==void 0&&Se!==t.v2?.store&&te.addReadinessProbe(()=>Se.readiness?.()??!0);let Ue=t.v2?.store;Ue?.readiness!==void 0&&te.addReadinessProbe(()=>Ue.readiness?.()??!0);let $e=(L,N,se,ge)=>{let qe=Bn(ge),Me=hg(L);R("error",Xe.requestUnhandled,{...Me!==void 0?{requestId:Me.requestId,route:Me.route}:{},method:se,message:qe},We(ae.requestUnhandled,{method:se,path:N,message:qe}));try{if(L.destroyed||L.writableEnded)return;if(!L.headersSent){pe(L,500,"internal_error",ae.internalError);return}L.end()}catch{L.destroy()}},Fe=async(L,N)=>{let se=pi(L,p),ge=J.reserveBody(se);return ge.admitted?(N.once("close",()=>J.releaseBody(se)),xi(L,p)):(ni(N,ge),"rejected")},lt=(L,N,se)=>{se==="too_large"?Tr(L,N,"body_too_large",ae.bodyTooLarge,{maxBytes:p}):pe(N,400,"invalid_json",ae.invalidJson)},kt=async(L,N)=>{let se=await Fe(L,N);if(se==="rejected")return;if(!se.ok){lt(L,N,se.reason);return}if(typeof se.value!="object"||se.value===null||Array.isArray(se.value)){pe(N,400,"invalid_body",ae.invalidBody);return}let ge=se.value;if(ge.prompt!==void 0&&typeof ge.prompt!="string"){pe(N,400,"invalid_body",ae.invalidBody);return}if(ge.model!==void 0&&typeof ge.model!="string"){pe(N,400,"invalid_body",ae.invalidBody);return}if(ge.profile!==void 0&&typeof ge.profile!="string"){pe(N,400,"invalid_body",ae.invalidBody);return}if(ge.tools!==void 0&&(!Array.isArray(ge.tools)||ge.tools.some(Te=>typeof Te!="string"))){pe(N,400,"invalid_body",ae.invalidBody);return}let qe;if(ge.labels!==void 0){let Te=vs.safeParse(ge.labels);if(!Te.success){pe(N,400,"invalid_body",ae.invalidBody);return}qe=Te.data}let Me;if(ge.budget!==void 0){if(typeof ge.budget!="object"||ge.budget===null||Array.isArray(ge.budget)){pe(N,400,"invalid_body",ae.invalidBody);return}let Te=ge.budget,Be=Qe=>typeof Qe=="number"&&Number.isFinite(Qe)&&Qe>0;if(Te.maxUsd!==void 0&&!Be(Te.maxUsd)||Te.maxTokens!==void 0&&(!Be(Te.maxTokens)||!Number.isInteger(Te.maxTokens))){pe(N,400,"invalid_body",ae.invalidBody);return}Me={...Te.maxUsd!==void 0?{maxUsd:Te.maxUsd}:{},...Te.maxTokens!==void 0?{maxTokens:Te.maxTokens}:{}}}let oe={...typeof ge.prompt=="string"&&ge.prompt!==""?{prompt:ge.prompt}:{},...typeof ge.model=="string"&&ge.model!==""?{model:ge.model}:{},...typeof ge.profile=="string"&&ge.profile!==""?{profile:ge.profile}:{},...ge.tools!==void 0?{tools:ge.tools}:{},...qe!==void 0?{labels:qe}:{},...Me!==void 0?{budget:Me}:{}},de=x?{admitted:!1,reason:"draining",retryAfterMs:J.retryAfterMs}:J.tryAdmitSession();if(!de.admitted){ni(N,de);return}$+=1;let Re;try{let Te=await t.createSession.create(oe);Re=W.adopt(Te)}catch(Te){pe(N,400,"create_failed",ae.createFailed,{message:Te instanceof Error?Te.message:String(Te)});return}finally{$-=1}Je(N,201,{sessionId:Re})},Ge=async(L,N,se)=>{if(W.get(se)===void 0){pe(N,404,"session_not_found",ae.sessionNotFound,{sessionId:se});return}let qe=await Fe(L,N);if(qe==="rejected")return;if(!qe.ok){lt(L,N,qe.reason);return}let Me=typeof qe.value=="object"&&qe.value!==null?qe.value:{};if(typeof Me.prompt!="string"||Me.prompt.trim()===""){pe(N,400,"prompt_required",ae.promptRequired);return}if(!W.send(se,Me.prompt)){pe(N,409,"session_ended",ae.sessionEnded,{sessionId:se});return}Je(N,202,{sessionId:se,accepted:!0})},rt=(L,N)=>{if(!W.interrupt(N)){pe(L,404,"session_not_found",ae.sessionNotFound,{sessionId:N});return}Je(L,202,{sessionId:N,accepted:!0})},Tt=(L,N,se)=>{let ge=J.tryAdmitSse();if(!ge.admitted){ni(N,ge);return}if(N.once("close",()=>{J.releaseSse()}),S>0&&L.socket.setKeepAlive(!0,S),L.socket.setTimeout(0),W.get(se)===void 0){pe(N,404,"session_not_found",ae.sessionNotFound,{sessionId:se});return}let qe=oa(L.headers["last-event-id"]);if(qe===void 0){pe(N,400,"invalid_last_event_id",ae.invalidLastEventId);return}N.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no"});let Me=h.attach(N,{gapFrame:de=>Pr(se,de)});A.add(Me);let oe=W.subscribe(se,qe,Me);N.on("close",()=>{A.delete(Me),oe?.()})},zt=()=>W.activeCount()+(D?.activeCount()??0),gn=L=>{Je(L,200,{version:v,protocolVersion:fp,activeSessions:zt(),uptimeMs:Date.now()-w})},wn=async(L,N,se,ge,qe="v1")=>{let Me=await Fe(L,N);if(Me==="rejected")return;if(!Me.ok){qe==="api"&&Me.reason==="too_large"?Tr(L,N,"payload_too_large",ae.bodyTooLarge,{maxBytes:p}):lt(L,N,Me.reason);return}let oe=qe==="api"?"validation_failed":"invalid_body";if(typeof Me.value!="object"||Me.value===null||Array.isArray(Me.value)){pe(N,400,oe,ae.approvalInvalidBody);return}let de=Me.value;if(typeof de.digest!="string"||de.digest===""||de.verdict!=="approve"&&de.verdict!=="deny"||typeof de.approver!="string"||de.approver.trim()===""){pe(N,400,oe,ae.approvalInvalidBody);return}let Re=se.submit({challengeId:ge,digest:de.digest,verdict:de.verdict,approver:de.approver});if(Re.code==="accepted"){Je(N,200,{challengeId:ge,result:"accepted"});return}if(qe==="api"){pe(N,xb[Re.code]??409,OI[Re.code]??`approval_${Re.code}`,ae.approvalRejected,{code:Re.code,challengeId:ge},void 0,{submitCode:Re.code,challengeId:ge});return}pe(N,xb[Re.code]??409,`approval_${Re.code}`,ae.approvalRejected,{code:Re.code,challengeId:ge})},Nt=(L,N,se,ge)=>{let qe=t.approvals;if(qe===void 0||m===void 0)return!1;let Me=kb.exec(se);if(Me===null)return!1;let oe=(async()=>{let de;try{de=await m.authenticate(L,N)}catch(Te){if(N.destroyed||N.writableEnded)return;if(Te instanceof Rt){pe(N,503,Te.code,Te.code==="overloaded"?ae.overloaded:ae.internalError,{},Ft(J.retryAfterMs));return}de=null}if(L.aborted||N.destroyed||N.writableEnded)return;if(de===null||typeof de.endUserId!="string"||de.endUserId===""){pe(N,401,"unauthorized",ae.unauthorized,void 0,{"www-authenticate":"Bearer"});return}if(ge!=="POST"){pe(N,405,"method_not_allowed",ae.methodNotAllowed,{method:ge,path:se},{allow:"POST"});return}let Re=fi(Me[1]);if(Re===null){pe(N,404,"not_found",ae.notFound,{path:se});return}await wn(L,N,qe,Re,"api")})();return M(oe),oe.catch(de=>$e(N,se,ge,de)),!0},yn=(L,N,se,ge)=>{if(me!==void 0&&se.startsWith("/api/sessions/")&&me.observeApi(se),ie!==void 0&&ie(L,N,se,ge))return;if(l&&(se==="/v1"||se.startsWith("/v1/"))){pe(N,404,"not_found",ae.notFound,{path:se});return}if(i?.offload?.only&&(se==="/v2"||se.startsWith("/v2/"))){pe(N,404,"not_found",ae.notFound);return}if(me!==void 0&&Yv(se)&&me.handleLegacy(L,N,se,ge)||U(L,N,se,ge))return;if(!ra(L.headers.authorization,s)){pe(N,401,"unauthorized",ae.unauthorized,void 0,{"www-authenticate":"Bearer"});return}let qe=de=>{M(de),de.catch(Re=>$e(N,se,ge,Re))};if(se==="/v1/sessions"){if(ge!=="POST"){pe(N,405,"method_not_allowed",ae.methodNotAllowed,{method:ge,path:se},{allow:"POST"});return}qe(kt(L,N));return}if(se==="/v1/status"){if(ge!=="GET"){pe(N,405,"method_not_allowed",ae.methodNotAllowed,{method:ge,path:se},{allow:"GET"});return}gn(N);return}let Me=MI.exec(se);if(Me!==null){let de=fi(Me[1]);if(de===null){pe(N,404,"not_found",ae.notFound,{path:se});return}let Re=Me[2];if(Re==="events"){if(ge!=="GET"){pe(N,405,"method_not_allowed",ae.methodNotAllowed,{method:ge,path:se},{allow:"GET"});return}Tt(L,N,de);return}if(ge!=="POST"){pe(N,405,"method_not_allowed",ae.methodNotAllowed,{method:ge,path:se},{allow:"POST"});return}Re==="messages"?qe(Ge(L,N,de)):rt(N,de);return}let oe=kb.exec(se);if(oe!==null&&t.approvals!==void 0){if(ge!=="POST"){pe(N,405,"method_not_allowed",ae.methodNotAllowed,{method:ge,path:se},{allow:"POST"});return}let de=fi(oe[1]);if(de===null){pe(N,404,"not_found",ae.notFound,{path:se});return}qe(wn(L,N,t.approvals,de));return}pe(N,404,"not_found",ae.notFound,{path:se})},_=(L,N)=>{let se=L.method??"GET",ge=(L.url??"/").split("?",1)[0];try{te.trackRequest(L,N)}catch{}try{if(te.handleEndpoint(L,N,ge,se))return;yn(L,N,ge,se)}catch(qe){$e(N,ge,se,qe)}},y=t.http??{},P=ph.createServer({requestTimeout:y.requestTimeout??TI,...y.headersTimeout!==void 0?{headersTimeout:y.headersTimeout}:{},...y.keepAliveTimeout!==void 0?{keepAliveTimeout:y.keepAliveTimeout}:{},...y.connectionsCheckingInterval!==void 0?{connectionsCheckingInterval:y.connectionsCheckingInterval}:{}},_);y.maxConnections!==void 0&&(P.maxConnections=y.maxConnections),y.maxRequestsPerSocket!==void 0&&(P.maxRequestsPerSocket=y.maxRequestsPerSocket),y.socketTimeoutMs!==void 0&&P.setTimeout(y.socketTimeoutMs);try{await new Promise((L,N)=>{let se=ge=>N(ge);P.once("error",se),P.listen(t.port,a,()=>{P.removeListener("error",se),L()})})}catch(L){throw re?.close(),m?.close(),D?.beginClosing(),await Promise.allSettled([D?.closeAll({timeoutMs:t.closeAllTimeoutMs??wb}),C?.close(),Promise.resolve(J.close()),Promise.resolve(te.close())]),L}let K=P.address(),ee=typeof K=="object"&&K!==null?K.port:t.port,G=a==="0.0.0.0"||a==="::"?"127.0.0.1":a,Y=`http://${G.includes(":")?`[${G}]`:G}:${ee}`;R("info",Xe.serverListening,{url:Y,host:a,port:ee},We(ae.listening,{url:Y})),Ma(t.readyFrame,{url:Y,pid:process.pid,readyz:En.readyz});let ve=L=>new Promise(N=>setTimeout(N,L)),fe=()=>new Promise(L=>P.getConnections((N,se)=>L(se??0))),xe=async L=>{x=!0,m?.close(),re?.close(),D?.beginClosing();let N=[],se=async oe=>{try{await oe()}catch(de){N.push(de)}},ge=t.closeAllTimeoutMs??wb,qe=async(oe,de)=>{await se(async()=>{let Re=await de();Re?.timedOut===!0&&R("warn",Xe.serverCloseTimeout,{face:oe,pending:Re.pending,timeoutMs:ge})})};await qe("v1",()=>W.closeAll({timeoutMs:ge})),await qe("v2",()=>D?.closeAll({timeoutMs:ge})),await se(()=>C?.close()),await se(()=>J.close());let Me=new Promise((oe,de)=>{P.close(Re=>Re!==void 0?de(Re):oe())});if(Me.catch(()=>{}),L){let oe=Date.now()+PI;for(P.closeIdleConnections();await fe()>0&&Date.now()<oe;)await ve(zf),P.closeIdleConnections()}if(P.closeAllConnections(),await se(()=>Me),await se(()=>te.close()),R("info",Xe.serverClosed,{host:a,port:ee},We(ae.closed)),N.length>0)throw new AggregateError(N,"Server shutdown failed.")},be=!1,Pe,_e=async(L={})=>{let N=L.timeoutMs??CI,se=Date.now();x=!0,J.beginDrain(),D?.beginClosing();let ge=on({retryMs:k,data:""}),qe=0;for(let ce of A)ce.stats().closed||(ce.write(ge),qe+=1);qe+=D?.broadcastRetry(k)??0;let Me=D?.runningCount()??0;b?.info(We(ae.drainStarted,{running:Me,subscribers:qe,timeoutMs:N}));let oe=se+N;for(;(D?.runningCount()??0)>0&&Date.now()<oe;)await ve(zf);let de=0;if(D!==void 0&&D.runningCount()>0){de=D.interruptRunning();let ce=Date.now()+_I;for(;D.runningCount()>0&&Date.now()<ce;)await ve(zf)}let Re=Math.max(0,Me-de),Te=0,Be=[];try{Te+=await t.v2?.createSession.flush?.()??0}catch(ce){Be.push(ce)}try{Te+=await t.createSession.flush?.()??0}catch(ce){Be.push(ce)}try{await xe(!0)}catch(ce){Be.push(ce)}if(be=!0,Be.length>0)throw new AggregateError(Be,"Server drain failed.");let Qe={completedTurns:Re,abortedTurns:de,flushedCommits:Te,durationMs:Date.now()-se};return b?.info(We(ae.drained,{...Qe})),Qe};return{port:ee,host:a,url:Y,activeSessionCount:()=>zt(),stats:()=>te.stats(),setSseRetryMs:L=>h.setRetryMs(L),sseStats:()=>h.stats(),readiness:()=>J.readiness(),settleResources:async()=>{for(;T.size>0;)await Promise.allSettled([...T]);let N=(await Promise.allSettled([W.settleResources(),D?.settleResources()])).flatMap(se=>se.status==="rejected"?[se.reason]:[]);if(N.length>0)throw new AggregateError(N,"Server resource cleanup failed.")},drain:L=>(Pe===void 0&&(Pe=be?Promise.resolve({completedTurns:0,abortedTurns:0,flushedCommits:0,durationMs:0}):_e(L)),Pe),close:async()=>{if(Pe!==void 0){await Pe;return}be||(be=!0,await xe(!1))}}}var us=[{name:"TANSR_SERVE_MAX_ACTIVE_SESSIONS",group:"admission",target:"admission.maxActiveSessions",kind:"int",min:1},{name:"TANSR_SERVE_MAX_SSE_CONNECTIONS",group:"admission",target:"admission.maxSseConnections",kind:"int",min:1},{name:"TANSR_SERVE_MAX_INFLIGHT_BODY_BYTES",group:"admission",target:"admission.maxInflightBodyBytes",kind:"int",min:1,unit:"bytes"},{name:"TANSR_SERVE_ELD_THRESHOLD_MS",group:"admission",target:"admission.eventLoopDelayP99Ms",kind:"int",min:1,unit:"ms"},{name:"TANSR_SERVE_REQUEST_TIMEOUT_MS",group:"http",target:"http.requestTimeout",kind:"int",min:0,unit:"ms"},{name:"TANSR_SERVE_EXPOSE_OBSERVABILITY",group:"observability",target:"observability.expose",kind:"bool"},{name:"TANSR_SERVE_EXPOSE_METRICS",group:"observability",target:"observability.exposeMetrics",kind:"bool"},{name:"TANSR_SERVE_EVENT_BUFFER_MAX_BYTES",group:"ring",target:"eventBufferMaxBytes",kind:"int",min:1,unit:"bytes"},{name:"TANSR_SERVE_ORPHAN_GRACE_MS",group:"governance",target:"v2.governance.orphanGraceMs",kind:"int",min:0,unit:"ms"},{name:"TANSR_SERVE_IDLE_AFTER_GONE_MS",group:"governance",target:"v2.governance.idleAfterGoneMs",kind:"int",min:0,unit:"ms"},{name:"TANSR_SERVE_MAX_RETAINED_SESSIONS",group:"governance",target:"v2.governance.maxRetainedSessions",kind:"int",min:0},{name:"TANSR_SERVE_MAX_SESSION_LIFETIME_MS",group:"governance",target:"v2.governance.maxSessionLifetimeMs",kind:"int",min:1,unit:"ms"},{name:"TANSR_SERVE_MAX_TURNS_PER_SESSION",group:"governance",target:"v2.governance.maxTurnsPerSession",kind:"int",min:1},{name:"TANSR_SERVE_SESSION_SHARD",group:"v2",target:"v2.sessionIdShard",kind:"int",min:0,max:Wr},{name:"TANSR_SERVE_AUTH_MAX_PENDING",group:"v2",target:"v2.authentication.maxPending",kind:"int",min:1},{name:"TANSR_SERVE_AUTH_TIMEOUT_MS",group:"v2",target:"v2.authentication.timeoutMs",kind:"int",min:1,max:2147483647,unit:"ms"},{name:"TANSR_SERVE_LEGACY_V1",group:"legacy",target:"disableV1",kind:"bool"},{name:"TANSR_SERVE_LEGACY_PREFIX",group:"legacy",target:"legacyPrefixes",kind:"enum",values:Mf},{name:"TANSR_SERVE_LEGACY_SUNSET",group:"legacy",target:"legacyPrefixSunset",kind:"string",format:"http-date"},{name:"TANSR_SERVE_NOTIFY_URL",group:"notify",target:"v2.onTurnEndNotify.url",kind:"string",format:"http-url"},{name:"TANSR_SERVE_NOTIFY_SECRET",group:"notify",target:"v2.onTurnEndNotify.secret",kind:"secret",requires:"TANSR_SERVE_NOTIFY_URL"},{name:"TANSR_SERVE_UPSTREAM_MAX_INFLIGHT",group:"upstream",target:"governor.bulkhead.maxConcurrent",kind:"int",min:1},{name:"TANSR_SERVE_UPSTREAM_CONNECT_TIMEOUT_MS",group:"session",target:"session.timeouts.connectTimeoutMs",kind:"int",min:1,unit:"ms"},{name:"TANSR_SERVE_UPSTREAM_IDLE_TIMEOUT_MS",group:"session",target:"session.timeouts.idleTimeoutMs",kind:"int",min:1,unit:"ms"},{name:"TANSR_SERVE_UPSTREAM_TOTAL_TIMEOUT_MS",group:"session",target:"session.timeouts.totalTimeoutMs",kind:"int",min:1,unit:"ms"},{name:"TANSR_SERVE_TURN_WALL_CLOCK_MS",group:"session",target:"session.maxTurnWallClockMs",kind:"int",min:1,unit:"ms"},{name:"TANSR_SERVE_HOST_SHELL",group:"session",target:"session.hostShell",kind:"enum",values:["posix","powershell"]},{name:"TANSR_SERVE_SSE_MAX_FRAME_BYTES",group:"sse",target:"sse.maxFrameBytes",kind:"int",min:1,unit:"bytes"},{name:"TANSR_SERVE_SSE_MAX_BUFFER_BYTES",group:"sse",target:"sse.maxBufferBytes",kind:"int",min:1,unit:"bytes"},{name:"TANSR_SERVE_SSE_SLOW_POLICY",group:"sse",target:"sse.onSlowSubscriber",kind:"enum",values:["disconnect","drop-oldest"]},{name:"TANSR_SERVE_SSE_RETRY_MS",group:"sse",target:"sse.retryMs",kind:"int",min:0,unit:"ms"},{name:"TANSR_SERVE_LOG_FORMAT",group:"log",target:"logger.log",kind:"enum",values:["json","text"]},{name:"TANSR_SERVE_LOG_LEVEL",group:"log",target:"logger.level",kind:"enum",values:["debug","info","warn","error"]},{name:"TANSR_SERVE_ON_UNHANDLED",group:"process",target:"processGuards.onFatal",kind:"enum",values:[...Qs]},{name:"TANSR_SERVE_READY_STREAM",group:"process",target:"readyFrame",kind:"enum",values:[...Sg]},{name:"TANSR_SERVE_CWD_ON_RESUME",group:"factory",target:"factory.cwdOnResume",kind:"enum",values:["current","stored"]},{name:"TANSR_SERVE_SESSION_MAX_AGE_DAYS",group:"factory",target:"factory.sessions.retention.maxAgeDays",kind:"int",min:1,unit:"days"},{name:"TANSR_SERVE_SESSION_MAX_PER_END_USER",group:"factory",target:"factory.sessions.retention.maxPerEndUser",kind:"int",min:1}],Ab=us.map(t=>t.name),Gf="(set)",BI=64,DI=new Set(["1","true","yes","on"]),qI=new Set(["0","false","no","off"]);function jI(t){let e=t?.trim();return e===void 0||e===""?void 0:e}function NI(t,e){switch(t.kind){case"int":{let n=t.min??0,i=t.max,o=i===void 0?`integer >= ${n}`:`integer in [${n}, ${i}]`;if(!/^\d+$/.test(e))return{ok:!1,expected:o};let s=Number.parseInt(e,10);return!Number.isSafeInteger(s)||s<n?{ok:!1,expected:o}:i!==void 0&&s>i?{ok:!1,expected:o}:{ok:!0,value:s}}case"bool":{let n=e.toLowerCase();return DI.has(n)?{ok:!0,value:!0}:qI.has(n)?{ok:!0,value:!1}:{ok:!1,expected:"1|true|0|false"}}case"enum":{let n=t.values??[],i=n.find(o=>o===e.toLowerCase());return i===void 0?{ok:!1,expected:n.join("|")}:{ok:!0,value:i}}case"string":{if(t.format==="http-url"){let n;try{n=new URL(e)}catch{return{ok:!1,expected:Ib}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{ok:!1,expected:Ib}}return t.format==="http-date"&&!Number.isFinite(Date.parse(e))?{ok:!1,expected:UI}:{ok:!0,value:e}}case"secret":return{ok:!0,value:e}}}var Ib="absolute http(s) URL",UI="HTTP date (IMF-fixdate) or ISO-8601 timestamp";function Tb(t,e){return t.kind==="secret"?Gf:(t.kind==="string"&&t.format==="http-url"?e.replace(/\/\/[^/@?#]*@/u,"//…@").replace(/\?.*$/su,"?…"):e).slice(0,BI)}function LI(t,e,n){switch(e.name){case"TANSR_SERVE_MAX_ACTIVE_SESSIONS":t.admission.maxActiveSessions=n;return;case"TANSR_SERVE_MAX_SSE_CONNECTIONS":t.admission.maxSseConnections=n;return;case"TANSR_SERVE_MAX_INFLIGHT_BODY_BYTES":t.admission.maxInflightBodyBytes=n;return;case"TANSR_SERVE_ELD_THRESHOLD_MS":t.admission.eventLoopDelayP99Ms=n;return;case"TANSR_SERVE_REQUEST_TIMEOUT_MS":t.http.requestTimeout=n;return;case"TANSR_SERVE_EXPOSE_OBSERVABILITY":t.observability.expose=n;return;case"TANSR_SERVE_EXPOSE_METRICS":t.observability.exposeMetrics=n;return;case"TANSR_SERVE_READY_STREAM":t.readyFrame=n;return;case"TANSR_SERVE_EVENT_BUFFER_MAX_BYTES":t.eventBufferMaxBytes=n;return;case"TANSR_SERVE_LEGACY_V1":t.disableV1=!n;return;case"TANSR_SERVE_LEGACY_PREFIX":t.legacyPrefixes=n;return;case"TANSR_SERVE_LEGACY_SUNSET":t.legacyPrefixSunset=n;return;case"TANSR_SERVE_ORPHAN_GRACE_MS":t.governance.orphanGraceMs=n;return;case"TANSR_SERVE_IDLE_AFTER_GONE_MS":t.governance.idleAfterGoneMs=n;return;case"TANSR_SERVE_MAX_RETAINED_SESSIONS":t.governance.maxRetainedSessions=n;return;case"TANSR_SERVE_MAX_SESSION_LIFETIME_MS":t.governance.maxSessionLifetimeMs=n;return;case"TANSR_SERVE_MAX_TURNS_PER_SESSION":t.governance.maxTurnsPerSession=n;return;case"TANSR_SERVE_SESSION_SHARD":t.sessionIdShard=n;return;case"TANSR_SERVE_NOTIFY_URL":t.notifyUrl=n;return;case"TANSR_SERVE_NOTIFY_SECRET":t.notifySecret=n;return;case"TANSR_SERVE_UPSTREAM_MAX_INFLIGHT":t.bulkhead.maxConcurrent=n;return;case"TANSR_SERVE_UPSTREAM_CONNECT_TIMEOUT_MS":t.timeouts.connectTimeoutMs=n;return;case"TANSR_SERVE_UPSTREAM_IDLE_TIMEOUT_MS":t.timeouts.idleTimeoutMs=n;return;case"TANSR_SERVE_UPSTREAM_TOTAL_TIMEOUT_MS":t.timeouts.totalTimeoutMs=n;return;case"TANSR_SERVE_TURN_WALL_CLOCK_MS":t.maxTurnWallClockMs=n;return;case"TANSR_SERVE_HOST_SHELL":t.hostShell=n;return;case"TANSR_SERVE_AUTH_MAX_PENDING":t.authentication.maxPending=n;return;case"TANSR_SERVE_AUTH_TIMEOUT_MS":t.authentication.timeoutMs=n;return;case"TANSR_SERVE_SSE_MAX_FRAME_BYTES":t.sse.maxFrameBytes=n;return;case"TANSR_SERVE_SSE_MAX_BUFFER_BYTES":t.sse.maxBufferBytes=n;return;case"TANSR_SERVE_SSE_SLOW_POLICY":t.sse.onSlowSubscriber=n;return;case"TANSR_SERVE_SSE_RETRY_MS":t.sse.retryMs=n;return;case"TANSR_SERVE_LOG_FORMAT":t.logFormat=n;return;case"TANSR_SERVE_LOG_LEVEL":t.logLevel=n;return;case"TANSR_SERVE_ON_UNHANDLED":t.onUnhandled=n;return;case"TANSR_SERVE_CWD_ON_RESUME":t.factory.cwdOnResume=n;return;case"TANSR_SERVE_SESSION_MAX_AGE_DAYS":t.factory.sessions={retention:{...t.factory.sessions?.retention??{},maxAgeDays:n}};return;case"TANSR_SERVE_SESSION_MAX_PER_END_USER":t.factory.sessions={retention:{...t.factory.sessions?.retention??{},maxPerEndUser:n}};return;default:throw new Error(`runtime-options: unmapped env ${e.name}`)}}function ji(t){return Object.keys(t).length>0}function Eb(t){let e={admission:{},http:{},observability:{},sse:{},eventBufferMaxBytes:void 0,disableV1:void 0,legacyPrefixes:void 0,legacyPrefixSunset:void 0,governance:{},authentication:{},sessionIdShard:void 0,bulkhead:{},timeouts:{},maxTurnWallClockMs:void 0,hostShell:void 0,logFormat:void 0,logLevel:void 0,onUnhandled:void 0,readyFrame:void 0,factory:{},notifyUrl:void 0,notifySecret:void 0},n=[],i=[];for(let d of us){let c=jI(t[d.name]);if(c===void 0)continue;let l=NI(d,c);if(!l.ok){i.push({name:d.name,value:Tb(d,c),expected:l.expected});continue}if(d.requires!==void 0&&!n.includes(d.requires)){i.push({name:d.name,value:Tb(d,c),expected:`${d.requires} to be set and valid (ignored without it)`});continue}LI(e,d,l.value),n.push(d.name)}let o={...ji(e.admission)?{admission:e.admission}:{},...ji(e.http)?{http:e.http}:{},...ji(e.sse)?{sse:e.sse}:{},...ji(e.observability)?{observability:e.observability}:{},...e.eventBufferMaxBytes!==void 0?{eventBufferMaxBytes:e.eventBufferMaxBytes}:{},...e.readyFrame!==void 0?{readyFrame:e.readyFrame}:{},...e.disableV1!==void 0?{disableV1:e.disableV1}:{},...e.legacyPrefixes!==void 0?{legacyPrefixes:e.legacyPrefixes}:{},...e.legacyPrefixSunset!==void 0?{legacyPrefixSunset:e.legacyPrefixSunset}:{}},s={...ji(e.timeouts)?{timeouts:e.timeouts}:{},...e.maxTurnWallClockMs!==void 0?{maxTurnWallClockMs:e.maxTurnWallClockMs}:{},...e.hostShell!==void 0?{hostShell:e.hostShell}:{}},a={...ji(e.authentication)?{authentication:e.authentication}:{},...ji(e.governance)?{governance:e.governance}:{},...e.sessionIdShard!==void 0?{sessionIdShard:e.sessionIdShard}:{},...e.notifyUrl!==void 0?{onTurnEndNotify:{url:e.notifyUrl,...e.notifySecret!==void 0?{secret:e.notifySecret}:{}}}:{}};return{server:o,v2:a,upstreamGovernor:ji(e.bulkhead)?{bulkhead:e.bulkhead}:void 0,session:s,factory:e.factory,logFormat:e.logFormat??"text",logLevel:e.logLevel??"warn",onUnhandled:e.onUnhandled,applied:n,warnings:i}}function Cb(t,...e){let n=new Set(e),i=new Set(us.filter(o=>n.has(o.group)).map(o=>o.name));return t.applied.filter(o=>i.has(o))}import{randomUUID as $d}from"node:crypto";import{rm as XI}from"node:fs/promises";import ZI from"node:path";import{randomUUID as Wf}from"node:crypto";var fs=class{#e=new Map;#n;constructor(e){this.#n=e}set(e,n){if(this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,n),this.#e.size>this.#n){let i=this.#e.keys().next().value;i!==void 0&&this.#e.delete(i)}}get(e){return this.#e.get(e)}};function _b(t){return t.reason??new DOMException("The request was aborted","AbortError")}var eo=class{#e;#n;#r;#s;#t;#o=new Map;#i=new Map;#a=new Map;#c=new fs(je.receiptTombstones);#d=new fs(je.receiptTombstones);#f=new fs(je.receiptTombstones);#m=null;#p=0;constructor(e){this.#e=e.cwd,this.#n=e.permissionTimeoutMs??je.permissionTimeoutMs,this.#r=e.questionGraceMs??je.questionGraceMs,this.#s=e.now??Date.now,this.#t=e.onPermissionReceipt}bindEmitter(e){this.#m=e}setCwd(e){this.#e=e}noteSubscribers(e){if(this.#p=e,e>0){for(let n of this.#a.values())n.graceTimer!==void 0&&(clearTimeout(n.graceTimer),delete n.graceTimer);return}for(let[n,i]of this.#a)i.graceTimer===void 0&&this.#v(n,i)}#w(e,n){this.#m?.(e,n)}emitPlatformWarning(e){this.#w(sn.platformWarning,e)}registerToolCall(e,n,i,o,s,a=Math.max(0,o-this.#s()),d){return this.#o.has(e)||this.#c.get(e)!==void 0?Promise.reject(new Error(`duplicate remote tool call ${e}`)):new Promise((c,l)=>{let f=setTimeout(()=>{g(new Error(`remote tool call ${e} timed out`))},Math.max(0,o-this.#s()));f.unref();let u=()=>{g(_b(s))},m=()=>{clearTimeout(f),s.removeEventListener("abort",u),this.#o.delete(e)},g=h=>{this.#o.has(e)&&(m(),this.#c.set(e,"expired"),this.#w(sn.toolCancel,{callId:e}),l(h))};if(this.#o.set(e,{resolve:h=>{m(),this.#c.set(e,"resolved"),c(h)},cleanup:m}),s.aborted){u();return}if(s.addEventListener("abort",u,{once:!0}),d!==void 0)try{Promise.resolve(d()).catch(g)}catch(h){g(h)}else this.#w(sn.toolRequest,{callId:e,name:n,args:i,deadlineAt:o,ttlMs:a})})}submitToolResult(e,n){let i=this.#o.get(e);if(i!==void 0)return i.resolve(n.status==="ok"?{content:n.content,...n.isError===!0?{isError:!0}:{}}:{content:[{t:"text",text:n.message}],isError:!0}),"accepted";let o=this.#c.get(e);return o==="resolved"?"already_resolved":o==="expired"?"expired":"not_found"}createAskUser(){return(e,n,i)=>new Promise(o=>{let s=Wf(),a=Qp({toolName:e.name,args:e.args,cwd:this.#e}),d=this.#s()+this.#n,c=setTimeout(()=>u("expired","deny"),this.#n);c.unref();let l=()=>u("expired","deny"),f=()=>{clearTimeout(c),n?.removeEventListener("abort",l),this.#i.delete(s)},u=(b,R)=>{this.#i.has(s)&&(f(),this.#d.set(s,b),this.#w(sn.permissionClosed,{requestId:s}),o(R))};if(this.#i.set(s,{digest:a,resolve:(b,R)=>{u("resolved",b);try{this.#t?.({requestId:s,verdict:b,...R!==void 0?{reason:R}:{}})}catch{}},cleanup:f}),n?.aborted===!0){l();return}n?.addEventListener("abort",l,{once:!0});let m=Lp(e.args),g=i?.executionTarget,h=g?.kind==="device"?We(tn.executionPermissionTarget,{executor:g.executorId,workspace:g.workspaceId??"",revision:g.bindingRevision}):void 0,p=h===void 0?m:[h,m].filter(Boolean).join(`
|
|
33
|
+
`),v=i??{decision:"ask",source:"mode"};this.#w(sn.permissionRequest,up({requestId:s,name:e.name,...p!==void 0?{summary:p}:{},attribution:{decision:v.decision,source:v.source,...v.matchedRule!==void 0?{matchedRule:v.matchedRule}:{},...v.reason!==void 0?{reason:v.reason}:{}},digest:a,expiresAt:d,ttlMs:this.#n}))})}submitPermission(e,n){let i=this.#i.get(e);if(i!==void 0)return n.digest!==i.digest?"digest_mismatch":(i.resolve(n.verdict,n.verdict==="deny"?n.reason:void 0),"accepted");let o=this.#d.get(e);return o==="resolved"?"already_resolved":o==="expired"?"expired":"not_found"}#v(e,n){n.graceTimer=setTimeout(()=>{this.#a.has(e)&&(n.cleanup(),this.#f.set(e,"expired"),this.#w(sn.questionClosed,{requestId:e}),n.reject(new hm))},this.#r),n.graceTimer.unref()}createPromptChannel(){return{ask:(e,n)=>new Promise((i,o)=>{let s=Wf(),a=()=>{this.#a.has(s)&&(d.cleanup(),this.#f.set(s,"expired"),this.#w(sn.questionClosed,{requestId:s}),o(_b(n)))},d={questions:e,resolve:l=>{d.cleanup(),this.#f.set(s,"resolved"),this.#w(sn.questionClosed,{requestId:s}),i(l)},reject:o,cleanup:()=>{d.graceTimer!==void 0&&clearTimeout(d.graceTimer),n.removeEventListener("abort",a),this.#a.delete(s)}};if(this.#a.set(s,d),n.aborted){a();return}n.addEventListener("abort",a,{once:!0});let c=this.#p===0;c&&this.#v(s,d),this.#w(sn.questionRequest,{requestId:s,questions:e.map(l=>({id:l.id,prompt:l.prompt,options:l.options.map(f=>({id:f.id,label:f.label})),...l.allowMultiple!==void 0?{allowMultiple:l.allowMultiple}:{}})),...c?{expiresAt:this.#s()+this.#r,ttlMs:this.#r}:{}})})}}submitQuestionAnswers(e,n){let i=this.#a.get(e);if(i!==void 0){let s=FI(i.questions,n);return s===null?"invalid":(i.resolve(s),"accepted")}let o=this.#f.get(e);return o==="resolved"?"already_resolved":o==="expired"?"expired":"not_found"}};function FI(t,e){let n=new Map(t.map(s=>[s.id,s]));if(e.answers.length!==t.length)return null;let i=new Set,o=[];for(let s of e.answers){let a=n.get(s.questionId);if(a===void 0||i.has(s.questionId))return null;i.add(s.questionId);let d=new Set(a.options.map(c=>c.id));for(let c of s.selectedOptionIds)if(!d.has(c))return null;if(a.allowMultiple!==!0&&s.selectedOptionIds.length>1)return null;o.push({questionId:s.questionId,selectedOptionIds:[...s.selectedOptionIds],...s.freeText!==void 0?{freeText:s.freeText}:{}})}return o}function Pb(t){let e;switch(t.type){case"string":e=r.string();break;case"number":e=r.number();break;case"boolean":e=r.boolean();break;case"array":e=r.array(t.items!==void 0?Pb(t.items):r.unknown());break;case"object":e=t.properties!==void 0?Mb(t.properties):r.record(r.unknown());break}return t.description!==void 0&&(e=e.describe(t.description)),e}function Mb(t){let e={};for(let[n,i]of Object.entries(t)){let o=Pb(i);e[n]=i.optional===!0?o.optional():o}return r.object(e)}function Vf(t){let e={type:t.type};if(t.description!==void 0&&(e.description=t.description),t.type==="array"&&t.items!==void 0&&(e.items=Vf(t.items)),t.type==="object"&&t.properties!==void 0){e.properties=Object.fromEntries(Object.entries(t.properties).map(([i,o])=>[i,Vf(o)]));let n=Object.entries(t.properties).filter(([,i])=>i.optional!==!0).map(([i])=>i);n.length>0&&(e.required=n)}return e}function Gd(t,e,n=Date.now,i){let o=Math.min(Math.max(t.timeoutMs??je.toolTimeoutDefaultMs,je.toolTimeoutMinMs),je.toolTimeoutCapMs),s=t.parameters!==void 0?Mb(t.parameters):r.object({}),a={name:t.name,description:t.description,inputSchema:s,argsValidation:"remote",isReadOnly:t.readOnly??!1,...t.effects!==void 0?{effects:t.effects}:{},isConcurrencySafe:!0,timeoutMs:o,async execute(c,l){let f=s.safeParse(c);if(!f.success){let m=f.error.issues.map(g=>g.path.length>0?`${g.path.join(".")}: ${g.message}`:g.message).join("; ");return{content:[{t:"text",text:`invalid ${t.name} args: ${m}`}],isError:!0}}if(i!==void 0)return i(f.data,l);let u=l.toolCallId??Wf();return e.registerToolCall(u,t.name,f.data,n()+o,l.signal,o)}},d={name:t.name,description:t.description,inputSchema:t.parameters!==void 0?{type:"object",properties:Object.fromEntries(Object.entries(t.parameters).map(([c,l])=>[c,Vf(l)])),...Object.entries(t.parameters).some(([,c])=>c.optional!==!0)?{required:Object.entries(t.parameters).filter(([,c])=>c.optional!==!0).map(([c])=>c)}:{}}:{type:"object",properties:{}}};return{tool:a,def:d}}import HI from"node:path";function Ob(t){return t instanceof vn&&t.code==="INVALID_CHECKPOINT_ID"}function ps(t){if(t.dir===void 0==(t.rootOf===void 0))throw new Error('createServeCheckpointStore requires exactly one of "dir" (standalone root) or "rootOf" (co-located root resolver)');let e=t.rootOf??(i=>HI.join(t.dir,"agent-checkpoints",Wt(i))),n={...t.max!==void 0?{max:t.max}:{},...t.retention!==void 0?{retention:t.retention}:{}};return{put(i,o,s){return Nc(e(i,o.sessionId),o,{...n,...s?.attachmentsFrom!==void 0?{attachmentsFrom:s.attachmentsFrom}:{}})},async get(i,o,s){try{return await Uc(e(i,o),o,s)}catch(a){if(Ob(a))return null;throw a}},list(i,o){return Lc(e(i,o),o)},async delete(i,o,s){try{return await Fc(e(i,o),o,s)}catch(a){if(Ob(a))return!1;throw a}}}}function yr(t){return{checkpointId:t.checkpointId,sessionId:t.sessionId,createdAt:t.createdAt,trigger:t.trigger,...t.label!==void 0?{label:t.label}:{},cwd:t.cwd,...t.model!==void 0?{model:t.model}:{},...t.tokens!==void 0?{tokens:t.tokens}:{},...t.compactionId!==void 0?{compactionId:t.compactionId}:{},messageCount:t.messageCount}}function Bb(t){return{checkpointId:t.checkpointId,sessionId:t.sessionId,createdAt:new Date((t.now??Date.now)()).toISOString(),trigger:t.trigger,...t.label!==void 0?{label:t.label}:{},cwd:t.cwd,...t.model!==void 0?{model:t.model}:{},messages:[...t.messages]}}var Hn=class extends Error{toolName;constructor(e){super(`client tool name conflicts with an assembled tool: ${e}`),this.name="ClientToolNameConflictError",this.toolName=e}};import{randomUUID as qb}from"node:crypto";import jb,{posix as Nb}from"node:path";var $f="adjudicator_unavailable",Kf="This app's bundle carries no adjudicator profile (older platform or malformed segment), so the session runs without an adjudicator: would-ask tool calls go to permission.askUser or are denied, as before.";function Wd(t,e,n){if(vl("createAgentSessionFactory",e),e?.enabled===!1)return;if(t.assembleAdjudicator===void 0){e!==void 0&&t.onAdjudicationWarning?.({code:$f,message:Kf});return}let i=e?.posture;if(i==="human-in-loop"&&!n)throw new Error("platform serve session factory: adjudication.posture 'human-in-loop' requires the /v2 permission bridge (extras.askUser) so the adjudicator can escalate dangerous calls to the end user; wire the bridge or use 'headless'.");let o=Gp(i,n);return t.assembleAdjudicator({posture:o,postureExplicit:i!==void 0,...e?.callBudget!==void 0?{callBudget:e.callBudget}:{}})}function zI(t){if(!t||typeof t!="object"||t.blocked!==void 0&&typeof t.blocked!="boolean"||t.blockReason!==void 0&&(typeof t.blockReason!="string"||t.blockReason.length>8192)||t.additionalContexts!==void 0&&(!Array.isArray(t.additionalContexts)||t.additionalContexts.length>64||t.additionalContexts.some(e=>typeof e!="string")||t.additionalContexts.join("").length>65536))throw new TypeError("Invalid trusted hook feedback");return structuredClone(t)}function Db(t,e){let n=t.timeoutMs??1e4;if(!Number.isSafeInteger(n)||n<1||n>12e4)throw new RangeError("Invalid trusted hook timeout");let i=new AbortController,o=new Set,s;async function a(l,f){let u=new AbortController,m=AbortSignal.any([f,i.signal,u.signal]);m.throwIfAborted();let g=setTimeout(()=>u.abort(new Error("Trusted hook timed out")),n),h,p=new Promise((R,w)=>{h=()=>w(m.reason),m.addEventListener("abort",h,{once:!0})}),v=Promise.resolve().then(()=>(m.throwIfAborted(),l(m))),b=v.catch(()=>{});o.add(b),b.finally(()=>o.delete(b));try{let R=await Promise.race([v,p]);return m.throwIfAborted(),R}finally{clearTimeout(g),m.removeEventListener("abort",h)}}let d=()=>(e(),{blocked:!0});async function c(l,f){try{return zI(await a(l,f))}catch{return d()}}return{queryHooks(l){let f;try{i.signal.throwIfAborted();let u=t.queryHooks===void 0?{}:t.queryHooks(Object.freeze([...l]));if(!u||typeof u!="object"||Array.isArray(u))throw new TypeError("Invalid trusted query hooks");let m={};for(let h of["userPromptSubmit","postToolUse","stop","preCompact","postCompact"]){let p=u[h];if(p!==void 0){if(typeof p!="function")throw new TypeError("Invalid trusted query hook callback");Object.defineProperty(m,h,{value:p,enumerable:!0})}}let g=u.maxConsecutiveStopBlocks;if(g!==void 0){if(!Number.isSafeInteger(g)||g<1||g>32)throw new TypeError("Invalid trusted query hooks");m.maxConsecutiveStopBlocks=g}f=Object.freeze(m)}catch{return{userPromptSubmit:d,preCompact:d,stop:d}}return{...f.userPromptSubmit===void 0?{}:{userPromptSubmit:u=>c(m=>f.userPromptSubmit({...u,signal:m}),u.signal)},...f.postToolUse===void 0?{}:{postToolUse:u=>c(m=>f.postToolUse({...u,signal:m}),u.signal)},...f.stop===void 0?{}:{stop:u=>c(m=>f.stop({...u,signal:m}),u.signal)},...f.preCompact===void 0?{}:{preCompact:u=>c(m=>f.preCompact({...u,signal:m}),u.signal)},...f.postCompact===void 0?{}:{postCompact:u=>a(m=>f.postCompact({...u,signal:m}),u.signal)},...f.maxConsecutiveStopBlocks===void 0?{}:{maxConsecutiveStopBlocks:f.maxConsecutiveStopBlocks}}},async system(l,f){return GI(await a(l,f))},boundary(l){return t.beforeTool?{resolve(f,u){let m=l.resolve(f,u);if(m)return{...m,executeService:async(g,h,p)=>{let v=structuredClone(g),b=await c(R=>t.beforeTool(v,{signal:R}),h);return h.throwIfAborted(),i.signal.throwIfAborted(),b.blocked?{isError:!0,content:[{t:"text",text:b.blockReason??We("tui.events.kind.hook_blocked")}],data:{error:"trusted_hook_blocked"}}:(await m.assertCurrent(),h.throwIfAborted(),i.signal.throwIfAborted(),m.executeService?m.executeService(g,h,p):p())}}}}:l},stop(){i.abort()},close(){return s||(i.abort(),s=(async()=>{for(;o.size;)await Promise.all([...o]);await t.onClosed?.()})(),s)}}}function GI(t){if(!t||typeof t!="object")throw new TypeError("Invalid trusted system configuration");for(let e of[t.system,t.systemAppend])if(e!==void 0&&(!Array.isArray(e)||e.some(n=>!n||typeof n.text!="string")))throw new TypeError("Invalid trusted system segments");return structuredClone(t)}var WI=1e4,VI=1e3,$I=12e4;function KI(t,e){return Tc(t===void 0?void 0:{...t.maxUsd!==void 0?{maxUsd:t.maxUsd}:{},...t.maxTokens!==void 0?{maxTotalTokens:t.maxTokens}:{}},e)}function QI(t,e){return fl(t,e)?.quirks?.reasoningTokens}var JI;function YI(t,e){let n=t.capabilities;if(n===void 0)return[Ns(e.todoStore),Ls(e.channel)];let i=[];if(n.tools.todoWrite&&i.push(Ns(e.todoStore)),n.tools.askUser&&i.push(Ls(e.channel)),n.tools.webFetch||n.tools.http){let a=JI??=oo({env:process.env});n.tools.webFetch&&i.push(Yc({client:a})),n.tools.http&&i.push(Zc({client:a,env:{},allowedAuthEnvVars:[],allowPrivate:!1}))}let o=t.platformTools;if(o===void 0)return i;let s={baseUrl:o.baseUrl,token:Wi,fetchImpl:o.fetchImpl};return n.tools.webSearch&&n.platform.webSearch&&i.push(Xc({provider:Ha(s)})),n.platform.imageGen&&i.push(Hs({provider:mo({...s,models:o.platformModels.imageGen})})),n.platform.videoGen&&i.push(zs({provider:ho({...s,models:o.platformModels.videoGen})})),n.platform.speechToText&&i.push(Gs({provider:yo({...s,models:o.platformModels.speechToText})})),n.platform.textToSpeech&&i.push(Ws({provider:bo({...s,models:o.platformModels.textToSpeech})})),i}function Vd(t){let e=t.maxOutputTokens;if(e!==void 0&&(!Number.isSafeInteger(e)||e<=0))throw new TypeError("maxOutputTokens must be a positive safe integer");return{create(n,i){if(n.profile!==void 0)throw new Ze("validation_failed",We(tn.platformProfileUnsupported,{profile:n.profile}));let o=i?.assembleModel;if(o===void 0)throw new Error("platform serve session factory requires extras.assembleModel (per-endUser platform token assembly)");let s=null,a=i?.trustedScope;if((t.trustedExtensionsFor||t.systemFor)&&!a)throw new TypeError("Trusted host extensions require an authenticated scope");let d=t.trustedExtensionsFor?.(Object.freeze({...a})),c=d?.decorateModelClient;if(c!==void 0&&typeof c!="function")throw new TypeError("Invalid trusted model client decorator");let l=d===void 0&&t.systemFor===void 0?void 0:Db(d??{},()=>s?.interrupt()),f=n.model??"main",u=o(f,oe=>{let de=uo(oe);de!==null&&s?.pushBody(de,"provider")}),m=e===void 0?u.maxOutputTokens:Math.min(e,u.maxOutputTokens??e),g=e===void 0?t.maxTokens??Fi:Math.min(t.maxTokens??Fi,m),h=e===void 0?u.compaction??{}:{...u.compaction,maxOutputTokens:Math.min(u.compaction?.maxOutputTokens??1/0,m)};if(i?.execution!==void 0){if(u.refreshApplicationCapabilities===void 0)throw new Error("Remote execution requires authoritative application capabilities");i.execution.bindApplicationCapabilities(u.refreshApplicationCapabilities)}let p=t.system?.map(oe=>({...oe})),v=t.systemAppend?.map(oe=>({...oe}))??[],b,R=[],w,x=new WeakMap,T=oe=>{let de=Ho(oe,p),Re=[...de.system,...v.map(Te=>({...Te})),...i?.execution?.systemSegments()??[],...R];return x.set(Re,Object.freeze({...de.info})),Re},M=new Is({onChange:oe=>s?.pushBody({type:"plan.todo.updated",items:oe},"tool")});b=T(u);let W=i?.promptChannel??new Us,$=YI(u,{todoStore:M,channel:W});if(u.capabilities!==void 0&&!u.capabilities.tools.customTools&&i?.sessionTools!==void 0&&i.sessionTools.length>0)throw new Ze("validation_failed",We(tn.capabilityDisabled,{bit:"customTools"}));let D=n.tools!==void 0?new Set(n.tools):void 0,J=D!==void 0?$.filter(oe=>D.has(oe.name)):$,S=i?.capabilityProfile,k=S!==void 0?$.map(oe=>oe.name).filter(oe=>!S.tools.includes(oe)):[],A=i?.execution,C=()=>he([A?.binding,A?.policy.authorizationRevision,A?.attachmentSourceRevision,A?.attachmentSource]),F=()=>{},H=new Vn,Q=[];for(let oe of J)H.register(oe),Q.push(bn(oe));if(i?.sessionTools!==void 0)for(let{tool:oe,def:de}of i.sessionTools){if($.some(Re=>Re.name===oe.name))throw new Hn(oe.name);H.register(oe),Q.push(de)}let re=A?.boundary(J);if(d?.beforeTool&&!re)throw new TypeError("Trusted tool control requires an explicit execution host");let O=re===void 0||l===void 0?re:{...l.boundary(re),registerBuiltin:re.registerBuiltin},I,B=async oe=>{if(A===void 0)return;await A.refresh(oe),oe.throwIfAborted();let de=C();de!==I&&((I!==void 0||A.binding!==null)&&s?.invalidateAttachmentReferences(),F(),I=de),s?.updateAttachmentSource(A.attachmentSource);let Re=[...J],Te=new Set($.map(Le=>Le.name));for(let Le of[...A.deviceTools(),...A.serviceTools()]){if(Te.has(Le.name))throw new Hn(Le.name);Te.add(Le.name),(D===void 0||D.has(Le.name)||A.isClientTool(Le.name)||A.isShellAuxiliary(Le.name)&&D.has("Shell"))&&Re.push(Le)}let Be=A.filterTools(Re.map(Le=>A.definition(Le)??bn(Le))),Qe=new Set(Be.map(Le=>Le.name));if(Qe.size!==Be.length||Be.some(Le=>!Re.some(De=>De.name===Le.name)))throw new Error("Execution policy returned invalid tool definitions.");let ce=new Map(Re.filter(Le=>Qe.has(Le.name)).map(Le=>[Le.name,Le]));for(let Le of H.names())H.get(Le)!==ce.get(Le)&&H.unregister(Le);for(let Le of ce.values())H.has(Le.name)||H.register(Le);Q.splice(0,Q.length,...Be)},z=oe=>{let de=c===void 0?oe:c(oe);if(!de||typeof de.stream!="function")throw new TypeError("Invalid trusted model client");let Re=Gn(de,oe);return A===void 0&&t.memoryFor===void 0&&t.memoryPublicationFor===void 0?Re:Gn({async*stream(Te,Be){let Qe=Be?.signal??new AbortController().signal;if(await B(Qe),A?.assertModelRequestsAllowed(),await ie?.verifyAvailable(),Qe.throwIfAborted(),w!==void 0&&w!==C())throw new Ve("stale_generation");let ce=Te.tools.length===0?[]:Q,Le=rc(oe)?oc(Te,ce):{...Te,tools:ce};yield*Re.stream(Le,Be)}},oe)},j=z(u.client),ne=i?.cwd??t.cwd,U=Wd(u,t.adjudication,i?.askUser!==void 0),le=new ro({...U!==void 0?{mode:Ec({posture:U.posture,tier:U.tier}),classifier:U.config}:{},...t.hostShell!==void 0?{hostShell:t.hostShell}:{}}),ue=Ci(le,H,{cwd:ne}),ie,me=new Cs({registry:H,cwd:ne,permissionGate:ue,...O===void 0?{}:{executionBoundary:O},...i?.askUser!==void 0?{askUser:i.askUser}:{},...t.onDecision!==void 0?{onDecision:t.onDecision}:{},...A?.host.options.memoryFor===void 0?{}:{onBoundToolSucceeded:(oe,de)=>{let Re=A.binding,Te=_;if(!Nt||Te===void 0||Re===null||de.kind!=="device"||de.bindingId!==Re.bindingId||de.bindingRevision!==Re.revision||de.authorizationRevision!==A.policy.authorizationRevision||!A.available("Read")||!A.available("List")||!["Read","Write","Edit"].includes(oe.name))return;let Be=oe.args!==null&&typeof oe.args=="object"?oe.args.file_path:void 0;if(typeof Be!="string"||/[\\\u0000]/.test(Be))return;let Qe=Nb.resolve(Te.root,Be);Qe!==Te.root&&!Qe.startsWith(Te.root+"/")||Ge?.observeTouched([{toolName:oe.name,paths:[Qe]}])}}}),q=i?.sessionId??qb(),X=i?.memoryScope??{sessionId:q,...A===void 0?{}:{applicationScopeId:A.host.options.applicationScopeId,endUserId:A.user}},te=D===void 0||D.has("SearchMemory")?t.memoryFor?.(X):void 0,Se=D===void 0||D.has("SearchMemory")?t.memoryPublicationFor?.(X):void 0,Ue=te!==void 0||Se!==void 0;if(te&&Se)throw new Ze("validation_failed","Choose one trusted memory source per session");if(Se&&(!A||Se.identity.kind!=="client-managed"))throw new Ze("validation_failed","Client memory requires execution");let $e=te?.host?.authority.identity??Se?.identity;if($e!==void 0&&(X.applicationScopeId!==void 0&&$e.applicationScopeId!==X.applicationScopeId||X.endUserId!==void 0&&$e.endUserId!==X.endUserId))throw new Ze("validation_failed","Memory source ownership mismatch");if(Ue&&A?.host.options.memoryFor!==void 0)throw new Ze("validation_failed","Choose one trusted memory source per session");if(Ue&&i?.persistBackgroundUsage===null)throw new Ze("validation_failed","Memory requires background usage persistence");let Fe=new Set,lt=[],kt=oe=>{Fe.add(oe),oe.finally(()=>Fe.delete(oe)).catch(()=>{})},Ge,rt,Tt=i?.memorySelectionPersistence?.checkpoint===void 0?void 0:tm(i.memorySelectionPersistence.checkpoint,i.memorySelectionPersistence.scope),zt,gn="",wn=!1,Nt=!1,yn=!1,_,y=new AbortController;F=()=>{Nt=!1,yn=!1,_?.cancel(),_=void 0,Ge?.invalidate?.(),rt?.invalidateSource()};let P=(oe,de,Re,Te)=>{if(_?.key===oe)return _;F();let Be,Qe=De=>{if(De.throwIfAborted(),de!==C())throw new Ve("stale_generation")},ce=async(De,Ye,ot)=>{let Ot=Be;if(Ot===void 0||A===void 0)throw new Ve("source_unavailable");let Yt=Ot.signal;await A.refresh(Yt),Qe(Yt);let Xt=H.get(De),kn=De==="Read"?{file_path:Ye}:{path:Ye},xt={id:"memory-"+qb(),name:De,args:kn,blockIndex:0};if(!A.available(De)||!Xt||!Xt.isReadOnly)throw Object.assign(new Error("Memory resource unavailable"),{code:"EACCES"});let ln,zn,Vt={...Xt,async execute(ht,Ut){if(Qe(Yt),he(ht)!==he(kn)||Ut.executionTarget?.kind!=="device"||!Ut.fs)throw Object.assign(new Error("Memory resource identity changed"),{code:"EACCES"});let $t=performance.now(),Z=setTimeout(()=>Ot.deadline.abort(),Math.max(1,Ot.remainingMs));try{return ln={value:await ot(Ut.fs)},Qe(Yt),{content:[]}}catch(Ie){throw zn=Ie,Ie}finally{clearTimeout(Z),Ot.remainingMs-=performance.now()-$t,Ot.remainingMs<=0&&Ot.deadline.abort()}}},xn=new Vn;xn.register(Vt);let bt=new Cs({registry:xn,cwd:Re,permissionGate:ue,executionBoundary:{resolve(ht,Ut){if(Qe(Yt),!(ht!==Vt||H.get(De)!==Xt))return O?.resolve(Xt,Ut)}},...i?.askUser===void 0?{}:{askUser:i.askUser},...t.onDecision===void 0?{}:{onDecision:t.onDecision}}),At=(async()=>{let ht=bt.execute([xt],{sessionId:q,turnId:xt.id,toolRound:0,signal:Yt,registerOperation:kt});for(;;){let Ut=await ht.next();if(Ut.done){if(await A.refresh(Yt),Qe(Yt),zn!==void 0)throw zn;if(Ut.value.aborted||Ut.value.results[0]?.isError||ln===void 0)throw Object.assign(new Error("Memory permission or execution denied"),{code:"EACCES"});return ln.value}Ut.value.t==="event"&&s?.pushBody(Ut.value.body,"tool")}})();return kt(At),At};return _={key:oe,scope:de,root:Re,source:{pathStyle:"posix",orgMemoryGate:()=>({inject:Te}),fs:{lstat:De=>ce("Read",De,Ye=>Ye.lstat(De)),readFilePrefix:(De,Ye)=>ce("Read",De,ot=>ot.readFilePrefix(De,Ye)),readdir:De=>ce("List",De,Ye=>Ye.readdir(De))}},begin(De,Ye){Be?.deadline.abort();let ot=new AbortController;return Be={signal:AbortSignal.any([De,ot.signal,y.signal]),deadline:ot,remainingMs:Ye},Be.signal},cancel(){Be?.deadline.abort(),Be=void 0}},_},K=async oe=>{if(R=[],w=void 0,Nt=!1,yn=!1,!A?.binding||!A.host.options.memoryFor||!A.available("Read")){F();return}let de=C(),Re=A.binding.target,Te=A.root(),Be=A.host.options.memoryFor({applicationScopeId:A.host.options.applicationScopeId,endUserId:A.user,sessionId:q,workspaceId:Re.workspaceId,workspaceRevision:Re.workspaceRevision});if(!Be){F();return}let Qe=xt=>{if(typeof xt!="string"||xt.startsWith("/")||/[\\:\u0000-\u001f\u007f]/.test(xt)||xt!==""&&xt.split("/").some(ln=>ln===""||ln==="."||ln===".."))throw new Ve("invalid_request",400);return Nb.join(Te,xt)},ce=Qe(Be.cwd??""),Le=Be.userDir===void 0?void 0:Qe(Be.userDir),De=Be.autoMemoryDir===void 0||Be.autoMemory===!1?void 0:Qe(Be.autoMemoryDir),Ye=Be.deviceIoBudgetMs??WI;if(!Number.isInteger(Ye)||Ye<VI||Ye>$I)throw new Ve("invalid_request",400);let ot=he([de,ce,Le??null,De??null,Be.orgMemory===!0]),Ot=_?.key!==ot,Yt=P(ot,de,Te,Be.orgMemory===!0),Xt=Yt.begin(oe,Ye),kn=Yt.source;w=de;try{let xt=await jp(ce,Te,{boundary:Te,source:kn,signal:Xt,...Le===void 0?{}:{userDir:Le},...De===void 0?{}:{autoMemory:{dir:De}}});if(await A.refresh(Xt),Xt.throwIfAborted(),de!==C())throw new Ve("stale_generation");if(xt.warnings.length&&s?.pushControl(sn.platformWarning,{code:"memory_source_partial",message:xt.warnings.join(`
|
|
34
|
+
`)}),xt.segments.length&&(R=[{text:Yp(xt.segments),cacheable:!1}]),De!==void 0&&A.available("List")){let ln={dir:De,roots:[ce,Te],source:kn};if(Ge===void 0?Ge=qs(ln):Ot&&Ge.invalidate?.(ln),Nt=!0,Be.recallSelector===!0){if(i?.persistBackgroundUsage===null||i?.persistBackgroundUsage!==void 0&&i.memorySelectionPersistence===void 0)throw new Ve("invalid_request",400);let zn={fileBytes:Be.recallBudgets?.fileBytes??Xp,roundBytes:Be.recallBudgets?.roundBytes??Zp,sessionBytes:Be.recallBudgets?.sessionBytes??em},Vt=he(zn);if(zt!==void 0&&zt!==Vt)throw new Ve("invalid_request",400);if(rt===void 0){zt=Vt;let xn=js({dir:De,source:kn,budgets:zn,...Y===void 0?{}:{budget:Y},excludeFiles:["pending-anchors.md"],modelTier:()=>{let At=u.memoryModel??s?.modelBinding()??{client:u.client,model:u.model},ht=_;return{...At,client:Gn({async*stream(Ut,$t){let Z=$t?.signal??new AbortController().signal;if(await A.refresh(Z),Z.throwIfAborted(),ht===void 0||ht.scope!==C())throw new Ve("stale_generation");yield*At.client.stream(Ut,$t)}},At.client)}},onUsage:(At,ht)=>{G?.record({provider:ht.provider,model:ht.model,usage:At,purpose:"memory"})?.accepted&&(ve++,kt(be().catch($t=>{lt.push($t)})))}}),bt=i?.memorySelectionPersistence;try{Tt!==void 0&&bt!==void 0&&xn.restoreCheckpoint(Tt,bt.scope)}catch{throw xn.dispose(),new Ve("invalid_request",400)}rt=xn}else Ot&&rt.invalidateSource({dir:De,source:kn});yn=!0}else rt?.invalidateSource()}else Ge?.invalidate?.(),rt?.invalidateSource()}catch(xt){if(oe.throwIfAborted(),F(),R=[],xt instanceof Ve&&xt.code==="invalid_request")throw xt;s?.pushControl(sn.platformWarning,{code:"memory_source_unavailable",message:We(tn.memorySourceUnavailable)})}},ee={sessionId:q,...u.pricing!==void 0?{pricing:u.pricing}:{},resolveReasoningTokens:QI},G=n.budget!==void 0||A?.host.options.memoryFor!==void 0||Ue?i?.usageSnapshot!==void 0?$s.fromSnapshot(i.usageSnapshot,ee):new $s(ee):void 0,Y=G!==void 0?KI(n.budget,()=>G.snapshot()):void 0,ve=0,fe=0,xe=Promise.resolve(),be=()=>(xe=xe.catch(()=>{}).then(async()=>{if(G===void 0||typeof i?.persistBackgroundUsage!="function"||ve===fe)return;let oe=ve;await i.persistBackgroundUsage(G.snapshot()),fe=oe}),xe),Pe=i?.onTurnEnd!==void 0||Ue?oe=>{ie?.onTurnEnd(oe),i?.onTurnEnd?.(G===void 0?oe:{...oe,costSnapshot:G.snapshot()})}:void 0,_e;if(A!==void 0&&O!==void 0&&u.capabilities?.tools.agent){if(H.has("Task"))throw new Hn("Task");let oe=(De,Ye)=>ot=>{let Ot=()=>he({binding:A.binding,revision:A.policy.authorizationRevision,tools:A.policy.tools}),Yt=Ye??Ot(),Xt=()=>{if(Yt!==Ot()||!A.available("Task")&&!A.available("SpawnAgent"))throw new Ve("stale_generation")};Xt();let kn=new Map(ot.replacements.map(bt=>[bt.replacement,bt.original])),xt=new Map,ln=new Set(A.policy.tools),zn=new Set(ot.localTools),Vt=async()=>{await A.refresh(new AbortController().signal),Xt()};for(let bt of ot.toolset.registry.names()){let At=ot.toolset.registry.get(bt),ht=At,Ut=new Set;if(zn.has(At)){xt.set(At,{target:{kind:"controlled-service",executorId:"managed-service",bindingId:q,bindingRevision:"0",authorizationRevision:A.policy.authorizationRevision},assertCurrent:Vt});continue}let $t;for(;$t=De.resolve(ht,{id:"subagent-scope",name:ht.name,args:{},blockIndex:0}),!($t!==void 0||Ut.has(ht)||!kn.has(ht));)Ut.add(ht),ht=kn.get(ht);$t!==void 0&&xt.set(At,$t)}let xn={resolve:bt=>{if(ot.toolset.registry.get(bt.name)!==bt)return;let At=xt.get(bt)??(ln.has(bt.name)&&A.isChildMcpTool(ot.toolset.registry,bt)?O.resolve(bt,{id:"subagent-mcp",name:bt.name,args:{},blockIndex:0}):void 0);if(At!==void 0)return{...At,assertCurrent:async()=>{Xt(),await At.assertCurrent(),Xt()}}}};return{executionBoundary:xn,derive:oe(xn,Yt),permissionGate:Ci(le,ot.toolset.registry,{cwd:ne}),wrapClient:bt=>Gn({async*stream(At,ht){let Ut=ht?.signal??new AbortController().signal;await B(Ut),A.assertModelRequestsAllowed(),Xt(),await ie?.verifyAvailable(),Ut.throwIfAborted();let $t=At.tools.filter(Ie=>{let Ce=ot.toolset.registry.get(Ie.name);return Ce!==void 0&&(xt.has(Ce)&&(A.available(Ie.name)||zn.has(Ce))||ln.has(Ce.name)&&A.isChildMcpTool(ot.toolset.registry,Ce)&&A.available(Ce.name))}),Z=rc(bt)?oc(At,$t):{...At,tools:$t};yield*bt.stream(Z,ht)}},bt)}},de=A.host.options.subagentsFor?.({applicationScopeId:A.host.options.applicationScopeId,endUserId:A.user,sessionId:q});if(de!==void 0&&(typeof de.onNotification!="function"||de.background!==void 0&&(typeof de.background.outputFile!="function"||typeof de.background.writeFileImpl!="function")))throw new TypeError("Subagent notification and report storage callbacks are required");if(G!==void 0&&i?.persistBackgroundUsage===null&&(de?.continuableAgents===!0||de?.background!==void 0))throw new Ze("validation_failed",We(tn.backgroundUsageStoreRequired));let Re=de===void 0?void 0:async De=>{De.channel==="settled"&&await be(),await de.onNotification(De)},Te=de?.background===void 0?void 0:new ym({emit:De=>s?.pushBody(De,"agent"),onNotification:Re,writeFileImpl:de.background.writeFileImpl}),Be=()=>{let De=s?.modelBinding()??{client:u.client,model:u.model,maxOutputTokens:m};return{client:De.client,parentModel:De.model,maxTokens:Math.min(t.maxTokens??Fi,e??1/0,De.maxOutputTokens??1/0)}},Qe={client:j,system:()=>b,parentModel:u.model,parentBinding:Be,maxTokens:g,sessionId:q,permissionGate:ue,mcpDiscover:De=>A.childMcpDiscover(De),execution:oe(O),...Y===void 0?{}:{budget:Y},resolveModel:u.resolveSubagentModel,...u.subagentDispatch===void 0?{}:{dispatchPolicy:u.subagentDispatch},...u.resolveSubagentContextWindow===void 0?{}:{resolveContextWindow:u.resolveSubagentContextWindow},compaction:{...h,...u.compactionManagerOptions?.timeoutMs===void 0?{}:{timeoutMs:u.compactionManagerOptions.timeoutMs}},...t.onDecision===void 0?{}:{onDecision:t.onDecision},adjudication:{enabled:()=>le.getMode()==="default",...i?.askUser===void 0?{}:{askUser:i.askUser},...G===void 0?{}:{onQueryUsage:(De,Ye)=>{G.record({provider:(Ye??u.model).provider,model:(Ye??u.model).model,usage:De,purpose:"other"}).accepted&&ve++}},budget:()=>{if(le.getClassifierBreakerState().tripped!=="none")return"breaker_open";if(Y!==void 0&&(Y.onExceeded??"block")==="block"){let De=Y.getSpend();if(Y.maxTotalTokens!==void 0&&De.totalTokens>=Y.maxTotalTokens||Y.maxUsd!==void 0&&De.usdNano>=Y.maxUsd*1e9)return"budget_exhausted"}return le.tryConsumeSharedConsult()?"ok":"budget_exhausted"}},...Te===void 0?{}:{background:{runner:Te,outputFile:de.background.outputFile}}};Go({registry:H,toolDefs:Q},Qe);let ce=H.get("Task");$.push(ce),O.registerBuiltin?.(ce),J!==$&&(D===void 0||D.has("Task"))&&J.push(ce),D!==void 0&&!D.has("Task")&&(H.unregister("Task"),Q.splice(Q.findIndex(De=>De.name==="Task"),1));let Le=de?.continuableAgents!==!0?void 0:new wm({client:j,model:u.model,maxTokens:g,sessionId:q,cwd:ne,modelBinding:()=>{let De=s?.modelBinding()??u;return{client:De.client,model:De.model,maxTokens:Be().maxTokens,...De.contextWindowTokens===void 0?{}:{contextWindowTokens:De.contextWindowTokens}}},permissionGate:ue,execution:Qe.execution,...Y===void 0?{}:{budget:Y},...u.contextWindowTokens===void 0?{}:{contextWindowTokens:u.contextWindowTokens},emit:De=>s?.pushBody(De,"agent"),onNotification:Re});if(Le!==void 0){let De=[km({manager:Le,client:j,parentModel:u.model,parentBinding:Be,system:()=>b,toolset:{registry:H,toolDefs:Q},agents:Fs,nestedTask:Qe,adjudication:Qe.adjudication,mcpDiscover:Ye=>A.childMcpDiscover(Ye)}),xm({manager:Le})];for(let Ye of De){if(H.has(Ye.name))throw new Hn(Ye.name);$.push(Ye),O.registerBuiltin?.(Ye),!(D!==void 0&&!D.has(Ye.name))&&(J!==$&&J.push(Ye),H.register(Ye),Q.push(bn(Ye)))}}(Le!==void 0||Te!==void 0)&&(A.attachChildrenIdle(async()=>{let De=()=>(Te?.size??0)>0||Le?.list().some(ot=>ot.status!=="settled"||ot.queuedMessages>0)===!0;if(De())return!1;let Ye=await Promise.all([Le?.settleResources({timeoutMs:0}),Te?.settleResources({timeoutMs:0})]);return!De()&&Ye.every(ot=>ot===void 0||ot.status==="completed")}),_e=async()=>{let De=await Promise.allSettled([Le?.drain(),Te?.drain()]),Ye=await Promise.all([Le?.settleResources({timeoutMs:1/0}),Te?.settleResources({timeoutMs:1/0})]),ot=De.flatMap(Ot=>Ot.status==="rejected"?[Ot.reason]:[]);ot.push(...Ye.flatMap(Ot=>Ot?.failures.map(Yt=>Yt.cause)??[]));try{await be()}catch(Ot){ot.push(Ot)}if(ot.length)throw new AggregateError(ot,"Subagent resource cleanup failed")})}let L,N=!1,se,ge=oe=>{if(N)throw new Error("Memory is closed");ie=ob({config:oe,sessionId:q,...Y===void 0?{}:{budget:Y},modelTier:()=>(A?.assertModelRequestsAllowed(),u.memoryModel!==void 0?{...u.memoryModel,modelSource:u.memoryModel.source??"main"}:{...s?.modelBinding()??{client:u.client,model:u.model},modelSource:"main"}),system:()=>b,history:()=>s?.historySnapshot().messages??[],...i?.askUser===void 0?{}:{askUser:i.askUser},...t.onDecision===void 0?{}:{onDecision:t.onDecision},onUsage:Re=>{G?.record({provider:Re.provider??u.model.provider,model:Re.model,usage:Re.usage,purpose:"memory"})?.accepted&&(ve++,kt(be().catch(Be=>{lt.push(Be)})))}});let de=ie.searchTool;if(H.has(de.name))throw new Hn(de.name);return H.register(de),Q.push(bn(de)),J.push(de),O?.registerBuiltin?.(de),s&&Zr(s,ie),se&&(ie.onTurnStart(se),se=void 0),ie.start(),ie};te&&ge(te);let qe=Se===void 0?void 0:{capability:()=>!N&&Se.enabled()&&A?.memoryPublicationSupported()===!0,prepare:async oe=>{if(oe.throwIfAborted(),N||!Se.enabled())throw new Error("Memory source unavailable");return ie?(await ie.verifyAvailable(),ie):(L??=(async()=>{let de=AbortSignal.any([oe,y.signal]);await A.refresh(de),de.throwIfAborted();let Re=await A.createMemoryPublicationStore(Se.identity,{signal:y.signal,enabled:Se.enabled}),Te=await id.open({identity:Se.identity,store:Re,mode:Se.mode,assertCurrent:()=>{if(N||!Se.enabled()||!A.memoryPublicationAvailable())throw new Error("Memory source unavailable")},...Se.minimumDeletionGeneration?{minimumDeletionGeneration:Se.minimumDeletionGeneration}:{}});de.throwIfAborted();let Be=await Te.createHost({...Se.provenance?{provenance:Se.provenance}:{}}),Qe=ce=>{if(jb.isAbsolute(ce)||ce.split(/[\\/]/).some(Le=>Le===".."||Le===""))throw new Error("Invalid promotion target");return jb.join(Be.rootDir,ce)};return de.throwIfAborted(),ge({kind:"client-managed",domain:Se.identity.domain,host:Be,management:Te,rootDir:Be.rootDir,memoryDir:Be.memoryDir,enabled:Se.enabled,balance:Se.balance,...Se.promotion?{projectAgentsPath:Qe(Se.promotion.projectFile),userAgentsPath:Qe(Se.promotion.userFile)}:{},...Se.extraction?{extraction:Se.extraction}:{},...Se.recallSelector===void 0?{}:{recallSelector:Se.recallSelector},...Se.onObservation?{onObservation:Se.onObservation}:{}})})(),L)}};Ue&&A?.bindMemorySearch(()=>ie!==void 0&&ie.status().enabled);let Me=new di({client:j,executor:me,..._e===void 0&&A?.host.options.memoryFor===void 0&&!Ue&&l===void 0?{}:{onClosed:async()=>{let oe=[];l?.stop(),N=!0,y.abort();let de=_e?.().catch(Be=>{oe.push(Be)});Ge?.dispose?.(),rt?.dispose();try{await L?.catch(()=>{}),await ie?.close()}catch(Be){oe.push(Be)}let Re=await Promise.all([Ge?.settleResources?.({timeoutMs:1/0}),rt?.settleResources?.({timeoutMs:1/0})]);for(;Fe.size;)await Promise.allSettled([...Fe]);await de;let Te=[...oe,...Re.flatMap(Be=>Be?.failures.map(Qe=>Qe.cause)??[])];try{await be()}catch(Be){Te.push(Be)}try{await l?.close()}catch(Be){Te.push(Be)}if(Te.push(...lt),Te.length)throw new AggregateError(Te,"Memory resource cleanup failed")}},system:b,applicationPromptInfo:x,...d?.queryHooks===void 0?{}:{queryHooks:oe=>l.queryHooks(oe)},...i?.attachmentPersistence===void 0?{}:{attachmentPersistence:i.attachmentPersistence},...i?.memorySelectionPersistence===void 0?{}:{getMemorySelectionCheckpoint:()=>rt?.snapshotCheckpoint(i.memorySelectionPersistence.scope)??Tt},...u.refreshApplicationPrompt!==void 0||A!==void 0||Ue||t.systemFor!==void 0?{prepareSystem:async oe=>{let de=u.refreshApplicationPrompt===void 0?u:await u.refreshApplicationPrompt(oe);if(t.systemFor!==void 0){let Re=await l.system(Te=>t.systemFor(Object.freeze({...a}),Te),oe);oe.throwIfAborted(),p=(Re.system??t.system)?.map(Te=>({...Te})),v=(Re.systemAppend??t.systemAppend??[]).map(Te=>({...Te}))}return await B(oe),await K(oe),await qe?.prepare(oe),ie!==void 0&&(R=await ie.prepare(oe)),b=T(de),b}}:{},tools:Q,model:u.model,cwd:ne,...u.contextWindowTokens!==void 0?{contextWindowTokens:u.contextWindowTokens}:{},...m!==void 0?{maxOutputTokens:m}:{},...t.maxTokens!==void 0?{maxTokens:t.maxTokens}:{},sessionId:q,...Y!==void 0?{budget:Y}:{},...G!==void 0?{runtimeCostSnapshot:()=>G.snapshot(),onEvent:oe=>{G.consume(oe)?.accepted&&(ve++,oe.type==="cost.usage.updated"&&oe.purpose==="compaction"&&typeof i?.persistBackgroundUsage=="function"&&s?.retainCostPersistence(be()))}}:{},...i?.initialHistory!==void 0?{initialHistory:i.initialHistory}:{},...i?.initialSeq!==void 0?{initialSeq:i.initialSeq}:{},maxTurnsPerQuery:t.maxTurnsPerQuery??hp,...t.temperature===void 0?{}:{temperature:t.temperature},...t.stopSequences===void 0?{}:{stopSequences:t.stopSequences},...t.maxToolRounds===void 0?{}:{maxToolRounds:t.maxToolRounds},...t.maxConsecutiveErrors===void 0?{}:{maxConsecutiveErrors:t.maxConsecutiveErrors},...t.timeouts!==void 0?{timeouts:t.timeouts}:{},...t.maxTurnWallClockMs!==void 0?{maxTurnWallClockMs:t.maxTurnWallClockMs}:{},compaction:Ue?{...h,observer:{...h.observer,onCompactionFinished:oe=>{h.observer?.onCompactionFinished?.(oe),ie?.compactionObserver.onCompactionFinished?.(oe)}}}:h,...u.compactionManagerOptions!==void 0?{compactionManagerOptions:u.compactionManagerOptions}:{},reminders:Tp({todoStore:M,...A?.host.options.memoryFor===void 0&&!Ue?{}:{prepareMemoryRecalls:async oe=>{await B(oe),await ie?.prepareReminders(oe),wn&&(wn=!1,yn&&rt?.prefetch(gn)),Nt&&(await Ge?.prepareReminders?.(oe),await B(oe))},drainMemoryRecalls:()=>[...ie?.drainReminders()??[],...Nt?Ge?.drainReminderEntries?.()??[]:[]],drainMemorySelections:()=>[...ie?.drainSelections()??[],...yn?rt?.drainReminderEntries?.()??[]:[]]}}),...i?.configurationThinking!==void 0?i.configurationThinking===null?{}:{thinking:i.configurationThinking}:n.thinking!==void 0?{thinking:n.thinking}:t.thinking!==void 0?{thinking:t.thinking}:{},...Pe!==void 0?{onTurnEnd:Pe}:{},...t.runQueryImpl!==void 0?{runQueryImpl:t.runQueryImpl}:{},...U!==void 0||A?.host.options.memoryFor!==void 0||Ue?{onTurnStart:(oe,de)=>{gn=de.join(`
|
|
35
|
+
`),wn=!0,ie?ie.onTurnStart(de):Ue&&(se=[...de]),U?.transcript.noteTurn(de)},onInputsConsumed:oe=>{U?.transcript.noteInput(oe),yn&&rt?.supplement?.(oe.join(`
|
|
36
|
+
`))}}:{}});return s=Me,Me.bindModelClientWrapper(z,u.client),ie!==void 0&&Zr(Me,ie),qe&&Bd(Me,qe),(Ue||A!==void 0)&&Me.bindModelRequestGuard(()=>{A?.assertModelRequestsAllowed(),ie?.assertAvailable()}),Ue&&Me.bindConfigurationReadiness(async()=>L!==void 0&&ie===void 0?!1:await ie?.readyForModelChange()??!0),i?.attachmentPersistence?.verifySource===!0&&A!==void 0&&A.attachAttachmentSourceConfirmation(()=>Me.confirmAttachmentSource(async oe=>(await A.refresh(oe),oe.throwIfAborted(),I=C(),F(),A.attachmentSource))),S!==void 0&&k.length>0&&Me.pushControl(sn.platformWarning,{code:"profile_narrowed_capabilities",message:We(tn.profileNarrowedCapabilities,{profile:S.name,dropped:k.join(", ")}),dropped:k}),Me.bindCwdRebinder(oe=>me.withCwd(oe,{permissionGate:Ci(le,H,{cwd:oe})})),Me}}}var Yf={"mobile-default":ml()},Xf=30,Zf=36e5,Qf=class{#e;#n;owner;#r;#s;sessionId;endUserId;createdAt;#t;#o;#i;#a;#c;platformAudio;#d;title$;#f=Promise.resolve();constructor(e){this.sessionId=e.sessionId,this.#e=e.configuration,this.#n=e.configure,this.owner=e.owner,this.#r=e.settleOwner,this.#s=e.checkpointOwner,this.endUserId=e.endUserId,this.createdAt=e.createdAt,this.#t=e.driver,this.#o=e.bridge,this.#i=e.persistence,this.#a=e.resolveCwd,this.#c=e.onCwdChanged,this.platformAudio=e.platformAudio,this.#d=e.media,this.title$=e.initialTitle}get events(){return this.#t.events}send(e){return this.owner?.assertCurrent(),this.#t.send(e)}sendMessage(e){return this.owner?.assertCurrent(),this.#t.sendMessage(e)}inputCapabilities(){return this.#t.inputCapabilities()}getInputTarget(){return this.#t.getInputTarget()}submitInput(e){return this.owner?.assertCurrent(),this.#t.submitInput(e)}getInputStatus(...e){return this.#t.getInputStatus(...e)}interrupt(e){this.#t.interrupt(e)}close(e){this.#t.close(e)}async settleResources(){await this.#t.settleResources(),this.#t.status()==="ended"&&await this.#r?.()}status(){return this.#t.status()}contextState(){return this.#t.contextState()}applicationPrompt(){return this.#t.applicationPrompt()}setModel(e){return this.owner?.assertCurrent(),this.#e?.()!==void 0?{status:"rejected",reason:"unsupported"}:typeof this.#t.setModel=="function"?this.#t.setModel(e):{status:"rejected",reason:"unsupported"}}setThinking(e){return this.owner?.assertCurrent(),this.#e?.()!==void 0?{status:"rejected",reason:"unsupported"}:typeof this.#t.setThinking=="function"?this.#t.setThinking(e):{status:"rejected",reason:"unsupported"}}configuration(){let e=this.#e?.();return e===void 0?void 0:structuredClone(e)}configure(e,n){return this.owner?.assertCurrent(),this.#n?.(e,n)??Promise.resolve({status:"rejected",reason:"unsupported"})}mediaState(){return this.#d?structuredClone(this.#d):void 0}lastSeq(){return this.#t.lastSeq()}firstSeq(){return this.#t.firstSeq()}historySnapshot(){return this.#t.historySnapshot()}title(){return this.title$}submitToolResult(e,n){return this.owner?.assertCurrent(),this.#o.submitToolResult(e,n)}submitPermission(e,n){return this.owner?.assertCurrent(),this.#o.submitPermission(e,n)}submitQuestionAnswers(e,n){return this.owner?.assertCurrent(),this.#o.submitQuestionAnswers(e,n)}noteSubscribers(e){this.#o.noteSubscribers(e)}async compact(e={}){if(this.owner?.assertCurrent(),e.checkpoint!==void 0&&e.checkpoint!==!1&&this.#i?.checkpoints===void 0)return{status:"rejected",reason:"checkpoints_not_wired"};let n=await this.#t.compactIdle({...e.instructions!==void 0?{instructions:e.instructions}:{},...e.checkpoint!==void 0?{checkpoint:e.checkpoint}:{}});if(n.status==="compacted"){this.#t.ownsArchiveHistoryCommit?.()!==!0&&this.#i?.commitRewritten(this.#t.historySnapshot().messages),await this.#s?.();let i=n.outcome;return{status:"compacted",compactionId:i.compactionId??i.observation?.compactionId??"",removedRange:i.removedRange,...n.checkpointId!==void 0?{checkpointId:n.checkpointId}:{}}}return n.status==="failed"?{status:"failed",reason:n.outcome.reason,message:n.outcome.message,...n.outcome.checkpointId!==void 0?{checkpointId:n.outcome.checkpointId}:{}}:{status:"rejected",reason:n.reason}}#m(e){let n=this.#f.then(()=>(this.owner?.assertCurrent(),e()));return this.#f=n.then(()=>{},()=>{}),n}#p(e){return this.owner===void 0?e():this.owner.write(e)}checkpoint(e={}){return this.#m(async()=>{if(this.#i?.checkpoints===void 0)return{status:"rejected",reason:"checkpoints_not_wired"};let n=this.#t.status();if(n==="ended")return{status:"rejected",reason:"session_ended"};if(n==="running")return{status:"rejected",reason:"turn_running"};let i=await this.#k("manual",this.#t.historySnapshot().messages,e.label);return{status:"created",checkpoint:yr(i)}})}async listCheckpoints(){let e=this.#i?.checkpoints;return e===void 0?{status:"rejected",reason:"checkpoints_not_wired"}:{status:"listed",checkpoints:(await e.store.list(this.endUserId,this.sessionId)).map(yr)}}restore(e,n={}){return this.owner===void 0?this.#w(e,n):(this.owner.assertCurrent(),this.#w(e,n).then(async i=>(i.status==="restored"&&await this.#s?.(),i)))}#w(e,n){if(this.#t.ownsArchiveHistoryCommit?.()===!0&&typeof this.#t.withArchiveRestore=="function"){if(this.#i?.checkpoints===void 0)return Promise.resolve({status:"rejected",reason:"checkpoints_not_wired"});let o=this.#t.status();return o==="ended"?Promise.resolve({status:"rejected",reason:"session_ended"}):o==="running"?Promise.resolve({status:"rejected",reason:"turn_running"}):this.#t.withArchiveRestore(s=>this.#v(e,n,void 0,s))}let i=this.#t.prepareHistoryRestore?.();return i!==void 0?i.then(o=>this.#v(e,n,o)):this.#v(e,n)}#v(e,n,i,o){return this.#m(async()=>{let s=this.#i;if(s?.checkpoints===void 0)return{status:"rejected",reason:"checkpoints_not_wired"};let a=this.#t.status();if(a==="ended")return{status:"rejected",reason:"session_ended"};if(a==="running"&&o===void 0)return{status:"rejected",reason:"turn_running"};let d;try{d=await s.checkpoints.store.get(this.endUserId,this.sessionId,e)}catch(f){throw f instanceof vn&&f.code==="CHECKPOINT_INVALID"?new et(this.sessionId,f.message,f):f}if(d===null)return{status:"rejected",reason:"not_found"};if(d.sessionId!==this.sessionId)return{status:"rejected",reason:"session_mismatch"};Zo(n,this),await this.owner?.beginTurn();let c;n.checkpoint!==!1&&(c=(await this.#k("pre_restore",this.#t.historySnapshot().messages)).checkpointId),Zo(n,this);let l=o===void 0?this.#t.restoreHistory(d.messages,e,i):await o(d.messages,e);return l.status==="rejected"?{status:"rejected",reason:l.reason}:(o===void 0&&s.commitRewritten(this.#t.historySnapshot().messages),d.cwd!==s.cwd&&this.#o.emitPlatformWarning({code:"cwd_mismatch_on_restore",message:We(wt.cwdMismatchOnRestore,{stored:d.cwd,current:s.cwd})}),{status:"restored",checkpointId:e,fromMessages:l.fromMessages,toMessages:l.toMessages,...c!==void 0?{preRestoreCheckpointId:c}:{}})})}deleteCheckpoint(e){return this.#m(async()=>{let n=this.#i?.checkpoints;return n===void 0?"checkpoints_not_wired":await this.#p(()=>n.store.delete(this.endUserId,this.sessionId,e))?"deleted":"not_found"})}async setCwd(e){let n=this.#t.status();if(n==="ended")return{status:"rejected",reason:"session_ended"};if(n==="running")return{status:"rejected",reason:"turn_running"};let i=this.#a;if(i===void 0)return{status:"rejected",reason:"unsupported"};let o=this.#t.cwd,s=await i(e,o);if(!s.ok)return{status:"rejected",reason:s.reason,...s.detail!==void 0?{detail:s.detail}:{}};let a=this.#t.setCwd(s.cwd);return a.status==="rejected"?{status:"rejected",reason:a.reason}:(a.to!==a.from&&(this.#i!==void 0&&(this.#i.cwd=a.to),this.#o.setCwd(a.to),this.#c?.({at:new Date().toISOString(),from:a.from,to:a.to})),{status:"changed",cwd:a.to,from:a.from})}async exportCheckpoint(e){let n=this.#i?.checkpoints;if(n===void 0)return{status:"rejected",reason:"checkpoints_not_wired"};let i;try{i=await n.store.get(this.endUserId,this.sessionId,e)}catch(o){throw o instanceof vn&&o.code==="CHECKPOINT_INVALID"?new et(this.sessionId,o.message,o):o}return i===null||i.sessionId!==this.sessionId?{status:"rejected",reason:"not_found"}:{status:"exported",bytes:Os(i)}}importCheckpoint(e,n={}){return this.#m(async()=>{let i=this.#i;if(i?.checkpoints===void 0)return{status:"rejected",reason:"checkpoints_not_wired"};if(this.#t.status()==="ended")return{status:"rejected",reason:"session_ended"};let o=Zo(n,this),s;try{s=Bs(e,{sessionId:this.sessionId,checkpointId:o?.checkpointId??Ms(i.now()),createdAt:o?.createdAt??new Date(i.now()).toISOString(),...n.label!==void 0?{label:n.label}:{}})}catch(d){if(d instanceof vn&&d.code==="CHECKPOINT_IMPORT_INVALID")return{status:"rejected",reason:"invalid",detail:d.message};throw d}if(o){let d=await i.checkpoints.store.get(this.endUserId,this.sessionId,o.checkpointId);if(Zo(n,this),d){let c=Bs(Os(d),{sessionId:this.sessionId,checkpointId:o.checkpointId,createdAt:o.createdAt});if(Bt(c)!==Bt(s))throw new Error("Archive checkpoint import conflict");return{status:"imported",checkpoint:yr(d)}}}let a=await this.#p(()=>i.checkpoints.store.put(this.endUserId,s));return this.#t.pushBody({type:"session.checkpointed",checkpointId:a.checkpointId,trigger:a.trigger,...a.label!==void 0?{label:a.label}:{},messageCount:a.messageCount},"server"),{status:"imported",checkpoint:yr(a)}})}beforeCompactHook(){let e=this.#i?.checkpoints;if(e!==void 0)return async(n,i)=>{if(i.checkpoint===!1||i.checkpoint===void 0&&!e.autoBeforeCompact)return;let o=typeof i.checkpoint=="object"?i.checkpoint.label:void 0;return{checkpointId:(await this.#m(()=>this.#k("pre_compaction",n.messages,o))).checkpointId}}}async#k(e,n,i){let o=this.#i,s=o.checkpoints,a=await this.#p(()=>s.store.put(this.endUserId,Bb({checkpointId:Ms(o.now()),sessionId:this.sessionId,trigger:e,cwd:o.cwd,messages:n,...i!==void 0?{label:i}:{},model:this.#t.model,now:o.now})));return this.#t.pushBody({type:"session.checkpointed",checkpointId:a.checkpointId,trigger:a.trigger,...a.label!==void 0?{label:a.label}:{},messageCount:a.messageCount},"server"),a}};function eT(t,e){let n=Date.parse(t);return Number.isNaN(n)?e:n}function tT(t,e){let n=t.lastSeq!==void 0&&Number.isSafeInteger(t.lastSeq)&&t.lastSeq>=0?t.lastSeq:void 0;if(n!==void 0&&t.seqSealed===!0)return n+1;let i=Date.parse(t.createdAt),o=Number.isNaN(i)?0:Math.max(0,Math.floor(e-i)),s=Math.max(n!==void 0?n+1:0,o);return Number.isSafeInteger(s)?s:Number.MAX_SAFE_INTEGER}function Ub(t){if(t.execution!==void 0&&t.transactionalExecution!==void 0)throw new TypeError("Conflicting execution backends");let e=t.execution??t.transactionalExecution;if(e!==void 0&&t.platform===void 0)throw new TypeError("Remote execution requires the built-in platform factory");if(t.transactionalExecution!==void 0&&typeof t.store?.claimOwner!="function")throw new TypeError("Transactional execution requires an explicit owned Store");let n=t.execution===void 0?void 0:new Yo(t.execution),i=t.transactionalExecution===void 0?void 0:new Yo(t.transactionalExecution),o=n??i;if(t.cacheHost!==void 0&&(t.platform===void 0||t.store===void 0||t.gatewayCache!==void 0))throw new TypeError("Durable cache host requires built-in platform and original Store exclusively");if(t.gatewayCache!==void 0&&t.platform===void 0)throw new Error("Gateway cache requires the built-in platform session factory");let s=t.capabilityProfiles??Yf,a=t.now??Date.now,d=t.store,c=$n(t.logger),l=Qn(),f=(S,k,A,C)=>{if((S==="commit"?l.storeCommitErrors:l.storeCreateErrors).inc(),C!==void 0)try{C.status()!=="ended"&&C.pushBody({type:"turn.error",scope:"server.persistence",message:We(S==="commit"?wt.storeCommitFailed:wt.storeCreateFailed),recoverable:!0,errorKind:S==="commit"?"store_commit_failed":"store_create_failed"},"server")}catch{}try{if(t.onStoreError!==void 0){t.onStoreError(k,A);return}console.error(JSON.stringify({level:"error",event:S==="commit"?Xe.storeCommitFailed:Xe.storeCreateFailed,sessionId:k,message:Bn(A)}))}catch{}},u=new Set,m=S=>{let k=S.then(()=>{},()=>{});u.add(k),k.then(()=>u.delete(k))},g=async()=>{let S=0;for(;u.size>0;){let k=[...u];S+=k.length,await Promise.all(k)}return await o?.settle(),S};if(t.factory===void 0==(t.platform===void 0))throw new Error('createAgentSessionFactory requires exactly one of "factory" (custom inner assembly) or "platform" (built-in tansr platform assembly)');if(t.platform!==void 0&&t.assembleEndUserModel!==void 0)throw new Error('"assembleEndUserModel" cannot be combined with "platform" (the built-in form wires the per-endUser assembly seam itself)');let h,p=t.assembleEndUserModel,v;if(t.platform!==void 0){let S=t.platform,k=Kr({governor:S.governor,fetchImpl:S.fetchImpl}),A=wd({apiBaseUrl:S.apiBaseUrl,appId:S.appId,appKey:S.appKey,...S.ttlSeconds!==void 0?{ttlSeconds:S.ttlSeconds}:{},...k!==void 0?{fetchImpl:k}:{},now:a,...S.tokenMinter??{}});t.cacheHost?.connectPlatform({appId:S.appId,apiBaseUrl:S.apiBaseUrl,tokenFor:H=>A.tokenFor(H),...k?{fetchImpl:k}:{}});let C=S.bundleCacheTtlMs??_i,F=S.bundleCache??(C>0?ar({ttlMs:C,...k!==void 0?{fetchImpl:k}:{},now:a}):void 0);p=mv({minter:A,apiBaseUrl:S.apiBaseUrl,appId:S.appId,...k!==void 0?{fetchImpl:k}:{},...S.onPlatformWarning!==void 0?{onPlatformWarning:S.onPlatformWarning}:{},...t.logger!==void 0?{logger:t.logger}:{},now:a,...F!==void 0?{bundleCache:F}:{bundleCacheTtlMs:0}},{...e===void 0?{}:{remoteExecution:!0},...t.cacheHost!==void 0?{gatewayCache:H=>t.cacheHost.assembler(H),refreshCacheConfiguration:(H,Q)=>t.cacheHost.refreshConfiguration(H.endUserId,H.sessionId,Q),cacheConfigurationRefreshRequired:H=>t.cacheHost.configurationRefreshRequired(H.endUserId,H.sessionId),confirmCacheConfiguration:(H,Q)=>t.cacheHost.confirmConfiguration(H.endUserId,H.sessionId,Q),archivedRuntime:H=>t.cacheHost.archivedRuntime(H.endUserId,H.sessionId,H.previous)}:t.gatewayCache===void 0?{}:{gatewayCache:t.gatewayCache}}),v=()=>({tokenMinter:A.stats(),...F!==void 0?{bundleCache:F.stats()}:{}}),h=Vd({...S.trustedExtensionsFor===void 0?{}:{trustedExtensionsFor:S.trustedExtensionsFor},...S.systemFor===void 0?{}:{systemFor:S.systemFor},...S.memoryFor===void 0?{}:{memoryFor:S.memoryFor},...S.memoryPublicationFor===void 0?{}:{memoryPublicationFor:S.memoryPublicationFor},cwd:t.cwd,...S.system!==void 0?{system:S.system}:{},...S.systemAppend!==void 0?{systemAppend:S.systemAppend}:{},...S.temperature===void 0?{}:{temperature:S.temperature},...S.stopSequences===void 0?{}:{stopSequences:S.stopSequences},...S.maxToolRounds===void 0?{}:{maxToolRounds:S.maxToolRounds},...S.maxConsecutiveErrors===void 0?{}:{maxConsecutiveErrors:S.maxConsecutiveErrors},...S.maxTokens!==void 0?{maxTokens:S.maxTokens}:{},...S.maxOutputTokens!==void 0?{maxOutputTokens:S.maxOutputTokens}:{},...S.maxTurnsPerQuery!==void 0?{maxTurnsPerQuery:S.maxTurnsPerQuery}:{},...S.timeouts!==void 0?{timeouts:S.timeouts}:{},...S.maxTurnWallClockMs!==void 0?{maxTurnWallClockMs:S.maxTurnWallClockMs}:{},...S.hostShell!==void 0?{hostShell:S.hostShell}:{},...S.runQueryImpl!==void 0?{runQueryImpl:S.runQueryImpl}:{},...S.adjudication!==void 0?{adjudication:S.adjudication}:{},...S.onDecision!==void 0?{onDecision:S.onDecision}:{}})}else h=t.factory;p!==void 0&&(p=kd(p));let b=iT(t.checkpoints,d);d!==void 0&&t.cacheHost?.connectStore(d);let R=nT(t.sessions?.retention),w=new Map,x=(S,k)=>{if(k===void 0)return;let A=Wt(S);k.sessionRetentionDays!==void 0?w.set(A,k.sessionRetentionDays):w.delete(A)},T,M=async(S={})=>{if(R===void 0||d?.sweepRetention===void 0)return;let k=a();if(!S.force&&T!==void 0&&k-T<R.sweepIntervalMs)return;T=k;let A=R.policy,C=await d.sweepRetention({policy:A,policyFor:H=>({...A,maxAgeDays:w.get(H)??A.maxAgeDays}),now:k,...S.activeSessionIds!==void 0?{keep:S.activeSessionIds}:{}}),F=t.checkpoints?.dir;if(F!==void 0)for(let{endUserKey:H,sessionId:Q}of C.deleted)await XI(ZI.join(F,"agent-checkpoints",H,Q),{recursive:!0,force:!0}).catch(re=>C.failures.push({endUserKey:H,sessionId:Q,message:`checkpoints: ${Bn(re)}`}));return(C.deleted.length>0||C.failures.length>0)&&t.logger?.log?.("info",Xe.sessionRetentionSwept,{scanned:C.scanned,deleted:C.deleted.length,failures:C.failures.length,byReason:C.deleted.reduce((H,Q)=>({...H,[Q.reason]:(H[Q.reason]??0)+1}),{})}),C},W=!1,$={get terminalCapabilities(){let S=[];return t.configuration!==void 0&&d?.claimOwner!==void 0&&d.initializeConfiguration!==void 0&&d.inspectConfiguration!==void 0&&d.commitConfiguration!==void 0&&S.push("session-configuration-v1"),W&&S.push("memory-lifecycle-v1"),S},...n!==void 0?{execution:n}:{},...i!==void 0?{transactionalExecution:i}:{},async create(S){let k,A,C,F,H,Q=!1,re,O=!1,I=ue=>{C===void 0&&(C=setInterval(()=>{if(Q||(Q=!0,ue.renew().then(void 0,ie=>{H??=ie,F?.close(),le?.close()}).finally(()=>{Q=!1})),!O&&re!==void 0){let ie=re;re=void 0,O=!0,ie().then(void 0,me=>c("error",Xe.storeCommitFailed,{message:Bn(me)})).finally(()=>{O=!1})}},Math.max(250,Math.floor(ue.leaseMs/3))),C.unref())},B=tv($,S),z,j,ne=B===void 0,U,le;try{if(o!==void 0&&(S.prompt!==void 0||S.cwd!==void 0))throw new Ze("validation_failed",We(tn.executionInitializeRequired));B?.assertCurrent();let ue=S.tools,ie;if(S.capabilitiesProfile!==void 0){let Z=s[S.capabilitiesProfile];if(Z===void 0)throw new Ze("validation_failed",We(tn.unknownCapabilitiesProfile,{profile:S.capabilitiesProfile,available:Object.keys(s).join(", ")}));ue=S.tools!==void 0?S.tools.filter(Ie=>Z.includes(Ie)):[...Z],ie={name:S.capabilitiesProfile,tools:Z}}let me=o===void 0?await rT(S,t):"/workspace/unbound",q,X,te,Se,Ue=S.model,$e=S.thinking,Fe=!1,lt,kt,Ge,rt,Tt,zt=!1,gn=a(),wn,Nt,yn,_,y;if(S.resume!==void 0){if(d===void 0)throw new Ze("resume_unavailable","session store is not wired");let Z;try{U=t.cacheHost?.beginSessionCreation(S.endUserId,S.resume.sessionId),k=await d.claimOwner?.(S.endUserId,S.resume.sessionId),k!==void 0&&I(k);let Ke=1e3;for(let dt=0;;dt+=1)try{Z=await d.get(S.endUserId,S.resume.sessionId);break}catch(Kt){if(!(Kt instanceof vn)||Kt.code!=="SESSION_LOCKED"||dt>=Ke-1)throw Kt;await new Promise(fn=>setTimeout(fn,5))}B?.assertCurrent()}catch(Ke){throw Ke instanceof et?new Ze("store_corrupted",Ke.message):Ke}if(Z===null)throw new Ze("session_not_found",`session not found in store: ${S.resume.sessionId}`);if(Z.ownershipRequired&&k===void 0)throw new Ze("resume_unavailable","Session requires durable ownership");if(te=S.resume.sessionId,j=Z.meta,Fe=!0,Se=Z.configuration,Se!==void 0&&(Ue=Se.model??void 0,$e=Se.thinking??void 0),A=Z.runtimeCheckpoint,A!==void 0&&(d.runtimeCheckpoints!==!0||k===void 0||S.prompt!==void 0))throw new Ze("resume_unavailable","Runtime checkpoint requires the original trusted Store");let Ie=A===void 0?Ps(Z.messages):{messages:Z.messages,synthesizedResults:0,droppedMessages:0};lt=Ie.messages,zt=Ie.synthesizedResults>0||Ie.droppedMessages>0||Z.recovery!==void 0,Z.recovery!==void 0&&(X={code:"session_recovery_degraded",message:We(wt.recoveryDegraded,{dropped:Z.recovery.droppedMessages,retained:Z.recovery.recoveredMessages,synthesized:Z.recovery.synthesizedToolResults})}),kt=Z.usageSnapshot,Ge=Z.attachmentCheckpoint,d.attachmentSourceCheckpoints===!0&&(rt=Z.attachmentSourceCheckpoint),Tt=Z.memorySelectionCheckpoint,gn=eT(Z.meta.createdAt,gn),wn=Z.meta.title,Nt=Z.meta.platformSessionId,yn=Z.meta.retentionDays,y=tT(Z.meta,a());let Ce=o!==void 0?{cwd:"/workspace/unbound",warning:void 0}:await sT(Z.meta.cwd,me,{mode:t.cwdOnResume??(t.cwdPolicy!==void 0?"stored":"current"),policy:Jf(t,S.endUserId)});me=Ce.cwd,zt||=o!==void 0&&(o.options.readAttachmentSource===void 0||d.attachmentSourceCheckpoints!==!0)||o===void 0&&Z.meta.cwd!==void 0&&Z.meta.cwd!==me,q=Ce.warning}else if(S.fork!==void 0){let Z=await aT({init:S,fork:S.fork,checkpointStore:b,store:d,cwd:me});te=Z.sessionId,lt=Z.history,wn=Z.title,_={sourceSessionId:S.fork.sessionId,checkpointId:S.fork.checkpointId}}else te=S.sessionId??$d();let P=!1;d?.claimOwner!==void 0&&k===void 0&&(B?.mode==="fresh"?(B.assertCurrent(),await Jl(d,S.endUserId,{sessionId:te,cwd:me}),B.assertCurrent(),P=!0):await d.create(S.endUserId,{sessionId:te,cwd:me}),k=await d.claimOwner(S.endUserId,te),I(k)),o!==void 0&&(me="/workspace/unbound");let K=new eo({cwd:me,...t.permissionTimeoutMs!==void 0?{permissionTimeoutMs:t.permissionTimeoutMs}:{},...t.questionGraceMs!==void 0?{questionGraceMs:t.questionGraceMs}:{},now:a,onPermissionReceipt:Z=>{c(Z.reason!==void 0?"warn":"info",Xe.bridgePermissionReceipt,{sessionId:te,requestId:Z.requestId,verdict:Z.verdict,...Z.reason!==void 0?{reason:Z.reason}:{}})}}),ee=[];if(S.clientTools!==void 0){let Z=new Set;for(let Ie of S.clientTools){if(Z.has(Ie.name))throw new Ze("validation_failed",We(tn.clientToolConflict,{name:Ie.name}));Z.add(Ie.name),ee.push(Gd(Ie,K,a,o===void 0?void 0:async(Ce,Ke)=>{if(le===void 0)throw new Error("Execution session is not ready");return le.invokeClientTool(Ie,Ce,Ke)}))}}let G,Y,ve=!1,fe=[],xe=!1,be,Pe;if(p!==void 0){Fe&&Nt!==void 0&&t.cacheHost!==void 0&&await t.cacheHost.recoverConfiguration(S.endUserId,te,Nt,()=>{k?.assertCurrent(),B?.assertCurrent()}),Y=t.cacheHost?.selectRuntime(S.endUserId,te,Nt,Fe)??Nt??zi();let Z=t.cacheHost?.prepareArchivedRecovery(S.endUserId,te,Y);Z!==void 0&&await Z;let Ie=await p({endUserId:S.endUserId,sessionId:te,...Ue!==void 0?{model:Ue}:{},onWarning:Ce=>{xe?K.emitPlatformWarning(Ce):fe.push(Ce)},platformSessionId:Y,onSessionArchived:(Ce,Ke)=>{if(Ce!==Y)throw new Error("Platform runtime changed during assembly");return ve=!0,Y=Ke??zi(),Y}});G=(Ce,Ke)=>{let dt=Ie(Ce,Ke);return Pe={...dt.readPlatformCatalog===void 0?{}:{readPlatformCatalog:dt.readPlatformCatalog},...dt.readPlatformUsage===void 0?{}:{readPlatformUsage:dt.readPlatformUsage}},be={capabilities:dt.capabilities,platformTools:dt.platformTools,...dt.sessionRetentionDays!==void 0?{sessionRetentionDays:dt.sessionRetentionDays}:{}},dt}}let _e=!1,L=!1,N=!1,se=!0,ge=0,qe=!1,Me=null,oe=null,de,Re=new Set,Te=(Z,Ie,Ce,Ke,dt)=>{if(d===void 0)return;if(N)return f("commit",te,new Error("Archive Store completion remains unobservable"),ce),Promise.resolve(!1);let Kt=++ge,fn=qe?{commitId:Ke?.commitId??$d(),observation:Ke?.observation??rn(te,Z,ce.archiveHistoryObservation().localHistoryGeneration)}:null,Lt=Ie||_e;_e=Lt;let to;qe&&(oe=null);try{let gt=Ce??ce?.currentCostSnapshot?.();to=d.commit(S.endUserId,te,Z,{...k===void 0?{}:{owner:k},rewritten:Lt,lastSeq:ce.lastSeq(),...gt!==void 0?{usageSnapshot:Vs(gt)}:{},...d.attachmentCheckpoints===!0?{attachmentCheckpoint:dt===void 0?ce.attachmentCheckpoint?.(Z,Ie):dt.attachmentCheckpoint}:{},...d.attachmentSourceCheckpoints===!0&&o?.options.readAttachmentSource!==void 0?{attachmentSourceCheckpoint:Ie?null:dt===void 0?ce.attachmentSourceCheckpoint?.(Z):dt.attachmentSourceCheckpoint}:{},...d.memorySelectionCheckpoints===!0?{memorySelectionCheckpoint:dt===void 0?ce.memorySelectionCheckpoint?.():dt.memorySelectionCheckpoint}:{}})}catch(gt){return qe&&(N=!0),_e=!0,L=!0,f("commit",te,gt,ce),Promise.resolve(!1)}let Ni=to;if(qe)try{oe=Sl({...fn,storeIdentity:d,original:to}),Ni=oe.completion,Ke?.onReceipt(oe)}catch(gt){return N=!0,_e=!0,L=!0,f("commit",te,gt,ce),Promise.resolve(!1)}let Rn=Ni.then(()=>{let gt=Kt===ge;return(Lt||!gt)&&(_e=!gt,L=!gt),fn!==null&&Kt===ge&&(Me=fn),!0},gt=>(_e=!0,L=!0,f("commit",te,gt,ce),!1));return Re.add(Rn),Rn.then(()=>Re.delete(Rn),()=>Re.delete(Rn)),m(Rn),Rn};if(le=o?.open(S.endUserId,te,K,ue),k!==void 0&&le?.bindOwner(k),le!==void 0)for(let Z=0;Z<ee.length;Z++)le.registerClientTool(S.clientTools[Z],ee[Z]);let Be=t.sessionCapture?.({endUserId:S.endUserId,sessionId:te}),Qe=t.contextMaterials?.({endUserId:S.endUserId,sessionId:te}),ce,Le=Promise.resolve(),De=async Z=>{await ce.settleResources();let Ie=Un(ce);if(Ie!==void 0){let Ce=await Ie.settleResources({timeoutMs:1/0});if(Ce.some(Ke=>Ke.status!=="completed"))throw new AggregateError(Ce.flatMap(Ke=>Ke.failures.map(dt=>dt.cause)),"Memory resources did not settle")}await Promise.all([...Re]),await d?.flush?.(),await k?.checkpoint(()=>Z?.()!==!1&&(ce.status()==="idle"||ce.status()==="ended")&&!_e&&!L&&(le?.ownershipStable()??!0)),Z?.()!==!1&&A!==void 0&&Se===void 0&&t.configuration!==void 0&&k!==void 0&&ce.status()==="idle"&&d?.initializeConfiguration!==void 0&&d.inspectConfiguration!==void 0&&d.commitConfiguration!==void 0&&(Se=await d.initializeConfiguration(S.endUserId,te,{model:Ue??null,thinking:ce.thinking()??null},k))},Ye=Z=>{let Ie=Le.then(()=>De(Z));return Le=Ie.then(()=>{},()=>{}),Ie},ot=3,Ot=Z=>Z instanceof Qt&&(Z.code==="owner_stale"||Z.code==="owner_corrupted"),Yt=(Z,Ie,Ce)=>{if(f("commit",te,Z,ce),Ot(Z)||Ce>=ot){ce.close();return}let Ke=async()=>{if(ce.status()==="running"){re??=Ke;return}await Ye(Ie).catch(dt=>Xt(dt,Ie,Ce+1))};re=Ke},Xt=(Z,Ie,Ce)=>{try{Yt(Z,Ie,Ce)}catch(Ke){f("commit",te,Ke)}};try{if(ce=h.create({...Ue!==void 0?{model:Ue}:{},...S.profile!==void 0?{profile:S.profile}:{},...S.labels!==void 0?{labels:S.labels}:{},...S.budget!==void 0?{budget:S.budget}:{},...ue!==void 0?{tools:[...ue]}:{},...$e!==void 0?{thinking:$e}:{}},{sessionId:te,...t.platform===void 0?{}:{trustedScope:{applicationScopeId:t.platform.appId,endUserId:S.endUserId,sessionId:te}},...Se===void 0?{}:{configurationThinking:Se.thinking},...t.platform?.memoryFor===void 0&&t.platform?.memoryPublicationFor===void 0?{}:{memoryScope:{sessionId:te,applicationScopeId:t.platform.appId,endUserId:S.endUserId}},...le!==void 0?{execution:le}:{},cwd:me,...ie!==void 0?{capabilityProfile:ie}:{},...G!==void 0?{assembleModel:G}:{},...lt!==void 0?{initialHistory:lt}:{},...d?.attachmentCheckpoints===!0?{attachmentPersistence:{scope:he({application:o?.options.applicationScopeId??t.platform?.appId??null,endUserId:S.endUserId,sessionId:te}),...Ge===void 0?{}:{checkpoint:Ge},...zt?{invalidateReferences:!0}:{},...o?.options.readAttachmentSource!==void 0&&d.attachmentSourceCheckpoints===!0?{verifySource:!0,...rt===void 0?{}:{sourceCheckpoint:rt}}:{}}}:{},...d?.memorySelectionCheckpoints===!0?{memorySelectionPersistence:{scope:he({application:o?.options.applicationScopeId??t.platform?.appId??null,endUserId:S.endUserId,sessionId:te}),...Tt===void 0?{}:{checkpoint:Tt}}}:{},...y!==void 0?{initialSeq:y}:{},...kt!==void 0&&(A!==void 0||S.budget!==void 0||o?.options.memoryFor!==void 0||t.platform?.memoryFor!==void 0||t.platform?.memoryPublicationFor!==void 0)?{usageSnapshot:kt.payload.snapshot}:{},...d===void 0||S.budget===void 0&&o?.options.memoryFor===void 0&&t.platform?.memoryFor===void 0&&t.platform?.memoryPublicationFor===void 0?{}:{persistBackgroundUsage:d.recordUsageSnapshot===void 0?null:Z=>{let Ie;try{Ie=d.recordUsageSnapshot(S.endUserId,te,Vs(Z),k)}catch(Ce){Ie=Promise.reject(Ce)}return m(Ie.catch(Ce=>{f("commit",te,Ce,ce)})),Ie}},...ee.length>0?{sessionTools:ee}:{},promptChannel:K.createPromptChannel(),askUser:K.createAskUser(),onTurnEnd:Z=>{Vt.title$=Qi(Z.history)??Vt.title$,ce.ownsArchiveHistoryCommit?.()===!0?de=Z:Te(Z.history,Z.rewritten,Z.costSnapshot,void 0,Z),k!==void 0&&(!Z.aborted||Z.abortReason==="budget_exceeded")&&Ye(Z.isCurrentTurn).catch(Ie=>Xt(Ie,Z.isCurrentTurn,0))}}),F=ce,H!==void 0)throw ce.close(),H}catch(Z){throw Z instanceof Hn?new Ze("validation_failed",We(tn.clientToolConflict,{name:Z.toolName})):Z}k!==void 0&&ce.bindOwner(k),B!==void 0&&(z=ce,gd(ce),B.assertCurrent()),x(S.endUserId,be),K.bindEmitter((Z,Ie)=>ce.pushControl(Z,Ie)),xe=!0,_!==void 0&&ce.pushBody({type:"session.forked",..._,sessionId:te},"server"),q!==void 0&&fe.push(q),X!==void 0&&fe.push(X),kt!==void 0&&(S.budget!==void 0||o?.options.memoryFor!==void 0||t.platform?.memoryFor!==void 0||t.platform?.memoryPublicationFor!==void 0)&&kt.staleMessages>0&&fe.push({code:"usage_snapshot_stale",message:We(wt.usageSnapshotStale,{count:kt.staleMessages})});for(let Z of fe)K.emitPlatformWarning(Z);fe.length=0;let kn=cT(be),xt=dT(be,gn),ln=t.configuration!==void 0&&k!==void 0&&d?.initializeConfiguration!==void 0&&d.inspectConfiguration!==void 0&&d.commitConfiguration!==void 0&&typeof ce.configure=="function";ln&&(A===void 0||Se!==void 0)&&(Se=await d.initializeConfiguration(S.endUserId,te,{model:Ue??null,thinking:ce.thinking()??null},k));let zn=async(Z,Ie={})=>{if(!ln)return{status:"rejected",reason:"unsupported"};let Ce=To(Z);if(!Ce)return{status:"rejected",reason:"invalid_configuration"};let Ke=ce.configurationRejection();return Ke||(await Le,await Promise.all([...Re]),ce.configure(async(dt,Kt)=>{let fn=await d.inspectConfiguration(S.endUserId,te,Ce,k);if(fn.status!=="ready")return fn;let Lt;if(Ce.changes.model!==void 0){try{if(t.configuration?.resolveModel!==void 0)Lt=await t.configuration.resolveModel({endUserId:S.endUserId,sessionId:te,model:Ce.changes.model,signal:Kt});else if(G!==void 0){let gt=G(Ce.changes.model,Qd=>{let tp=uo(Qd);tp&&ce.pushBody(tp,"provider")}),Pn=t.platform?.maxOutputTokens;Lt={client:gt.client,model:gt.model,...gt.contextWindowTokens===void 0?{}:{contextWindowTokens:gt.contextWindowTokens},...Pn===void 0&>.maxOutputTokens===void 0?{}:{maxOutputTokens:Math.min(Pn??1/0,gt.maxOutputTokens??1/0)}}}else return{status:"rejected",reason:"unsupported"}}catch(gt){let Pn=gt instanceof pt&>.code==="assembly_failed"?gt.cause:gt;if(Pn instanceof $m&&Pn.alias===Ce.changes.model||Pn instanceof Km&&Ce.changes.model.includes("/")&&Pn.ref===Ce.changes.model)return{status:"rejected",reason:"invalid_configuration"};throw gt}Lt!==void 0&&t.platform?.maxOutputTokens!==void 0&&(Lt={...Lt,maxOutputTokens:Math.min(t.platform.maxOutputTokens,Lt.maxOutputTokens??1/0)})}Kt.throwIfAborted(),await Ie.beforeCommit?.(),Kt.throwIfAborted();let to=Object.hasOwn(Ce.changes,"thinking")?Ce.changes.thinking:fn.configuration.thinking,Ni=dt(Lt,to??void 0);if(Ni.status==="rejected")return Ni;let Rn;try{Rn=await d.commitConfiguration(S.endUserId,te,Ce,k,()=>!Kt.aborted&&Ni.isCurrent())}catch(gt){let Pn;try{Pn=await d.inspectConfiguration(S.endUserId,te,Ce,k)}catch(Qd){throw ce.close(),new AggregateError([gt,Qd],"Configuration outcome is unknown")}if(Pn.status!=="replayed")throw Pn.status!=="ready"&&ce.close(),gt;Rn=Pn}return(Rn.status==="changed"||Rn.status==="replayed")&&(Se=Rn.configuration,Ni.publish()),Rn},Ie))},Vt=new Qf({configuration:()=>Se,configure:zn,...k===void 0?{}:{owner:k,checkpointOwner:De,settleOwner:async()=>{try{await Le;let Z=re;re=void 0,Z!==void 0&&await Z(),await Le,await Promise.all([...Re]),await d?.flush?.();try{await k.release()}catch{}}finally{C!==void 0&&(clearInterval(C),C=void 0)}}},sessionId:te,endUserId:S.endUserId,createdAt:gn,driver:ce,bridge:K,...wn!==void 0?{initialTitle:wn}:{},...kn!==void 0?{platformAudio:kn}:{},...xt!==void 0?{media:xt}:{},persistence:lT({checkpointStore:b,checkpointsOptions:t.checkpoints,cwd:me,now:a,commitRewritten:Z=>Te(Z,!0)}),resolveCwd:(Z,Ie)=>{let Ce=Jf(t,S.endUserId);return so({requested:Z,fallback:Ie,...Ce!==void 0?{policy:Ce}:{}})},...d?.recordCwdChange!==void 0?{onCwdChanged:Z=>{m(d.recordCwdChange.call(d,S.endUserId,te,Z,k).catch(Ie=>f("commit",te,Ie,ce)))}}:{}});bb(Vt,()=>Pe);let xn=Un(ce);xn&&Zr(Vt,xn);let bt=hr(ce);bt&&Bd(Vt,{capability:()=>bt.capability(),async prepare(Z){let Ie=await bt.prepare(Z);return Zr(Vt,Ie),Ie}}),(xn?.management!==void 0||bt!==void 0)&&(W=!0,ib(Vt,async(Z,Ie={})=>{if(k!==void 0&&k.assertIdle===void 0)throw new at("unsupported_capability");let Ce=ce.configurationRejection();if(Ce)throw new at(Ce.reason==="turn_running"?"busy":"source_unavailable");await Le,await Promise.all([...Re]);let Ke=await ce.configure(async(dt,Kt)=>{try{await k?.assertIdle?.()}catch(Lt){throw Lt instanceof Qt&&["reconciliation_required","owner_busy","owner_stale"].includes(Lt.code)?Object.assign(new at(Lt.code==="owner_stale"?"stale_generation":"busy"),{cause:Lt}):Lt}Kt.throwIfAborted();let fn=bt===void 0?Un(ce):await hr(Vt).prepare(Kt);if(fn?.management===void 0)throw new at("unsupported_capability");return Kt.throwIfAborted(),fn.executeManagedCommand(Z,{...Ie,signal:Kt})},Ie);if(Ke.status==="rejected")throw new at(Ke.reason==="turn_running"?"busy":"source_unavailable");return Ke}));let At=Vt.beforeCompactHook();if(At!==void 0&&ce.bindBeforeCompact(At),d!==void 0&&(typeof ce.bindArchiveSourceReadCheck=="function"&&ce.bindArchiveSourceReadCheck(()=>Re.size===0&&se&&!L&&!_e&&!N),typeof ce.bindArchivePersistenceBarrier=="function"&&ce.bindArchivePersistenceBarrier(async()=>{for(;Re.size>0;)await Promise.all([...Re]);if(!se||L||_e)throw new Error("Archive binding requires confirmed legacy history")}),typeof ce.bindArchiveHistoryPort=="function"&&typeof ce.archiveHistoryObservation=="function"&&typeof ce.bindArchivePersistenceBarrier=="function")){let Z=Object.freeze({storeIdentity:d,latestCommit:()=>oe,read(){let Ie=ce.archiveHistoryObservation(),Ce=Me,Ke=Re.size===0&&se&&!L&&!_e&&Ce!==null&&Ce.observation.localHistoryGeneration===Ie.localHistoryGeneration&&Ce.observation.sourceSnapshotDigest===Ie.sourceSnapshotDigest;return Object.freeze({observation:Ie,confirmedCommit:Ke?Object.freeze({commitId:Ce.commitId,observation:Object.freeze({...Ce.observation})}):null})}});typeof ce.bindArchiveHistoryCommit=="function"&&ce.bindArchiveHistoryCommit(Ie=>{if(!qe)throw new Error("Archive original Store observation is not enabled");let Ce,Ke=de?.history===Ie.history?de.costSnapshot:void 0,dt=de?.history===Ie.history?de:void 0;de=void 0;let Kt=Te(Ie.history,Ie.rewritten,Ke,{commitId:Ie.commitId,observation:Ie.observation,onReceipt:Lt=>{Ce=Lt}},dt);if(Ce===void 0||Kt===void 0)throw new Error("Archive original Store receipt unavailable");let fn=Kt.then(Lt=>{if(!Lt)throw new Error("Archive original Store failed")});return fn.catch(()=>{}),{receipt:Ce,completion:fn}}),ce.bindArchiveHistoryPort(Z,async()=>{if(qe&&Z.read().confirmedCommit!==null)return;if(qe=!0,!await Te(ce.historySnapshot().messages,!0)||Z.read().confirmedCommit===null)throw new Error("Archive binding requires confirmed legacy history")},{detach(){if(Re.size!==0||!se||L||_e||N)throw new Error("Archive original Store remains unsettled");qe=!1},assertDetached(){if(qe||de!==void 0)throw new Error("Archive original Store responsibility was not released")}}),typeof ce.bindArchiveColdHistory=="function"&&ce.bindArchiveColdHistory(Ie=>{let Ce=hh(Ie,{storeIdentity:d,sessionId:te});if(Re.size!==0||!se||L||_e||N||ge!==0||oe!==null||de!==void 0)throw new Error("Archive cold history requires an untouched, settled original Store");let Ke=ce.archiveHistoryObservation(),dt=Ce.details.runtime===void 0?0:Ce.details.history.observation.localHistoryGeneration;if(Ke.localHistoryGeneration!==dt||Ke.sessionId!==Ce.details.history.observation.sessionId||Ke.sourceSnapshotDigest!==Ce.details.history.observation.sourceSnapshotDigest)throw new Error("Archive cold history differs from the confirmed Store");Ce.assertCurrent(),Me=Object.freeze({commitId:Ce.details.history.commitId,observation:Ke}),qe=!0})}if(Be!==void 0||Qe!==void 0)try{Be!==void 0&&ce.bindSessionCapture(Be),Qe!==void 0&&ce.bindContextMaterials(Qe)}catch(Z){throw ce.close(),await ce.settleResources(),Z}if(d?.recordSeqWatermark!==void 0){let Z=d.recordSeqWatermark;ce.bindOnEnded(Ie=>{le?.close(),ne&&m(Z.call(d,S.endUserId,te,{lastSeq:Ie,sealed:!0},k).catch(Ce=>f("commit",te,Ce,ce)))})}let ht=be===void 0?void 0:be.sessionRetentionDays??null;if(d!==void 0&&(!Fe||Y!==void 0&&Nt===void 0||ve||ht!==void 0&&(ht===null?yn!==void 0:ht!==yn))){se=!1;let Z={sessionId:te,...Y!==void 0?{platformSessionId:t.cacheHost!==void 0&&Fe&&Nt!==void 0?Nt:Y}:{},...k===void 0?{}:{owner:k},cwd:me,...ht!==void 0?{retentionDays:ht}:{}};if(B!==void 0||ve){if(B?.assertCurrent(),j=await(B?.mode==="fresh"&&!P?Jl(d,S.endUserId,Z):d.create(S.endUserId,Z)),B?.assertCurrent(),ve&&t.cacheHost===void 0&&j.platformSessionId!==Y)throw new Error("Platform runtime metadata unconfirmed");se=!0}else{let Ie=d.create(S.endUserId,Z).then(()=>{se=!0},Ce=>f("create",te,Ce,ce));Re.add(Ie),Ie.then(()=>Re.delete(Ie),()=>Re.delete(Ie)),m(Ie)}}if(t.cacheHost!==void 0&&Y!==void 0&&d!==void 0)try{if(t.cacheHost.registerSession({endUserId:S.endUserId,sessionId:te,runtimeSessionId:Y,driver:ce,store:d,configurationRefreshRequired:Fe&&Nt===Y}),await t.cacheHost.restoreSession(S.endUserId,te),Fe&&Nt!==Y||t.cacheHost.needsStoreRuntime(S.endUserId,te,Y)){let Z=await d.create(S.endUserId,{sessionId:te,platformSessionId:Y,...k===void 0?{}:{owner:k}});if(B?.assertCurrent(),B!==void 0&&(j=Z),Z.platformSessionId!==Y)throw new Error("Cache host runtime metadata unconfirmed");t.cacheHost.confirmStoreRuntime(S.endUserId,te,Y)}}catch(Z){throw ce.close(),await ce.settleResources(),Z}if(B!==void 0){if(j===void 0)throw new Error("Archive factory registration is not confirmed");ne=!0,B.registered(j),nv($,S,Vt,ce,j)}if(le!==void 0){let Z=le;Z.attach(()=>ce.status()==="idle"),d?.recordSeqWatermark===void 0&&ce.bindOnEnded(()=>Z.close())}let $t=d?.runtimeCheckpoints===!0?ce.historySnapshot().messages:void 0;return k!==void 0&&d?.runtimeCheckpoints===!0&&ce.bindRuntimeRecovery(async(Z,Ie)=>{if(await Promise.all([...Re]),_e||L||!(le?.ownershipStable()??!0))throw new Qt("reconciliation_required");let Ce=$t!==void 0&&($t.length>Z.query.messages.length||$t.some((Ke,dt)=>he(Ke)!==he(Z.query.messages[dt])));await d.commit(S.endUserId,te,Z.query.messages,{owner:k,rewritten:Ce,lastSeq:ce.lastSeq(),runtimeCheckpoint:Z,...Ie===void 0?{}:{usageSnapshot:Vs(Ie)},...d.attachmentCheckpoints===!0?{attachmentCheckpoint:ce.attachmentCheckpoint(Z.query.messages)}:{},...d.attachmentSourceCheckpoints===!0?{attachmentSourceCheckpoint:ce.attachmentSourceCheckpoint(Z.query.messages)}:{},...d.memorySelectionCheckpoints===!0?{memorySelectionCheckpoint:ce.memorySelectionCheckpoint()}:{}}),$t=structuredClone(Z.query.messages)},A),A!==void 0&&(B!==void 0?ce.prepareArchiveRuntimeRecovery():ce.resumeRuntime()),S.prompt!==void 0&&ce.send(S.prompt),{handle:Vt,resumed:Fe}}catch(ue){C!==void 0&&clearInterval(C);try{await k?.release()}catch{}if(le?.close(),z!==void 0)try{z.close(),await z.settleResources()}catch(ie){throw new AggregateError([ue,ie],"Archive factory creation and driver cleanup failed")}throw ue instanceof Qt?new Ze(ue.code==="owner_corrupted"?"store_corrupted":ue.code==="reconciliation_required"?"resume_unavailable":"overloaded",ue.message,{retryAfterMs:1e3,detail:{reason:ue.code}}):ue}finally{U?.()}},flush:g,sweepRetention:S=>M({activeSessionIds:S.activeSessionIds})};ev($,d);let D=S=>({sessionId:S.sessionId,createdAt:S.createdAt,updatedAt:S.updatedAt,...S.title!==void 0?{title:S.title}:{},...S.lastSeq!==void 0?{lastSeq:S.lastSeq}:{}}),J=d!==void 0?{async list(S){return(await d.list(S)).map(D)},async getMeta(S,k){let A=d.getMeta!==void 0?await d.getMeta(S,k):(await d.list(S)).find(C=>C.sessionId===k);return A==null?null:D(A)},async getHistory(S,k){let A=await d.get(S,k);return A===null?null:Ps(A.messages).messages},...d.getHistoryPage!==void 0?{getHistoryPage:(S,k,A)=>d.getHistoryPage.call(d,S,k,A)}:{}}:void 0;return{factory:$,flush:g,sweepSessionRetention:M,...J!==void 0?{storeReader:J}:{},...v!==void 0?{upstreamStats:v}:{}}}function nT(t){if(t!==void 0)return{policy:{maxAgeDays:t.maxAgeDays??Xf,...t.maxPerEndUser!==void 0?{maxPerEndUser:t.maxPerEndUser}:{},...t.maxBytes!==void 0?{maxBytes:t.maxBytes}:{}},sweepIntervalMs:t.sweepIntervalMs??Zf}}function iT(t,e){if(t===void 0)return;if(t.store!==void 0)return t.store;let n={...t.max!==void 0?{max:t.max}:{},...t.retention!==void 0?{retention:t.retention}:{}};if(t.dir!==void 0)return ps({dir:t.dir,...n});let i=e?.sessionDirOf;if(e===void 0||i===void 0)throw new Error('createAgentSessionFactory "checkpoints" requires one of: checkpoints.store, checkpoints.dir, or a session store exposing sessionDirOf (co-located <sessionDir>/checkpoints)');return ps({rootOf:(o,s)=>hc(i.call(e,o,s)),...n})}function Jf(t,e){let n=t.cwdPolicy;if(n!==void 0)return"resolve"in n?{resolve:(i,o)=>n.resolve(i,{...o,endUserId:e})}:n}async function rT(t,e){let n=Jf(e,t.endUserId),i=await so({...t.cwd!==void 0?{requested:t.cwd}:{},fallback:e.cwd,...n!==void 0?{policy:n}:{}});if(i.ok)return i.cwd;let o=i.detail??i.reason;throw i.reason==="not_allowed"?new Ze("cwd_not_allowed",`cwd not allowed: ${o}`,{params:{detail:o}}):new Ze("cwd_invalid",`cwd invalid (${i.reason}): ${o}`,{params:{reason:i.reason,detail:o}})}async function oT(t){return Jp(await so({requested:t.requested,fallback:t.fallback,...t.policy!==void 0?{policy:t.policy}:{}}),{onResume:!0})}async function sT(t,e,n){if(t===void 0||t===e)return{cwd:e};if(n.mode==="current")return{cwd:e,warning:{code:"cwd_mismatch_on_resume",message:We(wt.cwdMismatchOnResume,{stored:t,current:e})}};let i=await oT({requested:t,fallback:e,policy:n.policy});if("error"in i)throw new Ze("cwd_unavailable",`stored cwd unavailable (${i.reason}): ${i.detail??t}`,{params:{cwd:t,reason:i.reason}});return{cwd:i.cwd,warning:{code:"cwd_mismatch_on_resume",message:We(wt.cwdMismatchOnResumeStored,{stored:t,current:e})}}}async function aT(t){let{init:e,fork:n,checkpointStore:i,store:o}=t;if(i===void 0)throw new Ze("checkpoints_not_wired","checkpoint store is not wired (fork needs one)");let s;try{s=await i.get(e.endUserId,n.sessionId,n.checkpointId)}catch(f){throw f instanceof vn&&f.code==="CHECKPOINT_INVALID"?new Ze("store_corrupted",f.message):f}if(s===null||s.sessionId!==n.sessionId)throw new Ze("fork_source_not_found",`fork source not found: session ${n.sessionId} / checkpoint ${n.checkpointId}`,{params:{sessionId:n.sessionId,checkpointId:n.checkpointId}});let a=Ps(s.messages).messages,d=Qi(a);if(o===void 0)return{sessionId:e.sessionId??$d(),history:a,title:d};let c={sourceSessionId:n.sessionId,checkpoint:s,...e.sessionId!==void 0?{newSessionId:e.sessionId}:{},cwd:t.cwd,...d!==void 0?{title:d}:{}},l;try{o.fork!==void 0?l=(await o.fork(e.endUserId,c)).sessionId:(l=c.newSessionId??$d(),await o.create(e.endUserId,{sessionId:l,cwd:t.cwd,...d!==void 0?{title:d}:{}}),await o.commit(e.endUserId,l,a,{rewritten:!1}))}catch(f){throw f instanceof et?new Ze("store_corrupted",f.message):f}return{sessionId:l,history:a,title:d}}function dT(t,e){if(!t?.capabilities||!t.platformTools)return;let n=t.capabilities.platform,i=po({platformModels:t.platformTools.platformModels})?.platformModels;if(i)return{capabilities:{imageGen:n.imageGen,videoGen:n.videoGen,speechToText:n.speechToText,textToSpeech:n.textToSpeech},models:i,sampledAt:e}}function cT(t){let e=t?.capabilities,n=t?.platformTools;if(!(e===void 0||n===void 0))return{capabilities:{speechToText:e.platform.speechToText,textToSpeech:e.platform.textToSpeech},request:(i,o,s)=>Uu({baseUrl:n.baseUrl,face:i,payload:o,token:Wi,fetchImpl:n.fetchImpl,...s!==void 0?{signal:s}:{}})}}function lT(t){return{...t.checkpointStore!==void 0?{checkpoints:{store:t.checkpointStore,autoBeforeCompact:t.checkpointsOptions?.autoBeforeCompact??!0}}:{},cwd:t.cwd,commitRewritten:t.commitRewritten,now:t.now}}var uT={};Lb(uT,{ADJUDICATOR_UNAVAILABLE_CODE:()=>$f,ADJUDICATOR_UNAVAILABLE_MESSAGE:()=>Kf,AGENT_SESSION_CONTRACT_VERSION:()=>eg,AUDIO_INPUT_PATTERN:()=>uu,AUDIO_LANGUAGE_MAX_CHARS:()=>pu,AUDIO_MAX_BODY_BYTES:()=>Mo,AUDIO_PROMPT_MAX_CHARS:()=>hu,AUDIO_ROUTE_SEGMENTS:()=>ng,AUDIO_SPEECH_FORMATS:()=>fu,AUDIO_SPEECH_INPUT_MAX_CHARS:()=>gu,AUDIO_VOICE_MAX_CHARS:()=>mu,AgentSessionBridge:()=>eo,AgentSessionCreateError:()=>Ze,AgentSessionStoreError:()=>et,AppTokenMintError:()=>Cn,AudioSpeechBodySchema:()=>ka,AudioTranscriptionsBodySchema:()=>wa,BUILTIN_CAPABILITY_PROFILES:()=>Yf,CHECKPOINT_EXPORT_CONTENT_TYPE:()=>ba,CHECKPOINT_IMPORT_MAX_BODY_BYTES:()=>Po,CHECKPOINT_IMPORT_SEGMENT:()=>Sa,CHECKPOINT_LABEL_MAX_CHARS:()=>Ji,CLIENT_TOOL_NAME_PATTERN:()=>iu,COMPACT_INSTRUCTIONS_MAX_CHARS:()=>cu,CONTROL_FRAME:()=>sn,CONTROL_FRAME_TS_KEY:()=>da,CheckpointBodySchema:()=>ga,CheckpointOptionSchema:()=>lu,ClientToolDeclSchema:()=>Co,ClientToolNameConflictError:()=>Hn,CompactBodySchema:()=>ha,CreateSessionBodySchema:()=>la,DEFAULT_BUNDLE_CACHE_TTL_MS:()=>_i,DEFAULT_PROCESS_GUARD_DRAIN_TIMEOUT_MS:()=>lh,DEFAULT_SESSION_MAX_AGE_DAYS:()=>Xf,DEFAULT_SESSION_RETENTION_SWEEP_INTERVAL_MS:()=>Zf,DEFAULT_SSE_FLUSH_SLICE_MS:()=>Su,DEFAULT_SSE_HEARTBEAT_MS:()=>vu,DEFAULT_SSE_RETRY_MS:()=>bu,DEFAULT_WEBHOOK_SIGNATURE_VERSIONS:()=>Iu,DEVELOPER_ONLY_ADJUDICATOR_WARNINGS:()=>yf,END_USER_ID_PATTERN:()=>nu,EXCLUDE_TOKEN_PATTERN:()=>ru,EventRingBuffer:()=>Ri,IMAGE_MIME_PATTERN:()=>aa,ImageGenDataSchema:()=>Yd,LOG_EVENT:()=>Xe,LOG_EVENT_NAMES:()=>ah,MemorySessionEventLog:()=>Or,MessageBlockSchema:()=>ou,MessagesBodySchema:()=>ua,OBSERVABILITY_PATHS:()=>En,OPENMETRICS_CONTENT_TYPE:()=>As,PERMISSION_DENY_REASON:()=>du,PROCESS_GUARD_POLICIES:()=>Qs,PROCESS_GUARD_STACK_MAX_CHARS:()=>ch,PermissionReceiptSchema:()=>fa,QuestionReceiptSchema:()=>pa,REPLAY_GAP_EVENT:()=>An,REQUEST_ID_HEADER:()=>Oo,ReceiptContentSchema:()=>au,RestoreBodySchema:()=>ya,SECRET_WARNING_VALUE:()=>Gf,SEGMENTED_STORE_DEFAULTS:()=>cc,SERVER_MESSAGE_KEY:()=>ae,SERVER_MESSAGE_KEYS:()=>sh,SERVE_RUNTIME_ENV:()=>us,SERVE_RUNTIME_ENV_NAMES:()=>Ab,SESSION_ID_SHARD_MAX:()=>Wr,SESSION_RECOVERY_VERSION:()=>_c,SESSION_STORE_CORE_ENV:()=>Ql,ServeSessionDriver:()=>di,SetCwdBodySchema:()=>va,SpeechDataSchema:()=>ec,SseTransport:()=>_r,StoreError:()=>Wn,TANSR_READY_FRAME_VERSION:()=>bg,TANSR_READY_PREFIX:()=>Bo,TOKEN_CHECK_UNAVAILABLE_REASON:()=>cv,TOKEN_INVALIDATING_CODES:()=>Wo,TURN_END_NOTIFY_SIGNATURE_HEADER:()=>ca,ToolParameterSpecSchema:()=>Eo,ToolResultReceiptSchema:()=>Cr,TranscriptDataSchema:()=>Zd,TurnEndNotifier:()=>Mr,V2_ASSEMBLY_MESSAGE_KEY:()=>tn,V2_ASSEMBLY_MESSAGE_KEYS:()=>sv,V2_CTX_PERSIST_MESSAGE_KEY:()=>wt,V2_CTX_PERSIST_MESSAGE_KEYS:()=>Ky,V2_ERROR_CODE:()=>Oe,V2_LIMITS:()=>je,V2_ROUTE_TABLE:()=>Yi,V2_SESSION_ACTIONS:()=>Ta,VideoGenDataSchema:()=>Xd,WEBHOOK_SIGNATURE_VERSIONS:()=>xg,alignHistoryPage:()=>Io,appliedRuntimeEnvByGroup:()=>Cb,assertSessionIdShard:()=>ts,buildRemoteTool:()=>Gd,countSpeechCharacters:()=>tl,createAgentSessionFactory:()=>Ub,createAppTokenMinter:()=>wd,createBundleCache:()=>ar,createChaosBlobStore:()=>Dc,createFsBlobStore:()=>Oc,createMemoryBlobStore:()=>Mc,createMetricsRegistry:()=>_p,createPlatformServeSessionFactory:()=>Vd,createPlatformSessionAssembler:()=>pv,createServeAgentSessionStore:()=>Jh,createServeCheckpointStore:()=>ps,createServeLogger:()=>dh,createUpstreamGovernor:()=>Jm,defaultMetrics:()=>wi,emitReadyFrame:()=>Ma,encodeAgentStreamFrame:()=>Ba,encodeKernelEventFrame:()=>Ao,encodeSseComment:()=>sa,encodeSseFrame:()=>on,endUserKeyOf:()=>Wt,extractBearerToken:()=>Yl,formatReadyFrame:()=>Ru,getRequestContext:()=>ii,installProcessGuards:()=>fh,isAuthorized:()=>ra,isControlFrameType:()=>Er,isExcluded:()=>_o,isLoopbackHost:()=>Pa,isSessionHistoryStore:()=>lc,kernelMetricsFor:()=>Es,negotiateLocale:()=>rp,parseExcludeTokens:()=>ma,parseHistoryPageQuery:()=>Zs,parseMediaArtifact:()=>tc,parseReadyFrame:()=>wg,planSpeechInput:()=>nl,processGuardRecordOf:()=>uh,registerBuiltinLocales:()=>np,rejectionCodeOf:()=>_a,renderOpenMetrics:()=>Ts,resolvePlatformAdjudicator:()=>Wd,resolveRequestId:()=>Ca,resolveServeRuntimeOptions:()=>Eb,resolveUpstreamFetch:()=>Kr,routeTemplateOf:()=>Ea,runIdleCompaction:()=>ud,runStorageConformance:()=>Bc,serveMetricsFor:()=>Qn,sessionIdShardOf:()=>ov,sessionIdShardPrefix:()=>hf,sessionTitleOf:()=>Qi,setLocale:()=>ip,shardedSessionId:()=>yd,signWebhookDelivery:()=>Tu,sliceHistoryPage:()=>Kn,slowSubscriberGapFrame:()=>Pr,startServer:()=>Rb,sumRingStats:()=>xa,toCheckpointMetaView:()=>yr,toStoreError:()=>dc,tokenMatches:()=>Xl,translateMintError:()=>vf,translateUpstreamAssemblyErrors:()=>kd,upstreamAgentOptions:()=>Ym,upstreamOriginOf:()=>Qm});import{mkdirSync as fT,statSync as pT}from"node:fs";import ms from"node:path";var ep=class extends Error{code="memory_project_mismatch";constructor(){let e=Ks.memoryProjectMismatch;super(`memory_project_mismatch: ${vr(e)}`),this.name="SessionMemoryProjectMismatchError"}};function Kd(t,e){try{let n=pT(t);return e==="dir"?n.isDirectory():n.isFile()}catch{return!1}}function vF(t){let e=Zm(t.env),n=new Set,i;return(o,s)=>{let a;if(s!==void 0){a=ao(o);let d=ao(s);if(a.key!==d.key)throw new ep}if(nh()!=="deny"&&(t.autoMemoryEnabled?.()??t.autoMemory!==void 0))try{if(a??=ao(o),t.autoMemory!==void 0&&t.autoMemoryEnabled===void 0&&(i??=ao(t.cwd),i.key===a.key))return{...t.autoMemory,injection:{...t.autoMemory.injection},projectKey:a.key,canonicalRoot:a.canonicalRoot};let d=ms.join(e,"projects",a.key,"memory");if(!n.has(a.key)||!Kd(d,"dir")){fT(d,{recursive:!0});let f=ms.join(d,ih);Kd(f,"file")||oh(f,JSON.stringify({path:a.canonicalRoot,createdAt:new Date().toISOString()},null,2)+`
|
|
37
|
+
`),n.size>=256&&n.clear(),n.add(a.key)}try{rh(e,a.key,d)}catch(f){t.onMemoryNotice?.({key:Ks.autoMemoryLegacyMergeFailed,params:{detail:f instanceof Error?f.message:String(f)}})}let c=d,l=op(e);if(l!==null&&!Kd(ms.join(d,"MEMORY.md"),"file")){let f=ms.join(l,"projects",a.key,"memory");Kd(f,"dir")&&(c=f)}return{dir:d,readDir:c,...c!==d?{legacyReadDir:c}:{},projectKey:a.key,canonicalRoot:a.canonicalRoot,injection:{indexPath:ms.join(c,"MEMORY.md"),present:!1,bytes:0,lines:0,truncated:!1}}}catch(d){t.onMemoryNotice?.({key:Ks.autoMemorySetupFailed,params:{detail:d instanceof Error?d.message:String(d)}});return}}}function SF(t,e,n){let i=e.usageObserver!==void 0?{...t,onRequestMeasured:o=>{t.onRequestMeasured?.(o),e.usageObserver?.(o)}}:t;return n!==void 0?{...i,onCompactionFinished:o=>{i.onCompactionFinished?.(o);let s=o.outcome;o.agentId===void 0&&o.mechanism===void 0&&s?.ok===!0&&n.noteCompactionSummary(s.summaryText)}}:i}export{ja as a,Ug as b,Lg as c,f1 as d,p1 as e,at as f,lr as g,w1 as h,k1 as i,id as j,Dy as k,af as l,Lk as m,vT as n,ct as o,bT as p,ST as q,Gb as r,Wb as s,Qt as t,Kn as u,OT as v,et as w,Wt as x,Qi as y,To as z,Ir as A,$l as B,Zb as C,eS as D,oS as E,JT as F,YT as G,XT as H,Jh as I,ZT as J,Wk as K,di as L,WB as M,VB as N,md as O,$B as P,yd as Q,ob as R,Rb as S,VN as T,$N as U,KN as V,Eb as W,Cb as X,Hn as Y,Ub as Z,uT as _,ep as $,vF as aa,SF as ba};
|
|
38
|
+
//# sourceMappingURL=tansr-chunk-TZJHQ3TT.mjs.map
|