@tansr/cli 0.9.0 → 0.10.0
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/NOTICE +1 -1
- package/package.json +1 -1
- package/tansr-artifacts.json +1291 -0
- package/tansr-bg-FHDDUMK4.mjs +5 -0
- package/tansr-chunk-2GVQN2VL.mjs +6 -0
- package/tansr-chunk-2HKJ4JJS.mjs +21 -0
- package/tansr-chunk-2QKLANZQ.mjs +7 -0
- package/tansr-chunk-4OSB7HBB.mjs +37 -0
- package/tansr-chunk-5VWLEU5D.mjs +4 -0
- package/tansr-chunk-5YXIDPAQ.mjs +67 -0
- package/tansr-chunk-6NUB6YQJ.mjs +25 -0
- package/tansr-chunk-A5EC3Z2Z.mjs +8 -0
- package/tansr-chunk-AMMPDY4V.mjs +5 -0
- package/tansr-chunk-B3GJDJ7R.mjs +5 -0
- package/tansr-chunk-BX7CF5RQ.mjs +25 -0
- package/tansr-chunk-C7GGA5ID.mjs +5 -0
- package/tansr-chunk-DIT3PBNB.mjs +5 -0
- package/tansr-chunk-F5STVU7J.mjs +5 -0
- package/tansr-chunk-F7C6ITED.mjs +5 -0
- package/tansr-chunk-G5YDZOSH.mjs +38 -0
- package/tansr-chunk-HRKJLVKC.mjs +7 -0
- package/tansr-chunk-I3TOVAA6.mjs +5 -0
- package/tansr-chunk-IHFZ4MW7.mjs +5 -0
- package/tansr-chunk-JOAFKQNW.mjs +5 -0
- package/tansr-chunk-M774GK3P.mjs +6 -0
- package/tansr-chunk-MKOKKJTO.mjs +5 -0
- package/tansr-chunk-MWHLITGY.mjs +11 -0
- package/tansr-chunk-MX3N5PNJ.mjs +12 -0
- package/tansr-chunk-NKZP22Y6.mjs +8 -0
- package/tansr-chunk-NROI7AG5.mjs +5 -0
- package/tansr-chunk-O32ZFMNV.mjs +6 -0
- package/tansr-chunk-OKAA4BJC.mjs +5 -0
- package/tansr-chunk-PIET7WB3.mjs +5 -0
- package/tansr-chunk-PQHOHOTR.mjs +22 -0
- package/tansr-chunk-PQNOMC4A.mjs +5 -0
- package/tansr-chunk-QEKVLX7W.mjs +5 -0
- package/tansr-chunk-QHEQQ2JB.mjs +9 -0
- package/tansr-chunk-QWGSXFEJ.mjs +7 -0
- package/tansr-chunk-RRAMVVYF.mjs +5 -0
- package/tansr-chunk-RS3LZ6KA.mjs +6 -0
- package/tansr-chunk-RVSBSUXE.mjs +5 -0
- package/tansr-chunk-S3KHAGOR.mjs +5 -0
- package/tansr-chunk-SJFDQLLC.mjs +5 -0
- package/tansr-chunk-T2BVA5NV.mjs +23 -0
- package/tansr-chunk-UIBBDNRB.mjs +279 -0
- package/tansr-chunk-VJGAX34A.mjs +5 -0
- package/tansr-chunk-WMHXOCGD.mjs +29 -0
- package/tansr-chunk-WT5YKFE7.mjs +12 -0
- package/tansr-chunk-WW5ZPL6Q.mjs +5 -0
- package/tansr-chunk-XAQNKJIC.mjs +4 -0
- package/tansr-chunk-XAR42OOH.mjs +7 -0
- package/tansr-chunk-XXBNISJJ.mjs +7 -0
- package/tansr-chunk-Y4DBYZRC.mjs +5 -0
- package/tansr-chunk-YOQS3FJQ.mjs +11 -0
- package/tansr-chunk-Z6RSXE57.mjs +35 -0
- package/tansr-chunk-ZGQJIXK7.mjs +5 -0
- package/tansr-chunk-ZQ3ZK7IL.mjs +37 -0
- package/tansr-ink-devtools-stub-GTR5M7WR.mjs +4 -0
- package/tansr-portal-FWLKNJM2.mjs +5 -0
- package/tansr-render-RTEKXH54.mjs +6 -0
- package/tansr-run-acp-entry-OYTDDWDR.mjs +63 -0
- package/tansr-run-approvals-entry-53SR25ZU.mjs +12 -0
- package/tansr-run-auth-entry-QFMRITYM.mjs +36 -0
- package/tansr-run-doctor-DO6CXMRK.mjs +10 -0
- package/tansr-run-headless-entry-7TNISK4Y.mjs +78 -0
- package/tansr-run-init-entry-EJ4UX6S7.mjs +5 -0
- package/tansr-run-logout-entry-YJMC6FYS.mjs +5 -0
- package/tansr-run-mcp-serve-entry-M5N7JSAX.mjs +14 -0
- package/tansr-run-orchestrate-entry-MFDKPE4I.mjs +11 -0
- package/tansr-run-org-entry-TGWBHE55.mjs +17 -0
- package/tansr-run-policy-entry-E3XZEYGV.mjs +16 -0
- package/tansr-run-profile-entry-R2KK52TF.mjs +14 -0
- package/tansr-run-serve-entry-JVHHZEKM.mjs +99 -0
- package/tansr-run-sessions-entry-PZQIF7KY.mjs +23 -0
- package/tansr-run-update-entry-GOW6DQH3.mjs +5 -0
- package/tansr-sqlite-event-store-UQLSSZKP.mjs +26 -0
- package/tansr-sqlite-spool-implementation-LHEIRSUX.mjs +29 -0
- package/tansr-src-KOEPYVXX.mjs +5 -0
- package/tansr-src-NSNVE7OD.mjs +206 -0
- package/tansr-startup-account-WI54Z7UU.mjs +7 -0
- package/tansr-startup-model-2MIOO25G.mjs +6 -0
- package/tansr-tui-LUXKR56D.mjs +75 -0
- package/tansr-undici.cjs +49 -0
- package/tansr.mjs +2 -1180
- package/tansrd.mjs +772 -0
|
@@ -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 ul}from"./tansr-chunk-MWHLITGY.mjs";import{$ as ol,Aa as cl,Ca as ll,F as Yc,I as Xc,J as Zr,K as ii,M as Vn,O as Zc,P as el,S as tl,X as nl,Y as en,Z as il,_ as rl,aa as Cs,ja as Op,la as sl,oa as al,v as Mp,za as dl}from"./tansr-chunk-BX7CF5RQ.mjs";import{a as Bp}from"./tansr-chunk-QHEQQ2JB.mjs";import{Oa as Sp,Ra as wp,Xa as kp,Ya as xp,i as bp}from"./tansr-chunk-5YXIDPAQ.mjs";import{a as yp}from"./tansr-chunk-Y4DBYZRC.mjs";import{a as le,b as Rp,c as at,d as Ip,e as Tp,f as jn,g as Nn,h as As,i as Ap,j as Cp,k as Ep,l as _p,w as Pp}from"./tansr-chunk-Z6RSXE57.mjs";import{A as Qc,B as Jc,a as Dn,b as Ts,c as cr,d as Gc,e as Wc,f as Vc,g as $c,h as Bi,j as Kc,k as Vr,l as lr,m as vp,o as $r,p as Kr,q as Qr,r as Jr,s as Yr,t as Xr,u as yt}from"./tansr-chunk-PQHOHOTR.mjs";import{$ as zf,$a as oc,$c as _c,Ac as xm,Bc as Ic,Bd as ks,Be as Dc,C as Qd,Cc as Tc,Db as Fr,Dc as Rm,De as Xm,E as Jd,Eb as ds,Ee as Zm,Fb as dc,Fe as ep,Gb as cc,Gc as Im,Gd as Hm,Ge as tp,H as ar,Ha as Zf,Hb as lc,Ib as uc,Ic as Tm,Ie as jc,J as Yd,Jb as fc,Jc as Am,Je as np,K as Xd,Kb as mc,Kc as Cm,Ke as ip,L as Zd,La as em,Lb as pc,Lc as Em,Le as rp,Ma as tm,Mb as hc,Mc as Ac,Me as op,N as Nr,Na as nm,Nb as cs,Nc as _m,Nd as Gm,O as _i,Ob as gc,Oc as Pm,P as ec,Pb as yc,Pc as hs,Pd as Wm,Pe as sp,Q as es,Qb as vc,Qc as Mm,Qd as Vm,Rb as bc,Rc as gs,Rd as $m,Re as ap,Sb as ls,Sc as Om,Ta as im,Tb as us,Tc as ys,U as Uf,Ua as qn,Ub as Sc,Uc as Bm,Va as ss,Vb as Lr,Vc as Cc,W as Ff,Wa as rc,Wb as mm,Wd as Km,We as Nc,X as ts,Xa as as,Ya as rm,Yb as fs,Ye as Uc,Za as om,Zc as Ec,Ze as Fc,_ as ns,_a as sm,_b as zr,a as Ef,aa as Hf,ac as pm,b as _f,ba as Gf,bb as gn,c as Pf,ca as Pi,cc as ms,cd as qm,cf as Is,d as un,da as Wf,dc as hm,dd as vs,e as Bn,ec as gm,ed as Dm,f as Fd,fc as ym,fd as jm,g as Ld,gc as vm,gd as Pc,h as zd,hb as Ur,hc as bm,i as Nt,ia as nc,ic as wc,id as Nm,ja as Mi,jc as ps,je as Bc,kb as am,kd as Um,ke as xs,l as Hd,la as ic,le as Qm,m as Ei,mb as sc,md as Fm,me as qc,n as Gd,na as Vf,nb as ac,nd as Lm,ne as Rs,o as Xo,oa as $f,ob as dm,oc as Sm,od as zm,p as Zo,pa as ui,pb as cm,pc as wm,q as Wd,qa as is,qb as lm,r as jf,ra as rs,rb as um,rd as bs,s as Vd,sa as os,t as Gt,tc as kc,td as Ss,u as $d,ua as Kf,uc as xc,va as Qf,vc as Hr,ve as Jm,wa as Jf,wc as Gr,x as Qt,xa as Yf,xd as ws,y as ni,yb as fm,yc as Rc,yd as Mc,z as Kd,za as Xf,zc as km,zd as Oc,ze as Ym}from"./tansr-chunk-UIBBDNRB.mjs";import{A as fp,D as zc,E as Hc,H as mp,I as pp,J as hp,K as gp,M as Wr,c as dp,d as cp,e as Oi,j as Lc,o as lp,t as _t,z as up}from"./tansr-chunk-6NUB6YQJ.mjs";import{a as Bd,b as qd,p as Dd,q as On,s as jd}from"./tansr-chunk-JOAFKQNW.mjs";import{Fa as Lf,Ia as tc,Ma as dr,n as sr,na as Nf}from"./tansr-chunk-ZQ3ZK7IL.mjs";import{C as Ud,N as fe,O as ft,P as xn,a as Zt,c as li,d as qf,k as Df,l as Yo,n as Nd}from"./tansr-chunk-I3TOVAA6.mjs";import{c as Mf,e as Of,f as Bf}from"./tansr-chunk-F7C6ITED.mjs";import{k as wf}from"./tansr-chunk-HRKJLVKC.mjs";import{a as $o,b as Ko,c as kf,d as xf,e as Rf,h as Qo}from"./tansr-chunk-OKAA4BJC.mjs";import{a as or,b as vf,k as bf,m as We,o as Sf}from"./tansr-chunk-IHFZ4MW7.mjs";import{Ba as Jo,Fb as Tf,Ib as Af,Jb as Cf,a as Cd,c as r,d as If,kb as Ed,lb as _d,nb as Pd,pb as Md,rb as Od,ua as jr}from"./tansr-chunk-QWGSXFEJ.mjs";import{c as Av}from"./tansr-chunk-RRAMVVYF.mjs";import{createHash as qv,randomUUID as Xp}from"node:crypto";import{createHash as Cv}from"node:crypto";import{mkdir as qp,open as Ev,readFile as Dp,readdir as _v}from"node:fs/promises";import eo from"node:path";var jp=new WeakMap;function nR(t){jp.set(t,"sdk2-offload-v1")}function qi(t){return jp.get(t)??"sdk1"}var ut=class extends Error{constructor(n){super(`SDK2 offload: ${n}`);this.code=n;this.name="OffloadSessionError"}code};function Es(t,e){let n=t.sdk2SessionFamily;if(e===void 0?n!==void 0:n===void 0||fe(n)!==fe(e.marker))throw new ut("family_mismatch")}function iR(t,e,n,i){if(!eo.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 ut("family_mismatch");let o=Object.freeze({...n}),s=eo.join(eo.resolve(t),"sdk2-offload-v1",Cv("sha256").update(n.applicationScopeId).digest("hex")),a=eo.join(s,"contract.json"),d=fe(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 qp(eo.dirname(s),{recursive:!0});try{await qp(s)}catch(p){if(p.code!=="EEXIST")throw p}if((await _v(s)).length===0){let p=await Ev(a,"wx",384);try{await p.writeFile(d),await p.sync()}finally{await p.close()}}}let u;try{u=await Dp(a,"utf8")}catch(p){throw p.code==="ENOENT"?new ut("family_missing"):p}if(u!==d)throw new ut("family_mismatch");c=!0})().catch(u=>{throw l=void 0,u})),await Dp(a,"utf8")!==d)throw new ut("family_mismatch")}})}function rR(t,e,n,i){if(!t||!("capabilities"in t)||t.capabilities.consistency!=="strong"||!t.capabilities.conditionalPut||t.capabilities.list!=="prefix")throw new ut("source_mismatch");let o=fe(n),s=ft(o),a=`sdk2-offload-v1/${s}/`,d=`${a}contract.json`,c=Buffer.from(o),l=m=>`${a}objects/${m}`,f,u=async()=>{await(f??=(async()=>{if(!await t.head(d)){if(i!=="create")throw new ut("family_missing");for await(let x of t.list(a))throw new ut("family_missing");try{await t.put(d,new ReadableStream({start(x){x.enqueue(c),x.close()}}),{bytes:c.length,contentType:"application/json",sha256:ft(o)},{ifNoneMatch:"*"})}catch(x){if(!(x instanceof Bn)||x.kind!=="precondition_failed")throw x}}})().catch(x=>{throw f=void 0,x}));let m=await t.head(d);if(!m)throw new ut("family_missing");if(m.bytes!==c.length||m.sha256!==ft(o))throw new ut("family_mismatch");let v=(await t.get(d)).getReader(),b=Buffer.alloc(0);try{for(;;){let x=await v.read();if(x.done)break;if(b.length+x.value.byteLength>c.length)throw new ut("family_mismatch");b=Buffer.concat([b,x.value])}}finally{await v.cancel().catch(()=>{}),v.releaseLock()}if(!b.equals(c))throw new ut("family_mismatch")},p={capabilities:t.capabilities,put:(m,v,b,x)=>t.put(l(m),v,b,x),get:(m,v,b)=>t.get(l(m),v,b),head:(m,v)=>t.head(l(m),v),async*list(m,v,b){let x=l("");for await(let R of t.list(l(m),v,b)){if(!R.key.startsWith(x))throw new ut("family_mismatch");yield{...R,key:R.key.slice(x.length)}}},delete:(m,v)=>t.delete(m.map(l),v)},h=m=>`sdk2-offload-v1:${s}:${m}`;return{cold:p,index:e&&{upsert:(m,v,b)=>e.upsert({...m,endUserKey:h(m.endUserKey)},v,b),async get(m,v){let b=await e.get(h(m),v);if(b&&b.endUserKey!==h(m))throw new ut("family_mismatch");return b&&{...b,endUserKey:m}},async*list(m,v){for await(let b of e.list(h(m),v)){if(b.endUserKey!==h(m))throw new ut("family_mismatch");yield{...b,endUserKey:m}}},remove:(m,v)=>e.remove(h(m),v)},check:u}}import{access as Dv,mkdir as Zp,readFile as jv,readdir as wl,rm as bl,stat as kl}from"node:fs/promises";import{randomUUID as Np}from"node:crypto";import{readFileSync as Up}from"node:fs";import{readFile as to}from"node:fs/promises";import{hostname as fl}from"node:os";var no="serveOwner",Jt=class extends Error{constructor(n){super(`Session ownership: ${n}`);this.code=n;this.name="ServeSessionOwnershipError"}code},Fp=new WeakMap;function yn(t){throw new Jt(t)}function ml(t){let e=t[no];if(e===void 0)return;(!e||typeof e!="object"||Array.isArray(e))&&yn("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")&&yn("owner_corrupted"),n}function io(t,e,n){n.serveOwnerDeleted===!0&&yn("owner_stale");let i=ml(n),o=e===void 0?void 0:Fp.get(e);if(!i){e&&yn("owner_stale");return}return e||yn("owner_stale"),(!o||o.dir!==t||i.ownerId!==o.record.ownerId||i.claimId!==o.record.claimId||i.attempt!==o.record.attempt||i.host!==fl()||i.released||i.expiresAt<=Date.now())&&yn("owner_stale"),i}function ro(t,e,n){io(t,e,n??JSON.parse(Up(Qt(t),"utf8")))}function _s(t,e){let n=ml(e??JSON.parse(Up(Qt(t),"utf8")));n&&(!n.released||n.phase!=="idle")&&yn("owner_stale")}async function Di(t,e){let n;for(let o=0;n===void 0;o++)try{n=await Hd(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 Lp(t,e,n=i=>i()){let i=e.leaseMs??3e4,o=e.ownerId??Np();if(!Number.isSafeInteger(i)||i<1e3||i>3e5||!o||o.length>256)throw new TypeError("Invalid session ownership options");let s=await Di(t,async()=>{let c=JSON.parse(await to(Qt(t),"utf8"));c.serveOwnerDeleted===!0&&yn("owner_stale");let l=ml(c),f=Date.now();l?.host!==void 0&&l.host!==fl()&&yn("owner_busy"),l&&!l.released&&l.expiresAt>f&&yn("owner_busy"),(l?.phase==="running"&&!(e.runtimeRecovery===!0&&c.serveRuntime!==void 0)||c.pendingRewrite===!0)&&yn("reconciliation_required");let u=(l?.attempt??0)+1;Number.isSafeInteger(u)||yn("owner_corrupted");let p={format:"serve-owner-v1",ownerId:o,claimId:Np(),host:fl(),attempt:u,expiresAt:f+i,phase:c.serveRuntime===void 0?"idle":"running",released:!1};return c[no]=p,await ni(Qt(t),JSON.stringify(c)+`
|
|
5
|
+
`),p}),a=c=>n(()=>Di(t,async()=>{let l=JSON.parse(await to(Qt(t),"utf8")),f=io(t,d,l);l[no]=c(f),await ni(Qt(t),JSON.stringify(l)+`
|
|
6
|
+
`)})),d=Object.freeze({ownerId:o,attempt:s.attempt,leaseMs:i,assertCurrent(){ro(t,d)},assertIdle(){return n(()=>Di(t,async()=>{let c=JSON.parse(await to(Qt(t),"utf8"));(io(t,d,c).phase!=="idle"||c.serveRuntime!==void 0||c.pendingRewrite===!0)&&yn("reconciliation_required")}))},fence(c){return n(()=>Di(t,async()=>(d.assertCurrent(),{value:c()})))},write(c){return n(()=>Di(t,async()=>(d.assertCurrent(),await c())))},beginTurn(){return n(()=>Di(t,async()=>{let c=JSON.parse(await to(Qt(t),"utf8")),l=io(t,d,c);c[no]={...l,phase:"running"},delete c.serveRuntime,await ni(Qt(t),JSON.stringify(c)+`
|
|
7
|
+
`)}))},checkpoint(c){return n(()=>Di(t,async()=>{let l=JSON.parse(await to(Qt(t),"utf8")),f=io(t,d,l);!c()||l.pendingRewrite===!0||l.historyTotal===void 0||(l[no]={...f,phase:"idle"},delete l.serveRuntime,await ni(Qt(t),JSON.stringify(l)+`
|
|
8
|
+
`))}))},renew(){return a(c=>({...c,expiresAt:Date.now()+i}))},release(){return a(c=>({...c,released:!0}))}});return Fp.set(d,{dir:t,record:s}),d}import{types as oh}from"node:util";import ji from"node:path";import{createHash as Pv}from"node:crypto";var oo=r.string().min(1).max(256),pl=r.string().regex(/^(0|[1-9][0-9]{0,18})$/),Hp=r.object({sourceId:oo,generation:pl,deletionGeneration:pl,variant:oo}).strict(),Mv=r.object({source:Hp,executorId:oo,workspaceId:oo,workspaceRevision:oo,authorizationRevision:pl}).strict(),zp=r.string().regex(/^[a-f0-9]{64}$/),hl=r.object({format:r.literal("tansr-attachment-source/1"),scope:r.string().min(1).max(4096),historyDigest:zp,checkpointDigest:zp,snapshot:Mv}).strict(),gl=t=>JSON.parse(Buffer.from(Zt(t)).toString("utf8")),Gp=t=>Pv("sha256").update("tansr-attachment-source/1\0").update(fe(t)).digest("hex");function Wp(t){return Object.freeze(Hp.parse(gl(t)))}function yl(t){return t===null?null:hl.parse(gl(t))}function fi(t){return fe(t)}function Vp(t,e,n,i){return hl.parse({format:"tansr-attachment-source/1",scope:t,historyDigest:Nr(e),checkpointDigest:Gp(n),snapshot:i})}function $p(t,e,n,i){return t.scope===e&&t.historyDigest===Nr(n)&&t.checkpointDigest===Gp(i)}function Kp(t){return{type:"attachment_source_checkpoint",version:1,checkpoint:yl(t)}}function vl(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:hl.nullable()}).strict().parse(gl(n.payload)).checkpoint}return e}var Qp=/^\d+$/;function Ps(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(!Qp.test(e))return{ok:!1,detail:"offset must be a non-negative integer"};i.offset=Number.parseInt(e,10)}if(n!==null){if(!Qp.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 Ov(t){return t.blocks.flatMap(e=>e.t==="tool_call"?[e.id]:[])}function Bv(t){return t.blocks.flatMap(e=>e.t==="tool_result"?[e.callId]:[])}function so(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 Ov(f))a.add(u);else for(let u of Bv(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 Un(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=so(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 Ms=new WeakMap;function Jp(t){if(Ms.has(t))throw new Error("Serve Store delete target already registered");Ms.set(t,{})}function yR(t,e){let n=Ms.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 Yp(t){return Ms.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 qv("sha256").update(t,"utf8").digest("hex").slice(0,16)}async function Sl(t){try{return await Dv(t),!0}catch{return!1}}var Il="TANSR_SESSION_STORE_CORE",eh=64;function Ni(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>eh?`${n.slice(0,eh)}…`:n}}var sh=1024;function ah(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 Bs(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)&&ah(e.thinking)}function ao(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&&!ah(t.changes.thinking)))return structuredClone(t)}function ur(t){let e=t.serveConfiguration;if(e===void 0)return;let n=e;if(!n||n.format!=="serve-configuration-v1"||!Bs(n.current)||!Array.isArray(n.requests)||n.requests.length>sh||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)||!Bs(i.configuration)||i.configuration.revision!==o+1)||new Set(n.requests.map(i=>i.requestId)).size!==n.requests.length||n.requests.length>0&&fe(n.requests.at(-1).configuration)!==fe(n.current))throw new et(String(t.sessionId),"Invalid durable configuration");return structuredClone(n)}function xl(t,e){let n=ft(fe(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>=sh?{status:"rejected",reason:"request_limit",configuration:structuredClone(t.current)}:{status:"ready",configuration:structuredClone(t.current)}}function Nv(t,e){let n=ur(t);if(n)return n.current;let i=structuredClone({...e,revision:0});if(!Bs(i))throw new TypeError("Invalid initial configuration");return t.serveConfiguration={format:"serve-configuration-v1",current:i,requests:[]},structuredClone(i)}function Uv(t,e,n){let i=ao(e);if(!i)return{status:"rejected",reason:"invalid_configuration"};let o=ur(t);if(!o)throw new et(String(t.sessionId),"Configuration not initialized");let s=xl(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:ft(fe(i)),configuration:a}),t.serveConfiguration=o,{status:"changed",configuration:structuredClone(a)}}async function th(t,e){let n=await dh(t);return n!==null&&(Xo(n),Es(n,e)),n}async function dh(t){try{let e=JSON.parse(await jv(Qt(t),"utf8"));return typeof e!="object"||e===null||Array.isArray(e)?null:e}catch{return null}}function Rn(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=Fv(t.cwdHistory);o!==void 0&&(i.cwdHistory=o);let s=uh(t);s!==void 0&&(i.forkedFrom=s);let a=lh(t);a!==void 0&&(i.retentionDays=a);let d=ch(t);return d!==void 0&&(i.lastSeq=d,t.seqSealed===!0&&(i.seqSealed=!0)),i}function ch(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=ch(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 qs="historyTotal";function ih(t){let e=t?.[qs];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 rh(t,e){if(e.cursor.lastHash===null){delete t[qs];return}let n={messages:e.persisted,records:e.cursor.recordCount,lastHash:e.cursor.lastHash};t[qs]=n}function lh(t){let e=t?.retentionDays;return typeof e=="number"?Os(e):void 0}function uh(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 Fv(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 Lv=1e5;function Os(t){return t!==void 0&&Number.isFinite(t)&&t>=0?t:void 0}async function fh(t){let e=0,n;try{n=await wl(t,{withFileTypes:!0})}catch{return 0}for(let i of n){let o=ji.join(t,i.name);if(i.isDirectory())e+=await fh(o);else if(i.isFile())try{e+=(await kl(o)).size}catch{}}return e}function zv(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 Hv(t,e){switch(e.type){case"store.segment_sealed":t("debug",at.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",at.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",at.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",at.storeHotFull,{hotBytes:e.hotBytes,maxBytes:e.maxBytes});return;case"store.hot_recovered":t("info",at.storeHotRecovered,{hotBytes:e.hotBytes,maxBytes:e.maxBytes});return;case"store.evicted":t("debug",at.storeEvicted,{sessionId:e.session.sessionId,endUserKey:e.session.endUserKey,n:e.segment.n,bytes:e.bytes});return;case"store.orphan_gc":t("info",at.storeOrphanGc,{sessionId:e.session.sessionId,endUserKey:e.session.endUserKey,deleted:e.deleted.length});return;default:return}}var Rl=new WeakMap;function Gv(t,e){if(Rl.has(t)||oh.isProxy(t))throw new Ei("identity_mismatch");Rl.set(t,{...e,methods:["create","get","list","commit","delete"].map(n=>({key:n,value:Object.getOwnPropertyDescriptor(t,n)?.value}))})}function $n(t){if(!t||typeof t!="object"||oh.isProxy(t))throw new Ei("identity_mismatch");let e=Rl.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 Ei("identity_mismatch");if(e.cold&&!e.family)throw new Ei("unsupported_capability");return e}function mh(t){$n(t)}function BR(t,e){if($n(t).family!==e)throw new ut("family_mismatch")}function qR(t,e,n,i){let o=$n(t);if(!o.family||!Number.isSafeInteger(i)||i<1)throw new ut("family_mismatch");return o.readBounded(e,n,i)}function DR(t){return $n(t).storageRoot}function Tl(t,e,n){let i=$n(t);if(typeof e!="string"||e.length===0)throw new Ei("invalid_input");let o=Gd(n,["title","platformSessionId","cwd","retentionDays"]);return i.create(e,o)}function ph(t){return hh(t)}function jR(t,e){if(!t.cold||ji.resolve(t.dir)!==e.directory)throw new ut("family_mismatch");return hh(t,e)}function hh(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=ji.resolve(t.dir),a=e?{sdk2SessionFamily:e.marker}:{},d=async(M,k)=>{if(e&&k===null&&await Sl(M)&&(await wl(M)).length>0)throw new ut("family_missing")},c=async M=>{await e?.checkRoot();let k=await th(M,e);return await d(M,k),k},l=async M=>{await e?.checkRoot();let k=await dh(M);return await d(M,k),k&&Es(k,e),k},f=async(M,k=!1)=>{if(!e)return Qd(M);await e.checkRoot();let j=Gt(M.storageRoot,M.sessionId);if(k?await th(j,e):await c(j))return{sessionDir:j,meta:await Kd(j),created:!1};await Zp(j,{recursive:!0});let q={schemaVersion:1,sessionId:M.sessionId,createdAt:new Date().toISOString(),cwd:M.cwd,...M.extra??{},sdk2SessionFamily:e.marker},Q=await jf(j,q,"fresh");if(!await c(j))throw new ut("family_missing");return{sessionDir:j,meta:await Kd(j),created:Q}},u=process.env[Il]==="legacy"?"legacy":"core";if(t.recovery!==void 0&&u==="legacy")throw new Error("session recovery requires the core store policy");let p={segmentation:t.segmentation??{}},h=t.cold===void 0?void 0:pc({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(h!==void 0){let M=Nn(t.logger);h.on(k=>{if(Hv(M,k),k.type==="store.commit_failed"&&k.gaveUp&&t.onStoreError!==void 0)try{t.onStoreError(k.session.sessionId,k.error)}catch{}if(t.onStoreEvent!==void 0)try{t.onStoreEvent(k)}catch{}})}function g(M,k){let j=(n.get(M)??Promise.resolve()).then(async()=>(await e?.checkRoot(),k())),W=j.then(()=>{},()=>{});return n.set(M,W),W.then(()=>{n.get(M)===W&&n.delete(M)}),j}let m=M=>ji.join(s,e?"offload-sessions":"agent-sessions",M),v=M=>m(Wt(M)),b=(M,k,j)=>h?.bind({sessionId:M,endUserKey:k,sessionDir:j}),x=M=>M===void 0?p:{...p,externalizeImages:!1,onSegmentSealed:M.onSegmentSealed},R=M=>M===void 0?{}:{segmentSource:M.segmentSource},A=(M,k)=>k instanceof Bn&&k.kind==="transient"?k:new et(M,jn(k),k),C=M=>{let k=o.get(M);return k===void 0&&(k=new hc({storageRoot:M,readMeta:async j=>{let W=await l(j);return W===null||typeof W.sessionId!="string"?null:Zo(W,Rn(W))}}),o.set(M,k)),k};function B(M,k,j,W){let q=i.get(M);if(q!==void 0)return i.delete(M),i.set(M,q),q;if(i.size>=Lv){let U=i.keys().next();U.done||i.delete(U.value)}let Q=Zd({sessionDir:W,sessionId:k,producer:"serve",policy:u,writerOptions:()=>x(b(k,j,W)),readOptions:()=>R(b(k,j,W)),onRotated:async({empty:U})=>{h?.unbind(W),U&&await h?.commitEmpty({sessionId:k,endUserKey:j,sessionDir:W})},...t.onStoreWarning!==void 0?{onWarning:t.onStoreWarning}:{}});return i.set(M,Q),Q}let Y=(M,k)=>k instanceof un?k.code==="SESSION_LOCKED"||k.code==="CURSOR_STALE"?k:new et(M,k.message,k):k instanceof Bn?A(M,k):k,ne=(M,k)=>k instanceof un&&(k.code==="SESSION_LOCKED"||k.code==="CURSOR_STALE")?k:A(M,k);async function N(M,k){let j=await c(M);return j===null?null:(k(j)&&(Es(j,e),await ni(Qt(M),`${JSON.stringify(j,null,2)}
|
|
9
|
+
`)),j)}async function X(M,k,j){return t.ownership===void 0&&k===void 0?(ro(M.sessionDir),j()):M.withLock(j,()=>ro(M.sessionDir,k))}async function S(M,k){return(await w(M,k)).messages}async function w(M,k,j=!1){let W=(await c(M.sessionDir))?.serveOwner!==void 0;if(!W&&t.recovery!==void 0)try{let U=await M.withLock(()=>cc(M,t.recovery));if(U.recovery!==void 0&&t.recovery.onRecovery===void 0){let ue=U.recovery,pe={sessionId:k,droppedMessages:ue.droppedMessages,recoveredMessages:ue.recoveredMessages,synthesizedToolResults:ue.synthesizedToolResults,reason:ue.reason,fingerprint:ue.fingerprint};t.logger!==void 0?Nn(t.logger)("warn","store.recovery_degraded",pe):process.emitWarning(JSON.stringify(pe),{code:"SESSION_RECOVERY_DEGRADED"})}return{messages:U.messages,usageSnapshot:qc(U.journal.records),attachmentCheckpoint:es(U.journal.records,U.recovery===void 0?U.messages:void 0),attachmentSourceCheckpoint:vl(U.journal.records),memorySelectionCheckpoint:wc(U.journal.records),...U.recovery!==void 0?{recovery:U.recovery}:{}}}catch(U){throw M.resetTail(),ne(k,U)}let q;try{q=W?await M.readAllConfirmed():await M.readAll(j?{repair:!1}:{})}catch(U){throw ne(k,U)}if(q.integrityBreakAt!==void 0)throw new et(k,`journal hash chain broken at record index ${q.integrityBreakAt}`);let Q=ar(q.records);if(Q.warnings.length>0)throw M.resetTail(),new et(k,Q.warnings.join("; "));try{return{messages:Q.messages,usageSnapshot:qc(q.records),attachmentCheckpoint:es(q.records,Q.messages),attachmentSourceCheckpoint:vl(q.records),memorySelectionCheckpoint:wc(q.records)}}catch(U){throw M.resetTail(),ne(k,U)}}async function T(M,k,j){if(h===void 0)return!1;await e?.checkRoot();let W;try{W=Gt(M,j)}catch{return!1}if(await c(W)!==null)return!1;let q=await Sl(W);await Zp(W,{recursive:!0});let Q;try{Q=await h.restore({sessionId:j,endUserKey:k,sessionDir:W})}catch(pe){throw q||await bl(W,{recursive:!0,force:!0}).catch(()=>{}),A(j,pe)}if(Q===null)return q||await bl(W,{recursive:!0,force:!0}).catch(()=>{}),!1;let U=Q.meta;await f({storageRoot:M,sessionId:j,cwd:process.cwd(),extra:{...a,...U.title!==void 0?{title:U.title}:{}}},!0);let ue=await N(W,pe=>(U.createdAt!==""&&(pe.createdAt=U.createdAt),pe.updatedAt=U.updatedAt!==""?U.updatedAt:pe.createdAt,U.platformSessionId!==void 0&&(pe.platformSessionId=U.platformSessionId),!0));if(ue===null)throw new et(j,"meta.json unreadable right after cold-tier restore");return i.get(`${M}|${j}`)?.resetTail(),await C(M).upsert(Rn(ue)),!0}function _(M,k){let j=m(M),W=`${j}|${k}`;return g(W,async()=>{let q=Gt(j,k);await c(q)!==null&&_s(q);let Q=Yp(re);if(Q!==void 0){let U=await Q(Object.freeze({storeIdentity:re,endUserKey:M,sessionId:k}));if(U!==null){if(!U||typeof U.confirm!="function")throw new TypeError("Invalid Serve Store delete confirmation");let ue=await c(q);if(ue===null&&await T(j,M,k)&&(ue=await c(q)),ue===null)await U.confirm(null);else{let pe=B(W,k,M,q);await pe.withLock(async()=>{let oe=await c(q);if(oe===null||oe.sessionId!==k||oe.pendingRewrite===!0)throw new et(k,"Guarded deletion requires confirmed original metadata");let ee=await pe.readAll({repair:!1});if(ee.integrityBreakAt!==void 0||ee.repairs.length>0)throw new et(k,"Guarded deletion requires intact original history");let O=ar(ee.records);if(O.warnings.length>0)throw new et(k,O.warnings.join("; "));let J=ih(oe);if(Object.hasOwn(oe,qs)&&J===void 0||J!==void 0&&(J.records!==ee.cursor.recordCount||J.lastHash!==ee.cursor.lastHash||J.messages!==O.messages.length))throw new et(k,"Guarded deletion requires confirmed original history");await U.confirm(Object.freeze({meta:Object.freeze(Rn(oe)),sourceSnapshotDigest:en(k,O.messages,0).sourceSnapshotDigest}))})}}}await c(q)!==null&&await B(W,k,M,q).withLock(async()=>{await N(q,U=>(_s(q,U),U.serveOwnerDeleted=!0,!0))},()=>_s(q)),i.delete(W),h!==void 0&&(h.unbind(q),await h.remove({sessionId:k,endUserKey:M})),await bl(q,{recursive:!0,force:!0}),await C(j).remove(k)})}async function G(M,k,j){let W=Wt(M),q=m(W),Q=`${q}|${k}`;return g(Q,async()=>{let U=Gt(q,k),ue=await c(U);if(ue===null&&await T(q,W,k)&&(ue=await c(U)),ue===null)return null;let pe=B(Q,k,W,U),oe=j===void 0?await w(pe,k):await pe.withLock(async()=>{let J=async qe=>{try{return(await kl(qe)).size}catch(ze){if(ze.code==="ENOENT")return 0;throw ze}};if(await J(ji.join(U,"manifest.json"))>262144)throw new ut("capacity_exceeded");let ke=await Jd(U),we=await J(ji.join(U,"journal.jsonl"));for(let qe of ke?.segments??[]){if(qe.status!=="sealed"||qe.bytes<=0)throw new ut("rollback_pending");we+=qe.bytes}if(!Number.isSafeInteger(we)||we>j)throw new ut("capacity_exceeded");if(ue=await c(U),!ue)throw new ut("family_missing");return w(pe,k,!0)}),ee=ue.serveRuntime;if(ee!==void 0&&(t.ownership?.runtimeRecovery!==!0||!ee||!ee.checkpoint||typeof ee.checkpoint!="object"||typeof ee.checkpoint.query!="object"||ee.checkpoint.query===null||ee.checkpoint.query.version!==1||ee.checkpoint.query.sessionId!==k||typeof ee.checkpoint.query.turnId!="string"||typeof ee.checkpoint.historyEpoch!="string"||!ee.checkpoint.historyEpoch||!Number.isSafeInteger(ee.checkpoint.turn)||ee.checkpoint.turn<1||ee.checkpoint.deadline!==void 0&&(!Number.isSafeInteger(ee.checkpoint.deadline)||ee.checkpoint.deadline<0)||ee.historyDigest!==ft(Nt(oe.messages))))throw new et(k,"Runtime checkpoint history mismatch");let O=ur(ue)?.current;return{...O===void 0?{}:{configuration:O},...ee===void 0?{}:{runtimeCheckpoint:{...ee.checkpoint,query:{...ee.checkpoint.query,messages:oe.messages}}},meta:Rn(ue),...ue.serveOwner===void 0?{}:{ownershipRequired:!0},messages:oe.messages,...oe.recovery!==void 0?{recovery:oe.recovery}:{},...oe.usageSnapshot!==void 0?{usageSnapshot:oe.usageSnapshot}:{},...oe.attachmentCheckpoint!==void 0?{attachmentCheckpoint:oe.attachmentCheckpoint}:{},...oe.attachmentSourceCheckpoint!==void 0?{attachmentSourceCheckpoint:oe.attachmentSourceCheckpoint}:{},...oe.memorySelectionCheckpoint!==void 0?{memorySelectionCheckpoint:oe.memorySelectionCheckpoint}:{}}})}let V=(M,k,j,W)=>{let q=v(M),Q=`${q}|${k}`;return g(Q,async()=>{let U=Gt(q,k);return X(B(Q,k,Wt(M),U),j,async()=>{let ue=await c(U);if(!ue)throw new et(k,"Configuration session not found");let pe=W(ue);return pe.changed&&await ni(Qt(U),`${JSON.stringify(ue,null,2)}
|
|
10
|
+
`),pe.value})})},te=M=>{if(M.serveOwner?.phase!=="idle"||M.serveRuntime!==void 0||M.pendingRewrite===!0)throw new Jt("reconciliation_required")},re={...t.ownership===void 0?{}:{initializeConfiguration(M,k,j,W){let q=structuredClone({...j,revision:0});return Bs(q)?V(M,k,W,Q=>{let U=ur(Q);return U?{value:U.current,changed:!1}:(te(Q),{value:Nv(Q,q),changed:!0})}):Promise.reject(new TypeError("Invalid initial configuration"))},inspectConfiguration(M,k,j,W){let q=ao(j);return q?V(M,k,W,Q=>{let U=ur(Q);if(!U)throw new et(k,"Configuration not initialized");return{value:xl(U,q),changed:!1}}):Promise.resolve({status:"rejected",reason:"invalid_configuration"})},commitConfiguration(M,k,j,W,q){let Q=ao(j);return Q?V(M,k,W,U=>{let ue=ur(U);if(!ue)throw new et(k,"Configuration not initialized");let pe=xl(ue,Q);if(pe.status!=="ready")return{value:pe,changed:!1};te(U);let oe=Uv(U,Q,q);return{value:oe,changed:oe.status==="changed"}}):Promise.resolve({status:"rejected",reason:"invalid_configuration"})}},...t.ownership?.runtimeRecovery===!0?{runtimeCheckpoints:!0}:{},...t.ownership===void 0?{}:{claimOwner:(M,k)=>g(`${v(M)}|${k}`,()=>Lp(Gt(v(M),k),t.ownership,j=>g(`${v(M)}|${k}`,j)))},attachmentCheckpoints:!0,attachmentSourceCheckpoints:!0,memorySelectionCheckpoints:!0,async create(M,k){let j=Wt(M),W=m(j),q=k.sessionId??Xp(),Q=`${W}|${q}`;return g(Q,async()=>{let U=C(W);await U.warm();let ue={...a,...k.title!==void 0?{title:k.title}:{},...typeof k.retentionDays=="number"?{retentionDays:k.retentionDays}:{}},{sessionDir:pe,created:oe}=await f({storageRoot:W,sessionId:q,cwd:k.cwd??process.cwd(),...Object.keys(ue).length>0?{extra:ue}:{}});if(!oe&&await Sl(Yd(pe)))try{await B(Q,q,j,pe).withLock(async()=>{},()=>ro(pe,k.owner))}catch(ee){throw ne(q,ee)}return X(B(Q,q,j,pe),k.owner,async()=>{let ee=await N(pe,J=>{Xo(J);let ke=!1;return oe&&typeof J.updatedAt!="string"&&(J.updatedAt=typeof J.createdAt=="string"?J.createdAt:new Date().toISOString(),ke=!0),k.platformSessionId!==void 0&&J.platformSessionId!==k.platformSessionId&&(J.platformSessionId=k.platformSessionId,ke=!0),k.title!==void 0&&J.title!==k.title&&(J.title=k.title,ke=!0),typeof k.retentionDays=="number"&&J.retentionDays!==k.retentionDays?(J.retentionDays=k.retentionDays,ke=!0):k.retentionDays===null&&"retentionDays"in J&&(delete J.retentionDays,ke=!0),ke});if(ee===null)throw new et(q,"meta.json unreadable right after creation");let O=Rn(ee);return await U.upsert(O),O})})},get:(M,k)=>G(M,k),async getMeta(M,k){let j=Wt(M),W=m(j),q;try{q=Gt(W,k)}catch{return null}let Q=await c(q);return Q===null&&h!==void 0&&await g(`${W}|${k}`,()=>T(W,j,k))&&(Q=await c(q)),Q===null||typeof Q.sessionId!="string"?null:Rn(Q)},async list(M,k){await e?.checkRoot();let j=Wt(M),W=await C(m(j)).entries(),q=W.filter(Wd);if(e){for(let Q of q)if(!await c(Gt(m(j),Q.sessionId)))throw new ut("family_missing")}if(h!==void 0){let Q=new Set(W.map(U=>U.sessionId));for await(let U of h.listSessions(j))Q.has(U.sessionId)||q.push(zv(U))}return q.sort((Q,U)=>U.updatedAt.localeCompare(Q.updatedAt)),k?.limit!==void 0?q.slice(0,k.limit):q},async commit(M,k,j,W){let q=Wt(M),Q=m(q),U=`${Q}|${k}`,ue=[...j],pe=W.attachmentCheckpoint===void 0?void 0:ec(W.attachmentCheckpoint),oe=W.attachmentSourceCheckpoint===void 0?void 0:Kp(W.attachmentSourceCheckpoint),ee=W.memorySelectionCheckpoint===void 0?void 0:bm(W.memorySelectionCheckpoint);return g(U,async()=>{let O=Ni(ue),J=C(Q);await J.warm(),await T(Q,q,k);let{sessionDir:ke}=await f({storageRoot:Q,sessionId:k,cwd:process.cwd(),extra:{...a,...O!==void 0?{title:O}:{}}}),we=B(U,k,q,ke);return X(we,W.owner,async()=>{if(W.runtimeCheckpoint!==void 0&&(t.ownership?.runtimeRecovery!==!0||W.owner===void 0||W.runtimeCheckpoint.query.sessionId!==k||Nt(W.runtimeCheckpoint.query.messages)!==Nt(ue)))throw new et(k,"Invalid runtime checkpoint");t.ownership?.runtimeRecovery===!0&&await N(ke,He=>(delete He.serveRuntime,!0));let qe;try{qe=await we.commit({snapshot:ue,rewritten:W.rewritten,...W.usageSnapshot!==void 0||pe!==void 0||oe!==void 0||ee!==void 0?{trailingEvents:[...W.usageSnapshot===void 0?[]:[W.usageSnapshot],...pe===void 0?[]:[pe],...oe===void 0?[]:[oe],...ee===void 0?[]:[ee]]}:{}})}catch(He){throw Y(k,He)}let ze=await N(ke,He=>{if(He.updatedAt=new Date().toISOString(),W.lastSeq!==void 0&&nh(He,{lastSeq:W.lastSeq,sealed:!1}),rh(He,qe),W.runtimeCheckpoint!==void 0){let{messages:ht,...Ot}=W.runtimeCheckpoint.query;He.serveRuntime={checkpoint:{...W.runtimeCheckpoint,query:Ot},historyDigest:ft(Nt(ue))}}return!0});ze!==null&&await J.upsert(Rn(ze))})})},async recordUsageSnapshot(M,k,j,W){let q=Qm(structuredClone(j));if(q===void 0||q.snapshot.sessionId!==k)throw new et(k,"recordUsageSnapshot: invalid snapshot");let Q=Wt(M),U=m(Q),ue=`${U}|${k}`;return g(ue,async()=>{let pe=Gt(U,k);await kl(Qt(pe)).then(()=>!1,J=>{if(typeof J=="object"&&J!==null&&"code"in J&&J.code==="ENOENT")return!0;throw J})&&await T(U,Q,k);let ee=await l(pe);if(ee===null||ee.sessionId!==k)throw new et(k,"recordUsageSnapshot: session not found");let O=C(U);return await O.warm(),X(B(ue,k,Q,pe),W,async()=>{let J;try{J=await B(ue,k,Q,pe).appendInternalEvents([q])}catch(we){throw Y(k,we)}let ke=await N(pe,we=>(rh(we,J),!0));if(ke===null)throw new et(k,"recordUsageSnapshot: metadata disappeared");await O.upsert(Rn(ke))})})},delete(M,k){return _(Wt(M),k)},async sweepRetention(M){let k={scanned:0,deleted:[],failures:[]},j=oe=>{let ee=Os(oe.maxAgeDays)!==void 0?oe.maxAgeDays*864e5:void 0,O=Os(oe.maxPerEndUser),J=Os(oe.maxBytes);return{...ee!==void 0?{maxAgeMs:ee}:{},...O!==void 0?{maxPerEndUser:O}:{},...J!==void 0?{maxBytes:J}:{}}},W=oe=>oe.maxAgeMs===void 0&&oe.maxPerEndUser===void 0&&oe.maxBytes===void 0,q=j(M.policy);if(M.policyFor===void 0&&W(q))return k;let Q=M.keep??new Set,U=ji.join(s,e?"offload-sessions":"agent-sessions"),ue;try{ue=(await wl(U,{withFileTypes:!0})).filter(oe=>oe.isDirectory()).map(oe=>oe.name)}catch(oe){if(oe?.code==="ENOENT")return k;throw oe}let pe=async(oe,ee,O)=>{try{await _(oe,ee),k.deleted.push({endUserKey:oe,sessionId:ee,reason:O})}catch(J){k.failures.push({endUserKey:oe,sessionId:ee,message:jn(J)})}};for(let oe of ue.sort()){let ee=M.policyFor?.(oe),{maxAgeMs:O,maxPerEndUser:J,maxBytes:ke}=ee!==void 0?j(ee):q;if(O===void 0&&J===void 0&&ke===void 0)continue;let we=m(oe),qe=await C(we).entries(),ze=[];for(let Fe of qe){if(k.scanned+=1,Q.has(Fe.sessionId))continue;let Ze;try{Ze=Gt(we,Fe.sessionId)}catch{continue}let It=await c(Ze),xt=typeof It?.updatedAt=="string"?Date.parse(It.updatedAt):Number.NaN,pn=lh(It);ze.push({sessionId:Fe.sessionId,updatedAtMs:Number.isFinite(xt)?xt:void 0,maxAgeMs:pn!==void 0?pn*864e5:O})}let He=ze,ht=He.filter(Fe=>Fe.updatedAtMs!==void 0&&Fe.maxAgeMs!==void 0&&M.now-Fe.updatedAtMs>Fe.maxAgeMs);for(let Fe of ht)await pe(oe,Fe.sessionId,"max_age");He=He.filter(Fe=>!ht.includes(Fe));let Ot=(Fe,Ze)=>(Ze.updatedAtMs??Number.NEGATIVE_INFINITY)-(Fe.updatedAtMs??Number.NEGATIVE_INFINITY);if(He.sort(Ot),J!==void 0&&He.length>J){let Fe=He.slice(Math.floor(J));for(let Ze of Fe)await pe(oe,Ze.sessionId,"max_per_end_user");He=He.slice(0,Math.floor(J))}if(ke!==void 0&&He.length>0){let Fe=[];for(let It of He)Fe.push({sessionId:It.sessionId,bytes:await fh(Gt(we,It.sessionId))});let Ze=Fe.reduce((It,xt)=>It+xt.bytes,0);for(let It=Fe.length-1;It>=0&&Ze>ke;It--){let xt=Fe[It];await pe(oe,xt.sessionId,"max_bytes"),Ze-=xt.bytes}}}return k},sessionDirOf(M,k){return Gt(v(M),k)},async getHistoryPage(M,k,j){if(!Number.isFinite(j.offset)||j.offset<0||!Number.isFinite(j.limit)||j.limit<0)throw new RangeError(`getHistoryPage: "offset" and "limit" must be non-negative finite numbers (got offset=${String(j.offset)}, limit=${String(j.limit)}).`);let W=Math.floor(j.offset),q=Math.floor(j.limit),Q=Wt(M),U=m(Q),ue=`${U}|${k}`;return g(ue,async()=>{let pe;try{pe=Gt(U,k)}catch{return null}let oe=await c(pe);if(oe===null){if(!await T(U,Q,k))return null;oe=await c(pe)}let ee=uh(oe)!==void 0,O=ih(oe),J=B(ue,k,Q,pe);return oe?.serveOwner!==void 0?Un(await S(J,k),W,q):t.recovery!==void 0?Un(await S(J,k),W,q):J.withLock(async()=>{if(ee)return Un(await S(J,k),W,q);let ke=Math.max(q,1);for(;;){let we;try{we=await J.readTail({minMessages:ke})}catch(Ze){throw ne(k,Ze)}if(we.integrityBreakAt!==void 0)throw J.resetTail(),new et(k,`journal hash chain broken at record index ${we.integrityBreakAt}`);let qe=ar(we.records);if(qe.warnings.length>0)throw J.resetTail(),new et(k,qe.warnings.join("; "));let ze=qe.messages;if(we.fromSegment===1)return Un(ze,W,q);let He=O!==void 0&&O.lastHash===we.cursor.lastHash&&O.records===we.cursor.recordCount,ht;if(He)ht=O.messages;else if(we.records.every(Ze=>Ze.producer==="serve"&&Xd(Ze)))ht=we.cursor.recordCount;else return Un(await S(J,k),W,q);let Ot=ht-ze.length;if(q===0||W>=ht)return{messages:[],total:ht,offset:Math.min(W,ht),nextOffset:Math.min(W,ht)};if(W<Ot){ke=ht-W;continue}let Fe=so(ze,W-Ot,q);if(Fe===null){ke=ze.length+1;continue}return{messages:ze.slice(Fe.start,Fe.end),total:ht,offset:Ot+Fe.start,nextOffset:Ot+Fe.end}}})})},async recordCwdChange(M,k,j,W){let q=v(M),Q=`${q}|${k}`;return g(Q,async()=>{let U=Gt(q,k);return X(B(Q,k,Wt(M),U),W,async()=>{let ue=await N(U,pe=>{pe.cwd=j.to;let oe=Array.isArray(pe.cwdHistory)?pe.cwdHistory:[];return pe.cwdHistory=[...oe,{at:j.at,from:j.from,to:j.to}],!0});if(ue===null)throw new et(k,"recordCwdChange: meta.json unreadable (session not found)");await C(q).upsert(Rn(ue))})})},async recordSeqWatermark(M,k,j,W){let q=v(M),Q=`${q}|${k}`;return g(Q,async()=>{let U=Gt(q,k);return X(B(Q,k,Wt(M),U),W,async()=>{let ue=await N(U,pe=>nh(pe,j));if(ue===null)throw new et(k,"recordSeqWatermark: meta.json unreadable (session not found)");await C(q).upsert(Rn(ue))})})},async fork(M,k){if(e)throw new ut("family_mismatch");let j=v(M),W=k.newSessionId??Xp(),q=`${j}|${W}`;return g(q,async()=>{let Q=C(j);await Q.warm();let U=k.title??Ni(k.checkpoint.messages),ue=await Sc({storageRoot:j,sourceSessionId:k.sourceSessionId,checkpoint:k.checkpoint,newSessionId:W,cwd:k.cwd,producer:"serve",...U!==void 0?{extra:{title:U}}:{}}),pe=await N(ue.sessionDir,oe=>(oe.updatedAt=typeof oe.createdAt=="string"?oe.createdAt:new Date().toISOString(),!0));if(pe===null)throw new et(W,"meta.json unreadable right after fork");return i.delete(q),await Q.upsert(Rn(pe)),{sessionId:ue.sessionId}})},async flush(M){return await Promise.all([...n.values()]),h===void 0?!0:h.flush(M)},readiness(){return h===void 0||h.ready?{ready:!0}:{ready:!1,reason:"store_hot_full"}}};return Jp(re),Gv(re,{readBounded:G,cold:h!==void 0,...e?{family:e}:{},storageRoot:s,create(M,k){let j=Wt(M),W=m(j),q=k.sessionId,Q=Gt(W,q);return g(`${W}|${q}`,async()=>{$n(re);let U=new Date().toISOString(),ue={...a,schemaVersion:1,sessionId:q,cwd:k.cwd??process.cwd(),createdAt:U,updatedAt:U,...k.title!==void 0?{title:k.title}:{},...k.platformSessionId!==void 0?{platformSessionId:k.platformSessionId}:{},...typeof k.retentionDays=="number"?{retentionDays:k.retentionDays}:{}};return Vd({sessionDir:Q,raw:ue,register:async pe=>{$n(re);let oe=C(W);await oe.warm();let ee=Rn(pe);return await oe.upsert(Zo(pe,ee)),$n(re),ee},publish:async pe=>{$n(re),await C(W).upsert(pe),$n(re)}})})}}),Ud(re,{directory:(M,k)=>Gt(v(k.endUserId),M),read:(M,k)=>re.get(k.endUserId,M),...t.ownership?.runtimeRecovery===!0?{readRuntimeCheckpoint:async(M,k)=>(await re.get(k.endUserId,M))?.runtimeCheckpoint??null}:{},readConfirmed:(M,k)=>{let j=Wt(k.endUserId),W=m(j),q=`${W}|${M}`;return g(q,async()=>{try{let Q=await B(q,M,j,Gt(W,M)).readAllConfirmed(e?{allowCold:!0}:void 0),U=ar(Q.records);if(U.warnings.length>0)throw new et(M,U.warnings.join("; "));return{messages:U.messages}}catch(Q){throw ne(M,Q)}})}}),re}import{createHash as gh,timingSafeEqual as Wv}from"node:crypto";var Pt=class extends Error{constructor(n){super(n);this.code=n;this.name="AuthenticationUnavailableError"}code};function yh(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 Pt("source_unavailable");if(s>=i)throw new Pt("overloaded");s++;let f,u;try{f=t.authenticate(c),u=f!==null&&typeof f.then=="function"}catch(g){throw s--,g}if(!u){if(s--,a||c.aborted||l.destroyed||l.writableEnded)throw new Pt("source_unavailable");return f}let p=Promise.resolve(f),h=()=>{s--};return p.then(h,h),new Promise((g,m)=>{let v=!1,b=(A,C)=>{v||(v=!0,clearTimeout(R),d.delete(x),c.removeListener("aborted",x),l.removeListener("close",x),A?g(C):m(C))},x=()=>b(!1,new Pt("source_unavailable")),R=setTimeout(x,o);R.unref(),d.add(x),c.once("aborted",x),l.once("close",x),(a||c.aborted||l.destroyed||l.writableEnded)&&x(),p.then(A=>{a||c.aborted||l.destroyed||l.writableEnded?x():b(!0,A)},A=>b(!1,A))})},close(){a=!0;for(let c of[...d])c()}}}function Al(t){return t===void 0?void 0:/^Bearer\s+(\S+)$/i.exec(t.trim())?.[1]}function Cl(t,e){let n=gh("sha256").update(t,"utf8").digest(),i=gh("sha256").update(e,"utf8").digest();return Wv(n,i)}function Ds(t,e){let n=Al(t);return n===void 0?!1:Cl(n,e)}function mi(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 me(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 El=1e3;function co(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,El);c.unref(),e.once("close",d)}function pi(t){try{return decodeURIComponent(t)}catch{return null}}function js(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 _l(t){return t.replace(/[\r\n]+/g," ")}function tn(t){let e="";t.retryMs!==void 0&&(e+=`retry: ${t.retryMs}
|
|
11
|
+
`),t.event!==void 0&&(e+=`event: ${_l(t.event)}
|
|
12
|
+
`),t.id!==void 0&&(e+=`id: ${_l(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 Ns(t){return`: ${_l(t)}
|
|
16
|
+
|
|
17
|
+
`}function lo(t){return tn({id:String(t.seq),event:t.type,data:JSON.stringify(t)})}var vh="v1",Be={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},Ml=/^[\x21-\x7E]{1,128}$/,Ol=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,Bl=/^[a-z][a-z0-9_]*$/,Us=/^image\/(png|jpeg|webp|gif)$/,Ee={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"},nn={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"},Vv=new Set(Object.values(nn));function mr(t){return Vv.has(t)}var vn="server.replay.gap",fr={evicted:"evicted",aheadOfLog:"ahead_of_log"},VR=r.object({type:r.literal(vn),sessionId:r.string(),requestedAfterSeq:r.number().int(),oldestRetainedSeq:r.number().int().optional(),reason:r.enum([fr.evicted,fr.aheadOfLog]).optional(),droppedEvents:r.number().int().nonnegative()}).strict(),Fs="ts",Ls="x-tansr-signature",uo=r.lazy(()=>r.object({type:r.enum(["string","number","boolean","array","object"]),description:r.string().max(Be.toolDescriptionMaxChars).optional(),optional:r.boolean().optional(),items:uo.optional(),properties:r.record(uo).optional()}).strict());function Pl(t){let e=0;if(t.items!==void 0&&(e=Math.max(e,Pl(t.items))),t.properties!==void 0)for(let n of Object.values(t.properties))e=Math.max(e,Pl(n));return e+1}var $v=r.enum(["irreversible","financial","external","affects-others"]),fo=r.object({name:r.string().regex(Ol),description:r.string().min(1).max(Be.toolDescriptionMaxChars),parameters:r.record(uo).optional(),readOnly:r.boolean().optional(),effects:r.array($v).max(4).refine(t=>new Set(t).size===t.length,{message:"effects must not repeat"}).optional(),timeoutMs:r.number().int().min(Be.toolTimeoutMinMs).max(Be.toolTimeoutCapMs).optional()}).strict().superRefine((t,e)=>{if(t.parameters===void 0)return;let n=JSON.stringify(t.parameters);if(Buffer.byteLength(n,"utf8")>Be.toolParametersMaxBytes){e.addIssue({code:r.ZodIssueCode.custom,path:["parameters"],message:`parameters exceeds ${Be.toolParametersMaxBytes} bytes`});return}for(let[i,o]of Object.entries(t.parameters))Pl(o)>Be.toolParametersMaxDepth&&e.addIssue({code:r.ZodIssueCode.custom,path:["parameters",i],message:`parameter nesting exceeds depth ${Be.toolParametersMaxDepth}`})}),zs=r.object({prompt:r.string().optional(),model:r.string().optional(),profile:r.string().optional(),labels:Jo.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(Ml)}).optional(),resume:r.object({sessionId:r.string().min(1)}).optional(),clientTools:r.array(fo).max(Be.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()}),ql=r.discriminatedUnion("t",[r.object({t:r.literal("text"),text:r.string().min(1).max(Be.textBlockMaxChars)}),r.object({t:r.literal("image"),mime:r.string().regex(Us),data:r.string().min(1)})]),Hs=r.object({prompt:r.string().optional(),blocks:r.array(ql).min(1).max(Be.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"})}),Dl=r.object({historyEpoch:r.string().min(1).max(128),turnId:r.string().min(1).max(128)}).strict(),bh=r.object({inputId:r.string().min(1).max(128),target:Dl,content:r.union([r.object({text:r.string().min(1).max(Be.textBlockMaxChars)}).strict(),r.object({blocks:r.array(r.object({t:r.literal("text"),text:r.string().min(1).max(Be.textBlockMaxChars)}).strict()).min(1).max(Be.blocksMaxItems)}).strict()]),ack:r.enum(["memory","durable"]).optional()}).strict(),jl=If.superRefine((t,e)=>{t.t==="image"&&!Us.test(t.mime)&&e.addIssue({code:r.ZodIssueCode.custom,path:["mime"],message:"unsupported image mime"})}),pr=r.discriminatedUnion("status",[r.object({status:r.literal("ok"),content:r.array(jl).min(1).max(Be.receiptContentMaxItems),isError:r.boolean().optional()}),r.object({status:r.literal("error"),message:r.string().min(1).max(Be.receiptErrorMessageMaxChars)})]),Nl={expiredOnArrival:"expired_on_arrival"},Gs=r.object({digest:r.string().min(1),verdict:r.enum(["allow","deny"]),reason:r.enum([Nl.expiredOnArrival]).optional()}),Ws=r.object({answers:r.array(r.object({questionId:r.string().min(1),selectedOptionIds:r.array(r.string()),freeText:r.string().max(Be.answerFreeTextMaxChars).optional()})).min(1)});function Vs(t){if(t===null||t==="")return[];let e=t.split(",").map(n=>n.trim()).filter(n=>n!=="");if(e.length>Be.excludeTokensMax)return null;for(let n of e)if(!Bl.test(n))return null;return e}function mo(t,e){for(let n of e)if(t===n||t.startsWith(n+"."))return!0;return!1}var Ui=120,Ul=4096,Fl=r.union([r.boolean(),r.object({label:r.string().max(Ui).optional()})]),$s=r.object({instructions:r.string().max(Ul).optional(),checkpoint:Fl.optional()}),Ks=r.object({label:r.string().max(Ui).optional()}),Qs=r.object({checkpoint:r.boolean().optional()}),Js=r.object({cwd:r.string().min(1)}),po=32*1024*1024,Ys="application/octet-stream",Xs="import",ho=32*1024*1024,Ll=/^(data:audio\/[a-z0-9.+-]+;base64,|https?:\/\/)/i,zl=["wav","mp3"],Hl=16,Gl=64,Wl=2048,Vl=2e4,Zs=r.object({model:r.string().min(1).optional(),audio:r.string().regex(Ll),language:r.string().min(2).max(Hl).optional(),diarize:r.boolean().optional(),prompt:r.string().max(Wl).optional()}),ea=r.object({model:r.string().min(1).optional(),input:r.string().max(Vl).refine(t=>t.trim().length>0,{message:"input must not be blank"}),voice:r.string().min(1).max(Gl).optional(),format:r.enum(zl).optional(),speed:r.number().positive().optional()}),Sh=["transcriptions","speech"];var Kl=15e3,Ql=3e3,Jl=20,Kv=Ns("hb");function gr(t,e){return tn({event:vn,data:JSON.stringify({type:vn,sessionId:t,requestedAfterSeq:-1,droppedEvents:e})})}var $l=class{#e;#n;#r;#s;#t=!1;#o;#i=[];#a=[];#c=0;#d;#f;#p=0;#m=!1;#w=0;#v=!1;#k=!1;#y=!1;#B=!1;#C=0;#H=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.#m&&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.#m){this.#_();return}if(this.#c>this.#n.maxBufferBytes){this.#N(),this.#t&&this.#i.length>1&&this.#c>this.#n.maxBufferBytes&&this.#U(),this.#m&&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.#m&&!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.#m||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.#m,queuedBytes:this.#c,queuedFrames:this.#i.length,writes:this.#H,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.#m)&&this.#N()}#N(){if(this.#y||this.#t||this.#m&&(!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:Be.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.#m)return;this.#m=!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.#m&&!this.#y;){let e=this.#E();if(e===void 0)break;this.#u(e)}this.#k&&!this.#y&&!this.#m&&this.#d===void 0&&this.#f===void 0&&this.#i.length===0&&this.#I()}#E(){if(this.#d!==void 0||this.#f!==void 0){let e=this.#q();if(e!==void 0)return e}if(this.#i.length!==0)return this.#Y()}#q(){let e=this.#n.maxBufferBytes,n=[],i=0;for(this.#f!==void 0&&(n.push(this.#f),i=this.#p,this.#f=void 0,this.#p=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.#p=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.#C>0){if(n=this.#r?.(this.#C)??"",i=Buffer.byteLength(n,"utf8"),!this.#T(i))return;if(this.#C=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.#C>0&&(this.#r!==void 0&&(l=this.#r(this.#C)+l),this.#C=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.#H+=1;let i=n.socket;i?.cork();let o=n.write(e);i?.uncork(),!o&&!this.#m&&(this.#m=!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.#C+=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.#p=0,e!==void 0)try{e.return?.()}catch{}this.#m&&(this.#m=!1,this.#n.onResumed()),this.#n.detach(this)}},hr=class{#e=new Set;#n=[];#r=!1;#s;#t;#o;#i;#a;#c;#d;#f=0;#p=0;#m=0;#w=0;#v=0;#k=0;constructor(e={}){this.#t=e.heartbeatMs??Kl,this.#o=e.flushSliceMs??Jl,this.#c=e.retryMs??Ql,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??Be.maxSubscriberBufferBytes,maxFrameBytes:n,slowGraceMs:e.slowGraceMs??Be.slowSubscriberGraceMs,policy:e.onSlowSubscriber??"disconnect",now:i,markDirty:o=>this.#B(o),onPaused:()=>{this.#f+=1},onResumed:()=>{this.#f-=1},onQueued:o=>{this.#p+=o},onDequeued:o=>{this.#p-=o},onWrite:o=>{this.#m+=1,this.#w+=o},onDropped:o=>{this.#v+=o},onSlowDisconnect:()=>{this.#k+=1},detach:o=>this.#H(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 $l(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(tn({retryMs:this.#y(),data:""})),i}stats(){return{activeSubscribers:this.#e.size,pausedSubscribers:this.#f,queuedBytes:this.#p,writes:this.#m,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.#C))}#C=()=>{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.#C))};#H(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(Kv)}};function ta(...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 hi=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.#p();this.#c+=1,this.#d=e.seq;return}for(this.#i===this.#e&&this.#p();this.#i>0&&this.#a+i>this.#n;)this.#p();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}#p(){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 na(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 Qv=6e4;function*Jv(t){for(let e of t)yield lo(e)}function Yl(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;#p;#m;#w;#v;#k=0;#y=0;constructor(e){this.#i=e,this.#p=e.retentionMs??1/0,this.#m=e.maxRetainedSessions??1/0,this.#w=e.now??Date.now,this.#f=this.#p!==1/0||this.#m!==1/0;let n=e.sweepIntervalMs??Qv;this.#p!==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 hi(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:vn,sessionId:e,requestedAfterSeq:n,...s!==void 0?{oldestRetainedSeq:s}:{},droppedEvents:o.buffer.droppedCount()};i.write(tn({event:vn,data:JSON.stringify(a)}))}return Yl(i,Jv(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.#p===1/0)return;let e=this.#w();for(;;){let n=this.#C();if(n===void 0)break;let[i,o]=n;if(o.endedAt===void 0||e-o.endedAt<this.#p)break;this.#e.delete(i),this.#k+=1}this.#H()}#B(e){for(this.#c.push(e);this.#e.size-this.#a>this.#m;){let n=this.#C();if(n===void 0)break;this.#e.delete(n[0]),this.#y+=1}}#C(){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.#H()}#H(){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 na(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?lo(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 Yv}from"node:perf_hooks";var Xv=5e3,Zv=1e3,eb=6e4,tb=20;function $t(t){return{"retry-after":String(Math.max(1,Math.ceil(t/1e3)))}}function ri(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 Kn(t,e){let n=$t(e.retryAfterMs);if(e.reason==="rate_limited"){me(t,429,Ee.rateLimited,le.rateLimited,void 0,n);return}if(e.reason==="draining"){me(t,503,Ee.draining,le.draining,void 0,n);return}me(t,503,Ee.overloaded,le.overloaded,void 0,n)}function nb(t){let e=Yv({resolution:tb});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 wh(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??Xv,o=t.rejectLogIntervalMs??eb,s=e.now??Date.now,a=e.logger,d,c=t.eldSampler;c===void 0&&t.eventLoopDelayP99Ms!==void 0&&(d=nb(t.eventLoopDelayWindowMs??Zv),c=d.p99Ms);let l=0,f=new Map,u=0,p=!1,h=!1,g={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},m=new Map,v=(R,A,C=i)=>{if(g[R]+=1,R!=="draining"&&a!==void 0){let B=s(),Y=m.get(R);if(Y===void 0||B-Y>=o){m.set(R,B);try{a.error(We(le.admissionRejected,{reason:R,detail:A}))}catch{}}}return{admitted:!1,reason:R,retryAfterMs:C}},b=()=>c?.(),x=()=>p?{reason:"draining"}:c!==void 0&&c()>n.eventLoopDelayP99Ms?{reason:"event_loop_delay"}:null;return{tryAdmitSession(){let R=x();if(R!==null)return v(R.reason,R.reason==="event_loop_delay"?`p99=${(b()??0).toFixed(1)}ms max=${n.eventLoopDelayP99Ms}ms`:"draining");let A=e.activeSessions();return A>=n.maxActiveSessions?v("max_active_sessions",`active=${A} max=${n.maxActiveSessions}`):{admitted:!0}},tryAdmitSse(R){if(l>=n.maxSseConnections)return v("max_sse_connections",`connections=${l} max=${n.maxSseConnections}`);if(R!==void 0){let A=f.get(R)??0;if(A>=n.maxSseConnectionsPerEndUser)return v("max_sse_connections_per_end_user",`connections=${A} max=${n.maxSseConnectionsPerEndUser}`);f.set(R,A+1)}return l+=1,{admitted:!0}},releaseSse(R){if(l=Math.max(0,l-1),R===void 0)return;let A=f.get(R);A!==void 0&&(A<=1?f.delete(R):f.set(R,A-1))},reserveBody(R){return u+R>n.maxInflightBodyBytes?v("max_inflight_body_bytes",`inflight=${u} request=${R} max=${n.maxInflightBodyBytes}`):(u+=R,{admitted:!0})},releaseBody(R){u=Math.max(0,u-R)},async rateLimit(R,A){if(t.rateLimit===void 0)return{admitted:!0};let C;try{C=await t.rateLimit(R,A)}catch(Y){try{a?.error(We(le.requestUnhandled,{method:"rateLimit",path:"/v2/sessions",message:Y instanceof Error?Y.message:String(Y)}))}catch{}return{admitted:!0}}if(C==="allow")return{admitted:!0};let B=Number.isFinite(C.retryAfterMs)&&C.retryAfterMs>0?C.retryAfterMs:i;return v("rate_limited",`retryAfterMs=${B}`,B)},overloaded:x,readiness(){let R=[];return p&&R.push("draining"),c!==void 0&&c()>n.eventLoopDelayP99Ms&&R.push("event_loop_delay"),{ready:R.length===0,reasons:R}},beginDrain(){p=!0},get draining(){return p},retryAfterMs:i,stats(){let R=b();return{activeSessions:e.activeSessions(),sseConnections:l,inflightBodyBytes:u,...R!==void 0?{eventLoopDelayP99Ms:R}:{},draining:p,rejected:{...g},limits:{...n}}},close(){h||(h=!0,d?.close(),d=void 0)}}}import{monitorEventLoopDelay as vb}from"node:perf_hooks";import{randomUUID as fb}from"node:crypto";var ra=["messages","inputs","input-capabilities","events","interrupt","history","tool-results","permission","questions","compact","checkpoints","cwd","audio"],kh=new RegExp(`^\\/v2\\/sessions\\/([^/]+)(?:\\/(${ra.join("|")})(?:\\/([^/]+)(?:\\/(restore|export))?)?)?$`);function ib(t){let e=t.split("/").map(n=>n.startsWith(":")?"[^/]+":n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\/");return new RegExp(`^${e}$`)}function dt(t,e,n){return{method:t,endpoint:e,action:n,pattern:ib(n)}}var oa=[dt("POST","SDK2-initialize","/v2/sessions/:id/initialize"),dt("GET","SDK2-capabilities","/v2/sessions/:id/execution-capabilities"),dt("GET","SDK2-boundary","/v2/sessions/:id/execution-boundary"),dt("POST","SDK2-binding","/v2/sessions/:id/execution-bindings"),dt("GET","SDK2-execution","/v2/sessions/:id/executions/:targetId"),dt("POST","SDK2-executor","/v2/executors/connections"),dt("POST","SDK2-heartbeat","/v2/executors/:id/heartbeats"),dt("GET","SDK2-poll","/v2/executors/:id/operations"),dt("POST","SDK2-receipt","/v2/executors/:id/receipts")],Fi=[dt("POST","①","/v2/sessions"),dt("GET","②","/v2/sessions"),dt("GET","③","/v2/sessions/:id"),dt("DELETE","④","/v2/sessions/:id"),dt("POST","⑤","/v2/sessions/:id/messages"),dt("GET","⑥","/v2/sessions/:id/events"),dt("POST","⑦","/v2/sessions/:id/interrupt"),dt("GET","⑧","/v2/sessions/:id/history"),dt("POST","⑨","/v2/sessions/:id/tool-results/:targetId"),dt("POST","⑩","/v2/sessions/:id/permission/:targetId"),dt("POST","⑪","/v2/sessions/:id/questions/:targetId"),dt("POST","⑫","/v2/sessions/:id/compact"),dt("GET","⑬","/v2/sessions/:id/checkpoints"),dt("POST","⑭","/v2/sessions/:id/checkpoints"),dt("POST","⑱","/v2/sessions/:id/checkpoints/import"),dt("POST","⑮","/v2/sessions/:id/checkpoints/:targetId/restore"),dt("GET","⑰","/v2/sessions/:id/checkpoints/:targetId/export"),dt("DELETE","⑯","/v2/sessions/:id/checkpoints/:targetId"),dt("POST","⑲","/v2/sessions/:id/cwd"),dt("POST","⑳","/v2/sessions/:id/audio/transcriptions"),dt("POST","㉑","/v2/sessions/:id/audio/speech"),dt("GET","INJ-capabilities","/v2/sessions/:id/input-capabilities"),dt("POST","INJ-submit","/v2/sessions/:id/inputs"),dt("GET","INJ-status","/v2/sessions/:id/inputs/:targetId")];function xh(t){for(let e of[...Fi,...oa])if(e.pattern.test(t))return e.action}var Fn="unified-v1",Li={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 sa="/api/manifest",Xl="/api/capabilities",gi=t=>t[1]??"",rb=[{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${gi(t)}`},{domain:"terminal-profile",match:/^\/api\/terminal\/profile(\/.*)?$/,rewrite:t=>`/v3/terminal-profile${gi(t)}`},{domain:"terminal",match:/^\/api\/terminal(\/.*)?$/,rewrite:t=>`/v3/terminal${gi(t)}`},{domain:"cache",match:/^\/api\/cache(\/.*)?$/,rewrite:t=>`/v3/sdk2/cache${gi(t)}`},{domain:"archive-sync",match:/^\/api\/archive\/sync(\/.*)?$/,rewrite:t=>`/v3/sdk2/archive-sync${gi(t)}`},{domain:"archive",match:/^\/api\/archive\/bindings(\/.*)?$/,rewrite:t=>`/v3/sdk2/bindings${gi(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${gi(t)}`},{domain:"execution",match:/^\/api\/executors(\/.*)?$/,rewrite:(t,e)=>`${e.offloadSessions?"/v3/sdk2":"/v2"}/executors${gi(t)}`}];function Rh(t,e){for(let n of rb){let i=n.match.exec(t);if(i!==null)return{domain:n.domain,legacyPathname:n.rewrite(i,e)}}}function ob(t){let e=t.split("/").map(n=>n.startsWith(":")?"[^/]+":n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\/");return new RegExp(`^${e}$`)}var Ih=t=>({template:t,pattern:ob(t)}),sb=[...new Set([...Fi,...oa].map(t=>t.action.slice(3)))],Th=["/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",...sb.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"],ab=Th.map(Ih);function Zl(t){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 db="/api/sessions/:id/capabilities",cb=["/api/sessions/:id/memory/commands/:targetId","/api/sessions/:id/memory/commands","/api/sessions/:id/memory","/api/sessions/:id/configuration"],lb=[sa,Xl,db,...cb,...new Set([...Th,...Fi.map(t=>t.action),...oa.map(t=>t.action)].map(Zl).filter(t=>t!==void 0))],ub=lb.map(Ih);function Ah(t){for(let e of ab)if(e.pattern.test(t))return e.template}function Ch(t){for(let e of ub)if(e.pattern.test(t))return e.template}var mb=/^\/v1\/sessions\/[^/]+\/(messages|events|abort)$/,pb=/^\/v1\/approvals\/[^/]+\/credential$/,bn={healthz:"/healthz",readyz:"/readyz",metrics:"/metrics"};function aa(t){if(t.startsWith("/api/"))return Ch(t)??"other";if(t.startsWith("/v3/"))return Ah(t)??"other";switch(t){case"/v1/sessions":case"/v1/status":case bn.healthz:case bn.readyz:case bn.metrics:return t;default:break}let e=mb.exec(t);return e!==null?`/v1/sessions/:id/${e[1]}`:pb.test(t)?"/v1/approvals/:id/credential":xh(t)??"other"}var go="x-request-id",hb=/^[A-Za-z0-9._-]{1,128}$/,gb=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function Eh(t){if(t!==void 0)return Array.isArray(t)?t[0]:t}function da(t){let e=Eh(t.headers[go])?.trim();if(e!==void 0&&hb.test(e))return e;let n=Eh(t.headers.traceparent)?.trim().toLowerCase();if(n!==void 0){let i=gb.exec(n);if(i!==null&&i[1]!=="ff"&&!/^0{32}$/.test(i[2]))return i[2]}return fb()}var _h=new WeakMap,Ph=new WeakMap;function Mh(t,e,n){_h.set(t,n),Ph.set(e,n)}function yr(t){return _h.get(t)}function Oh(t){return Ph.get(t)}var yb=Vf.filter(t=>t<=3e4),Bh=new WeakMap;function Ln(t=ui){let e=Bh.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.",yb,["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 Bh.set(t,n),n}function ca(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 qh(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 la(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:")?la(e.slice(7)):/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function bb(){let t;try{t=vb({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 Sb(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 wb(t,e){return typeof t=="boolean"?{ready:t,reason:`probe_${e}`}:{ready:t.ready,reason:t.reason??`probe_${e}`}}function Dh(t){let e=t.options??{},n=t.now??Date.now,i=e.metrics??ui,o=Ln(i);os(ui);let s=la(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=bb(),p=new Set(e.readinessProbes??[]),h=new Set,g=0,m=0,v=!1,b=()=>u.sample(),x=()=>{let S=t.v1Active(),w=t.v2();o.sessionsActive.set(S,{face:"v1"}),o.sessionsActive.set(w?.active??0,{face:"v2"}),w?.pending!==void 0&&o.sessionsPending.set(w.pending),w?.retainedEnded!==void 0&&o.sessionsRetainedEnded.set(w.retainedEnded),o.sseConnectionsActive.set(g);let T=b();o.eventLoopDelayMs.set(T.p50,{stat:"p50"}),o.eventLoopDelayMs.set(T.p99,{stat:"p99"}),o.eventLoopDelayMs.set(T.max,{stat:"max"}),o.residentMemoryBytes.set(process.memoryUsage.rss());let _=t.notifierStats();_!==void 0&&(o.webhookDeliveries.set(_.delivered,{result:"delivered"}),o.webhookDeliveries.set(_.failed,{result:"failed"}),o.webhookDeliveries.set(_.droppedQueueFull,{result:"dropped_queue_full"}),o.webhookDeliveries.set(_.droppedCircuitOpen,{result:"dropped_circuit_open"}));let G=t.sseStats?.();G!==void 0&&o.sseFramesWritten.set(G.frames);let V=t.ringStats?.();V!==void 0&&o.ringEvictions.set(V.dropped);let te=R();if(te!==void 0){for(let re of te.origins){let M={origin:re.origin};o.upstreamInflight.set(re.inflight,M),o.upstreamQueued.set(re.queued+re.tokenQueued,M),o.upstreamBreakerState.set(re.breakerStateCode,M);for(let[k,j]of Object.entries(re.rejected))o.upstreamRejections.set(j,{origin:re.origin,reason:k})}o.upstreamRetriesBudgeted.set(te.totals.retriesBudgeted)}},R=()=>{if(t.governorStats!==void 0)try{return t.governorStats()}catch{return}},A=i.onCollect(x),C=()=>{let S=[];t.closing()&&S.push("closing");let w=0;for(let T of p){w+=1;try{let _=wb(T(),w);_.ready||S.push(_.reason)}catch{S.push(`probe_${w}_threw`)}}return{ready:S.length===0,reasons:S}},B=()=>{let S=t.v1Active(),w=t.v2(),T=process.memoryUsage(),_=t.notifierStats(),G=t.ringStats?.(),V=R();return{uptimeMs:n()-t.startedAt,closing:t.closing(),sessions:{active:S+(w?.active??0),byFace:{v1:S,v2:w?.active??0},...w?.pending!==void 0?{pending:w.pending}:{},...w?.retainedEnded!==void 0?{retainedEnded:w.retainedEnded}:{}},sse:{connectionsActive:g,framesWritten:t.sseStats?.()?.frames??o.sseFramesWritten.get()},http:{inflight:h.size,requestsTotal:m},replay:{gapTotal:o.replayGaps.get(),ringEvictionsTotal:G?.dropped??o.ringEvictions.get(),...G!==void 0?{ringEvents:G.size,ringBytes:G.bytes}:{}},eventLoopDelayMs:b(),memory:{rssBytes:T.rss,heapUsedBytes:T.heapUsed},..._!==void 0?{notifier:_}:{},...V!==void 0?{upstream:V}:{},readiness:C()}},Y=(S,w)=>{let T;if(w.startsWith("/v1/sessions/:id")||w.startsWith("/v2/sessions/:id")||w.startsWith("/api/sessions/:id"))T=3;else if(w.startsWith("/v3/sdk2/sessions/:id"))T=4;else return;let _=S.split("/")[T];if(_===void 0)return;let G=pi(_)??_;return G.length>128?`${G.slice(0,125)}...`:G},ne=(S,w)=>{let T=S.method??"GET",_=(S.url??"/").split("?",1)[0],G=aa(_),V={requestId:da(S),startedAt:n(),method:T,route:G,sse:!1};Mh(S,w,V),h.add(V),w.headersSent||w.setHeader(go,V.requestId);let te=Y(_,G),re=()=>({requestId:V.requestId,method:T,route:G,...te!==void 0?{sessionId:te}:{},...V.endUserId!==void 0?{endUserId:V.endUserId}:{}}),M=w.writeHead,k=!1,j=Q=>{if(k)return;k=!0;let U=Sb(w,Q);U!==void 0&&U.startsWith("text/event-stream")&&(V.sse=!0,g+=1,t.log("info",at.sseOpened,re()))};w.writeHead=function(...U){let ue=M.apply(this,U);return j(U),ue};let W=!1,q=()=>{if(W)return;W=!0,h.delete(V),m+=1,V.sse&&(g=Math.max(0,g-1));let Q=w.headersSent?w.statusCode:0,U=Math.max(0,n()-V.startedAt),ue={method:T,route:G,status:String(Q)};o.httpRequests.inc(ue),o.httpRequestDurationMs.observe(U,{route:G});let pe=ca(Q);pe!==void 0&&o.rejections.inc({code:pe}),V.sse&&t.log("info",at.sseClosed,{...re(),reason:w.writableEnded?"ended":"aborted",durationMs:U}),f()&&t.log("info",at.requestCompleted,{...re(),status:Q,durationMs:U,...V.sse?{sse:!0}:{}})};return w.once("close",q),V},N=(S,w,T,_)=>{let G=T===bn.healthz||T===bn.readyz,V=T===bn.metrics;if(!(G&&a)&&!(V&&d))return!1;if(_!=="GET"&&_!=="HEAD")return me(w,405,"method_not_allowed",le.methodNotAllowed,{method:_,path:T},{allow:"GET"}),!0;if(T===bn.healthz)return Je(w,200,{status:"ok"}),!0;if(T===bn.readyz){let re=C();return Je(w,re.ready?200:503,re),!0}let te=X();return w.writeHead(200,{"content-type":rs,"content-length":Buffer.byteLength(te),"cache-control":"no-store"}),w.end(_==="HEAD"?void 0:te),!0},X=()=>is([ui,i]);return{metrics:o,registry:i,exposeHealth:a,exposeMetrics:d,trackRequest:ne,handleEndpoint:N,stats:B,readiness:C,renderMetrics:X,addReadinessProbe:S=>(p.add(S),()=>{p.delete(S)}),sseActive:()=>g,close:()=>{v||(v=!0,A(),u.dispose())}}}var yo="TANSR_READY ",jh=1,Nh=["stdout","stderr","none"];function eu(t){let e={v:1,url:t.url,pid:t.pid,readyz:t.readyz};return`${yo}${JSON.stringify(e)}
|
|
18
|
+
`}function Uh(t){let e=t.replace(/\r?\n$/u,"");if(!e.startsWith(yo))return;let n;try{n=JSON.parse(e.slice(yo.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 ua(t,e){let n=t??"stdout";if(n==="none")return;let i=eu(e);try{typeof n=="function"?n(i):n==="stderr"?process.stderr.write(i):process.stdout.write(i)}catch{}}import{createHash as kb,createHmac as Fh,randomUUID as xb}from"node:crypto";var Lh=["v1","v2"],tu=["v2","v1"];function nu(t){let e=[],n={};for(let i of t.versions){if(i==="v1"){e.push(`v1=${Fh("sha256",t.secret).update(t.body,"utf8").digest("hex")}`);continue}let o=[jr.canonicalPrefix,(t.method??"POST").toUpperCase(),t.path,String(t.timestampMs),t.nonce,kb("sha256").update(t.body,"utf8").digest("hex")].join(`
|
|
19
|
+
`);e.push(`${jr.prefix}${Fh("sha256",t.secret).update(o).digest("hex")}`),n[jr.headers.timestamp]=String(t.timestampMs),n[jr.headers.nonce]=t.nonce}return e.length>0&&(n[Ls]=e.join(", ")),n}var vr=class{#e;#n;#r;#s;#t;#o;#i;#a;#c;#d;#f;#p;#m;#w;#v=new Set;#k=[];#y=new AbortController;#B=!1;#C="closed";#H=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??tu)],this.#s=(()=>{try{return new URL(e.url).pathname}catch{return""}})(),this.#t=e.maxRetries??Be.notifyMaxRetries,this.#o=e.timeoutMs??Be.notifyTimeoutMs,this.#i=e.backoffMs??Be.notifyBackoffMs,this.#a=e.maxInflight??Be.notifyMaxInflight,this.#c=e.maxQueue??Be.notifyMaxQueue,this.#d=e.breakerFailureThreshold??Be.notifyBreakerFailureThreshold,this.#f=e.breakerOpenMs??Be.notifyBreakerOpenMs,this.#p=e.fetchImpl??fetch,this.#m=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.#q(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.#E(),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.#C==="closed"?!0:this.#C==="open"&&this.#m()>=this.#H?(this.#C="half_open",!0):!1}#E(){return this.#C==="open"&&this.#m()>=this.#H?"half_open":this.#C}#q(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.#q(e)}}#I(){this.#J+=1,this.#S=0,this.#C="closed"}#u(){if(this.#U+=1,this.#S+=1,!(this.#C!=="closed"||this.#S>=this.#d))return;this.#C="open",this.#H=this.#m()+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,nu({secret:this.#n,body:n,versions:this.#r,path:this.#s,timestampMs:this.#m(),nonce:xb()}));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.#p(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 br=class{#e;#n;#r;constructor(e,n={}){let{floorSeq:i,...o}=n;if(this.#e=new hi(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 ma(t){if(mr(t.type)){let e=t;return tn({id:String(t.seq),event:t.type,data:JSON.stringify({...e.payload,[Fs]:e.ts})})}return tn({id:String(t.seq),data:JSON.stringify(t)})}function*Rb(t,e,n){for(let i of t)n&&i.seq<n()||!mr(i.type)&&mo(i.type,e)||(yield ma(i))}var iu=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()}},oi=class extends Error{constructor(){super("registry is closing; new sessions are not accepted"),this.name="RegistryClosingError"}},fa=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;#p=new Map;#m=new Map;#w=0;#v=0;#k;#y;#B;#C;#H;#S;#g;#N;#J;#U;#j;#E;#q;#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.#C=e.eventLog,this.#H=e.retentionMs??Be.retentionMs,this.#S=e.idleTimeoutMs??Be.idleTimeoutMs,this.#g=e.maxSessionsPerEndUser??Be.maxSessionsPerEndUser,this.#N=e.maxRetainedSessions??1/0,this.#J=e.orphanGraceMs??Be.orphanGraceMs,this.#U=e.idleAfterGoneMs??Be.idleAfterGoneMs,this.#j=e.maxSessionLifetimeMs??1/0,this.#E=e.maxTurnsPerSession??1/0,this.#q=e.onSubscribersGone,this.#Y=e.notifyDeferMs??Be.notifyDeferMs,this.#I=e.now??Date.now,this.#u=e.onPumpError,this.#_=e.onSweep,this.#T=e.onTurnEndNotify;let n=e.sweepIntervalMs??Be.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.#F(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 iu(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 oi;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.#F(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.#p.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.#D(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}}#F(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.#C!==void 0?this.#C({sessionId:e.sessionId,endUserId:e.endUserId,...n>0?{epochStartSeq:n}:{}}):new br(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)}}}#D(e,n){n.replayWaiters.size>0&&this.#me(n,new Error("Event publication was evicted")),this.#i.delete(e),this.#p.delete(e),this.#m.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.#D(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.#p.delete(e),this.#p.set(e,n),n.goneSince!==void 0&&(n.goneSince=i,n.goneRunningDecided=!1,n.goneIdleDecided=!1,this.#m.delete(e),this.#m.set(e,n)))}#Re(e,n){n.ended||(n.goneSince=this.#I(),n.goneRunningDecided=!1,n.goneIdleDecided=!1,this.#m.delete(e),this.#m.set(e,n))}#Ie(e,n){n.goneSince=void 0,n.goneRunningDecided=!1,n.goneIdleDecided=!1,this.#m.delete(e),this.#p.delete(e),this.#p.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 oi):!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})})}#me(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 g=s.handle.firstSeq?.()??s.epochStartSeq;return g>s.epochStartSeq?g: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,p=(n>=0||d>0)&&n<l-1;if(c.gap||u||p){let g={type:vn,sessionId:e,requestedAfterSeq:n,...c.oldestRetainedSeq!==void 0&&c.oldestRetainedSeq>=d?{oldestRetainedSeq:c.oldestRetainedSeq}:{},droppedEvents:c.dropped,reason:u?fr.aheadOfLog:fr.evicted};i.write(tn({event:vn,data:JSON.stringify(g)}))}if(Yl(i,Rb(c.events,o,a)),s.ended)return i.end(),()=>{};let h={raw:i,excludes:o};return s.subscribers.add(h),s.lastActivityAt=this.#I(),this.#Ie(e,s),s.handle.noteSubscribers(s.subscribers.size),()=>{s.subscribers.delete(h)&&(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.#H)break;this.#D(o,s),this.#Q.evictedByRetention+=1}this.#ye();for(let[i,o]of this.#p){if(o.ended){this.#p.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.#m){if(o.ended){this.#m.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.#pe(o,"running",a,"interrupt"))):d==="idle"&&!o.goneIdleDecided&&a>=this.#U&&(o.goneIdleDecided=!0,this.#le(i,o,this.#pe(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)}}}#pe(e,n,i,o){if(this.#q===void 0)return o;try{let s=this.#q({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.#L(e,n,{source:"client_gone"}))}#L(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.#Ce(e),e.replayWaiters.size>0&&this.#me(e,new oi)}runningCount(){let e=0;for(let[n,i]of this.#p)!i.ended&&this.#ce(n,i)==="running"&&(e+=1);return e}interruptRunning(){let e=0;for(let[n,i]of this.#p)i.ended||this.#ce(n,i)!=="running"||(this.#L(n,i),e+=1);return e}broadcastRetry(e){let n=tn({retryMs:e,data:""}),i=0;for(let o of this.#p.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 na(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=mr(o.type),d=[...n.subscribers].filter(l=>a||!mo(o.type,l.excludes)),c=d.length>0||Number.isFinite(this.#B)?ma(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.#me(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.#Ce(n),n.turns+=1,n.turns>this.#E&&!n.closeRequested&&(this.#L(e,n),this.#se(e,n,"turnCapCloses"))):(o.type==="turn.completed"||o.type==="turn.aborted")&&(this.#be(n,o),n.turns>=this.#E&&!n.closeRequested&&this.#se(e,n,"turnCapCloses"))}}catch(o){i=o,n.closeFailure="publication_failed",n.closeRequested=!0,this.#me(n,o),this.#Q.pumpErrors+=1;try{n.handle.close()}catch{}this.#u?.(e,o)}finally{n.replayWaiters.size>0&&this.#me(n,i??new Error("Event publication ended before the requested watermark")),this.#he(n.handle),n.ended=!0,n.endedAt=this.#I(),this.#Ce(n),this.#de(e,n);for(let o of[...n.subscribers])o.raw.end();n.subscribers.clear()}}#Ce(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.#Ce(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 xw}from"node:events";import{randomUUID as uw}from"node:crypto";import{randomUUID as Ab}from"node:crypto";import{types as Cb}from"node:util";var vo=class extends Error{constructor(n){super(n);this.code=n;this.name="ArchiveHttpEventError"}code},Ib=262317;function zi(){let t=new Error("Archive event subscription aborted");return t.name="AbortError",t}async function ru(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 Tb(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 zh(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 ru(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 ru(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 ru(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>Ib)throw new vo("internal_error");n.write(f)||(await Tb(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 ou={ackBytes:262144,requestEnvelopeBytes:1024,responseEnvelopeBytes:4096,requestBytes:263168,responseBytes:528384},Ue={};Ue.ArchiveAckRequest=r.object({protocol:r.literal("sdk2-ext-v1"),request:r.lazy(()=>Ue.RequestIdentity),bindingId:r.lazy(()=>Ue.Id),expectedRevision:r.lazy(()=>Ue.Sequence),generations:r.lazy(()=>Ue.Generations),sourceId:r.lazy(()=>Ue.Id),sourceGeneration:r.lazy(()=>Ue.Id),coverage:r.lazy(()=>Ue.Coverage),attachments:r.array(r.lazy(()=>Ue.ArchiveArtifactReceipt)).min(0).max(128).refine(t=>new Set(t.map(e=>JSON.stringify(e))).size===t.length),ackFormat:r.lazy(()=>Ue.ArchiveAckFormat),payloads:r.array(r.lazy(()=>Ue.ArchiveArtifactReceipt)).min(1).max(128).refine(t=>new Set(t.map(e=>JSON.stringify(e))).size===t.length)}).strict();Ue.RequestIdentity=r.object({requestId:r.lazy(()=>Ue.Id),operationEpoch:r.lazy(()=>Ue.Id)}).strict();Ue.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);Ue.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);Ue.Generations=r.object({historyEpoch:r.lazy(()=>Ue.LegacyId),deletionGeneration:r.lazy(()=>Ue.Sequence),projectionRevision:r.lazy(()=>Ue.Sequence)}).strict();Ue.LegacyId=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);Ue.Coverage=r.object({fromSequence:r.lazy(()=>Ue.RecordSequence),throughSequence:r.lazy(()=>Ue.RecordSequence),headDigest:r.lazy(()=>Ue.Digest)}).strict();Ue.RecordSequence=r.lazy(()=>Ue.Sequence).refine(t=>t!=="0");Ue.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));Ue.ArchiveArtifactReceipt=r.object({artifactId:r.lazy(()=>Ue.Id),sha256:r.lazy(()=>Ue.Digest),state:r.literal("durably-stored")}).strict();Ue.ArchiveAckFormat=r.literal("split-receipts-v1");Ue.MutationReceipt=r.object({protocol:r.literal("sdk2-ext-v1"),request:r.lazy(()=>Ue.RequestIdentity),bindingId:r.lazy(()=>Ue.Id),operation:r.union([r.literal("binding-create"),r.literal("archive-ack"),r.literal("material-response"),r.literal("binding-close")]),semanticDigest:r.lazy(()=>Ue.Digest),state:r.union([r.literal("accepted"),r.literal("completed"),r.literal("rejected")]),revision:r.lazy(()=>Ue.Sequence),outcomeRef:r.lazy(()=>Ue.Id)}).strict();Ue.AckRebaseRequest=r.object({protocol:r.literal("sdk2-ext-v1"),bindingId:r.lazy(()=>Ue.Id),previous:r.lazy(()=>Ue.ArchiveAckRequest),request:r.lazy(()=>Ue.RequestIdentity)}).strict();Ue.AckRebaseReceipt=r.object({protocol:r.literal("sdk2-ext-v1"),bindingId:r.lazy(()=>Ue.Id),previous:r.lazy(()=>Ue.ArchiveAckRequest),request:r.lazy(()=>Ue.RequestIdentity),next:r.lazy(()=>Ue.ArchiveAckRequest),receipt:r.lazy(()=>Ue.MutationReceipt)}).strict();function su(t){let e=Ue[t];if(!e)throw new Error("Unknown archive recovery contract");return e}var yi="sdk2-ext-v1",au=262144,Eb=611+512*6+38+8+6+8+128+4*Math.ceil(262144/3),mt=r.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._~-]*$/),bo=r.string().min(1).refine(t=>[...t].length<=512),rn=r.string().max(19).regex(/^(0|[1-9][0-9]*)$/).refine(t=>/^(0|[1-9][0-9]{0,18})$/.test(t)&&BigInt(t)<=9223372036854775807n),Wi=r.string().regex(/^[a-f0-9]{64}$/),So=r.object({historyEpoch:bo,deletionGeneration:rn,projectionRevision:rn}).strict(),wo=r.object({sessionId:bo,generations:So,sourceSnapshotDigest:Wi}).strict(),Gi=r.object({operationEpoch:mt,requestId:mt}).strict(),Vi={protocol:r.literal(yi),bindingId:mt},wt=(t,e)=>r.number().int().min(t).max(e),Hh=r.object({artifactId:mt,sha256:Wi,state:r.literal("durably-stored")}).strict(),_b=r.object({...Vi,request:Gi,ackFormat:r.literal("split-receipts-v1"),expectedRevision:rn,generations:So,sourceId:mt,sourceGeneration:mt,coverage:r.object({fromSequence:rn.refine(t=>t!=="0"),throughSequence:rn.refine(t=>t!=="0"),headDigest:Wi}).strict(),payloads:r.array(Hh).min(1).max(128),attachments:r.array(Hh).max(128)}).strict(),Pb=r.object({...Vi,materialRequestId:mt,target:wo,sourceId:mt,sourceGeneration:mt,artifactId:mt,offset:wt(0,1048576),bytes:wt(0,65536),chunkSha256:Wi,base64:r.string().max(87384).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict(),Gh=r.object({uploadId:mt}).strict(),Mb=r.object({...Vi,request:Gi,materialRequestId:mt,target:wo,sourceId:mt,sourceGeneration:mt,results:r.array(r.object({recordId:mt,digest:Wi,payload:Gh,attachments:r.array(Gh).max(128)}).strict()).min(1).max(32)}).strict(),Qh=r.enum(["archive-transfer-v1","context-materials-v1"]),ha=t=>r.array(Qh).min(t).max(2).refine(e=>new Set(e).size===e.length).readonly(),Jh=r.object({controlBytes:wt(1024,262144),recordBytes:wt(1024,262144),pageRecords:wt(1,128),pageBytes:wt(1024,1048576),attachmentBytes:wt(1024,33554432),chunkBytes:wt(1024,262144),materialConcurrent:wt(1,2),materialQueue:wt(1,16),materialCandidates:wt(1,32),materialBytes:wt(1024,1048576),materialDeadlineMs:wt(1e3,3e4),pendingRecords:wt(1,4096),pendingBytes:wt(1048576,67108864),inflightReserveBytes:wt(1048576,16777216),offlineMs:wt(1e3,864e5),eventRetentionMs:wt(1e3,6e5),eventRetentionFrames:wt(1,4096),eventRetentionBytes:wt(1024,8388608),terminalReceiptRetentionMs:wt(6e4,6048e5),epochLifetimeMs:wt(6e4,864e5),materialChunkBytes:wt(1,65536)}).strict().refine(t=>t.inflightReserveBytes<=t.pendingBytes),du=r.object({id:mt,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)),Ob=r.object({applicationScopeId:mt,endUserId:bo,authorizationRevision:rn}).strict(),Yh=r.enum(["active","backpressured","closing","closed"]),Bb=r.object({protocol:r.literal(yi),availability:r.literal("legacy-complete"),capabilities:ha(1),limits:Jh,operationEpoch:du,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)),qb=r.object({protocol:r.literal(yi),target:wo,revision:rn,bindingId:mt.nullable(),operationEpoch:du.nullable()}).strict(),Wh=r.object({...Vi,scope:Ob,target:wo,revision:rn,state:Yh,sourceId:mt,acceptedCapabilities:ha(1),rejectedCapabilities:r.array(r.object({capability:Qh,reason:r.enum(["unsupported_capability","not_authorized"])}).strict()).max(2).readonly(),availability:r.literal("legacy-complete"),operationEpoch:du.nullable(),limits:Jh,archiveAckFormat:r.literal("split-receipts-v1").nullable()}).strict().refine(t=>t.archiveAckFormat===(t.acceptedCapabilities.includes("archive-transfer-v1")?"split-receipts-v1":null)),Db=r.object({fromSequence:rn.refine(t=>t!=="0"),throughSequence:rn.refine(t=>t!=="0"),headDigest:Wi}).strict(),jb=r.object({...Vi,revision:rn,generations:So,sourceId:mt,sourceGeneration:mt,publishedThroughSequence:rn.nullable(),acknowledgedCoverage:Db.nullable(),releasableThroughSequence:rn.nullable(),pendingBytes:wt(0,67108864),pendingRecords:wt(0,4096),sessionPersistence:r.literal("unchanged"),state:Yh}).strict(),Nb=r.object({protocol:r.literal(yi),request:Gi,target:wo,expectedRevision:rn,requiredCapabilities:ha(1),optionalCapabilities:ha(0),archive:r.object({strategy:r.literal("single-authorized-source"),sourceId:mt,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))),Ub=r.object({...Vi,request:Gi,expectedRevision:rn,generations:So}).strict(),Vh=r.object({...Vi,request:Gi,operation:r.enum(["binding-create","archive-ack","binding-close"]),semanticDigest:Wi,state:r.literal("completed"),revision:rn,outcomeRef:mt}).strict(),Xh={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 ya(t){return Xh[t]}var ga=class extends Error{constructor(n){super(n);this.code=n;this.name="ArchiveHttpError"}code};function be(t){throw new ga(t)}function Ut(t,e){let n=t.safeParse(e);return n.success||be("invalid_request"),n.data}function Hi(t,e,n){try{let i=li(Zt(e,{maxBytes:n})),o=t.safeParse(i);if(o.success)return o.data}catch{}return be("internal_error")}function Fb(t,e){try{(!t||typeof t!="object"||Cb.isProxy(t)||Array.isArray(t)||![null,Object.prototype].includes(Object.getPrototypeOf(t)))&&be("internal_error");let n=Object.getOwnPropertyDescriptors(t),i={};for(let o of Reflect.ownKeys(n)){typeof o!="string"&&be("internal_error");let s=n[o];(!s.enumerable||!Object.hasOwn(s,"value"))&&be("internal_error"),i[o]=li(Zt(s.value))}return cu(i,e),Ut(su("AckRebaseReceipt"),i)}catch{return be("internal_error")}}function Lb(t){if(t instanceof ga||t instanceof vo)return t.code;if(t instanceof Bp)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 ll&&t.code==="dependency_held")return"source_unavailable";if(t instanceof Yo||t instanceof Nf||t instanceof Mp||t instanceof ll)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 cu(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&&be("capacity_exceeded"),i}function Qn(t,e,n,i=au){if(t.destroyed||t.writableEnded)return;let o=cu(n,i);t.writeHead(e,{"content-type":"application/json; charset=utf-8","content-length":o.length,"cache-control":"no-store"}),t.end(o)}function Zh(t){try{return decodeURIComponent(t)}catch{return be("invalid_request")}}function si(t,e,n=[]){let i=Object.create(null);for(let o of t.split("&")){let s=o.indexOf("=");(s<1||o.includes("+"))&&be("invalid_request");let a=o.slice(0,s),d=Zh(o.slice(s+1));(![...e,...n].includes(a)||Object.hasOwn(i,a)||d==="")&&be("invalid_request"),i[a]=d}return e.some(o=>!Object.hasOwn(i,o))&&be("invalid_request"),i.protocol!==yi&&be("protocol_version_mismatch"),i}function pa(t,e,n){return/^(0|[1-9][0-9]*)$/.test(t)||be("invalid_request"),Ut(wt(e,n),Number(t))}function $h(t){return Ut(So,{historyEpoch:t.historyEpoch,deletionGeneration:t.deletionGeneration,projectionRevision:t.projectionRevision})}function Kh(t,e){return t.historyEpoch===e.historyEpoch&&t.deletionGeneration===e.deletionGeneration&&t.projectionRevision===e.projectionRevision}async function zb(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")&&be("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&&be("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),cu(a,e).equals(d)||be("invalid_request")}else a=li(d,{maxBytes:e})}catch{return be("invalid_request")}return(!a||typeof a!="object"||Array.isArray(a))&&be("invalid_request"),a.protocol!==yi&&be("protocol_version_mismatch"),a}function eg(t){let e=t.host.controlBytes??au;Ut(wt(1024,au),e),Ut(mt,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=Ab(),f=(async()=>{(n>=128||t.admission.overloaded())&&be("capacity_exceeded"),n++,a=!0,Buffer.byteLength(s)>8192&&be("payload_too_large"),s.includes("#")&&be("invalid_request");let u=s.indexOf("?"),p=u<0?s:s.slice(0,u),h=u<0?"":s.slice(u+1),g=p.split("/").slice(3).map(Zh),m=i.method??"GET";m!=="GET"&&m!=="POST"&&be("invalid_request"),m==="GET"&&(i.headers["transfer-encoding"]!==void 0||i.headers["content-length"]!==void 0&&i.headers["content-length"]!=="0")&&be("invalid_request"),m==="POST"&&u>=0&&be("invalid_request");let v=m==="POST"&&g.length===4&&g[0]==="bindings"&&g[2]==="archive"&&g[3]==="ack-rebases";v&&(c+=ou.requestEnvelopeBytes),m==="POST"&&(t.admission.reserveBody(c).admitted||be("capacity_exceeded"),d=!0);let b=m==="POST"?await zb(i,c,v):void 0,x=async k=>{let j;try{j=await t.authenticate(i,o)}catch(W){return W instanceof Pt?be(W.code==="overloaded"?"capacity_exceeded":"source_unavailable"):be("unauthorized")}return(!j?.endUserId||k!==void 0&&j.endUserId!==k)&&be("unauthorized"),(i.aborted||o.destroyed||o.writableEnded)&&be("unauthorized"),j.endUserId},R=async()=>{let k=await x();return(await t.admission.rateLimit(i,k)).admitted||be("capacity_exceeded"),await x(k),k};if(g.length===1&&g[0]==="capabilities"&&m==="GET"){u>=0&&be("invalid_request");let k=await R(),j=t.host.capabilities;j||be("unsupported_capability");let W=await j.call(t.host,k);await x(k),t.host.capabilities!==j&&be("forbidden"),Qn(o,200,Hi(Bb,W,e),e);return}let A=g.length===3&&g[0]==="sessions"&&g[2]==="binding-target"&&m==="GET",C=g.length===1&&g[0]==="bindings"&&m==="POST",B;if(g.length===1&&g[0]==="operations"&&m==="GET"){let k=si(h,["protocol","operation","operationEpoch","requestId"],["bindingId","sessionId"]);k.operation==="binding-create"?((k.bindingId!==void 0||k.sessionId===void 0)&&be("invalid_request"),B=k):(k.sessionId!==void 0||k.bindingId===void 0)&&be("invalid_request")}if(A||C||B){let k,j,W;A?(si(h,["protocol"]),k=Ut(bo,g[1])):C?(j=Ut(Nb,b),k=j.target.sessionId,l=j.request.requestId):(k=Ut(bo,B.sessionId),W=Ut(Gi,{operationEpoch:B.operationEpoch,requestId:B.requestId}),l=W.requestId);let q=await R(),Q=t.host.resolveSession;Q||be("unsupported_capability");let U=Q.call(t.host,q,k);U||be("forbidden");let ue=async()=>{await x(q),(t.host.resolveSession!==Q||Q.call(t.host,q,k)!==U)&&be("forbidden")};if(A){let pe=U.readTarget,oe=await pe.call(U);await ue(),U.readTarget!==pe&&be("forbidden");let ee=Hi(qb,oe,e);ee.target.sessionId!==k&&be("forbidden"),Qn(o,200,ee,e)}else if(j){let pe=U.create;pe||be("unsupported_capability");let oe=await pe.call(U,j);await ue(),U.create!==pe&&be("forbidden");let ee=Hi(Wh,oe,e);(ee.target.sessionId!==k||ee.scope.applicationScopeId!==t.host.applicationScopeId||ee.scope.endUserId!==q)&&be("forbidden"),Qn(o,201,ee,e)}else{let pe=U.queryCreate;pe||be("unsupported_capability");let oe=await pe.call(U,W);await ue(),U.queryCreate!==pe&&be("forbidden"),oe===null&&be("receipt_expired");let ee=Hi(Vh,oe,e);(ee.operation!=="binding-create"||ee.request.operationEpoch!==W.operationEpoch||ee.request.requestId!==W.requestId)&&be("internal_error"),Qn(o,200,ee,e)}return}let Y=["historyEpoch","deletionGeneration","projectionRevision"],ne,N,X,S=Object.create(null),w=b;if(g.length===1&&g[0]==="operations"&&m==="GET")S=si(h,["protocol","operation","bindingId","operationEpoch","requestId"]),ne=Ut(mt,S.bindingId),Ut(Gi,{operationEpoch:S.operationEpoch,requestId:S.requestId}),["archive-ack","material-response","binding-close"].includes(S.operation)||be("unsupported_capability"),l=S.requestId,N="operation";else if(g[0]!=="bindings"&&be("invalid_request"),ne=Ut(mt,g[1]),g.length===2&&m==="GET")si(h,["protocol"]),N="view";else if(g.length===4&&g[2]==="archive"&&g[3]==="status"&&m==="GET")si(h,["protocol"]),N="archive-status";else if(g.length===3&&g[2]==="close"&&m==="POST")w=Ut(Ub,b),N="close";else if(g.length===3&&g[2]==="events"&&m==="GET"){S=si(h,["protocol"]);let k=[];for(let j=0;j<i.rawHeaders.length;j+=2)i.rawHeaders[j].toLowerCase()==="last-event-id"&&k.push(i.rawHeaders[j+1]);k.length>1&&be("invalid_request"),k.length===1&&(X=Ut(mt,k[0])),N="events"}else if(g.length===4&&g[2]==="archive"&&g[3]==="records"&&m==="GET")S=si(h,["protocol",...Y,"limit","maxBytes"],["afterSequence"]),w={generations:$h(S),afterSequence:S.afterSequence===void 0?null:Ut(rn,S.afterSequence),limit:pa(S.limit,1,128),maxBytes:pa(S.maxBytes,1024,1048576)},N="records";else if(g.length===5&&g[2]==="archive"&&g[3]==="artifacts"&&m==="GET")S=si(h,["protocol",...Y,"offset","maxBytes"]),w={generations:$h(S),artifactId:Ut(mt,g[4]),offset:pa(S.offset,0,33554431),maxBytes:pa(S.maxBytes,1,262144)},N="artifact";else if(g.length===4&&g[2]==="archive"&&g[3]==="acks"&&m==="POST")w=Ut(_b,b),N="ack";else if(g.length===4&&g[2]==="archive"&&g[3]==="ack-rebases"&&m==="POST")w=Ut(su("AckRebaseRequest"),b),N="ack-rebase";else if(g.length===3&&g[2]==="material-responses"&&m==="POST")w=Ut(Mb,b),N="response";else if(g[2]==="materials"&&(g.length===4||g.length===6||g.length===7))if(Ut(mt,g[3]),g.length>4&&(g[4]!=="uploads"&&be("invalid_request"),Ut(mt,g[5])),g.length===7&&g[6]==="chunks"&&m==="POST")w=Ut(Pb,b),N="upload";else if(m==="GET"&&g.length!==7)si(h,["protocol"]),N=g.length===4?"status":"upload-status";else return be("invalid_request");else return be("unsupported_capability");if(m==="POST"){let k=w;(k.bindingId!==ne||N==="upload"&&(k.materialRequestId!==g[3]||k.artifactId!==g[5]))&&be("invalid_request"),k.request&&(l=k.request.requestId)}if(N==="upload"){let k=w,j=Buffer.from(k.base64,"base64");(j.length!==k.bytes||j.toString("base64")!==k.base64||qf(j)!==k.chunkSha256)&&be("invalid_request")}let T={endUserId:await R()},_=t.host.resolve(T.endUserId,ne);_||be("forbidden");let G=_.control.read();if((!G||G.registration.bindingId!==ne||G.registration.scope.endUserId!==T.endUserId||G.registration.scope.applicationScopeId!==t.host.applicationScopeId)&&be("forbidden"),G.state==="unbound"&&be("binding_closed"),N==="view"||N==="archive-status"||N==="close"||N==="ack-rebase"){let k=async()=>{await x(T.endUserId),t.host.resolve(T.endUserId,ne)!==_&&be("forbidden");let j=_.control.read();(!j||j.registration.bindingId!==ne||j.registration.scope.endUserId!==T.endUserId||j.registration.scope.applicationScopeId!==t.host.applicationScopeId)&&be("forbidden")};if(N==="view"){let j=_.readView;j||be("unsupported_capability");let W=await j.call(_);await k(),_.readView!==j&&be("forbidden");let q=Hi(Wh,W,e);(q.bindingId!==ne||q.scope.applicationScopeId!==t.host.applicationScopeId||q.scope.endUserId!==T.endUserId||q.target.sessionId!==G.registration.sessionId)&&be("forbidden"),Qn(o,200,q,e)}else if(N==="archive-status"){G.acceptedCapabilities.includes("archive-transfer-v1")||be("unsupported_capability");let j=_.readArchiveStatus;j||be("unsupported_capability");let W=await j.call(_);await k(),_.readArchiveStatus!==j&&be("forbidden");let q=Hi(jb,W,e);(q.bindingId!==ne||q.sourceId!==G.registration.sourceId||q.sourceGeneration!==G.registration.sourceGeneration)&&be("forbidden"),Qn(o,200,q,e)}else if(N==="ack-rebase"){G.acceptedCapabilities.includes("archive-transfer-v1")||be("unsupported_capability");let j=_.rebaseAck;j||be("unsupported_capability");let W=w,q=await j.call(_,W);await k(),_.rebaseAck!==j&&be("forbidden");let Q=2*e+ou.responseEnvelopeBytes,U=Fb(q,Q),ue=(pe,oe)=>Zt(pe).toString()===Zt(oe).toString();(U.bindingId!==ne||!ue(U.previous,W.previous)||!ue(U.request,W.request)||!ue(U.next.request,W.request)||BigInt(U.next.expectedRevision)<=BigInt(W.previous.expectedRevision)||!ue({...U.next,request:W.previous.request,expectedRevision:W.previous.expectedRevision},W.previous)||U.receipt.operation!=="archive-ack"||!ue(U.receipt.request,U.next.request)||U.receipt.bindingId!==ne)&&be("internal_error"),Qn(o,200,U,Q)}else{let j=_.close;j||be("unsupported_capability");let W=w,q=await j.call(_,W);await k(),_.close!==j&&be("forbidden");let Q=Hi(Vh,q,e);(Q.bindingId!==ne||Q.operation!=="binding-close"||Q.request.operationEpoch!==W.request.operationEpoch||Q.request.requestId!==W.request.requestId)&&be("internal_error"),Qn(o,200,Q,e)}return}if(N==="events"){let k=_.events;k||be("unsupported_capability");let j=T.endUserId;if(i.aborted||o.destroyed||o.writableEnded)return;t.admission.tryAdmitSse(j).admitted||be("capacity_exceeded"),o.once("close",()=>t.admission.releaseSse(j)),i.socket.setTimeout(0);let W=async()=>{let q;try{q=await t.authenticate(i,o)}catch(ue){return ue instanceof Pt?be(ue.code==="overloaded"?"capacity_exceeded":"source_unavailable"):be("unauthorized")}(!q?.endUserId||q.endUserId!==j)&&be("unauthorized");let Q=t.host.resolve(j,ne);(!Q||Q.events!==k||Q.control!==_.control)&&be("forbidden");let U=Q.control.read();(!U||U.registration.bindingId!==ne||U.registration.scope.endUserId!==j||U.registration.scope.applicationScopeId!==t.host.applicationScopeId)&&be("forbidden"),U.state==="unbound"&&be("binding_closed")};await zh({req:i,res:o,port:k,scope:{applicationScopeId:t.host.applicationScopeId,endUserId:j,bindingId:ne},...X===void 0?{}:{lastEventId:X},authorize:W});return}let V=()=>{let k=_.materials;(!G.acceptedCapabilities.includes("context-materials-v1")||!k)&&be("unsupported_capability"),(k.bindingId!==ne||!G.registration.relatedBindingIds.includes(k.storageBindingId))&&be("forbidden");let j=_.spool.bindingIdentity(k.storageBindingId);return(j.applicationScopeId!==t.host.applicationScopeId||j.endUserId!==T.endUserId)&&be("forbidden"),k};["records","artifact","ack"].includes(N)&&!G.acceptedCapabilities.includes("archive-transfer-v1")&&be("unsupported_capability");let te,re=200,M=e;if(N==="records"){let k=w;Kh(k.generations,G.target.generations)||be("stale_generation"),te=_.journal.list(k),M=k.maxBytes}else if(N==="artifact"){let k=w;Kh(k.generations,G.target.generations)||be("stale_generation");let j=_.journal.readArtifact(k);te={protocol:yi,bindingId:ne,artifactId:j.artifact.artifactId,sourceId:j.artifact.sourceId,generations:k.generations,offset:j.offset,bytes:j.body.byteLength,totalBytes:j.artifact.bytes,sha256:j.artifact.sha256,chunkSha256:j.chunkSha256,base64:Buffer.from(j.body).toString("base64")},M=Eb}else if(N==="ack")te=_.acknowledger.acknowledge(w);else if(N==="upload")te=V().uploadChunk(w);else if(N==="response")te=V().respond(w),re=202;else if(N==="status")te=V().status(g[3]);else if(N==="upload-status")te=V().uploadStatus(g[3],g[5]);else{let k={operationEpoch:S.operationEpoch,requestId:S.requestId};te=S.operation==="material-response"?V().queryResponse(k):_.control.query(S.operation,k)?.receipt,te||be("receipt_expired")}if(!te||typeof te!="object"||te.bindingId!==ne)throw new Error("Mismatched host binding");Qn(o,re,te,M)})().catch(u=>{if(o.headersSent||o.destroyed||o.writableEnded)return;let p=Lb(u),[h,g]=Xh[p];(h===429||h===503)&&o.setHeader("retry-after","5"),Qn(o,h,{protocol:yi,requestId:l,code:p,status:h,message:p,retryAction:g})}).finally(()=>{a&&n--,d&&t.admission.releaseBody(c)});return t.track(f),!0}}import{createHash as Ar,randomUUID as _o}from"node:crypto";var $i="TansrTerminalShellSandbox",ko="058f31335cbb45a6ffe1b5ede8466013462c544c8108d687f41fa18447d51b96",Se={};Se.BackgroundRequest=r.union([r.object({contract:r.lazy(()=>Se.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(()=>Se.BackgroundContract),action:r.literal("query"),identity:r.lazy(()=>Se.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>Se.BackgroundContract),action:r.literal("cancel"),identity:r.lazy(()=>Se.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>Se.BackgroundContract),action:r.literal("outputRead"),identity:r.lazy(()=>Se.BackgroundIdentity),artifact:r.lazy(()=>Se.ArtifactReference),offset:r.lazy(()=>Se.Sequence),length:r.number().int().safe().min(1).max(16384)}).strict(),r.object({contract:r.lazy(()=>Se.BackgroundContract),action:r.literal("artifactDelete"),identity:r.lazy(()=>Se.BackgroundIdentity),artifact:r.lazy(()=>Se.ArtifactReference)}).strict()]);Se.BackgroundContract=r.literal("terminal-services-v1");Se.BackgroundIdentity=r.object({taskId:r.lazy(()=>Se.Id),operationId:r.lazy(()=>Se.Id),requestDigest:r.lazy(()=>Se.Digest),runtimeInstanceId:r.lazy(()=>Se.Id),processInstanceId:r.lazy(()=>Se.Id)}).strict();Se.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);Se.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));Se.ArtifactReference=r.object({artifactId:r.lazy(()=>Se.Id),operationId:r.lazy(()=>Se.Id),requestDigest:r.lazy(()=>Se.Digest)}).strict();Se.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);Se.BackgroundResponse=r.union([r.object({contract:r.lazy(()=>Se.BackgroundContract),action:r.literal("launch"),task:r.lazy(()=>Se.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>Se.BackgroundContract),action:r.literal("query"),task:r.lazy(()=>Se.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>Se.BackgroundContract),action:r.literal("cancel"),task:r.lazy(()=>Se.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>Se.BackgroundContract),action:r.literal("outputRead"),identity:r.lazy(()=>Se.BackgroundIdentity),artifact:r.lazy(()=>Se.ArtifactReference),offset:r.lazy(()=>Se.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(()=>Se.Digest),nextOffset:r.lazy(()=>Se.Sequence),complete:r.boolean(),gap:r.boolean()}).strict(),r.object({contract:r.lazy(()=>Se.BackgroundContract),action:r.literal("artifactDelete"),identity:r.lazy(()=>Se.BackgroundIdentity),artifact:r.lazy(()=>Se.ArtifactReference),status:r.union([r.literal("deleted"),r.literal("already_deleted")])}).strict()]);Se.BackgroundTaskState=r.object({identity:r.lazy(()=>Se.BackgroundIdentity),artifact:r.lazy(()=>Se.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(()=>Se.Sequence),r.null()]),truncated:r.boolean()}).strict();Se.ExecutionInterpreter=r.object({id:r.lazy(()=>Se.Id),revision:r.lazy(()=>Se.Id),hostShell:r.union([r.literal("posix"),r.literal("powershell")])}).strict();Se.Contract=r.literal("terminal-shell-sandbox-v1");Se.Call=r.object({turnId:r.lazy(()=>Se.Id),toolCallId:r.lazy(()=>Se.Id)}).strict();Se.ApprovedCall=r.object({turnId:r.lazy(()=>Se.Id),toolCallId:r.lazy(()=>Se.Id),argsDigest:r.lazy(()=>Se.Digest)}).strict();Se.Escalation=r.object({previousDeniedOperationId:r.lazy(()=>Se.Id),approvedCall:r.lazy(()=>Se.ApprovedCall)}).strict();Se.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();Se.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();Se.Request=r.union([r.object({contract:r.lazy(()=>Se.Contract),action:r.literal("exec"),call:r.lazy(()=>Se.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(()=>Se.ExecutionInterpreter),escalation:r.lazy(()=>Se.Escalation).optional()}).strict(),r.object({contract:r.lazy(()=>Se.Contract),action:r.literal("background"),request:r.lazy(()=>Se.BackgroundRequest),call:r.lazy(()=>Se.Call).optional(),escalation:r.lazy(()=>Se.Escalation).optional()}).strict()]);Se.Response=r.union([r.object({contract:r.lazy(()=>Se.Contract),action:r.literal("exec"),result:r.union([r.lazy(()=>Se.ExecResult),r.null()]),sandbox:r.lazy(()=>Se.Sandbox),output:r.union([r.lazy(()=>Se.Output),r.null()])}).strict(),r.object({contract:r.lazy(()=>Se.Contract),action:r.literal("background"),result:r.union([r.lazy(()=>Se.BackgroundResponse),r.null()]),sandbox:r.lazy(()=>Se.Sandbox)}).strict()]);Se.OutputChannel=r.object({totalBytes:r.number().int().safe().min(0).max(65536),payloadDigest:r.lazy(()=>Se.Digest)}).strict();Se.Output=r.object({previewTruncated:r.boolean(),stdout:r.lazy(()=>Se.OutputChannel),stderr:r.lazy(()=>Se.OutputChannel)}).strict();function lu(t,e){if(!Object.hasOwn(Se,t))throw new TypeError("Unknown terminal shell sandbox contract type");return Se[t].parse(e)}function ai(){throw new TypeError("Invalid terminal shell sandbox semantics")}function xo(t){let e=lu("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))&&ai(),e.escalation&&(e.escalation.approvedCall.turnId!==e.call?.turnId||e.escalation.approvedCall.toolCallId!==e.call?.toolCallId)&&ai(),e}function tg(t,e){let n=lu("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)&&ai(),n.action==="exec"&&n.result?.exitCode!==null&&n.result!==null){let o=BigInt(n.result.exitCode);(o<-2147483648n||o>2147483647n)&&ai()}if(n.action==="exec"&&(n.result===null!=(n.output===null)&&ai(),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)&&ai()}return e&&((e.action!==n.action||i.escalated&&e.escalation===void 0)&&ai(),e.action==="exec"&&n.action==="exec"&&n.output&&n.output.stdout.totalBytes+n.output.stderr.totalBytes>e.maxOutputBytes&&ai(),e.action==="background"&&n.action==="background"&&n.result?.action!==void 0&&e.request.action!==n.result.action&&ai()),n}function Ki(t){return t.operation==="tool.invoke"&&t.args.name===$i&&t.args.definitionDigest===ko}function Sr(t){if(!Ki(t)||t.operation!=="tool.invoke")throw new Error("Invalid shell sandbox profile");return xo(JSON.parse(t.args.argsJson))}function va(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 tg(JSON.parse(n.content[0].text),t)}function Ro(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 fe({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=Sr(n.request);if(o.escalation!==void 0||o.call?.toolCallId===t.call?.toolCallId||Ro(o,n)!==Ro(t,e))return!1;let s=va(o,i.result);return s.sandbox.isolationDenied&&!s.sandbox.escalated}catch{return!1}}import{createHash as Hb}from"node:crypto";var ig="8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",rg="2026-09-26.candidate-7",vi="TansrTerminalBackground",wr="03848c0c75af6e2e358ac64f81a61c79f595d8fc70442d06ae3c0576e39157b8",Jn="TansrTerminalMemoryPublication",bi="8532a582d40d2d8993a80db59412a89671670ed7f994eaf9bf972bd544a111b0",I={};I.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);I.LegacyId=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);I.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);I.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));I.Scope=r.object({applicationScopeId:r.lazy(()=>I.Id),endUserId:r.lazy(()=>I.LegacyId),authorizationRevision:r.lazy(()=>I.Sequence)}).strict();I.ExecutionBinding=r.object({bindingId:r.lazy(()=>I.Id),revision:r.lazy(()=>I.Sequence),target:r.lazy(()=>I.ExecutionTarget)}).strict();I.ExecutionTarget=r.object({executorId:r.lazy(()=>I.Id),connectionId:r.lazy(()=>I.Id),connectionRevision:r.lazy(()=>I.Sequence),workspaceId:r.lazy(()=>I.Id),workspaceRevision:r.lazy(()=>I.Sequence),interpreter:r.lazy(()=>I.ExecutionInterpreter).optional()}).strict();I.ExecutionInterpreter=r.object({id:r.lazy(()=>I.Id),revision:r.lazy(()=>I.Id),hostShell:r.union([r.literal("posix"),r.literal("powershell")])}).strict();I.Contract=r.literal("terminal-services-v1");I.SchemaRevision=r.literal("2026-09-26.candidate-7");I.SessionContract=r.union([r.literal("sdk1"),r.literal("sdk2-offload-v1")]);I.Feature=r.union([r.literal("execution-stream-v1"),r.literal("execution-background-v1"),r.literal("memory-lifecycle-v1"),r.literal("session-configuration-v1")]);I.SessionReference=r.object({sessionContract:r.lazy(()=>I.SessionContract),sessionId:r.lazy(()=>I.LegacyId)}).strict();I.FeatureAvailability=r.object({feature:r.lazy(()=>I.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();I.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();I.CapabilitiesResponse=r.object({contract:r.lazy(()=>I.Contract),schemaRevision:r.lazy(()=>I.SchemaRevision),schemaSha256:r.lazy(()=>I.Digest),sessionContracts:r.array(r.lazy(()=>I.SessionContract)).min(1).max(2).refine(t=>new Set(t).size===t.length),features:r.array(r.lazy(()=>I.FeatureAvailability)).min(4).max(4),limits:r.lazy(()=>I.Limits)}).strict();I.BindingRequest=r.object({contract:r.lazy(()=>I.Contract),requestId:r.lazy(()=>I.Id),session:r.lazy(()=>I.SessionReference),executionBinding:r.union([r.lazy(()=>I.ExecutionBinding),r.null()]),required:r.array(r.lazy(()=>I.Feature)).min(0).max(4).refine(t=>new Set(t).size===t.length),optional:r.array(r.lazy(()=>I.Feature)).min(0).max(4).refine(t=>new Set(t).size===t.length)}).strict();I.BindingResponse=r.object({contract:r.lazy(()=>I.Contract),requestId:r.lazy(()=>I.Id),session:r.lazy(()=>I.SessionReference),scope:r.lazy(()=>I.Scope),executionBinding:r.union([r.lazy(()=>I.ExecutionBinding),r.null()]),accepted:r.array(r.lazy(()=>I.Feature)).min(0).max(4).refine(t=>new Set(t).size===t.length),unavailable:r.array(r.lazy(()=>I.FeatureAvailability)).min(0).max(4),outputAuthority:r.union([r.literal("session-events"),r.literal("tool-output")]),limits:r.lazy(()=>I.Limits)}).strict();I.OperationReference=r.object({operationId:r.lazy(()=>I.Id),requestDigest:r.lazy(()=>I.Digest)}).strict();I.OutputBlock=r.object({seq:r.lazy(()=>I.Sequence),byteOffset:r.lazy(()=>I.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(()=>I.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();I.OutputSeal=r.object({lastSeq:r.union([r.lazy(()=>I.Sequence),r.null()]),totalBytes:r.lazy(()=>I.Sequence),payloadDigest:r.lazy(()=>I.Digest),truncated:r.boolean()}).strict();I.OutputBatchRequest=r.object({contract:r.lazy(()=>I.Contract),session:r.lazy(()=>I.SessionReference),operation:r.lazy(()=>I.OperationReference),executorId:r.lazy(()=>I.Id),connectionId:r.lazy(()=>I.Id),blocks:r.array(r.lazy(()=>I.OutputBlock)).min(0).max(32),seal:r.union([r.lazy(()=>I.OutputSeal),r.null()])}).strict();I.OutputStatus=r.object({contract:r.lazy(()=>I.Contract),operation:r.lazy(()=>I.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(()=>I.Sequence),r.null()]),durableThrough:r.union([r.lazy(()=>I.Sequence),r.null()]),retainedFrom:r.union([r.lazy(()=>I.Sequence),r.null()]),nextByteOffset:r.union([r.lazy(()=>I.Sequence),r.null()]),seal:r.union([r.lazy(()=>I.OutputSeal),r.null()])}).strict();I.OutputEvent=r.union([r.object({contract:r.lazy(()=>I.Contract),type:r.literal("output.block"),operation:r.lazy(()=>I.OperationReference),block:r.lazy(()=>I.OutputBlock)}).strict(),r.object({contract:r.lazy(()=>I.Contract),type:r.literal("output.status"),status:r.lazy(()=>I.OutputStatus)}).strict()]);I.ExecutorEvent=r.object({contract:r.lazy(()=>I.Contract),eventId:r.lazy(()=>I.Sequence),type:r.union([r.literal("operations-available"),r.literal("operation-cancelled"),r.literal("reconcile-required")]),executorId:r.lazy(()=>I.Id),connectionId:r.lazy(()=>I.Id),operation:r.union([r.lazy(()=>I.OperationReference),r.null()])}).strict();I.OutputCorrelation=r.object({contract:r.lazy(()=>I.Contract),session:r.lazy(()=>I.SessionReference),toolCallId:r.lazy(()=>I.LegacyId),operation:r.lazy(()=>I.OperationReference),outputAuthority:r.union([r.literal("session-events"),r.literal("tool-output")])}).strict();I.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")]);I.ErrorResponse=r.object({contract:r.lazy(()=>I.Contract),requestId:r.lazy(()=>I.Id),code:r.lazy(()=>I.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();I.ConfigurationRevision=r.number().int().safe().min(0).max(9007199254740991);I.Thinking=r.object({budget:r.number().int().safe().min(0).max(9007199254740991).optional()}).strict();I.SessionConfiguration=r.object({revision:r.lazy(()=>I.ConfigurationRevision),model:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512),r.null()]),thinking:r.union([r.lazy(()=>I.Thinking),r.null()])}).strict();I.ConfigurationChanges=r.object({model:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512).optional(),thinking:r.union([r.lazy(()=>I.Thinking),r.null()]).optional()}).strict();I.ConfigurationRequest=r.object({contract:r.lazy(()=>I.Contract),requestId:r.lazy(()=>I.Id),session:r.lazy(()=>I.SessionReference),expectedRevision:r.lazy(()=>I.ConfigurationRevision),changes:r.lazy(()=>I.ConfigurationChanges)}).strict();I.ConfigurationResponse=r.object({contract:r.lazy(()=>I.Contract),session:r.lazy(()=>I.SessionReference),configuration:r.lazy(()=>I.SessionConfiguration)}).strict();I.ConfigurationCommitResponse=r.object({contract:r.lazy(()=>I.Contract),requestId:r.lazy(()=>I.Id),session:r.lazy(()=>I.SessionReference),status:r.union([r.literal("changed"),r.literal("replayed")]),configuration:r.lazy(()=>I.SessionConfiguration)}).strict();I.ExecutionStatus=r.object({protocol:r.literal("sdk2-ext-v1"),operation:r.lazy(()=>I.ExecutionOperation),status:r.union([r.literal("pending"),r.literal("completed"),r.literal("failed"),r.literal("unknown")]),receipt:r.union([r.lazy(()=>I.ExecutionReceiptRequest),r.null()])}).strict();I.ExecutionOperation=r.object({protocol:r.literal("sdk2-ext-v1"),operationId:r.lazy(()=>I.Id),sessionId:r.lazy(()=>I.LegacyId),scope:r.lazy(()=>I.Scope),binding:r.lazy(()=>I.ExecutionBinding),toolName:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),request:r.lazy(()=>I.ResourceRequest),digest:r.lazy(()=>I.Digest),expiresAt:r.string().datetime({offset:!0})}).strict();I.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(()=>I.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(()=>I.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(()=>I.Digest),argsJson:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768)}).strict()}).strict()]);I.ExecutionReceiptRequest=r.object({protocol:r.literal("sdk2-ext-v1"),executorId:r.lazy(()=>I.Id),connectionId:r.lazy(()=>I.Id),operationId:r.lazy(()=>I.Id),digest:r.lazy(()=>I.Digest),status:r.union([r.literal("completed"),r.literal("failed"),r.literal("unknown")]),result:r.union([r.lazy(()=>I.ResourceResult),r.null()]),errorCode:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),r.null()])}).strict();I.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(()=>I.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()]);I.ExecutionState=r.object({contract:r.lazy(()=>I.Contract),session:r.lazy(()=>I.SessionReference),execution:r.lazy(()=>I.ExecutionStatus)}).strict();I.BackgroundIdentity=r.object({taskId:r.lazy(()=>I.Id),operationId:r.lazy(()=>I.Id),requestDigest:r.lazy(()=>I.Digest),runtimeInstanceId:r.lazy(()=>I.Id),processInstanceId:r.lazy(()=>I.Id)}).strict();I.ArtifactReference=r.object({artifactId:r.lazy(()=>I.Id),operationId:r.lazy(()=>I.Id),requestDigest:r.lazy(()=>I.Digest)}).strict();I.BackgroundRequest=r.union([r.object({contract:r.lazy(()=>I.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(()=>I.Contract),action:r.literal("query"),identity:r.lazy(()=>I.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>I.Contract),action:r.literal("cancel"),identity:r.lazy(()=>I.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>I.Contract),action:r.literal("outputRead"),identity:r.lazy(()=>I.BackgroundIdentity),artifact:r.lazy(()=>I.ArtifactReference),offset:r.lazy(()=>I.Sequence),length:r.number().int().safe().min(1).max(16384)}).strict(),r.object({contract:r.lazy(()=>I.Contract),action:r.literal("artifactDelete"),identity:r.lazy(()=>I.BackgroundIdentity),artifact:r.lazy(()=>I.ArtifactReference)}).strict()]);I.BackgroundTaskState=r.object({identity:r.lazy(()=>I.BackgroundIdentity),artifact:r.lazy(()=>I.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(()=>I.Sequence),r.null()]),truncated:r.boolean()}).strict();I.BackgroundResponse=r.union([r.object({contract:r.lazy(()=>I.Contract),action:r.literal("launch"),task:r.lazy(()=>I.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>I.Contract),action:r.literal("query"),task:r.lazy(()=>I.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>I.Contract),action:r.literal("cancel"),task:r.lazy(()=>I.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>I.Contract),action:r.literal("outputRead"),identity:r.lazy(()=>I.BackgroundIdentity),artifact:r.lazy(()=>I.ArtifactReference),offset:r.lazy(()=>I.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(()=>I.Digest),nextOffset:r.lazy(()=>I.Sequence),complete:r.boolean(),gap:r.boolean()}).strict(),r.object({contract:r.lazy(()=>I.Contract),action:r.literal("artifactDelete"),identity:r.lazy(()=>I.BackgroundIdentity),artifact:r.lazy(()=>I.ArtifactReference),status:r.union([r.literal("deleted"),r.literal("already_deleted")])}).strict()]);I.MemoryIdentity=r.object({kind:r.union([r.literal("server-managed"),r.literal("client-managed"),r.literal("developer-managed")]),domain:r.lazy(()=>I.MemoryIdentifier),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),applicationScopeId:r.lazy(()=>I.Id),endUserId:r.lazy(()=>I.LegacyId)}).strict();I.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(()=>I.MemoryIdentifier)}).strict()]);I.MemoryCommandRequest=r.object({contract:r.lazy(()=>I.Contract),session:r.lazy(()=>I.SessionReference),requestId:r.lazy(()=>I.MemoryIdentifier),operationId:r.lazy(()=>I.MemoryIdentifier),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),expectedRevision:r.lazy(()=>I.Sequence),command:r.lazy(()=>I.MemoryCommand)}).strict();I.MemoryReceipt=r.object({requestId:r.lazy(()=>I.MemoryIdentifier),operationId:r.lazy(()=>I.MemoryIdentifier),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),expectedRevision:r.lazy(()=>I.Sequence),status:r.union([r.literal("pending"),r.literal("unknown"),r.literal("committed"),r.literal("failed")]),publishedRevision:r.lazy(()=>I.Sequence).optional(),errorCode:r.union([r.literal("operation_failed"),r.literal("commit_unknown")]).optional(),executionComplete:r.boolean(),durable:r.boolean(),consumed:r.boolean()}).strict();I.MemoryState=r.object({identity:r.lazy(()=>I.MemoryIdentity),revision:r.lazy(()=>I.Sequence),deletionGeneration:r.lazy(()=>I.Sequence),available:r.boolean()}).strict();I.MemoryStateResponse=r.object({contract:r.lazy(()=>I.Contract),session:r.lazy(()=>I.SessionReference),memory:r.lazy(()=>I.MemoryState)}).strict();I.MemoryReceiptResponse=r.object({contract:r.lazy(()=>I.Contract),session:r.lazy(()=>I.SessionReference),receipt:r.union([r.lazy(()=>I.MemoryReceipt),r.null()])}).strict();I.MemoryIdentifier=r.string().regex(new RegExp("^[^\\u0000-\\u001f\\u007f]+$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=256);I.MemoryPublicationEtag=r.string().regex(new RegExp("^[^\\u0000-\\u001f\\u007f]+$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=256);I.MemoryPublicationHead=r.object({etag:r.lazy(()=>I.MemoryPublicationEtag),byteLength:r.number().int().safe().min(1).max(4194304),sha256:r.lazy(()=>I.Digest)}).strict();I.MemoryPublicationTransfer=r.object({transferId:r.lazy(()=>I.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(()=>I.MemoryPublicationEtag),r.null()])}).strict();I.MemoryPublicationRequest=r.union([r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("head")}).strict(),r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("read"),etag:r.lazy(()=>I.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(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("begin"),transferId:r.lazy(()=>I.Id),expectedEtag:r.union([r.lazy(()=>I.MemoryPublicationEtag),r.null()]),byteLength:r.number().int().safe().min(1).max(4194304),sha256:r.lazy(()=>I.Digest)}).strict(),r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("chunk"),transferId:r.lazy(()=>I.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(()=>I.Digest)}).strict(),r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("commit"),transferId:r.lazy(()=>I.Id)}).strict(),r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("query"),transferId:r.lazy(()=>I.Id)}).strict()]);I.MemoryPublicationResponse=r.union([r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("head"),publication:r.union([r.lazy(()=>I.MemoryPublicationHead),r.null()])}).strict(),r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("read"),etag:r.lazy(()=>I.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(()=>I.Digest),nextOffset:r.number().int().safe().min(0).max(4194304),complete:r.boolean()}).strict(),r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("begin"),transfer:r.lazy(()=>I.MemoryPublicationTransfer)}).strict(),r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("chunk"),transfer:r.lazy(()=>I.MemoryPublicationTransfer)}).strict(),r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("commit"),transfer:r.lazy(()=>I.MemoryPublicationTransfer)}).strict(),r.object({contract:r.lazy(()=>I.Contract),sourceId:r.lazy(()=>I.MemoryIdentifier),sourceGeneration:r.lazy(()=>I.Sequence),domainKey:r.lazy(()=>I.MemoryIdentifier),action:r.literal("query"),transfer:r.lazy(()=>I.MemoryPublicationTransfer)}).strict()]);function vt(t,e){if(!Object.hasOwn(I,t))throw new TypeError("Unknown terminal contract type");return I[t].parse(e)}function ba(t,e){return fe(t)===fe(e)}function In(){throw new Error("Invalid terminal background response.")}function og(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 Em({signal:t.signal,maxTasks:128}),d=g=>fe([g.toolCallId,g.executionTarget]);async function c(g,m,v){if((m.waiting??0)>=4)throw new Error("Background control capacity exceeded.");let b=m.tail??Promise.resolve(),x,R=new Promise(A=>{x=A});m.tail=R,m.waiting=(m.waiting??0)+1;try{return await new Promise((A,C)=>{let B=()=>{v.removeEventListener("abort",B),C(v.reason)};v.addEventListener("abort",B,{once:!0}),b.then(()=>{v.removeEventListener("abort",B),A()}),v.aborted&&B()}),v.throwIfAborted(),await l(g,m,v)}finally{b.then(()=>{m.waiting=(m.waiting??1)-1,x()})}}async function l(g,m,v){if(s||!t.enabled())throw new Error("Background capability is no longer available.");if(!m.launch)throw new Error("Missing original background launch identity.");let b=await t.invoke(g,m.call.executionTarget,v,m.launch),x=vt("BackgroundResponse","response"in b?b.response:b);if(g.action==="launch"&&"response"in b&&(m.sandbox=Object.freeze({...b.sandbox})),g.action!=="launch"&&v.throwIfAborted(),x.action!==g.action&&In(),g.action!=="launch"){let R="task"in x?x.task.identity:x.identity;ba(R,g.identity)||In(),"artifact"in g&&(!("artifact"in x)||!ba(x.artifact,g.artifact))&&In()}return x}async function f(g,m){if(!g.task)throw new Error("Background launch has not been confirmed.");let v=m.signal?AbortSignal.any([m.signal,t.signal]):t.signal,b=await c({contract:"terminal-services-v1",action:"outputRead",identity:g.task.identity,artifact:g.task.artifact,offset:String(m.offset),length:Math.min(m.length,16384)},g,v);b.action!=="outputRead"&&In();let x=Buffer.from(b.base64,"base64");return(x.toString("base64")!==b.base64||x.length!==b.byteLength||x.length>Math.min(m.length,16384)||b.offset!==String(m.offset)||BigInt(b.nextOffset)!==m.offset+BigInt(x.length)||Hb("sha256").update(x).digest("hex")!==b.payloadDigest||b.gap&&b.complete)&&In(),{offset:m.offset,bytes:x,nextOffset:BigInt(b.nextOffset),complete:b.complete,gap:b.gap}}let u=g=>{if(t.signal.throwIfAborted(),s)throw new Error("Background runtime is closed.");let m=d(g);if(i.has(m)||i.size+o.size>=128)throw new Error("Background capacity exceeded.");let v={call:{...g,executionTarget:Object.freeze({...g.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(m)},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 x=await c({contract:"terminal-services-v1",action:"artifactDelete",identity:v.task.identity,artifact:v.task.artifact},v,AbortSignal.any([b,t.signal]));return x.action!=="artifactDelete"&&In(),x.status}},i.set(m,v),v.port};async function p(g,m,v=!1){let b=i.get(d(g));if(!b)throw new Error("Missing original background output port.");a.assertCapacity(),b.launch={...g,executionTarget:Object.freeze({...g.executionTarget})},b.call=b.launch;let x;try{x=await c({contract:"terminal-services-v1",action:"launch",command:g.command,cwd:g.cwd,mode:m===void 0?"background":"foreground-handoff",timeoutMs:e,...m===void 0?{}:{foregroundTimeoutMs:Math.min(m,12e4)}},b,g.signal)}catch(q){throw i.delete(d(g)),q}x.action!=="launch"&&In();let R=Am(x.task.identity);(x.task.artifact.operationId!==R.operationId||x.task.artifact.requestDigest!==R.requestDigest||x.task.state==="unknown")&&In(),b.task=x.task,i.delete(d(g)),x.task.truncated&&(b.error="Background output is incomplete.");let A=!1,C,B=0n,Y,ne,N=Date.now(),X=new Promise(q=>{ne=q}),S=v&&m!==void 0?N+m:void 0,w=m===void 0?n:Math.min(n,Math.max(1,Math.floor(m/4))),T=S!==void 0,_=new AbortController,G=q=>{if(A)return;A=!0,_.abort(),o.delete(V);let Q=q===void 0||q.state==="unknown";ne({exitCode:Q?null:q.exitCode,signalName:Q?null:q.signalName,durationMs:Date.now()-N,...Q?{outcomeUnknown:!0}:{},...q?.state==="failed"?{executionFailed:!0}:{},...q?.state==="cancelled"?{cancelled:!0}:{}})},V={close:()=>G()};o.add(V);let te=q=>{(!ba(q.identity,R)||!ba(q.artifact,b.task?.artifact))&&In(),q.truncated&&(b.error="Background output is incomplete."),b.task=q},re=AbortSignal.any([_.signal,t.signal]),M=async(q,Q)=>{let U=await c({contract:"terminal-services-v1",action:q,identity:R},b,AbortSignal.any([Q,t.signal]));return(U.action!==q||!("task"in U))&&In(),te(U.task),U.task.state==="unknown"&&G(U.task),{state:U.task.state,exitCode:U.task.exitCode,signalName:U.task.signalName}},k=()=>{A||Y||(Y=c({contract:"terminal-services-v1",action:"cancel",identity:R},b,re).then(q=>{q.action!=="cancel"&&In(),te(q.task),q.task.state==="unknown"&&G(q.task)}).catch(()=>G()).finally(()=>{Y=void 0}))},j={identity:R,pid:void 0,startedAt:N,...b.sandbox?{sandbox:b.sandbox}:{},get lastOutputAt(){return C},get settled(){return A},exit:X,kill:k,control:{query:q=>M("query",q),cancel:q=>M("cancel",q)},killSync:()=>G()};g.signal.aborted&&k();let W=new TextDecoder;return(async()=>{try{for(;!A;){re.throwIfAborted();let q=b.task;if(q.state==="unknown"){G(q);break}for(let U=0;U<16&&q.totalBytes!==null&&B<BigInt(q.totalBytes);U++){let ue=await f(b,{offset:B,length:16384,signal:re});if(ue.gap||ue.bytes.length===0){b.error="Background output gap.";break}B=ue.nextOffset,C=Date.now();let pe=W.decode(ue.bytes,{stream:!0});pe&&g.onChunk?.(pe,"stdout")}if(q.state!=="running"){if(q.totalBytes!==null&&B<BigInt(q.totalBytes)&&!b.error)continue;let U=W.decode();U&&g.onChunk?.(U,"stdout"),G(q);break}if(!T){let U=S!==void 0&&Date.now()<S?w:n;await new Promise((ue,pe)=>{let oe=setTimeout(()=>{re.removeEventListener("abort",ee),ue()},U);oe.unref();let ee=()=>{clearTimeout(oe),re.removeEventListener("abort",ee),pe(re.reason)};re.addEventListener("abort",ee,{once:!0}),re.aborted&&ee()})}T=!1;let Q=await c({contract:"terminal-services-v1",action:"query",identity:R},b,re);Q.action!=="query"&&In(),te(Q.task)}}catch{G()}})(),j}return{runtime:{enabled:t.enabled,createOutput:u,launch:p,registry:a,timeoutHandoff:!0},registry:a,async exec(g){if(!g.executionTarget||!g.toolCallId)throw new Error("Missing bound execution identity.");let m=await p({...g,executionTarget:g.executionTarget,toolCallId:g.toolCallId},g.timeoutMs,g.timeoutHandoff!==void 0),v=await Cm(g,m);return"sandbox"in m&&m.sandbox?{...v,sandbox:m.sandbox}:v},close(){s=!0;for(let g of o)g.close();i.clear()}}}import sg from"node:path";var wT=sg.resolve(sg.sep,".tansr-sdk-no-discovery");function Gb(t){let e=[];for(let[n,i]of Object.entries(t)){if(!Vm.test(n)||n.includes("__"))throw new yt("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=$m.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 yt("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 kr=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=Gb(e.servers),this.#n=e}manager(){return this.#s?Promise.reject(new yt("invalid_options","This McpHost has been disposed; create a new host, or pass { servers } for a session-scoped host.")):(this.#r??=Km({registry:new qn,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 Hm&&(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 Sa(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(Pc(i)),e.toolDefs.push(jm),{segment:Gm(n.catalog),discoverToolFactory:o=>Pc(n.forToolset(o))})}function Io(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 Vb="Skill",$b="TodoWrite";function Si(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,p=f!==void 0?{description:f.description,...f.effects!==void 0?{effects:f.effects}:{}}:void 0,h=a?.suppressClassifierSoften===!0,g=lm(a),m=um(a),v=!1,b=t.decide({toolName:s.name,args:s.args,isReadOnly:u,cwd:c,...l}),x=s.name===Om&&b.decision==="ask"&&b.source==="mode"&&b.matchedRule===void 0,R=!x&&s.name===Vb&&(b.decision==="ask"||b.decision==="deny")&&b.source==="mode"&&b.matchedRule===void 0&&u,A=!x&&!R&&s.name===Dm&&(b.decision==="ask"||b.decision==="deny")&&b.source==="mode"&&b.matchedRule===void 0&&u,C=!x&&!R&&!A&&s.name===$b&&(b.decision==="ask"||b.decision==="deny")&&b.source==="mode"&&b.matchedRule===void 0&&u,B=x?{decision:"allow",source:"policy"}:R?{decision:"allow",source:"policy",matchedRule:"skill(default-allow)"}:A?{decision:"allow",source:"policy",matchedRule:"mcp-discover(default-allow)"}:C?{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}:{}},Y=(ne,N)=>{if(!cm(ne,v)||m)return ne;let X=t.consultClassifier({...a?.signal!==void 0?{signal:a.signal}:{},toolName:s.name,args:N,isReadOnly:u,cwd:c,...l,...h?{suppressClassifierSoften:!0}:{},...p!==void 0?{toolMeta:p}:{}},{decision:ne.decision,source:ne.source,...ne.matchedRule!==void 0?{matchedRule:ne.matchedRule}:{}}),S=w=>w.decision==="ask"?w.source==="classifier"?{...ne,source:"classifier",...w.reason!==void 0?{reason:w.reason}:{},...w.adjudication!==void 0?{classifierAdjudication:w.adjudication}:{}}:w.adjudication!==void 0?{...ne,classifierAdjudication:w.adjudication}:ne:{decision:w.decision,source:w.source,...w.matchedRule!==void 0?{matchedRule:w.matchedRule}:{},...w.sourceLayer!==void 0?{sourceLayer:w.sourceLayer}:{},...w.reason!==void 0?{reason:w.reason}:{},...w.adjudication!==void 0?{classifierAdjudication:w.adjudication}:{},...w.decision==="allow"&&ne.updatedArgs!==void 0?{updatedArgs:ne.updatedArgs}:{}};return X instanceof Promise?X.then(S):S(X)};return B.decision==="deny"||g||o===void 0||!o.hasHooks("PreToolUse",s.name)?Y(B,s.args):(async()=>{let N=(await o.run({event:"PreToolUse",tool_name:s.name,tool_input:s.args,tool_use_id:s.id})).preToolUse??{},X=N.decision;v=X==="ask";let S=X!==void 0&&ac[X]>ac[B.decision]?{decision:X,source:"hook"}:{...B};if(N.updatedInput!==void 0&&S.decision!=="deny"){let w=t.decide({toolName:s.name,args:N.updatedInput,isReadOnly:u,cwd:c,...l});return S=dm(S,w),S.decision==="deny"?S:Y({...S,updatedArgs:N.updatedInput},N.updatedInput)}return Y(S,s.args)})()}}}var ag="tansr-platform";function Kb(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 wa(t){let e=t.baseUrl.replace(/\/+$/,""),n=t.fetchImpl??fetch,i=t.token;return{name:ag,async search(o,s){let a;try{a=await n(`${e}/t1/websearch`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",[Dn]: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}.${Kb(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 fn(t){let e=bp(t.inputSchema),{$schema:n,...i}=e;return{name:t.name,description:t.description,inputSchema:i}}function xr(t,e,n){try{let{client:i,resolved:o}=gp(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 yt("assembly_failed",`Failed to assemble model client for "${e}": ${o}`,{cause:i})}}import{createHash as Zb}from"node:crypto";var Tn=class extends yt{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 mu(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 Rr(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 Tn)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"}:mu(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 ka(t){let e=Rr(t),n=e.stage==="turn_start"?"start":e.stage==="credential_refresh"?"credentials":"config";return`${or(`sdk.prompt_failure.${n}`)} ${or(`sdk.prompt_failure.${e.reason}`)} ${or(`sdk.prompt_retry.${e.retry}`)}`.trim()}var lg=new WeakMap;function xa(t){return lg.get(t)}function To(t,e){return e===void 0?Zb("sha256").update(JSON.stringify(t)).digest("hex"):e.replace(/^W\//,"").replace(/^"|"$/g,"")}var eS=[$o,Ko,kf,xf,Rf];function ug(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 eS)a.delete(d);return a.set(Dn,t),n(o,{...s,headers:a})}}var tS="session_archived";function pu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Ra(t,e,n,i,o=cr){try{let s=await n(`${t}${Qo.heartbeat}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",[Dn]:e,[Ts]: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=pu(c)&&pu(c.error)?c.error:null;if(l!==null&&l.code===tS){let f=pu(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 fg(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 Yn(t,e,n,i,o=cr,s=!1){let a=`${t}${Qo.config}`,d;try{d=await n(a,{method:"GET",headers:{accept:"application/json",[Dn]:e,[Ts]:o.join(","),...i!==void 0?{"if-none-match":i}:{}}})}catch(p){let h=Rr(p);throw new Tn(h.reason==="unknown"?{stage:"app_config",reason:"network",retry:"retry"}:h,{cause:p})}let c=d.headers.get("etag")??void 0,l=fg(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 Tn(mu(d.status));let f;try{f=await d.json()}catch(p){throw new Tn({stage:"app_config",reason:"invalid_config",retry:"check_configuration"},{cause:p})}let u=Vr(f);if(u===null||s&&(typeof f!="object"||f===null||!Object.hasOwn(f,"capabilities")||u.capabilitiesIssues!==null))throw new Tn({stage:"app_config",reason:"invalid_config",retry:"check_configuration"});return{bundle:u,status:d.status,etag:c,maxAgeMs:l}}function Ia(t,e){return nS(t,e)}async function nS(t,e){let n=t.baseUrl.replace(/\/+$/,""),i=t.fetchImpl??fetch,o,s,a,d;if(t.bundleCache!==void 0){let g=t.sessionId?.(),m=await t.bundleCache.resolve({baseUrl:n,token:t.token,fetchImpl:i,...t.appId!==void 0?{appId:t.appId}:{},...g!==void 0?{sessionId:g}:{}});o=m.bundle,d=m.etag,s=m.features,a=m.registryConfig,m.archivedSessionId!==void 0&&t.onSessionArchived?.(m.archivedSessionId)}else{let g=Ra(n,t.token,i,t.sessionId?.()),m=await Yn(n,t.token,i);if(m.bundle===null)throw new yt("assembly_failed",`App config bundle request to ${n}${Qo.config} returned 304 without a conditional request. Check that "baseUrl" points to the tansr API.`);o=m.bundle,d=m.etag;let v=await g;s=v.features,v.archived!==void 0&&t.onSessionArchived?.(v.archived.sessionId)}if(o.capabilitiesIssues!==null&&t.onWarn!==void 0){let g=o.capabilitiesIssues[0],m=g!==void 0?` (first issue: ${g.path.length>0?g.path.join("."):"<root>"}: ${g.message})`:"";t.onWarn({code:"capabilities_unparsed",message:`The app's platform bundle "capabilities" section could not be parsed${m}; 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=ug(t.token,t.fetchImpl),l=e?.gatewayCache===void 0?void 0:t.sessionId?.();if(e?.gatewayCache!==void 0&&!l)throw new yt("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:To(o,d),fetchImpl:c});if(f!==void 0&&(!l||f.runtimeSessionId!==l))throw new yt("assembly_failed","Gateway cache must bind the current platform session.");let u=new zc(a??lr(o,n),{env:{[$c]:Bi},fetchImpl:c,twp:{...f!==void 0?{gatewayCache:f}:{},...t.sessionId!==void 0?{sessionId:t.sessionId}:{},features:()=>s,...t.onWarn!==void 0?{onWarn:t.onWarn}:{}}}),h={...xr(u,t.model??"main",t.onProviderSelected),registry:u,capabilities:o.capabilities,platformModels:o.platformModels,pricingUpdates:Kc(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&&lg.set(h,{revision:To(o,d),...d===void 0?{}:{etag:d}}),h}function Ao(t,e){let n=Nm({...e,agents:vs,toolset:{registry:t.registry,toolDefs:t.toolDefs}});t.registry.register(n),t.toolDefs.push(fn(n))}function Ta(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,p)=>{let h=new Headers(p?.headers);h.set("cache-control","no-cache");let g=p?.signal??(u instanceof Request?u.signal:void 0);return i(u,{...p,headers:h,cache:"no-cache",signal:g?AbortSignal.any([c,g]):c})},f=await Yn(n,t.token,l,s);if(c.throwIfAborted(),e){let u=f.bundle===null?a:To(f.bundle,f.etag);if(u!==a||d||e.refreshRequired?.()){d=!0,await e.refreshConfiguration(c),c.throwIfAborted();let p=await Yn(n,t.token,l,f.etag??s);if((p.bundle!==null||p.etag!==void 0)&&To(p.bundle,p.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 gS}from"node:crypto";function Aa(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(h=>{d=h}),l=gS(),f=0,u=h=>({...h,sessionId:t.sessionId,turnId:l,seq:f++,ts:Date.now(),v:"v0",source:t.errorScope??"sdk"});return{events:(async function*(){let h=!0,g,m=setTimeout(()=>{s="timeout",e.abort(s)},a);m.unref?.();try{try{let v=new Promise((x,R)=>{g=()=>R(e.signal.reason),e.signal.addEventListener("abort",g,{once:!0}),e.signal.aborted&&g()}),b=await Promise.race([Promise.resolve().then(()=>(e.signal.throwIfAborted(),t.prepare(e.signal))),v]);e.signal.throwIfAborted(),h=!1,i=t.start(b.map(x=>({...x})));for(let x of n)i.enqueueUserInput(x);n.length=0}catch(v){if(yield u({type:"turn.started"}),!e.signal.aborted||e.signal.reason==="timeout"){let b=h?e.signal.aborted?new Tn({stage:"app_config",reason:"timeout",retry:"retry"}):v:new Tn({stage:"turn_start",reason:"unknown",retry:"retry"});yield u({type:"turn.error",scope:t.errorScope??"sdk",message:(t.errorMessage??ka)(b),recoverable:!1,errorKind:h?"application_prompt_refresh_failed":"turn_start_failed",detail:{...Rr(b)}})}yield u({type:"turn.aborted",reason:e.signal.aborted?s:"model_error"});return}finally{clearTimeout(m),g!==void 0&&e.signal.removeEventListener("abort",g),d()}yield*t.eventsFor?.(i)??i.events}finally{o=!0}})(),enqueueUserInput(h){o||e.signal.aborted||(i!==void 0?i.enqueueUserInput(h):n.push(h))},abort(h){o||(i!==void 0?i.abort(h):(s=h??"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:h=>i?.reserveUserInput?.(h)??{status:"closed",code:"turn_closed"},compactNow:async h=>(await c,i?.compactNow?.(h)??{status:"rejected",reason:i===void 0?"turn_ended":"not_configured"})}}async function hu(t){let e=t.baseUrl.replace(/\/+$/,""),n=t.fetchImpl??fetch,i;try{let s=vp(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",[Dn]: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 gu(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=zm(n.error?.detail);return{code:i,message:o,...s?{detail:s}:{}}}var AE=Object.freeze({maxEvents:1e3,maxBytes:2*1024*1024});var Co=["unauthorized"];var Eo=["check_unavailable"];function Ea(t){return Co.includes(t)}function _a(t){return typeof t=="string"&&Eo.includes(t)}import{createHash as Ag}from"node:crypto";var wi=6e4,qS=16,DS=1e5,jS=5e3,NS=36e5,vu="app_user",Ma=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 US(t){return Ag("sha256").update(t,"utf8").digest("hex")}function Pa(t=cr){return Ag("sha256").update(t.join(","),"utf8").digest("hex").slice(0,8)}function bu(t,e,n,i){return`${t}\0${e??""}\0${n}\0${i}`}function Su(t){let e=t.trim().replace(/^W\//,"");return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Qi(t={}){let e=t.now??Date.now,n=Math.max(0,t.ttlMs??wi),i=new Ma(t.maxEntries??qS),o=new Ma(t.maxFeatureEntries??DS),s=new Map,a=new Map,d={hits:0,misses:0,revalidations:0,notModified:0,inflightDedup:0,featureHits:0,featureMisses:0,etagInvalidations:0},c=h=>{let g=i.peek(h);g!==void 0&&(g.expiresAt=0)},l=(h,g)=>{if(g===void 0)return;let m=i.peek(h);m===void 0||m.etag===void 0||Su(m.etag)!==Su(g)&&(m.expiresAt<=e()||(m.expiresAt=0,d.etagInvalidations+=1))},f=h=>Math.min(NS,h===void 0?n:Math.min(h,n)),u=(h,g,m,v,b)=>{let x=i.get(g);if(x!==void 0&&x.expiresAt>e())return d.hits+=1,Promise.resolve(x);let R=s.get(g);if(R!==void 0)return d.inflightDedup+=1,R;let A=(async()=>{x===void 0?d.misses+=1:d.revalidations+=1;let C=await Yn(h,m,v,x?.etag,b),B=f(C.maxAgeMs);if(C.bundle===null){if(x===void 0){let ne=await Yn(h,m,v,void 0,b);if(ne.bundle===null)throw new Error("bundle cache: unconditional request returned 304");let N={bundle:ne.bundle,registryConfig:lr(ne.bundle,h),etag:ne.etag,expiresAt:e()+f(ne.maxAgeMs)};return i.set(g,N),N}return d.notModified+=1,x.expiresAt=e()+B,C.etag!==void 0&&(x.etag=C.etag),i.set(g,x),x}let Y={bundle:C.bundle,registryConfig:lr(C.bundle,h),etag:C.etag,expiresAt:e()+B};return i.set(g,Y),Y})().finally(()=>s.delete(g));return s.set(g,A),A},p=(h,g,m,v,b,x)=>{let R=`${h}\0${US(m)}\0${Pa(x)}`,A=o.get(R);if(A!==void 0&&A.expiresAt>e())return d.featureHits+=1,Promise.resolve({features:A.features});let C=a.get(R);if(C!==void 0)return d.inflightDedup+=1,C;d.featureMisses+=1;let B=(async()=>{let Y=await Ra(h,m,v,b,x),ne=Y.features,N=ne===void 0?Math.min(jS,n):n;return o.set(R,{features:ne,expiresAt:e()+N}),l(g,Y.bundleEtag),{features:ne,...Y.archived!==void 0?{archived:Y.archived}:{}}})().finally(()=>a.delete(R));return a.set(R,B),B};return{async resolve(h){let g=h.baseUrl.replace(/\/+$/,""),m=h.fetchImpl??t.fetchImpl??fetch,v=bu(g,h.appId,h.scope??vu,Pa(h.clientFeatures)),[b,x]=await Promise.all([u(g,v,h.token,m,h.clientFeatures),p(g,v,h.token,m,h.sessionId,h.clientFeatures)]),R=x.archived!==void 0&&h.sessionId!==void 0&&(x.archived.sessionId===void 0||x.archived.sessionId===h.sessionId)?h.sessionId:void 0;return{bundle:b.bundle,registryConfig:b.registryConfig,etag:b.etag,features:x.features,...R!==void 0?{archivedSessionId:R}:{}}},invalidate(h){if(h===void 0){i.clear(),o.clear();return}c(bu(h.baseUrl.replace(/\/+$/,""),h.appId,h.scope??vu,Pa(h.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 qt(t,e){return ye[t].parse(e)}var Ir=262144,VS=8*1048576,$S=4096,Oa=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:Ir});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=qt(i,JSON.parse(l.toString("utf8")));return!(i==="ExecutionReceiptRequest"&&f.status==="unknown")&&this.#e.size<$S&&this.#n+l.length<=VS&&(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!==ft(fe(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=qt("ExecutionReceiptRequest",e.receipt),o=this.receipt(i.operationId),s=this.operation(i.operationId);if(o?.status!=="unknown"||!s||i.status==="unknown"||e.unknownReceiptDigest!==ft(fe(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=fe({source:"trusted-host",evidenceId:e.evidenceId,authorizationRevision:n,operationDigest:s.digest,unknownReceiptDigest:e.unknownReceiptDigest}),c=Buffer.from(fe(i));if(c.length>Ir||Buffer.byteLength(d)>1024)throw new Error("Execution reconciliation exceeds bound");if(a!==null)return fe(a)===fe(i);let l=this.#r("reconciliation",i.operationId);return this.storage.spool.reserve({...l,intentDigest:e.unknownReceiptDigest,originalMax:{bytes:Ir+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=Nd(this.storage.spool,{bindingId:this.storage.bindingId,operationKeyPrefix:"execution-",maxBodyBytes:Ir}),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=Nd(this.storage.spool,{bindingId:this.storage.bindingId,operationKeyPrefix:"execution-",maxBodyBytes:Ir}),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:Ir+128,records:1}},o=Buffer.from(fe(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(ft(fe(n))!==ft(fe(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(fe(e))}]})}};import{randomUUID as KS}from"node:crypto";function zn(t,e){return fe(t)===fe(e)}function Tr(t){if(!/^[a-zA-Z0-9_-]{1,128}$/.test(t))throw new TypeError("Invalid execution operation id");return`operation:${t}`}function wu(t,e){return t.sessionId===e.sessionId&&t.scope.applicationScopeId===e.applicationScopeId&&t.scope.endUserId===e.endUserId}function ki(t,e){let n=t.executions[Tr(e)];if(n&&(n.generation!==t.generation||!wu(n.operation,t.scope)))throw new Error("Execution fact scope mismatch");return n}function Ba(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(fe(e))>262144)throw new RangeError("Execution receipt exceeds bound")}function dO(t,e){let n={transactional:!0,scope:Object.freeze({...t}),acceptsOwner:e.acceptsOwner,operation:i=>e.read(o=>structuredClone(ki(o,i)?.operation??null)),receipt:i=>e.read(o=>structuredClone(ki(o,i)?.receipt??null)),reconciledReceipt:i=>e.read(o=>{let s=ki(o,i);if(s?.reconciled&&(s.receipt?.status!=="unknown"||s.reconciled.status==="unknown"||s.observation?.unknownReceiptDigest!==ft(fe(s.receipt))))throw new Error("Execution reconciliation identity mismatch");return structuredClone(s?.reconciled??null)}),recoverableOperations:i=>e.read(o=>{if(!zn(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(ki(o,a.operation.operationId)!==a)throw new Error("Execution fact unavailable");if(a.receipt&&Ba(a,a.receipt),a.reconciled&&(Ba(a,a.reconciled),a.receipt?.status!=="unknown"||a.reconciled.status==="unknown"||a.observation?.unknownReceiptDigest!==ft(fe(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(!zn(i,t))throw new Error("Execution fact scope mismatch");return Object.values(s.serviceExecutions??{}).some(a=>(ku(s,a),!a.receipt&&o?.activeOperationIds.has(a.operation.operationId)&&a.claimId===s.owner?.claimId&&a.attempt===s.owner.attempt?!1:_g(a)))||Object.values(s.executions).some(a=>{if(!wu(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=qt("ExecutionOperation",structuredClone(i));if(!wu(o,t)||Buffer.byteLength(fe(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=ki(s,o.operationId);if(a){if(!zn(a.operation,o)||a.claimId!==s.owner.claimId||a.attempt!==s.owner.attempt)throw new Error("Conflicting execution preparation");return}s.executions[Tr(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=ki(o,i.operationId);if(!a||!zn(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=qt("ExecutionReceiptRequest",structuredClone(i));await e.write(s=>{let a=ki(s,o.operationId);if(!a)throw new Error("Execution request missing");if(Ba(a,o),a.receipt&&!zn(a.receipt,o))throw new Error("Conflicting execution receipt");a.receipt=o})},async reconcile(i,o){let s=qt("ExecutionReceiptRequest",structuredClone(i.receipt));return e.write(a=>{let d=ki(a,s.operationId);if(!d||d.receipt?.status!=="unknown"||s.status==="unknown"||i.operationDigest!==d.operation.digest||i.unknownReceiptDigest!==ft(fe(d.receipt)))throw new Error("Execution reconciliation identity mismatch");Ba(d,s);let c={evidenceId:i.evidenceId,unknownReceiptDigest:i.unknownReceiptDigest,authorizationRevision:o};if(Buffer.byteLength(fe(c))>1024)throw new RangeError("Execution reconciliation exceeds bound");return d.reconciled?zn(d.reconciled,s):(d.reconciled=s,d.observation=c,!0)})}};return Object.assign(n,{services:QS(t,e)}),Object.freeze(n)}var qa=262144;function Cg(t){return ft(`tansr.service.execution.v1\0${fe(t)}`)}function Eg(t,e){let{digest:n,...i}=t;if(Tr(t.operationId),!zn(t.scope,e)||!t.callId||!t.toolName||t.target.kind!=="controlled-service"||!t.target.authorizationRevision||!/^[a-f0-9]{64}$/.test(t.argumentsDigest)||n!==Cg(i)||Buffer.byteLength(fe(t))>4096)throw new Error("Service execution identity mismatch")}function Da(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(Nt(e))>qa)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!==ft(e.resultJson))throw new Error("Service result digest mismatch")}}function ku(t,e){if(Eg(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&&Da(e,e.receipt),e.reconciled&&(Da(e,e.reconciled),e.reconciled.status==="unknown"||e.receipt&&e.receipt.status!=="unknown"||e.observation?.unknownReceiptDigest!==ft(fe(e.receipt??null))))throw new Error("Service reconciliation identity mismatch")}function _g(t){let e=t.reconciled??t.receipt;return!e||e.status==="unknown"}function cO(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(ku(t,s),o!==Tr(s.operation.operationId))throw new Error("Service fact key mismatch");s.receipt||(e+=qa),_g(s)&&(e+=qa+1024,n=!0)}return{count:i.length,reserved:e,unsettled:n}}function QS(t,e){let n=(i,o)=>{let s=i.serviceExecutions?.[Tr(o)];return s&&ku(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);Eg(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(!zn(a.operation,o)||a.claimId!==s.owner.claimId||a.attempt!==s.owner.attempt)throw new Error("Conflicting service preparation");return}s.serviceExecutions??={},s.serviceExecutions[Tr(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||!zn(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(Da(a,o),a.receipt&&!zn(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!==ft(fe(a.receipt??null))||!/^[A-Za-z0-9][A-Za-z0-9._~:-]{0,127}$/.test(o.evidenceId))throw new Error("Service observation identity mismatch");if(Da(a,o.receipt),a.reconciled&&!zn(a.reconciled,o.receipt))throw new Error("Conflicting service reconciliation");a.reconciled=o.receipt,a.observation={evidenceId:o.evidenceId,unknownReceiptDigest:o.unknownReceiptDigest}})}})}async function xu(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:KS(),callId:t.callId,toolName:t.toolName,scope:n.scope,target:structuredClone(t.target),argumentsDigest:ft(Nt(t.args))},c={...d,digest:Cg(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=(p,h,g)=>{let m=h===null?null:Nt(h);return{operationId:c.operationId,digest:c.digest,status:p,resultJson:m,...m===null?{}:{resultDigest:ft(m)},...g===void 0?{}:{reason:g}}};try{await t.beforeDispatch?.(),o.throwIfAborted(),await i.write(async()=>{o.throwIfAborted(),await a.dispatch(c)}),o.throwIfAborted(),i.assertCurrent(),l=!0;let p=await e(),h=u(p?.isError===!0?"unknown":"completed",p);if(Buffer.byteLength(Nt(h))>qa&&(h.status="unknown",h.resultJson=null,h.reason="result_too_large"),f=!0,await i.write(()=>a.settle(h)),h.reason==="result_too_large")throw new RangeError("Service result exceeds durable receipt bound");return o.throwIfAborted(),p}catch(p){throw f||await i.write(()=>a.settle(u(l?"unknown":"cancelled",null,o.aborted?"aborted":"execution_error"))),p}finally{s.delete(c.operationId)}}import{createHash as ow,randomUUID as sw}from"node:crypto";import{createHash as JS,randomUUID as YS}from"node:crypto";import{realpathSync as XS}from"node:fs";import Mt from"node:path";import ZS from"node:os";var Og=9223372036854775807n,Yi=4*1024*1024,Pg=1024*1024,Mg=256,mn=r.string().regex(/^(0|[1-9][0-9]{0,18})$/).refine(t=>BigInt(t)<=Og),Iu=t=>r.string().refine(e=>[...e].length<=t),Ft=Iu(256).refine(t=>t.length>0&&!/[\u0000-\u001f\u007f]/.test(t)),Tu=r.object({kind:r.enum(["server-managed","client-managed","developer-managed"]),domain:Ft,sourceId:Ft,sourceGeneration:mn,applicationScopeId:Ft,endUserId:Iu(512).refine(t=>t.length>0)}).strict(),Bg=new WeakMap;function Au(t){return Bg.get(t)}var ew=r.discriminatedUnion("kind",[r.object({kind:r.literal("pin"),text:Iu(4096).refine(t=>t.length>0)}).strict(),r.object({kind:r.literal("remember")}).strict(),r.object({kind:r.literal("forget"),topic:Ft}).strict()]),tw=r.object({requestId:Ft,operationId:Ft,sourceId:Ft,sourceGeneration:mn,expectedRevision:mn,command:ew}).strict(),nw=r.object({requestId:Ft,operationId:Ft,sourceId:Ft,sourceGeneration:mn,expectedRevision:mn,status:r.enum(["pending","unknown","committed","failed"]),publishedRevision:mn.optional(),errorCode:r.enum(["operation_failed","commit_unknown"]).optional(),executionComplete:r.boolean(),durable:r.boolean(),consumed:r.boolean()}).strict(),iw=r.object({text:r.string(),sha256:r.string().regex(/^[a-f0-9]{64}$/),modifiedAt:r.number().int().nonnegative(),provenance:r.array(Ft).max(256),deletionGeneration:mn}).strict(),qg=r.object({turn:r.number().int().optional(),text:r.string().max(32768),queuedAt:Ft,owner:Ft.optional()}).strict(),Ru=r.object({version:r.literal(1),identity:Tu,epoch:mn,revision:mn,deletionGeneration:mn,files:r.record(iw),indexValid:r.boolean(),invites:r.array(qg).max(256),consolidation:r.string().nullable(),tombstones:r.record(mn),receipts:r.record(r.object({digest:r.string(),receipt:nw}).strict()),activeOperation:Ft.nullable(),lease:r.object({owner:Ft,fence:mn}).strict().nullable(),fence:mn}).strict(),ct=class extends Error{constructor(n){super(n);this.code=n;this.name="MemoryManagementError"}code};function xe(t){throw new ct(t)}var Hn=t=>JS("sha256").update(t).digest("hex"),Yt=t=>structuredClone(t),Ji=t=>(BigInt(t)>=Og&&xe("capacity_exceeded"),(BigInt(t)+1n).toString()),dn=t=>Hn(t),di=(t,e)=>Nt(t)===Nt(e);function rw(){let t=ZS.tmpdir();try{return XS.native(t)}catch{return t}}function Xi(t){return Hn(Nt({...Tu.parse(t),sourceGeneration:void 0}))}async function yO(t){(!Mt.isAbsolute(t)||t===":memory:")&&xe("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&&xe("source_unavailable");let a=i.get(s);return a!==void 0&&Hn(a.body)!==a.etag&&xe("integrity_mismatch"),a===void 0?null:{...a}},async compareAndSwap(s,a,d){o&&xe("source_unavailable"),Buffer.byteLength(d)>Yi&&xe("capacity_exceeded"),n.exec("BEGIN IMMEDIATE");try{(i.get(s)?.etag??null)!==a&&xe("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,Hn(d),d),n.exec("COMMIT")}catch(c){try{n.exec("ROLLBACK")}catch{}throw c}},close(){o||(n.close(),o=!0)}}}function vO(t,e){return(e.atomicDurablePublication!==!0||t.capabilities.consistency!=="strong"||!t.capabilities.conditionalPut||t.capabilities.maxObjectBytes<Yi)&&xe("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>Yi)&&xe("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>Yi&&xe("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&&xe("revision_conflict"),(c.length!==o.bytes||Hn(c)!==o.sha256)&&xe("integrity_mismatch"),{etag:o.etag,body:c.toString("utf8")}},async compareAndSwap(n,i,o){let s=Buffer.from(o);s.length>Yi&&xe("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:Hn(s)},i===null?{ifNoneMatch:"*"}:{ifMatch:i})}catch(a){throw a?.kind==="precondition_failed"&&xe("revision_conflict"),a}}}}var ja=class t{identity;#e;#n;#r="0";#s=new WeakMap;#t=new WeakMap;constructor(e){this.#e=e,this.identity=Object.freeze(Tu.parse(e.identity)),this.#n=Xi(this.identity)}static async open(e){e.store.atomicDurablePublication!==!0&&xe("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"&&xe("source_unavailable");let o={version:1,identity:Yt(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,Nt(o))}else e.mode==="create"&&xe("revision_conflict");return await n.#i(),n}assertCurrent(){this.#e.assertCurrent()}#o(e){let n=this.#e.minimumDeletionGeneration?.();BigInt(e)<BigInt(this.#r)&&xe("stale_generation"),n!==void 0&&BigInt(e)<BigInt(mn.parse(n))&&xe("stale_generation")}async#i(){this.assertCurrent();let e=await this.#e.store.read(this.#n);this.assertCurrent(),e===null&&xe("source_unavailable"),Buffer.byteLength(e.body)>Yi&&xe("capacity_exceeded");let n;try{n=Ru.parse(JSON.parse(e.body))}catch{return xe("integrity_mismatch")}di(n.identity,this.identity)||xe("stale_generation"),this.#o(n.deletionGeneration);for(let i of Object.values(n.files))(Hn(i.text)!==i.sha256||Buffer.byteLength(i.text)>Pg)&&xe("integrity_mismatch");return(Object.keys(n.files).length>256||Object.keys(n.receipts).length>Mg||Object.keys(n.tombstones).length>512)&&xe("capacity_exceeded"),this.#r=n.deletionGeneration,{state:n,etag:e.etag}}async#a(e,n){this.assertCurrent(),n.epoch=Ji(e.state.epoch),this.#o(n.deletionGeneration),Ru.parse(n);let i=Nt(n);Buffer.byteLength(i)>Yi&&xe("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){Ft.parse(e),n!==void 0&&Ft.parse(n);let{state:i}=await this.#i(),o=i.receipts[dn(e)];return o?(n!==void 0&&o.receipt.requestId!==n&&xe("request_conflict"),Yt(o.receipt)):null}async consume(e){let n=await this.#i(),i=Yt(n.state),o=i.receipts[dn(e)];return(!o||o.receipt.status!=="committed")&&xe("invalid_request"),(i.activeOperation!==null||i.lease!==null)&&xe("busy"),o.receipt.consumed||(o.receipt.consumed=!0,await this.#a(n,i)),Yt(o.receipt)}async prepareReconciliation(e,n){Ft.parse(e),Ft.parse(n);let i=await this.#i(),o=i.state.receipts[dn(e)];if(!o||(o.receipt.requestId!==n&&xe("request_conflict"),!["pending","unknown"].includes(o.receipt.status)))return null;i.state.activeOperation!==e&&xe("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||xe("forbidden"),n.signal?.throwIfAborted(),await n.beforeCommit?.(),n.signal?.throwIfAborted();let o=await this.#i(),s=o.state.receipts[dn(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)&&xe("stale_generation");let a=Yt(o.state),d=a.receipts[dn(e.operationId)].receipt;a.fence=Ji(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),Yt(d)}catch(c){if(c instanceof ct&&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&&xe("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||xe("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||!di(o.state.lease,{owner:e.owner,fence:e.fence}))&&xe("stale_generation");let s=Yt(o.state);s.fence=Ji(s.fence),s.lease=null;try{await this.#a(o,s),this.#t.delete(e)}catch(a){if(a instanceof ct&&a.code==="revision_conflict")throw a;xe("commit_unknown")}}async createHost(e={}){return this.#d(e)}async execute(e,n,i={},o={}){let s=tw.parse(e);(s.sourceId!==this.identity.sourceId||s.sourceGeneration!==this.identity.sourceGeneration)&&xe("stale_generation");let a=async()=>{o.signal?.throwIfAborted(),await o.beforeCommit?.(),o.signal?.throwIfAborted(),this.assertCurrent()};await a();let d=await this.#i(),c=Yt(d.state),l=Hn(Nt(s)),f=c.receipts[dn(s.operationId)];if(f)return f.digest!==l&&xe("request_conflict"),Yt(f.receipt);Object.values(c.receipts).some(v=>v.receipt.requestId===s.requestId)&&xe("request_conflict"),c.revision!==s.expectedRevision&&xe("revision_conflict"),(c.activeOperation!==null||c.lease!==null)&&xe("busy"),Object.keys(c.receipts).length>=Mg&&xe("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[dn(s.operationId)]={digest:l,receipt:u},c.activeOperation=s.operationId;try{await this.#a(d,c)}catch(v){if(v instanceof ct&&v.code==="revision_conflict")throw v;return{...u,status:"unknown",errorCode:"commit_unknown"}}let p;try{p=await this.#i()}catch{return{...u,status:"unknown",errorCode:"commit_unknown"}}let h=p.state.receipts[dn(s.operationId)];if((!h||h.digest!==l)&&xe("integrity_mismatch"),h.receipt.status==="committed"||h.receipt.status==="failed")return Yt(h.receipt);(p.state.activeOperation!==s.operationId||p.state.fence!==c.fence)&&xe("stale_generation");let g=Yt(p.state),m=!0;try{o.signal?.throwIfAborted();let v=await this.#d({...i,provenance:()=>{let x=i.provenance?.();return{deletionGeneration:x?.deletionGeneration??g.deletionGeneration,origins:[...x?.origins??[],"operation:"+dn(s.operationId)]}}},{state:g,assertActive:()=>{m||xe("stale_generation"),o.signal?.throwIfAborted()},verifyCurrent:async()=>{let x=await this.#i();(x.etag!==p.etag||x.state.activeOperation!==s.operationId)&&xe("stale_generation")}});await n(v),v.assertCurrent(),s.command.kind==="forget"&&this.#c(g,v,s.command.topic),g.revision=Ji(g.revision),g.activeOperation=null,g.lease=null;let b=g.receipts[dn(s.operationId)].receipt;b.status="committed",b.executionComplete=!0,b.durable=!0,b.publishedRevision=g.revision,await a();try{return await this.#a(p,g),Yt(b)}catch{let x=await this.status(s.operationId,s.requestId).catch(()=>null);return x?.status==="committed"||x?.status==="failed"?x:{...u,status:"unknown",executionComplete:!0,errorCode:"commit_unknown"}}}catch{let v=Yt(p.state),b=v.receipts[dn(s.operationId)].receipt;b.status="failed",b.executionComplete=!0,b.errorCode="operation_failed",v.activeOperation=null;try{return await this.#a(p,v),Yt(b)}catch{let x=await this.status(s.operationId,s.requestId).catch(()=>null);return x?.status==="committed"||x?.status==="failed"?x:{...u,status:"unknown",errorCode:"commit_unknown"}}}finally{m=!1}}#c(e,n,i){(!/^[^/\\\u0000]+\.md$/i.test(i)||["memory.md","pending-anchors.md"].includes(i.toLowerCase()))&&xe("invalid_request");let o=Mt.relative(n.rootDir,Mt.join(n.memoryDir,i)).split(Mt.sep).join("/"),s=process.platform==="win32"?o.toLowerCase():o,a=Mt.relative(n.rootDir,Mt.join(n.memoryDir,"MEMORY.md")).split(Mt.sep).join("/"),d=process.platform==="win32"?a.toLowerCase():a,c=Mt.relative(n.rootDir,Mt.join(n.memoryDir,"pending-anchors.md")).split(Mt.sep).join("/"),l=process.platform==="win32"?c.toLowerCase():c,f=new Set([s,d]),u=!0;for(;u;){u=!1;for(let[p,h]of Object.entries(e.files))!f.has(p)&&h.provenance.some(g=>f.has(g))&&(f.add(p),u=!0)}e.deletionGeneration=Ji(e.deletionGeneration);for(let p of f)delete e.files[p],p!==d&&p!==l&&(e.tombstones[dn(p)]=e.deletionGeneration);e.indexValid=!1,e.invites=[],e.consolidation=null,Object.keys(e.tombstones).length>512&&xe("capacity_exceeded")}async#d(e,n){let i=e.rootDir??Mt.join(rw(),"tansr-memory-world",this.#n),o=e.memoryDir??Mt.join(i,"memory");(!Mt.isAbsolute(i)||!Mt.isAbsolute(o)||Mt.resolve(i)!==i||Mt.resolve(o)!==o||!o.startsWith(i+Mt.sep))&&xe("invalid_request");let s=n?.state??(await this.#i()).state,a=s.deletionGeneration,d=Yt(s.invites),c=null,l=new Set,f=()=>{this.assertCurrent(),this.#o(a),n?.assertActive()},u=w=>{f(),(!Mt.isAbsolute(w)||/\u0000/.test(w))&&xe("forbidden");let T=Mt.relative(i,Mt.resolve(w));(T.startsWith("..")||Mt.isAbsolute(T))&&xe("forbidden");let _=T.split(Mt.sep).join("/"),G=process.platform==="win32"?_.toLowerCase():_;return[_,G].some(V=>V.split("/").some(te=>Object.hasOwn(Object.prototype,te)))&&xe("forbidden"),G},p=u(o),h=u(Mt.join(o,"MEMORY.md")),g=p+"/pending-anchors.md",m=w=>{let T=u(w),_=T.slice(p.length+1);return(T===""||T===p)&&xe("forbidden"),Ft.parse(T),T.startsWith(p+"/")&&tm.includes(_.toLowerCase())&&xe("forbidden"),T},v=async()=>{f(),await n?.verifyCurrent();let w=n?.state??(await this.#i()).state;return w.deletionGeneration!==a&&xe("stale_generation"),!n&&w.activeOperation!==null&&xe("busy"),c!==null&&!di(w.lease,c)&&xe("stale_generation"),w.lease!==null&&(!c||!di(w.lease,c))&&xe("busy"),w},b=async(w,T=!1)=>{if(f(),n){await v();let te=w(n.state);return Ru.parse(n.state),te}let _=await this.#i();_.state.deletionGeneration!==a&&xe("stale_generation"),c!==null&&!di(_.state.lease,c)&&xe("stale_generation"),(_.state.activeOperation!==null||_.state.lease!==null&&(!c||!di(_.state.lease,c)))&&xe("busy");let G=Yt(_.state),V=w(G);return T&&(G.revision=Ji(G.revision)),await this.#a(_,G),V},x=async w=>{let T=m(w),_=await v();if(T===h&&!_.indexValid)throw Object.assign(new Error("Memory index unavailable"),{code:"ENOENT"});let G=_.files[T];if(!G)throw Object.assign(new Error("Memory file absent"),{code:"ENOENT"});return l.add(T),G.provenance.forEach(V=>l.add(V)),Buffer.from(G.text)},R=async(w,T,_)=>{let G=m(w);(T.length>Pg||!T.equals(Buffer.from(T.toString("utf8"))))&&xe("invalid_request");let V=e.provenance?.();(!V||V.deletionGeneration!==a||V.origins.length===0)&&xe("stale_generation");let te=[...new Set([...V.origins,...l])];te.forEach(re=>Ft.parse(re)),await b(re=>{Object.keys(re.files).some(k=>k!==G&&(k.startsWith(G+"/")||G.startsWith(k+"/")))&&xe("invalid_request"),_!==void 0&&(re.files[G]?.sha256??null)!==_&&xe("revision_conflict"),(re.tombstones[dn(G)]||te.some(k=>re.tombstones[dn(k)]!==void 0))&&xe("stale_generation");let M={text:T.toString("utf8"),sha256:Hn(T),modifiedAt:Date.now(),provenance:te,deletionGeneration:a};re.files[G]=M,re.indexValid=G===h,G!==h&&delete re.files[h],Object.keys(re.files).length>256&&xe("capacity_exceeded")},!0)},A=async w=>{let T=u(w),_=await v(),G=T===""||T===p||Object.keys(_.files).some(te=>te.startsWith(T+"/")),V=_.files[T];if(!G&&(!V||T===h&&!_.indexValid))throw Object.assign(new Error("Memory file absent"),{code:"ENOENT"});return{size:G?0:Buffer.byteLength(V.text),mtimeMs:V?.modifiedAt??0,isFile:()=>!G,isDirectory:()=>G,isSymbolicLink:()=>!1}},C={stat:A,lstat:A,realpath:async w=>(await A(w),Mt.resolve(w)),readFile:x,readFilePrefix:async(w,T)=>(await x(w)).subarray(0,T),readFileRange:async(w,T,_)=>(await x(w)).subarray(T,T+_),writeFile:(w,T)=>R(w,T),compareAndWrite:(w,T,_)=>R(w,_,T),appendFile:async(w,T)=>{let _=null,G=await x(w).then(V=>(_=Hn(V),V)).catch(V=>{if(V.code==="ENOENT")return Buffer.alloc(0);throw V});await R(w,Buffer.concat([G,T]),_)},mkdir:async w=>{u(w),await v()},readdir:async w=>{let T=u(w),_=await v(),G=T?T+"/":"",V=new Map;T===""&&V.set(p.split("/")[0],!0);for(let te of Object.keys(_.files))if(te.startsWith(G)&&!(te===h&&!_.indexValid)){let re=te.slice(G.length),M=re.split("/")[0];V.set(M,re.includes("/"))}return[...V].map(([te,re])=>({name:te,isFile:()=>!re,isDirectory:()=>re,isSymbolicLink:()=>!1}))}},B=async()=>{if(c)return null;let w;try{await b(_=>{_.lease!==null&&xe("busy"),_.fence=Ji(_.fence),w={owner:YS(),fence:_.fence},_.lease=w})}catch(_){if(_ instanceof ct&&["busy","revision_conflict"].includes(_.code))return null;throw _}c=w;let T=!1;return{release:async()=>{T||(await b(_=>{di(_.lease,c)||xe("stale_generation"),_.lease=null}),c=null,T=!0)}}},Y=w=>np(w.files[g]?.text??""),ne=(w,T,_=[])=>{if(!T.length){delete w.files[g];return}let G=ip(T),V=[...new Set([...w.files[g]?.provenance??[],..._])];V.forEach(te=>Ft.parse(te)),w.files[g]={text:G,sha256:Hn(G),modifiedAt:Date.now(),provenance:V,deletionGeneration:a}},N={acquireLock:B,pendingInvitesLocation:`memory:${this.identity.sourceId}:pending-invites`,readInitialPendingInvites:()=>(f(),Yt(d)),persistPendingInvites:async(w,T)=>{await b(_=>{let G=T.map(te=>qg.parse({...te,owner:w})),V=new Set(G.map(te=>te.queuedAt+"\0"+te.text));_.invites=[..._.invites.filter(te=>te.owner!==w&&!V.has(te.queuedAt+"\0"+te.text)),...G],_.invites.length>256&&xe("capacity_exceeded")})},readIndexSnapshot:async w=>{let T=await v();if(!T.indexValid||!T.files[h])return null;let _=T.files[h];if(!(Buffer.byteLength(_.text)>w))return l.add(h),_.provenance.forEach(G=>l.add(G)),_.text}},X={acquireLock:B,readConsolidationMeta:async()=>{let w=(await v()).consolidation;return w===null?null:Dc(w)},writeConsolidationMeta:async w=>{Dc(JSON.stringify(w))||xe("invalid_request"),await b(T=>{T.consolidation=JSON.stringify(w)})},readPendingAnchors:async()=>{let w=await v(),T=Y(w);return T.length&&(l.add(g),w.files[g]?.provenance.forEach(_=>l.add(_))),T.length===0?null:{content:T.map(_=>`- [${_.date}] ${_.text}`).join(`
|
|
20
|
+
`),keys:new Set(T.map(_=>jc(_.text)))}},clearPendingAnchors:async w=>{await b(T=>{ne(T,Y(T).filter(_=>!w.has(jc(_.text))))},!0)}},S={authority:this,rootDir:i,memoryDir:o,fs:C,source:{fs:C,pathStyle:process.platform==="win32"?"win32":"posix"},extractionHost:N,consolidationHost:X,provenance:e.provenance,assertCurrent:f,refresh:async()=>{f(),await n?.verifyCurrent();let w=n?.state??(await this.#i()).state;(w.activeOperation!==null&&!n||w.lease!==null&&(!c||!di(w.lease,c)))&&xe("busy"),c!==null&&!di(w.lease,c)&&xe("stale_generation"),a!==w.deletionGeneration&&xe("stale_generation"),d=Yt(w.invites)},appendPendingAnchors:async w=>b(T=>{let _=e.provenance?.();_!==void 0&&_.deletionGeneration!==a&&xe("stale_generation");let G=[...new Set([..._?.origins??[],...l])];G.some(te=>T.tombstones[dn(te)]!==void 0)&&xe("stale_generation");let V=op(Y(T),w,new Date().toISOString().slice(0,10));return ne(T,V.entries,G),V.added},!0)};return Bg.set(S,a),S}};var Dg=4*1024*1024,Na=12288,Ua=t=>ow("sha256").update(t).digest("hex"),Tt=t=>{throw new ct(t)};function jg(t){let e=Xi(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&&Tt("forbidden")};async function o(u){i(u.domainKey);let p=vt("MemoryPublicationRequest",u),h=vt("MemoryPublicationResponse",await t.invoke(p,t.signal));return i(u.domainKey),(h.action!==u.action||h.sourceId!==n.sourceId||h.sourceGeneration!==n.sourceGeneration||h.domainKey!==n.domainKey)&&Tt("integrity_mismatch"),h}async function s(){let u=await o({...n,action:"head"});return u.action!=="head"?Tt("integrity_mismatch"):(u.publication!==null&&(u.publication.byteLength<1||u.publication.byteLength>Dg)&&Tt("capacity_exceeded"),u.publication)}let a=(u,p,h)=>{if(!("transfer"in u)||u.transfer.transferId!==p)return Tt("integrity_mismatch");let g=u.transfer;return g.receivedBytes!==null&&(g.receivedBytes<0||g.receivedBytes>h)&&Tt("integrity_mismatch"),g.status==="conflict"&&Tt("revision_conflict"),g.status==="unknown"&&Tt("commit_unknown"),g.status==="committed"&&(g.receivedBytes!==h||g.etag===null)&&Tt("integrity_mismatch"),g},d=new Map,c=u=>JSON.stringify([u.expectedEtag,u.sha256]),l=u=>{vt("MemoryPublicationRequest",{...n,action:"begin",...u});let p=c(u),h=d.get(p);h&&(h.transferId!==u.transferId||h.expectedEtag!==u.expectedEtag||h.byteLength!==u.byteLength||h.sha256!==u.sha256)&&Tt("request_conflict"),!h&&d.size>=128&&Tt("capacity_exceeded"),d.set(p,{...u})};async function f(u){i(u);let p=await s();if(p===null)return null;let h=[],g=0;for(;g<p.byteLength;){let x=Math.min(Na,p.byteLength-g),R=await o({...n,action:"read",etag:p.etag,offset:g,length:x});if(R.action!=="read")return Tt("integrity_mismatch");let A=Buffer.from(R.base64,"base64");(R.etag!==p.etag||R.offset!==g||A.toString("base64")!==R.base64||A.length!==R.byteLength||A.length!==x||Ua(A)!==R.payloadDigest||R.nextOffset!==g+A.length||R.complete!==(g+A.length===p.byteLength))&&Tt("integrity_mismatch"),h.push(A),g+=A.length}let m=await s();if(m===null||m.etag!==p.etag)return Tt("revision_conflict");(m.byteLength!==p.byteLength||m.sha256!==p.sha256)&&Tt("integrity_mismatch");let v=Buffer.concat(h);(v.length!==p.byteLength||Ua(v)!==p.sha256)&&Tt("integrity_mismatch");let b;try{b=new TextDecoder("utf-8",{fatal:!0}).decode(v)}catch{return Tt("integrity_mismatch")}return{etag:p.etag,body:b}}return{atomicDurablePublication:!0,pendingTransfers:()=>[...d.values()].map(u=>({...u})),restorePendingTransfer:l,async read(u){for(let p=0;p<3;p++)try{return await f(u)}catch(h){if(!(h instanceof ct)||h.code!=="revision_conflict"||p===2)throw h}return Tt("revision_conflict")},async compareAndSwap(u,p,h){i(u);let g=Buffer.from(h);(g.length<1||g.length>Dg)&&Tt("capacity_exceeded");let m=Ua(g),v=c({expectedEtag:p,sha256:m}),b=d.get(v),x=b??{transferId:sw(),expectedEtag:p,byteLength:g.length,sha256:m};x.byteLength!==g.length&&Tt("integrity_mismatch"),l(x);let{transferId:R}=x,A=C=>{let B=a(C,R,g.length);return B.status==="committed"&&(B.etag!==m&&Tt("integrity_mismatch"),d.delete(v)),B};try{let C=A(await o(b?{...n,action:"query",transferId:R}:{...n,action:"begin",...x}));if(C.status==="committed")return;if(C.receivedBytes===null||C.receivedBytes!==g.length&&C.receivedBytes%Na!==0)return Tt("integrity_mismatch");for(let Y=C.receivedBytes;Y<g.length;Y+=Na){let ne=g.subarray(Y,Math.min(Y+Na,g.length)),N=A(await o({...n,action:"chunk",transferId:R,offset:Y,base64:ne.toString("base64"),byteLength:ne.length,payloadDigest:Ua(ne)}));(N.status!=="staging"||N.receivedBytes!==Y+ne.length)&&Tt("integrity_mismatch")}A(await o({...n,action:"commit",transferId:R})).status!=="committed"&&Tt("commit_unknown")}catch(C){if(C instanceof ct&&C.code==="revision_conflict")throw d.delete(v),C;if(C instanceof ct&&C.code==="integrity_mismatch")throw C;try{if(A(await o({...n,action:"query",transferId:R})).status==="committed")return}catch(B){if(B instanceof ct&&(B.code==="revision_conflict"||B.code==="integrity_mismatch"))throw B}return Tt("commit_unknown")}}}}import{createHash as Ug}from"node:crypto";var Ng=t=>Ug("sha256").update(t).digest("hex"),Cu=(t,e)=>fe(t)===fe(e),ci=()=>{throw new ct("integrity_mismatch")};function Eu(t,e){if(t.length>8192)throw new ct("capacity_exceeded");let n=Xi(e.identity),i=new Map;for(let s of t){let a=qt("ExecutionOperation",s.operation);if(a.toolName!=="MemoryPublication")continue;let d=e.allowPriorAuthority?.(a)===!0;if(!d&&s.receipt!==null&&s.receipt.status!=="unknown"&&(!Cu(a.binding,e.binding)||a.scope.authorizationRevision!==e.authorizationRevision))continue;let{digest:c,...l}=a;if((Ng("tansr.sdk2.execution.v1\0"+fe(l))!==c||a.sessionId!==e.sessionId||a.scope.applicationScopeId!==e.identity.applicationScopeId||a.scope.endUserId!==e.identity.endUserId||!d&&(a.scope.authorizationRevision!==e.authorizationRevision||!Cu(a.binding,e.binding))||a.request.operation!=="tool.invoke"||a.request.args.name!==Jn||a.request.args.definitionDigest!==bi)&&ci(),a.request.operation!=="tool.invoke")return ci();let f=vt("MemoryPublicationRequest",JSON.parse(a.request.args.argsJson));if((f.sourceId!==e.identity.sourceId||f.sourceGeneration!==e.identity.sourceGeneration||f.domainKey!==n)&&ci(),!["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)&&ci();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&&!Cu(u.begin,f)&&ci(),u.begin=f;else if(f.action==="chunk"){let p=Buffer.from(f.base64,"base64"),h=u.chunks.get(f.offset);(p.toString("base64")!==f.base64||p.length!==f.byteLength||Ng(p)!==f.payloadDigest||h!==void 0&&!Buffer.from(h).equals(p))&&ci(),u.chunks.set(f.offset,p)}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??ci(),c=[...a.chunks].sort(([u],[p])=>u-p),l=Ug("sha256"),f=0;for(let[u,p]of c)(u!==f||f+p.length>d.byteLength)&&ci(),f+=p.length,l.update(p);a.commits&&(f!==d.byteLength||l.digest("hex")!==d.sha256)&&ci(),o.push({transfer:{transferId:s,expectedEtag:d.expectedEtag,byteLength:d.byteLength,sha256:d.sha256},unresolvedOperationIds:a.unresolved})}return o}var Ri="sdk2-ext-v1",aw=16,dw=1e4,cw={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"]},Fg={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"},Lg={ImageGen:"imageGen",VideoGen:"videoGen",SpeechToText:"speechToText",TextToSpeech:"textToSpeech"},Ve=class extends Error{constructor(n,i=ya(n)[0]){super(n);this.code=n;this.status=i}code;status};function z(t,e){throw new Ve(t,e)}function pt(t,e){return fe(t)===fe(e)}function An(t){let e=JSON.parse(fe(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 Zi(t){return(t.startsWith("/")||/[\\:\u0000-\u001f\u007f]/.test(t)||t.split("/").some(e=>e==="."||e===".."))&&z("invalid_request",400),t}function lw(t){return Ar("sha256").update("tansr.sdk2.client-tool.v1\0").update(Nt(fo.parse(t))).digest("hex")}function er(t){Buffer.byteLength(t)>32768&&z("payload_too_large");let e;try{e=JSON.parse(t)}catch{z("invalid_request")}let n=(i,o)=>{if((o>32||typeof i=="number"&&!Number.isFinite(i))&&z("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))&&z("invalid_request"),e}function Fa(t){let e=pr.safeParse(er(t));return e.success||z("invalid_request"),e.data}function La(t,e,n){if(t.operation!==e.operation&&z("invalid_request",400),e.operation==="tool.invoke"){let i=Fa(e.args.resultJson);if(Ki(t)){(!n||n.toolName!=="Shell")&&z("invalid_request");let o,s;try{o=Sr(t),s=va(o,e)}catch{z("invalid_request")}o.action==="exec"&&s.action==="exec"&&s.result!==null?La({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&&La({operation:"tool.invoke",args:{name:vi,definitionDigest:wr,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===Jn&&t.args.definitionDigest===bi&&((!n||n.toolName!=="MemoryPublication")&&z("invalid_request"),i.status==="ok")){(i.isError||i.content.length!==1||i.content[0]?.t!=="text")&&z("invalid_request");let o,s;try{o=vt("MemoryPublicationRequest",er(t.args.argsJson)),s=vt("MemoryPublicationResponse",JSON.parse(i.content[0].text))}catch{z("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))&&z("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||Ar("sha256").update(a).digest("hex")!==s.payloadDigest)&&z("invalid_request")}}if(t.operation==="tool.invoke"&&t.args.name===vi&&t.args.definitionDigest===wr){(!n||n.toolName!=="Shell"||i.status!=="ok"||i.isError||i.content.length!==1||i.content[0]?.t!=="text")&&z("invalid_request");let o,s;try{o=vt("BackgroundRequest",er(t.args.argsJson)),s=vt("BackgroundResponse",JSON.parse(i.content[0].text))}catch{z("invalid_request")}s.action!==o.action&&z("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)&&z("binding_conflict"),o.action==="launch"?(a.operationId!==n.operationId||a.requestDigest!==n.digest)&&z("binding_conflict"):(!pt(o.identity,a)||"artifact"in o&&!pt(o.artifact,d))&&z("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)||Ar("sha256").update(c).digest("hex")!==s.payloadDigest||s.complete&&s.gap)&&z("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)&&z("invalid_request",400)}if(t.operation==="fs.write"&&e.operation==="fs.write"&&e.args.hash!==Ar("sha256").update(Buffer.from(t.args.bytesBase64,"base64")).digest("hex")&&z("invalid_request",400),e.operation==="fs.inspect"&&(Zi(e.args.realpath),Number.isFinite(Number(e.args.mtimeMs))||z("invalid_request",400)),e.operation==="fs.list"){let i=new Set;for(let o of e.args.entries)Zi(o.name),(o.name.includes("/")||i.has(o.name))&&z("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)&&z("invalid_request",400)}}function zg(t,e){return JSON.stringify([t,e])}function xi(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 Po=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");qt("Scope",{applicationScopeId:e.applicationScopeId,endUserId:"validation",authorizationRevision:"0"}),xi(e.maxConnections,256),xi(e.maxConnectionsPerEndUser,16),xi(e.maxSessions,512),xi(e.maxSessionsPerEndUser,Be.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&&z("capacity_exceeded",429),this.#r.add(e),()=>{this.#r.delete(e)}}changed(e){if(this.#r.size===0)return;let n=An(e);for(let i of this.#r)try{i(n)}catch{}}connection(e,n,i){let o=this.connections.get(zg(e,n));return(!o||o.user!==e||o.connection.connectionId!==i||Date.parse(o.connection.expiresAt)<=this.now())&&z("stale_generation"),o}register(e,n,i){n.executorId!==i.executorId&&z("forbidden",403),i=qt("ExecutorRegistrationRequest",JSON.parse(fe(i))),new Set(i.workspaces.map(f=>f.workspaceId)).size!==i.workspaces.length&&z("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"))&&z("invalid_request");for(let[f,u]of this.connections)Date.parse(u.connection.expiresAt)<=this.now()&&this.connections.delete(f);let s=zg(e,i.executorId),a=this.connections.get(s),d=xi(this.options.maxConnections,256),c=xi(this.options.maxConnectionsPerEndUser,16);!a&&(this.connections.size>=d||[...this.connections.values()].filter(f=>f.user===e).length>=c)&&z("capacity_exceeded",429),this.#e>=9223372036854775807n&&z("capacity_exceeded",429);let l={protocol:Ri,executorId:i.executorId,connectionId:_o(),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&&z("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))&&z("binding_conflict");let s=xi(this.options.maxSessions,512),a=xi(this.options.maxSessionsPerEndUser,Be.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)&&z("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||!pt(c.scope,{applicationScopeId:this.options.applicationScopeId,endUserId:e,sessionId:n}))&&z("forbidden",403);else{let f=this.options.spoolFor({endUserId:e,sessionId:n});pt(f.spool.bindingIdentity(f.bindingId),{applicationScopeId:this.options.applicationScopeId,endUserId:e})||z("forbidden",403),c=new Oa(f)}let l=new _u(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)&&z("source_unavailable"),i}async poll(e,n,i,o){n.executorId!==i&&z("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:Ri,executorId:i,connectionId:o,operations:s}}async receipt(e,n,i){n.executorId!==i.executorId&&z("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 z("source_unavailable")}},_u=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)&&z("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 Fg||f.name in Lg||f.name.startsWith("mcp__")||["Skill","McpDiscover","SearchMemory","ShellOutput","ShellTask","MemoryPublication",vi,Jn,$i].includes(f.name)||this.#a.has(f.name))&&z("binding_conflict");let u=Object.freeze({...f,execute:f.execute.bind(f)});this.#a.set(u.name,{tool:u,def:An(fn(u))})}let c=e.options.skillsFor?.({endUserId:n,sessionId:i});this.#c=c===void 0?void 0:{registry:new Nc(c.registry.list()),execution:c.execution},this.#d=this.#c===void 0?void 0:Fc(this.#c.registry),this.#f=e.options.mcpFor?.({endUserId:n,sessionId:i}),this.#ee=og({enabled:()=>this.backgroundEnabled(),signal:this.#K.signal,...e.options.backgroundRuntimeMs===void 0?{}:{timeoutMs:e.options.backgroundRuntimeMs},invoke:(f,u,p,h)=>this.#se(f,u,p,h)});let l={exec:async f=>{if(this.backgroundEnabled())return this.#ee.exec(f);let u=this.binding,p=this.policy.authorizationRevision,h=f.executionTarget;(!u||!h||h.bindingId!==u.bindingId||h.bindingRevision!==u.revision||h.executorId!==u.target.executorId||h.workspaceId!==u.target.workspaceId||h.workspaceRevision!==u.target.workspaceRevision||h.authorizationRevision!==p||!u.target.interpreter||!h.interpreter||!pt(h.interpreter,u.target.interpreter))&&z("stale_generation");let g=this.root(),m=f.cwd===g?"":f.cwd.startsWith(`${g}/`)?f.cwd.slice(g.length+1):z("forbidden",403),v=await this.#ie("Shell",{operation:"process.exec",args:{command:f.command,cwd:Zi(m),timeoutMs:Math.min(12e4,f.timeoutMs),maxOutputBytes:65536,interpreter:u.target.interpreter}},f.signal,u,p,3e4,!1,void 0,!1,!1,f.toolCallId);v.operation!=="process.exec"&&z("invalid_request",400),f.onChunk?.(v.args.stdout,"stdout"),f.onChunk?.(v.args.stderr,"stderr");let{stdout:b,stderr:x,...R}=v.args,A=R.exitCode===null?null:Number(R.exitCode);return A!==null&&(!Number.isSafeInteger(A)||A<-2147483648||A>2147483647)&&z("invalid_request",400),{...R,exitCode:A,signalName:R.signalName}}};this.#t=[kc(),Hr,Gr,Tc,Rc,Ic,Ac({executor:l,outputStorage:"memory",boundBackground:this.#ee.runtime,boundSandbox:{enabled:()=>this.shellSandboxEnabled(),exec:f=>this.#me(f),launch:async f=>{let u=await this.#ee.runtime.launch(f);return(!("sandbox"in u)||!u.sandbox)&&z("invalid_request"),u}}}),_m(this.#ee.registry),Pm(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)&&z("unsupported_capability"),this.transactional&&!this.transactional.acceptsOwner(e)&&z("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))&&z("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;#p;#m=null;#w=new qn;#v=[];#k=!1;#y;#B=new WeakMap;#C=new Map;#H;#S;#g=!0;#N=()=>!1;#J;#U;#j=Promise.resolve();#E=0;#q;#Y=!1;#I=!1;#u;#T;#_=new Map;#K=new AbortController;#P;#Q=new Map;#ne=new Set;#V=!1;#F=!1;#b;#ee;#A=new Map;#D;#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())&&z("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.#p!==void 0&&this.host.trackClose(this.#p.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")?Uc(this.#c.registry.list()):null;return[...e?[e]:[],...this.#m&&this.available("McpDiscover")?[this.#m]:[]]}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.#H??=(async()=>{let o,s=async()=>(o=await this.attachMcp(),null);this.transactional?(this.#e||z("forbidden",403),await xu({facts:this.transactional,owner:this.#e,callId:`mcp-initialize-${_o()}`,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)&&z("source_unavailable"),this.#m=o.segment,this.#y=o.discoverToolFactory,this.#k=!0})(),await this.#H,e.throwIfAborted(),this.#g||z("source_unavailable"))}async attachMcp(){return this.#f||z("unsupported_capability"),this.#p??=new kr({servers:this.#f.servers,baseEnv:{},connectFactory:Wm({client:Fr({env:{}}),allowedUrls:this.#f.allowedUrls,authorize:async(e,n,i)=>{if(i==="DELETE")return;(!this.#g||this.#T===void 0)&&z("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||!pt(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))))&&z("forbidden")}})}),Sa(this.#p,{registry:this.#w,toolDefs:this.#v})}childMcpDiscover(e){this.#y===void 0&&z("unsupported_capability");let n={registry:new qn,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(p=>p.name===f.name)||e.toolDefs.push(l),o.add(f),this.#C.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.#q?.signal.aborted)return Promise.reject(new Ve("source_unavailable"));if(this.#E>=aw)return Promise.reject(new Ve("capacity_exceeded",429));this.#E++;let i=new AbortController,o=AbortSignal.any([e,this.#K.signal,i.signal]),s=setTimeout(()=>i.abort(new Ve("source_unavailable")),dw),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.#q!==void 0)&&z("source_unavailable");let f=this.refreshNow(o,n),u={work:f,signal:o};this.#q=u;let p=()=>{this.#q===u&&(this.#q=void 0)};return f.then(p,p),f}),l=Promise.race([c,d]);return this.#j=l.catch(()=>{}),l.finally(()=>{clearTimeout(s),o.removeEventListener("abort",a),this.#E--})}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&&z("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)||z("source_unavailable"),qt("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))&&z("stale_generation"),this.#Y&&a.authorizationRevision===this.policy.authorizationRevision&&!pt(a.tools,this.policy.tools)&&z("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:An(c),authorizationRevision:a.authorizationRevision},e));this.host.trackClose(u.then(()=>{},()=>{}));let p=await u;e.throwIfAborted(),(this.binding!==c||!this.#g||this.policy!==i)&&z("stale_generation"),this.host.connection(this.user,c.target.executorId,c.target.connectionId),p!==null&&(l=Object.freeze({source:Wp(p),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,p=await this.host.options.confirmInterpreter({endUserId:this.user,executorId:u.executorId,workspaceId:u.workspaceId,interpreter:Object.freeze({...u.interpreter})},e);e.throwIfAborted(),d=p===!0&&this.#g&&this.binding===c}this.#e?.assertCurrent(),e.throwIfAborted(),(!this.#g||this.binding!==c||this.policy!==i)&&z("stale_generation"),this.policyCurrent(a)||z("source_unavailable");let f=fi(l)!==fi(this.attachmentSource);f&&this.attachmentSourceRevision===Number.MAX_SAFE_INTEGER&&z("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()||z("source_unavailable"),(!pt(i,this.policy)||!pt(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===$i||e.name===vi||e.name===Jn||e.name==="MemoryPublication"||this.#a.has(e.name)||this.#i.has(e.name)||this.#t.some(i=>i.name===e.name))&&z("binding_conflict"),this.#i.set(e.name,{...n,digest:lw(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?fn(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"]:cw[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===$i&&n.definitionDigest===ko)}catch{return!1}}attachShellOutputReader(e){if(this.#D!==void 0||typeof e!="function")throw new Error("Shell output reader is already attached");this.#D=e}readOutputCorrelations(e){return this.#e?.assertCurrent(),this.#g||z("source_unavailable"),An([...this.#de.values()].filter(n=>e===void 0||n.toolCallId===e))}#Re(e){return(!e.turnId||!e.toolCallId)&&z("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||!pt(o.interpreter,n.target.interpreter))&&z("stale_generation");let s=this.root(),a=e.cwd===s?"":e.cwd.startsWith(`${s}/`)?e.cwd.slice(s.length+1):z("forbidden");return{binding:n,revision:i,cwd:Zi(a)}}async#me(e){let{binding:n,revision:i,cwd:o}=this.#Ie(e);if(this.backgroundEnabled()){let p=await this.#ee.exec(e);return p.sandbox||z("invalid_request"),p}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"&&z("invalid_request"),s.result===null)return{exitCode:null,signalName:null,durationMs:0,timedOut:!1,aborted:!1,sandbox:s.sandbox};let d=s.output;d||z("invalid_request");let c={stdout:s.result.stdout,stderr:s.result.stderr};if(d.previewTruncated){this.#D||z("source_unavailable");try{c=await this.#D(a,e.signal)}catch{z("source_unavailable")}}e.signal.throwIfAborted(),this.#e?.assertCurrent(),(!this.shellSandboxEnabled()||!pt(this.binding,a.binding)||this.policy.authorizationRevision!==a.scope.authorizationRevision)&&z("stale_generation");for(let p of["stdout","stderr"]){typeof c[p]!="string"&&z("invalid_request");let h=Buffer.from(c[p],"utf8");(!c[p].startsWith(s.result[p])||h.length>65536||h.length!==d[p].totalBytes||Ar("sha256").update(h).digest("hex")!==d[p].payloadDigest)&&z("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()||z("unsupported_capability");let d=e.action==="exec"||e.request.action==="launch",c=xo(e),l={sessionId:this.sessionId,scope:{applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,authorizationRevision:o},binding:i};if(d&&s.escalationApproval!==void 0){Jf(s.escalationApproval,s);let h=this.#A.get(Ro(c,l));(!h||!ng(c,l,await this.store.operation(h),await this.store.receipt(h)))&&z("forbidden"),c=xo({...c,escalation:{previousDeniedOperationId:h,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:$i,definitionDigest:ko,argsJson:JSON.stringify(c)}},n,i,o,c.action==="exec"?c.timeoutMs+5e3:3e4,a,h=>{f=h},!1,!0,a?void 0:s.toolCallId),p=va(c,u);if(d&&f&&c.escalation===void 0&&p.sandbox.isolationDenied)for(this.#A.set(Ro(c,f),f.operationId);this.#A.size>1024;)this.#A.delete(this.#A.keys().next().value);return f||z("source_unavailable"),{response:p,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===vi&&n.definitionDigest===wr)}catch{return!1}}backgroundEnabled(){return this.#b!==void 0&&pt(this.#b.binding,this.binding)&&this.#b.authorizationRevision===this.policy.authorizationRevision&&this.backgroundSupported()}configureBackground(e){e&&(!this.binding||!this.backgroundSupported())&&z("unsupported_capability"),this.#b=e?{binding:An(this.binding),authorizationRevision:this.policy.authorizationRevision}:void 0}#ce(e){return e.operation==="tool.invoke"&&e.args.name===vi&&e.args.definitionDigest===wr}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||!pt(n.interpreter,s.target.interpreter))&&z("stale_generation");let d=vt("BackgroundRequest",e);if(d.action==="launch"){let m=this.root(),v=d.cwd===m?"":d.cwd.startsWith(`${m}/`)?d.cwd.slice(m.length+1):z("forbidden");d={...d,cwd:Zi(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||!pt(c.binding,s))&&z("binding_conflict"),d.action==="launch"?this.shellSandboxEnabled():Ki(c.request)){this.shellSandboxEnabled()||z("unsupported_capability");let{response:m}=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(m.action!=="background"&&z("invalid_request"),m.result===null)throw new Tm(m.sandbox);return{response:m.result,sandbox:m.sandbox}}(o.escalationApproval!==void 0||o.turnId!==void 0&&this.host.options.shellSandbox===!0)&&z("unsupported_capability");let f=JSON.stringify(d);er(f);let u,p=await this.#ie("Shell",{operation:"tool.invoke",args:{name:vi,definitionDigest:wr,argsJson:f}},i,s,a,3e4,!0,m=>{u=m});p.operation!=="tool.invoke"&&z("invalid_request");let h=Fa(p.args.resultJson);(h.status!=="ok"||h.isError||h.content.length!==1||h.content[0]?.t!=="text")&&z("source_unavailable");let g=vt("BackgroundResponse",JSON.parse(h.content[0].text));return g.action!==d.action&&z("invalid_request"),g.action==="launch"&&(!u||g.task.identity.operationId!==u.operationId||g.task.identity.requestDigest!==u.digest||g.task.artifact.operationId!==u.operationId||g.task.artifact.requestDigest!==u.digest)&&z("binding_conflict"),g}async createMemoryPublicationStore(e,n){(e.kind!=="client-managed"||e.applicationScopeId!==this.host.options.applicationScopeId||e.endUserId!==this.user||!this.binding||!this.platform||!n.enabled())&&z("forbidden");let i=Xi(e),o=An(this.binding);this.#P&&(!pt(this.#P.identity,e)||!pt(this.#P.binding,o))&&z("binding_conflict"),this.#P={identity:An(e),domainKey:i,binding:o,authorizationRevision:this.policy.authorizationRevision,enabled:n.enabled},this.memoryPublicationAvailable()||(this.#P=void 0,z("unsupported_capability"));let s=jg({identity:e,signal:AbortSignal.any([n.signal,this.#K.signal]),assertCurrent:()=>{this.memoryPublicationAvailable()||z("source_unavailable")},invoke:(d,c)=>this.#he(d,c)});this.store.recoverableOperations===void 0&&z("unsupported_capability");let a=await this.store.recoverableOperations({applicationScopeId:e.applicationScopeId,endUserId:e.endUserId,sessionId:this.sessionId});n.signal.throwIfAborted(),this.memoryPublicationAvailable()||z("source_unavailable");for(let d of Eu(a,{identity:e,sessionId:this.sessionId,binding:o,authorizationRevision:this.policy.authorizationRevision,allowPriorAuthority:c=>this.#F&&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.#F||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")&&z("forbidden");let n=()=>{e.signal.throwIfAborted(),this.#e?.assertCurrent(),(!this.#g||!e.enabled()||!this.#N()||this.pending.size!==0||this.#s.size!==0)&&z("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(g=>g.operation.toolName==="MemoryPublication"&&(g.receipt===null||g.receipt.status==="unknown"));d||z("binding_conflict");let c=d.operation;Eu(a,{identity:e.identity,sessionId:this.sessionId,binding:c.binding,authorizationRevision:c.scope.authorizationRevision}).length===0&&z("binding_conflict");let f=this.host.connection(this.user,e.executorId,e.connectionId),u=f.registration.workspaces.find(g=>g.workspaceId===e.workspaceId);u||z("forbidden");let p={bindingId:_o(),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}},h=await e.authorizeRecovery(An({identity:e.identity,original:a,currentBinding:p,currentAuthorizationRevision:s}));n(),await this.refresh(e.signal,!1),n(),await this.#e.assertIdle(),await this.#X(),(!h||typeof h.evidenceId!="string"||!/^[^\u0000-\u001f\u007f]{1,256}$/.test(h.evidenceId))&&z("forbidden"),await this.#e.write(async()=>{n();let g=await this.store.recoverableOperations({applicationScopeId:e.identity.applicationScopeId,endUserId:e.identity.endUserId,sessionId:this.sessionId});(!pt(g,a)||s!==this.policy.authorizationRevision||this.binding!==i||this.host.connection(this.user,e.executorId,e.connectionId)!==f)&&z("stale_generation")}),n(),this.binding=p,this.#P=void 0,this.#F=!0;for(let g of a)g.operation.toolName==="MemoryPublication"&&this.#ne.add(g.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.#F=!1,this.#ne.clear(),s}finally{this.#V=!1}}assertModelRequestsAllowed(){(this.#V||this.#F)&&z("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===Jn&&i.definitionDigest===bi)}catch{return!1}}#pe;bindMemorySearch(e){if(this.#pe)throw new Error("Memory search already bound");this.#pe=e}memoryPublicationAvailable(){let e=this.#P;if(!e||!this.#g||!this.platform||!this.policyCurrent()||!e.enabled()||!pt(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===Jn&&i.definitionDigest===bi)}catch{return!1}}#le(e){if(!(e.operation!=="tool.invoke"||e.args.name!==Jn||e.args.definitionDigest!==bi))try{return vt("MemoryPublicationRequest",er(e.args.argsJson))}catch{return}}#L(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.#L(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)&&(!pt(s.binding,this.binding)||s.scope.authorizationRevision!==this.policy.authorizationRevision)||!this.#L(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:Jn,definitionDigest:bi,argsJson:JSON.stringify(e)}};this.#L(i)||z("source_unavailable"),this.#F&&!["head","read","query"].includes(e.action)&&z("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"&&z("invalid_request");let a=Fa(s.args.resultJson);if(e.action==="read"&&a.status==="error"&&a.message==="revision_conflict")throw new ct("revision_conflict");(a.status!=="ok"||a.isError||a.content.length!==1||a.content[0]?.t!=="text")&&z("source_unavailable");let d=vt("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))&&z("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)&&z("stale_generation");let d=JSON.stringify(n);er(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"&&z("invalid_request");let l=Fa(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.#pe?.()===!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=Fg[e],o=Lg[e],s=this.#u,a=this.#i.get(e),d=e==="Skill"&&this.#d!==void 0,c=this.#w.has(e)||this.#C.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 p=this.operations(e);if(!p)return[...this.#o,...this.serviceTools()].some(h=>h.name===e)||this.#C.has(e);if(!this.binding)return!1;try{let h=this.binding.target;if(!n)return!0;let g=this.host.connection(this.user,h.executorId,h.connectionId);return g.connection.connectionRevision===h.connectionRevision&&g.registration.workspaces.some(m=>m.workspaceId===h.workspaceId&&m.revision===h.workspaceRevision)&&p.every(m=>g.registration.operations.includes(m))&&(e!=="Shell"||pt(g.registration.interpreter,h.interpreter))&&(!a||(g.registration.tools??[]).some(m=>m.name===e&&m.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:Ri,sessionId:this.sessionId,effectiveTools:n,binding:this.binding};return{...i,platform:e,capabilityRevision:ft(fe({...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:Gc.filter(a=>this.#u?.platform[a]===!0),executionProfile:this.#u?.execution?.version??"legacy"},s={protocol:Ri,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:ft(fe(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)&&z("unsupported_capability"),(this.#S!==void 0||this.#V)&&z("binding_conflict")}async initialize(e){e.sessionId!==this.sessionId&&z("invalid_request",400),(!this.#g||this.#S!==void 0||this.#V||this.#F)&&z("binding_conflict");let n=e.requestedTools??this.requested;if(n?.some(i=>this.sharedDispatchUnsupported(i))&&z("unsupported_capability"),this.platform!==null&&pt(n??null,this.requested??null))return await this.refresh(new AbortController().signal,!1),(!this.#g||this.#S!==void 0||!pt(n??null,this.requested??null))&&z("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||z("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)&&z("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})&&z("binding_conflict"),e.expectedCapabilityRevision!==this.capabilities().capabilityRevision&&z("stale_generation");let n=this.host.connection(this.user,e.executorId,e.connectionId),i=n.registration.workspaces.find(a=>a.workspaceId===e.workspaceId);i||z("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)&&z("stale_generation"),await this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId})&&z("binding_conflict"),this.binding={bindingId:_o(),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)&&z("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.#C.get(n.name)!==n||!this.available(n.name))return;let s=this.binding,a=this.policy.authorizationRevision,d=fe(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&&fe(this.binding)!==d)&&z("stale_generation")},...i?{cwd:this.root(),fsForCall:(l,f,u)=>_f({root:this.root(),callId:l,toolName:f,signal:u,execute:async p=>{let{kind:h,...g}=p,m=await this.execute(f,{operation:h,args:g},u,s,a);return m.operation==="fs.inspect"?{...m.args,mtimeMs:Number(m.args.mtimeMs)}:((m.operation==="process.exec"||m.operation==="tool.invoke")&&z("invalid_request",400),m.args)}})}:{}};return this.transactional&&!i&&this.serviceDispatchRequired(n.name)&&(c.executeService=(l,f,u)=>((!this.#e||!this.transactional)&&z("forbidden",403),xu({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())&&pt(e.binding,this.binding)&&e.scope.authorizationRevision===this.policy.authorizationRevision&&Date.parse(e.expiresAt)>this.host.now()}operationAvailable(e,n=!0){if(Ki(e.request)){if(!this.shellSandboxEnabled(n))return!1;try{if(n&&Sr(e.request).action==="background"&&!this.backgroundEnabled())return!1}catch{return!1}}return e.toolName==="MemoryPublication"?this.#L(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.#F)&&z("forbidden"),await this.refresh(i),(!pt(this.binding,o)||s!==this.policy.authorizationRevision)&&z("stale_generation"),(!(l?e==="MemoryPublication"&&this.#L(n):this.available(e))||!this.binding||!d&&!l&&!f&&!this.operations(e)?.includes(n.operation))&&z("forbidden",403),d&&(e!=="Shell"||!this.backgroundEnabled()||!(f?Ki(n):this.#ce(n)))&&z("forbidden"),f&&(e!=="Shell"||!this.shellSandboxEnabled()||!Ki(n))&&z("forbidden"),qt("ResourceRequest",n),n.operation==="tool.invoke"?(!d&&!l&&!f&&(n.args.name!==e||n.args.definitionDigest!==this.#i.get(e)?.digest)&&z("forbidden"),er(n.args.argsJson)):n.operation==="process.exec"?((!this.binding.target.interpreter||!pt(n.args.interpreter,this.binding.target.interpreter))&&z("stale_generation"),Zi(n.args.cwd)):Zi(n.args.path);let p=l&&await this.#te(n);!p&&await this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId},{activeOperationIds:new Set([...this.#s,...[...this.pending.values()].filter(B=>this.isCurrent(B)).map(B=>B.operationId)])})&&z("binding_conflict"),this.pending.size>=64&&z("capacity_exceeded",429);let h=this.host.now()+(n.operation==="process.exec"?n.args.timeoutMs+5e3:a),g={protocol:Ri,operationId:_o(),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(h).toISOString()},m={...g,digest:Ar("sha256").update("tansr.sdk2.execution.v1\0").update(fe(g)).digest("hex")};c?.(m);let v=B=>this.bridge.registerToolCall(m.operationId,e,{},h,i,h-this.host.now(),B).then(Y=>({value:Y}),Y=>({error:Y})),b,x=!1;if(this.transactional?(await this.#r(async()=>{i.throwIfAborted(),!(p&&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()])})&&z("binding_conflict"),await this.store.prepare(m)}),x=!0,b={value:v(()=>{i.throwIfAborted(),this.pending.set(m.operationId,m)})}):b=await this.#n(()=>v(()=>{i.throwIfAborted(),this.store.prepare(m),x=!0,this.pending.set(m.operationId,m)})),x&&!d&&u)for(this.#de.set(m.operationId,An({toolCallId:u,operation:{operationId:m.operationId,requestDigest:m.digest},binding:m.binding}));this.#de.size>1024;)this.#de.delete(this.#de.keys().next().value);this.pending.has(m.operationId)&&this.host.changed({kind:"operation-available",user:this.user,sessionId:this.sessionId,operation:m});let R=await b.value.finally(()=>{this.pending.delete(m.operationId)&&this.host.changed({kind:i.aborted||this.host.now()>=h?"operation-cancelled":"operation-removed",user:this.user,sessionId:this.sessionId,operation:m})});if("error"in R)throw R.error;let A=R.value,C=await this.store.receipt(m.operationId);if(C?.status==="failed"&&C.errorCode&&["ENOENT","EACCES","ESTALE","EFBIG","ENOTSUP","EEXIST","ENOTDIR"].includes(C.errorCode))throw Object.assign(new Error(C.errorCode),{code:C.errorCode});return(A.isError||A.content[0]?.t!=="text")&&z("source_unavailable"),(C?.status!=="completed"||!C.result)&&z("source_unavailable"),C.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)&&z("source_unavailable");let o=n.reconciledReceipt(e)??n.receipt(e);return{protocol:Ri,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)&&z("source_unavailable");let i=await this.store.reconciledReceipt(e)??await this.store.receipt(e);return{protocol:Ri,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)&&z("source_unavailable"),An(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=An({operation:o.operation,unknownReceipt:a,unknownReceiptDigest:ft(fe(a)),currentAuthorizationRevision:this.policy.authorizationRevision}),c=await s(d,this.#K.signal);if((!this.#g||this.host.sessions.get(this.sessionId)!==this)&&z("source_unavailable"),(!pt(await this.store.operation(e),d.operation)||!pt(await this.store.receipt(e),a))&&z("binding_conflict"),c===null)return this.readStatus(e);let l=An(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))&&z("binding_conflict");let f=qt("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")&&z("binding_conflict"),(f.status==="completed"?f.result===null||f.errorCode!==null:f.result!==null||f.errorCode===null)&&z("invalid_request",400),f.result!==null&&La(d.operation.request,f.result,d.operation),await this.#r(()=>this.store.reconcile(l,d.currentAuthorizationRevision))||z("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)&&z("source_unavailable"),(e.digest!==n.digest||e.executorId!==n.binding.target.executorId||e.connectionId!==n.binding.target.connectionId)&&z("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&&z("stale_generation"),!pt(n.binding,this.binding)&&(this.binding!==null||o)&&z("stale_generation"),o&&(n.scope.authorizationRevision!==this.policy.authorizationRevision&&z("stale_generation"),this.operationAvailable(n,i)||z("forbidden")),(e.status==="completed"?e.result===null||e.errorCode!==null||e.result.operation!==n.request.operation:e.result!==null)&&z("invalid_request",400),e.result!==null&&La(n.request,e.result,n);let s=await this.store.receipt(e.operationId);return s&&!pt(s,e)&&z("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:Ri,operation:n,status:e.status,receipt:e}}};var fw=128,mw=16,pw=1e4,Hg=new WeakMap;async function Pu(t,e,n,i){if(e.aborted||n.destroyed)throw new Ve("source_unavailable");let o=Hg.get(t);o||(o={total:0,users:new Map},Hg.set(t,o));let s=o.users.get(i)??0;if(o.total>=fw||s>=mw)throw new Ve("capacity_exceeded",429);o.total++,o.users.set(i,s+1);let a=()=>{o.total--;let h=o.users.get(i)-1;h===0?o.users.delete(i):o.users.set(i,h)},d;try{d=Promise.resolve(t.options.authorize(e,i))}catch(h){throw a(),h}d.then(a,a);let c=!1,l,f=()=>{c=!0,l(new Ve("source_unavailable"))},u=new Promise((h,g)=>{l=g}),p=setTimeout(f,pw);p.unref(),e.once("aborted",f),n.once("close",f),(e.aborted||n.destroyed)&&f();try{let h=await Promise.race([d,u]);if(c||e.aborted||n.destroyed)throw new Ve("source_unavailable");return h}finally{clearTimeout(p),e.removeListener("aborted",f),n.removeListener("close",f)}}function Xn(t,e,n){let i=fe(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 Gg(t){let{host:e,req:n,res:i,pathname:o,method:s,endUserId:a}=t,d=p=>{let h=e.sessions.get(p);if(t.sessionFamily===void 0&&h!==void 0&&h.user!==a)throw new Ve("forbidden",403);return e.session(a,p)},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 p=await Pu(e,n,i,a);if(!u){if(!p.controller&&s!=="GET"||/\/(tool-results|cwd)(?:\/|$)/.test(o))throw new Ve("forbidden",403);let x=/^\/v2\/sessions\/([^/]+)\/(messages|inputs)$/.exec(o);x&&s==="POST"&&d(decodeURIComponent(x[1])).assertReady();let R=/^\/v2\/sessions\/([^/]+)\/audio\/(transcriptions|speech)$/.exec(o);if(R&&s==="POST"){let A=d(decodeURIComponent(R[1]));if(await A.refresh(new AbortController().signal),!A.available(R[2]==="transcriptions"?"SpeechToText":"TextToSpeech"))throw new Ve("forbidden")}return!1}let h=c?.[2]==="operations"||l?.[2]==="execution-capabilities"||l?.[2]==="execution-boundary"||l?.[2]==="executions"?"GET":"POST";if(s!==h)throw new Ve("invalid_request",400);let g=new URL(n.url??"/","http://serve.invalid").searchParams;if(s==="GET"&&(g.get("protocol")!=="sdk2-ext-v1"||[...g.keys()].some(x=>x!=="protocol"&&!(c&&x==="connectionId"))||[...new Set(g.keys())].some(x=>g.getAll(x).length!==1)))throw new Ve("invalid_request",400);let m;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 x=await t.readBody();if(x==="rejected")return!0;if(!x.ok)throw x.reason==="too_large"?(i.setHeader("connection","close"),i.once("finish",()=>n.destroy()),new Ve("payload_too_large")):new Ve("invalid_request",400);m=x.value}if(f)return Xn(i,201,e.register(a,p,qt("ExecutorRegistrationRequest",m))),!0;if(c){let x=decodeURIComponent(c[1]);if(c[2]==="operations")Xn(i,200,await e.poll(a,p,x,qt("Id",g.get("connectionId"))));else if(c[2]==="heartbeats"){let R=qt("ExecutorHeartbeatRequest",m);if(R.executorId!==x)throw new Ve("invalid_request",400);Xn(i,200,e.heartbeat(a,p,x,R.connectionId))}else{let R=qt("ExecutionReceiptRequest",m);if(R.executorId!==x)throw new Ve("invalid_request",400);let A=await e.receipt(a,p,R);(A.status==="unknown"||A.status==="failed")&&t.log?.("warn","execution.result",{endUserId:a,sessionId:A.operation.sessionId,operationId:R.operationId,status:A.status,code:R.errorCode??A.status}),Xn(i,200,A)}return!0}if(!p.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":Xn(i,200,await b.initialize(qt("SessionInitializeRequest",m)));break;case"execution-capabilities":await b.refresh(new AbortController().signal),Xn(i,200,b.capabilities());break;case"execution-boundary":await b.refresh(new AbortController().signal),Xn(i,200,b.executionBoundary());break;case"execution-bindings":Xn(i,200,await b.bind(qt("ExecutionBindingRequest",m)));break;case"executions":{let x=decodeURIComponent(l[3]??"");qt("Id",x),await b.refresh(new AbortController().signal);let R=await b.reconcileStatus(x);R.status==="unknown"&&t.log?.("warn","execution.result",{endUserId:a,sessionId:v,operationId:x,status:"unknown",code:"unknown"}),Xn(i,200,R);break}}return!0}catch(p){if(i.destroyed||i.writableEnded)return!0;let h=p instanceof Ve,g=p instanceof URIError||p instanceof Error&&p.name==="ZodError",m=h?p.code:g?"invalid_request":"source_unavailable";t.log?.("warn","execution.rejected",{endUserId:a,code:m});let[v,b]=ya(m);if(v===429)for(let[x,R]of Object.entries($t(t.retryAfterMs??5e3)))i.setHeader(x,R);if(!u){let x=m==="forbidden"?le.v2Forbidden:m==="source_unavailable"?le.internalError:le.v2ValidationFailed;return me(i,v,m,x,{detail:m},{"cache-control":"no-store"}),!0}return Xn(i,v,{protocol:"sdk2-ext-v1",requestId:uw(),code:m,status:v,message:m,retryAction:b}),!0}}import{types as Mo}from"node:util";import{randomUUID as Xg}from"node:crypto";import{randomUUID as za}from"node:crypto";function Wg(t,e){return t.sessionId===e.sessionId&&t.sourceSnapshotDigest===e.sourceSnapshotDigest&&t.localHistoryGeneration===e.localHistoryGeneration}var Ha=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||!Wg(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??za(),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")):Wg(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:za(),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:za(),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:za(),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 en(n.sessionId,e,n.localHistoryGeneration+1)}};var Vg=/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/;function hw(t){let e=fe(t);if(Buffer.byteLength(e)>262144)throw new Error("Archive lineage capacity exceeded");let n=JSON.parse(e);xn(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"||!Vg.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(xn(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"||!Vg.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 Mu(t,e,n,i,o){if(o.length!==t.history.length)throw new Error("Archive lineage snapshot length changed");return hw({format:"serve-archive-lineage-v1",storeCommitId:t.commitId,sourceSnapshotDigest:t.observation.sourceSnapshotDigest,workId:e,baselineSequence:n,retentionRevision:i,origins:o})}function $g(t,e,n,i,o){return Qg(t,e,n,i,o)}function Kg(t,e,n){return Qg(t,e,void 0,n,!0)}function Qg(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 p of u.recordIds)c.add(p);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 kt={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"},Jg=Object.values(kt);function Yg(t){return t instanceof Error?t.message:String(t)}async function Ga(t){let{manager:e,compaction:n,view:i,hooks:o,signal:s}=t,a=[],d=t.sessionCapture===void 0?void 0:await dr({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 p=Mi({messages:[],transform:{ops:[],usage:u},usageAttribution:{model:n.model??t.model,contextWindowTokens:t.contextWindowTokens}}).events;t.onAbandonedUsage?.(p)};try{let u=[];if(o?.preCompact!==void 0)try{let C=await o.preCompact({signal:s,trigger:"manual",...t.instructions!==void 0?{customInstructions:t.instructions}:{}});if(C.blocked===!0)return a.push({type:"turn.error",scope:"hooks",message:We(kt.compactHookBlocked,{reason:C.blockReason??"-"}),recoverable:!0}),{status:"rejected",reason:"hook_blocked",events:a};u=C.additionalContexts??[]}catch(C){a.push({type:"turn.error",scope:"hooks",message:Yg(C),recoverable:!0})}let p=[...t.instructions!==void 0?[t.instructions]:[],...u].filter(C=>C.trim().length>0),h=p.length>0?p.join(`
|
|
21
|
+
|
|
22
|
+
`):void 0,g=n.model??t.model;d?.assertSourceCurrent();let m=await e.compact({view:i,model:g,trigger:"manual",signal:s,maxTokens:Math.min(n.maxOutputTokens??2e4,e.thresholds.compactOutputBudget),...h!==void 0?{instructions:h}:{},...t.beforeCompact!==void 0?{beforeCompact:t.beforeCompact}:{},...d===void 0?{}:{publication:d},onUsage:C=>{l?f(C):c=C}});if(d?.assertSourceCurrent(),!m.ok){let C=m.usage??c;return a.push(...Mi({messages:[...i.messages],transform:{ops:[],failure:m,...C!==void 0?{usage:C}:{}},usageAttribution:{model:g,contextWindowTokens:t.contextWindowTokens}}).events),a.push({type:"turn.error",scope:"compaction",message:m.message,recoverable:!0}),c=void 0,{status:"failed",outcome:m,events:a}}let v=[...i.messages],b=e.compactionObserver,x=m.compactionUsage??c,R={messages:v,transform:{ops:[ic(m,i.messages)],...x!==void 0?{usage:x}:{},outcome:m,invalidations:"strategy"},usageAttribution:{model:g,...t.contextWindowTokens!==void 0?{contextWindowTokens:t.contextWindowTokens}:{}},...b!==void 0?{observation:{observer:b,trigger:"manual"}}:{}},A;if(d===void 0)A=Mi(R);else{let C=nc({...R,afterPublishBeforeNotifications:()=>{t.publishHistory(B),d.accept()}}),B=Object.freeze(structuredClone([...C.nextMessages]));t.beforePublish!==void 0&&await t.beforePublish(B,m.messages);let Y=()=>C.commit(()=>(d.assertSourceCurrent(),t.publishHistory!==void 0));A=t.commitPrepared===void 0?Y():ul(B,Y,t.commitPrepared)}if(a.push(...A.events),c=void 0,o?.postCompact!==void 0)try{await o.postCompact({signal:s,trigger:"manual",summaryText:m.summaryText,removedCount:m.removedIndices.length})}catch(C){a.push({type:"turn.error",scope:"hooks",message:Yg(C),recoverable:!0})}return{status:"compacted",outcome:m,messages:v,events:a}}catch(u){throw c!==void 0&&f(c),u}finally{l=!0}}function gw(){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 Zn=class{#e=null;#n=null;#r=null;#s=gw();#t;#o;#i;#a;#c;#d;#f;#p;#m;#w;#v;#k;#y;#B;#C;#H=!1;#S;#g;#N;#J;#U;#j;#E;#q;#Y;#I;#u;#T;#_=!1;#K;#P;#Q;#ne;#V;#F;#b;#ee;#A=null;#D=[];#de;#X;#ye;#Re;#Ie;#me;#ve;#ce;#se;#pe;#le;#L;#te;#he=null;#ie;#Te;#Ce;#be;#je;#Ze;#Pe;#Ne=null;#M=null;#l;#Ue;#ge;#ae=!1;#Z;#Fe="0";#Me=[];#Oe=new WeakMap;#et;#Le=!1;#O;#G;#$=null;#ke;#ze;#x;#He=!1;#Ve;#Be;#tt;#z=0;#xe=0;#ue=new AbortController;#re=new rm;#Ee=new Set;#h=Object.freeze([]);#qe=[];#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.#F?.model===void 0?this.#y:n;if(this.#C=On({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.#E=e.contextWindowTokens,this.#q=e.maxOutputTokens,this.#Y=e.maxTokens??Pi,this.#I=e.thinking,this.#u=e.sessionId??Xg(),this.#T=new oc(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.#F=e.compaction===void 0?void 0:om(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.#me=e.onClosed,this.#ve=e.requestMeasurement,this.#ce=e.sessionEvents,this.#se=e.onTurnStart,this.#pe=e.onInputsConsumed,this.#le=e.onTurnEnd,this.#Ce=e.getMemorySelectionCheckpoint,this.#L=e.attachmentPersistence?.scope,this.#te=e.attachmentPersistence?.verifySource===!0,this.#je=e.runQueryImpl??as,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=yl(s.sourceCheckpoint),l=_i(s.checkpoint,{scope:this.#L,messages:this.#h});c!==null&&$p(c,this.#L,this.#h,l)&&(this.#ie=c,a=!0)}let d={scope:this.#L,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=_i(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.#F===void 0||this.#E===void 0)return;let{manager:n,...i}=this.#F,o=sm(i,void 0,{client:this.#C,contextWindowTokens:this.#E}),s=zf(this.#de);if(s!==void 0&&o.registerPostCompactInvalidation(s),e&&this.#L!==void 0&&this.#b!==void 0){let a={scope:this.#L,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.#L===void 0)return;let i={scope:this.#L,messages:e},o=this.#b?.exportAttachmentCheckpoint(i)??(this.#be===void 0?void 0:_i(this.#be,{...i,invalidateReferences:this.#be.historyDigest!==Nr(e)}));return o!==void 0&&n&&(o=_i(o,{...i,invalidateReferences:!0})),this.#b===void 0&&(this.#be=o),this.#p===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.#L!==void 0&&(this.#be=_i(this.#be,{scope:this.#L,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:Vp(this.#L,e,n,this.#he)}updateAttachmentSource(e){this.#te&&(fi(e)!==fi(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.#z,s=AbortSignal.any([this.#ue.signal,n.signal]),a=Promise.resolve().then(async()=>{await gn(this.#Xe(),s),this.#ke!==void 0&&await gn(this.#ke(),s);let d=e(s);this.#re.track(d.then(()=>{},()=>{}));let c=await gn(d,s);if(s.aborted||this.#R||this.#h!==i||this.#z!==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||fi(c)!==fi(l.snapshot)||!this.#b?.activateRestoredAttachmentReferences({scope:this.#L,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.#D.length>0){let d=this.#D;this.#D=[],this.#we(d)}});return this.#$=a,a}memorySelectionCheckpoint(){return this.#Ce?.()}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.#E??null};return{selected:e,active:this.#M===null?null:structuredClone(e),lastObserved:structuredClone(this.#e),lastUsage:structuredClone(this.#n),fallback:structuredClone(this.#r),budget:fs({system:this.#a,tools:this.#k,messages:this.#M?.messages()??this.#h},{contextWindowTokens:this.#E,maxOutputTokens:this.#q,requestedOutputTokens:this.#Y,thinkingBudgetTokens:this.#I?.budget,thresholds:this.#F?.thresholds,resolvedThresholds:this.#b?.thresholds,estimator:this.#b?.requestEstimator??this.#F?.estimator,settingsSource:this.#F?"configured":this.#E===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 On({async*stream(i,o){n(),yield*e.stream(i,o)}},e)}#ft(){let e=this.#F;return!this.#H||e===void 0||e.client!==void 0||e.model!==void 0||this.#q===void 0?e:{...e,maxOutputTokens:Math.min(e.maxOutputTokens??1/0,this.#q)}}#Ye(){if(this.#R||this.#W||this.#ae)return{status:"rejected",reason:"session_ended"};if(this.status()!=="idle"||this.#Ee.size>0||!this.#re.isSettled()||this.#ge!==void 0||this.#m!==void 0||this.#Te!==void 0)return{status:"rejected",reason:"turn_running"};this.#f?.assertCurrent(),Vn(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ii(this.#x?.storeIdentity,this.#u,this.#l?.runtime),this.#l?.assertReady(),this.#O?.assertReady()}modelBinding(){return{client:this.#U,model:{...this.#j},...this.#E===void 0?{}:{contextWindowTokens:this.#E},...this.#q===void 0?{}:{maxOutputTokens:this.#q}}}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=m=>m===void 0||Number.isSafeInteger(m)&&m>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.#E:e.contextWindowTokens,d=e===void 0?this.#q:e.maxOutputTokens,c=n===void 0?void 0:{...n.budget===void 0?{}:{budget:n.budget}},l=o!==this.#B||fe(s)!==fe(this.#j)||a!==this.#E||d!==this.#q;if(!l&&fe(c??null)===fe(this.#I??null)){let m=this.#z;return{status:"ready",isCurrent:()=>!this.#R&&this.#z===m,publish(){}}}if(l&&(this.#b!==void 0&&(a===void 0||this.#b.thresholds.contextWindow>a)||this.#b===void 0&&this.#F!==void 0&&a!==void 0))return{status:"rejected",reason:"context_transition_required"};let f=fs({system:this.#a,tools:this.#k,messages:this.#h},{contextWindowTokens:a,maxOutputTokens:d,requestedOutputTokens:this.#Y,thinkingBudgetTokens:c?.budget,thresholds:this.#F?.thresholds,resolvedThresholds:this.#b?.thresholds,estimator:this.#b?.requestEstimator??this.#F?.estimator});if(this.#h.length>0&&(f.fits===!1||this.#E!==void 0&&a===void 0))return{status:"rejected",reason:"context_transition_required"};let u=this.#z,p=l?this.#Je(o):this.#y,h=e===void 0?this.#U:this.#Je(e.client),g=()=>!this.#R&&!this.#W&&this.#z===u&&!this.#ae&&this.#M===null&&this.#A===null&&!this.#_;return{status:"ready",isCurrent:g,publish:()=>{if(!(this.#R||this.#W)){if(this.#f?.assertCurrent(),!g())throw new Error("Configuration publication lost its safe point");l&&(this.#b?.bindRequestModel(s,p),this.#F?.model===void 0&&On(this.#C,o),this.#y=p,this.#U=h,this.#B=o,this.#j=s,this.#E=a,this.#q=d,this.#H=!0),(l||fe(c??null)!==fe(this.#I??null))&&(this.#I=c,this.#z++)}}}}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.#D.length){let s=this.#D;this.#D=[],this.#we(s)}}}get events(){return this.#s.iterable}get callbackErrors(){return this.#ut}send(e){return this.#ae||(Vn(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ii(this.#x?.storeIdentity,this.#u,this.#l?.runtime),this.#R||this.#W)?"ended":this.#S||this.#_||this.#$!==null||this.#l?.busy?(this.#D.push(e),"queued"):this.#M!==null?(this.#qe.push(e),this.#M.enqueueUserInput(e),"queued"):this.#A!==null?(this.#D.push(e),"queued"):(ts(this.#G),this.#we([e]),"started")}sendMessage(e){return this.#ae||(Vn(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ii(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":(ts(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.#mt()}historyDeletionReady(){return this.#W&&this.#lt}#mt(){!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.#p||this.#O!==void 0&&!Lf(this.#O))throw new Error("Runtime recovery unavailable");if(this.#b!==void 0&&this.#L===void 0)throw new Jt("reconciliation_required");if(this.#Ie!==void 0||this.#ce!==void 0||this.#G!==void 0&&!Uf(this.#G)||this.#se!==void 0||this.#pe!==void 0)throw new Jt("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 Jt("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 Jt("reconciliation_required");this.#a=structuredClone(i.system)}this.#p=e,this.#m=n}resumeRuntime(){if(!this.#m||!this.#p||this.#M||this.#R)throw new Error("Runtime recovery unavailable");this.#we([])}prepareArchiveRuntimeRecovery(){if(!this.#m||!this.#p||this.#l||this.#M||this.#R||this.#oe!==0)throw new Error("Archive runtime recovery unavailable");let e=Cs(this.#m);if(e.query.sessionId!==this.#u||fe(e.query.messages)!==fe(this.#h))throw new Jt("reconciliation_required");this.#h=structuredClone(e.archive.messages),this.#z=e.archive.history.observation.localHistoryGeneration,this.#xe=e.archive.history.observation.localHistoryGeneration}resumeArchiveRuntime(e){if(!this.#l||!this.#m||fe(e)!==fe(this.#m))throw new Jt("reconciliation_required");Cs(e),this.resumeRuntime()}historySnapshot(){return{lastSeq:this.#_e,messages:[...this.#h]}}interrupt(e){this.#Te!==void 0&&(this.#Te.abort(),this.#D=[],this.invalidateAttachmentReferences()),this.#M?.abort(e?.source),this.#A?.ac.abort()}pushBody(e,n="server"){this.#pt({...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.#Le)throw this.#et}async#Xe(){for(;this.#Ee.size>0||this.#A!==null||this.#ge!==void 0;)await Promise.allSettled([...this.#Ee,...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.#z+=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.#ze!==e){if(this.#ze!==void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive source read check must be bound before execution");this.#ze=e}}withArchiveSourceObservation(e){let n=this.#h,i=this.#z,o=this.#b;return ol(this,()=>en(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.#Ee.size>0||!this.#re.isSettled()||this.#Le||this.#h!==n||this.#z!==i||this.#b!==o||this.#ze!==void 0&&this.#ze()!==!0)throw new Error("Archive source observation requires an idle, settled session")},e)}archiveHistoryObservation(){return en(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.#Fe=i?.baselineSequence??e.head()?.sequence??"0",this.#Me=i?.origins??this.#h.map(()=>({recordIds:[],throughSequence:this.#Fe==="0"?null:this.#Fe})),i||e.write(Mu({history:this.#h,rewritten:!1,commitId:n.confirmedCommit.commitId,observation:n.observation},"installation",this.#Fe,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(Mu(e,n.workId,this.#Fe,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 gn(this.#Xe(),o),this.#ke!==void 0&&await gn(this.#ke(),o)),o.aborted||this.#R||this.#W)throw new Error("Archive binding cancelled");!i&&n===void 0&&this.#Ve!==void 0&&(Vn(this.#x?.storeIdentity,this.#u,this.#l?.runtime,!0),this.#He=!0,await gn(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.#z,u=this.#b,p=en(this.#u,l,f),h=!1,g=this.#l,m=this.#O,v=this.#G,b=()=>{if(h&&(this.#l!==g||this.#O!==m||this.#G!==v)||!s||o.aborted||this.#R||this.#W||this.#h!==l||this.#z!==f||this.#b!==u||this.#M!==null||en(this.#u,this.#h,f).sourceSnapshotDigest!==p.sourceSnapshotDigest)throw new Error("Archive binding source changed")};b();let x={observation:p,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.#He=!0,b()}let R=()=>{let A=il(e(x));if(i)return(async()=>{let B=await A.value;if(b(),Object.keys(A).some(Y=>Y!=="value"))throw new Error("Archive committed read cannot install state");return B})();A.installation!==void 0&&dl(A.installation,{lease:x,storeIdentity:this.#x?.storeIdentity,contextMaterials:A.contextMaterials??this.#G});let C=A.installation!==void 0&&this.#l!==void 0;if(A.lifecycle!==void 0){if(!C&&(this.#l!==void 0||this.#O!==void 0)||A.capture!==void 0||this.#Ue===void 0||this.#x===void 0)throw new Error("Complete archive lifecycle requires exclusive factory ownership");if(A.contextMaterials!==void 0&&this.#G!==void 0&&A.contextMaterials!==this.#G)throw new Error("Archive binding cannot replace existing ownership");if(b(),C){if(h=!0,el(A.lifecycle,{lease:x,storeIdentity:this.#x.storeIdentity})!==this.#l.runtime)throw new Error("Archive installation runtime ownership changed")}else{let B=tl(A.lifecycle,{lease:x,storeIdentity:this.#x.storeIdentity});this.#l=new Ha(B,this.#x,this.#gt),this.#O=B.capture,A.contextMaterials!==void 0&&(this.#G=A.contextMaterials)}return A.installation!==void 0&&(g=this.#l,m=this.#O,v=this.#G,h=!0,Zc(A.lifecycle,{lease:x,storeIdentity:this.#x.storeIdentity,runtime:this.#l.runtime}),cl(A.installation,A.lifecycle,x,this.#G),b()),A.value}if(b(),A.capture!==void 0&&this.#O!==void 0&&A.capture!==this.#O||A.contextMaterials!==void 0&&this.#G!==void 0&&A.contextMaterials!==this.#G)throw new Error("Archive binding cannot replace existing ownership");return rl(A.capture),b(),A.capture!==void 0&&(this.#O=A.capture),A.contextMaterials!==void 0&&(this.#G=A.contextMaterials),A.value};return c===void 0?R():al(c,x,R)};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 gn(sl(n,{storeIdentity:this.#x.storeIdentity,sessionId:this.#u},(c,l)=>d(l)),o)}).finally(()=>{if(s=!1,this.#$===a&&(this.#$=null),Zr(this.#x?.storeIdentity,this.#u,this.#l?.runtime)){this.#R&&this.#Se();return}if(this.#l!==void 0){this.#Ae();return}let d=this.#D;this.#D=[],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"));Xc(this.#x.storeIdentity,this.#u);let n=this.#ue.signal,i=!0,o=Promise.resolve().then(async()=>{if(await gn(this.#Xe(),n),this.#ke!==void 0&&await gn(this.#ke(),n),this.#l!==void 0&&await gn(this.#l.settle(),n),this.#G!==void 0&&(await gn(this.#G.settle(),n)).status!=="completed")throw new Error("Archive retirement requires settled materials");if(this.#O!==void 0&&tc(this.#O),this.#Le)throw new Error("Archive retirement requires settled inputs");let s=this.#h,a=this.#z,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 p=this.#tt,h=en(this.#u,s,a),g=()=>{if(!i||n.aborted||this.#R||this.#W||this.#S!==void 0||this.#M!==null||this.#A!==null||this.#h!==s||this.#z!==a||this.#b!==d||this.#l!==c||this.#O!==l||this.#G!==f||this.#x!==u||en(this.#u,this.#h,a).sourceSnapshotDigest!==h.sourceSnapshotDigest)throw new Error("Archive detachment source changed")};return nl({observation:h,signal:n,assertCurrent:g,historyPort:u},{runtime:c?.runtime??null,contextMaterials:f,prepareDetach:()=>{g(),p.detach(),p.assertDetached()},detachOwnedState:()=>{this.#l=void 0,this.#O=void 0,this.#G=void 0,this.#He=!1,this.#x=void 0},assertDetached:()=>{if(this.#l!==void 0||this.#O!==void 0||this.#G!==void 0||this.#He||this.#x!==void 0)throw new Error("Archive detachment is incomplete")}},e)}).finally(()=>{if(i=!1,this.#$===o&&(this.#$=null),Zr(this.#x?.storeIdentity,this.#u,this.#l?.runtime))return;if(this.#l!==void 0){this.#Ae();return}let s=this.#D;this.#D=[],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.#z,o=this.#b;return dr({capture:e,messages:n,signal:this.#ue.signal,isCurrent:()=>!this.#R&&!this.#W&&this.#M===null&&this.#A===null&&this.#h===n&&this.#z===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(Vn(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ii(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.#D;this.#D=[],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.#z,a=this.#h,d=this.#a,c=this.#O,l=this.#l,f=this.#Z?Kf(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.#z!==s||this.#b!==i||this.#a!==d)throw new Error("Archive compaction source changed")}}),p;try{let h=this.#ee,g=h!==void 0&&o.checkpoint!==!1?v=>h(v,{trigger:"manual",...o.checkpoint!==void 0?{checkpoint:o.checkpoint}:{}}):void 0,m=await Ga({manager:i,compaction:n,view:{system:d,messages:a,tools:this.#k},model:this.#j,...this.#E!==void 0?{contextWindowTokens:this.#E}:{},...o.instructions!==void 0?{instructions:o.instructions}:{},...g!==void 0?{beforeCompact:g}:{},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 x=f(b);if(en(this.#u,x.messages,0).sourceSnapshotDigest!==en(this.#u,v,0).sourceSnapshotDigest)throw new Error("Archive compaction lineage changed");this.#Oe.set(v,{origins:Kg(x,this.#Me,this.#Z.head()),workId:u.ticket.rewriteId})}p=await l.persistRewrite(u,v)},commitPrepared:((v,b)=>{let x;return p(()=>{x=b()}),x})},isCurrent:()=>!this.#R&&!this.#W&&this.#z===s&&this.#h===a&&this.#a===d&&this.#b===i,publishHistory:v=>{this.#h=v,this.#z+=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 m.events)v.type==="cost.usage.updated"&&this.pushBody(v,"server");return{status:"rejected",reason:"session_ended"}}if(m.status==="compacted"){c===void 0&&(this.#h=Object.freeze(structuredClone(m.messages)),this.#z+=1,this.#xe+=1);for(let v of m.events)this.pushBody(v,"server");return this.#_e=this.#fe-1,{status:"compacted",outcome:m.outcome,...m.outcome.checkpointId!==void 0?{checkpointId:m.outcome.checkpointId}:{}}}for(let v of m.events)this.pushBody(v,"server");return m.status==="failed"?{status:"failed",outcome:m.outcome}:{status:"rejected",reason:m.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");Vn(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ii(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.#z,d=this.#b,c=this.#ue.signal,l=()=>!this.#R&&!this.#W&&this.#h===s&&this.#z===a&&this.#b===d,f=o.beginRewrite("restore",{signal:c,history:s,resources:new sr,assertCurrent:()=>{if(c.throwIfAborted(),!l())throw new Error("Archive restore source changed")}}),u=(async()=>{try{let p=await dr({capture:f.ticket.governanceCapture,messages:s,signal:c,isCurrent:l});return await e(async(h,g)=>{p.assertSourceCurrent();let m=Object.freeze(structuredClone([...h]));i&&this.#Oe.set(m,{origins:i,workId:g});let v=this.#rt(!0),b=await o.persistRewrite(f,m);return p.assertSourceCurrent(),b(()=>{this.#h=m,this.#z++,this.#xe++,this.#T.reset(),this.#b=v,this.#L!==void 0&&this.#b===void 0&&this.invalidateAttachmentReferences(),p.accept()}),this.pushBody({type:"session.restored",checkpointId:g,fromMessages:s.length,toMessages:h.length},"server"),this.#_e=this.#fe-1,{status:"restored",fromMessages:s.length,toMessages:h.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.#D=[]}}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(Vn(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ii(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.#z+=1,this.#xe+=1,this.#T.reset(),this.#b=s,this.#L!==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.#L!==void 0&&this.invalidateAttachmentReferences(),this.#o=e,this.#z+=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.#De("onEnded",e)}if(this.#me!==void 0)try{let e=Promise.resolve(this.#me()).catch(n=>{throw this.#De("onClosed",n),n});this.#re.track(e)}catch(e){this.#De("onClosed",e),this.#re.track(Promise.reject(e))}this.#mt()}}#vt(e){this.#pt({...e,seq:this.#fe++})}#pt(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.#De("onEvent",n.err)}#De(e,n){if(this.#ut+=1,!(this.#it||this.#W)){this.#it=!0;try{this.pushBody({type:"turn.error",scope:"server",message:ey(Zg.callbackFailed,{callback:e,message:Wa(n)},`Assembly callback ${e} threw (${Wa(n)}); the session continues.`),recoverable:!0,errorKind:"callback_error"},"server")}finally{this.#it=!1}}}#We(e,n){try{n()}catch(i){this.#De(e,i)}}#ht(e){if(this.#Ie!==void 0)try{return this.#Ie(e)}catch(n){this.#De("queryHooks",n);return}}#Ae(){if(this.#R&&this.#M===null&&this.#A===null&&this.#ge===void 0&&!this.#_){this.#Se();return}if(Zr(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.#D.length===0)return;let e=[...this.#D];try{this.#we(e),this.#D.splice(0,e.length),this.#Le=!1,this.#et=void 0}catch(n){this.#Le=!0,this.#et=n}}#we(e){let n=this.#m;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(Vn(this.#x?.storeIdentity,this.#u,this.#l?.runtime),ii(this.#x?.storeIdentity,this.#u,this.#l?.runtime),n?.archive){if(!this.#l)throw new Jt("reconciliation_required");Cs(n)}else this.#l?.assertReady();let i=this.#O===void 0?void 0:this.#h.length,o=n?.query.messages??[...this.#h,...e.map(m=>typeof m=="string"?{role:"user",blocks:[{t:"text",text:m}]}:m)],s=e.map(m=>typeof m=="string"?m:m.blocks.flatMap(v=>v.t==="text"?[v.text]:[]).join(`
|
|
23
|
+
`));this.#qe=[],this.#oe=n?.turn??this.#oe+1,this.#Ke=[],this.#Qe=!1,this.#Ge=n?.archive!==void 0&&fe(n.query.messages.slice(0,this.#h.length))!==fe(this.#h);let a=this.#oe;if(n===void 0&&this.#l===void 0&&this.#se!==void 0){let m=this.#se;this.#We("onTurnStart",()=>m(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.#q!==void 0?{maxOutputTokens:this.#q}:{},maxTokensEscalation:{ceilingTokens:Wf},...this.#I!==void 0?{thinking:this.#I}:{},sessionId:this.#u,initialMessages:o,...this.#p===void 0?{}:{recovery:{scope:this.#L??this.#u,...n===void 0?{}:{resume:n.query},...n===void 0||this.#d===void 0?{}:{prepare:async m=>{await this.#d(m)}},checkpoint:m=>{let v=this.#T.historyEpoch(),b=this.#oe,x=this.#l===void 0?void 0:this.#x?.read().confirmedCommit;if(this.#l&&!x)throw new Jt("reconciliation_required");return this.#p({query:m,historyEpoch:v,turn:b,...x===void 0?{}:{archive:{version:1,history:n?.archive?.history??x,messages:structuredClone(this.#h),queryDigest:ft(fe(m)),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.#pe!==void 0?{onInputsConsumed:m=>{this.#We("onInputsConsumed",()=>this.#pe?.(m.map(v=>v.text)))}}:{},...this.#E!==void 0?{contextWindowTokens:this.#E}:{},...this.#F!==void 0&&this.#b!==void 0?{...this.#v===void 0?{}:{onReportedUsage:m=>{if(m.purpose!=="compaction")return;let v=Mi({messages:[],transform:{ops:[],usage:m.usage},usageAttribution:{model:{model:m.model,provider:m.provider},contextWindowTokens:this.#E}});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=m=>{let v=n?.archive?this.#l.runtime.run.resumeRun(n.query.capture):this.#l?.runtime.run.planRun({turnId:Xg(),onAdmitted:()=>{this.#se!==void 0&&this.#We("onTurnStart",()=>this.#se(a,s))}}),b=this.#je(v===void 0?m:{...m,turnId:v.turnId});if(this.#He){let x=this.#re.registerWithReceipt(b);l=x.markEventsEnded,v!==void 0&&(v.bindQuery({handle:b,receipt:x.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},p,h=n!==void 0||this.#d===void 0?u(c):Aa({sessionId:this.#u,history:this.#h,prepare:async m=>(p=await this.#d(m),p),start:m=>{n!==void 0&&(m=this.#a),m.length===this.#a.length&&m.every((x,R)=>{let A=this.#a[R];return A?.text===x.text&&A.cacheable===x.cacheable&&A.label===x.label})||this.#b?.invalidateRequestBasis();let b=p===void 0?void 0:this.#c?.get(p);return b!==void 0&&this.#c.set(m,b),this.#a=m,u({...c,system:m})},...this.#l===void 0?{}:{eventsFor:m=>f?.query===m?f.events:m.events},errorScope:"server"});this.#M=h,this.#T.bind(h),n!==void 0&&(this.#T.restoreIdentity(n.historyEpoch,n.query.inputs),this.#m=void 0),this.#bt(h);let g=this.#St(h,a,()=>f,()=>l?.()).catch(m=>this.#wt(h,m)).finally(()=>l?.());this.#Ee.add(g),this.#re.track(g),g.then(()=>{this.#Ee.delete(g)},()=>{this.#Ee.delete(g)})}#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.#qe.slice(c):[];if(this.#l!==void 0){let f=i();this.#M=null,this.#qe=[],this.#D.unshift(...l);try{if(f!==void 0){let u=this.#Z&&!s?Qf(f.query):void 0;if(this.#Z&&!s&&!u)throw new Error("Archive query source snapshot unavailable");let p=s?this.#h:Object.freeze(u?[...u.messages]:e.messages());if(this.#Z&&u){let g=f.ticket.status();if(!g.captureRunKey)throw new Error("Archive captured run source unavailable");let m=this.#Z.turnRecord(g.captureRunKey,g.turnId),v=$g(u,this.#Me,m,this.#Z.head(),this.#Ge);this.#Oe.set(p,{origins:v,workId:g.captureRunKey})}let h={turn:n,history:p,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,p,h.rewritten,()=>{this.#h=p,this.#z++,this.#xe++,this.#_e=this.#fe-1,!s&&this.#le!==void 0&&this.#We("onTurnEnd",()=>{this.#L!==void 0&&(h.attachmentCheckpoint=this.attachmentCheckpoint(p)),h.attachmentSourceCheckpoint=this.attachmentSourceCheckpoint(p),h.memorySelectionCheckpoint=this.memorySelectionCheckpoint(),this.#le(h)})},s)}}finally{this.#_=!1,this.#Ae()}}else{if(!s&&(this.#h=Object.freeze(e.messages()),this.#z+=1,this.#xe+=1,this.#_e=this.#fe-1,this.#le!==void 0)){let u=this.#le,p={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.#L!==void 0&&(p.attachmentCheckpoint=this.attachmentCheckpoint(p.history)),p.attachmentSourceCheckpoint=this.attachmentSourceCheckpoint(p.history),p.memorySelectionCheckpoint=this.memorySelectionCheckpoint(),u(p)})}this.#M=null,this.#qe=[],this.#_=!1;let f=[...l,...this.#D.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:ey(Zg.pumpFailed,{message:Wa(n)},`Internal error in the session driver (${Wa(n)}); this turn was terminated.`),recoverable:!1,errorKind:"internal_error"},"server"),this.#M===e&&(this.#_=!1,this.#T.finish(e),this.#M=null,this.#qe=[],this.#at()),this.#R&&!this.#W&&this.#Se()}},Zg={callbackFailed:"server.v2.session.callback_failed",pumpFailed:"server.v2.session.pump_failed",promptRefreshFailed:"server.v2.session.prompt_refresh_failed"};function ey(t,e,n){let i=We(t,e);return i===t?n:i}function Wa(t){let e=t instanceof Error?t.message:String(t);return Tf(e).slice(0,400)}var Ou=new WeakMap;function U0(t,e,n){$a(t,e);let i={import:Object.freeze({}),restore:Object.freeze({checkpoint:!1})},o=Object.freeze({...n,handle:e});return Ou.set(i.import,o),Ou.set(i.restore,o),i}function Oo(t,e){let n=Ou.get(t);return n&&(n.handle!==e&&Lt(),n.assertCurrent()),n}var Du=new WeakMap,Va=new WeakMap,Ka=new WeakMap,yw=["withArchiveBinding","withArchiveColdBinding","withArchiveDetachment","archiveHistoryObservation","assertArchiveContextMaterialsAvailable","historySnapshot","bindArchiveHistoryPort","bindArchiveHistoryCommit","bindArchivePersistenceBarrier","bindArchiveColdHistory","prepareArchiveRuntimeRecovery","resumeArchiveRuntime","send","close","status","settleResources"],vw=yw.map(t=>({key:t,value:Zn.prototype[t]})),bw=Zn.prototype.status;function Lt(){throw new Error("Serve archive factory identity or lifecycle mismatch")}function tr(t){(!t||Mo.isProxy(t))&&Lt();let e=Du.get(t),n=Object.getOwnPropertyDescriptor(t,"create");return(!e||!n||!("value"in n)||n.value!==e.create)&&Lt(),mh(e.store),e}function Bo(t){t.inCallback&&(t.reentered=!0,Lt())}function Bu(t,e,n=[]){Bo(t),t.inCallback=!0,t.reentered=!1;try{let i=Reflect.apply(e,void 0,n);i!==void 0&&(Df(i),Lt()),t.reentered&&Lt()}finally{t.inCallback=!1}}function qu(t){(typeof t!="function"||Mo.isProxy(t))&&Lt()}function ty(t,e){let n=t;for(;n!==null;){Mo.isProxy(n)&&Lt();let i=Object.getOwnPropertyDescriptor(n,e);if(i!==void 0)return"value"in i||Lt(),i.value;n=Object.getPrototypeOf(n)}}function ny(t,e){e!==void 0&&Du.set(t,{factory:t,create:t.create,store:e,inCallback:!1,reentered:!1})}function iy(t,e){let n=Du.get(t);n!==void 0&&Bo(n);let i=Va.get(e);return i&&i.owner!==tr(t)&&Lt(),i}function Qa(t){(!t||Mo.isProxy(t)||vw.some(({key:e,value:n})=>ty(t,e)!==n))&&Lt(),Reflect.apply(bw,t,[])}function ry(t,e,n,i,o){let s=Va.get(e);(!s||s.owner!==tr(t))&&Lt(),Qa(i),(n.sessionId!==o.sessionId||n.endUserId!==e.endUserId)&&Lt(),Ka.set(n,{owner:s.owner,driver:i,handle:n,registration:Object.freeze({...o}),request:s,close:n.close,attempted:!1})}async function F0(t,e,n){let i=tr(t);Bo(i),(!n||Mo.isProxy(n))&&Lt();let o=Object.getOwnPropertyDescriptors(n);for(let h of Reflect.ownKeys(o))(typeof h!="string"||!["mode","assertCurrent","onRegistered"].includes(h)||!("value"in o[h])||!o[h].enumerable)&&Lt();let s=o.mode?.value,a=o.assertCurrent?.value,d=o.onRegistered?.value;s!=="fresh"&&s!=="resume"&&Lt(),qu(a),d!==void 0&&qu(d);let c=xn(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"&&Lt();let u=JSON.parse(fe(f));(u.fork!==void 0||s==="fresh"!=(u.resume===void 0)||typeof u.endUserId!="string"||u.endUserId.length===0)&&Lt();let p={owner:i,mode:s,prompt:l,assertCurrent(){tr(t),Bu(i,a),tr(t)},registered(h){this.assertCurrent(),d!==void 0&&Bu(i,d,[Object.freeze({...h})]),this.assertCurrent()}};Va.set(u,p);try{return p.assertCurrent(),await Reflect.apply(i.create,t,[u])}finally{Va.delete(u)}}function $a(t,e){let n=tr(t),i=Ka.get(e);return(!i||i.owner!==n||ty(e,"close")!==i.close)&&Lt(),Qa(i.driver),Object.freeze({driver:i.driver,store:n.store,registration:i.registration})}function L0(t,e,n){let i=tr(t);Bo(i),qu(n),$a(t,e);let o=Ka.get(e);(o.attempted||o.adoption!==void 0)&&Lt(),o.adoption=n}function oy(t){let e=Ka.get(t);if(!e)return;let n=e.owner;Bo(n),e.attempted&&Lt(),e.attempted=!0;try{$a(n.factory,t),e.adoption||Lt(),e.request.assertCurrent(),Bu(n,e.adoption),$a(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 Sw="<system-reminder>",ww="</system-reminder>";function sy(t){return t.t==="text"&&t.text.startsWith(Sw)&&t.text.endsWith(ww)}function Cr(t){let e=[];for(let n of t){if(n.role!=="user"||!n.blocks.some(sy)){e.push(n);continue}let i=n.blocks.filter(o=>!sy(o));i.length!==0&&e.push({...n,blocks:i})}return e}var Xe=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 kw}from"node:crypto";var Er=255;function qo(t){if(!Number.isInteger(t)||t<0||t>Er)throw new RangeError(`sessionIdShard must be an integer in [0, ${Er}], got ${String(t)}`)}function ju(t){return qo(t),t.toString(16).padStart(2,"0")}function Ja(t,e=kw){return ju(t)+e().slice(2)}function ay(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 Ya=class extends Error{cause;constructor(e){super(e instanceof Error?e.message:String(e)),this.name="AdoptFailure",this.cause=e}};function Rw(t){switch(t){case"not_found":return 404;case"already_resolved":case"digest_mismatch":return 409;case"expired":return 410}}function Nu(t){let{options:e,registry:n,admission:i}=t,o=t.sessionFamily??"sdk1",s=t.sessionFamily?{contract:t.sessionFamily,availability:"source-required"}:{},a=E=>qi(E)===o,d=t.authenticate??(E=>e.authenticate(E)),c=e.mediaMaxBodyBytes??Be.mediaMaxBodyBytes,l=e.sessionIdShard;l!==void 0&&qo(l);let f=async(E,y,P,L=!1)=>{let Z=ri(E,P),H=i.reserveBody(Z);return H.admitted?(y.once("close",()=>i.releaseBody(Z)),mi(E,P,L?de=>li(de,{maxBytes:P}):void 0)):(Kn(y,H),"rejected")},u=(E,y,P,L)=>{P==="too_large"?co(E,y,Ee.payloadTooLarge,le.v2PayloadTooLarge,{maxBytes:L}):me(y,400,Ee.invalidJson,le.invalidJson)},p=E=>{me(E,503,Ee.draining,le.draining,void 0,$t(i.retryAfterMs))},h=(E,y)=>{me(E,400,Ee.validationFailed,le.v2ValidationFailed,{detail:y})},g=(E,y)=>{me(E,404,Ee.sessionNotFound,le.sessionNotFound,{sessionId:y})},m=E=>{me(E,403,Ee.forbidden,le.v2Forbidden)},v=Nn(t.logger),b=(E,y,P)=>{v("error",at.storeError,{op:E,code:Ee.storeCorrupted,message:jn(y),...P!==void 0?{sessionId:P}:{}})},x=(E,y,P,L)=>{v("warn",at.sessionRejected,{status:E,code:y,message:jn(P),...L!==void 0?{sessionId:L}:{}})},R=(E,y,P,L,Z)=>{v("warn",at.upstreamRejected,{face:E,sessionId:y,...P!==void 0?{upstreamStatus:P}:{},upstreamCode:L,message:Z,status:503})},A=(E,y,P)=>{if(t.sessionFamily&&y instanceof Bn&&y.kind==="transient"){me(E,503,"source_unavailable",le.v2StoreCorrupted);return}b("read",y,P),me(E,500,Ee.storeCorrupted,le.v2StoreCorrupted)},C=(E,y,P)=>{let L=P instanceof Error?P.message:String(P);try{t.logger?.error(We(le.requestUnhandled,{method:y,path:E,message:L}))}catch{}},B=(E,y)=>{try{t.logger?.log?.("warn",at.sessionIdHintIgnored,{hintedSessionId:E,sessionId:y,shard:l})}catch{}},Y=(E,y,P)=>{try{let L=E.detail??{},Z=H=>{let de=L[H];return typeof de=="string"||typeof de=="number"||typeof de=="boolean"?de:void 0};t.logger?.log?.("warn",at.sessionRejected,{status:y,code:P,scope:"plan",platformCode:typeof E.params?.code=="string"?E.params.code:void 0,tier:Z("tier"),cap:Z("cap"),hardCap:Z("hardCap"),current:Z("current"),limit:Z("limit"),used:Z("used"),retryAfterMs:E.retryAfterMs,upgradeUrl:Z("upgradeUrl")})}catch{}},ne=(E,y,P,L)=>{C(y,P,L);try{if(E.destroyed||E.writableEnded)return;if(!E.headersSent){me(E,500,Ee.internalError,le.internalError);return}E.end()}catch{E.destroy()}},N=(E,y,P,L)=>{me(E,405,Ee.methodNotAllowed,le.methodNotAllowed,{method:y,path:P},{allow:L})},X=(E,y,P)=>{let L=n.get(y);return L===void 0||!a(L.handle)?"absent":L.handle.endUserId!==P?(m(E),"forbidden"):L},S=async(E,y)=>{if(E.destroyed)return!1;let P=new AbortController;xw(Math.max(10,y.length),P.signal);let L=()=>P.abort();E.once("close",L);try{await Promise.all(y.map(({handle:Z,lastSeq:H})=>n.waitForReplayWatermark(Z,H,P.signal)));for(let{handle:Z}of y){let H=n.get(Z.sessionId);if(!H||H.handle!==Z)throw new Error("Event publication identity changed");!H.ended&&Z.status()!=="ended"&&Z.owner?.assertCurrent()}return!E.destroyed}catch(Z){return P.signal.aborted||(Z instanceof oi?p(E):(C("/v2/sessions","GET",Z),me(E,500,Ee.internalError,le.internalError))),!1}finally{P.abort(),E.removeListener("close",L)}},w=E=>{let y=E.handle,P=n.lastActivityAt(y.sessionId)??y.createdAt,L=y.title(),Z=y.mediaState?.();return{...s,sessionId:y.sessionId,endUserId:y.endUserId,status:E.ended?"ended":y.status(),live:!E.ended,lastSeq:y.lastSeq(),createdAt:new Date(y.createdAt).toISOString(),lastActivityAt:new Date(P).toISOString(),...L!==void 0?{title:L}:{},...y.contextState?{context:y.contextState()}:{},...Z?{media:Z}:{}}},T=E=>{let y=E?.lastSeq;return typeof y=="number"&&Number.isSafeInteger(y)&&y>=0?y:0},_=(E,y,P)=>E.getMeta(y,P).then(T),G=(E,y)=>({...s,sessionId:E.sessionId,endUserId:y,status:"ended",live:!1,lastSeq:T(E),createdAt:E.createdAt,lastActivityAt:E.updatedAt,...E.title!==void 0?{title:E.title}:{}}),V=async(E,y,P)=>{let L=await f(E,y,t.maxBodyBytes);if(L==="rejected")return;if(!L.ok){u(E,y,L.reason,t.maxBodyBytes);return}let Z=zs.safeParse(L.value);if(!Z.success){h(y,Z.error.issues[0]?.message??"invalid body");return}let H=Z.data,de;if(H.endUser!==void 0&&H.endUser.id!==P){m(y);return}if(t.sessionFamily&&!H.resume){let F=L.value.requestId;if(typeof F!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(F)||H.fork||!t.prepareCreate){h(y,"offload creation requires requestId");return}try{de=t.prepareCreate(P,F,H)}catch($){if($ instanceof ut){me(y,$.code==="rollback_pending"?503:409,$.code,le.v2CreateFailed);return}throw $}if(de.resume){let{prompt:$,...K}=H;H={...K,resume:{sessionId:de.sessionId}}}}if(H.fork!==void 0){if(H.resume!==void 0){h(y,'"fork" and "resume" are mutually exclusive');return}let F=n.get(H.fork.sessionId);if(F&&!a(F.handle)){g(y,H.fork.sessionId);return}if(F!==void 0&&F.handle.endUserId!==P){m(y);return}}let ge=H.resume?.sessionId;if(ge!==void 0){let F=n.get(ge);if(F&&!a(F.handle)){g(y,ge);return}if(F!==void 0){if(F.handle.endUserId!==P){m(y);return}if(!F.ended){await M(y,F.handle,()=>de?.assertCurrent());return}}if(e.store===void 0){me(y,409,Ee.resumeUnavailable,le.v2ResumeUnavailable);return}}let ce=await i.rateLimit(E,P);if(!ce.admitted){Kn(y,ce);return}let ve=i.tryAdmitSession();if(!ve.admitted){Kn(y,ve);return}let D=n.beginCreate(ge??de?.sessionId,P);if(D.kind==="ticket"){let F=D.ticket,$=F.run(()=>te(F,H,de)),K;try{K=await $,de?.assertCurrent()}catch(Ae){k(y,Ae,ge);return}let he=K.handle.lastSeq();if(!await S(y,[{handle:K.handle,lastSeq:he}]))return;de?.assertCurrent(),Je(y,201,{...s,sessionId:K.handle.sessionId,resumed:K.resumed,lastSeq:he});return}switch(D.kind){case"live":if(!a(D.handle)){g(y,ge??"");return}try{de?.assertCurrent()}catch(F){k(y,F,ge,!1);return}await M(y,D.handle,()=>de?.assertCurrent());return;case"joined":{try{let F=await D.outcome;if(de?.assertCurrent(),!a(F.handle)){g(y,ge??"");return}await M(y,F.handle,()=>de?.assertCurrent())}catch(F){k(y,F,ge,!1)}return}case"forbidden":m(y);return;case"closing":p(y);return;case"reserve_rejected":me(y,429,Ee.sessionLimitExceeded,le.v2SessionLimit,{max:D.max},$t(i.retryAfterMs));return}},te=async(E,y,P)=>{let Z={endUserId:E.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:Ja(l)}:{}};P&&!P.resume&&(Z.sessionId=P.sessionId),P?.apply(Z);let H=E.id,de=await e.createSession.create(Z);if(!a(de.handle))throw de.handle.close(),await de.handle.settleResources?.(),new Error("Session family mismatch");Z.sessionId!==void 0&&de.handle.sessionId!==Z.sessionId&&B(Z.sessionId,de.handle.sessionId),H!==void 0&&n.evictEnded(H);try{E.adopt(de.handle),oy(de.handle)}catch(ge){throw ge instanceof oi?ge:(C("/v2/sessions","POST",ge),new Ya(ge))}return de},re=E=>({...s,sessionId:E.sessionId,resumed:!1,lastSeq:E.lastSeq()}),M=async(E,y,P)=>{let L=re(y);await S(E,[{handle:y,lastSeq:L.lastSeq}])&&(P(),Je(E,200,L))},k=(E,y,P,L=!0)=>{if(t.sessionFamily&&y instanceof ut){me(E,y.code==="rollback_pending"?503:409,y.code,le.v2CreateFailed);return}if(y instanceof Xe){if(y.code==="session_not_found"){g(E,P??"");return}if(y.code==="resume_unavailable"){me(E,409,Ee.resumeUnavailable,le.v2ResumeUnavailable);return}if(y.code==="store_corrupted"){L&&b("create",y,P),me(E,500,Ee.storeCorrupted,le.v2StoreCorrupted);return}let Z=$t(y.retryAfterMs??i.retryAfterMs);if(y.code==="upstream_unavailable"){L&&x(503,Ee.upstreamUnavailable,y,P),me(E,503,Ee.upstreamUnavailable,le.v2UpstreamUnavailable,void 0,Z);return}if(y.code==="overloaded"){me(E,503,Ee.overloaded,le.overloaded,void 0,Z);return}if(y.code==="plan_limited"){Y(y,429,Ee.rateLimited),me(E,429,Ee.rateLimited,le.v2PlanConcurrencyLimited,void 0,Z,{scope:"plan"});return}if(y.code==="plan_denied"){let H=typeof y.params?.code=="string"?y.params.code:"plan_required";Y(y,403,H),me(E,403,H,le.v2PlanDenied,{code:H},void 0,{scope:"plan"});return}if(y.code==="cwd_not_allowed"){me(E,400,Ee.cwdNotAllowed,kt.cwdNotAllowed,{detail:y.message,...y.params??{}});return}if(y.code==="cwd_invalid"){me(E,400,Ee.cwdInvalid,kt.cwdInvalid,{reason:"invalid",detail:y.message,...y.params??{}});return}if(y.code==="cwd_unavailable"){let H=y.params?.reason;me(E,409,Ee.cwdUnavailable,kt.cwdUnavailable,{cwd:y.message,...y.params??{}},void 0,typeof H=="string"?{cwd:y.params?.cwd??y.message,reason:H}:void 0);return}if(y.code==="fork_source_not_found"){me(E,404,Ee.forkSourceNotFound,kt.forkSourceNotFound,{sessionId:"",checkpointId:"",...y.params??{}});return}if(y.code==="checkpoints_not_wired"){me(E,409,Ee.checkpointsNotWired,kt.checkpointsNotWired);return}h(E,y.message);return}if(y instanceof oi){p(E);return}if(y instanceof Ya){me(E,500,Ee.internalError,le.internalError);return}L&&x(400,Ee.createFailed,y,P),me(E,400,Ee.createFailed,le.v2CreateFailed)},j=async(E,y,P)=>{let L=new URL(E.url??"/","http://local").searchParams,Z=L.get("limit"),H=L.get("offset"),de=Be.listLimitDefault,ge=0;if(Z!==null){if(!/^\d+$/.test(Z)){h(y,"limit must be a positive integer");return}if(de=Number.parseInt(Z,10),de<1||de>Be.listLimitMax){h(y,`limit must be within 1..${Be.listLimitMax}`);return}}if(H!==null){if(!/^\d+$/.test(H)){h(y,"offset must be a non-negative integer");return}ge=Number.parseInt(H,10)}let ce=new Map;if(e.store!==void 0){let K;try{K=await e.store.list(P)}catch(he){A(y,he);return}for(let he of K)ce.set(he.sessionId,G(he,P))}let ve=new Map;for(let K of n.entriesFor(P))a(K.handle)&&(ce.set(K.handle.sessionId,w(K)),ve.set(K.handle.sessionId,K.handle));if(t.filterSessionReads){let K=new Set(await t.filterSessionReads(P,[...ce.keys()]));for(let he of ce.keys())K.has(he)||ce.delete(he)}let D=[...ce.values()].sort((K,he)=>he.lastActivityAt.localeCompare(K.lastActivityAt)),F=D.slice(ge,ge+de),$=F.flatMap(K=>{let he=ve.get(K.sessionId);return he?[{handle:he,lastSeq:K.lastSeq}]:[]});if(await S(y,$))if(t.filterSessionReads){let K=new Set(await t.filterSessionReads(P,[...ce.keys()]));Je(y,200,{sessions:F.filter(he=>K.has(he.sessionId)),total:D.filter(he=>K.has(he.sessionId)).length})}else Je(y,200,{sessions:F,total:D.length})},W=(E,y)=>{try{return y()}catch(P){if(P instanceof Ff)return me(E,503,Ee.overloaded,le.materialRequired,void 0,$t(i.retryAfterMs),{scope:"context.materials",reason:P.code}),null;if(!(P instanceof Yo)||P.code!=="capacity_exceeded")throw P;return me(E,503,Ee.overloaded,le.overloaded,void 0,$t(i.retryAfterMs),{scope:"archive",reason:"capacity_exceeded"}),null}},q=async(E,y,P,L)=>{let Z=X(y,P,L);if(Z==="forbidden")return;if(Z==="absent"){g(y,P);return}let H=await f(E,y,c);if(H==="rejected")return;if(!H.ok){u(E,y,H.reason,c);return}let de=Hs.safeParse(H.value);if(!de.success){h(y,de.error.issues[0]?.message??"invalid body");return}if(Z.ended){me(y,409,Ee.sessionEnded,le.sessionEnded,{sessionId:P});return}if(de.data.prompt!==void 0){let ve=W(y,()=>Z.handle.send(de.data.prompt));if(ve===null)return;if(ve==="ended"){me(y,409,Ee.sessionEnded,le.sessionEnded,{sessionId:P});return}n.touch(P),Je(y,202,{sessionId:P,accepted:!0});return}let ge={role:"user",blocks:(de.data.blocks??[]).map(ve=>ve.t==="text"?{t:"text",text:ve.text}:{t:"image",mime:ve.mime,data:ve.data})},ce=W(y,()=>Z.handle.sendMessage(ge));if(ce!==null){if(ce==="midturn"){me(y,422,Ee.midturnBlocksRejected,le.v2MidturnBlocks);return}if(ce==="ended"){me(y,409,Ee.sessionEnded,le.sessionEnded,{sessionId:P});return}n.touch(P),Je(y,202,{sessionId:P,accepted:!0})}},Q=async(E,y,P,L,Z,H)=>{let de=X(y,P,L);if(de==="forbidden")return;if(de==="absent"){g(y,P);return}let ge=de.handle;if(Z==="input-capabilities"){Je(y,200,ge.inputCapabilities?.()??{version:1,text:!1,textBlocks:!1,image:!1,memoryAck:!1,durableAck:!1,receiptRetention:"current-and-last-turn",target:null});return}if(H!==void 0){let F=new URL(E.url??"/","http://local").searchParams,$=Dl.safeParse({historyEpoch:F.get("historyEpoch"),turnId:F.get("turnId")});if(!$.success){h(y,$.error.issues[0]?.message??"invalid target");return}let K=ge.getInputStatus?.(H,$.data)??null;Je(y,K===null?404:200,K===null?{outcome:"rejected",code:"input_not_found"}:{receipt:K});return}let ce=await f(E,y,c);if(ce==="rejected")return;if(!ce.ok){u(E,y,ce.reason,c);return}let ve=bh.safeParse(ce.value);if(!ve.success){h(y,ve.error.issues[0]?.message??"invalid input");return}if(ge.submitInput===void 0){Je(y,422,{outcome:"rejected",code:"input_unsupported"});return}let D=await ge.submitInput({inputId:ve.data.inputId,target:ve.data.target,content:ve.data.content,...ve.data.ack!==void 0?{ack:ve.data.ack}:{}});D.outcome==="accepted"&&n.touch(P),Je(y,D.outcome==="accepted"?202:D.outcome==="closed"?409:D.code==="injection_limit"?429:D.code==="input_conflict"?409:422,D)},U=(E,y,P,L)=>{let Z=i.tryAdmitSse(L);if(!Z.admitted){Kn(y,Z);return}y.once("close",()=>i.releaseSse(L)),t.sseKeepAliveMs>0&&E.socket.setKeepAlive(!0,t.sseKeepAliveMs),E.socket.setTimeout(0);let H=X(y,P,L);if(H==="forbidden")return;if(H==="absent"){g(y,P);return}let de=js(E.headers["last-event-id"]);if(de===void 0){h(y,"invalid Last-Event-ID");return}let ge=new URL(E.url??"/","http://local").searchParams,ce=Vs(ge.get("exclude"));if(ce===null){h(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 ve=H.handle.firstSeq?.()??0,D=()=>(H.handle.firstSeq?.()??0)===ve,F=t.sse.attach(y,{gapFrame:K=>gr(P,K),beforeFlush:()=>{if(!D())return!1;let K=d(E,y);return t.filterSessionReads?Promise.resolve(K).then(async he=>he?.endUserId===L&&(await t.filterSessionReads(L,[P])).includes(P)&&D()):K!==null&&"then"in K?Promise.resolve(K).then(he=>he?.endUserId===L&&D()):K?.endUserId===L&&D()}}),$=n.subscribe(P,de,F,ce);y.on("close",()=>{$?.()})},ue=async(E,y,P,L)=>{let Z=new URL(E.url??"/","http://local").searchParams.getAll("include");if(Z.length>1||Z.length===1&&Z[0]!=="applicationPrompt"){h(y,"include must be applicationPrompt and occur once");return}let H=X(y,P,L);if(H==="forbidden")return;if(H!=="absent"){let ce=w(H);if(!await S(y,[{handle:H.handle,lastSeq:ce.lastSeq}]))return;let ve=t.readHistoryOrigin?{historyOrigin:await t.readHistoryOrigin(L,P)}:{},D=Z.length===1&&!H.ended&&H.handle.status()!=="ended"?H.handle.applicationPrompt?.():void 0,$=D!=null&&Object.keys(D).length===2&&(D.policy==="fallback"||D.policy==="prepend")&&["none","platform","sdk","platform+sdk"].includes(D.source)&&!(D.policy==="fallback"&&D.source==="platform+sdk")?{applicationPrompt:{policy:D.policy,source:D.source}}:{};if(t.filterSessionReads&&!(await t.filterSessionReads(L,[P])).includes(P)){g(y,P);return}Je(y,200,{...ce,...ve,...$});return}let de;try{de=await e.store?.getMeta(L,P)}catch(ce){A(y,ce,P);return}if(de==null){g(y,P);return}let ge=t.readHistoryOrigin?{historyOrigin:await t.readHistoryOrigin(L,P)}:{};Je(y,200,{...G(de,L),...ge})},pe=async(E,y,P,L)=>{let Z=X(y,P,L);if(Z==="forbidden")return;let H=Ps(new URL(E.url??"/","http://local").searchParams);if(!H.ok){h(y,H.detail);return}let de=H.page,{offset:ge=0,limit:ce}=de??{};if(Z!=="absent"){let K=Z.handle.historySnapshot();if(de===null){Je(y,200,{sessionId:P,lastSeq:K.lastSeq,messages:Cr(K.messages)});return}let he=Un(K.messages,ge,ce);Je(y,200,{sessionId:P,lastSeq:K.lastSeq,messages:Cr(he.messages),total:he.total,offset:he.offset,nextOffset:he.nextOffset});return}let ve=e.store;if(de!==null&&ce!==void 0&&ve?.getHistoryPage!==void 0){let K;try{K=await ve.getHistoryPage(L,P,{offset:ge,limit:ce})}catch(Ae){A(y,Ae,P);return}if(K===null){g(y,P);return}let he;try{he=await _(ve,L,P)}catch(Ae){A(y,Ae,P);return}Je(y,200,{sessionId:P,lastSeq:he,messages:Cr(K.messages),total:K.total,offset:K.offset,nextOffset:K.nextOffset});return}if(ve===void 0){g(y,P);return}let D;try{D=await ve.getHistory(L,P)}catch(K){A(y,K,P);return}if(D===null){g(y,P);return}let F;try{F=await _(ve,L,P)}catch(K){A(y,K,P);return}if(de===null){Je(y,200,{sessionId:P,lastSeq:F,messages:Cr(D)});return}let $=Un(D,ge,ce);Je(y,200,{sessionId:P,lastSeq:F,messages:Cr($.messages),total:$.total,offset:$.offset,nextOffset:$.nextOffset})},oe=E=>{me(E,409,Ee.turnRunning,kt.turnRunning)},ee=E=>{me(E,409,Ee.checkpointsNotWired,kt.checkpointsNotWired)},O=(E,y)=>{me(E,404,Ee.checkpointNotFound,kt.checkpointNotFound,{checkpointId:y})},J=(E,y)=>{me(E,409,Ee.sessionEnded,le.sessionEnded,{sessionId:y})},ke=(E,y)=>{if(y instanceof et){A(E,y);return}throw y},we=async(E,y,P,L)=>{let Z=X(y,P,L);if(Z==="forbidden")return;if(Z==="absent"){g(y,P);return}let H=await f(E,y,t.maxBodyBytes);if(H==="rejected")return;if(!H.ok){u(E,y,H.reason,t.maxBodyBytes);return}let de=$s.safeParse(H.value);if(!de.success){h(y,de.error.issues[0]?.message??"invalid body");return}if(Z.ended){J(y,P);return}if(Z.handle.compact===void 0){Je(y,200,{status:"rejected",reason:"not_configured"});return}let ge;try{ge=await Z.handle.compact(de.data)}catch(ce){ke(y,ce);return}if(n.touch(P),ge.status==="rejected"&&ge.reason==="turn_running"){oe(y);return}if(ge.status==="rejected"&&ge.reason==="session_ended"){J(y,P);return}if(ge.status==="rejected"&&ge.reason==="checkpoints_not_wired"){ee(y);return}Je(y,200,ge)},qe=async(E,y,P)=>{let L=X(E,y,P);if(L==="forbidden")return;if(L==="absent"){g(E,y);return}if(L.handle.listCheckpoints===void 0){ee(E);return}let Z;try{Z=await L.handle.listCheckpoints()}catch(H){ke(E,H);return}if(Z.status==="rejected"){ee(E);return}Je(E,200,{checkpoints:Z.checkpoints})},ze=async(E,y,P,L)=>{let Z=X(y,P,L);if(Z==="forbidden")return;if(Z==="absent"){g(y,P);return}let H=await f(E,y,t.maxBodyBytes);if(H==="rejected")return;if(!H.ok){u(E,y,H.reason,t.maxBodyBytes);return}let de=Ks.safeParse(H.value);if(!de.success){h(y,de.error.issues[0]?.message??"invalid body");return}if(Z.ended){J(y,P);return}if(Z.handle.checkpoint===void 0){ee(y);return}let ge;try{ge=await Z.handle.checkpoint(de.data)}catch(ce){ke(y,ce);return}if(n.touch(P),ge.status==="created"){Je(y,201,ge.checkpoint);return}ge.reason==="turn_running"?oe(y):ge.reason==="session_ended"?J(y,P):ee(y)},He=async(E,y,P,L,Z)=>{let H=X(y,P,L);if(H==="forbidden")return;if(H==="absent"){g(y,P);return}let de=await f(E,y,t.maxBodyBytes);if(de==="rejected")return;if(!de.ok){u(E,y,de.reason,t.maxBodyBytes);return}let ge=Qs.safeParse(de.value);if(!ge.success){h(y,ge.error.issues[0]?.message??"invalid body");return}if(H.ended){J(y,P);return}if(H.handle.restore===void 0){ee(y);return}let ce;try{ce=await H.handle.restore(Z,ge.data)}catch(ve){ke(y,ve);return}if(n.touch(P),ce.status==="restored"){Je(y,200,ce);return}switch(ce.reason){case"turn_running":oe(y);return;case"session_ended":J(y,P);return;case"not_found":O(y,Z);return;case"session_mismatch":me(y,409,Ee.sessionMismatch,kt.sessionMismatch,{checkpointId:Z});return;case"checkpoints_not_wired":ee(y);return}},ht=async(E,y,P,L)=>{let Z=X(E,y,P);if(Z==="forbidden")return;if(Z==="absent"){g(E,y);return}if(Z.handle.deleteCheckpoint===void 0){ee(E);return}let H;try{H=await Z.handle.deleteCheckpoint(L)}catch(de){ke(E,de);return}if(H==="deleted"){E.writeHead(204),E.end();return}H==="not_found"?O(E,L):ee(E)},Ot=async(E,y,P,L)=>{let Z=X(y,P,L);if(Z==="forbidden")return;if(Z==="absent"){g(y,P);return}let H=await f(E,y,t.maxBodyBytes);if(H==="rejected")return;if(!H.ok){u(E,y,H.reason,t.maxBodyBytes);return}let de=Js.safeParse(H.value);if(!de.success){h(y,de.error.issues[0]?.message??"invalid body");return}if(Z.ended){J(y,P);return}let ge=()=>{me(y,409,Ee.cwdSwitchUnsupported,kt.cwdSwitchUnsupported)};if(Z.handle.setCwd===void 0){ge();return}let ce;try{ce=await Z.handle.setCwd(de.data.cwd)}catch(D){ke(y,D);return}if(n.touch(P),ce.status==="changed"){Je(y,200,{cwd:ce.cwd,from:ce.from});return}let ve=ce.detail??ce.reason;switch(ce.reason){case"turn_running":oe(y);return;case"session_ended":J(y,P);return;case"not_allowed":me(y,400,Ee.cwdNotAllowed,kt.cwdNotAllowed,{detail:ve});return;case"not_absolute":case"not_found":case"not_directory":me(y,400,Ee.cwdInvalid,kt.cwdInvalid,{reason:ce.reason,detail:ve});return;case"unsupported":ge();return}},Fe=async(E,y,P,L,Z)=>{let H=X(y,P,L);if(H==="forbidden")return;if(H==="absent"){g(y,P);return}let de=H.handle.platformAudio;if(de===void 0){me(y,409,Ee.platformUnavailable,le.v2PlatformUnavailable);return}if(H.ended){J(y,P);return}let ge=Z==="transcriptions"?"speechToText":"textToSpeech";if(!de.capabilities[ge]){me(y,403,Ee.capabilityDisabled,le.v2PlatformCapabilityDisabled,{bit:ge});return}let ce=await f(E,y,ho);if(ce==="rejected")return;if(!ce.ok){u(E,y,ce.reason,ho);return}let ve=Z==="transcriptions"?Zs.safeParse(ce.value):ea.safeParse(ce.value);if(!ve.success){h(y,ve.error.issues[0]?.message??"invalid body");return}let D=new AbortController;y.once("close",()=>{y.writableEnded||D.abort()});let F=Z==="transcriptions"?"asr":"tts",$=await de.request(F,ve.data,D.signal);if(n.touch(P),$.kind==="transport_error"){R(F,P,void 0,"transport_error",$.message),me(y,503,Ee.upstreamUnavailable,le.v2UpstreamUnavailable,void 0,$t(i.retryAfterMs));return}if($.status<200||$.status>=300){let{code:Ae,message:ot,detail:$e}=gu($.body,$.status);if($.status===401||$.status===403||$.status>=500){R(F,P,$.status,Ae,ot),me(y,503,Ee.upstreamUnavailable,le.v2UpstreamUnavailable,void 0,$t(i.retryAfterMs));return}me(y,$.status,Ae,le.v2PlatformAudioRejected,{code:Ae,message:ot},void 0,$e);return}let K=ve.data.model??"(default)",he=Z==="transcriptions"?Qr($.body,K):Yr($.body,K);if(he===null){me(y,503,Ee.upstreamUnavailable,le.v2PlatformAudioUnexpected,void 0,$t(i.retryAfterMs));return}Je(y,200,he)},Ze=async(E,y,P)=>{let L=ri(E,P),Z=i.reserveBody(L);return Z.admitted?(y.once("close",()=>i.releaseBody(L)),new Promise(H=>{let de=[],ge=0,ce=!1,ve=F=>{ce||(ce=!0,H(F))},D=F=>{if(ge+=F.length,ge>P){de.length=0,E.off("data",D),E.pause(),ve("too_large");return}de.push(F)};E.on("data",D),E.on("end",()=>ve(new Uint8Array(Buffer.concat(de)))),E.on("error",()=>ve(new Uint8Array))})):(Kn(y,Z),"rejected")},It=async(E,y,P,L)=>{let Z=X(E,y,P);if(Z==="forbidden")return;if(Z==="absent"){g(E,y);return}if(Z.handle.exportCheckpoint===void 0){ee(E);return}let H;try{H=await Z.handle.exportCheckpoint(L)}catch(de){ke(E,de);return}if(H.status==="rejected"){H.reason==="not_found"?O(E,L):ee(E);return}E.writeHead(200,{"content-type":Ys,"content-length":H.bytes.byteLength,"content-disposition":`attachment; filename="${y}-${L}.tansr-checkpoint.json"`}),E.end(Buffer.from(H.bytes.buffer,H.bytes.byteOffset,H.bytes.byteLength))},xt=async(E,y,P,L)=>{let Z=X(y,P,L);if(Z==="forbidden")return;if(Z==="absent"){g(y,P);return}if(Z.handle.importCheckpoint===void 0){ee(y);return}if(Z.ended){J(y,P);return}let H=await Ze(E,y,po);if(H==="rejected")return;if(H==="too_large"){co(E,y,Ee.payloadTooLarge,le.v2PayloadTooLarge,{maxBytes:po});return}let de=new URL(E.url??"/","http://local").searchParams.get("label");if(de!==null&&de.length>Ui){h(y,`label must be at most ${Ui} characters`);return}let ge;try{ge=await Z.handle.importCheckpoint(H,de!==null&&de!==""?{label:de}:{})}catch(ce){ke(y,ce);return}if(n.touch(P),ge.status==="imported"){Je(y,201,ge.checkpoint);return}if(ge.reason==="invalid"){me(y,400,Ee.checkpointImportInvalid,kt.checkpointImportInvalid,{detail:ge.detail});return}ge.reason==="session_ended"?J(y,P):ee(y)},pn=(E,y,P)=>{let L=X(E,y,P);if(L!=="forbidden"){if(L==="absent"){g(E,y);return}L.handle.interrupt(),n.touch(y),Je(E,202,{sessionId:y,accepted:!0})}},Mn=async(E,y,P)=>{let L=X(E,y,P);if(L==="forbidden")return;if(L!=="absent"){n.requestClose(y),Je(E,202,{sessionId:y,accepted:!0});return}let Z;try{Z=await e.store?.getMeta(P,y)}catch(H){A(E,H,y);return}if(Z==null){g(E,y);return}Je(E,202,{sessionId:y,accepted:!0})},Rt=async(E,y,P,L,Z,H)=>{let de=X(y,P,L);if(de==="forbidden")return;if(de==="absent"){g(y,P);return}let ge=Z==="tool-results"?c:t.maxBodyBytes,ce=await f(E,y,ge);if(ce==="rejected")return;if(!ce.ok){u(E,y,ce.reason,ge);return}let ve,D;if(Z==="tool-results"){D="call";let $=pr.safeParse(ce.value);if(!$.success){h(y,$.error.issues[0]?.message??"invalid receipt");return}ve=de.handle.submitToolResult(H,$.data)}else if(Z==="permission"){D="request";let $=Gs.safeParse(ce.value);if(!$.success){h(y,$.error.issues[0]?.message??"invalid receipt");return}ve=de.handle.submitPermission(H,$.data)}else{D="request";let $=Ws.safeParse(ce.value);if(!$.success){h(y,$.error.issues[0]?.message??"invalid receipt");return}ve=de.handle.submitQuestionAnswers(H,$.data)}if(n.touch(P),ve==="accepted"){Je(y,200,{accepted:!0});return}if(ve==="invalid"){h(y,"receipt does not match the pending request");return}let F=ve==="digest_mismatch"?Ee.digestMismatch:`${D}_${ve}`;me(y,Rw(ve),F,le.v2ReceiptRejected,{code:F})},At=async(E,y,P,L)=>{let Z;try{Z=await d(E,y)}catch(ce){if(y.destroyed||y.writableEnded)return;if(ce instanceof Pt){me(y,503,ce.code,ce.code==="overloaded"?le.overloaded:le.internalError,{},$t(i.retryAfterMs));return}Z=null}if(E.aborted||y.destroyed||y.writableEnded)return;if(Z===null){me(y,401,Ee.unauthorized,le.unauthorized);return}let H=Z.endUserId;if(P==="/v3/sdk2/session-capabilities"){if(L!=="GET"){N(y,L,P,"GET");return}if(E.headers["transfer-encoding"]!==void 0||E.headers["content-length"]!==void 0&&E.headers["content-length"]!=="0"){me(y,400,"invalid_request",le.v2ValidationFailed);return}let ce=new URL(E.url??"","http://serve").searchParams;if([...ce.keys()].some(D=>D!=="protocol")||ce.getAll("protocol").length>1){me(y,400,"invalid_request",le.v2ValidationFailed);return}if(ce.getAll("protocol").length!==1||ce.get("protocol")!=="sdk2-ext-v1"){me(y,400,"protocol_version_mismatch",le.v2ValidationFailed);return}let ve=Zt({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(ve);return}let de=e.createSession.execution??e.createSession.transactionalExecution;if(de!==void 0&&await Gg({host:de,req:E,res:y,pathname:P,method:L,endUserId:H,log:v,retryAfterMs:i.retryAfterMs,...t.sessionFamily===void 0?{}:{sessionFamily:t.sessionFamily},readBody:()=>f(E,y,Math.min(t.maxBodyBytes,262144),!0)}))return;if(P==="/v2/sessions"){if(L==="POST"){await V(E,y,H);return}if(L==="GET"){await j(E,y,H);return}N(y,L,P,"POST, GET");return}let ge=kh.exec(P);if(ge!==null){let ce=pi(ge[1]),ve=ge[3]!==void 0?pi(ge[3]):void 0;if(ce===null||ve===null){me(y,404,Ee.notFound,le.notFound,{path:P});return}if(L==="GET"&&t.filterSessionReads&&!(await t.filterSessionReads(H,[ce])).includes(ce)){g(y,ce);return}let D=ge[2],F=ge[4];if(D==="inputs"||D==="input-capabilities"){let $=D==="input-capabilities"||ve!==void 0?"GET":"POST";if(F!==void 0||D==="input-capabilities"&&ve!==void 0){me(y,404,Ee.notFound,le.notFound,{path:P});return}if(L!==$){N(y,L,P,$);return}await Q(E,y,ce,H,D,ve);return}if(D==="audio"){if(ve!=="transcriptions"&&ve!=="speech"||F!==void 0){me(y,404,Ee.notFound,le.notFound,{path:P});return}if(L!=="POST"){N(y,L,P,"POST");return}await Fe(E,y,ce,H,ve);return}if(D==="cwd"){if(ve!==void 0){me(y,404,Ee.notFound,le.notFound,{path:P});return}if(L!=="POST"){N(y,L,P,"POST");return}await Ot(E,y,ce,H);return}if(D==="compact"||D==="checkpoints"){if(D==="compact"){if(ve!==void 0){me(y,404,Ee.notFound,le.notFound,{path:P});return}if(L!=="POST"){N(y,L,P,"POST");return}await we(E,y,ce,H);return}if(ve===void 0){if(L==="GET"){await qe(y,ce,H);return}if(L==="POST"){await ze(E,y,ce,H);return}N(y,L,P,"GET, POST");return}if(ve===Xs&&F===void 0){if(L!=="POST"){N(y,L,P,"POST");return}await xt(E,y,ce,H);return}if(F==="restore"){if(L!=="POST"){N(y,L,P,"POST");return}await He(E,y,ce,H,ve);return}if(F==="export"){if(L!=="GET"){N(y,L,P,"GET");return}await It(y,ce,H,ve);return}if(L!=="DELETE"){N(y,L,P,"DELETE");return}await ht(y,ce,H,ve);return}if(F!==void 0){me(y,404,Ee.notFound,le.notFound,{path:P});return}if(D===void 0){if(ve!==void 0){me(y,404,Ee.notFound,le.notFound,{path:P});return}if(L==="GET"){await ue(E,y,ce,H);return}if(L==="DELETE"){await Mn(y,ce,H);return}N(y,L,P,"GET, DELETE");return}if(D==="tool-results"||D==="permission"||D==="questions"){if(ve===void 0){me(y,404,Ee.notFound,le.notFound,{path:P});return}if(L!=="POST"){N(y,L,P,"POST");return}await Rt(E,y,ce,H,D,ve);return}if(ve!==void 0){me(y,404,Ee.notFound,le.notFound,{path:P});return}if(D==="events"||D==="history"){if(L!=="GET"){N(y,L,P,"GET");return}D==="events"?U(E,y,ce,H):await pe(E,y,ce,H);return}if(L!=="POST"){N(y,L,P,"POST");return}D==="messages"?await q(E,y,ce,H):pn(y,ce,H);return}me(y,404,Ee.notFound,le.notFound,{path:P})};return(E,y,P,L)=>{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 Z=At(E,y,P,L);return t.trackRequestWork?.(Z),Z.catch(H=>{ne(y,P,L,H)}),!0}}var _r=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}},Xa=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 _r("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 _r("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())}}},Pr=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}}},Za=class{#e;#n;#r;constructor(e){this.#e=new Pr(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 Xt={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"},dy=Object.values(Xt);var cy="/v1/app-tokens",Iw=16*1024,Tw=3e5,Aw=32,Cw=1024,Ew=1e4,_w=.15,ly=5e3,Pw=6e4,Mw=1e5,Ow=36e5,Bw=1e4,Uu=new Set(["adjudicator_evidence_drifted","adjudicator_budget_exhausted","adjudicator_breaker_tripped","adjudicator_unavailable","adjudicator_posture_overridden","adjudicator_budget_unenforced"]),qw=6e5,uy=Eo[0],fy="unknown",Sn=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 Dw(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,qw)}function my(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 py(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 jw(t){let e;try{e=await t.clone().json()}catch{return}let n=my(e);if(!Ea(n))return;let o=py(e)?.reason,s=typeof o=="string"&&o!==""?o:fy;if(!_a(s))return{code:n,reason:s}}function Nw(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 ed(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(Tw,s*1e3/2),d=Math.min(.99,Math.max(0,t.expiryJitterRatio??_w)),c=Math.max(0,t.negativeCacheInitialMs??ly),l=Math.max(c,t.negativeCacheMaxMs??Pw),f=t.maxCachedTokens??Mw,u=dp(t.appKey),p=Ln(t.metrics),h=new Xa({maxConcurrent:t.maxConcurrentMints??Aw,maxQueued:t.maxQueuedMints??Cw,queueTimeoutMs:t.mintQueueTimeoutMs??Ew}),g=new Pr(f),m=new Pr(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:{}},x=(N,X)=>We(Xt.mintFailed,{status:N,code:X}),R=N=>{let X=g.get(N);if(X!==void 0){if(X.expiresAtMs<=i()){g.delete(N);return}return X}},A=(N,X)=>{if(b.failures[X.kind]+=1,X.kind==="saturated")return;p.tokenMintFailures.inc();let S=m.peek(N),w=S===void 0?c:Math.min(l,S.backoffMs*2),T=Math.max(w,Math.min(X.retryAfterMs??0,l));m.set(N,{until:i()+T,backoffMs:w,kind:X.kind,status:X.status,message:X.message,code:X.code,detail:X.detail})},C=async N=>{b.mints+=1;let X=JSON.stringify({endUserId:N,ttlSeconds:s}),S;try{S=await n(`${e}${cy}`,{method:"POST",headers:{"content-type":"application/json",[$o]:t.appId,[Ko]:t.appKey,...cp({signingKey:u,method:"POST",pathWithQuery:cy,body:X,now:i})},body:X})}catch(te){throw new Sn("network",x("network",te instanceof Error?te.message:String(te)),{cause:te})}let w=await S.json().catch(()=>null);if(!S.ok){let te=my(w),re=py(w),M=Dw(S.headers.get("retry-after"),i()),k=S.status===429?"rate_limited":S.status>=500?"unavailable":"rejected";throw new Sn(k,x(String(S.status),te),{status:S.status,...M!==void 0?{retryAfterMs:M}:{},code:te,...re!==void 0?{detail:re}:{}})}let T=typeof w=="object"&&w!==null?w:{};if(typeof T.token!="string"||T.token==="")throw new Sn("unavailable",x(String(S.status),"malformed_response"),{status:S.status});let _=typeof T.expiresAt=="string"&&!Number.isNaN(Date.parse(T.expiresAt))?Date.parse(T.expiresAt):i()+s*1e3,G=Math.max(0,_-i()),V=i()+G*(1-o()*d);return g.set(N,{token:T.token,expiresAtMs:V}),m.delete(N),T.token},B=async N=>{let X;try{X=await h.acquire()}catch(S){let w=S instanceof _r?S.reason:"queue_full",T=new Sn("saturated",x("saturated",w),{retryAfterMs:ly});throw A(N,T),T}try{let S=R(N);return S!==void 0&&S.expiresAtMs-i()>a?S.token:await C(N)}catch(S){let w=S instanceof Sn?S:new Sn("network",x("network",S instanceof Error?S.message:String(S)),{cause:S});A(N,w);let T=R(N);if(T!==void 0)return b.staleServed+=1,T.token;throw w}finally{X()}},Y=N=>{let X=R(N);if(X!==void 0&&X.expiresAtMs-i()>a)return b.hits+=1,Promise.resolve(X.token);let S=m.peek(N);if(S!==void 0&&S.until>i())return b.negativeHits+=1,X!==void 0?(b.staleServed+=1,Promise.resolve(X.token)):Promise.reject(new Sn(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 w=v.get(N);if(w!==void 0)return w;let T=B(N).finally(()=>v.delete(N));return v.set(N,T),T};return{tokenFor:Y,invalidate:(N,X={})=>{let S=g.peek(N);if(S===void 0||X.token!==void 0&&S.token!==X.token)return!1;g.delete(N);let w=X.reason??fy;return b.invalidations[w]=(b.invalidations[w]??0)+1,!0},async warm(N){let X={minted:0,cached:0,failed:0},S=await Promise.allSettled([...N].map(async w=>{let T=R(w),_=T!==void 0&&T.expiresAtMs-i()>a;return await Y(w),_}));for(let w of S)w.status==="rejected"?X.failed+=1:w.value?X.cached+=1:X.minted+=1;return X},stats(){let N=h.stats();return{inflight:N.active,queued:N.queued,mints:b.mints,hits:b.hits,negativeHits:b.negativeHits,staleServed:b.staleServed,failures:{...b.failures},cached:g.size,evicted:g.stats().evicted,invalidations:{...b.invalidations}}}}}function Uw(t){if(t===void 0)return n=>{console.warn(`[tansr-serve] platform warning ${n.code} (endUser=${n.endUserId}): ${n.message}`)};let e=Nn(t);return n=>{e("warn",at.platformWarning,{endUserId:n.endUserId,sessionId:n.sessionId,code:n.code,message:n.message})}}function Fw(t){if(t.bundleCache!==void 0)return t.bundleCache;let e=t.bundleCacheTtlMs??wi;if(!(e<=0))return Qi({ttlMs:e,...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{},...t.now!==void 0?{now:t.now}:{}})}function hy(t){return yy(t)}function gy(t,e){return yy(t,e)}function yy(t,e){let n=new Za({ttlMs:Ow,maxEntries:Bw,...t.now!==void 0?{now:t.now}:{}}),i=Uw(t.logger),o=t.onPlatformWarning??(c=>{let l=`${c.endUserId}\0${c.code}`;n.has(l)||(n.add(l),i(c))}),s=Fw(t),a=Ln(t.metrics),d=t.fetchImpl??fetch;return async c=>{let l=await t.minter.tokenFor(c.endUserId),f=c.platformSessionId??Oi(),u=(async(w,T)=>{let _=await t.minter.tokenFor(c.endUserId),G=M=>{let k=new Headers(T?.headers??(w instanceof Request?w.headers:void 0));return k.set(Dn,M),d(w,{...T,headers:k})},V=await G(_);if(V.status!==401)return V;let te=await jw(V);if(te===void 0||(a.tokenInvalidations.inc({reason:te.reason}),t.minter.invalidate===void 0)||(t.minter.invalidate(c.endUserId,{token:_,reason:te.reason}),!Nw(w,T)))return V;let re;try{re=await t.minter.tokenFor(c.endUserId)}catch{return V}return re===_?V:G(re)}),p=e?.gatewayCache?.({endUserId:c.endUserId,sessionId:c.sessionId}),h=await Ia({token:l,baseUrl:t.apiBaseUrl,...c.model!==void 0?{model:c.model}:{},fetchImpl:u,sessionId:()=>f,onSessionArchived:w=>{if(w!==void 0&&w!==f)return;s?.invalidate();let T=f,_=p===void 0?void 0:e?.archivedRuntime?.({endUserId:c.endUserId,sessionId:c.sessionId,previous:T});if(p!==void 0&&_===void 0)throw new _t("session_archived",void 0,410);f=c.onSessionArchived?.(T,_)??_??Oi();let G={code:"platform_session_archived",message:`platform session "${T}" 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,...G}),c.onWarning?.(G)},...s!==void 0?{bundleCache:s}:{},...t.appId!==void 0?{appId:t.appId}:{},onWarn:w=>{o({endUserId:c.endUserId,sessionId:c.sessionId,code:w.code,message:w.message}),c.onWarning?.({code:w.code,message:w.message})}},p===void 0?{}:{gatewayCache:p}),g=xa(h),m=Ta({baseUrl:t.apiBaseUrl,token:l,fetchImpl:u,initial:{...h.systemPrompt!==void 0?{systemPrompt:h.systemPrompt}:{},...h.systemPromptPolicy!==void 0?{systemPromptPolicy:h.systemPromptPolicy}:{}}},g&&e?.refreshCacheConfiguration?{initial:g,refreshRequired:()=>e.cacheConfigurationRefreshRequired?.({endUserId:c.endUserId,sessionId:c.sessionId})??!1,confirmConfiguration:w=>e.confirmCacheConfiguration?.({endUserId:c.endUserId,sessionId:c.sessionId},w),refreshConfiguration:w=>e.refreshCacheConfiguration({endUserId:c.endUserId,sessionId:c.sessionId},w)}:void 0),v,b,x=async(w,T)=>{w.throwIfAborted();let _=(V,te)=>u(V,{...te,cache:"no-cache",headers:{...Object.fromEntries(new Headers(te?.headers)),"cache-control":"no-cache"},signal:te?.signal?AbortSignal.any([te.signal,w]):w}),G=await Yn(t.apiBaseUrl.replace(/\/+$/,""),l,_,T,void 0,!0);return w.throwIfAborted(),G},R=async w=>{let T=await x(w,b);if(T.bundle!==null&&(v=T.bundle.capabilities),b=T.etag??b,v===void 0)throw new Error("Application capabilities are unconfirmed");return v},A,C,B=async w=>{let T=await x(w,C);if(T.bundle!==null){let _=T.bundle.models.map(({handle:te,displayName:re,manufacturer:M,family:k,adapterDiagnostics:j})=>({handle:te,displayName:re,manufacturer:M,family:k,...j===void 0?{}:{adapterDiagnostics:structuredClone(j)}})),G=new Set(_.map(te=>te.handle)),V=Object.fromEntries(Object.entries(T.bundle.aliases).flatMap(([te,re])=>{let M=G.has(re)?re:re.startsWith("tansr/")?re.slice(6):void 0;return M!==void 0&&G.has(M)?[[te,M]]:[]}));A={models:_,aliases:V,capabilities:T.bundle.capabilities},C=T.etag}else C=T.etag??C;if(A===void 0)throw new Error("Platform catalog is unconfirmed");return structuredClone(A)},Y=async w=>{w.throwIfAborted();let T=await u(`${t.apiBaseUrl.replace(/\/+$/,"")}/v1/my-usage?window=1d`,{method:"GET",headers:{accept:"application/json","cache-control":"no-cache"},cache:"no-cache",signal:w});if(w.throwIfAborted(),!T.ok)throw T.body?.cancel().catch(()=>{}),new Error("Platform usage is unavailable");let{bytes:_,truncated:G}=await Bm(T,Iw,w);if(G)throw new Error("Platform usage response exceeded the size limit");let V;try{V=JSON.parse(new TextDecoder().decode(_))}catch{throw new Error("Platform usage is unconfirmed")}let te=Vc.safeParse(V);if(w.throwIfAborted(),!te.success||te.data.endUserId!==c.endUserId||te.data.window!=="1d")throw new Error("Platform usage is unconfirmed");return te.data},ne;h.pricingUpdates.length>0&&(ne=Bc(),ne.refreshPricing(h.pricingUpdates,"refreshed"));let N=h.adjudicator,X=w=>{o({endUserId:c.endUserId,sessionId:c.sessionId,...w}),!Uu.has(w.code)&&c.onWarning?.(w)},S=wm(h.contextScheme,w=>o({endUserId:c.endUserId,sessionId:c.sessionId,code:Sm,message:`${w.reason}: ${w.detail}`}));return(w,T)=>{let _=xr(h.registry,w,T);return{client:_.client,model:_.model,..._.contextWindowTokens!==void 0?{contextWindowTokens:_.contextWindowTokens}:{},..._.maxOutputTokens!==void 0?{maxOutputTokens:_.maxOutputTokens}:{},...ne!==void 0?{pricing:ne}:{},...S!==void 0?{compactionManagerOptions:S}:{},...h.governance.sessionRetentionDays!==void 0?{sessionRetentionDays:h.governance.sessionRetentionDays}:{},resolveSubagentModel:(G,V)=>{try{let te=h.registry.resolveAlias(G);return{provider:te.providerId,model:te.modelName}}catch{return V}},capabilities:h.capabilities,...h.systemPrompt!==void 0?{systemPrompt:h.systemPrompt}:{},...h.systemPromptPolicy!==void 0?{systemPromptPolicy:h.systemPromptPolicy}:{},refreshApplicationPrompt:m,refreshApplicationCapabilities:R,readPlatformCatalog:B,readPlatformUsage:Y,platform:h.platform,platformTools:{baseUrl:t.apiBaseUrl,fetchImpl:u,platformModels:h.platformModels},onAdjudicationWarning:X,...N!==null?{assembleAdjudicator:G=>Jc({registry:h.registry,mainModel:_.model,adjudicator:N,app:{...h.app,endUser:c.endUserId},posture:G.posture,...G.postureExplicit!==void 0?{postureExplicit:G.postureExplicit}:{},pricing:h.pricingUpdates,...G.callBudget!==void 0?{callBudget:G.callBudget}:{},onWarn:X})}:{}}}}}function Mr(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 td(t){return async e=>{try{return await t(e)}catch(n){throw Fu(n)}}}var Lw=new Set(["plan_concurrency_exceeded","plan_end_users_exceeded"]),zw=new Set(["plan_required","plan_tier_insufficient"]),Hw=3e4;function Fu(t){if(!(t instanceof Sn))return t;let e=t.retryAfterMs!==void 0?{retryAfterMs:t.retryAfterMs}:{};if(t.code!==void 0&&Lw.has(t.code))return new Xe("plan_limited",t.message,{retryAfterMs:t.retryAfterMs??Hw,params:{code:t.code},...t.detail!==void 0?{detail:t.detail}:{}});if(t.code!==void 0&&zw.has(t.code))return new Xe("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 Xe("upstream_unavailable",t.message,e);case"saturated":return new Xe("overloaded",t.message,e);case"rejected":return t}}import{randomUUID as Gw}from"node:crypto";function vy(t,e,n){if(t.destroyed||t.writableEnded)return;let i=Bd(n);t.writeHead(e,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":i.length}),t.end(i)}async function by(t){if(t.headers["content-type"]?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new _t("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 _t("payload_too_large",void 0,413);e.push(o)}try{return qd(Buffer.concat(e))}catch{throw new _t("invalid_request",void 0,400)}}function Lu(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 _t("invalid_request",void 0,400);if(e.some(o=>!i.has(o))||i.get("protocol")!==Lc)throw new _t("invalid_request",void 0,400);return i}function Sy(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 _t("capacity_exceeded",void 0,503);e++,d=!0;let l;try{l=await t.authenticate(n,i)}catch(v){if(v instanceof Pt)throw new _t("capacity_exceeded",void 0,503,"same-request");l=null}if(n.aborted||i.destroyed||i.writableEnded)return;if(!l||!l.endUserId)throw new _t("unauthorized",void 0,401);if(!(await t.admission.rateLimit(n,l.endUserId)).admitted)throw new _t("capacity_exceeded",void 0,429);if(s==="POST"){let v=ri(n,65536);if(!t.admission.reserveBody(v).admitted)throw new _t("capacity_exceeded",void 0,503);a=v}let u=l.endUserId,p=new URL(n.url??"/","http://serve.invalid"),h=o.slice(14),g,m=/^\/core\/v1\/bindings\/([A-Za-z0-9][A-Za-z0-9._~-]{0,127})\/diagnostics$/.exec(h);if(s==="GET"&&m){let v=p.searchParams;if([...v.keys()].some(x=>!["protocol","limit","after"].includes(x)||v.getAll(x).length!==1)||v.get("protocol")!=="sdk2-cache-core-v1")throw new _t("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 _t("invalid_request",void 0,400);g=await t.link.coreDiagnostics(u,m[1],v.get("after"),Number(b))}else if(s==="GET"&&h==="/capabilities"){if(p.search)throw new _t("invalid_request",void 0,400);g=await t.link.capabilities(u)}else if(s==="POST"&&h==="/bindings"){if(p.search)throw new _t("invalid_request",void 0,400);g=await t.link.execute(u,"open",await by(n))}else if(s==="GET"&&h==="/operations"){let v=Lu(p,["protocol","operation","operationEpoch","requestId"],["bindingId"]),b=v.get("operation");if(b!=="open"&&b!=="renew"&&b!=="rebind"&&b!=="rotate"&&b!=="close")throw new _t("invalid_request",void 0,400);g=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(h);if(!v)throw new _t("mapping_unavailable",void 0,404);let b=v[1],x=v[2];if(s==="GET"&&x===void 0)Lu(p,["protocol"]),g=await t.link.read(u,b);else if(s==="GET"&&x==="diagnostics"){let R=Lu(p,["protocol"],["after","limit"]),A=R.get("limit")??"100";if(!/^[1-9][0-9]{0,2}$/.test(A)||Number(A)>100)throw new _t("invalid_request",void 0,400);g=await t.link.diagnostics(u,b,R.get("after"),Number(A))}else if(s==="POST"&&(x==="renew"||x==="rebind"||x==="rotate"||x==="close")){if(p.search)throw new _t("invalid_request",void 0,400);let R=await by(n);if(!R||typeof R!="object"||R.bindingId!==b)throw new _t("invalid_request",void 0,400);g=await t.link.execute(u,x,R)}else throw new _t("invalid_request",void 0,400)}vy(i,200,g)})().catch(l=>{if(i.destroyed||i.writableEnded)return;let f=l instanceof _t,u=f?l.status??503:l instanceof Cd?400:503,p=f?l.code:l instanceof Cd?"invalid_request":"result_unknown",h={protocol:Lc,requestId:Gw(),code:p,status:u,retryAction:f?l.retryAction:p==="result_unknown"?"query-status":"none",fallback:"none",message:p},g=lp.safeParse(h);(u===429||u===503)&&i.setHeader("retry-after","5"),vy(i,g.success?u:503,g.success?g.data:{...h,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 Ww}from"node:util";var Vw=new Set(["receive","confirm","pending","head","coverage","identity","operation","records","body-chunk","sync-page","retention","retention-page","apply-retention","reconcile"]),$w=new Set(["head","coverage","identity","records","body-chunk","sync-page","retention","retention-page"]),Kw=new Set(["invalid_input","identity_mismatch","integrity_mismatch","capacity_exceeded","pending_ack","receipt_mismatch","context_changed","reentrant","closed","storage_error","reconciliation_required"]),zu=class extends Error{constructor(n){super(n);this.code=n}code};function bt(t,e="invalid_input"){if(!t)throw new zu(e)}function Hu(t,e){let n=0,i=0,o=new Set,s=d=>(i+=Buffer.byteLength(d),bt(i<=e,"capacity_exceeded"),d),a=(d,c)=>{if(bt(c<=32&&++n<=1e5),d===null||typeof d=="boolean")return s(String(d));if(typeof d=="number")return bt(Number.isSafeInteger(d)&&d>=0&&!Object.is(d,-0)),s(String(d));if(typeof d=="string")return bt(Buffer.from(d).toString("utf8")===d),s(JSON.stringify(d));bt(d&&typeof d=="object"&&!Ww.isProxy(d)&&!o.has(d)),o.add(d);try{let l=Object.getOwnPropertyDescriptors(d);if(Array.isArray(d)){let p=l.length?.value;bt(Number.isSafeInteger(p)&&p<=1e5&&Reflect.ownKeys(l).length===p+1);let h=[s("[")];for(let g=0;g<p;g++){let m=l[g];bt(m&&Object.hasOwn(m,"value")&&m.enumerable),g&&h.push(s(",")),h.push(a(m.value,c+1))}return h.push(s("]")),h.join("")}bt(Object.getPrototypeOf(d)===Object.prototype||Object.getPrototypeOf(d)===null);let f=Reflect.ownKeys(l);bt(f.every(p=>typeof p=="string"&&/^[\x21-\x7e]+$/.test(p)));let u=[s("{")];for(let[p,h]of f.sort().entries()){let g=l[h];bt(Object.hasOwn(g,"value")&&g.enumerable),p&&u.push(s(",")),u.push(s(JSON.stringify(h)+":"),a(g.value,c+1))}return u.push(s("}")),u.join("")}finally{o.delete(d)}};return Buffer.from(a(t,0))}function Qw(t,e){let n=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t),i=JSON.parse(n);return bt(Hu(i,e).equals(t)),i}function nd(t,e){return JSON.parse(Hu(t,e).toString("utf8"))}function wy(t,e,n){if(t.destroyed||t.writableEnded)return;let i=Hu(n,1638400);t.writeHead(e,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":i.length}),t.end(i)}function ky(t){bt(/^[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()=>{bt(e<32&&!t.admission.overloaded(),"capacity_exceeded"),e++,s=!0,bt(n.method==="POST"&&/^\/v3\/sdk2\/archive-sync\/[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(o)),bt(n.headers["content-type"]?.split(";")[0]==="application/json");let u=o.slice(22),p=await t.authenticate(n,i);bt(p?.endUserId,"context_changed"),bt((await t.admission.rateLimit(n,p.endUserId)).admitted,"capacity_exceeded");let h=t.host.resolve(p.endUserId,u),g=h?null:t.host.resolveReadOnly?.(p.endUserId,u),m=h??g?.binding;bt(m,"identity_mismatch"),c=nd(m.identity,65536);let v=g?nd(g.grant,65536):null;v&&(xn(v,["actor","owner","grantRevision"]),xn(v.actor,["applicationScopeId","endUserId","authorizationRevision"]),xn(v.owner,["scope","bindingId","target","sourceId","sourceGeneration"]),xn(v.owner.target,["sessionId","generations"]),xn(v.owner.target.generations,["historyEpoch","deletionGeneration","projectionRevision"]),bt(v.actor.endUserId===p.endUserId&&v.actor.applicationScopeId===t.host.applicationScopeId&&/^[0-9]{1,19}$/.test(v.actor.authorizationRevision)&&/^[0-9]{1,19}$/.test(v.grantRevision)&&fe(v.owner)===fe(c),"identity_mismatch")),bt(m.identity.bindingId===u&&(v!==null||m.identity.scope.endUserId===p.endUserId)&&m.identity.scope.applicationScopeId===t.host.applicationScopeId,"identity_mismatch"),bt(Number.isSafeInteger(m.maxRequestBytes)&&m.maxRequestBytes>0&&m.maxRequestBytes<=94371840),bt(Number.isSafeInteger(m.maxResponseBytes)&&m.maxResponseBytes>0&&m.maxResponseBytes<=1572864),d=m.maxRequestBytes+65536,bt(t.admission.reserveBody(d).admitted,"capacity_exceeded"),a=!0;let b=async()=>{let C=await t.authenticate(n,i),B=v?t.host.resolveReadOnly?.(p.endUserId,u):null;bt(!n.aborted&&!i.destroyed&&C?.endUserId===p.endUserId&&(v?B?.binding===m&&fe(nd(B.grant,65536))===fe(v):t.host.resolve(p.endUserId,u)===m)&&fe(m.identity)===fe(c),"context_changed")};await b();let x=await mi(n,d,C=>Qw(C,d));bt(x.ok,x.ok===!1&&x.reason==="too_large"?"capacity_exceeded":"invalid_input");let R=xn(x.value,["format","identity","method","value"]);bt(R.format==="archive-sync-v1"&&fe(R.identity)===fe(c),"identity_mismatch"),bt(typeof R.method=="string"&&Vw.has(R.method)),l=R.method,bt(!v||$w.has(l),"context_changed"),await b();let A=await m.dispatch(l,R.value);await b(),wy(i,200,{format:"archive-sync-v1",identity:c,method:l,value:nd(A,m.maxResponseBytes)})})().catch(u=>{let p=u&&typeof u=="object"?Object.getOwnPropertyDescriptor(u,"code"):void 0,h=typeof p?.value=="string"&&Kw.has(p.value)?p.value:"storage_error";wy(i,h==="context_changed"||h==="identity_mismatch"?403:h==="capacity_exceeded"?429:h==="invalid_input"?400:409,{format:"archive-sync-v1",identity:c,method:l,error:{code:h}})}).finally(()=>{s&&e--,a&&t.admission.releaseBody(d)});return t.track(f),!0}}import{randomUUID as Bk}from"node:crypto";import{createHash as Jw}from"node:crypto";import{types as Yw}from"node:util";var aB=Object.freeze(["session","execution","archive","archive-sync","cache","terminal","terminal-observation","terminal-profile"]),Xw=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"}),Te=(t,e,n,i,o=null)=>Object.freeze({name:t,domain:e,kind:n,lifecycle:i,requires:o}),rt=Xw,Zw=Object.freeze([Te("session.create","session","write","independent"),Te("session.list","session","read","independent"),Te("session.get","session","read","session"),Te("session.close","session","write","session"),Te("session.message.send","session","write","session"),Te("session.events.observe","session","stream","session"),Te("session.interrupt","session","write","session"),Te("session.history.read","session","read","session"),Te("session.tool.result","session","write","session"),Te("session.permission.decide","session","write","session"),Te("session.question.answer","session","write","session"),Te("session.compact","session","write","session"),Te("session.checkpoint.list","session","read","session"),Te("session.checkpoint.create","session","write","session"),Te("session.checkpoint.import","session","write","session"),Te("session.checkpoint.restore","session","write","session"),Te("session.checkpoint.export","session","read","session"),Te("session.checkpoint.delete","session","write","session"),Te("session.cwd.set","session","write","session"),Te("session.audio.transcribe","session","write","session",rt.audioTranscribe),Te("session.audio.speak","session","write","session",rt.audioSpeak),Te("session.input.capabilities","session","read","session"),Te("session.input.submit","session","write","session",rt.inputAccepts),Te("session.input.status","session","read","session"),Te("execution.initialize","execution","write","session"),Te("execution.capabilities","execution","read","session"),Te("execution.boundary","execution","read","session"),Te("execution.binding.create","execution","write","session",rt.executionBoundDevice),Te("execution.status","execution","read","session"),Te("executor.register","execution","write","independent"),Te("executor.heartbeat","execution","write","independent"),Te("executor.operations.poll","execution","read","independent"),Te("executor.receipt.submit","execution","write","independent"),Te("archive.capabilities","archive","read","independent"),Te("archive.binding.target","archive","read","independent"),Te("archive.binding.create","archive","write","independent"),Te("archive.binding.get","archive","read","independent"),Te("archive.binding.close","archive","write","independent"),Te("archive.status","archive","read","independent",rt.archiveTransfer),Te("archive.events.observe","archive","stream","independent"),Te("archive.records.read","archive","read","independent",rt.archiveTransfer),Te("archive.artifact.read","archive","read","independent",rt.archiveTransfer),Te("archive.ack.commit","archive","write","independent",rt.archiveTransfer),Te("archive.ack.rebase","archive","write","independent",rt.archiveTransfer),Te("archive.operation.query","archive","read","independent"),Te("archive.sync","archive-sync","write","independent"),Te("material.response.submit","archive","write","independent",rt.archiveMaterials),Te("material.status","archive","read","independent",rt.archiveMaterials),Te("material.upload.status","archive","read","independent",rt.archiveMaterials),Te("material.upload.chunk","archive","write","independent",rt.archiveMaterials),Te("cache.capabilities","cache","read","independent"),Te("cache.binding.open","cache","write","independent",rt.cacheFeature),Te("cache.binding.get","cache","read","independent",rt.cacheFeature),Te("cache.binding.renew","cache","write","independent",rt.cacheFeature),Te("cache.binding.rebind","cache","write","independent",rt.cacheFeature),Te("cache.binding.rotate","cache","write","independent",rt.cacheFeature),Te("cache.binding.close","cache","write","independent",rt.cacheFeature),Te("cache.operation.query","cache","read","independent",rt.cacheFeature),Te("cache.diagnostics","cache","read","independent",rt.cacheFeature),Te("cache.core.diagnostics","cache","read","independent",rt.cacheFeature),Te("terminal.capabilities","terminal","read","independent"),Te("terminal.binding.create","terminal","write","session"),Te("terminal.executor.events.observe","terminal","stream","independent",rt.terminalStream),Te("terminal.output.batch","terminal","write","session",rt.terminalStream),Te("terminal.execution.state","terminal","read","session",rt.terminalStream),Te("terminal.output.observe","terminal","stream","session",rt.terminalStream),Te("terminal.output.status","terminal","read","session",rt.terminalStream),Te("terminal.configuration.read","terminal","read","session",rt.terminalConfiguration),Te("terminal.configuration.commit","terminal","write","session",rt.terminalConfiguration),Te("terminal.memory.read","terminal","read","session",rt.terminalMemory),Te("terminal.memory.command","terminal","write","session",rt.terminalMemory),Te("terminal.memory.receipt","terminal","read","session",rt.terminalMemory),Te("terminal.observation.resources","terminal-observation","read","session"),Te("terminal.observation.correlations","terminal-observation","read","session"),Te("terminal.profile.catalog","terminal-profile","read","session"),Te("terminal.profile.usage","terminal-profile","read","session")]),ek="tansr.unified.closure.v1";var tk=t=>t!==null&&(t.state==="ended"||t.state==="closing");function nk(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 ik(t){let e=new Set,n=new Set;t.input!==null&&t.input.accepts.some(s=>lk.includes(s))&&n.add(rt.inputAccepts),t.audio?.speechToText===!0&&n.add(rt.audioTranscribe),t.audio?.textToSpeech===!0&&n.add(rt.audioSpeak);let i=new Set;t.execution?.effectiveTools.some(s=>s.executionKind==="bound-device"&&s.available)===!0&&i.add(rt.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 rk(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 ok(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"&&tk(e.session)||t.domain==="archive"&&e.archive!==null&&e.archive.epochId===null)?"disabled":"enabled"}var sk=262144,ak=t=>new Uint8Array(Jw("sha256").update(t).digest());function dk(t){let e=Mf({authorizationRevision:t.authorizationRevision,domains:t.domains,operations:t.operations},{maxBytes:sk,isProxy:Yw.isProxy});return Bf(Of(ek,e,ak))}function xy(t){let e=nk(t),n=ik(t),i=rk(t),o={};for(let a of Zw)o[a.name]=ok(a,t,e,n);let s=t.authorizationRevision;return{contract:Fn,closureId:dk({authorizationRevision:s,domains:i,operations:o}),authorizationRevision:s,domains:i,operations:o}}function Ry(t,e){return t===void 0||t===e.closureId?{ok:!0}:{ok:!1,code:"closure_stale",status:412,retryAction:"rediscover",closureId:e.closureId}}function ck(t){return t.supported?t.installed?t.authorization!=="allowed"||t.device==="unavailable"||t.device==="unconfirmed"?"unconfirmed":"installed":"supported":"unconfirmed"}function Iy(t){let e={};for(let n of t)e[n.feature]=ck(n);return e}var lk=["text","textBlocks","image"];function Ty(t){let e=["text","textBlocks","image"];return{version:t.version,accepts:e.filter(n=>t[n]===!0)}}import{randomUUID as fk}from"node:crypto";var id={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 rd={"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"}},Ay={"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 uk=Object.keys(rd);function Cy(t){return Object.hasOwn(rd,t)}function sd(t,e){let n=rd[t];return Object.hasOwn(n,e)?n[e]??null:null}function Ey(t){let e=new Set;for(let n of uk){let i=sd(n,t);i!==null&&e.add(i)}return e.size===1?[...e][0]??null:null}function od(t,e){let n=Ay[t];return Object.hasOwn(n,e)?n[e]??null:null}function Gu(t,e,n){let i=n??null,o=sd(t,e);if(o===null)return{code:"internal_error",status:500,retryAction:(i===null?null:od(t,i))??"none",domainCode:e,domainRetryAction:i};let s=id[o],a=i===null?null:od(t,i);return{code:o,status:s.status,retryAction:a??s.retryAction,domainCode:e,domainRetryAction:i}}function mk(t){let e=Li[t];return Cy(e)?e:t==="terminal-observation"||t==="terminal-profile"?"terminal-services-v1":null}var pk={invalid_request:[400,422],conflict:[409,412],gap:[409,410],capability_unavailable:[404,403],capacity_exceeded:[429,503]};function _y(t,e,n){let i=pk[t];return i!==void 0&&i.includes(n)?n:e}function hk(t,e,n,i){if(sd(t,e)!==null){let a=Gu(t,e,n);return{code:a.code,status:_y(a.code,a.status,i),retryAction:a.retryAction}}let o=Ey(e);if(o!==null){let a=id[o],d=n===null?null:od(t,n);return{code:o,status:_y(o,a.status,i),retryAction:d??a.retryAction}}let s=Gu(t,e,n);return{code:s.code,status:i,retryAction:s.retryAction}}function ad(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gk(t){if(!ad(t)||t.contract===Fn)return null;let e=t.error;return ad(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:ad(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 yk=/\/v[123](?:\/\S*)?(?!\S)/g;function vk(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:Zl(o)??t;return{path:i,text:o=>o.replace(yk,s=>i(s))}}var bk=new Set(["domainCode","domainStatus","domainRetryAction","fallback","retryAfterMs"]);function Sk(t){let e=gk(t.body);if(e===null)return null;let n=vk(t.apiPathname,t.legacyPathname),i=hk(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))bk.has(s)||(o[s]=s==="path"&&typeof a=="string"?n.path(a):a);return{contract:Fn,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 wk=/^application\/json(?:\s*;.*)?$/i,Py=1024*1024;function kk(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 xk(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:kk(i)}}function My(t){if(t!==void 0)return Array.isArray(t)?t.length>0?String(t[0]):void 0:String(t)}function Rk(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 Oy(t,e,n){let i=mk(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=[],p=0,h=R=>{if(R.status<400)return!1;let C=My(R.headers["content-type"])??My(e.getHeader("content-type"));return C!==void 0&&wk.test(C)},g=(R,A,C)=>{R.statusMessage===void 0?a.call(e,A,C):a.call(e,A,R.statusMessage,C)},m=(R,A)=>{let C=f;l="passthrough";let B=Buffer.concat(u);u.length=0,!e.destroyed&&(g(C,C.status,C.headers),R?c.call(e,B,A):d.call(e,B,A))},v=(R,A)=>{let C=f,B;try{B=JSON.parse(Buffer.concat(u).toString("utf8"))}catch{return R?(m(!0,A),!0):!1}let Y=ad(B)?Sk({family:i,status:C.status,body:B,apiPathname:o,legacyPathname:s,traceId:yr(t)?.requestId??fk()}):null;if(Y===null)return R?(m(!0,A),!0):!1;l="passthrough",u.length=0;let ne=Buffer.from(JSON.stringify(Y),"utf8"),N={...C.headers,"content-length":ne.length};return Y.status===401&&N["www-authenticate"]===void 0&&e.getHeader("www-authenticate")===void 0&&(N["www-authenticate"]="Bearer"),e.destroyed||(g(C,Y.status,N),R?c.call(e,ne,A):d.call(e,ne,A)),!0},b=(R,A)=>{let C=Rk(R,A);C!==null&&(u.push(C),p+=C.length)},x=()=>{let R={status:e.statusCode,statusMessage:void 0,headers:{}};h(R)?(l="buffering",f=R):l="passthrough"};e.writeHead=function(...A){if(l==="passthrough")return a.apply(this,A);let C=xk(A);return l==="buffering"?(f=C,this):h(C)?(l="buffering",f=C,this):(l="passthrough",a.apply(this,A))},e.write=function(A,C,B){if(l==="idle"&&x(),l!=="buffering")return d.call(this,A,C,B);let Y=typeof C=="function"?C:B;return b(A,C),p>Py?(m(!1,Y),!0):(!v(!1,Y)&&typeof Y=="function"&&process.nextTick(Y),!0)},e.end=function(A,C,B){if(l==="idle"&&x(),l!=="buffering")return c.call(this,A,C,B);let Y=[A,C,B].find(ne=>typeof ne=="function");return typeof A!="function"&&b(A,C),p>Py?m(!0,Y):v(!0,Y),this}}var jo="tansr-event-envelope",ld="unified-v1",bB=Object.freeze(["contract","eventId","domain","type","cursorSet","terminalStatus","raw"]);function Ik(t){let e=t.headers[jo],n=Array.isArray(e)?e.length===1?e[0]:void 0:e;return e===void 0?"absent":n===ld?"unified-v1":"invalid"}var By=Object.freeze({eventCursor:null,archiveCoverage:null,outputWatermark:null,materialConsumed:null,ackReceipt:null});function Do(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function dd(t){return typeof t=="string"?t:null}function Tk(t,e,n,i){let o=i===null?By:{...By,eventCursor:i},s=null,a=Do(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&&Do(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:dd(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"&&Do(n.block)?o={...o,outputWatermark:dd(n.block.seq)}:e==="output.status"&&Do(n.status)&&n.status.state==="complete"&&(s="completed");break;default:break}return{cursorSet:o,terminalStatus:s}}var cd=10,Dy=13;function Ak(t){let e=[],n=0;for(let i=0;i<t.length;i+=1){let o=t.charCodeAt(i);if(o===cd)e.push({text:t.slice(n,i),eol:`
|
|
24
|
+
`}),n=i+1;else if(o===Dy){let s=t.charCodeAt(i+1)===cd;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 Ck(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 Ek(t,e){let n=Ak(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 x=Ck(b.text);x!=="comment"&&(x.field==="data"?(s.add(v),a.push(x.value)):x.field==="event"?i=x.value:x.field==="id"&&!x.value.includes("\0")&&(o=x.value))}if(s.size===0)return t;let d=a.join(`
|
|
26
|
+
`),c;try{c=JSON.parse(d)}catch{return t}if(!Do(c))return t;let l=i??dd(c.type)??dd(c.eventType),f=o??null,u=Tk(e,l,c,f),p=`{"contract":${JSON.stringify(Fn)},"eventId":${JSON.stringify(f)},"domain":${JSON.stringify(e)},"type":${JSON.stringify(l)},"cursorSet":${JSON.stringify(u.cursorSet)},"terminalStatus":${JSON.stringify(u.terminalStatus)},"raw":${d}}`,h=Math.min(...s),g=n[h].eol===""?`
|
|
27
|
+
`:n[h].eol,m="";for(let v=0;v<n.length;v+=1){let b=n[v];if(v===h)for(let x of p.split(`
|
|
28
|
+
`))m+=`data: ${x}${g}`;else s.has(v)||(m+=b.text+b.eol)}return Buffer.from(m,"utf8")}var _k=1<<20,Or=Buffer.alloc(0),Wu=class{#e;#n;#r=Or;#s=0;#t=0;#o=!1;constructor(e){this.#e=e.domain,this.#n=e.maxCarryBytes??_k}get carryBytes(){return this.#r.length}push(e){if(e.length===0)return Or;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===cd)l=a+1;else if(c===Dy){if(a+1>=n.length)break;l=n[a+1]===cd?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:Ek(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)):Or,this.#s=s-o-l,this.#t=0}else this.#r=d.length===0?Or:Buffer.from(d),this.#s=s-o,this.#t=a-o;return i.length===0?Or:i.length===1?i[0]:Buffer.concat(i)}flush(){let e=this.#r;return this.#r=Or,this.#s=0,this.#t=0,this.#o=!1,e}};function qy(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 Pk(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 Mk(t){return t!==void 0&&/^\s*text\/event-stream(?:\s*;|\s*$)/i.test(t)}function Ok(t,e){let n=t.writeHead,i=t.write,o=t.end,s=!1,a,d=c=>{s||t.headersSent||(s=!0,Mk(Pk(t,c))&&(t.setHeader(jo,ld),a=new Wu({domain:e})))};t.writeHead=function(...l){return d(l),n.apply(this,l)},t.write=function(l,f,u){s||d([]);let p=i;if(a===void 0)return p.call(this,l,f,u);let h=typeof f=="string"?f:void 0,g=typeof f=="function"?f:u,m=qy(l,h);if(m===void 0)return p.call(this,l,f,u);let v=a.push(m);return v.length===0?(g!==void 0&&process.nextTick(g),!this.writableNeedDrain):g===void 0?p.call(this,v):p.call(this,v,g)},t.end=function(l,f,u){s||d([]);let p=o;if(a===void 0)return p.call(this,l,f,u);let h=typeof l=="function"?void 0:l,g=typeof l=="function"?l:typeof f=="function"?f:u,m=typeof f=="string"?f:void 0,v=[];if(h!=null){let x=qy(h,m);if(x===void 0)return p.call(this,l,f,u);v.push(a.push(x))}v.push(a.flush()),a=void 0;let b=Buffer.concat(v);return b.length===0?g===void 0?p.call(this):p.call(this,g):g===void 0?p.call(this,b):p.call(this,b,g)}}function jy(t,e,n){let i=Ik(t);return i==="unified-v1"&&Ok(e,n),i}var Ii={format:"tansr-api-manifest-v1",contract:"unified-v1",revision:6,schemaHash:"19cafed0f01d3fdb8b8aac695980db30dec43bbd1729824d8c5bc8644a84b4b1",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}],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}]},{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}]},{id:"archive-sync-v1",domains:["archive-sync"],status:"additive",rfc:"doc/rfc/SDK2-档案同步与保留扩展.md",source:"packages/server/src/sdk2/archive-sync.ts",sha256:"fac68e8ba9540c6511f677d23ef0d18c32c2eb91b5157556ae3e2869e7f4e533",golden:{},generated:[],legacyEntries:["/v3/sdk2/archive-sync/:bindingId"],apiEntries:["/api/archive/sync/:bindingId"],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}]},{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:"hand-written",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}]},{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:"hand-written",observed:"2026-10-01",drift:!1}]},{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}]},{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}]},{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}]},{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}]},{id:"unified-v1",domains:["discovery"],status:"candidate",rfc:"doc/rfc/RFC-UAPI-1-统一信封与canonical单模块.md",source:"doc/rfc/unified-v1.schema.json",sha256:"a2449bc121b5183e50b0c2432d29042446659ec8b32b355af7f204c6cb684a8e",golden:{"doc/rfc/unified-v1.golden.json":"7c6baad1e7053d57249c19b4c0aeda014a812c98662ec94878e0ec0d1dda0773"},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}]}],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"},{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)"},{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)"},{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"},{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 同端点"},{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"},{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},{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"},{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"},{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"},{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 }"},{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"},{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 }"},{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,旧模板占位为 :targetId"},{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,旧模板占位为 :targetId"},{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},{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},{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},{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"},{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},{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'},{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 无体"},{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},{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"},{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"},{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"},{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"},{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"},{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},{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},{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},{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},{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"},{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"},{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},{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},{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},{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},{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},{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"},{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},{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},{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},{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 续订(独立重放日志 / 游标)"},{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},{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"},{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},{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},{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"},{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:null,response:null,query:[],notes:'体 { format: "archive-sync-v1", identity, method, value };method 词表见 sdk2/archive-sync.ts;无 schema 文件(UAPI-03 补);:id = bindingId'},{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"},{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"},{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"},{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"},{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},{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},{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},{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},{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},{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},{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},{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"},{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},{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"},{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},{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},{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 游标"},{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"},{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"},{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"},{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},{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},{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},{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},{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},{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"},{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},{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},{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},{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}],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}]};var Vu="tansr-session-family",Br="tansr-closure-id",qk=/^\/api\/sessions\/([^/]+)\/capabilities$/,Dk=/^\/api\/sessions\/([^/]+)(?:\/|$)/,jk=Ii.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 Nk(t,e){return jk.find(n=>n.method===t&&n.pattern.test(e))?.name}var Uk={unauthorized:401,not_found:404,method_not_allowed:405,invalid_request:400,capability_unavailable:404,capacity_exceeded:503,precondition_failed:412,upstream_unavailable:503},Fk={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 Uy(t){return Ii.families.find(e=>e.id===t)}function Fy(t){if(t==="discovery")return`sha256:${Ii.schemaHash}`;let e=Uy(Li[t]);return e===void 0?"none":`sha256:${e.sha256}`}function ud(t,e){t.setHeader("tansr-contract",Fn),t.setHeader("tansr-manifest-revision",String(Ii.revision)),t.setHeader("tansr-domain",e),t.setHeader("tansr-schema-hash",Fy(e))}function Lk(t){return yr(t)?.requestId??Bk()}function $u(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 wn(t,e,n,i,o={},s={}){let a=s.status??Uk[n];$u(e,a,{contract:Fn,traceId:Lk(t),requestId:null,code:n,status:a,retryAction:Fk[n],message:i,...s.detail!==void 0?{detail:s.detail}:{}},o)}function Ny(t){return t.headers["transfer-encoding"]!==void 0||t.headers["content-length"]!==void 0&&t.headers["content-length"]!=="0"}function Ly(t){let{authenticate:e,delegate:n,installed:i,track:o,sessionFamilies:s}=t,a=()=>{let R=t.retryAfterMs?.()??5e3;return{"retry-after":String(Math.max(1,Math.ceil(R/1e3)))}},d=async(R,A)=>{let C;try{C=await e(R,A)}catch(B){if(A.destroyed||A.writableEnded)return null;if(B instanceof Pt)return wn(R,A,"capacity_exceeded","authentication source unavailable",a()),null;C=null}return R.aborted||A.destroyed||A.writableEnded?null:C===null||typeof C.endUserId!="string"||C.endUserId===""?(wn(R,A,"unauthorized","authentication required",{"www-authenticate":"Bearer"}),null):C.endUserId},c=()=>{let R={};for(let A of Object.keys(Li)){let C=Uy(Li[A]),B=i[A];R[A]={installed:A==="session"?B!==null:B===!0,...A==="session"?{family:{preferred:B,available:s}}:{},contract:Li[A],status:C?.status??"unregistered",schemaHash:Fy(A)}}return{contract:Fn,manifestRevision:Ii.revision,schemaHash:`sha256:${Ii.schemaHash}`,domains:R}},l=R=>{let A=R.headers[Vu],C=Array.isArray(A)?A[0]:A;return C===void 0?{family:i.session}:C!=="sdk1"&&C!=="sdk2-offload-v1"?{family:null,error:"invalid"}:s.includes(C)?{family:C}:{family:null,error:"not_installed"}},f=()=>({...Ii,runtime:{installed:i}}),u=async(R,A,C,B)=>{if(B!=="GET"){if(await d(R,A)===null)return;wn(R,A,"method_not_allowed",`${B} not allowed`,{allow:"GET"});return}if((R.url??"").includes("?")||Ny(R)){if(await d(R,A)===null)return;wn(R,A,"invalid_request","discovery endpoints accept no query string or body");return}await d(R,A)!==null&&$u(A,200,C===sa?f():c())},p=async(R,A,C,B,Y)=>{await d(R,A)!==null&&wn(R,A,C,B,{},Y===void 0?{}:{detail:Y})},h=R=>R==="session"?i.session!==null:i[R]===!0,g=async(R,A,C,B)=>{if(t.sessionClosure===void 0||i.session===null){wn(R,A,"capability_unavailable","session capability closure is not installed on this serve",{},{detail:{reason:"not_installed"}});return}let Y;try{Y=decodeURIComponent(C)}catch{wn(R,A,"not_found","no such api resource");return}let ne;try{ne=await t.sessionClosure(Y,B,R)}catch{if(A.destroyed||A.writableEnded)return;wn(R,A,"upstream_unavailable","capability closure source unavailable",a());return}if(!(R.aborted||A.destroyed||A.writableEnded)){if(ne===null){wn(R,A,"not_found","no such api resource");return}return ne}},m=async(R,A,C,B)=>{let Y=await d(R,A);if(Y===null)return;if(B!=="GET"){wn(R,A,"method_not_allowed",`${B} not allowed`,{allow:"GET"});return}if((R.url??"").includes("?")||Ny(R)){wn(R,A,"invalid_request","capabilities accept no query string or body");return}let ne=await g(R,A,C,Y);ne!==void 0&&$u(A,200,ne,{[Br]:ne.closureId})},v=(R,A,C,B)=>{if(jy(R,A,C.domain)==="invalid"){o(p(R,A,"invalid_request",`${jo} must be ${ld}`,{header:jo}));return}Oy(R,A,C);let Y=R.url??"",ne=Y.indexOf("?");R.url=ne<0?C.legacyPathname:`${C.legacyPathname}${Y.slice(ne)}`,!n(R,A,C.legacyPathname,B)&&o(p(R,A,"capability_unavailable",`${C.domain} does not serve this resource`,{reason:"not_installed"}))},b=async(R,A,C,B,Y,ne,N)=>{let X=await d(R,A);if(X===null)return;let S=await g(R,A,ne,X);if(S===void 0)return;let w=Ry(N,S);if(!w.ok){wn(R,A,"precondition_failed","capability closure is stale; rediscover before retrying",{[Br]:w.closureId},{detail:{domainCode:w.code,closureId:w.closureId}});return}let T=Nk(Y,B),_=T===void 0?void 0:S.operations[T];if(_==="disabled"||_==="unavailable"){wn(R,A,"capability_unavailable",`${T} is ${_} for this session`,{[Br]:S.closureId},{status:_==="disabled"?403:404,detail:{reason:"outside_closure",operation:T,state:_,closureId:S.closureId}});return}v(R,A,C,Y)},x=R=>{let A=R.headers[Br];return Array.isArray(A)?A[0]:A};return(R,A,C,B)=>{if(C!=="/api"&&!C.startsWith("/api/"))return!1;if(C===sa||C===Xl)return ud(A,"discovery"),o(u(R,A,C,B)),!0;let Y=qk.exec(C);if(Y!==null)return ud(A,"discovery"),o(m(R,A,Y[1],B)),!0;let ne=l(R),N=Rh(C,{offloadSessions:ne.family==="sdk2-offload-v1"});if(N===void 0)return ud(A,"discovery"),o(p(R,A,"not_found","no such api resource")),!0;if(ud(A,N.domain),!h(N.domain))return o(p(R,A,"capability_unavailable",`${N.domain} is not installed on this serve`,{reason:"not_installed"})),!0;if((N.domain==="session"||N.domain==="execution")&&ne.error!==void 0)return o(ne.error==="invalid"?p(R,A,"invalid_request",`${Vu} must be sdk1 or sdk2-offload-v1`):p(R,A,"capability_unavailable","requested session family is not installed on this serve",{reason:"not_installed",header:Vu})),!0;let X=x(R);if(X!==void 0){let S=Dk.exec(C);return S===null||B==="GET"||B==="HEAD"?(o(p(R,A,"invalid_request",`${Br} applies to session-scoped write operations only`,{header:Br})),!0):(o(b(R,A,N,C,B,S[1],X)),!0)}return v(R,A,N,B),!0}}var zk=5e3;async function Ku(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 Hk(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 Gk(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 zy(t){let{registry:e,installed:n}=t,i=t.timeoutMs??zk,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=qi(l),u=AbortSignal.timeout(i),p=null,h=null;if(t.execution!==void 0&&n.execution){let B=await Ku(t.execution.options.readPolicy(a,u),u,i);if(B.expiresAt!==void 0&&(!Number.isSafeInteger(B.expiresAt)||B.expiresAt<=o()))throw new Error("policy source expired");p=B.authorizationRevision;try{let Y=t.execution.session(a,s).executionBoundary();h={boundaryRevision:Y.revision,effectiveTools:Y.effectiveTools}}catch{h=null}}let g=null;if(t.archive?.capabilities!==void 0&&n.archive){let B=await Ku(t.archive.capabilities(a),u,i);g={epochId:B.operationEpoch.id,capabilities:B.capabilities}}let m=null;if(t.terminal!==void 0&&n.terminal)try{let B=t.terminal.sessionFeatures(a,{sessionContract:f,sessionId:s});m={schemaRevision:t.terminal.capabilities().schemaRevision,features:Iy(B)}}catch{m=null}let v=l.inputCapabilities?.(),b=v===void 0?null:Ty(v),x=l.platformAudio,R=x===void 0?null:{speechToText:x.capabilities.speechToText===!0,textToSpeech:x.capabilities.textToSpeech===!0},A=null;t.cache!==void 0&&n.cache&&(A=Gk(await Ku(t.cache.capabilities(a),u,i)));let C=e.get(s);return C===void 0||C.handle!==l?null:xy({installed:n,authorizationRevision:p,session:{family:f,state:Hk(C)},execution:h,archive:g,terminal:m,input:b,audio:R,cache:A})}}import{lstatSync as Qu,realpathSync as Hy}from"node:fs";import Kt from"node:path";var Gy=new WeakMap;function fd(t,e){Gy.set(t,e)}function nr(t){return Gy.get(t)}var Wy=new WeakMap;function qr(t,e){Wy.set(t,e)}function Cn(t){return Wy.get(t)}var Ju=new WeakMap;function Vy(t,e){if(Ju.has(t))throw new Error("Memory command runner already bound");Ju.set(t,e)}function $y(t){return Ju.get(t)}function Ky(t){let e=t,n=Yu(t),i=t.config.management;if(!i||!t.config.host||Au(t.config.host)===void 0)return n;let o=!1,s=!1,a=!1,d,c,l,f,u=new sr,p=()=>l||(l=(async()=>{if(s)throw new ct("source_unavailable");try{await n.verifyAvailable()}catch(v){if(!(v instanceof ct)||v.code!=="stale_generation")throw v;let b=e.config.host,x=Au(b),R=await i.read();if(x===void 0||BigInt(R.deletionGeneration)<=BigInt(x))throw v;if(a&&d===n||!(await n.settleResources({timeoutMs:0})).every(C=>C.status==="completed"))throw new ct("busy");let A=await i.createHost({rootDir:b.rootDir,memoryDir:b.memoryDir,...b.provenance===void 0?{}:{provenance:b.provenance}});if(await A.refresh(),s||!e.config.enabled())throw new ct("source_unavailable");if(a&&d===n)throw new ct("busy");if(await n.retireDeletedSource(),s||!e.config.enabled())throw new ct("source_unavailable");A.assertCurrent(),e={...e,config:{...e.config,host:A}},n=Yu(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),h={...n.searchTool,execute:async(m,v)=>(await p(),n.searchTool.execute(m,v))},g=async m=>{let v=performance.now(),b=m?.timeoutMs??3e4,x=()=>({...m,timeoutMs:Math.max(0,b-(performance.now()-v))}),R=[];for(;;){let A=await u.settle(x()),C=n,Y=[...await C.settleResources(x()),A];if(C===n&&l===void 0||Y.some(ne=>ne.status!=="completed"))return[...R,...Y];R.push(...Y.filter(ne=>ne.failureCount>0))}};return{searchTool:h,management:i,assertAvailable:()=>n.assertAvailable(),verifyAvailable:p,executeManagedCommand:async(m,v)=>(await p(),n.executeManagedCommand(m,v)),status:()=>n.status(),start:()=>{o=!0,n.start()},prepare:async m=>{await p();let v=n,b=await v.prepare(m);return d=v,b},onTurnStart:m=>{a=!0,d===n?n.onTurnStart(m):c=[...m]},onTurnEnd:m=>{a=!1,d=void 0,c=void 0,n.onTurnEnd(m)},noteBalanceLow:()=>n.noteBalanceLow(),observeTouched:m=>n.observeTouched(m),compactionObserver:{onCompactionFinished:m=>n.compactionObserver.onCompactionFinished?.(m)},prepareReminders:async m=>{await p(),await n.prepareReminders(m)},drainReminders:()=>n.drainReminders(),drainSelections:()=>n.drainSelections(),pin:async m=>(await p(),n.pin(m)),remember:()=>n.remember(),rememberAndWait:async()=>{await p(),await n.rememberAndWait()},readyForModelChange:async()=>!s&&(await g({timeoutMs:0})).every(m=>m.status==="completed"),close:()=>f??=(async()=>{s=!0,await l?.catch(()=>{}),await n.close()})(),settleResources:g}}function Yu(t){let e=t.config;if(!["server-managed","client-managed","developer-managed"].includes(e.kind)||!e.domain.trim()||!Kt.isAbsolute(e.rootDir)||!Kt.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=Kt.resolve(e.rootDir),i=Kt.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=O=>process.platform==="win32"?O.toLowerCase():O,s=(O,J)=>o(J)===o(O)||o(J).startsWith(o(O+Kt.sep));if(!s(n,i)||o(n)===o(i)||e.host===void 0&&(o(Hy(n))!==o(n)||!Qu(n).isDirectory()))throw new TypeError("Memory domain requires an explicit real root and child directory");let a=[e.projectAgentsPath,e.userAgentsPath].filter(O=>O!==void 0);if(a.some(O=>!Kt.isAbsolute(O)||!s(n,Kt.resolve(O))||s(i,Kt.resolve(O))))throw new TypeError("Promotion targets must be explicit paths within the trusted root, outside auto-memory");let d=!1,c=!1,l,f=new sr,u=new Set,p=()=>{if(c||!e.enabled())throw new Error("Memory source unavailable");e.host?.assertCurrent()},h=async()=>{p(),await e.host?.refresh(),p()},g=O=>a.some(J=>o(Kt.resolve(J))===o(O)),m=(O,J=!1)=>{if(p(),!Kt.isAbsolute(O))throw new Error("Memory path must be absolute");let ke=Kt.resolve(O);if(!(s(i,ke)||g(ke)||J&&s(n,ke)&&(s(ke,i)||a.some(ze=>s(ke,Kt.resolve(ze))))))throw new Error("Memory path outside trusted domain");if(e.host!==void 0)return ke;let qe=n;for(let ze of Kt.relative(n,ke).split(Kt.sep).filter(Boolean)){qe=Kt.join(qe,ze);try{if(Qu(qe).isSymbolicLink())throw new Error("Memory links are not permitted")}catch(He){if(He.code!=="ENOENT")throw He}}if(o(Hy(n))!==o(n))throw new Error("Memory root changed");return ke};if(m(i,!0),e.host===void 0&&!Qu(i).isDirectory())throw new TypeError("Memory directory must already exist");let v=e.host?.fs??Ef,b={...v.compareAndWrite===void 0?{}:{compareAndWrite:async(O,J,ke)=>v.compareAndWrite(m(O),J,ke)},stat:async O=>v.stat(m(O,!0)),lstat:async O=>v.lstat(m(O,!0)),realpath:async O=>v.realpath(m(O,!0)),readFile:async O=>v.readFile(m(O)),readFilePrefix:async(O,J)=>v.readFilePrefix(m(O),J),...v.readFileRange===void 0?{}:{readFileRange:async(O,J,ke)=>v.readFileRange(m(O),J,ke)},writeFile:async(O,J)=>v.writeFile(m(O),J),appendFile:async(O,J)=>v.appendFile(m(O),J),mkdir:async(O,J)=>v.mkdir(m(O,!0),J),readdir:async O=>{let J=await v.readdir(m(O,!0));if(J.length>500||J.some(ke=>ke.isSymbolicLink()))throw new Error("Memory directory cannot be admitted");return J}},x={...e.host?.source,pathStyle:process.platform==="win32"?"win32":"posix",fs:b},R=e.host?.extractionHost??sp(i),A=e.host?.consolidationHost??ap(i),C=O=>{m(Kt.join(i,O)),m(Kt.join(i,"lock"))},B=new Ur({homedir:n,memoryWriteCarveOut:{dirs:[i]}}),Y=new qn;for(let O of[xc,Hr,Gr])Y.register({...O,execute:async(J,ke)=>{let we=J&&typeof J=="object"?J.file_path:void 0;if(typeof we!="string")return{isError:!0,content:[{t:"text",text:"A memory file path is required."}]};try{return m(we),await O.execute(J,{...ke,fs:b,cwd:n})}catch{return{isError:!0,content:[{t:"text",text:"Memory access denied or unavailable."}]}}}});let ne=Si(B,Y,{cwd:n}),N={decide:async(O,J)=>{try{p();let ke=O.args&&typeof O.args=="object"?O.args.file_path:void 0;if(typeof ke!="string")throw new Error("Missing path");return m(ke),g(Kt.resolve(ke))&&["Write","Edit"].includes(O.name)?{decision:"ask",source:"policy",reason:"Memory promotion requires approval"}:await ne.decide(O,J)}catch{return{decision:"deny",source:"policy",reason:"Memory source unavailable or outside scope"}}}},X=()=>{p();let O=t.modelTier(),J=O.client;return{...O,client:On({async*stream(ke,we){await h(),yield*J.stream(ke,we)}},J)}},S=(O,J)=>{try{e.onObservation?.(O,J)}catch{}},w=Y.names().map(O=>fn(Y.get(O))),T={memoryDir:i,cwd:n,modelTier:X,registry:Y,tools:w,permissionGate:N,...t.budget===void 0?{}:{budget:t.budget},onUsage:t.onUsage,...t.onDecision?{onDecision:t.onDecision}:{},...t.requestMeasurement?{requestMeasurement:t.requestMeasurement}:{}},_=Ym({...T,interactive:!0,sessionId:()=>t.sessionId,balance:e.balance,...e.extraction,host:{pendingInvitesLocation:R.pendingInvitesLocation,readInitialPendingInvites:()=>(C("pending-invites.json"),R.readInitialPendingInvites()),persistPendingInvites:async(O,J)=>{C("pending-invites.json"),await R.persistPendingInvites(O,J)},acquireLock:async O=>(C("lock"),R.acquireLock(O)),readIndexSnapshot:async O=>(C("MEMORY.md"),R.readIndexSnapshot(O))},writePlanePreflight:Jm(B,i,n),probeWrite:O=>S("write.extract",O),probeInvite:O=>S("invite",O),probeExtraction:O=>S("extraction",O),notifySaved:O=>S("saved",{count:O})}),G=Xm({...T,interactive:!0,sessionId:t.sessionId,balance:e.balance,system:t.system,host:{acquireLock:async O=>(C("lock"),A.acquireLock(O)),readConsolidationMeta:async()=>(C("consolidation.json"),A.readConsolidationMeta()),writeConsolidationMeta:async O=>{C("consolidation.json"),await A.writeConsolidationMeta(O)},readPendingAnchors:async()=>(C("pending-anchors.md"),A.readPendingAnchors()),clearPendingAnchors:async O=>{C("pending-anchors.md"),await A.clearPendingAnchors(O)}},probeWrite:O=>S("write.consolidate",O),notifyConsolidated:O=>S("consolidated",{count:O})}),V=!1,te=e.projectAgentsPath!==void 0&&e.userAgentsPath!==void 0&&t.askUser!==void 0?Zm({...T,sessionId:t.sessionId,system:t.system,history:t.history,projectAgentsPath:e.projectAgentsPath,userAgentsPath:e.userAgentsPath,askUser:t.askUser,notifyReport:O=>S("promotion.report",{text:O}),probePromotion:O=>S("promotion",O),onOutcome:O=>{V=O.kind==="completed"}}):void 0,re=ms({dir:i,roots:[n],source:x}),M=e.recallSelector?ps({dir:i,source:x,...t.budget===void 0?{}:{budget:t.budget},onBudgetWarning:O=>S("budget.warning",{reason:O}),excludeFiles:["pending-anchors.md"],modelTier:X,onUsage:(O,J)=>t.onUsage({model:J.model,provider:J.provider,usage:O})}):void 0,k=km({forceEngine:"js"}),j={source:"local",async search(O,J){p();let ke=xm(),we=[];if(O.kind!==void 0&&O.kind!=="memory")return{hits:we};for await(let qe of k.search({root:i,pattern:Rm(O.query),caseInsensitive:!0,collectLines:!0,contextLines:2,glob:"*.md"},{signal:J,stats:ke,fs:b})){if(p(),["pending-anchors.md","quarantine.md"].includes(Kt.basename(qe.abs)))continue;let ze=qe.lines.slice(0,30);if(we.push({kind:"memory",key:qe.rel,title:qe.rel,occurredAt:"",lineStart:ze[0]?.line??1,lineEnd:ze.at(-1)?.line??1,score:1,text:ze.map(He=>He.text).join(`
|
|
29
|
+
`).slice(0,4096)}),we.length>=O.limit)break}return{hits:we,truncated:ke.limitHit||we.length>=O.limit}}},W=Im({projectKey:e.domain,searcher:j,enabled:()=>!c&&e.enabled()});W.description="Search the authorized memory source. Returns bounded memory snippets from the configured domain only; never falls back to host files.";let q=new Gf,Q=()=>{if(p(),d)throw new Error("Memory is closing")},U=()=>{if(Q(),!te)throw new Error("Memory promotion requires explicit targets and approval bridge");if(te.promotionInFlight())throw new Error("Memory busy");V=!1,te.run()},ue=O=>{let J=(async()=>{Q(),C("lock");let ke=await R.acquireLock({staleMs:6e5});if(!ke)throw new Error("Memory busy");try{return Q(),await O()}finally{let we=ke.release();f.track(we,"tool_executor"),await we}})();return f.track(J,"tool_executor",{reportFailure:!1}),J},pe=async O=>(await Promise.all([f.settle(O),_.settleResources(O),G.settleResources(O),te?.settleResources(O),re.settleResources?.(O),M?.settleResources?.(O)])).filter(ke=>ke!==void 0),oe=(O=!1)=>l??=(async()=>{d=!0,await Promise.all([...u].map(ke=>ke.close())),await f.settle({timeoutMs:1/0}),!O&&e.enabled()&&_.handleSessionClose(),await Promise.all([_.drain(),G.drain(),te?.drain()]),re.dispose?.(),M?.dispose();let J=await pe({timeoutMs:1/0});if(c=!0,J.some(ke=>ke.status!=="completed"))throw new Error("Memory cleanup did not complete")})();return{searchTool:W,assertAvailable:p,verifyAvailable:h,...e.management===void 0?{}:{management:e.management},executeManagedCommand:(O,J)=>{let ke=(async()=>{if(Q(),e.management===void 0||e.host===void 0)throw new Error("Memory management is not configured");let we=[],qe=await e.management.execute(O,async ze=>{Q(),J?.signal?.throwIfAborted();let He=Yu({...t,config:{...e,host:ze,rootDir:ze.rootDir,memoryDir:ze.memoryDir,onObservation:(Ot,Fe)=>we.push({kind:Ot,value:Fe})}});u.add(He);let ht=()=>{f.track(He.close(),"tool_executor")};J?.signal?.addEventListener("abort",ht,{once:!0});try{J?.signal?.throwIfAborted(),O.command.kind==="pin"?await He.pin(O.command.text):O.command.kind==="remember"&&await He.rememberAndWait(),J?.signal?.throwIfAborted()}finally{try{await He.close()}finally{J?.signal?.removeEventListener("abort",ht),u.delete(He)}}},{rootDir:n,memoryDir:i,...e.host.provenance===void 0?{}:{provenance:e.host.provenance}},{...J?.signal===void 0?{}:{signal:J.signal},beforeCommit:async()=>{Q(),await J?.beforeCommit?.(),Q()}});if(qe.status==="committed"){re.invalidate?.({dir:i,roots:[n],source:x}),M?.invalidateSource({dir:i,source:x});for(let ze of we)S(ze.kind,ze.value)}return S("management",{operationId:O.operationId,status:qe.status,durable:qe.durable}),qe})();return f.track(ke,"tool_executor",{reportFailure:!1}),ke},status:()=>({kind:e.kind,domain:e.domain,enabled:!c&&e.enabled(),extractionInFlight:_.extractionInFlight(),consolidationInFlight:G.consolidationInFlight(),promotionInFlight:te?.promotionInFlight()??!1,closing:d}),start:()=>{p(),G.start()},prepare:async O=>{p(),O.throwIfAborted(),await h();let J=await Zf(i,{source:x,signal:O});return p(),[{text:Xf,cacheable:!0},...J.content===null?[]:[{text:`${Yf}
|
|
30
|
+
|
|
31
|
+
${J.content}`,cacheable:!1}]]},onTurnStart:O=>{_.noteTurnStart(),e.enabled()&&M?.prefetch(O.join(`
|
|
32
|
+
`))},onTurnEnd:O=>{!e.enabled()||d||(_.noteInviteParse(ep(tp(O.history)),O.turn),_.handleTurnEnd(O))},noteBalanceLow:()=>{_.noteBalanceLow(),G.noteBalanceLow()},observeTouched:O=>{e.enabled()&&re.observeTouched(O)},compactionObserver:{onCompactionFinished:O=>{O.agentId===void 0&&O.mechanism===void 0&&O.outcome?.ok===!0&&_.noteCompactionSummary(O.outcome.summaryText)}},prepareReminders:async O=>{p(),await re.prepareReminders?.(O)},drainReminders:()=>e.enabled()?re.drainReminderEntries?.()??[]:[],drainSelections:()=>e.enabled()?M?.drainReminderEntries?.()??[]:[],pin:async O=>ue(async()=>{if(nm(O).length>0)throw new Error("Memory pin contains protected secret material");let J=q.pin(O,0,ke=>ke.length);if(!J)throw new Error("Invalid memory pin");return C("pending-anchors.md"),{added:e.host===void 0?await rp(i,[J.entry]):await e.host.appendPendingAnchors([J.entry])}}),remember:U,rememberAndWait:async()=>{U();let O=await te.settleResources({timeoutMs:1/0});if(p(),O.status!=="completed"||!V)throw new Error("Memory promotion did not complete")},readyForModelChange:async()=>!d&&(await pe({timeoutMs:0})).every(O=>O.status==="completed"),close:()=>oe(),retireDeletedSource:()=>oe(!0),settleResources:pe}}var Ti=Object.freeze(["execution-stream-v1","execution-background-v1","memory-lifecycle-v1","session-configuration-v1"]),Ai=Object.freeze({maxControlBytes:262144,maxBlockBytes:16384,maxBatchBytes:65536,maxPendingBytes:2097152,maxRetainedBytes:8388608}),je=class extends Error{constructor(n){super(n);this.code=n;this.name="TerminalCapabilityError"}code};function Gn(t){throw new je(t)}function Xu(t,e){try{return vt(t,e)}catch{return Gn("invalid_request")}}function Wk(t){let e=new Set(t.map(n=>n.feature));return(e.size!==Ti.length||Ti.some(n=>!e.has(n))||t.some(n=>n.installed&&!n.supported))&&Gn("invalid_request"),t}function Vk(t){(t.maxBlockBytes>t.maxBatchBytes||t.maxBatchBytes>t.maxPendingBytes||t.maxBatchBytes>t.maxRetainedBytes)&&Gn("invalid_request")}function No(t){let e=Xu("CapabilitiesResponse",{...t,contract:"terminal-services-v1",schemaRevision:rg,schemaSha256:ig});return Wk(e.features),Vk(e.limits),e}function md(t,e){let n=Xu("BindingRequest",t),i=No({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)&&Gn("invalid_request"),fe(n.session)!==fe(e.session)&&Gn("not_found"),fe(n.executionBinding)!==fe(e.executionBinding)&&Gn("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)&&Gn("unsupported_capability"),a.push(c);continue}c.authorization==="denied"&&Gn("forbidden"),(c.authorization==="unconfirmed"||c.device==="unconfirmed")&&Gn("capability_unconfirmed"),c.device==="unavailable"&&Gn("source_unavailable"),(d==="execution-stream-v1"||d==="execution-background-v1")&&e.executionBinding===null&&Gn("stale_generation"),s.push(d)}return Xu("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 Qy}from"node:crypto";var Jy=9223372036854775807n,$k=65536,Yy=8*1024*1024,Xy=4096,Uo=class extends Error{constructor(n){super(n);this.code=n;this.name="TerminalOutputError"}code};function cn(t){throw new Uo(t)}function Zu(t,e){try{return vt(t,e)}catch{return cn("invalid_request")}}function Kk(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 Qk(t,e){return t.lastSeq===e.lastSeq&&t.totalBytes===e.totalBytes&&t.payloadDigest===e.payloadDigest&&t.truncated===e.truncated}var pd=class{#e;#n;#r;#s=new Map;#t=new Map;#o=0;#i=0n;#a=0n;#c=Qy("sha256");#d=null;#f=!1;constructor(e,n={}){let i=Zu("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??Yy,this.#r=n.maxRetainedBlocks??Xy,(!Number.isSafeInteger(this.#n)||this.#n<1||this.#n>Yy||!Number.isSafeInteger(this.#r)||this.#r<1||this.#r>Xy)&&cn("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=Zu("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)&&cn("binding_conflict"),n.blocks.reduce((p,h)=>p+h.byteLength,0)>$k&&cn("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 p of n.blocks){let h=Buffer.from(p.base64,"base64");(h.toString("base64")!==p.base64||h.length!==p.byteLength||Qy("sha256").update(h).digest("hex")!==p.payloadDigest)&&cn("integrity_mismatch");let g=BigInt(p.seq);if(g<d){let b=o.get(g);b||cn("output_gap"),Kk(b,p)||cn("revision_conflict");continue}f&&cn("revision_conflict"),g!==d&&cn("output_gap"),BigInt(p.byteOffset)!==c&&cn("integrity_mismatch");let m=s.get(p.channel);m!==void 0&&m!==p.encoding&&cn("revision_conflict"),s.set(p.channel,p.encoding);let v=c+BigInt(h.length);(d>Jy||v>Jy)&&cn("capacity_exceeded"),a.update(h),o.set(g,Object.freeze({...p})),d++,c=v,l+=h.length}for(n.seal&&(f?Qk(f,n.seal)||cn("revision_conflict"):((n.seal.lastSeq!==(d?String(d-1n):null)||n.seal.totalBytes!==String(c)||n.seal.payloadDigest!==a.copy().digest("hex"))&&cn("integrity_mismatch"),f=Object.freeze({...n.seal})));o.size>this.#r||l>this.#n;){let p=o.entries().next().value;o.delete(p[0]),l-=p[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(Zu("Sequence",e));(n>=this.#i||n+1n<(this.#s.keys().next().value??this.#i))&&cn("output_gap");let i=Object.freeze([...this.#s].filter(([o])=>o>n).map(([,o])=>o));return Object.freeze({blocks:i,status:this.status()})}};function Wn(t,e){return fe(t)===fe(e)}function hd(t){let e=t.request;if(e.operation==="process.exec")return e.args.maxOutputBytes;try{let n=Sr(e);return n.action==="exec"?n.maxOutputBytes:void 0}catch{return}}function tt(t){throw new je(t)}function En(t,e){try{return vt(t,e)}catch{return tt("invalid_request")}}function _n(t,e){let n=t??e;return(!Number.isSafeInteger(n)||n<1)&&tt("invalid_request"),n}function Fo(t,e){return JSON.stringify([t,e.sessionContract,e.sessionId])}function gd(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 Lo(t){let e=t?.code;return["forbidden","stale_generation","source_unavailable","capacity_exceeded","binding_conflict","output_gap"].includes(e??"")?e:"source_unavailable"}var yd=class{#e;#n;#r=new Map;#s=new WeakSet;#t=new Map;#o=new Set;#i;#a;#c;#d;#f;#p;#m;#w;#v;#k;#y;#B;#C;#H=0;#S=0;#g=0n;#N=!1;constructor(e){this.#e=e.host,this.#n=e,this.#a=_n(e.maxBindings,256),this.#c=_n(e.maxOperations,256),this.#d=_n(e.maxOperationsPerSession,64),this.#f=_n(e.maxSubscriptions,64),this.#p=_n(e.maxSubscriptionsPerSession,8),this.#m=_n(e.maxSubscriptionsPerExecutor,8),this.#w=_n(e.maxRetainedBytes,64*1048576),this.#v=_n(e.maxRetainedBlocks,16384),this.#k=_n(e.maxRetainedBytesPerSession,Math.min(this.#w,16*1048576)),this.#y=_n(e.maxRetainedBlocksPerSession,Math.min(this.#v,8192)),this.#B=_n(e.maxRetainedBytesPerOperation,Ai.maxRetainedBytes),this.#C=_n(e.retentionMs,3e5),(this.#B>Ai.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.#D(n))}capabilities(){return No({sessionContracts:this.#n.sessionContracts,limits:Ai,features:this.#J("unconfirmed","unconfirmed")})}#J(e,n){return Ti.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=En("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}#E(e,n,i=!0,o=!0){this.#U();let s=this.#r.get(Fo(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||!Wn(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}#q(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=En("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=md(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:Ai}),f=Fo(e,l.session),u=this.#r.get(f);return!u&&this.#r.size>=this.#a&&tt("capacity_exceeded"),u&&(!Wn(u.response.scope,l.scope)||!Wn(u.response.executionBinding,l.executionBinding)||!Wn(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:En("BindingResponse",l),session:a}),this.#e.options.shellSandbox===!0&&!this.#s.has(a)&&(a.attachShellOutputReader((p,h)=>this.readCompletedOutput(e,l.session,p,h)),this.#s.add(a)),En("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=En("SessionReference",i);let d=En("OperationReference",o),c=await this.#j(e,i,s),l=this.#E(e,i,a,a);this.#q(n,l);let f=await c.readOperation(d.operationId);return s.throwIfAborted(),this.#E(e,i,a,a),this.#q(n,l),(f.digest!==d.requestDigest||!Wn(f.binding,l.response.executionBinding)||!Wn(f.scope,l.response.scope))&&tt("stale_generation"),a&&hd(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.#E(e,c.binding.response.session,!1,!1),(!Wn(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([Fo(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,p=new Promise((m,v)=>{f=m,u=v}),h=()=>u(new je("source_unavailable"));d.addEventListener("abort",h,{once:!0}),p.catch(()=>{});let g=()=>{try{d.throwIfAborted();let m=this.#E(e,n),v=this.#t.get(this.#u(m,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 x=hd(i);(x===void 0||!b.seal||b.seal.truncated||BigInt(b.seal.totalBytes)>BigInt(x))&&tt("integrity_mismatch");let R=v.window.observe(null).blocks,A=[],C=[];for(let N of R)(N.channel==="stdout"?A:C).push(Buffer.from(N.base64,"base64"));let B=Buffer.concat(A),Y=Buffer.concat(C);BigInt(B.length+Y.length)!==BigInt(b.seal.totalBytes)&&tt("integrity_mismatch");let ne=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});f({stdout:ne.decode(B),stderr:ne.decode(Y)})}catch(m){u(m)}};try{let m=await this.#I(e,{controller:!0},n,s,d);Wn(m.operation,i)||tt("integrity_mismatch"),l=await this.subscribeOutput(e,{controller:!0},n,s,null,{event:b=>{b.type==="output.status"&&g()},close:b=>u(new je(b))},d),g();let v=await p;return await this.#I(e,{controller:!0},n,s,d),v}finally{clearTimeout(c),l?.close(),d.removeEventListener("abort",h),a.abort()}}async readOutputCorrelations(e,n,i,o,s=new AbortController().signal){let a=En("SessionReference",i);o!==void 0&&En("LegacyId",o);let d=await this.#j(e,a,s),c=this.#E(e,a);return this.#q(n,c),d.readOutputCorrelations(o).filter(l=>Wn(l.binding,c.response.executionBinding)).map(l=>En("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=En("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=hd(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 p=u.window.receive(s),h=p.retainedFrom===null?p.acceptedThrough:p.retainedFrom==="0"?null:String(BigInt(p.retainedFrom)-1n),g=u.window.observe(h).blocks;this.#H-=u.retainedBytes,this.#S-=u.retainedBlocks,u.retainedBytes=g.reduce((b,x)=>b+x.byteLength,0),u.retainedBlocks=g.length,this.#H+=u.retainedBytes,this.#S+=u.retainedBlocks,u.status=p,this.#t.delete(f),this.#t.set(f,u);let m=0,v=0;for(let b of this.#t.values())b.bindingKey===u.bindingKey&&(m+=b.retainedBytes,v+=b.retainedBlocks);for(let[b,x]of this.#t){if(m<=this.#k&&v<=this.#y)break;b!==f&&x.bindingKey===u.bindingKey&&x.window&&(m-=x.retainedBytes,v-=x.retainedBlocks,this.#_(x))}for(let[b,x]of this.#t){if(this.#H<=this.#w&&this.#S<=this.#v)break;b!==f&&x.window&&this.#_(x)}(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??gd({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&&En("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??gd({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.#H-=e.retainedBytes,this.#S-=e.retainedBlocks,e.retainedBytes=0,e.retainedBlocks=0,e.window=null,e.status=gd(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(hd(n)===void 0||!Wn(n.binding,e.response.executionBinding)||!Wn(n.scope,e.response.scope))return;let i=this.#u(e,n.operationId);if(this.#t.has(i))return;this.#T();let o=Fo(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 pd({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.#C})}#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,Lo(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{}}#F(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.#q(n,s)}}catch(s){throw this.#V(e,Lo(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.#E(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.#q(e.authority,a)}s.throwIfAborted(),e.closed&&tt("source_unavailable"),this.#F(e)};return e.checking||(e.checking=o().catch(s=>{throw this.#V(e,Lo(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.#m||e.bindingKey&&[...this.#o].filter(n=>n.bindingKey===e.bindingKey).length>=this.#p)&&tt("capacity_exceeded"),this.#o.add(e),e.signal.addEventListener("abort",e.abort,{once:!0}),e.signal.aborted?e.abort():this.#F(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&&En("Sequence",s),this.#T();let f=l.response.executionBinding.target,u={kind:"output",user:e,authority:{...n},executorId:f.executorId,connectionId:f.connectionId,bindingKey:Fo(e,i),reference:Object.freeze({...o}),afterSeq:s,listener:a,signal:d,stop:new AbortController,closed:!1,abort:()=>this.#V(u)},p=this.#ee(u),h=this.#t.get(this.#u(l,o.operationId));return h?this.#ne(u,h,!0):this.#P(u,Object.freeze({contract:"terminal-services-v1",type:"output.status",status:gd(o)})),p}#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.#H-=o.retainedBytes,this.#S-=o.retainedBlocks,this.#t.delete(i));for(let i of this.#o)i.bindingKey===e&&this.#V(i,n)}#D(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.#E(i.user,i.response.session,!1,!1)}catch(o){this.#A(n,Lo(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.#E(n.user,i.response.session,!1),this.#q(n.authority,i)}this.#F(n)}catch(i){this.#V(n,Lo(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.#H=0,this.#S=0}}};function Zy(t){let e=new Map,n=new Map,i=!1;function o(u,p){if(i)throw new je("source_unavailable");if(!t.families.has(p.sessionContract))throw new je("unsupported_capability");let h=t.registry.get(p.sessionId);if(!h||h.handle.endUserId!==u||qi(h.handle)!==p.sessionContract)throw new je("not_found");if(h.ended)throw new je("stale_generation");return h.handle}function s(u,p){if(i)throw new je("source_unavailable");if(!t.families.has(p.sessionContract))throw new je("unsupported_capability");let h=t.registry.get(p.sessionId);if(!h||h.handle.endUserId!==u||qi(h.handle)!==p.sessionContract)throw new je("not_found");return{handle:h.handle,registry:t.registry}}function a(u,p,h){if(u.endUserId!==p)throw new je("forbidden");let g=Cn(h)?.management?.identity;if(g&&(g.applicationScopeId!==u.applicationScopeId||g.endUserId!==u.endUserId))throw new je("forbidden");return u}function d(u,p,h,g){if(!t.scopeFor)throw new je("capability_unconfirmed");g.throwIfAborted();let m=t.scopeFor({endUserId:u,...p}),v;try{v=vt("Scope",m)}catch{throw new je("capability_unconfirmed")}return g.throwIfAborted(),a(v,u,h)}function c(u,p,h,g){let m=d(u,p,h,g);if(o(u,p)!==h)throw new je("stale_generation");return m}function l(u){return Ti.map(p=>{let h=p==="session-configuration-v1"?u.configuration?.()!==void 0&&u.configure!==void 0:p==="memory-lifecycle-v1"&&Cn(u)?.management!==void 0;return{feature:p,supported:h,installed:h,authorization:h?"allowed":"unconfirmed",device:h?"not-required":"unconfirmed"}})}let f=new Map;for(let[u,p]of t.families){if(p.execution&&p.transactionalExecution)throw new TypeError("Conflicting terminal execution backends");let h=p.execution??p.transactionalExecution;if(!h)continue;e.set(u,h);let g=(m,v)=>{let b=o(m,{sessionContract:u,sessionId:v.sessionId}),x="unavailable";if(v.binding)try{h.connection(m,v.binding.target.executorId,v.binding.target.connectionId),x="available"}catch{}let R=nr(b),A=v.deviceTools().some(C=>v.available(C.name))||R?.capability()===!0;return Ti.map(C=>{let B=C==="execution-stream-v1"||C==="execution-background-v1"&&v.backgroundSupported()||C==="memory-lifecycle-v1"&&(R!==void 0||Cn(b)?.management!==void 0)||C==="session-configuration-v1"&&b.configuration?.()!==void 0&&b.configure!==void 0;return{feature:C,supported:B,installed:B,authorization:C==="execution-stream-v1"?A?"allowed":"denied":C==="execution-background-v1"?v.available("Shell")?"allowed":"denied":C==="memory-lifecycle-v1"&&R?R.capability()?"allowed":"unconfirmed":B?"allowed":"unconfirmed",device:C==="execution-stream-v1"||C==="execution-background-v1"||C==="memory-lifecycle-v1"&&R?x:B?"not-required":"unconfirmed"}})};f.set(u,g),n.set(u,new yd({host:h,sessionContracts:[u],resolveSession(m,v){return o(m,v),h.session(m,v.sessionId)},sessionFeatures:g}))}return{resolve:o,resolveObservation:s,sessionFeatures(u,p){let h=o(u,p),g=e.get(p.sessionContract),m=f.get(p.sessionContract);return!g||!m?l(h):m(u,g.session(u,p.sessionId))},async checkObservation(u,p,h){h.throwIfAborted();let{handle:g}=s(u,p),m=()=>{if(h.throwIfAborted(),s(u,p).handle!==g)throw new je("stale_generation");!t.registry.get(p.sessionId).ended&&g.status()!=="ended"&&g.owner?.assertCurrent()};if(m(),t.filterObservationReads&&!await t.filterObservationReads(u,p))throw new je("not_found");m();let v=e.get(p.sessionContract);if(v){let b=await v.options.readPolicy(u,h);if(m(),b.expiresAt!==void 0&&(!Number.isSafeInteger(b.expiresAt)||b.expiresAt<=v.now()))throw new je("source_unavailable");let x;try{x=vt("Scope",{applicationScopeId:v.options.applicationScopeId,endUserId:u,authorizationRevision:b.authorizationRevision})}catch{throw new je("capability_unconfirmed")}a(x,u,g);let R=v.sessions.get(p.sessionId);if(R&&(R.user!==u||BigInt(x.authorizationRevision)<BigInt(R.policy.authorizationRevision)))throw new je("stale_generation")}else d(u,p,g,h);if(m(),t.filterObservationReads&&!await t.filterObservationReads(u,p))throw new je("not_found");m()},async check(u,p,h){let g=o(u,p),m=e.get(p.sessionContract);if(m?await m.session(u,p.sessionId).refresh(h,!1):(await g.owner?.assertCurrent(),c(u,p,g,h)),h.throwIfAborted(),g!==o(u,p))throw new je("stale_generation")},async bindControl(u,p,h,g){if(!p.controller)throw new je("forbidden");if(!t.scopeFor||h.executionBinding!==null)throw new je("capability_unconfirmed");let m=o(u,h.session);await m.owner?.assertCurrent(),g.throwIfAborted();let v=c(u,h.session,m,g);return md(h,{session:h.session,scope:v,executionBinding:null,features:l(m),limits:Ai})},serviceFor:u=>n.get(u),async authorize(u,p,h,g){if(i)throw new je("source_unavailable");if(!t.families.has(g))throw new je("unsupported_capability");let m=e.get(g);return m?Pu(m,u,p,h):{controller:!0}},capabilities(){let u=Ti.map(p=>({feature:p,supported:(p==="execution-stream-v1"||p==="execution-background-v1")&&n.size>0||(p==="session-configuration-v1"||p==="memory-lifecycle-v1")&&[...t.families.values()].some(h=>h.terminalCapabilities?.includes(p)),installed:(p==="execution-stream-v1"||p==="execution-background-v1")&&n.size>0||(p==="session-configuration-v1"||p==="memory-lifecycle-v1")&&[...t.families.values()].some(h=>h.terminalCapabilities?.includes(p)),authorization:"unconfirmed",device:"unconfirmed"}));return No({sessionContracts:[...t.families.keys()],features:u,limits:Ai})},close(){if(!i){i=!0;for(let u of n.values())u.close();n.clear(),e.clear()}}}}import{randomUUID as Jk}from"node:crypto";var ev="terminal-services-v1",zo=262144,Yk=128;function Dt(t){throw new je(t)}function jt(t,e){try{return vt(t,e)}catch{return Dt("invalid_request")}}function ei(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)&&Dt("invalid_request"),e.includes("contract")&&i.get("contract")!==ev&&Dt("protocol_version_mismatch"),e.some(o=>!i.has(o))&&Dt("invalid_request"),i}function Xk(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 ir(t,e,n,i=200){if(t.destroyed||t.writableEnded)return;let o=Zt(jt(e,n),{maxBytes:zo});t.writeHead(i,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length}),t.end(o)}function Zk(t){return t instanceof je||t instanceof Uo?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 Pt&&t.code==="overloaded"?"capacity_exceeded":"source_unavailable"}function tv(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,zo),i=0;async function o(l,f){let u;try{u=await t.authenticate(l,f)}catch(p){if(p instanceof Pt)throw p;return Dt("unauthorized")}return u?.endUserId||Dt("unauthorized"),(l.aborted||f.destroyed||f.writableEnded)&&Dt("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"])&&Dt("invalid_request");let u=ri(l,n);t.admission.reserveBody(u).admitted||Dt("capacity_exceeded");try{let p=await mi(l,n,h=>li(h,{maxBytes:n}));return p.ok||(p.reason==="too_large"&&f.setHeader("connection","close"),Dt(p.reason==="too_large"?"payload_too_large":"invalid_request")),p.value}finally{t.admission.releaseBody(u)}}function a(l){return t.serviceFor(l)??Dt("unsupported_capability")}async function d(l,f,u,p,h){t.admission.tryAdmitSse(u).admitted||Dt("capacity_exceeded");let m=new AbortController,v,b,x,R,A=!1,C=[],B=0,Y,ne,N=_=>{let G="eventId"in _,V=jt(G?"ExecutorEvent":"OutputEvent",_);return tn({event:_.type,...G?{id:_.eventId}:{},data:Buffer.from(Zt(V,{maxBytes:zo})).toString("utf8")})},X=_=>{R||(R=_,m.abort(),v?.close(),f.headersSent&&!f.destroyed&&f.destroy())},S=()=>{A||(A=!0,x&&clearInterval(x),m.abort(),v?.close(),C=[],B=0,ne=void 0,t.admission.releaseSse(u),l.removeListener("aborted",w))},w=()=>{X("source_unavailable"),S()};l.once("aborted",w),f.once("close",S);let T=()=>Y||(Y=(async()=>{if(m.signal.aborted||await o(l,f)!==u)return!1;let _=await t.authorize(l,f,u,p);return await v.check(_,m.signal),!m.signal.aborted})().catch(()=>!1).then(_=>(_||X("forbidden"),_)).finally(()=>{Y=void 0}),Y);try{let _=await t.authorize(l,f,u,p);v=await h(_,te=>{if(m.signal.aborted)return;let re=N(te);if(b)b.write(re);else{if(B+=Buffer.byteLength(re),C.length>=32||B>zo){X("capacity_exceeded");return}C.push(re)}},te=>{if(ne!==void 0||b!==void 0){X("invalid_request");return}ne=te},X,m.signal),(R||m.signal.aborted||f.destroyed)&&(v.close(),Dt(R??"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:T,gapFrame:()=>(X("output_gap"),"")});let G=ne,V=C;if(b.replay((function*(){for(let te of G??[])yield N(te);yield*V})()),C=[],B=0,ne=void 0,A||m.signal.aborted||f.destroyed){S();return}x=setInterval(()=>{T()},e),x.unref()}catch(_){throw S(),_}}async function c(l,f,u,p,h){let g=await o(l,f);t.admission.overloaded()&&Dt("source_unavailable"),p==="GET"&&(l.headers["transfer-encoding"]!==void 0||l.headers["content-length"]!==void 0&&l.headers["content-length"]!=="0")&&Dt("invalid_request");let m=/^\/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),x=u==="/v3/terminal/capabilities",R=u==="/v3/terminal/bindings";if(!m&&!v&&!b&&!x&&!R){let X;if(await t.control?.({req:l,res:f,pathname:u,method:p,endUserId:g,signal:h,readBody:()=>X??=s(l,f),authorize:async S=>{h.throwIfAborted(),await o(l,f)!==g&&Dt("unauthorized");let w=await t.authorize(l,f,g,S);return h.throwIfAborted(),w},reply:(S,w,T)=>ir(f,S,w,T)}))return;Dt("not_found")}let A=R||m?.[2]==="output-batches"?"POST":"GET";if(p!==A&&Dt("invalid_request"),x){ei(l,["contract"]),ir(f,"CapabilitiesResponse",t.capabilities());return}if(v){let X=ei(l,["contract","sessionContract","sessionId","requestDigest","connectionId"]),S=jt("SessionReference",{sessionContract:X.get("sessionContract"),sessionId:X.get("sessionId")}),w=jt("OperationReference",{operationId:decodeURIComponent(v[2]),requestDigest:X.get("requestDigest")}),T=jt("Id",decodeURIComponent(v[1])),_=jt("Id",X.get("connectionId")),G=await t.authorize(l,f,g,S.sessionContract);ir(f,"ExecutionState",await a(S.sessionContract).executionState(g,G,T,_,S,w,h));return}if(p==="POST"){ei(l,[]);let X=await s(l,f);if(await o(l,f)!==g&&Dt("unauthorized"),R){let S=jt("BindingRequest",X),w=S.session.sessionContract,T=t.serviceFor(w),_=await t.authorize(l,f,g,w),G=T?await T.bind(g,_,S,h):await t.bindControl?.(g,_,S,h);G||Dt("unsupported_capability"),ir(f,"BindingResponse",G)}else{let S=jt("OutputBatchRequest",X),w=S.session.sessionContract;S.executorId!==decodeURIComponent(m[1])&&Dt("invalid_request");let T=a(w),_=await t.authorize(l,f,g,w);ir(f,"OutputStatus",await T.receive(g,_,S,h))}return}if(m){let X=ei(l,["contract","sessionContract","connectionId"]),S=jt("SessionContract",X.get("sessionContract")),w=a(S),T=jt("Id",decodeURIComponent(m[1])),_=jt("Id",X.get("connectionId")),G=l.headers["last-event-id"];G!==void 0&&jt("Sequence",G),await d(l,f,g,S,(V,te,re,M,k)=>w.subscribeExecutor(g,V,T,_,{event:te,close:M},k));return}let C=b[2]==="tool-output",B=ei(l,["contract","sessionContract","operationId","requestDigest"],C?["afterSeq"]:[]);l.headers["last-event-id"]!==void 0&&Dt("invalid_request");let Y=jt("SessionReference",{sessionContract:B.get("sessionContract"),sessionId:decodeURIComponent(b[1])}),ne=a(Y.sessionContract),N=jt("OperationReference",{operationId:B.get("operationId"),requestDigest:B.get("requestDigest")});if(C){let X=B.has("afterSeq")?jt("Sequence",B.get("afterSeq")):null;await d(l,f,g,Y.sessionContract,(S,w,T,_,G)=>ne.subscribeOutput(g,S,Y,N,X,{event:w,replay:T,close:_},G))}else ir(f,"OutputStatus",await ne.outputStatus(g,await t.authorize(l,f,g,Y.sessionContract),Y,N,h))}return(l,f,u,p)=>{if(u!=="/v3/terminal"&&!u.startsWith("/v3/terminal/"))return!1;let h=i<Yk;h&&i++;let g=new AbortController,m=()=>g.abort();l.once("aborted",m),f.once("close",m);let v=(async()=>{h||Dt("capacity_exceeded"),await c(l,f,u,p,g.signal)})().catch(b=>{if(f.destroyed||f.writableEnded)return;if(f.headersSent){f.destroy();return}let x=Zk(b),[R,A]=Xk(x);if(R===429||R===503)for(let[B,Y]of Object.entries($t(t.admission.retryAfterMs)))f.setHeader(B,Y);let C={contract:ev,requestId:Jk(),code:x,status:R,retryAction:A};if(R===413&&!l.complete){let B=Zt(jt("ErrorResponse",C),{maxBytes:zo});f.writeHead(R,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":B.length,connection:"close"}),f.write(B);let Y=setTimeout(()=>{f.destroyed||f.end()},El);Y.unref(),f.once("close",()=>clearTimeout(Y))}else ir(f,"ErrorResponse",C,R)}).finally(()=>{h&&i--,l.removeListener("aborted",m),f.removeListener("close",m)});return t.trackRequestWork(v),!0}}function zt(t){throw new je(t)}function ex(t){let e=t.reason;switch(e){case"turn_running":return zt("busy");case"session_ended":return zt("stale_generation");case"invalid_configuration":return zt("invalid_request");case"unsupported":return zt("unsupported_capability");case"context_transition_required":case"revision_conflict":case"request_conflict":case"request_limit":return zt(e)}}function nv(t){return async e=>{let n=/^\/v3\/terminal\/sessions\/([^/]+)\/memory(?:\/commands(?:\/([^/]+))?)?$/.exec(e.pathname);if(n)return tx(e,t,n);let i=/^\/v3\/terminal\/sessions\/([^/]+)\/configuration$/.exec(e.pathname);if(!i)return!1;e.method!=="GET"&&e.method!=="POST"&&zt("invalid_request");let o,s,a=decodeURIComponent(i[1]);if(e.method==="GET"){let f=ei(e.req,["contract","sessionContract"]);o=jt("SessionReference",{sessionContract:f.get("sessionContract"),sessionId:a})}else ei(e.req,[]),s=jt("ConfigurationRequest",await e.readBody()),(s.session.sessionId!==a||Object.keys(s.changes).length===0)&&zt("invalid_request"),o=s.session;(await e.authorize(o.sessionContract)).controller||zt("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)&&zt("stale_generation"),e.signal.throwIfAborted();let l=c.configuration?.();if((!l||!c.configure)&&zt("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||zt("forbidden"),await t.check(e.endUserId,o,e.signal),c!==t.resolve(e.endUserId,o)&&zt("stale_generation"),e.signal.throwIfAborted()}});f.status==="rejected"&&ex(f),e.reply("ConfigurationCommitResponse",{contract:s.contract,requestId:s.requestId,session:o,status:f.status,configuration:f.configuration})}return!0}}async function tx(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")&&zt("invalid_request");let a,d,c;if(o)ei(t.req,[]),d=jt("MemoryCommandRequest",await t.readBody()),d.session.sessionId!==i&&zt("invalid_request"),a=d.session;else{let g=ei(t.req,["contract","sessionContract",...s?["requestId"]:[]]);a=jt("SessionReference",{sessionContract:g.get("sessionContract"),sessionId:i}),s!==void 0&&(jt("MemoryIdentifier",s),c=jt("MemoryIdentifier",g.get("requestId")))}let l=e.resolve(t.endUserId,a),f=async()=>{(await t.authorize(a.sessionContract)).controller||zt("forbidden"),await e.check(t.endUserId,a,t.signal),l!==e.resolve(t.endUserId,a)&&zt("stale_generation"),t.signal.throwIfAborted()};await f(),(d!==void 0||Cn(l)?.management===void 0)&&await nr(l)?.prepare(t.signal),await f();let u=Cn(l),p=u?.management;(!u||!p)&&zt("unsupported_capability");let h=()=>{(Cn(l)!==u||u.management!==p)&&zt("stale_generation"),u.status().enabled||zt("source_unavailable"),p.assertCurrent()};if(h(),p.identity.endUserId!==t.endUserId&&zt("forbidden"),d!==void 0){let g=$y(l);g||zt("unsupported_capability");let{contract:m,session:v,...b}=d,x=await g(b,{signal:t.signal,beforeCommit:f});await p.read(),await f(),h(),t.reply("MemoryReceiptResponse",{contract:"terminal-services-v1",session:a,receipt:x})}else if(s!==void 0){let g=await p.status(s,c);await f(),h(),t.reply("MemoryReceiptResponse",{contract:"terminal-services-v1",session:a,receipt:g})}else{let g=await p.read();await f(),h(),t.reply("MemoryStateResponse",{contract:"terminal-services-v1",session:a,memory:g})}return!0}catch(i){throw i instanceof ct?new je(i.code):i}}import{randomUUID as nx}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 iv(t,e){if(!Object.hasOwn(nt,t))throw new TypeError("Unknown terminal observation type");return nt[t].parse(e)}var vd="terminal-observation-v1",ix=262144;function sn(t){throw new je(t)}function tf(t,e){try{return iv(t,e)}catch{return sn("invalid_request")}}function ef(t,e,n,i=200){if(t.destroyed||t.writableEnded)return;let o=Zt(tf(e,n),{maxBytes:ix});t.writeHead(i,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length}),t.end(o)}function rx(t){return t instanceof je?t.code:t instanceof Ve?t.code==="request_expired"?"stale_generation":t.code:t instanceof URIError?"invalid_request":t instanceof Pt&&t.code==="overloaded"?"capacity_exceeded":"source_unavailable"}function ox(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 rv(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 Pt)throw l;return sn("unauthorized")}return d.throwIfAborted(),c?.endUserId||sn("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"&&sn("source_unavailable"),u>=16&&sn("capacity_exceeded"),n.set(f,u+1);try{let p=/^\/v3\/terminal-observation\/sessions\/([^/]+)\/(resources|output-correlations)$/.exec(d);p||sn("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"])&&sn("invalid_request");let h=new URL(s.url??"/","http://serve.invalid").searchParams,g=["contract","sessionContract",...p[2]==="output-correlations"?["toolCallId"]:[]];[...h.keys()].some(C=>!g.includes(C)||h.getAll(C).length!==1)&&sn("invalid_request"),h.get("contract")!==vd&&sn("protocol_version_mismatch");let m=tf("SessionReference",{sessionContract:h.get("sessionContract"),sessionId:decodeURIComponent(p[1])}),v=h.has("toolCallId")?tf("LegacyId",h.get("toolCallId")):void 0,b=await t.authorize(s,a,f,m.sessionContract);l.throwIfAborted(),b.controller||sn("forbidden");let x=t.resolve(f,m);await t.check(f,m,l),l.throwIfAborted();let R=p[2]==="output-correlations"?await t.readOutputCorrelations(f,b,m,v,l):void 0;await i(s,a,l)!==f&&sn("unauthorized");let A=await t.authorize(s,a,f,m.sessionContract);if(l.throwIfAborted(),A.controller||sn("forbidden"),await t.check(f,m,l),l.throwIfAborted(),(x.handle!==t.resolve(f,m).handle||x.registry.get(m.sessionId)?.handle!==x.handle)&&sn("stale_generation"),R)R.some(C=>C.session.sessionContract!==m.sessionContract||C.session.sessionId!==m.sessionId||v!==void 0&&C.toolCallId!==v)&&sn("integrity_mismatch"),ef(a,"CorrelationsResponse",{contract:vd,session:m,correlations:R.slice(-32),truncated:R.length>32});else{let C=x.registry.resourceObservation(m.sessionId);C||sn("not_found"),ef(a,"ResourcesResponse",{contract:vd,session:m,...C})}}finally{let p=n.get(f)-1;p===0?n.delete(f):n.set(f,p)}}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,p=new Promise((R,A)=>{u=A}),h=()=>u(new je("source_unavailable"));l.signal.addEventListener("abort",h,{once:!0});let g=setTimeout(f,1e4);g.unref(),(s.aborted||a.destroyed||a.writableEnded)&&f();let m=e<128;m&&e++;let v=(async()=>{m||sn("capacity_exceeded"),await o(s,a,d,c,l.signal)})(),b=v.then(()=>{},()=>{}).finally(()=>{m&&e--});t.trackRequestWork(b);let x=Promise.race([v,p]).catch(R=>{if(a.destroyed||a.writableEnded)return;if(a.headersSent){a.destroy();return}let A=rx(R),[C,B]=ox(A);if(C===429||C===503)for(let[Y,ne]of Object.entries($t(t.admission.retryAfterMs)))a.setHeader(Y,ne);ef(a,"ErrorResponse",{contract:vd,requestId:nx(),code:A,status:C,retryAction:B},C)}).finally(()=>{clearTimeout(g),s.removeListener("aborted",f),a.removeListener("close",f),l.signal.removeEventListener("abort",h)});return t.trackRequestWork(x),!0}}import{randomUUID as sx}from"node:crypto";var Oe={};Oe.Contract=r.literal("terminal-profile-v1");Oe.Text=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);Oe.NullableText=r.union([r.lazy(()=>Oe.Text),r.null()]);Oe.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);Oe.SessionContract=r.union([r.literal("sdk1"),r.literal("sdk2-offload-v1")]);Oe.SessionReference=r.object({sessionContract:r.lazy(()=>Oe.SessionContract),sessionId:r.lazy(()=>Oe.Text)}).strict();Oe.Model=r.object({handle:r.lazy(()=>Oe.Text),displayName:r.lazy(()=>Oe.Text),manufacturer:r.lazy(()=>Oe.NullableText),family:r.lazy(()=>Oe.NullableText)}).strict();Oe.Aliases=r.record(r.lazy(()=>Oe.Text),r.lazy(()=>Oe.Text)).refine(t=>Object.keys(t).length<=1024);Oe.Catalog=r.object({models:r.array(r.lazy(()=>Oe.Model)).max(1024),aliases:r.lazy(()=>Oe.Aliases),capabilities:r.lazy(()=>Oe.Capabilities)}).strict();Oe.Quota=r.object({state:r.literal("not_exposed"),enforcement:r.literal("gateway")}).strict();Oe.Counter=r.number().int().safe().min(0).max(9007199254740991);Oe.Usage=r.object({window:r.literal("1d"),endUserId:r.lazy(()=>Oe.Text),requests:r.lazy(()=>Oe.Counter),inTokens:r.lazy(()=>Oe.Counter),outTokens:r.lazy(()=>Oe.Counter),cacheRTokens:r.lazy(()=>Oe.Counter),cacheWTokens:r.lazy(()=>Oe.Counter)}).strict();Oe.CatalogResponse=r.object({contract:r.lazy(()=>Oe.Contract),session:r.lazy(()=>Oe.SessionReference),models:r.array(r.lazy(()=>Oe.Model)).max(1024),aliases:r.lazy(()=>Oe.Aliases),quota:r.lazy(()=>Oe.Quota),capabilities:r.lazy(()=>Oe.Capabilities)}).strict();Oe.UsageResponse=r.object({contract:r.lazy(()=>Oe.Contract),session:r.lazy(()=>Oe.SessionReference),usage:r.lazy(()=>Oe.Usage),quota:r.lazy(()=>Oe.Quota)}).strict();Oe.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")]);Oe.ErrorResponse=r.object({contract:r.lazy(()=>Oe.Contract),requestId:r.lazy(()=>Oe.Id),code:r.lazy(()=>Oe.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();Oe.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();Oe.CapabilityPlatform=r.object({imageGen:r.boolean(),videoGen:r.boolean(),webSearch:r.boolean(),speechToText:r.boolean(),textToSpeech:r.boolean()}).strict();Oe.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();Oe.ExecutionCapabilities=r.object({version:r.literal("bound-device-v1"),boundDevice:r.object({tools:r.lazy(()=>Oe.BoundDeviceTools)}).strict()}).strict();Oe.Capabilities=r.object({tools:r.lazy(()=>Oe.CapabilityTools),platform:r.lazy(()=>Oe.CapabilityPlatform),execution:r.lazy(()=>Oe.ExecutionCapabilities).optional()}).strict();function bd(t,e){if(!Object.hasOwn(Oe,t))throw new TypeError("Unknown terminal profile type");return Oe[t].parse(e)}var Sd="terminal-profile-v1",ax=262144;function on(t){throw new je(t)}function ov(t,e){try{return bd(t,e)}catch{return on("invalid_request")}}function nf(t,e,n,i=200){if(t.destroyed||t.writableEnded)return;let o=Zt(ov(e,n),{maxBytes:ax});t.writeHead(i,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length}),t.end(o)}function dx(t){return t instanceof je?t.code:t instanceof Ve?t.code==="request_expired"?"stale_generation":t.code:t instanceof URIError?"invalid_request":t instanceof Pt&&t.code==="overloaded"?"capacity_exceeded":"source_unavailable"}function cx(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 sv(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 Pt)throw l;return on("unauthorized")}return d.throwIfAborted(),c?.endUserId||on("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"&&on("source_unavailable"),u>=16&&on("capacity_exceeded"),n.set(f,u+1);try{let p=/^\/v3\/terminal-profile\/sessions\/([^/]+)\/(catalog|usage)$/.exec(d);p||on("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"])&&on("invalid_request");let h=new URL(s.url??"/","http://serve.invalid").searchParams,g=["contract","sessionContract"];[...h.keys()].some(B=>!g.includes(B)||h.getAll(B).length!==1)&&on("invalid_request"),h.get("contract")!==Sd&&on("protocol_version_mismatch");let m=ov("SessionReference",{sessionContract:h.get("sessionContract"),sessionId:decodeURIComponent(p[1])}),v=await t.authorize(s,a,f,m.sessionContract);l.throwIfAborted(),v.controller||on("forbidden");let b=t.resolve(f,m);await t.check(f,m,l),l.throwIfAborted();let x=p[2]==="catalog"?await t.readCatalog(f,m,l):void 0,R=p[2]==="usage"?await t.readUsage(f,m,l):void 0;await i(s,a,l)!==f&&on("unauthorized");let A=await t.authorize(s,a,f,m.sessionContract);l.throwIfAborted(),A.controller||on("forbidden"),await t.check(f,m,l),l.throwIfAborted(),(b.handle!==t.resolve(f,m).handle||b.registry.get(m.sessionId)?.handle!==b.handle)&&on("stale_generation");let C={state:"not_exposed",enforcement:"gateway"};if(x!==void 0){let B=bd("Catalog",x),Y=new Set(B.models.map(ne=>ne.handle));(Y.size!==B.models.length||Object.values(B.aliases).some(ne=>!Y.has(ne)))&&on("integrity_mismatch"),nf(a,"CatalogResponse",{contract:Sd,session:m,...B,quota:C})}else if(R!==void 0){let B=bd("Usage",R);(B.endUserId!==f||B.endUserId!==b.handle.endUserId)&&on("integrity_mismatch"),nf(a,"UsageResponse",{contract:Sd,session:m,usage:B,quota:C})}else on("unsupported_capability")}finally{let p=n.get(f)-1;p===0?n.delete(f):n.set(f,p)}}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,p=new Promise((R,A)=>{u=A}),h=()=>u(new je("source_unavailable"));l.signal.addEventListener("abort",h,{once:!0});let g=setTimeout(f,1e4);g.unref(),(s.aborted||a.destroyed||a.writableEnded)&&f();let m=e<128;m&&e++;let v=(async()=>{m||on("capacity_exceeded"),await o(s,a,d,c,l.signal)})(),b=v.then(()=>{},()=>{}).finally(()=>{m&&e--});t.trackRequestWork(b);let x=Promise.race([v,p]).catch(R=>{if(a.destroyed||a.writableEnded)return;if(a.headersSent){a.destroy();return}let A=dx(R),[C,B]=cx(A);if(C===429||C===503)for(let[Y,ne]of Object.entries($t(t.admission.retryAfterMs)))a.setHeader(Y,ne);nf(a,"ErrorResponse",{contract:Sd,requestId:sx(),code:A,status:C,retryAction:B},C)}).finally(()=>{clearTimeout(g),s.removeListener("aborted",f),a.removeListener("close",f),l.signal.removeEventListener("abort",h)});return t.trackRequestWork(x),!0}}var av=new WeakMap;function dv(t,e){av.set(t,e)}function rf(t){let e=av.get(t)?.();if(e===void 0)throw new je("unsupported_capability");return e}var lx="127.0.0.1",cv=1024,ux=15e3,fx=1024*1024,mx=3e4,px=3e4,hx=1e4,gx=3e4,yx=5e3,vx=5e3,of=50,lv=5e3,bx=/^\/v1\/sessions\/([^/]+)\/(messages|events|abort)$/,Sx=/^\/v1\/approvals\/([^/]+)\/credential$/,wx={unknown_challenge:404,expired:410,digest_mismatch:409,already_resolved:409};async function uv(t){return wd(t)}async function xq(t,e){if(t.v2===void 0)throw new TypeError("Cache routes require v2 end-user authentication");return wd(t,e)}async function Rq(t,e,n,i){if(t.v2===void 0)throw new TypeError("Archive routes require v2 end-user authentication");return wd(t,n,e,i)}async function Iq(t,e,n){if(t.v2===void 0)throw new TypeError("Archive sync requires v2 end-user authentication");return wd(t,void 0,n,{disableV1:!0},e)}async function wd(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??lx,d=t.heartbeatMs??ux;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 D of[u.maxFrameBytes??2097152,u.maxBufferBytes??2097152])if(!Number.isSafeInteger(D)||D<1||D>2097152)throw new RangeError("Terminal SSE budgets must be finite and no greater than 2 MiB")}let p=t.v2===void 0?void 0:yh(t.v2,f),h=t.eventBufferMaxBytes??(f?4*1024*1024:void 0),g=new hr({...u,heartbeatMs:u.heartbeatMs??d}),m=t.maxBodyBytes??fx,v=t.version??"0.0.0-dev",b=t.logger,x=Nn(b),R=Date.now(),A=!1,C=new Set,B=D=>{C.add(D);let F=()=>{C.delete(D)};D.then(F,F)},Y=new ia({eventBufferSize:t.eventBufferSize??cv,...h!==void 0?{eventBufferMaxBytes:h}:{},...u.maxFrameBytes!==void 0?{maxEventBytes:u.maxFrameBytes}:{},...t.v1?.governance??{},...t.v1?.now!==void 0?{now:t.v1.now}:{},onPumpError:(D,F)=>{b?.error(We(le.createFailed,{message:`[${D}] ${F instanceof Error?F.message:String(F)}`}))}}),ne=0,N,X=wh(t.admission??{},{activeSessions:()=>Y.activeCount()+ne+(N?.activeCount()??0)+(N?.pendingCount()??0),...b!==void 0?{logger:b}:{}}),S=t.sse?.keepAliveMs??px,w=t.sse?.drainRetryMs??hx,T=new Set,_,G,V;if(t.v2!==void 0){let D=t.v2.onTurnEndNotify;if(D!==void 0){let he=Mr({governor:t.governor});_=new vr({...he!==void 0?{fetchImpl:he}:{},...D,onDeliveryFailure:Ae=>{x("error",at.notifyDeliveryFailed,{sessionId:Ae.sessionId,...Ae.turnId!==void 0?{turnId:Ae.turnId}:{},attempts:Ae.attempts,reason:Ae.reason},We(le.v2NotifyFailed,{sessionId:Ae.sessionId,attempts:Ae.attempts,reason:Ae.reason})),D.onDeliveryFailure?.(Ae)}})}let F=_,$=t.v2.createSession,K=$.sweepRetention?.bind($);N=new fa({eventBufferSize:t.eventBufferSize??cv,...h!==void 0?{eventBufferMaxBytes:h}:{},...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}:{},...F!==void 0?{onTurnEndNotify:he=>F.notify(he)}:{},...K!==void 0?{onSweep:K}:{},onPumpError:(he,Ae)=>{Ln(t.observability?.metrics).pumpErrors.inc(),b?.error(We(le.createFailed,{message:`[v2:${he}] ${Ae instanceof Error?Ae.message:String(Ae)}`}))}}),V=i?.offload?.only?void 0:Nu({...!i?.offload&&i?.filterSessionReads?{filterSessionReads:i.filterSessionReads}:{},options:t.v2,authenticate:p.authenticate,registry:N,admission:X,maxBodyBytes:m,sse:g,sseKeepAliveMs:S,trackRequestWork:B,...b!==void 0?{logger:b}:{}}),i?.offload&&(G=Nu({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:p.authenticate,registry:N,admission:X,maxBodyBytes:m,sse:g,sseKeepAliveMs:S,trackRequestWork:B,...b!==void 0?{logger:b}:{}}))}let te=new Map;t.v2&&!i?.offload?.only&&te.set("sdk1",t.v2.createSession),i?.offload&&te.set("sdk2-offload-v1",i.offload.options.createSession);let re=t.terminal!==void 0&&N!==void 0?Zy({registry:N,families:te,scopeFor:t.terminal.scopeFor,...i?.filterSessionReads?{filterObservationReads:async(D,F)=>i.offload&&F.sessionContract!=="sdk2-offload-v1"?!0:(await i.filterSessionReads(D,[F.sessionId])).includes(F.sessionId)}:{}}):void 0,M=re===void 0?void 0:tv({...re,control:nv(re),authenticate:p.authenticate,admission:X,sse:g,maxBodyBytes:m,sseKeepAliveMs:S,trackRequestWork:B,...t.terminal?.revalidateMs===void 0?{}:{revalidateMs:t.terminal.revalidateMs}}),k=re===void 0?void 0:rv({authenticate:p.authenticate,authorize:re.authorize,resolve:re.resolveObservation,check:re.checkObservation,admission:X,trackRequestWork:B,readOutputCorrelations:(D,F,$,K,he)=>{let Ae=re.serviceFor($.sessionContract);if(!Ae)throw new je("unsupported_capability");return Ae.readOutputCorrelations(D,F,$,K,he)}}),j=re===void 0?void 0:sv({authenticate:p.authenticate,authorize:re.authorize,resolve:re.resolveObservation,check:re.checkObservation,admission:X,trackRequestWork:B,readCatalog:(D,F,$)=>{let K=rf(re.resolveObservation(D,F).handle).readPlatformCatalog;if(K===void 0)throw new je("unsupported_capability");return K($)},readUsage:(D,F,$)=>{let K=rf(re.resolveObservation(D,F).handle).readPlatformUsage;if(K===void 0)throw new je("unsupported_capability");return K($)}}),W=e!==void 0&&t.v2!==void 0?Sy({link:e,admission:X,authenticate:p.authenticate,track:B}):void 0,q=n!==void 0&&t.v2!==void 0?eg({host:n,admission:X,authenticate:p.authenticate,track:B}):void 0,Q=o!==void 0&&t.v2!==void 0?ky({host:o,admission:X,authenticate:p.authenticate,track:B}):void 0,U=(D,F,$,K)=>!!(k?.(D,F,$,K)||j?.(D,F,$,K)||M?.(D,F,$,K)||W?.(D,F,$,K)||Q?.(D,F)||G!==void 0&&G(D,F,$,K)||q?.(D,F)||V!==void 0&&V(D,F,$,K)),ue={session:G!==void 0?"sdk2-offload-v1":V!==void 0?"sdk1":null,execution:c!==void 0&&(G!==void 0||V!==void 0),archive:q!==void 0,"archive-sync":Q!==void 0,cache:W!==void 0,terminal:M!==void 0,"terminal-observation":k!==void 0,"terminal-profile":j!==void 0},pe=t.v2===void 0?void 0:Ly({authenticate:p.authenticate,delegate:U,sessionFamilies:[...V!==void 0?["sdk1"]:[],...G!==void 0?["sdk2-offload-v1"]:[]],installed:ue,track:B,retryAfterMs:()=>X.retryAfterMs,...N===void 0?{}:{sessionClosure:zy({registry:N,installed:ue,...c===void 0?{}:{execution:c},...n===void 0?{}:{archive:n},...re===void 0?{}:{terminal:re},...e===void 0?{}:{cache:e}})}}),oe=N,ee=_,O=Dh({host:a,options:t.observability,startedAt:R,log:x,v1Active:()=>Y.activeCount(),v2:()=>oe===void 0?void 0:qh(oe),notifierStats:()=>ee?.stats(),sseStats:()=>g.stats(),ringStats:()=>ta(Y.ringStats(),oe?.ringStats()),...t.governor!==void 0?{governorStats:()=>t.governor?.stats()}:{},closing:()=>A});O.addReadinessProbe(()=>{let D=X.readiness();return D.ready?!0:{ready:!1,reason:D.reasons.join(",")||"admission"}});let J=i?.offload?.options.store;J?.readiness!==void 0&&J!==t.v2?.store&&O.addReadinessProbe(()=>J.readiness?.()??!0);let ke=t.v2?.store;ke?.readiness!==void 0&&O.addReadinessProbe(()=>ke.readiness?.()??!0);let we=(D,F,$,K)=>{let he=jn(K),Ae=Oh(D);x("error",at.requestUnhandled,{...Ae!==void 0?{requestId:Ae.requestId,route:Ae.route}:{},method:$,message:he},We(le.requestUnhandled,{method:$,path:F,message:he}));try{if(D.destroyed||D.writableEnded)return;if(!D.headersSent){me(D,500,"internal_error",le.internalError);return}D.end()}catch{D.destroy()}},qe=async(D,F)=>{let $=ri(D,m),K=X.reserveBody($);return K.admitted?(F.once("close",()=>X.releaseBody($)),mi(D,m)):(Kn(F,K),"rejected")},ze=(D,F,$)=>{$==="too_large"?co(D,F,"body_too_large",le.bodyTooLarge,{maxBytes:m}):me(F,400,"invalid_json",le.invalidJson)},He=async(D,F)=>{let $=await qe(D,F);if($==="rejected")return;if(!$.ok){ze(D,F,$.reason);return}if(typeof $.value!="object"||$.value===null||Array.isArray($.value)){me(F,400,"invalid_body",le.invalidBody);return}let K=$.value;if(K.prompt!==void 0&&typeof K.prompt!="string"){me(F,400,"invalid_body",le.invalidBody);return}if(K.model!==void 0&&typeof K.model!="string"){me(F,400,"invalid_body",le.invalidBody);return}if(K.profile!==void 0&&typeof K.profile!="string"){me(F,400,"invalid_body",le.invalidBody);return}if(K.tools!==void 0&&(!Array.isArray(K.tools)||K.tools.some(ae=>typeof ae!="string"))){me(F,400,"invalid_body",le.invalidBody);return}let he;if(K.labels!==void 0){let ae=Jo.safeParse(K.labels);if(!ae.success){me(F,400,"invalid_body",le.invalidBody);return}he=ae.data}let Ae;if(K.budget!==void 0){if(typeof K.budget!="object"||K.budget===null||Array.isArray(K.budget)){me(F,400,"invalid_body",le.invalidBody);return}let ae=K.budget,Re=Le=>typeof Le=="number"&&Number.isFinite(Le)&&Le>0;if(ae.maxUsd!==void 0&&!Re(ae.maxUsd)||ae.maxTokens!==void 0&&(!Re(ae.maxTokens)||!Number.isInteger(ae.maxTokens))){me(F,400,"invalid_body",le.invalidBody);return}Ae={...ae.maxUsd!==void 0?{maxUsd:ae.maxUsd}:{},...ae.maxTokens!==void 0?{maxTokens:ae.maxTokens}:{}}}let ot={...typeof K.prompt=="string"&&K.prompt!==""?{prompt:K.prompt}:{},...typeof K.model=="string"&&K.model!==""?{model:K.model}:{},...typeof K.profile=="string"&&K.profile!==""?{profile:K.profile}:{},...K.tools!==void 0?{tools:K.tools}:{},...he!==void 0?{labels:he}:{},...Ae!==void 0?{budget:Ae}:{}},$e=A?{admitted:!1,reason:"draining",retryAfterMs:X.retryAfterMs}:X.tryAdmitSession();if(!$e.admitted){Kn(F,$e);return}ne+=1;let Ge;try{let ae=await t.createSession.create(ot);Ge=Y.adopt(ae)}catch(ae){me(F,400,"create_failed",le.createFailed,{message:ae instanceof Error?ae.message:String(ae)});return}finally{ne-=1}Je(F,201,{sessionId:Ge})},ht=async(D,F,$)=>{if(Y.get($)===void 0){me(F,404,"session_not_found",le.sessionNotFound,{sessionId:$});return}let he=await qe(D,F);if(he==="rejected")return;if(!he.ok){ze(D,F,he.reason);return}let Ae=typeof he.value=="object"&&he.value!==null?he.value:{};if(typeof Ae.prompt!="string"||Ae.prompt.trim()===""){me(F,400,"prompt_required",le.promptRequired);return}if(!Y.send($,Ae.prompt)){me(F,409,"session_ended",le.sessionEnded,{sessionId:$});return}Je(F,202,{sessionId:$,accepted:!0})},Ot=(D,F)=>{if(!Y.interrupt(F)){me(D,404,"session_not_found",le.sessionNotFound,{sessionId:F});return}Je(D,202,{sessionId:F,accepted:!0})},Fe=(D,F,$)=>{let K=X.tryAdmitSse();if(!K.admitted){Kn(F,K);return}if(F.once("close",()=>{X.releaseSse()}),S>0&&D.socket.setKeepAlive(!0,S),D.socket.setTimeout(0),Y.get($)===void 0){me(F,404,"session_not_found",le.sessionNotFound,{sessionId:$});return}let he=js(D.headers["last-event-id"]);if(he===void 0){me(F,400,"invalid_last_event_id",le.invalidLastEventId);return}F.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no"});let Ae=g.attach(F,{gapFrame:$e=>gr($,$e)});T.add(Ae);let ot=Y.subscribe($,he,Ae);F.on("close",()=>{T.delete(Ae),ot?.()})},Ze=()=>Y.activeCount()+(N?.activeCount()??0),It=D=>{Je(D,200,{version:v,protocolVersion:Cf,activeSessions:Ze(),uptimeMs:Date.now()-R})},xt=async(D,F,$,K)=>{let he=await qe(D,F);if(he==="rejected")return;if(!he.ok){ze(D,F,he.reason);return}if(typeof he.value!="object"||he.value===null||Array.isArray(he.value)){me(F,400,"invalid_body",le.approvalInvalidBody);return}let Ae=he.value;if(typeof Ae.digest!="string"||Ae.digest===""||Ae.verdict!=="approve"&&Ae.verdict!=="deny"||typeof Ae.approver!="string"||Ae.approver.trim()===""){me(F,400,"invalid_body",le.approvalInvalidBody);return}let ot=$.submit({challengeId:K,digest:Ae.digest,verdict:Ae.verdict,approver:Ae.approver});if(ot.code==="accepted"){Je(F,200,{challengeId:K,result:"accepted"});return}me(F,wx[ot.code]??409,`approval_${ot.code}`,le.approvalRejected,{code:ot.code,challengeId:K})},pn=(D,F,$,K)=>{if(pe!==void 0&&pe(D,F,$,K))return;if(l&&($==="/v1"||$.startsWith("/v1/"))){me(F,404,"not_found",le.notFound,{path:$});return}if(i?.offload?.only&&($==="/v2"||$.startsWith("/v2/"))){me(F,404,"not_found",le.notFound);return}if(U(D,F,$,K))return;if(!Ds(D.headers.authorization,s)){me(F,401,"unauthorized",le.unauthorized,void 0,{"www-authenticate":"Bearer"});return}let he=$e=>{B($e),$e.catch(Ge=>we(F,$,K,Ge))};if($==="/v1/sessions"){if(K!=="POST"){me(F,405,"method_not_allowed",le.methodNotAllowed,{method:K,path:$},{allow:"POST"});return}he(He(D,F));return}if($==="/v1/status"){if(K!=="GET"){me(F,405,"method_not_allowed",le.methodNotAllowed,{method:K,path:$},{allow:"GET"});return}It(F);return}let Ae=bx.exec($);if(Ae!==null){let $e=pi(Ae[1]);if($e===null){me(F,404,"not_found",le.notFound,{path:$});return}let Ge=Ae[2];if(Ge==="events"){if(K!=="GET"){me(F,405,"method_not_allowed",le.methodNotAllowed,{method:K,path:$},{allow:"GET"});return}Fe(D,F,$e);return}if(K!=="POST"){me(F,405,"method_not_allowed",le.methodNotAllowed,{method:K,path:$},{allow:"POST"});return}Ge==="messages"?he(ht(D,F,$e)):Ot(F,$e);return}let ot=Sx.exec($);if(ot!==null&&t.approvals!==void 0){if(K!=="POST"){me(F,405,"method_not_allowed",le.methodNotAllowed,{method:K,path:$},{allow:"POST"});return}let $e=pi(ot[1]);if($e===null){me(F,404,"not_found",le.notFound,{path:$});return}he(xt(D,F,t.approvals,$e));return}me(F,404,"not_found",le.notFound,{path:$})},Mn=(D,F)=>{let $=D.method??"GET",K=(D.url??"/").split("?",1)[0];try{O.trackRequest(D,F)}catch{}try{if(O.handleEndpoint(D,F,K,$))return;pn(D,F,K,$)}catch(he){we(F,K,$,he)}},Rt=t.http??{},At=Pp.createServer({requestTimeout:Rt.requestTimeout??mx,...Rt.headersTimeout!==void 0?{headersTimeout:Rt.headersTimeout}:{},...Rt.keepAliveTimeout!==void 0?{keepAliveTimeout:Rt.keepAliveTimeout}:{},...Rt.connectionsCheckingInterval!==void 0?{connectionsCheckingInterval:Rt.connectionsCheckingInterval}:{}},Mn);Rt.maxConnections!==void 0&&(At.maxConnections=Rt.maxConnections),Rt.maxRequestsPerSocket!==void 0&&(At.maxRequestsPerSocket=Rt.maxRequestsPerSocket),Rt.socketTimeoutMs!==void 0&&At.setTimeout(Rt.socketTimeoutMs);try{await new Promise((D,F)=>{let $=K=>F(K);At.once("error",$),At.listen(t.port,a,()=>{At.removeListener("error",$),D()})})}catch(D){throw re?.close(),p?.close(),N?.beginClosing(),await Promise.allSettled([N?.closeAll({timeoutMs:t.closeAllTimeoutMs??lv}),_?.close(),Promise.resolve(X.close()),Promise.resolve(O.close())]),D}let E=At.address(),y=typeof E=="object"&&E!==null?E.port:t.port,P=a==="0.0.0.0"||a==="::"?"127.0.0.1":a,L=`http://${P.includes(":")?`[${P}]`:P}:${y}`;x("info",at.serverListening,{url:L,host:a,port:y},We(le.listening,{url:L})),ua(t.readyFrame,{url:L,pid:process.pid,readyz:bn.readyz});let Z=D=>new Promise(F=>setTimeout(F,D)),H=()=>new Promise(D=>At.getConnections((F,$)=>D($??0))),de=async D=>{A=!0,p?.close(),re?.close(),N?.beginClosing();let F=[],$=async ot=>{try{await ot()}catch($e){F.push($e)}},K=t.closeAllTimeoutMs??lv,he=async(ot,$e)=>{await $(async()=>{let Ge=await $e();Ge?.timedOut===!0&&x("warn",at.serverCloseTimeout,{face:ot,pending:Ge.pending,timeoutMs:K})})};await he("v1",()=>Y.closeAll({timeoutMs:K})),await he("v2",()=>N?.closeAll({timeoutMs:K})),await $(()=>_?.close()),await $(()=>X.close());let Ae=new Promise((ot,$e)=>{At.close(Ge=>Ge!==void 0?$e(Ge):ot())});if(Ae.catch(()=>{}),D){let ot=Date.now()+vx;for(At.closeIdleConnections();await H()>0&&Date.now()<ot;)await Z(of),At.closeIdleConnections()}if(At.closeAllConnections(),await $(()=>Ae),await $(()=>O.close()),x("info",at.serverClosed,{host:a,port:y},We(le.closed)),F.length>0)throw new AggregateError(F,"Server shutdown failed.")},ge=!1,ce,ve=async(D={})=>{let F=D.timeoutMs??gx,$=Date.now();A=!0,X.beginDrain(),N?.beginClosing();let K=tn({retryMs:w,data:""}),he=0;for(let ie of T)ie.stats().closed||(ie.write(K),he+=1);he+=N?.broadcastRetry(w)??0;let Ae=N?.runningCount()??0;b?.info(We(le.drainStarted,{running:Ae,subscribers:he,timeoutMs:F}));let ot=$+F;for(;(N?.runningCount()??0)>0&&Date.now()<ot;)await Z(of);let $e=0;if(N!==void 0&&N.runningCount()>0){$e=N.interruptRunning();let ie=Date.now()+yx;for(;N.runningCount()>0&&Date.now()<ie;)await Z(of)}let Ge=Math.max(0,Ae-$e),ae=0,Re=[];try{ae+=await t.v2?.createSession.flush?.()??0}catch(ie){Re.push(ie)}try{ae+=await t.createSession.flush?.()??0}catch(ie){Re.push(ie)}try{await de(!0)}catch(ie){Re.push(ie)}if(ge=!0,Re.length>0)throw new AggregateError(Re,"Server drain failed.");let Le={completedTurns:Ge,abortedTurns:$e,flushedCommits:ae,durationMs:Date.now()-$};return b?.info(We(le.drained,{...Le})),Le};return{port:y,host:a,url:L,activeSessionCount:()=>Ze(),stats:()=>O.stats(),setSseRetryMs:D=>g.setRetryMs(D),sseStats:()=>g.stats(),readiness:()=>X.readiness(),settleResources:async()=>{for(;C.size>0;)await Promise.allSettled([...C]);let F=(await Promise.allSettled([Y.settleResources(),N?.settleResources()])).flatMap($=>$.status==="rejected"?[$.reason]:[]);if(F.length>0)throw new AggregateError(F,"Server resource cleanup failed.")},drain:D=>(ce===void 0&&(ce=ge?Promise.resolve({completedTurns:0,abortedTurns:0,flushedCommits:0,durationMs:0}):ve(D)),ce),close:async()=>{if(ce!==void 0){await ce;return}ge||(ge=!0,await de(!1))}}}var Ho=[{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:Er},{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_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:[...As]},{name:"TANSR_SERVE_READY_STREAM",group:"process",target:"readyFrame",kind:"enum",values:[...Nh]},{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}],pv=Ho.map(t=>t.name),sf="(set)",kx=64,xx=new Set(["1","true","yes","on"]),Rx=new Set(["0","false","no","off"]);function Ix(t){let e=t?.trim();return e===void 0||e===""?void 0:e}function Tx(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 xx.has(n)?{ok:!0,value:!0}:Rx.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:fv}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{ok:!1,expected:fv}}return{ok:!0,value:e}}case"secret":return{ok:!0,value:e}}}var fv="absolute http(s) URL";function mv(t,e){return t.kind==="secret"?sf:(t.kind==="string"&&t.format==="http-url"?e.replace(/\/\/[^/@?#]*@/u,"//…@").replace(/\?.*$/su,"?…"):e).slice(0,kx)}function Ax(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_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 Ci(t){return Object.keys(t).length>0}function hv(t){let e={admission:{},http:{},observability:{},sse:{},eventBufferMaxBytes:void 0,disableV1: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 Ho){let c=Ix(t[d.name]);if(c===void 0)continue;let l=Tx(d,c);if(!l.ok){i.push({name:d.name,value:mv(d,c),expected:l.expected});continue}if(d.requires!==void 0&&!n.includes(d.requires)){i.push({name:d.name,value:mv(d,c),expected:`${d.requires} to be set and valid (ignored without it)`});continue}Ax(e,d,l.value),n.push(d.name)}let o={...Ci(e.admission)?{admission:e.admission}:{},...Ci(e.http)?{http:e.http}:{},...Ci(e.sse)?{sse:e.sse}:{},...Ci(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}:{}},s={...Ci(e.timeouts)?{timeouts:e.timeouts}:{},...e.maxTurnWallClockMs!==void 0?{maxTurnWallClockMs:e.maxTurnWallClockMs}:{},...e.hostShell!==void 0?{hostShell:e.hostShell}:{}},a={...Ci(e.authentication)?{authentication:e.authentication}:{},...Ci(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:Ci(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 gv(t,...e){let n=new Set(e),i=new Set(Ho.filter(o=>n.has(o.group)).map(o=>o.name));return t.applied.filter(o=>i.has(o))}import{randomUUID as Id}from"node:crypto";import{rm as Dx}from"node:fs/promises";import jx from"node:path";import{randomUUID as af}from"node:crypto";var Go=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 yv(t){return t.reason??new DOMException("The request was aborted","AbortError")}var Dr=class{#e;#n;#r;#s;#t;#o=new Map;#i=new Map;#a=new Map;#c=new Go(Be.receiptTombstones);#d=new Go(Be.receiptTombstones);#f=new Go(Be.receiptTombstones);#p=null;#m=0;constructor(e){this.#e=e.cwd,this.#n=e.permissionTimeoutMs??Be.permissionTimeoutMs,this.#r=e.questionGraceMs??Be.questionGraceMs,this.#s=e.now??Date.now,this.#t=e.onPermissionReceipt}bindEmitter(e){this.#p=e}setCwd(e){this.#e=e}noteSubscribers(e){if(this.#m=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.#p?.(e,n)}emitPlatformWarning(e){this.#w(nn.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(()=>{h(new Error(`remote tool call ${e} timed out`))},Math.max(0,o-this.#s()));f.unref();let u=()=>{h(yv(s))},p=()=>{clearTimeout(f),s.removeEventListener("abort",u),this.#o.delete(e)},h=g=>{this.#o.has(e)&&(p(),this.#c.set(e,"expired"),this.#w(nn.toolCancel,{callId:e}),l(g))};if(this.#o.set(e,{resolve:g=>{p(),this.#c.set(e,"resolved"),c(g)},cleanup:p}),s.aborted){u();return}if(s.addEventListener("abort",u,{once:!0}),d!==void 0)try{Promise.resolve(d()).catch(h)}catch(g){h(g)}else this.#w(nn.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=af(),a=fm({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,x)=>{this.#i.has(s)&&(f(),this.#d.set(s,b),this.#w(nn.permissionClosed,{requestId:s}),o(x))};if(this.#i.set(s,{digest:a,resolve:(b,x)=>{u("resolved",b);try{this.#t?.({requestId:s,verdict:b,...x!==void 0?{reason:x}:{}})}catch{}},cleanup:f}),n?.aborted===!0){l();return}n?.addEventListener("abort",l,{once:!0});let p=im(e.args),h=i?.executionTarget,g=h?.kind==="device"?We(Xt.executionPermissionTarget,{executor:h.executorId,workspace:h.workspaceId??"",revision:h.bindingRevision}):void 0,m=g===void 0?p:[g,p].filter(Boolean).join(`
|
|
33
|
+
`),v=i??{decision:"ask",source:"mode"};this.#w(nn.permissionRequest,Af({requestId:s,name:e.name,...m!==void 0?{summary:m}:{},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(nn.questionClosed,{requestId:e}),n.reject(new Mm))},this.#r),n.graceTimer.unref()}createPromptChannel(){return{ask:(e,n)=>new Promise((i,o)=>{let s=af(),a=()=>{this.#a.has(s)&&(d.cleanup(),this.#f.set(s,"expired"),this.#w(nn.questionClosed,{requestId:s}),o(yv(n)))},d={questions:e,resolve:l=>{d.cleanup(),this.#f.set(s,"resolved"),this.#w(nn.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.#m===0;c&&this.#v(s,d),this.#w(nn.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=Cx(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 Cx(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 vv(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?vv(t.items):r.unknown());break;case"object":e=t.properties!==void 0?bv(t.properties):r.record(r.unknown());break}return t.description!==void 0&&(e=e.describe(t.description)),e}function bv(t){let e={};for(let[n,i]of Object.entries(t)){let o=vv(i);e[n]=i.optional===!0?o.optional():o}return r.object(e)}function df(t){let e={type:t.type};if(t.description!==void 0&&(e.description=t.description),t.type==="array"&&t.items!==void 0&&(e.items=df(t.items)),t.type==="object"&&t.properties!==void 0){e.properties=Object.fromEntries(Object.entries(t.properties).map(([i,o])=>[i,df(o)]));let n=Object.entries(t.properties).filter(([,i])=>i.optional!==!0).map(([i])=>i);n.length>0&&(e.required=n)}return e}function kd(t,e,n=Date.now,i){let o=Math.min(Math.max(t.timeoutMs??Be.toolTimeoutDefaultMs,Be.toolTimeoutMinMs),Be.toolTimeoutCapMs),s=t.parameters!==void 0?bv(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 p=f.error.issues.map(h=>h.path.length>0?`${h.path.join(".")}: ${h.message}`:h.message).join("; ");return{content:[{t:"text",text:`invalid ${t.name} args: ${p}`}],isError:!0}}if(i!==void 0)return i(f.data,l);let u=l.toolCallId??af();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,df(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 Ex from"node:path";function Sv(t){return t instanceof un&&t.code==="INVALID_CHECKPOINT_ID"}function Wo(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=>Ex.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 gc(e(i,o.sessionId),o,{...n,...s?.attachmentsFrom!==void 0?{attachmentsFrom:s.attachmentsFrom}:{}})},async get(i,o,s){try{return await yc(e(i,o),o,s)}catch(a){if(Sv(a))return null;throw a}},list(i,o){return vc(e(i,o),o)},async delete(i,o,s){try{return await bc(e(i,o),o,s)}catch(a){if(Sv(a))return!1;throw a}}}}function rr(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 wv(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 Pn=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 xv}from"node:crypto";import Rv,{posix as Iv}from"node:path";var cf="adjudicator_unavailable",lf="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 xd(t,e,n){if(Qc("createAgentSessionFactory",e),e?.enabled===!1)return;if(t.assembleAdjudicator===void 0){e!==void 0&&t.onAdjudicationWarning?.({code:cf,message:lf});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=am(i,n);return t.assembleAdjudicator({posture:o,postureExplicit:i!==void 0,...e?.callBudget!==void 0?{callBudget:e.callBudget}:{}})}function _x(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 kv(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,p=AbortSignal.any([f,i.signal,u.signal]);p.throwIfAborted();let h=setTimeout(()=>u.abort(new Error("Trusted hook timed out")),n),g,m=new Promise((x,R)=>{g=()=>R(p.reason),p.addEventListener("abort",g,{once:!0})}),v=Promise.resolve().then(()=>(p.throwIfAborted(),l(p))),b=v.catch(()=>{});o.add(b),b.finally(()=>o.delete(b));try{let x=await Promise.race([v,m]);return p.throwIfAborted(),x}finally{clearTimeout(h),p.removeEventListener("abort",g)}}let d=()=>(e(),{blocked:!0});async function c(l,f){try{return _x(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 p={};for(let g of["userPromptSubmit","postToolUse","stop","preCompact","postCompact"]){let m=u[g];if(m!==void 0){if(typeof m!="function")throw new TypeError("Invalid trusted query hook callback");Object.defineProperty(p,g,{value:m,enumerable:!0})}}let h=u.maxConsecutiveStopBlocks;if(h!==void 0){if(!Number.isSafeInteger(h)||h<1||h>32)throw new TypeError("Invalid trusted query hooks");p.maxConsecutiveStopBlocks=h}f=Object.freeze(p)}catch{return{userPromptSubmit:d,preCompact:d,stop:d}}return{...f.userPromptSubmit===void 0?{}:{userPromptSubmit:u=>c(p=>f.userPromptSubmit({...u,signal:p}),u.signal)},...f.postToolUse===void 0?{}:{postToolUse:u=>c(p=>f.postToolUse({...u,signal:p}),u.signal)},...f.stop===void 0?{}:{stop:u=>c(p=>f.stop({...u,signal:p}),u.signal)},...f.preCompact===void 0?{}:{preCompact:u=>c(p=>f.preCompact({...u,signal:p}),u.signal)},...f.postCompact===void 0?{}:{postCompact:u=>a(p=>f.postCompact({...u,signal:p}),u.signal)},...f.maxConsecutiveStopBlocks===void 0?{}:{maxConsecutiveStopBlocks:f.maxConsecutiveStopBlocks}}},async system(l,f){return Px(await a(l,f))},boundary(l){return t.beforeTool?{resolve(f,u){let p=l.resolve(f,u);if(p)return{...p,executeService:async(h,g,m)=>{let v=structuredClone(h),b=await c(x=>t.beforeTool(v,{signal:x}),g);return g.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 p.assertCurrent(),g.throwIfAborted(),i.signal.throwIfAborted(),p.executeService?p.executeService(h,g,m):m())}}}}:l},stop(){i.abort()},close(){return s||(i.abort(),s=(async()=>{for(;o.size;)await Promise.all([...o]);await t.onClosed?.()})(),s)}}}function Px(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)}function Mx(t,e){return rc(t===void 0?void 0:{...t.maxUsd!==void 0?{maxUsd:t.maxUsd}:{},...t.maxTokens!==void 0?{maxTotalTokens:t.maxTokens}:{}},e)}function Ox(t,e){return Hc(t,e)?.quirks?.reasoningTokens}var Bx;function qx(t,e){let n=t.capabilities;if(n===void 0)return[hs(e.todoStore),ys(e.channel)];let i=[];if(n.tools.todoWrite&&i.push(hs(e.todoStore)),n.tools.askUser&&i.push(ys(e.channel)),n.tools.webFetch||n.tools.http){let a=Bx??=Fr({env:process.env});n.tools.webFetch&&i.push(Cc({client:a})),n.tools.http&&i.push(_c({client:a,env:{},allowedAuthEnvVars:[],allowPrivate:!1}))}let o=t.platformTools;if(o===void 0)return i;let s={baseUrl:o.baseUrl,token:Bi,fetchImpl:o.fetchImpl};return n.tools.webSearch&&n.platform.webSearch&&i.push(Ec({provider:wa(s)})),n.platform.imageGen&&i.push(bs({provider:$r({...s,models:o.platformModels.imageGen})})),n.platform.videoGen&&i.push(Ss({provider:Kr({...s,models:o.platformModels.videoGen})})),n.platform.speechToText&&i.push(ws({provider:Jr({...s,models:o.platformModels.speechToText})})),n.platform.textToSpeech&&i.push(ks({provider:Xr({...s,models:o.platformModels.textToSpeech})})),i}function Rd(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 Xe("validation_failed",We(Xt.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:kv(d??{},()=>s?.interrupt()),f=n.model??"main",u=o(f,ae=>{let Re=Wr(ae);Re!==null&&s?.pushBody(Re,"provider")}),p=e===void 0?u.maxOutputTokens:Math.min(e,u.maxOutputTokens??e),h=e===void 0?t.maxTokens??Pi:Math.min(t.maxTokens??Pi,p),g=e===void 0?u.compaction??{}:{...u.compaction,maxOutputTokens:Math.min(u.compaction?.maxOutputTokens??1/0,p)};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 m=t.system?.map(ae=>({...ae})),v=t.systemAppend?.map(ae=>({...ae}))??[],b,x=[],R,A=new WeakMap,C=ae=>{let Re=Io(ae,m),Le=[...Re.system,...v.map(ie=>({...ie})),...i?.execution?.systemSegments()??[],...x];return A.set(Le,Object.freeze({...Re.info})),Le},B=new ns({onChange:ae=>s?.pushBody({type:"plan.todo.updated",items:ae},"tool")});b=C(u);let Y=i?.promptChannel??new gs,ne=qx(u,{todoStore:B,channel:Y});if(u.capabilities!==void 0&&!u.capabilities.tools.customTools&&i?.sessionTools!==void 0&&i.sessionTools.length>0)throw new Xe("validation_failed",We(Xt.capabilityDisabled,{bit:"customTools"}));let N=n.tools!==void 0?new Set(n.tools):void 0,X=N!==void 0?ne.filter(ae=>N.has(ae.name)):ne,S=i?.capabilityProfile,w=S!==void 0?ne.map(ae=>ae.name).filter(ae=>!S.tools.includes(ae)):[],T=i?.execution,_=()=>fe([T?.binding,T?.policy.authorizationRevision,T?.attachmentSourceRevision,T?.attachmentSource]),G=()=>{},V=new qn,te=[];for(let ae of X)V.register(ae),te.push(fn(ae));if(i?.sessionTools!==void 0)for(let{tool:ae,def:Re}of i.sessionTools){if(ne.some(Le=>Le.name===ae.name))throw new Pn(ae.name);V.register(ae),te.push(Re)}let re=T?.boundary(X);if(d?.beforeTool&&!re)throw new TypeError("Trusted tool control requires an explicit execution host");let M=re===void 0||l===void 0?re:{...l.boundary(re),registerBuiltin:re.registerBuiltin},k,j=async ae=>{if(T===void 0)return;await T.refresh(ae),ae.throwIfAborted();let Re=_();Re!==k&&((k!==void 0||T.binding!==null)&&s?.invalidateAttachmentReferences(),G(),k=Re),s?.updateAttachmentSource(T.attachmentSource);let Le=[...X],ie=new Set(ne.map(Ne=>Ne.name));for(let Ne of[...T.deviceTools(),...T.serviceTools()]){if(ie.has(Ne.name))throw new Pn(Ne.name);ie.add(Ne.name),(N===void 0||N.has(Ne.name)||T.isClientTool(Ne.name)||T.isShellAuxiliary(Ne.name)&&N.has("Shell"))&&Le.push(Ne)}let Me=T.filterTools(Le.map(Ne=>T.definition(Ne)??fn(Ne))),lt=new Set(Me.map(Ne=>Ne.name));if(lt.size!==Me.length||Me.some(Ne=>!Le.some(_e=>_e.name===Ne.name)))throw new Error("Execution policy returned invalid tool definitions.");let Ct=new Map(Le.filter(Ne=>lt.has(Ne.name)).map(Ne=>[Ne.name,Ne]));for(let Ne of V.names())V.get(Ne)!==Ct.get(Ne)&&V.unregister(Ne);for(let Ne of Ct.values())V.has(Ne.name)||V.register(Ne);te.splice(0,te.length,...Me)},W=ae=>{let Re=c===void 0?ae:c(ae);if(!Re||typeof Re.stream!="function")throw new TypeError("Invalid trusted model client");let Le=On(Re,ae);return T===void 0&&t.memoryFor===void 0&&t.memoryPublicationFor===void 0?Le:On({async*stream(ie,Me){let lt=Me?.signal??new AbortController().signal;if(await j(lt),T?.assertModelRequestsAllowed(),await oe?.verifyAvailable(),lt.throwIfAborted(),R!==void 0&&R!==_())throw new Ve("stale_generation");let Ct=ie.tools.length===0?[]:te,Ne=Dd(ae)?jd(ie,Ct):{...ie,tools:Ct};yield*Le.stream(Ne,Me)}},ae)},q=W(u.client),Q=i?.cwd??t.cwd,U=xd(u,t.adjudication,i?.askUser!==void 0),ue=new Ur({...U!==void 0?{mode:sc({posture:U.posture,tier:U.tier}),classifier:U.config}:{},...t.hostShell!==void 0?{hostShell:t.hostShell}:{}}),pe=Si(ue,V,{cwd:Q}),oe,ee=new ss({registry:V,cwd:Q,permissionGate:pe,...M===void 0?{}:{executionBoundary:M},...i?.askUser!==void 0?{askUser:i.askUser}:{},...t.onDecision!==void 0?{onDecision:t.onDecision}:{},...T?.host.options.memoryFor===void 0?{}:{onBoundToolSucceeded:(ae,Re)=>{let Le=T.binding,ie=E;if(!Rt||ie===void 0||Le===null||Re.kind!=="device"||Re.bindingId!==Le.bindingId||Re.bindingRevision!==Le.revision||Re.authorizationRevision!==T.policy.authorizationRevision||!T.available("Read")||!T.available("List")||!["Read","Write","Edit"].includes(ae.name))return;let Me=ae.args!==null&&typeof ae.args=="object"?ae.args.file_path:void 0;if(typeof Me!="string"||/[\\\u0000]/.test(Me))return;let lt=Iv.resolve(ie.root,Me);lt!==ie.root&&!lt.startsWith(ie.root+"/")||Fe?.observeTouched([{toolName:ae.name,paths:[lt]}])}}}),O=i?.sessionId??xv(),J=i?.memoryScope??{sessionId:O,...T===void 0?{}:{applicationScopeId:T.host.options.applicationScopeId,endUserId:T.user}},ke=N===void 0||N.has("SearchMemory")?t.memoryFor?.(J):void 0,we=N===void 0||N.has("SearchMemory")?t.memoryPublicationFor?.(J):void 0,qe=ke!==void 0||we!==void 0;if(ke&&we)throw new Xe("validation_failed","Choose one trusted memory source per session");if(we&&(!T||we.identity.kind!=="client-managed"))throw new Xe("validation_failed","Client memory requires execution");let ze=ke?.host?.authority.identity??we?.identity;if(ze!==void 0&&(J.applicationScopeId!==void 0&&ze.applicationScopeId!==J.applicationScopeId||J.endUserId!==void 0&&ze.endUserId!==J.endUserId))throw new Xe("validation_failed","Memory source ownership mismatch");if(qe&&T?.host.options.memoryFor!==void 0)throw new Xe("validation_failed","Choose one trusted memory source per session");if(qe&&i?.persistBackgroundUsage===null)throw new Xe("validation_failed","Memory requires background usage persistence");let He=new Set,ht=[],Ot=ae=>{He.add(ae),ae.finally(()=>He.delete(ae)).catch(()=>{})},Fe,Ze,It=i?.memorySelectionPersistence?.checkpoint===void 0?void 0:vm(i.memorySelectionPersistence.checkpoint,i.memorySelectionPersistence.scope),xt,pn="",Mn=!1,Rt=!1,At=!1,E,y=new AbortController;G=()=>{Rt=!1,At=!1,E?.cancel(),E=void 0,Fe?.invalidate?.(),Ze?.invalidateSource()};let P=(ae,Re,Le,ie)=>{if(E?.key===ae)return E;G();let Me,lt=_e=>{if(_e.throwIfAborted(),Re!==_())throw new Ve("stale_generation")},Ct=async(_e,it,Ke)=>{let Et=Me;if(Et===void 0||T===void 0)throw new Ve("source_unavailable");let Bt=Et.signal;await T.refresh(Bt),lt(Bt);let Vt=V.get(_e),St=_e==="Read"?{file_path:it}:{path:it},an={id:"memory-"+xv(),name:_e,args:St,blockIndex:0};if(!T.available(_e)||!Vt||!Vt.isReadOnly)throw Object.assign(new Error("Memory resource unavailable"),{code:"EACCES"});let ln,se,Ie={...Vt,async execute(Qe,Ye){if(lt(Bt),fe(Qe)!==fe(St)||Ye.executionTarget?.kind!=="device"||!Ye.fs)throw Object.assign(new Error("Memory resource identity changed"),{code:"EACCES"});let st=performance.now(),ti=setTimeout(()=>Et.deadline.abort(),Math.max(1,Et.remainingMs));try{return ln={value:await Ke(Ye.fs)},lt(Bt),{content:[]}}catch(hn){throw se=hn,hn}finally{clearTimeout(ti),Et.remainingMs-=performance.now()-st,Et.remainingMs<=0&&Et.deadline.abort()}}},Ce=new qn;Ce.register(Ie);let Pe=new ss({registry:Ce,cwd:Le,permissionGate:pe,executionBoundary:{resolve(Qe,Ye){if(lt(Bt),!(Qe!==Ie||V.get(_e)!==Vt))return M?.resolve(Vt,Ye)}},...i?.askUser===void 0?{}:{askUser:i.askUser},...t.onDecision===void 0?{}:{onDecision:t.onDecision}}),De=(async()=>{let Qe=Pe.execute([an],{sessionId:O,turnId:an.id,toolRound:0,signal:Bt,registerOperation:Ot});for(;;){let Ye=await Qe.next();if(Ye.done){if(await T.refresh(Bt),lt(Bt),se!==void 0)throw se;if(Ye.value.aborted||Ye.value.results[0]?.isError||ln===void 0)throw Object.assign(new Error("Memory permission or execution denied"),{code:"EACCES"});return ln.value}Ye.value.t==="event"&&s?.pushBody(Ye.value.body,"tool")}})();return Ot(De),De};return E={key:ae,scope:Re,root:Le,source:{pathStyle:"posix",orgMemoryGate:()=>({inject:ie}),fs:{lstat:_e=>Ct("Read",_e,it=>it.lstat(_e)),readFilePrefix:(_e,it)=>Ct("Read",_e,Ke=>Ke.readFilePrefix(_e,it)),readdir:_e=>Ct("List",_e,it=>it.readdir(_e))}},begin(_e){Me?.deadline.abort();let it=new AbortController;return Me={signal:AbortSignal.any([_e,it.signal,y.signal]),deadline:it,remainingMs:1e4},Me.signal},cancel(){Me?.deadline.abort(),Me=void 0}},E},L=async ae=>{if(x=[],R=void 0,Rt=!1,At=!1,!T?.binding||!T.host.options.memoryFor||!T.available("Read")){G();return}let Re=_(),Le=T.binding.target,ie=T.root(),Me=T.host.options.memoryFor({applicationScopeId:T.host.options.applicationScopeId,endUserId:T.user,sessionId:O,workspaceId:Le.workspaceId,workspaceRevision:Le.workspaceRevision});if(!Me){G();return}let lt=St=>{if(typeof St!="string"||St.startsWith("/")||/[\\:\u0000-\u001f\u007f]/.test(St)||St!==""&&St.split("/").some(an=>an===""||an==="."||an===".."))throw new Ve("invalid_request",400);return Iv.join(ie,St)},Ct=lt(Me.cwd??""),Ne=Me.userDir===void 0?void 0:lt(Me.userDir),_e=Me.autoMemoryDir===void 0||Me.autoMemory===!1?void 0:lt(Me.autoMemoryDir),it=fe([Re,Ct,Ne??null,_e??null,Me.orgMemory===!0]),Ke=E?.key!==it,Et=P(it,Re,ie,Me.orgMemory===!0),Bt=Et.begin(ae),Vt=Et.source;R=Re;try{let St=await em(Ct,ie,{boundary:ie,source:Vt,signal:Bt,...Ne===void 0?{}:{userDir:Ne},..._e===void 0?{}:{autoMemory:{dir:_e}}});if(await T.refresh(Bt),Bt.throwIfAborted(),Re!==_())throw new Ve("stale_generation");if(St.warnings.length&&s?.pushControl(nn.platformWarning,{code:"memory_source_partial",message:St.warnings.join(`
|
|
34
|
+
`)}),St.segments.length&&(x=[{text:pm(St.segments),cacheable:!1}]),_e!==void 0&&T.available("List")){let an={dir:_e,roots:[Ct,ie],source:Vt};if(Fe===void 0?Fe=ms(an):Ke&&Fe.invalidate?.(an),Rt=!0,Me.recallSelector===!0){if(i?.persistBackgroundUsage===null||i?.persistBackgroundUsage!==void 0&&i.memorySelectionPersistence===void 0)throw new Ve("invalid_request",400);let ln={fileBytes:Me.recallBudgets?.fileBytes??hm,roundBytes:Me.recallBudgets?.roundBytes??gm,sessionBytes:Me.recallBudgets?.sessionBytes??ym},se=fe(ln);if(xt!==void 0&&xt!==se)throw new Ve("invalid_request",400);if(Ze===void 0){xt=se;let Ie=ps({dir:_e,source:Vt,budgets:ln,...de===void 0?{}:{budget:de},excludeFiles:["pending-anchors.md"],modelTier:()=>{let Pe=u.memoryModel??s?.modelBinding()??{client:u.client,model:u.model},De=E;return{...Pe,client:On({async*stream(Qe,Ye){let st=Ye?.signal??new AbortController().signal;if(await T.refresh(st),st.throwIfAborted(),De===void 0||De.scope!==_())throw new Ve("stale_generation");yield*Pe.client.stream(Qe,Ye)}},Pe.client)}},onUsage:(Pe,De)=>{H?.record({provider:De.provider,model:De.model,usage:Pe,purpose:"memory"})?.accepted&&(ge++,Ot(D().catch(Ye=>{ht.push(Ye)})))}}),Ce=i?.memorySelectionPersistence;try{It!==void 0&&Ce!==void 0&&Ie.restoreCheckpoint(It,Ce.scope)}catch{throw Ie.dispose(),new Ve("invalid_request",400)}Ze=Ie}else Ke&&Ze.invalidateSource({dir:_e,source:Vt});At=!0}else Ze?.invalidateSource()}else Fe?.invalidate?.(),Ze?.invalidateSource()}catch(St){if(ae.throwIfAborted(),G(),x=[],St instanceof Ve&&St.code==="invalid_request")throw St;s?.pushControl(nn.platformWarning,{code:"memory_source_unavailable",message:We(Xt.memorySourceUnavailable)})}},Z={sessionId:O,...u.pricing!==void 0?{pricing:u.pricing}:{},resolveReasoningTokens:Ox},H=n.budget!==void 0||T?.host.options.memoryFor!==void 0||qe?i?.usageSnapshot!==void 0?Rs.fromSnapshot(i.usageSnapshot,Z):new Rs(Z):void 0,de=H!==void 0?Mx(n.budget,()=>H.snapshot()):void 0,ge=0,ce=0,ve=Promise.resolve(),D=()=>(ve=ve.catch(()=>{}).then(async()=>{if(H===void 0||typeof i?.persistBackgroundUsage!="function"||ge===ce)return;let ae=ge;await i.persistBackgroundUsage(H.snapshot()),ce=ae}),ve),F=i?.onTurnEnd!==void 0||qe?ae=>{oe?.onTurnEnd(ae),i?.onTurnEnd?.(H===void 0?ae:{...ae,costSnapshot:H.snapshot()})}:void 0,$;if(T!==void 0&&M!==void 0&&u.capabilities?.tools.agent){if(V.has("Task"))throw new Pn("Task");let ae=(_e,it)=>Ke=>{let Et=()=>fe({binding:T.binding,revision:T.policy.authorizationRevision,tools:T.policy.tools}),Bt=it??Et(),Vt=()=>{if(Bt!==Et()||!T.available("Task")&&!T.available("SpawnAgent"))throw new Ve("stale_generation")};Vt();let St=new Map(Ke.replacements.map(Pe=>[Pe.replacement,Pe.original])),an=new Map,ln=new Set(T.policy.tools),se=new Set(Ke.localTools),Ie=async()=>{await T.refresh(new AbortController().signal),Vt()};for(let Pe of Ke.toolset.registry.names()){let De=Ke.toolset.registry.get(Pe),Qe=De,Ye=new Set;if(se.has(De)){an.set(De,{target:{kind:"controlled-service",executorId:"managed-service",bindingId:O,bindingRevision:"0",authorizationRevision:T.policy.authorizationRevision},assertCurrent:Ie});continue}let st;for(;st=_e.resolve(Qe,{id:"subagent-scope",name:Qe.name,args:{},blockIndex:0}),!(st!==void 0||Ye.has(Qe)||!St.has(Qe));)Ye.add(Qe),Qe=St.get(Qe);st!==void 0&&an.set(De,st)}let Ce={resolve:Pe=>{if(Ke.toolset.registry.get(Pe.name)!==Pe)return;let De=an.get(Pe)??(ln.has(Pe.name)&&T.isChildMcpTool(Ke.toolset.registry,Pe)?M.resolve(Pe,{id:"subagent-mcp",name:Pe.name,args:{},blockIndex:0}):void 0);if(De!==void 0)return{...De,assertCurrent:async()=>{Vt(),await De.assertCurrent(),Vt()}}}};return{executionBoundary:Ce,derive:ae(Ce,Bt),permissionGate:Si(ue,Ke.toolset.registry,{cwd:Q}),wrapClient:Pe=>On({async*stream(De,Qe){let Ye=Qe?.signal??new AbortController().signal;await j(Ye),T.assertModelRequestsAllowed(),Vt(),await oe?.verifyAvailable(),Ye.throwIfAborted();let st=De.tools.filter(hn=>{let Ht=Ke.toolset.registry.get(hn.name);return Ht!==void 0&&(an.has(Ht)&&(T.available(hn.name)||se.has(Ht))||ln.has(Ht.name)&&T.isChildMcpTool(Ke.toolset.registry,Ht)&&T.available(Ht.name))}),ti=Dd(Pe)?jd(De,st):{...De,tools:st};yield*Pe.stream(ti,Qe)}},Pe)}},Re=T.host.options.subagentsFor?.({applicationScopeId:T.host.options.applicationScopeId,endUserId:T.user,sessionId:O});if(Re!==void 0&&(typeof Re.onNotification!="function"||Re.background!==void 0&&(typeof Re.background.outputFile!="function"||typeof Re.background.writeFileImpl!="function")))throw new TypeError("Subagent notification and report storage callbacks are required");if(H!==void 0&&i?.persistBackgroundUsage===null&&(Re?.continuableAgents===!0||Re?.background!==void 0))throw new Xe("validation_failed",We(Xt.backgroundUsageStoreRequired));let Le=Re===void 0?void 0:async _e=>{_e.channel==="settled"&&await D(),await Re.onNotification(_e)},ie=Re?.background===void 0?void 0:new qm({emit:_e=>s?.pushBody(_e,"agent"),onNotification:Le,writeFileImpl:Re.background.writeFileImpl}),Me=()=>{let _e=s?.modelBinding()??{client:u.client,model:u.model,maxOutputTokens:p};return{client:_e.client,parentModel:_e.model,maxTokens:Math.min(t.maxTokens??Pi,e??1/0,_e.maxOutputTokens??1/0)}},lt={client:q,system:()=>b,parentModel:u.model,parentBinding:Me,maxTokens:h,sessionId:O,permissionGate:pe,mcpDiscover:_e=>T.childMcpDiscover(_e),execution:ae(M),...de===void 0?{}:{budget:de},resolveModel:u.resolveSubagentModel,...u.subagentDispatch===void 0?{}:{dispatchPolicy:u.subagentDispatch},...u.resolveSubagentContextWindow===void 0?{}:{resolveContextWindow:u.resolveSubagentContextWindow},compaction:{...g,...u.compactionManagerOptions?.timeoutMs===void 0?{}:{timeoutMs:u.compactionManagerOptions.timeoutMs}},...t.onDecision===void 0?{}:{onDecision:t.onDecision},adjudication:{enabled:()=>ue.getMode()==="default",...i?.askUser===void 0?{}:{askUser:i.askUser},...H===void 0?{}:{onQueryUsage:(_e,it)=>{H.record({provider:(it??u.model).provider,model:(it??u.model).model,usage:_e,purpose:"other"}).accepted&&ge++}},budget:()=>{if(ue.getClassifierBreakerState().tripped!=="none")return"breaker_open";if(de!==void 0&&(de.onExceeded??"block")==="block"){let _e=de.getSpend();if(de.maxTotalTokens!==void 0&&_e.totalTokens>=de.maxTotalTokens||de.maxUsd!==void 0&&_e.usdNano>=de.maxUsd*1e9)return"budget_exhausted"}return ue.tryConsumeSharedConsult()?"ok":"budget_exhausted"}},...ie===void 0?{}:{background:{runner:ie,outputFile:Re.background.outputFile}}};Ao({registry:V,toolDefs:te},lt);let Ct=V.get("Task");ne.push(Ct),M.registerBuiltin?.(Ct),X!==ne&&(N===void 0||N.has("Task"))&&X.push(Ct),N!==void 0&&!N.has("Task")&&(V.unregister("Task"),te.splice(te.findIndex(_e=>_e.name==="Task"),1));let Ne=Re?.continuableAgents!==!0?void 0:new Um({client:q,model:u.model,maxTokens:h,sessionId:O,cwd:Q,modelBinding:()=>{let _e=s?.modelBinding()??u;return{client:_e.client,model:_e.model,maxTokens:Me().maxTokens,..._e.contextWindowTokens===void 0?{}:{contextWindowTokens:_e.contextWindowTokens}}},permissionGate:pe,execution:lt.execution,...de===void 0?{}:{budget:de},...u.contextWindowTokens===void 0?{}:{contextWindowTokens:u.contextWindowTokens},emit:_e=>s?.pushBody(_e,"agent"),onNotification:Le});if(Ne!==void 0){let _e=[Fm({manager:Ne,client:q,parentModel:u.model,parentBinding:Me,system:()=>b,toolset:{registry:V,toolDefs:te},agents:vs,nestedTask:lt,adjudication:lt.adjudication,mcpDiscover:it=>T.childMcpDiscover(it)}),Lm({manager:Ne})];for(let it of _e){if(V.has(it.name))throw new Pn(it.name);ne.push(it),M.registerBuiltin?.(it),!(N!==void 0&&!N.has(it.name))&&(X!==ne&&X.push(it),V.register(it),te.push(fn(it)))}}(Ne!==void 0||ie!==void 0)&&(T.attachChildrenIdle(async()=>{let _e=()=>(ie?.size??0)>0||Ne?.list().some(Ke=>Ke.status!=="settled"||Ke.queuedMessages>0)===!0;if(_e())return!1;let it=await Promise.all([Ne?.settleResources({timeoutMs:0}),ie?.settleResources({timeoutMs:0})]);return!_e()&&it.every(Ke=>Ke===void 0||Ke.status==="completed")}),$=async()=>{let _e=await Promise.allSettled([Ne?.drain(),ie?.drain()]),it=await Promise.all([Ne?.settleResources({timeoutMs:1/0}),ie?.settleResources({timeoutMs:1/0})]),Ke=_e.flatMap(Et=>Et.status==="rejected"?[Et.reason]:[]);Ke.push(...it.flatMap(Et=>Et?.failures.map(Bt=>Bt.cause)??[]));try{await D()}catch(Et){Ke.push(Et)}if(Ke.length)throw new AggregateError(Ke,"Subagent resource cleanup failed")})}let K,he=!1,Ae,ot=ae=>{if(he)throw new Error("Memory is closed");oe=Ky({config:ae,sessionId:O,...de===void 0?{}:{budget:de},modelTier:()=>(T?.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:Le=>{H?.record({provider:Le.provider??u.model.provider,model:Le.model,usage:Le.usage,purpose:"memory"})?.accepted&&(ge++,Ot(D().catch(Me=>{ht.push(Me)})))}});let Re=oe.searchTool;if(V.has(Re.name))throw new Pn(Re.name);return V.register(Re),te.push(fn(Re)),X.push(Re),M?.registerBuiltin?.(Re),s&&qr(s,oe),Ae&&(oe.onTurnStart(Ae),Ae=void 0),oe.start(),oe};ke&&ot(ke);let $e=we===void 0?void 0:{capability:()=>!he&&we.enabled()&&T?.memoryPublicationSupported()===!0,prepare:async ae=>{if(ae.throwIfAborted(),he||!we.enabled())throw new Error("Memory source unavailable");return oe?(await oe.verifyAvailable(),oe):(K??=(async()=>{let Re=AbortSignal.any([ae,y.signal]);await T.refresh(Re),Re.throwIfAborted();let Le=await T.createMemoryPublicationStore(we.identity,{signal:y.signal,enabled:we.enabled}),ie=await ja.open({identity:we.identity,store:Le,mode:we.mode,assertCurrent:()=>{if(he||!we.enabled()||!T.memoryPublicationAvailable())throw new Error("Memory source unavailable")},...we.minimumDeletionGeneration?{minimumDeletionGeneration:we.minimumDeletionGeneration}:{}});Re.throwIfAborted();let Me=await ie.createHost({...we.provenance?{provenance:we.provenance}:{}}),lt=Ct=>{if(Rv.isAbsolute(Ct)||Ct.split(/[\\/]/).some(Ne=>Ne===".."||Ne===""))throw new Error("Invalid promotion target");return Rv.join(Me.rootDir,Ct)};return Re.throwIfAborted(),ot({kind:"client-managed",domain:we.identity.domain,host:Me,management:ie,rootDir:Me.rootDir,memoryDir:Me.memoryDir,enabled:we.enabled,balance:we.balance,...we.promotion?{projectAgentsPath:lt(we.promotion.projectFile),userAgentsPath:lt(we.promotion.userFile)}:{},...we.extraction?{extraction:we.extraction}:{},...we.recallSelector===void 0?{}:{recallSelector:we.recallSelector},...we.onObservation?{onObservation:we.onObservation}:{}})})(),K)}};qe&&T?.bindMemorySearch(()=>oe!==void 0&&oe.status().enabled);let Ge=new Zn({client:q,executor:ee,...$===void 0&&T?.host.options.memoryFor===void 0&&!qe&&l===void 0?{}:{onClosed:async()=>{let ae=[];l?.stop(),he=!0,y.abort();let Re=$?.().catch(Me=>{ae.push(Me)});Fe?.dispose?.(),Ze?.dispose();try{await K?.catch(()=>{}),await oe?.close()}catch(Me){ae.push(Me)}let Le=await Promise.all([Fe?.settleResources?.({timeoutMs:1/0}),Ze?.settleResources?.({timeoutMs:1/0})]);for(;He.size;)await Promise.allSettled([...He]);await Re;let ie=[...ae,...Le.flatMap(Me=>Me?.failures.map(lt=>lt.cause)??[])];try{await D()}catch(Me){ie.push(Me)}try{await l?.close()}catch(Me){ie.push(Me)}if(ie.push(...ht),ie.length)throw new AggregateError(ie,"Memory resource cleanup failed")}},system:b,applicationPromptInfo:A,...d?.queryHooks===void 0?{}:{queryHooks:ae=>l.queryHooks(ae)},...i?.attachmentPersistence===void 0?{}:{attachmentPersistence:i.attachmentPersistence},...i?.memorySelectionPersistence===void 0?{}:{getMemorySelectionCheckpoint:()=>Ze?.snapshotCheckpoint(i.memorySelectionPersistence.scope)??It},...u.refreshApplicationPrompt!==void 0||T!==void 0||qe||t.systemFor!==void 0?{prepareSystem:async ae=>{let Re=u.refreshApplicationPrompt===void 0?u:await u.refreshApplicationPrompt(ae);if(t.systemFor!==void 0){let Le=await l.system(ie=>t.systemFor(Object.freeze({...a}),ie),ae);ae.throwIfAborted(),m=(Le.system??t.system)?.map(ie=>({...ie})),v=(Le.systemAppend??t.systemAppend??[]).map(ie=>({...ie}))}return await j(ae),await L(ae),await $e?.prepare(ae),oe!==void 0&&(x=await oe.prepare(ae)),b=C(Re),b}}:{},tools:te,model:u.model,cwd:Q,...u.contextWindowTokens!==void 0?{contextWindowTokens:u.contextWindowTokens}:{},...p!==void 0?{maxOutputTokens:p}:{},...t.maxTokens!==void 0?{maxTokens:t.maxTokens}:{},sessionId:O,...de!==void 0?{budget:de}:{},...H!==void 0?{runtimeCostSnapshot:()=>H.snapshot(),onEvent:ae=>{H.consume(ae)?.accepted&&(ge++,ae.type==="cost.usage.updated"&&ae.purpose==="compaction"&&typeof i?.persistBackgroundUsage=="function"&&s?.retainCostPersistence(D()))}}:{},...i?.initialHistory!==void 0?{initialHistory:i.initialHistory}:{},...i?.initialSeq!==void 0?{initialSeq:i.initialSeq}:{},maxTurnsPerQuery:t.maxTurnsPerQuery??Pf,...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:qe?{...g,observer:{...g.observer,onCompactionFinished:ae=>{g.observer?.onCompactionFinished?.(ae),oe?.compactionObserver.onCompactionFinished?.(ae)}}}:g,...u.compactionManagerOptions!==void 0?{compactionManagerOptions:u.compactionManagerOptions}:{},reminders:Hf({todoStore:B,...T?.host.options.memoryFor===void 0&&!qe?{}:{prepareMemoryRecalls:async ae=>{await j(ae),await oe?.prepareReminders(ae),Mn&&(Mn=!1,At&&Ze?.prefetch(pn)),Rt&&(await Fe?.prepareReminders?.(ae),await j(ae))},drainMemoryRecalls:()=>[...oe?.drainReminders()??[],...Rt?Fe?.drainReminderEntries?.()??[]:[]],drainMemorySelections:()=>[...oe?.drainSelections()??[],...At?Ze?.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}:{},...F!==void 0?{onTurnEnd:F}:{},...t.runQueryImpl!==void 0?{runQueryImpl:t.runQueryImpl}:{},...U!==void 0||T?.host.options.memoryFor!==void 0||qe?{onTurnStart:(ae,Re)=>{pn=Re.join(`
|
|
35
|
+
`),Mn=!0,oe?oe.onTurnStart(Re):qe&&(Ae=[...Re]),U?.transcript.noteTurn(Re)},onInputsConsumed:ae=>{U?.transcript.noteInput(ae),At&&Ze?.supplement?.(ae.join(`
|
|
36
|
+
`))}}:{}});return s=Ge,Ge.bindModelClientWrapper(W,u.client),oe!==void 0&&qr(Ge,oe),$e&&fd(Ge,$e),(qe||T!==void 0)&&Ge.bindModelRequestGuard(()=>{T?.assertModelRequestsAllowed(),oe?.assertAvailable()}),qe&&Ge.bindConfigurationReadiness(async()=>K!==void 0&&oe===void 0?!1:await oe?.readyForModelChange()??!0),i?.attachmentPersistence?.verifySource===!0&&T!==void 0&&T.attachAttachmentSourceConfirmation(()=>Ge.confirmAttachmentSource(async ae=>(await T.refresh(ae),ae.throwIfAborted(),k=_(),G(),T.attachmentSource))),S!==void 0&&w.length>0&&Ge.pushControl(nn.platformWarning,{code:"profile_narrowed_capabilities",message:We(Xt.profileNarrowedCapabilities,{profile:S.name,dropped:w.join(", ")}),dropped:w}),Ge.bindCwdRebinder(ae=>ee.withCwd(ae,{permissionGate:Si(ue,V,{cwd:ae})})),Ge}}}var mf={"mobile-default":Wc()},pf=30,hf=36e5,uf=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}}#p(e){let n=this.#f.then(()=>(this.owner?.assertCurrent(),e()));return this.#f=n.then(()=>{},()=>{}),n}#m(e){return this.owner===void 0?e():this.owner.write(e)}checkpoint(e={}){return this.#p(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:rr(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(rr)}}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.#p(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 un&&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"};Oo(n,this),await this.owner?.beginTurn();let c;n.checkpoint!==!1&&(c=(await this.#k("pre_restore",this.#t.historySnapshot().messages)).checkpointId),Oo(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(kt.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.#p(async()=>{let n=this.#i?.checkpoints;return n===void 0?"checkpoints_not_wired":await this.#m(()=>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 un&&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:ls(i)}}importCheckpoint(e,n={}){return this.#p(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=Oo(n,this),s;try{s=us(e,{sessionId:this.sessionId,checkpointId:o?.checkpointId??cs(i.now()),createdAt:o?.createdAt??new Date(i.now()).toISOString(),...n.label!==void 0?{label:n.label}:{}})}catch(d){if(d instanceof un&&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(Oo(n,this),d){let c=us(ls(d),{sessionId:this.sessionId,checkpointId:o.checkpointId,createdAt:o.createdAt});if(Nt(c)!==Nt(s))throw new Error("Archive checkpoint import conflict");return{status:"imported",checkpoint:rr(d)}}}let a=await this.#m(()=>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:rr(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.#p(()=>this.#k("pre_compaction",n.messages,o))).checkpointId}}}async#k(e,n,i){let o=this.#i,s=o.checkpoints,a=await this.#m(()=>s.store.put(this.endUserId,wv({checkpointId:cs(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 Nx(t,e){let n=Date.parse(t);return Number.isNaN(n)?e:n}function Ux(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 Tv(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 Po(t.execution),i=t.transactionalExecution===void 0?void 0:new Po(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??mf,a=t.now??Date.now,d=t.store,c=Nn(t.logger),l=Ln(),f=(S,w,T,_)=>{if((S==="commit"?l.storeCommitErrors:l.storeCreateErrors).inc(),_!==void 0)try{_.status()!=="ended"&&_.pushBody({type:"turn.error",scope:"server.persistence",message:We(S==="commit"?kt.storeCommitFailed:kt.storeCreateFailed),recoverable:!0,errorKind:S==="commit"?"store_commit_failed":"store_create_failed"},"server")}catch{}try{if(t.onStoreError!==void 0){t.onStoreError(w,T);return}console.error(JSON.stringify({level:"error",event:S==="commit"?at.storeCommitFailed:at.storeCreateFailed,sessionId:w,message:jn(T)}))}catch{}},u=new Set,p=S=>{let w=S.then(()=>{},()=>{});u.add(w),w.then(()=>u.delete(w))},h=async()=>{let S=0;for(;u.size>0;){let w=[...u];S+=w.length,await Promise.all(w)}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 g,m=t.assembleEndUserModel,v;if(t.platform!==void 0){let S=t.platform,w=Mr({governor:S.governor,fetchImpl:S.fetchImpl}),T=ed({apiBaseUrl:S.apiBaseUrl,appId:S.appId,appKey:S.appKey,...S.ttlSeconds!==void 0?{ttlSeconds:S.ttlSeconds}:{},...w!==void 0?{fetchImpl:w}:{},now:a,...S.tokenMinter??{}});t.cacheHost?.connectPlatform({appId:S.appId,apiBaseUrl:S.apiBaseUrl,tokenFor:V=>T.tokenFor(V),...w?{fetchImpl:w}:{}});let _=S.bundleCacheTtlMs??wi,G=S.bundleCache??(_>0?Qi({ttlMs:_,...w!==void 0?{fetchImpl:w}:{},now:a}):void 0);m=gy({minter:T,apiBaseUrl:S.apiBaseUrl,appId:S.appId,...w!==void 0?{fetchImpl:w}:{},...S.onPlatformWarning!==void 0?{onPlatformWarning:S.onPlatformWarning}:{},...t.logger!==void 0?{logger:t.logger}:{},now:a,...G!==void 0?{bundleCache:G}:{bundleCacheTtlMs:0}},{...e===void 0?{}:{remoteExecution:!0},...t.cacheHost!==void 0?{gatewayCache:V=>t.cacheHost.assembler(V),refreshCacheConfiguration:(V,te)=>t.cacheHost.refreshConfiguration(V.endUserId,V.sessionId,te),cacheConfigurationRefreshRequired:V=>t.cacheHost.configurationRefreshRequired(V.endUserId,V.sessionId),confirmCacheConfiguration:(V,te)=>t.cacheHost.confirmConfiguration(V.endUserId,V.sessionId,te),archivedRuntime:V=>t.cacheHost.archivedRuntime(V.endUserId,V.sessionId,V.previous)}:t.gatewayCache===void 0?{}:{gatewayCache:t.gatewayCache}}),v=()=>({tokenMinter:T.stats(),...G!==void 0?{bundleCache:G.stats()}:{}}),g=Rd({...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 g=t.factory;m!==void 0&&(m=td(m));let b=Lx(t.checkpoints,d);d!==void 0&&t.cacheHost?.connectStore(d);let x=Fx(t.sessions?.retention),R=new Map,A=(S,w)=>{if(w===void 0)return;let T=Wt(S);w.sessionRetentionDays!==void 0?R.set(T,w.sessionRetentionDays):R.delete(T)},C,B=async(S={})=>{if(x===void 0||d?.sweepRetention===void 0)return;let w=a();if(!S.force&&C!==void 0&&w-C<x.sweepIntervalMs)return;C=w;let T=x.policy,_=await d.sweepRetention({policy:T,policyFor:V=>({...T,maxAgeDays:R.get(V)??T.maxAgeDays}),now:w,...S.activeSessionIds!==void 0?{keep:S.activeSessionIds}:{}}),G=t.checkpoints?.dir;if(G!==void 0)for(let{endUserKey:V,sessionId:te}of _.deleted)await Dx(jx.join(G,"agent-checkpoints",V,te),{recursive:!0,force:!0}).catch(re=>_.failures.push({endUserKey:V,sessionId:te,message:`checkpoints: ${jn(re)}`}));return(_.deleted.length>0||_.failures.length>0)&&t.logger?.log?.("info",at.sessionRetentionSwept,{scanned:_.scanned,deleted:_.deleted.length,failures:_.failures.length,byReason:_.deleted.reduce((V,te)=>({...V,[te.reason]:(V[te.reason]??0)+1}),{})}),_},Y=!1,ne={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"),Y&&S.push("memory-lifecycle-v1"),S},...n!==void 0?{execution:n}:{},...i!==void 0?{transactionalExecution:i}:{},async create(S){let w,T,_,G,V,te=Q=>{_===void 0&&(_=setInterval(()=>{Q.renew().catch(U=>{V??=U,G?.close(),q?.close()})},Math.max(250,Math.floor(Q.leaseMs/3))),_.unref())},re=iy(ne,S),M,k,j=re===void 0,W,q;try{if(o!==void 0&&(S.prompt!==void 0||S.cwd!==void 0))throw new Xe("validation_failed",We(Xt.executionInitializeRequired));re?.assertCurrent();let Q=S.tools,U;if(S.capabilitiesProfile!==void 0){let se=s[S.capabilitiesProfile];if(se===void 0)throw new Xe("validation_failed",We(Xt.unknownCapabilitiesProfile,{profile:S.capabilitiesProfile,available:Object.keys(s).join(", ")}));Q=S.tools!==void 0?S.tools.filter(Ie=>se.includes(Ie)):[...se],U={name:S.capabilitiesProfile,tools:se}}let ue=o===void 0?await zx(S,t):"/workspace/unbound",pe,oe,ee,O,J=S.model,ke=S.thinking,we=!1,qe,ze,He,ht,Ot,Fe=!1,Ze=a(),It,xt,pn,Mn,Rt;if(S.resume!==void 0){if(d===void 0)throw new Xe("resume_unavailable","session store is not wired");let se;try{W=t.cacheHost?.beginSessionCreation(S.endUserId,S.resume.sessionId),w=await d.claimOwner?.(S.endUserId,S.resume.sessionId),w!==void 0&&te(w);let Pe=1e3;for(let De=0;;De+=1)try{se=await d.get(S.endUserId,S.resume.sessionId);break}catch(Qe){if(!(Qe instanceof un)||Qe.code!=="SESSION_LOCKED"||De>=Pe-1)throw Qe;await new Promise(Ye=>setTimeout(Ye,5))}re?.assertCurrent()}catch(Pe){throw Pe instanceof et?new Xe("store_corrupted",Pe.message):Pe}if(se===null)throw new Xe("session_not_found",`session not found in store: ${S.resume.sessionId}`);if(se.ownershipRequired&&w===void 0)throw new Xe("resume_unavailable","Session requires durable ownership");if(ee=S.resume.sessionId,k=se.meta,we=!0,O=se.configuration,O!==void 0&&(J=O.model??void 0,ke=O.thinking??void 0),T=se.runtimeCheckpoint,T!==void 0&&(d.runtimeCheckpoints!==!0||w===void 0||S.prompt!==void 0))throw new Xe("resume_unavailable","Runtime checkpoint requires the original trusted Store");let Ie=T===void 0?ds(se.messages):{messages:se.messages,synthesizedResults:0,droppedMessages:0};qe=Ie.messages,Fe=Ie.synthesizedResults>0||Ie.droppedMessages>0||se.recovery!==void 0,se.recovery!==void 0&&(oe={code:"session_recovery_degraded",message:We(kt.recoveryDegraded,{dropped:se.recovery.droppedMessages,retained:se.recovery.recoveredMessages,synthesized:se.recovery.synthesizedToolResults})}),ze=se.usageSnapshot,He=se.attachmentCheckpoint,d.attachmentSourceCheckpoints===!0&&(ht=se.attachmentSourceCheckpoint),Ot=se.memorySelectionCheckpoint,Ze=Nx(se.meta.createdAt,Ze),It=se.meta.title,xt=se.meta.platformSessionId,pn=se.meta.retentionDays,Rt=Ux(se.meta,a());let Ce=o!==void 0?{cwd:"/workspace/unbound",warning:void 0}:await Gx(se.meta.cwd,ue,{mode:t.cwdOnResume??(t.cwdPolicy!==void 0?"stored":"current"),policy:ff(t,S.endUserId)});ue=Ce.cwd,Fe||=o!==void 0&&(o.options.readAttachmentSource===void 0||d.attachmentSourceCheckpoints!==!0)||o===void 0&&se.meta.cwd!==void 0&&se.meta.cwd!==ue,pe=Ce.warning}else if(S.fork!==void 0){let se=await Wx({init:S,fork:S.fork,checkpointStore:b,store:d,cwd:ue});ee=se.sessionId,qe=se.history,It=se.title,Mn={sourceSessionId:S.fork.sessionId,checkpointId:S.fork.checkpointId}}else ee=S.sessionId??Id();let At=!1;d?.claimOwner!==void 0&&w===void 0&&(re?.mode==="fresh"?(re.assertCurrent(),await Tl(d,S.endUserId,{sessionId:ee,cwd:ue}),re.assertCurrent(),At=!0):await d.create(S.endUserId,{sessionId:ee,cwd:ue}),w=await d.claimOwner(S.endUserId,ee),te(w)),o!==void 0&&(ue="/workspace/unbound");let E=new Dr({cwd:ue,...t.permissionTimeoutMs!==void 0?{permissionTimeoutMs:t.permissionTimeoutMs}:{},...t.questionGraceMs!==void 0?{questionGraceMs:t.questionGraceMs}:{},now:a,onPermissionReceipt:se=>{c(se.reason!==void 0?"warn":"info",at.bridgePermissionReceipt,{sessionId:ee,requestId:se.requestId,verdict:se.verdict,...se.reason!==void 0?{reason:se.reason}:{}})}}),y=[];if(S.clientTools!==void 0){let se=new Set;for(let Ie of S.clientTools){if(se.has(Ie.name))throw new Xe("validation_failed",We(Xt.clientToolConflict,{name:Ie.name}));se.add(Ie.name),y.push(kd(Ie,E,a,o===void 0?void 0:async(Ce,Pe)=>{if(q===void 0)throw new Error("Execution session is not ready");return q.invokeClientTool(Ie,Ce,Pe)}))}}let P,L,Z=!1,H=[],de=!1,ge,ce;if(m!==void 0){we&&xt!==void 0&&t.cacheHost!==void 0&&await t.cacheHost.recoverConfiguration(S.endUserId,ee,xt,()=>{w?.assertCurrent(),re?.assertCurrent()}),L=t.cacheHost?.selectRuntime(S.endUserId,ee,xt,we)??xt??Oi();let se=t.cacheHost?.prepareArchivedRecovery(S.endUserId,ee,L);se!==void 0&&await se;let Ie=await m({endUserId:S.endUserId,sessionId:ee,...J!==void 0?{model:J}:{},onWarning:Ce=>{de?E.emitPlatformWarning(Ce):H.push(Ce)},platformSessionId:L,onSessionArchived:(Ce,Pe)=>{if(Ce!==L)throw new Error("Platform runtime changed during assembly");return Z=!0,L=Pe??Oi(),L}});P=(Ce,Pe)=>{let De=Ie(Ce,Pe);return ce={...De.readPlatformCatalog===void 0?{}:{readPlatformCatalog:De.readPlatformCatalog},...De.readPlatformUsage===void 0?{}:{readPlatformUsage:De.readPlatformUsage}},ge={capabilities:De.capabilities,platformTools:De.platformTools,...De.sessionRetentionDays!==void 0?{sessionRetentionDays:De.sessionRetentionDays}:{}},De}}let ve=!1,D=!1,F=!1,$=!0,K=0,he=!1,Ae=null,ot=null,$e,Ge=new Set,ae=(se,Ie,Ce,Pe,De)=>{if(d===void 0)return;if(F)return f("commit",ee,new Error("Archive Store completion remains unobservable"),ie),Promise.resolve(!1);let Qe=++K,Ye=he?{commitId:Pe?.commitId??Id(),observation:Pe?.observation??en(ee,se,ie.archiveHistoryObservation().localHistoryGeneration)}:null,st=Ie||ve;ve=st;let ti;he&&(ot=null);try{let gt=Ce??ie?.currentCostSnapshot?.();ti=d.commit(S.endUserId,ee,se,{...w===void 0?{}:{owner:w},rewritten:st,lastSeq:ie.lastSeq(),...gt!==void 0?{usageSnapshot:xs(gt)}:{},...d.attachmentCheckpoints===!0?{attachmentCheckpoint:De===void 0?ie.attachmentCheckpoint?.(se,Ie):De.attachmentCheckpoint}:{},...d.attachmentSourceCheckpoints===!0&&o?.options.readAttachmentSource!==void 0?{attachmentSourceCheckpoint:Ie?null:De===void 0?ie.attachmentSourceCheckpoint?.(se):De.attachmentSourceCheckpoint}:{},...d.memorySelectionCheckpoints===!0?{memorySelectionCheckpoint:De===void 0?ie.memorySelectionCheckpoint?.():De.memorySelectionCheckpoint}:{}})}catch(gt){return he&&(F=!0),ve=!0,D=!0,f("commit",ee,gt,ie),Promise.resolve(!1)}let hn=ti;if(he)try{ot=Yc({...Ye,storeIdentity:d,original:ti}),hn=ot.completion,Pe?.onReceipt(ot)}catch(gt){return F=!0,ve=!0,D=!0,f("commit",ee,gt,ie),Promise.resolve(!1)}let Ht=hn.then(()=>{let gt=Qe===K;return(st||!gt)&&(ve=!gt,D=!gt),Ye!==null&&Qe===K&&(Ae=Ye),!0},gt=>(ve=!0,D=!0,f("commit",ee,gt,ie),!1));return Ge.add(Ht),Ht.then(()=>Ge.delete(Ht),()=>Ge.delete(Ht)),p(Ht),Ht};if(q=o?.open(S.endUserId,ee,E,Q),w!==void 0&&q?.bindOwner(w),q!==void 0)for(let se=0;se<y.length;se++)q.registerClientTool(S.clientTools[se],y[se]);let Re=t.sessionCapture?.({endUserId:S.endUserId,sessionId:ee}),Le=t.contextMaterials?.({endUserId:S.endUserId,sessionId:ee}),ie,Me=Promise.resolve(),lt=async se=>{await ie.settleResources();let Ie=Cn(ie);if(Ie!==void 0){let Ce=await Ie.settleResources({timeoutMs:1/0});if(Ce.some(Pe=>Pe.status!=="completed"))throw new AggregateError(Ce.flatMap(Pe=>Pe.failures.map(De=>De.cause)),"Memory resources did not settle")}await Promise.all([...Ge]),await d?.flush?.(),await w?.checkpoint(()=>se?.()!==!1&&(ie.status()==="idle"||ie.status()==="ended")&&!ve&&!D&&(q?.ownershipStable()??!0)),se?.()!==!1&&T!==void 0&&O===void 0&&t.configuration!==void 0&&w!==void 0&&ie.status()==="idle"&&d?.initializeConfiguration!==void 0&&d.inspectConfiguration!==void 0&&d.commitConfiguration!==void 0&&(O=await d.initializeConfiguration(S.endUserId,ee,{model:J??null,thinking:ie.thinking()??null},w))};try{if(ie=g.create({...J!==void 0?{model:J}:{},...S.profile!==void 0?{profile:S.profile}:{},...S.labels!==void 0?{labels:S.labels}:{},...S.budget!==void 0?{budget:S.budget}:{},...Q!==void 0?{tools:[...Q]}:{},...ke!==void 0?{thinking:ke}:{}},{sessionId:ee,...t.platform===void 0?{}:{trustedScope:{applicationScopeId:t.platform.appId,endUserId:S.endUserId,sessionId:ee}},...O===void 0?{}:{configurationThinking:O.thinking},...t.platform?.memoryFor===void 0&&t.platform?.memoryPublicationFor===void 0?{}:{memoryScope:{sessionId:ee,applicationScopeId:t.platform.appId,endUserId:S.endUserId}},...q!==void 0?{execution:q}:{},cwd:ue,...U!==void 0?{capabilityProfile:U}:{},...P!==void 0?{assembleModel:P}:{},...qe!==void 0?{initialHistory:qe}:{},...d?.attachmentCheckpoints===!0?{attachmentPersistence:{scope:fe({application:o?.options.applicationScopeId??t.platform?.appId??null,endUserId:S.endUserId,sessionId:ee}),...He===void 0?{}:{checkpoint:He},...Fe?{invalidateReferences:!0}:{},...o?.options.readAttachmentSource!==void 0&&d.attachmentSourceCheckpoints===!0?{verifySource:!0,...ht===void 0?{}:{sourceCheckpoint:ht}}:{}}}:{},...d?.memorySelectionCheckpoints===!0?{memorySelectionPersistence:{scope:fe({application:o?.options.applicationScopeId??t.platform?.appId??null,endUserId:S.endUserId,sessionId:ee}),...Ot===void 0?{}:{checkpoint:Ot}}}:{},...Rt!==void 0?{initialSeq:Rt}:{},...ze!==void 0&&(T!==void 0||S.budget!==void 0||o?.options.memoryFor!==void 0||t.platform?.memoryFor!==void 0||t.platform?.memoryPublicationFor!==void 0)?{usageSnapshot:ze.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:se=>{let Ie;try{Ie=d.recordUsageSnapshot(S.endUserId,ee,xs(se),w)}catch(Ce){Ie=Promise.reject(Ce)}return p(Ie.catch(Ce=>{f("commit",ee,Ce,ie)})),Ie}},...y.length>0?{sessionTools:y}:{},promptChannel:E.createPromptChannel(),askUser:E.createAskUser(),onTurnEnd:se=>{Ke.title$=Ni(se.history)??Ke.title$,ie.ownsArchiveHistoryCommit?.()===!0?$e=se:ae(se.history,se.rewritten,se.costSnapshot,void 0,se),w!==void 0&&(!se.aborted||se.abortReason==="budget_exceeded")&&(Me=Me.then(()=>lt(se.isCurrentTurn)),Me.catch(Ie=>f("commit",ee,Ie,ie)))}}),G=ie,V!==void 0)throw ie.close(),V}catch(se){throw se instanceof Pn?new Xe("validation_failed",We(Xt.clientToolConflict,{name:se.toolName})):se}w!==void 0&&ie.bindOwner(w),re!==void 0&&(M=ie,Qa(ie),re.assertCurrent()),A(S.endUserId,ge),E.bindEmitter((se,Ie)=>ie.pushControl(se,Ie)),de=!0,Mn!==void 0&&ie.pushBody({type:"session.forked",...Mn,sessionId:ee},"server"),pe!==void 0&&H.push(pe),oe!==void 0&&H.push(oe),ze!==void 0&&(S.budget!==void 0||o?.options.memoryFor!==void 0||t.platform?.memoryFor!==void 0||t.platform?.memoryPublicationFor!==void 0)&&ze.staleMessages>0&&H.push({code:"usage_snapshot_stale",message:We(kt.usageSnapshotStale,{count:ze.staleMessages})});for(let se of H)E.emitPlatformWarning(se);H.length=0;let Ct=$x(ge),Ne=Vx(ge,Ze),_e=t.configuration!==void 0&&w!==void 0&&d?.initializeConfiguration!==void 0&&d.inspectConfiguration!==void 0&&d.commitConfiguration!==void 0&&typeof ie.configure=="function";_e&&(T===void 0||O!==void 0)&&(O=await d.initializeConfiguration(S.endUserId,ee,{model:J??null,thinking:ie.thinking()??null},w));let it=async(se,Ie={})=>{if(!_e)return{status:"rejected",reason:"unsupported"};let Ce=ao(se);if(!Ce)return{status:"rejected",reason:"invalid_configuration"};let Pe=ie.configurationRejection();return Pe||(await Me,await Promise.all([...Ge]),ie.configure(async(De,Qe)=>{let Ye=await d.inspectConfiguration(S.endUserId,ee,Ce,w);if(Ye.status!=="ready")return Ye;let st;if(Ce.changes.model!==void 0){try{if(t.configuration?.resolveModel!==void 0)st=await t.configuration.resolveModel({endUserId:S.endUserId,sessionId:ee,model:Ce.changes.model,signal:Qe});else if(P!==void 0){let gt=P(Ce.changes.model,Ad=>{let yf=Wr(Ad);yf&&ie.pushBody(yf,"provider")}),kn=t.platform?.maxOutputTokens;st={client:gt.client,model:gt.model,...gt.contextWindowTokens===void 0?{}:{contextWindowTokens:gt.contextWindowTokens},...kn===void 0&>.maxOutputTokens===void 0?{}:{maxOutputTokens:Math.min(kn??1/0,gt.maxOutputTokens??1/0)}}}else return{status:"rejected",reason:"unsupported"}}catch(gt){let kn=gt instanceof yt&>.code==="assembly_failed"?gt.cause:gt;if(kn instanceof up&&kn.alias===Ce.changes.model||kn instanceof fp&&Ce.changes.model.includes("/")&&kn.ref===Ce.changes.model)return{status:"rejected",reason:"invalid_configuration"};throw gt}st!==void 0&&t.platform?.maxOutputTokens!==void 0&&(st={...st,maxOutputTokens:Math.min(t.platform.maxOutputTokens,st.maxOutputTokens??1/0)})}Qe.throwIfAborted(),await Ie.beforeCommit?.(),Qe.throwIfAborted();let ti=Object.hasOwn(Ce.changes,"thinking")?Ce.changes.thinking:Ye.configuration.thinking,hn=De(st,ti??void 0);if(hn.status==="rejected")return hn;let Ht;try{Ht=await d.commitConfiguration(S.endUserId,ee,Ce,w,()=>!Qe.aborted&&hn.isCurrent())}catch(gt){let kn;try{kn=await d.inspectConfiguration(S.endUserId,ee,Ce,w)}catch(Ad){throw ie.close(),new AggregateError([gt,Ad],"Configuration outcome is unknown")}if(kn.status!=="replayed")throw kn.status!=="ready"&&ie.close(),gt;Ht=kn}return(Ht.status==="changed"||Ht.status==="replayed")&&(O=Ht.configuration,hn.publish()),Ht},Ie))},Ke=new uf({configuration:()=>O,configure:it,...w===void 0?{}:{owner:w,checkpointOwner:lt,settleOwner:async()=>{try{await Me,await Promise.all([...Ge]),await d?.flush?.();try{await w.release()}catch{}}finally{_!==void 0&&(clearInterval(_),_=void 0)}}},sessionId:ee,endUserId:S.endUserId,createdAt:Ze,driver:ie,bridge:E,...It!==void 0?{initialTitle:It}:{},...Ct!==void 0?{platformAudio:Ct}:{},...Ne!==void 0?{media:Ne}:{},persistence:Kx({checkpointStore:b,checkpointsOptions:t.checkpoints,cwd:ue,now:a,commitRewritten:se=>ae(se,!0)}),resolveCwd:(se,Ie)=>{let Ce=ff(t,S.endUserId);return Lr({requested:se,fallback:Ie,...Ce!==void 0?{policy:Ce}:{}})},...d?.recordCwdChange!==void 0?{onCwdChanged:se=>{p(d.recordCwdChange.call(d,S.endUserId,ee,se,w).catch(Ie=>f("commit",ee,Ie,ie)))}}:{}});dv(Ke,()=>ce);let Et=Cn(ie);Et&&qr(Ke,Et);let Bt=nr(ie);Bt&&fd(Ke,{capability:()=>Bt.capability(),async prepare(se){let Ie=await Bt.prepare(se);return qr(Ke,Ie),Ie}}),(Et?.management!==void 0||Bt!==void 0)&&(Y=!0,Vy(Ke,async(se,Ie={})=>{if(w!==void 0&&w.assertIdle===void 0)throw new ct("unsupported_capability");let Ce=ie.configurationRejection();if(Ce)throw new ct(Ce.reason==="turn_running"?"busy":"source_unavailable");await Me,await Promise.all([...Ge]);let Pe=await ie.configure(async(De,Qe)=>{try{await w?.assertIdle?.()}catch(st){throw st instanceof Jt&&["reconciliation_required","owner_busy","owner_stale"].includes(st.code)?Object.assign(new ct(st.code==="owner_stale"?"stale_generation":"busy"),{cause:st}):st}Qe.throwIfAborted();let Ye=Bt===void 0?Cn(ie):await nr(Ke).prepare(Qe);if(Ye?.management===void 0)throw new ct("unsupported_capability");return Qe.throwIfAborted(),Ye.executeManagedCommand(se,{...Ie,signal:Qe})},Ie);if(Pe.status==="rejected")throw new ct(Pe.reason==="turn_running"?"busy":"source_unavailable");return Pe}));let Vt=Ke.beforeCompactHook();if(Vt!==void 0&&ie.bindBeforeCompact(Vt),d!==void 0&&(typeof ie.bindArchiveSourceReadCheck=="function"&&ie.bindArchiveSourceReadCheck(()=>Ge.size===0&&$&&!D&&!ve&&!F),typeof ie.bindArchivePersistenceBarrier=="function"&&ie.bindArchivePersistenceBarrier(async()=>{for(;Ge.size>0;)await Promise.all([...Ge]);if(!$||D||ve)throw new Error("Archive binding requires confirmed legacy history")}),typeof ie.bindArchiveHistoryPort=="function"&&typeof ie.archiveHistoryObservation=="function"&&typeof ie.bindArchivePersistenceBarrier=="function")){let se=Object.freeze({storeIdentity:d,latestCommit:()=>ot,read(){let Ie=ie.archiveHistoryObservation(),Ce=Ae,Pe=Ge.size===0&&$&&!D&&!ve&&Ce!==null&&Ce.observation.localHistoryGeneration===Ie.localHistoryGeneration&&Ce.observation.sourceSnapshotDigest===Ie.sourceSnapshotDigest;return Object.freeze({observation:Ie,confirmedCommit:Pe?Object.freeze({commitId:Ce.commitId,observation:Object.freeze({...Ce.observation})}):null})}});typeof ie.bindArchiveHistoryCommit=="function"&&ie.bindArchiveHistoryCommit(Ie=>{if(!he)throw new Error("Archive original Store observation is not enabled");let Ce,Pe=$e?.history===Ie.history?$e.costSnapshot:void 0,De=$e?.history===Ie.history?$e:void 0;$e=void 0;let Qe=ae(Ie.history,Ie.rewritten,Pe,{commitId:Ie.commitId,observation:Ie.observation,onReceipt:st=>{Ce=st}},De);if(Ce===void 0||Qe===void 0)throw new Error("Archive original Store receipt unavailable");let Ye=Qe.then(st=>{if(!st)throw new Error("Archive original Store failed")});return Ye.catch(()=>{}),{receipt:Ce,completion:Ye}}),ie.bindArchiveHistoryPort(se,async()=>{if(he&&se.read().confirmedCommit!==null)return;if(he=!0,!await ae(ie.historySnapshot().messages,!0)||se.read().confirmedCommit===null)throw new Error("Archive binding requires confirmed legacy history")},{detach(){if(Ge.size!==0||!$||D||ve||F)throw new Error("Archive original Store remains unsettled");he=!1},assertDetached(){if(he||$e!==void 0)throw new Error("Archive original Store responsibility was not released")}}),typeof ie.bindArchiveColdHistory=="function"&&ie.bindArchiveColdHistory(Ie=>{let Ce=Op(Ie,{storeIdentity:d,sessionId:ee});if(Ge.size!==0||!$||D||ve||F||K!==0||ot!==null||$e!==void 0)throw new Error("Archive cold history requires an untouched, settled original Store");let Pe=ie.archiveHistoryObservation(),De=Ce.details.runtime===void 0?0:Ce.details.history.observation.localHistoryGeneration;if(Pe.localHistoryGeneration!==De||Pe.sessionId!==Ce.details.history.observation.sessionId||Pe.sourceSnapshotDigest!==Ce.details.history.observation.sourceSnapshotDigest)throw new Error("Archive cold history differs from the confirmed Store");Ce.assertCurrent(),Ae=Object.freeze({commitId:Ce.details.history.commitId,observation:Pe}),he=!0})}if(Re!==void 0||Le!==void 0)try{Re!==void 0&&ie.bindSessionCapture(Re),Le!==void 0&&ie.bindContextMaterials(Le)}catch(se){throw ie.close(),await ie.settleResources(),se}if(d?.recordSeqWatermark!==void 0){let se=d.recordSeqWatermark;ie.bindOnEnded(Ie=>{q?.close(),j&&p(se.call(d,S.endUserId,ee,{lastSeq:Ie,sealed:!0},w).catch(Ce=>f("commit",ee,Ce,ie)))})}let St=ge===void 0?void 0:ge.sessionRetentionDays??null;if(d!==void 0&&(!we||L!==void 0&&xt===void 0||Z||St!==void 0&&(St===null?pn!==void 0:St!==pn))){$=!1;let se={sessionId:ee,...L!==void 0?{platformSessionId:t.cacheHost!==void 0&&we&&xt!==void 0?xt:L}:{},...w===void 0?{}:{owner:w},cwd:ue,...St!==void 0?{retentionDays:St}:{}};if(re!==void 0||Z){if(re?.assertCurrent(),k=await(re?.mode==="fresh"&&!At?Tl(d,S.endUserId,se):d.create(S.endUserId,se)),re?.assertCurrent(),Z&&t.cacheHost===void 0&&k.platformSessionId!==L)throw new Error("Platform runtime metadata unconfirmed");$=!0}else{let Ie=d.create(S.endUserId,se).then(()=>{$=!0},Ce=>f("create",ee,Ce,ie));Ge.add(Ie),Ie.then(()=>Ge.delete(Ie),()=>Ge.delete(Ie)),p(Ie)}}if(t.cacheHost!==void 0&&L!==void 0&&d!==void 0)try{if(t.cacheHost.registerSession({endUserId:S.endUserId,sessionId:ee,runtimeSessionId:L,driver:ie,store:d,configurationRefreshRequired:we&&xt===L}),await t.cacheHost.restoreSession(S.endUserId,ee),we&&xt!==L||t.cacheHost.needsStoreRuntime(S.endUserId,ee,L)){let se=await d.create(S.endUserId,{sessionId:ee,platformSessionId:L,...w===void 0?{}:{owner:w}});if(re?.assertCurrent(),re!==void 0&&(k=se),se.platformSessionId!==L)throw new Error("Cache host runtime metadata unconfirmed");t.cacheHost.confirmStoreRuntime(S.endUserId,ee,L)}}catch(se){throw ie.close(),await ie.settleResources(),se}if(re!==void 0){if(k===void 0)throw new Error("Archive factory registration is not confirmed");j=!0,re.registered(k),ry(ne,S,Ke,ie,k)}if(q!==void 0){let se=q;se.attach(()=>ie.status()==="idle"),d?.recordSeqWatermark===void 0&&ie.bindOnEnded(()=>se.close())}let ln=d?.runtimeCheckpoints===!0?ie.historySnapshot().messages:void 0;return w!==void 0&&d?.runtimeCheckpoints===!0&&ie.bindRuntimeRecovery(async(se,Ie)=>{if(await Promise.all([...Ge]),ve||D||!(q?.ownershipStable()??!0))throw new Jt("reconciliation_required");let Ce=ln!==void 0&&(ln.length>se.query.messages.length||ln.some((Pe,De)=>fe(Pe)!==fe(se.query.messages[De])));await d.commit(S.endUserId,ee,se.query.messages,{owner:w,rewritten:Ce,lastSeq:ie.lastSeq(),runtimeCheckpoint:se,...Ie===void 0?{}:{usageSnapshot:xs(Ie)},...d.attachmentCheckpoints===!0?{attachmentCheckpoint:ie.attachmentCheckpoint(se.query.messages)}:{},...d.attachmentSourceCheckpoints===!0?{attachmentSourceCheckpoint:ie.attachmentSourceCheckpoint(se.query.messages)}:{},...d.memorySelectionCheckpoints===!0?{memorySelectionCheckpoint:ie.memorySelectionCheckpoint()}:{}}),ln=structuredClone(se.query.messages)},T),T!==void 0&&(re!==void 0?ie.prepareArchiveRuntimeRecovery():ie.resumeRuntime()),S.prompt!==void 0&&ie.send(S.prompt),{handle:Ke,resumed:we}}catch(Q){_!==void 0&&clearInterval(_);try{await w?.release()}catch{}if(q?.close(),M!==void 0)try{M.close(),await M.settleResources()}catch(U){throw new AggregateError([Q,U],"Archive factory creation and driver cleanup failed")}throw Q instanceof Jt?new Xe(Q.code==="owner_corrupted"?"store_corrupted":Q.code==="reconciliation_required"?"resume_unavailable":"overloaded",Q.message,{retryAfterMs:1e3,detail:{reason:Q.code}}):Q}finally{W?.()}},flush:h,sweepRetention:S=>B({activeSessionIds:S.activeSessionIds})};ny(ne,d);let N=S=>({sessionId:S.sessionId,createdAt:S.createdAt,updatedAt:S.updatedAt,...S.title!==void 0?{title:S.title}:{},...S.lastSeq!==void 0?{lastSeq:S.lastSeq}:{}}),X=d!==void 0?{async list(S){return(await d.list(S)).map(N)},async getMeta(S,w){let T=d.getMeta!==void 0?await d.getMeta(S,w):(await d.list(S)).find(_=>_.sessionId===w);return T==null?null:N(T)},async getHistory(S,w){let T=await d.get(S,w);return T===null?null:ds(T.messages).messages},...d.getHistoryPage!==void 0?{getHistoryPage:(S,w,T)=>d.getHistoryPage.call(d,S,w,T)}:{}}:void 0;return{factory:ne,flush:h,sweepSessionRetention:B,...X!==void 0?{storeReader:X}:{},...v!==void 0?{upstreamStats:v}:{}}}function Fx(t){if(t!==void 0)return{policy:{maxAgeDays:t.maxAgeDays??pf,...t.maxPerEndUser!==void 0?{maxPerEndUser:t.maxPerEndUser}:{},...t.maxBytes!==void 0?{maxBytes:t.maxBytes}:{}},sweepIntervalMs:t.sweepIntervalMs??hf}}function Lx(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 Wo({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 Wo({rootOf:(o,s)=>$d(i.call(e,o,s)),...n})}function ff(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 zx(t,e){let n=ff(e,t.endUserId),i=await Lr({...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 Xe("cwd_not_allowed",`cwd not allowed: ${o}`,{params:{detail:o}}):new Xe("cwd_invalid",`cwd invalid (${i.reason}): ${o}`,{params:{reason:i.reason,detail:o}})}async function Hx(t){return mm(await Lr({requested:t.requested,fallback:t.fallback,...t.policy!==void 0?{policy:t.policy}:{}}),{onResume:!0})}async function Gx(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(kt.cwdMismatchOnResume,{stored:t,current:e})}};let i=await Hx({requested:t,fallback:e,policy:n.policy});if("error"in i)throw new Xe("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(kt.cwdMismatchOnResumeStored,{stored:t,current:e})}}}async function Wx(t){let{init:e,fork:n,checkpointStore:i,store:o}=t;if(i===void 0)throw new Xe("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 un&&f.code==="CHECKPOINT_INVALID"?new Xe("store_corrupted",f.message):f}if(s===null||s.sessionId!==n.sessionId)throw new Xe("fork_source_not_found",`fork source not found: session ${n.sessionId} / checkpoint ${n.checkpointId}`,{params:{sessionId:n.sessionId,checkpointId:n.checkpointId}});let a=ds(s.messages).messages,d=Ni(a);if(o===void 0)return{sessionId:e.sessionId??Id(),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??Id(),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 Xe("store_corrupted",f.message):f}return{sessionId:l,history:a,title:d}}function Vx(t,e){if(!t?.capabilities||!t.platformTools)return;let n=t.capabilities.platform,i=Vr({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 $x(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)=>hu({baseUrl:n.baseUrl,face:i,payload:o,token:Bi,fetchImpl:n.fetchImpl,...s!==void 0?{signal:s}:{}})}}function Kx(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 Qx={};Av(Qx,{ADJUDICATOR_UNAVAILABLE_CODE:()=>cf,ADJUDICATOR_UNAVAILABLE_MESSAGE:()=>lf,AGENT_SESSION_CONTRACT_VERSION:()=>vh,AUDIO_INPUT_PATTERN:()=>Ll,AUDIO_LANGUAGE_MAX_CHARS:()=>Hl,AUDIO_MAX_BODY_BYTES:()=>ho,AUDIO_PROMPT_MAX_CHARS:()=>Wl,AUDIO_ROUTE_SEGMENTS:()=>Sh,AUDIO_SPEECH_FORMATS:()=>zl,AUDIO_SPEECH_INPUT_MAX_CHARS:()=>Vl,AUDIO_VOICE_MAX_CHARS:()=>Gl,AgentSessionBridge:()=>Dr,AgentSessionCreateError:()=>Xe,AgentSessionStoreError:()=>et,AppTokenMintError:()=>Sn,AudioSpeechBodySchema:()=>ea,AudioTranscriptionsBodySchema:()=>Zs,BUILTIN_CAPABILITY_PROFILES:()=>mf,CHECKPOINT_EXPORT_CONTENT_TYPE:()=>Ys,CHECKPOINT_IMPORT_MAX_BODY_BYTES:()=>po,CHECKPOINT_IMPORT_SEGMENT:()=>Xs,CHECKPOINT_LABEL_MAX_CHARS:()=>Ui,CLIENT_TOOL_NAME_PATTERN:()=>Ol,COMPACT_INSTRUCTIONS_MAX_CHARS:()=>Ul,CONTROL_FRAME:()=>nn,CONTROL_FRAME_TS_KEY:()=>Fs,CheckpointBodySchema:()=>Ks,CheckpointOptionSchema:()=>Fl,ClientToolDeclSchema:()=>fo,ClientToolNameConflictError:()=>Pn,CompactBodySchema:()=>$s,CreateSessionBodySchema:()=>zs,DEFAULT_BUNDLE_CACHE_TTL_MS:()=>wi,DEFAULT_PROCESS_GUARD_DRAIN_TIMEOUT_MS:()=>Cp,DEFAULT_SESSION_MAX_AGE_DAYS:()=>pf,DEFAULT_SESSION_RETENTION_SWEEP_INTERVAL_MS:()=>hf,DEFAULT_SSE_FLUSH_SLICE_MS:()=>Jl,DEFAULT_SSE_HEARTBEAT_MS:()=>Kl,DEFAULT_SSE_RETRY_MS:()=>Ql,DEFAULT_WEBHOOK_SIGNATURE_VERSIONS:()=>tu,DEVELOPER_ONLY_ADJUDICATOR_WARNINGS:()=>Uu,END_USER_ID_PATTERN:()=>Ml,EXCLUDE_TOKEN_PATTERN:()=>Bl,EventRingBuffer:()=>hi,IMAGE_MIME_PATTERN:()=>Us,ImageGenDataSchema:()=>Ed,LOG_EVENT:()=>at,LOG_EVENT_NAMES:()=>Ip,MemorySessionEventLog:()=>br,MessageBlockSchema:()=>ql,MessagesBodySchema:()=>Hs,OBSERVABILITY_PATHS:()=>bn,OPENMETRICS_CONTENT_TYPE:()=>rs,PERMISSION_DENY_REASON:()=>Nl,PROCESS_GUARD_POLICIES:()=>As,PROCESS_GUARD_STACK_MAX_CHARS:()=>Ap,PermissionReceiptSchema:()=>Gs,QuestionReceiptSchema:()=>Ws,REPLAY_GAP_EVENT:()=>vn,REQUEST_ID_HEADER:()=>go,ReceiptContentSchema:()=>jl,RestoreBodySchema:()=>Qs,SECRET_WARNING_VALUE:()=>sf,SEGMENTED_STORE_DEFAULTS:()=>Ld,SERVER_MESSAGE_KEY:()=>le,SERVER_MESSAGE_KEYS:()=>Rp,SERVE_RUNTIME_ENV:()=>Ho,SERVE_RUNTIME_ENV_NAMES:()=>pv,SESSION_ID_SHARD_MAX:()=>Er,SESSION_RECOVERY_VERSION:()=>dc,SESSION_STORE_CORE_ENV:()=>Il,ServeSessionDriver:()=>Zn,SetCwdBodySchema:()=>Js,SpeechDataSchema:()=>Md,SseTransport:()=>hr,StoreError:()=>Bn,TANSR_READY_FRAME_VERSION:()=>jh,TANSR_READY_PREFIX:()=>yo,TOKEN_CHECK_UNAVAILABLE_REASON:()=>uy,TOKEN_INVALIDATING_CODES:()=>Co,TURN_END_NOTIFY_SIGNATURE_HEADER:()=>Ls,ToolParameterSpecSchema:()=>uo,ToolResultReceiptSchema:()=>pr,TranscriptDataSchema:()=>Pd,TurnEndNotifier:()=>vr,V2_ASSEMBLY_MESSAGE_KEY:()=>Xt,V2_ASSEMBLY_MESSAGE_KEYS:()=>dy,V2_CTX_PERSIST_MESSAGE_KEY:()=>kt,V2_CTX_PERSIST_MESSAGE_KEYS:()=>Jg,V2_ERROR_CODE:()=>Ee,V2_LIMITS:()=>Be,V2_ROUTE_TABLE:()=>Fi,V2_SESSION_ACTIONS:()=>ra,VideoGenDataSchema:()=>_d,WEBHOOK_SIGNATURE_VERSIONS:()=>Lh,alignHistoryPage:()=>so,appliedRuntimeEnvByGroup:()=>gv,assertSessionIdShard:()=>qo,buildRemoteTool:()=>kd,countSpeechCharacters:()=>Mc,createAgentSessionFactory:()=>Tv,createAppTokenMinter:()=>ed,createBundleCache:()=>Qi,createChaosBlobStore:()=>mc,createFsBlobStore:()=>uc,createMemoryBlobStore:()=>lc,createMetricsRegistry:()=>$f,createPlatformServeSessionFactory:()=>Rd,createPlatformSessionAssembler:()=>hy,createServeAgentSessionStore:()=>ph,createServeCheckpointStore:()=>Wo,createServeLogger:()=>Tp,createUpstreamGovernor:()=>pp,defaultMetrics:()=>ui,emitReadyFrame:()=>ua,encodeAgentStreamFrame:()=>ma,encodeKernelEventFrame:()=>lo,encodeSseComment:()=>Ns,encodeSseFrame:()=>tn,endUserKeyOf:()=>Wt,extractBearerToken:()=>Al,formatReadyFrame:()=>eu,getRequestContext:()=>yr,installProcessGuards:()=>_p,isAuthorized:()=>Ds,isControlFrameType:()=>mr,isExcluded:()=>mo,isLoopbackHost:()=>la,isSessionHistoryStore:()=>zd,kernelMetricsFor:()=>os,negotiateLocale:()=>Sf,parseExcludeTokens:()=>Vs,parseHistoryPageQuery:()=>Ps,parseMediaArtifact:()=>Od,parseReadyFrame:()=>Uh,planSpeechInput:()=>Oc,processGuardRecordOf:()=>Ep,registerBuiltinLocales:()=>vf,rejectionCodeOf:()=>ca,renderOpenMetrics:()=>is,resolvePlatformAdjudicator:()=>xd,resolveRequestId:()=>da,resolveServeRuntimeOptions:()=>hv,resolveUpstreamFetch:()=>Mr,routeTemplateOf:()=>aa,runIdleCompaction:()=>Ga,runStorageConformance:()=>fc,serveMetricsFor:()=>Ln,sessionIdShardOf:()=>ay,sessionIdShardPrefix:()=>ju,sessionTitleOf:()=>Ni,setLocale:()=>bf,shardedSessionId:()=>Ja,signWebhookDelivery:()=>nu,sliceHistoryPage:()=>Un,slowSubscriberGapFrame:()=>gr,startServer:()=>uv,sumRingStats:()=>ta,toCheckpointMetaView:()=>rr,toStoreError:()=>Fd,tokenMatches:()=>Cl,translateMintError:()=>Fu,translateUpstreamAssemblyErrors:()=>td,upstreamAgentOptions:()=>hp,upstreamOriginOf:()=>mp});import{mkdirSync as Jx,statSync as Yx}from"node:fs";import Vo from"node:path";var gf=class extends Error{code="memory_project_mismatch";constructor(){let e=Is.memoryProjectMismatch;super(`memory_project_mismatch: ${or(e)}`),this.name="SessionMemoryProjectMismatchError"}};function Td(t,e){try{let n=Yx(t);return e==="dir"?n.isDirectory():n.isFile()}catch{return!1}}function Kj(t){let e=yp(t.env),n=new Set,i;return(o,s)=>{let a;if(s!==void 0){a=zr(o);let d=zr(s);if(a.key!==d.key)throw new gf}if(Sp()!=="deny"&&(t.autoMemoryEnabled?.()??t.autoMemory!==void 0))try{if(a??=zr(o),t.autoMemory!==void 0&&t.autoMemoryEnabled===void 0&&(i??=zr(t.cwd),i.key===a.key))return{...t.autoMemory,injection:{...t.autoMemory.injection},projectKey:a.key,canonicalRoot:a.canonicalRoot};let d=Vo.join(e,"projects",a.key,"memory");if(!n.has(a.key)||!Td(d,"dir")){Jx(d,{recursive:!0});let f=Vo.join(d,wp);Td(f,"file")||xp(f,JSON.stringify({path:a.canonicalRoot,createdAt:new Date().toISOString()},null,2)+`
|
|
37
|
+
`),n.size>=256&&n.clear(),n.add(a.key)}try{kp(e,a.key,d)}catch(f){t.onMemoryNotice?.({key:Is.autoMemoryLegacyMergeFailed,params:{detail:f instanceof Error?f.message:String(f)}})}let c=d,l=wf(e);if(l!==null&&!Td(Vo.join(d,"MEMORY.md"),"file")){let f=Vo.join(l,"projects",a.key,"memory");Td(f,"dir")&&(c=f)}return{dir:d,readDir:c,...c!==d?{legacyReadDir:c}:{},projectKey:a.key,canonicalRoot:a.canonicalRoot,injection:{indexPath:Vo.join(c,"MEMORY.md"),present:!1,bytes:0,lines:0,truncated:!1}}}catch(d){t.onMemoryNotice?.({key:Is.autoMemorySetupFailed,params:{detail:d instanceof Error?d.message:String(d)}});return}}}function Jj(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{ga as a,ig as b,rg as c,dO as d,cO as e,ct as f,Xi as g,yO as h,vO as i,ja as j,jg as k,Eu as l,lw as m,nR as n,ut as o,iR as p,rR as q,Jt as r,Un as s,yR as t,et as u,Wt as v,Ni as w,ao as x,ur as y,xl as z,Nv as A,Uv as B,Gv as C,BR as D,qR as E,DR as F,ph as G,jR as H,hw as I,Zn as J,U0 as K,F0 as L,$a as M,L0 as N,Ja as O,Ky as P,uv as Q,xq as R,Rq as S,Iq as T,hv as U,gv as V,Pn as W,Tv as X,Qx as Y,gf as Z,Kj as _,Jj as $};
|
|
38
|
+
//# sourceMappingURL=tansr-chunk-G5YDZOSH.mjs.map
|