@tansr/cli 0.10.1 → 0.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/tansr-artifacts.json +443 -443
- package/{tansr-bg-OUP4JX3I.mjs → tansr-bg-EAYYM4XW.mjs} +2 -2
- package/{tansr-chunk-2AJTBN37.mjs → tansr-chunk-2X337GKC.mjs} +2 -2
- package/tansr-chunk-4LNN4SQL.mjs +22 -0
- package/{tansr-chunk-YAYVXUHY.mjs → tansr-chunk-5TJVZSZE.mjs} +2 -2
- package/{tansr-chunk-54YMMSEF.mjs → tansr-chunk-74H5GQTJ.mjs} +7 -7
- package/{tansr-chunk-R4W5HKDF.mjs → tansr-chunk-7T6OLLFW.mjs} +2 -2
- package/{tansr-chunk-MXYVQZY3.mjs → tansr-chunk-CJP7YEGC.mjs} +2 -2
- package/{tansr-chunk-LSGFLGLS.mjs → tansr-chunk-D7VSW2LQ.mjs} +2 -2
- package/{tansr-chunk-UAEARRRH.mjs → tansr-chunk-DN22GXHD.mjs} +2 -2
- package/{tansr-chunk-NCIMR6LB.mjs → tansr-chunk-GDJ5YVNY.mjs} +2 -2
- package/{tansr-chunk-4R5ZK4RG.mjs → tansr-chunk-GMPMRXL4.mjs} +3 -3
- package/tansr-chunk-GR6BWQGG.mjs +38 -0
- package/{tansr-chunk-S77B4PI7.mjs → tansr-chunk-HHL7HM62.mjs} +2 -2
- package/{tansr-chunk-BCOFZJWA.mjs → tansr-chunk-IZICOKKF.mjs} +9 -9
- package/{tansr-chunk-Q6MUMULP.mjs → tansr-chunk-J2LWM3S7.mjs} +2 -2
- package/{tansr-chunk-XIOD3RQD.mjs → tansr-chunk-KQVXXXEF.mjs} +2 -2
- package/{tansr-chunk-QNHXB55W.mjs → tansr-chunk-M6XHWCMA.mjs} +2 -2
- package/{tansr-chunk-TYJWMSVW.mjs → tansr-chunk-N3R2URKL.mjs} +2 -2
- package/{tansr-chunk-J2ED6CI4.mjs → tansr-chunk-QUFHVA3F.mjs} +2 -2
- package/{tansr-chunk-HQY7FXGU.mjs → tansr-chunk-X4GLXJ2Z.mjs} +2 -2
- package/{tansr-chunk-M63EZH2M.mjs → tansr-chunk-X5REV3T3.mjs} +2 -2
- package/{tansr-chunk-AEIS2NWD.mjs → tansr-chunk-ZV3NCXTD.mjs} +2 -2
- package/{tansr-main-O6RSYTGN.mjs → tansr-main-STVTNYAI.mjs} +3 -3
- package/{tansr-run-acp-entry-XJMGBZ7Q.mjs → tansr-run-acp-entry-6J44XOYJ.mjs} +3 -3
- package/{tansr-run-approvals-entry-I6FX6AYX.mjs → tansr-run-approvals-entry-HQWSIW3P.mjs} +2 -2
- package/{tansr-run-auth-entry-LJC3UJWR.mjs → tansr-run-auth-entry-7HA4C4NJ.mjs} +2 -2
- package/{tansr-run-doctor-RFMVNKS5.mjs → tansr-run-doctor-7T6IAXYE.mjs} +3 -3
- package/{tansr-run-headless-entry-G2G44HY3.mjs → tansr-run-headless-entry-XEFQC5LE.mjs} +2 -2
- package/{tansr-run-init-entry-JVJEH4PI.mjs → tansr-run-init-entry-3VKXS2WK.mjs} +2 -2
- package/{tansr-run-logout-entry-DI42PBLR.mjs → tansr-run-logout-entry-VNCNNCSS.mjs} +2 -2
- package/{tansr-run-mcp-serve-entry-ZPOSEKDA.mjs → tansr-run-mcp-serve-entry-5KLWER3G.mjs} +2 -2
- package/{tansr-run-orchestrate-entry-43QIZUZA.mjs → tansr-run-orchestrate-entry-AR57AZLR.mjs} +2 -2
- package/{tansr-run-org-entry-D2FTJY7E.mjs → tansr-run-org-entry-TJPRLGCL.mjs} +2 -2
- package/{tansr-run-policy-entry-SLI4BZ2I.mjs → tansr-run-policy-entry-DHMQ3PAP.mjs} +2 -2
- package/{tansr-run-profile-entry-643TLJUU.mjs → tansr-run-profile-entry-LOFPHFG4.mjs} +2 -2
- package/tansr-run-serve-entry-CHVKUY5J.mjs +99 -0
- package/{tansr-run-sessions-entry-MROXZKQS.mjs → tansr-run-sessions-entry-JOMFB5LJ.mjs} +2 -2
- package/{tansr-run-update-entry-BOZIZIWN.mjs → tansr-run-update-entry-XI6KG7UI.mjs} +2 -2
- package/{tansr-src-5BMLUX6E.mjs → tansr-src-A6WDMY6X.mjs} +3 -3
- package/{tansr-startup-account-YMNFBBH2.mjs → tansr-startup-account-7ZFSP3FV.mjs} +4 -4
- package/{tansr-startup-model-LYYMNZ32.mjs → tansr-startup-model-I6LOCFDP.mjs} +3 -3
- package/{tansr-tui-4EYUVRFQ.mjs → tansr-tui-OWG3JNA6.mjs} +5 -5
- package/tansr.mjs +1 -1
- package/tansrd.mjs +244 -244
- package/tansr-chunk-3GJD3L4B.mjs +0 -22
- package/tansr-chunk-LLW6GX7K.mjs +0 -38
- package/tansr-run-serve-entry-CX6EBQAV.mjs +0 -99
package/tansr-chunk-LLW6GX7K.mjs
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
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 Al}from"./tansr-chunk-MWHLITGY.mjs";import{$ as wl,Aa as Il,Ca as Tl,F as pl,I as ml,J as ho,K as li,M as ei,O as hl,P as gl,S as yl,X as vl,Y as rn,Z as bl,_ as Sl,aa as zs,ja as th,la as kl,oa as xl,v as eh,za as Rl}from"./tansr-chunk-BX7CF5RQ.mjs";import{a as nh}from"./tansr-chunk-QHEQQ2JB.mjs";import{Oa as Hm,Ra as zm,Xa as Gm,Ya as Wm,i as Lm}from"./tansr-chunk-HQY7FXGU.mjs";import{a as Um}from"./tansr-chunk-Q6MUMULP.mjs";import{a as ae,b as Vm,c as rt,d as $m,e as Km,f as On,g as $n,h as Hs,i as Qm,j as Jm,k as Ym,l as Xm,w as Zm}from"./tansr-chunk-54YMMSEF.mjs";import{A as ul,B as fl,a as Vn,b as Ls,c as br,d as sl,e as al,f as dl,g as cl,h as Gi,j as ll,k as ao,l as Sr,m as Fm,o as co,p as lo,q as uo,r as fo,s as po,t as mo,u as gt}from"./tansr-chunk-3GJD3L4B.mjs";import{k as Gf}from"./tansr-chunk-HRKJLVKC.mjs";import{$ as lp,$a as wc,$c as Vc,Ac as Wp,Bc as Lc,Bd as js,Be as Xc,C as uc,Cc as Hc,Db as to,Dc as Vp,De as Sm,E as fc,Eb as xs,Ee as wm,Fb as Rc,Fe as km,Gb as Ic,Gc as $p,Gd as um,Ge as xm,H as yr,Ha as wp,Hb as Tc,Ib as Ac,Ic as Kp,Ie as Zc,J as pc,Jb as Ec,Jc as Qp,Je as Rm,K as mc,Kb as Cc,Kc as Jp,Ke as Im,L as hc,La as kp,Lb as _c,Lc as Yp,Le as Tm,Ma as xp,Mb as Pc,Mc as zc,Me as Am,N as Zr,Na as Rp,Nb as Rs,Nc as Xp,Nd as fm,O as Fi,Ob as Mc,Oc as Zp,P as gc,Pb as Oc,Pc as _s,Pd as pm,Pe as Em,Q as hs,Qb as Bc,Qc as em,Qd as mm,Rb as qc,Rc as Ps,Rd as hm,Re as Cm,Sb as Is,Sc as tm,Ta as Ip,Tb as Ts,Tc as Ms,U as ap,Ua as Wn,Ub as Dc,Uc as nm,Va as ws,Vb as no,Vc as Gc,W as dp,Wa as Sc,Wb as qp,Wd as gm,We as el,X as gs,Xa as ks,Ya as Tp,Yb as As,Ye as tl,Za as Ap,Zc as Wc,Ze as nl,_ as ys,_a as Ep,_b as io,a as Xf,aa as up,ac as Dp,b as Zf,ba as fp,bb as xn,c as ep,ca as Li,cc as Es,cd as im,cf as Fs,d as gn,da as pp,dc as jp,dd as Os,e as Gn,ec as Np,ed as rm,f as nc,fc as Up,fd as om,g as ic,gc as Fp,gd as $c,h as rc,hb as eo,hc as Lp,i as Bt,ia as vc,ic as jc,id as sm,ja as Hi,jc as Cs,je as Jc,kb as Cp,kd as am,ke as Ns,l as oc,la as bc,le as ym,m as Ui,mb as kc,md as dm,me as Yc,n as sc,na as mp,nb as xc,nd as cm,ne as Us,o as ps,oa as hp,ob as _p,oc as Hp,od as lm,p as ms,pa as Si,pb as Pp,pc as zp,q as ac,qa as vs,qb as Mp,r as op,ra as bs,rb as Op,rd as Bs,s as dc,sa as Ss,t as zt,tc as Nc,td as qs,u as cc,ua as gp,uc as Uc,va as yp,vc as ro,ve as vm,wa as vp,wc as oo,x as Zt,xa as bp,xd as Ds,y as ci,yb as Bp,yc as Fc,yd as Kc,z as lc,za as Sp,zc as Gp,zd as Qc,ze as bm}from"./tansr-chunk-BCOFZJWA.mjs";import{A as Bm,D as rl,E as ol,H as qm,I as Dm,J as jm,K as Nm,M as so,c as _m,d as Pm,e as zi,j as il,o as Mm,t as Et,z as Om}from"./tansr-chunk-2C6JKHKM.mjs";import{a as as,b as ds,c as Wf,d as Vf,e as $f,h as cs}from"./tansr-chunk-OKAA4BJC.mjs";import{a as Jd,b as Yd,p as Xd,q as zn,s as Zd}from"./tansr-chunk-OSK64SU3.mjs";import{Fa as cp,Ia as yc,Ma as vr,n as gr,na as sp}from"./tansr-chunk-ZQ3ZK7IL.mjs";import{C as tc,N as me,O as lt,P as Mn,a as nn,c as bi,d as ip,k as rp,l as fs,n as ec}from"./tansr-chunk-I3TOVAA6.mjs";import{c as us,e as tp,f as np}from"./tansr-chunk-F7C6ITED.mjs";import{a as hr,b as Lf,k as Hf,m as We,o as zf}from"./tansr-chunk-NA22YT73.mjs";import{Ba as ls,Fb as Qf,Ib as Jf,Jb as Yf,a as Gd,c as r,d as Kf,kb as Wd,lb as Vd,nb as $d,pb as Kd,rb as Qd,ua as Xr}from"./tansr-chunk-QWGSXFEJ.mjs";import{c as nb}from"./tansr-chunk-RRAMVVYF.mjs";import{createHash as fb,randomUUID as Sh}from"node:crypto";import{createHash as ib}from"node:crypto";import{mkdir as ih,open as rb,readFile as rh,readdir as ob}from"node:fs/promises";import go from"node:path";var oh=new WeakMap;function dI(t){oh.set(t,"sdk2-offload-v1")}function Wi(t){return oh.get(t)??"sdk1"}var ct=class extends Error{constructor(n){super(`SDK2 offload: ${n}`);this.code=n;this.name="OffloadSessionError"}code};function Gs(t,e){let n=t.sdk2SessionFamily;if(e===void 0?n!==void 0:n===void 0||me(n)!==me(e.marker))throw new ct("family_mismatch")}function cI(t,e,n,i){if(!go.isAbsolute(t)||!["create","reopen"].includes(e)||[n.applicationScopeId,n.sourceId,n.sourceGeneration].some(u=>typeof u!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(u)))throw new ct("family_mismatch");let o=Object.freeze({...n}),s=go.join(go.resolve(t),"sdk2-offload-v1",ib("sha256").update(n.applicationScopeId).digest("hex")),a=go.join(s,"contract.json"),d=me(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 ih(go.dirname(s),{recursive:!0});try{await ih(s)}catch(m){if(m.code!=="EEXIST")throw m}if((await ob(s)).length===0){let m=await rb(a,"wx",384);try{await m.writeFile(d),await m.sync()}finally{await m.close()}}}let u;try{u=await rh(a,"utf8")}catch(m){throw m.code==="ENOENT"?new ct("family_missing"):m}if(u!==d)throw new ct("family_mismatch");c=!0})().catch(u=>{throw l=void 0,u})),await rh(a,"utf8")!==d)throw new ct("family_mismatch")}})}function lI(t,e,n,i){if(!t||!("capabilities"in t)||t.capabilities.consistency!=="strong"||!t.capabilities.conditionalPut||t.capabilities.list!=="prefix")throw new ct("source_mismatch");let o=me(n),s=lt(o),a=`sdk2-offload-v1/${s}/`,d=`${a}contract.json`,c=Buffer.from(o),l=p=>`${a}objects/${p}`,f,u=async()=>{await(f??=(async()=>{if(!await t.head(d)){if(i!=="create")throw new ct("family_missing");for await(let R of t.list(a))throw new ct("family_missing");try{await t.put(d,new ReadableStream({start(R){R.enqueue(c),R.close()}}),{bytes:c.length,contentType:"application/json",sha256:lt(o)},{ifNoneMatch:"*"})}catch(R){if(!(R instanceof Gn)||R.kind!=="precondition_failed")throw R}}})().catch(R=>{throw f=void 0,R}));let p=await t.head(d);if(!p)throw new ct("family_missing");if(p.bytes!==c.length||p.sha256!==lt(o))throw new ct("family_mismatch");let v=(await t.get(d)).getReader(),b=Buffer.alloc(0);try{for(;;){let R=await v.read();if(R.done)break;if(b.length+R.value.byteLength>c.length)throw new ct("family_mismatch");b=Buffer.concat([b,R.value])}}finally{await v.cancel().catch(()=>{}),v.releaseLock()}if(!b.equals(c))throw new ct("family_mismatch")},m={capabilities:t.capabilities,put:(p,v,b,R)=>t.put(l(p),v,b,R),get:(p,v,b)=>t.get(l(p),v,b),head:(p,v)=>t.head(l(p),v),async*list(p,v,b){let R=l("");for await(let w of t.list(l(p),v,b)){if(!w.key.startsWith(R))throw new ct("family_mismatch");yield{...w,key:w.key.slice(R.length)}}},delete:(p,v)=>t.delete(p.map(l),v)},h=p=>`sdk2-offload-v1:${s}:${p}`;return{cold:m,index:e&&{upsert:(p,v,b)=>e.upsert({...p,endUserKey:h(p.endUserKey)},v,b),async get(p,v){let b=await e.get(h(p),v);if(b&&b.endUserKey!==h(p))throw new ct("family_mismatch");return b&&{...b,endUserKey:p}},async*list(p,v){for await(let b of e.list(h(p),v)){if(b.endUserKey!==h(p))throw new ct("family_mismatch");yield{...b,endUserKey:p}}},remove:(p,v)=>e.remove(h(p),v)},check:u}}import{access as pb,mkdir as wh,readFile as mb,readdir as Nl,rm as Dl,stat as Ul}from"node:fs/promises";import{randomUUID as sh}from"node:crypto";import{readFileSync as ah}from"node:fs";import{readFile as yo}from"node:fs/promises";import{hostname as El}from"node:os";var wr="serveOwner",sb=5e3,ab=3e5,Qt=class extends Error{constructor(n){super(`Session ownership: ${n}`);this.code=n;this.name="ServeSessionOwnershipError"}code},dh=new WeakMap;function Rn(t){throw new Qt(t)}function Cl(t){let e=t[wr];if(e===void 0)return;(!e||typeof e!="object"||Array.isArray(e))&&Rn("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")&&Rn("owner_corrupted"),n}function kr(t,e,n){n.serveOwnerDeleted===!0&&Rn("owner_stale");let i=Cl(n),o=e===void 0?void 0:dh.get(e);if(!i){e&&Rn("owner_stale");return}return e||Rn("owner_stale"),(!o||o.dir!==t||i.ownerId!==o.record.ownerId||i.claimId!==o.record.claimId||i.attempt!==o.record.attempt||i.host!==El()||i.released)&&Rn("owner_stale"),i}function vo(t,e,n){kr(t,e,n??JSON.parse(ah(Zt(t),"utf8")))}function _l(t,e,n){let i=kr(t,e,n);n[wr]={...i,expiresAt:Date.now()+e.leaseMs}}function Ws(t,e){let n=Cl(e??JSON.parse(ah(Zt(t),"utf8")));n&&(!n.released||n.phase!=="idle")&&Rn("owner_stale")}async function Vi(t,e){let n;for(let o=0;n===void 0;o++)try{n=await oc(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 ch(t,e,n=i=>i()){let i=e.leaseMs??3e4,o=e.ownerId??sh();if(!Number.isSafeInteger(i)||i<sb||i>ab||!o||o.length>256)throw new TypeError("Invalid session ownership options");let s=await Vi(t,async()=>{let c=JSON.parse(await yo(Zt(t),"utf8"));c.serveOwnerDeleted===!0&&Rn("owner_stale");let l=Cl(c),f=Date.now();l?.host!==void 0&&l.host!==El()&&Rn("owner_busy"),l&&!l.released&&l.expiresAt>f&&Rn("owner_busy"),(l?.phase==="running"&&!(e.runtimeRecovery===!0&&c.serveRuntime!==void 0)||c.pendingRewrite===!0)&&Rn("reconciliation_required");let u=(l?.attempt??0)+1;Number.isSafeInteger(u)||Rn("owner_corrupted");let m={format:"serve-owner-v1",ownerId:o,claimId:sh(),host:El(),attempt:u,expiresAt:f+i,phase:c.serveRuntime===void 0?"idle":"running",released:!1};return c[wr]=m,await ci(Zt(t),JSON.stringify(c)+`
|
|
5
|
-
`),m}),a=c=>n(()=>Vi(t,async()=>{let l=JSON.parse(await yo(Zt(t),"utf8")),f=kr(t,d,l);l[wr]=c(f),await ci(Zt(t),JSON.stringify(l)+`
|
|
6
|
-
`)})),d=Object.freeze({ownerId:o,attempt:s.attempt,leaseMs:i,assertCurrent(){vo(t,d)},assertIdle(){return n(()=>Vi(t,async()=>{let c=JSON.parse(await yo(Zt(t),"utf8"));(kr(t,d,c).phase!=="idle"||c.serveRuntime!==void 0||c.pendingRewrite===!0)&&Rn("reconciliation_required")}))},fence(c){return n(()=>Vi(t,async()=>(d.assertCurrent(),{value:c()})))},write(c){return n(()=>Vi(t,async()=>(d.assertCurrent(),await c())))},beginTurn(){return n(()=>Vi(t,async()=>{let c=JSON.parse(await yo(Zt(t),"utf8")),l=kr(t,d,c);c[wr]={...l,phase:"running",expiresAt:Date.now()+i},delete c.serveRuntime,await ci(Zt(t),JSON.stringify(c)+`
|
|
7
|
-
`)}))},checkpoint(c){return n(()=>Vi(t,async()=>{let l=JSON.parse(await yo(Zt(t),"utf8")),f=kr(t,d,l);!c()||l.pendingRewrite===!0||l.historyTotal===void 0||(l[wr]={...f,phase:"idle",expiresAt:Date.now()+i},delete l.serveRuntime,await ci(Zt(t),JSON.stringify(l)+`
|
|
8
|
-
`))}))},renew(){return a(c=>({...c,expiresAt:Date.now()+i}))},release(){return a(c=>({...c,released:!0}))}});return dh.set(d,{dir:t,record:s}),d}import{types as Ah}from"node:util";import $i from"node:path";import{createHash as db}from"node:crypto";var bo=r.string().min(1).max(256),Pl=r.string().regex(/^(0|[1-9][0-9]{0,18})$/),uh=r.object({sourceId:bo,generation:Pl,deletionGeneration:Pl,variant:bo}).strict(),cb=r.object({source:uh,executorId:bo,workspaceId:bo,workspaceRevision:bo,authorizationRevision:Pl}).strict(),lh=r.string().regex(/^[a-f0-9]{64}$/),Ml=r.object({format:r.literal("tansr-attachment-source/1"),scope:r.string().min(1).max(4096),historyDigest:lh,checkpointDigest:lh,snapshot:cb}).strict(),Ol=t=>JSON.parse(Buffer.from(nn(t)).toString("utf8")),fh=t=>db("sha256").update("tansr-attachment-source/1\0").update(me(t)).digest("hex");function ph(t){return Object.freeze(uh.parse(Ol(t)))}function Bl(t){return t===null?null:Ml.parse(Ol(t))}function wi(t){return me(t)}function mh(t,e,n,i){return Ml.parse({format:"tansr-attachment-source/1",scope:t,historyDigest:Zr(e),checkpointDigest:fh(n),snapshot:i})}function hh(t,e,n,i){return t.scope===e&&t.historyDigest===Zr(n)&&t.checkpointDigest===fh(i)}function gh(t){return{type:"attachment_source_checkpoint",version:1,checkpoint:Bl(t)}}function ql(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:Ml.nullable()}).strict().parse(Ol(n.payload)).checkpoint}return e}var yh=/^\d+$/;function Vs(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(!yh.test(e))return{ok:!1,detail:"offset must be a non-negative integer"};i.offset=Number.parseInt(e,10)}if(n!==null){if(!yh.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 lb(t){return t.blocks.flatMap(e=>e.t==="tool_call"?[e.id]:[])}function ub(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 lb(f))a.add(u);else for(let u of ub(f)){if(!a.has(u))return null;a.delete(u)}if(a.size===0){let u=l+1;u<=o&&(d=u),c===null&&u>=s&&(c=u)}}return{start:d,end:c??i}}function Kn(t,e,n){let i=t.length,o=n??i;if(o===0||e>=i){let a=Math.min(e,i);return{messages:[],total:i,offset:a,nextOffset:a}}let s=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 $s=new WeakMap;function vh(t){if($s.has(t))throw new Error("Serve Store delete target already registered");$s.set(t,{})}function xI(t,e){let n=$s.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 bh(t){return $s.get(t)?.guard}var Ze=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 Gt(t){return fb("sha256").update(t,"utf8").digest("hex").slice(0,16)}async function jl(t){try{return await pb(t),!0}catch{return!1}}var Hl="TANSR_SESSION_STORE_CORE",kh=64;function Ki(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>kh?`${n.slice(0,kh)}…`:n}}var Eh=1024;function Ch(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 Qs(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)&&Ch(e.thinking)}function wo(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&&!Ch(t.changes.thinking)))return structuredClone(t)}function xr(t){let e=t.serveConfiguration;if(e===void 0)return;let n=e;if(!n||n.format!=="serve-configuration-v1"||!Qs(n.current)||!Array.isArray(n.requests)||n.requests.length>Eh||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)||!Qs(i.configuration)||i.configuration.revision!==o+1)||new Set(n.requests.map(i=>i.requestId)).size!==n.requests.length||n.requests.length>0&&me(n.requests.at(-1).configuration)!==me(n.current))throw new Ze(String(t.sessionId),"Invalid durable configuration");return structuredClone(n)}function Fl(t,e){let n=lt(me(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>=Eh?{status:"rejected",reason:"request_limit",configuration:structuredClone(t.current)}:{status:"ready",configuration:structuredClone(t.current)}}function hb(t,e){let n=xr(t);if(n)return n.current;let i=structuredClone({...e,revision:0});if(!Qs(i))throw new TypeError("Invalid initial configuration");return t.serveConfiguration={format:"serve-configuration-v1",current:i,requests:[]},structuredClone(i)}function gb(t,e,n){let i=wo(e);if(!i)return{status:"rejected",reason:"invalid_configuration"};let o=xr(t);if(!o)throw new Ze(String(t.sessionId),"Configuration not initialized");let s=Fl(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:lt(me(i)),configuration:a}),t.serveConfiguration=o,{status:"changed",configuration:structuredClone(a)}}async function xh(t,e){let n=await _h(t);return n!==null&&(ps(n),Gs(n,e)),n}async function _h(t){try{let e=JSON.parse(await mb(Zt(t),"utf8"));return typeof e!="object"||e===null||Array.isArray(e)?null:e}catch{return null}}function Bn(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=yb(t.cwdHistory);o!==void 0&&(i.cwdHistory=o);let s=Oh(t);s!==void 0&&(i.forkedFrom=s);let a=Mh(t);a!==void 0&&(i.retentionDays=a);let d=Ph(t);return d!==void 0&&(i.lastSeq=d,t.seqSealed===!0&&(i.seqSealed=!0)),i}function Ph(t){let e=t?.lastSeq;return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function Rh(t,e){if(!Number.isSafeInteger(e.lastSeq)||e.lastSeq<0)return!1;let n=Ph(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 Js="historyTotal";function Ih(t){let e=t?.[Js];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 Th(t,e){if(e.cursor.lastHash===null){delete t[Js];return}let n={messages:e.persisted,records:e.cursor.recordCount,lastHash:e.cursor.lastHash};t[Js]=n}function Mh(t){let e=t?.retentionDays;return typeof e=="number"?Ks(e):void 0}function Oh(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 yb(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 vb=1e5;function Ks(t){return t!==void 0&&Number.isFinite(t)&&t>=0?t:void 0}async function Bh(t){let e=0,n;try{n=await Nl(t,{withFileTypes:!0})}catch{return 0}for(let i of n){let o=$i.join(t,i.name);if(i.isDirectory())e+=await Bh(o);else if(i.isFile())try{e+=(await Ul(o)).size}catch{}}return e}function bb(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 Sb(t,e){switch(e.type){case"store.segment_sealed":t("debug",rt.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",rt.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",rt.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",rt.storeHotFull,{hotBytes:e.hotBytes,maxBytes:e.maxBytes});return;case"store.hot_recovered":t("info",rt.storeHotRecovered,{hotBytes:e.hotBytes,maxBytes:e.maxBytes});return;case"store.evicted":t("debug",rt.storeEvicted,{sessionId:e.session.sessionId,endUserKey:e.session.endUserKey,n:e.segment.n,bytes:e.bytes});return;case"store.orphan_gc":t("info",rt.storeOrphanGc,{sessionId:e.session.sessionId,endUserKey:e.session.endUserKey,deleted:e.deleted.length});return;default:return}}var Ll=new WeakMap;function wb(t,e){if(Ll.has(t)||Ah.isProxy(t))throw new Ui("identity_mismatch");Ll.set(t,{...e,methods:["create","get","list","commit","delete"].map(n=>({key:n,value:Object.getOwnPropertyDescriptor(t,n)?.value}))})}function ti(t){if(!t||typeof t!="object"||Ah.isProxy(t))throw new Ui("identity_mismatch");let e=Ll.get(t);if(!e||e.methods.some(n=>{let i=Object.getOwnPropertyDescriptor(t,n.key);return!i||!("value"in i)||i.value!==n.value}))throw new Ui("identity_mismatch");if(e.cold&&!e.family)throw new Ui("unsupported_capability");return e}function qh(t){ti(t)}function FI(t,e){if(ti(t).family!==e)throw new ct("family_mismatch")}function LI(t,e,n,i){let o=ti(t);if(!o.family||!Number.isSafeInteger(i)||i<1)throw new ct("family_mismatch");return o.readBounded(e,n,i)}function HI(t){return ti(t).storageRoot}function zl(t,e,n){let i=ti(t);if(typeof e!="string"||e.length===0)throw new Ui("invalid_input");let o=sc(n,["title","platformSessionId","cwd","retentionDays"]);return i.create(e,o)}function Dh(t){return jh(t)}function zI(t,e){if(!t.cold||$i.resolve(t.dir)!==e.directory)throw new ct("family_mismatch");return jh(t,e)}function jh(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=$i.resolve(t.dir),a=e?{sdk2SessionFamily:e.marker}:{},d=async(O,I)=>{if(e&&I===null&&await jl(O)&&(await Nl(O)).length>0)throw new ct("family_missing")},c=async O=>{await e?.checkRoot();let I=await xh(O,e);return await d(O,I),I},l=async O=>{await e?.checkRoot();let I=await _h(O);return await d(O,I),I&&Gs(I,e),I},f=async(O,I=!1)=>{if(!e)return uc(O);await e.checkRoot();let q=zt(O.storageRoot,O.sessionId);if(I?await xh(q,e):await c(q))return{sessionDir:q,meta:await lc(q),created:!1};await wh(q,{recursive:!0});let N={schemaVersion:1,sessionId:O.sessionId,createdAt:new Date().toISOString(),cwd:O.cwd,...O.extra??{},sdk2SessionFamily:e.marker},ie=await op(q,N,"fresh");if(!await c(q))throw new ct("family_missing");return{sessionDir:q,meta:await lc(q),created:ie}},u=process.env[Hl]==="legacy"?"legacy":"core";if(t.recovery!==void 0&&u==="legacy")throw new Error("session recovery requires the core store policy");let m={segmentation:t.segmentation??{}},h=t.cold===void 0?void 0:_c({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 O=$n(t.logger);h.on(I=>{if(Sb(O,I),I.type==="store.commit_failed"&&I.gaveUp&&t.onStoreError!==void 0)try{t.onStoreError(I.session.sessionId,I.error)}catch{}if(t.onStoreEvent!==void 0)try{t.onStoreEvent(I)}catch{}})}function g(O,I){let q=(n.get(O)??Promise.resolve()).then(async()=>(await e?.checkRoot(),I())),H=q.then(()=>{},()=>{});return n.set(O,H),H.then(()=>{n.get(O)===H&&n.delete(O)}),q}let p=O=>$i.join(s,e?"offload-sessions":"agent-sessions",O),v=O=>p(Gt(O)),b=(O,I,q)=>h?.bind({sessionId:O,endUserKey:I,sessionDir:q}),R=O=>O===void 0?m:{...m,externalizeImages:!1,onSegmentSealed:O.onSegmentSealed},w=O=>O===void 0?{}:{segmentSource:O.segmentSource},x=(O,I)=>I instanceof Gn&&I.kind==="transient"?I:new Ze(O,On(I),I),T=O=>{let I=o.get(O);return I===void 0&&(I=new Pc({storageRoot:O,readMeta:async q=>{let H=await l(q);return H===null||typeof H.sessionId!="string"?null:ms(H,Bn(H))}}),o.set(O,I)),I};function P(O,I,q,H){let N=i.get(O);if(N!==void 0)return i.delete(O),i.set(O,N),N;if(i.size>=vb){let U=i.keys().next();U.done||i.delete(U.value)}let ie=hc({sessionDir:H,sessionId:I,producer:"serve",policy:u,writerOptions:()=>R(b(I,q,H)),readOptions:()=>w(b(I,q,H)),onRotated:async({empty:U})=>{h?.unbind(H),U&&await h?.commitEmpty({sessionId:I,endUserKey:q,sessionDir:H})},...t.onStoreWarning!==void 0?{onWarning:t.onStoreWarning}:{}});return i.set(O,ie),ie}let W=(O,I)=>I instanceof gn?I.code==="SESSION_LOCKED"||I.code==="CURSOR_STALE"?I:new Ze(O,I.message,I):I instanceof Gn?x(O,I):I,K=(O,I)=>I instanceof gn&&(I.code==="SESSION_LOCKED"||I.code==="CURSOR_STALE")?I:x(O,I);async function D(O,I,q){let H=await c(O);return H===null?null:(I(H)&&(q!==void 0&&_l(O,q,H),Gs(H,e),await ci(Zt(O),`${JSON.stringify(H,null,2)}
|
|
9
|
-
`)),H)}async function J(O,I,q){return t.ownership===void 0&&I===void 0?(vo(O.sessionDir),q()):O.withLock(q,()=>vo(O.sessionDir,I))}async function S(O,I){return(await k(O,I)).messages}async function k(O,I,q=!1){let H=(await c(O.sessionDir))?.serveOwner!==void 0;if(!H&&t.recovery!==void 0)try{let U=await O.withLock(()=>Ic(O,t.recovery));if(U.recovery!==void 0&&t.recovery.onRecovery===void 0){let ce=U.recovery,le={sessionId:I,droppedMessages:ce.droppedMessages,recoveredMessages:ce.recoveredMessages,synthesizedToolResults:ce.synthesizedToolResults,reason:ce.reason,fingerprint:ce.fingerprint};t.logger!==void 0?$n(t.logger)("warn","store.recovery_degraded",le):process.emitWarning(JSON.stringify(le),{code:"SESSION_RECOVERY_DEGRADED"})}return{messages:U.messages,usageSnapshot:Yc(U.journal.records),attachmentCheckpoint:hs(U.journal.records,U.recovery===void 0?U.messages:void 0),attachmentSourceCheckpoint:ql(U.journal.records),memorySelectionCheckpoint:jc(U.journal.records),...U.recovery!==void 0?{recovery:U.recovery}:{}}}catch(U){throw O.resetTail(),K(I,U)}let N;try{N=H?await O.readAllConfirmed():await O.readAll(q?{repair:!1}:{})}catch(U){throw K(I,U)}if(N.integrityBreakAt!==void 0)throw new Ze(I,`journal hash chain broken at record index ${N.integrityBreakAt}`);let ie=yr(N.records);if(ie.warnings.length>0)throw O.resetTail(),new Ze(I,ie.warnings.join("; "));try{return{messages:ie.messages,usageSnapshot:Yc(N.records),attachmentCheckpoint:hs(N.records,ie.messages),attachmentSourceCheckpoint:ql(N.records),memorySelectionCheckpoint:jc(N.records)}}catch(U){throw O.resetTail(),K(I,U)}}async function A(O,I,q){if(h===void 0)return!1;await e?.checkRoot();let H;try{H=zt(O,q)}catch{return!1}if(await c(H)!==null)return!1;let N=await jl(H);await wh(H,{recursive:!0});let ie;try{ie=await h.restore({sessionId:q,endUserKey:I,sessionDir:H})}catch(le){throw N||await Dl(H,{recursive:!0,force:!0}).catch(()=>{}),x(q,le)}if(ie===null)return N||await Dl(H,{recursive:!0,force:!0}).catch(()=>{}),!1;let U=ie.meta;await f({storageRoot:O,sessionId:q,cwd:process.cwd(),extra:{...a,...U.title!==void 0?{title:U.title}:{}}},!0);let ce=await D(H,le=>(U.createdAt!==""&&(le.createdAt=U.createdAt),le.updatedAt=U.updatedAt!==""?U.updatedAt:le.createdAt,U.platformSessionId!==void 0&&(le.platformSessionId=U.platformSessionId),!0));if(ce===null)throw new Ze(q,"meta.json unreadable right after cold-tier restore");return i.get(`${O}|${q}`)?.resetTail(),await T(O).upsert(Bn(ce)),!0}function C(O,I){let q=p(O),H=`${q}|${I}`;return g(H,async()=>{let N=zt(q,I);await c(N)!==null&&Ws(N);let ie=bh(se);if(ie!==void 0){let U=await ie(Object.freeze({storeIdentity:se,endUserKey:O,sessionId:I}));if(U!==null){if(!U||typeof U.confirm!="function")throw new TypeError("Invalid Serve Store delete confirmation");let ce=await c(N);if(ce===null&&await A(q,O,I)&&(ce=await c(N)),ce===null)await U.confirm(null);else{let le=P(H,I,O,N);await le.withLock(async()=>{let re=await c(N);if(re===null||re.sessionId!==I||re.pendingRewrite===!0)throw new Ze(I,"Guarded deletion requires confirmed original metadata");let pe=await le.readAll({repair:!1});if(pe.integrityBreakAt!==void 0||pe.repairs.length>0)throw new Ze(I,"Guarded deletion requires intact original history");let j=yr(pe.records);if(j.warnings.length>0)throw new Ze(I,j.warnings.join("; "));let Y=Ih(re);if(Object.hasOwn(re,Js)&&Y===void 0||Y!==void 0&&(Y.records!==pe.cursor.recordCount||Y.lastHash!==pe.cursor.lastHash||Y.messages!==j.messages.length))throw new Ze(I,"Guarded deletion requires confirmed original history");await U.confirm(Object.freeze({meta:Object.freeze(Bn(re)),sourceSnapshotDigest:rn(I,j.messages,0).sourceSnapshotDigest}))})}}}await c(N)!==null&&await P(H,I,O,N).withLock(async()=>{await D(N,U=>(Ws(N,U),U.serveOwnerDeleted=!0,!0))},()=>Ws(N)),i.delete(H),h!==void 0&&(h.unbind(N),await h.remove({sessionId:I,endUserKey:O})),await Dl(N,{recursive:!0,force:!0}),await T(q).remove(I)})}async function F(O,I,q){let H=Gt(O),N=p(H),ie=`${N}|${I}`;return g(ie,async()=>{let U=zt(N,I),ce=await c(U);if(ce===null&&await A(N,H,I)&&(ce=await c(U)),ce===null)return null;let le=P(ie,I,H,U),re=q===void 0?await k(le,I):await le.withLock(async()=>{let Y=async je=>{try{return(await Ul(je)).size}catch($e){if($e.code==="ENOENT")return 0;throw $e}};if(await Y($i.join(U,"manifest.json"))>262144)throw new ct("capacity_exceeded");let oe=await fc(U),Se=await Y($i.join(U,"journal.jsonl"));for(let je of oe?.segments??[]){if(je.status!=="sealed"||je.bytes<=0)throw new ct("rollback_pending");Se+=je.bytes}if(!Number.isSafeInteger(Se)||Se>q)throw new ct("capacity_exceeded");if(ce=await c(U),!ce)throw new ct("family_missing");return k(le,I,!0)}),pe=ce.serveRuntime;if(pe!==void 0&&(t.ownership?.runtimeRecovery!==!0||!pe||!pe.checkpoint||typeof pe.checkpoint!="object"||typeof pe.checkpoint.query!="object"||pe.checkpoint.query===null||pe.checkpoint.query.version!==1||pe.checkpoint.query.sessionId!==I||typeof pe.checkpoint.query.turnId!="string"||typeof pe.checkpoint.historyEpoch!="string"||!pe.checkpoint.historyEpoch||!Number.isSafeInteger(pe.checkpoint.turn)||pe.checkpoint.turn<1||pe.checkpoint.deadline!==void 0&&(!Number.isSafeInteger(pe.checkpoint.deadline)||pe.checkpoint.deadline<0)||pe.historyDigest!==lt(Bt(re.messages))))throw new Ze(I,"Runtime checkpoint history mismatch");let j=xr(ce)?.current;return{...j===void 0?{}:{configuration:j},...pe===void 0?{}:{runtimeCheckpoint:{...pe.checkpoint,query:{...pe.checkpoint.query,messages:re.messages}}},meta:Bn(ce),...ce.serveOwner===void 0?{}:{ownershipRequired:!0},messages:re.messages,...re.recovery!==void 0?{recovery:re.recovery}:{},...re.usageSnapshot!==void 0?{usageSnapshot:re.usageSnapshot}:{},...re.attachmentCheckpoint!==void 0?{attachmentCheckpoint:re.attachmentCheckpoint}:{},...re.attachmentSourceCheckpoint!==void 0?{attachmentSourceCheckpoint:re.attachmentSourceCheckpoint}:{},...re.memorySelectionCheckpoint!==void 0?{memorySelectionCheckpoint:re.memorySelectionCheckpoint}:{}}})}let L=(O,I,q,H)=>{let N=v(O),ie=`${N}|${I}`;return g(ie,async()=>{let U=zt(N,I);return J(P(ie,I,Gt(O),U),q,async()=>{let ce=await c(U);if(!ce)throw new Ze(I,"Configuration session not found");let le=H(ce);return le.changed&&(_l(U,q,ce),await ci(Zt(U),`${JSON.stringify(ce,null,2)}
|
|
10
|
-
`)),le.value})})},Q=O=>{if(O.serveOwner?.phase!=="idle"||O.serveRuntime!==void 0||O.pendingRewrite===!0)throw new Qt("reconciliation_required")},se={...t.ownership===void 0?{}:{initializeConfiguration(O,I,q,H){let N=structuredClone({...q,revision:0});return Qs(N)?L(O,I,H,ie=>{let U=xr(ie);return U?{value:U.current,changed:!1}:(Q(ie),{value:hb(ie,N),changed:!0})}):Promise.reject(new TypeError("Invalid initial configuration"))},inspectConfiguration(O,I,q,H){let N=wo(q);return N?L(O,I,H,ie=>{let U=xr(ie);if(!U)throw new Ze(I,"Configuration not initialized");return{value:Fl(U,N),changed:!1}}):Promise.resolve({status:"rejected",reason:"invalid_configuration"})},commitConfiguration(O,I,q,H,N){let ie=wo(q);return ie?L(O,I,H,U=>{let ce=xr(U);if(!ce)throw new Ze(I,"Configuration not initialized");let le=Fl(ce,ie);if(le.status!=="ready")return{value:le,changed:!1};Q(U);let re=gb(U,ie,N);return{value:re,changed:re.status==="changed"}}):Promise.resolve({status:"rejected",reason:"invalid_configuration"})}},...t.ownership?.runtimeRecovery===!0?{runtimeCheckpoints:!0}:{},...t.ownership===void 0?{}:{claimOwner:(O,I)=>g(`${v(O)}|${I}`,()=>ch(zt(v(O),I),t.ownership,q=>g(`${v(O)}|${I}`,q)))},attachmentCheckpoints:!0,attachmentSourceCheckpoints:!0,memorySelectionCheckpoints:!0,async create(O,I){let q=Gt(O),H=p(q),N=I.sessionId??Sh(),ie=`${H}|${N}`;return g(ie,async()=>{let U=T(H);await U.warm();let ce={...a,...I.title!==void 0?{title:I.title}:{},...typeof I.retentionDays=="number"?{retentionDays:I.retentionDays}:{}},{sessionDir:le,created:re}=await f({storageRoot:H,sessionId:N,cwd:I.cwd??process.cwd(),...Object.keys(ce).length>0?{extra:ce}:{}});if(!re&&await jl(pc(le)))try{await P(ie,N,q,le).withLock(async()=>{},()=>vo(le,I.owner))}catch(pe){throw K(N,pe)}return J(P(ie,N,q,le),I.owner,async()=>{let pe=await D(le,Y=>{ps(Y);let oe=!1;return re&&typeof Y.updatedAt!="string"&&(Y.updatedAt=typeof Y.createdAt=="string"?Y.createdAt:new Date().toISOString(),oe=!0),I.platformSessionId!==void 0&&Y.platformSessionId!==I.platformSessionId&&(Y.platformSessionId=I.platformSessionId,oe=!0),I.title!==void 0&&Y.title!==I.title&&(Y.title=I.title,oe=!0),typeof I.retentionDays=="number"&&Y.retentionDays!==I.retentionDays?(Y.retentionDays=I.retentionDays,oe=!0):I.retentionDays===null&&"retentionDays"in Y&&(delete Y.retentionDays,oe=!0),oe},I.owner);if(pe===null)throw new Ze(N,"meta.json unreadable right after creation");let j=Bn(pe);return await U.upsert(j),j})})},get:(O,I)=>F(O,I),async getMeta(O,I){let q=Gt(O),H=p(q),N;try{N=zt(H,I)}catch{return null}let ie=await c(N);return ie===null&&h!==void 0&&await g(`${H}|${I}`,()=>A(H,q,I))&&(ie=await c(N)),ie===null||typeof ie.sessionId!="string"?null:Bn(ie)},async list(O,I){await e?.checkRoot();let q=Gt(O),H=await T(p(q)).entries(),N=H.filter(ac);if(e){for(let ie of N)if(!await c(zt(p(q),ie.sessionId)))throw new ct("family_missing")}if(h!==void 0){let ie=new Set(H.map(U=>U.sessionId));for await(let U of h.listSessions(q))ie.has(U.sessionId)||N.push(bb(U))}return N.sort((ie,U)=>U.updatedAt.localeCompare(ie.updatedAt)),I?.limit!==void 0?N.slice(0,I.limit):N},async commit(O,I,q,H){let N=Gt(O),ie=p(N),U=`${ie}|${I}`,ce=[...q],le=H.attachmentCheckpoint===void 0?void 0:gc(H.attachmentCheckpoint),re=H.attachmentSourceCheckpoint===void 0?void 0:gh(H.attachmentSourceCheckpoint),pe=H.memorySelectionCheckpoint===void 0?void 0:Lp(H.memorySelectionCheckpoint);return g(U,async()=>{let j=Ki(ce),Y=T(ie);await Y.warm(),await A(ie,N,I);let{sessionDir:oe}=await f({storageRoot:ie,sessionId:I,cwd:process.cwd(),extra:{...a,...j!==void 0?{title:j}:{}}}),Se=P(U,I,N,oe);return J(Se,H.owner,async()=>{if(H.runtimeCheckpoint!==void 0&&(t.ownership?.runtimeRecovery!==!0||H.owner===void 0||H.runtimeCheckpoint.query.sessionId!==I||Bt(H.runtimeCheckpoint.query.messages)!==Bt(ce)))throw new Ze(I,"Invalid runtime checkpoint");t.ownership?.runtimeRecovery===!0&&await D(oe,Fe=>(delete Fe.serveRuntime,!0),H.owner);let je;try{je=await Se.commit({snapshot:ce,rewritten:H.rewritten,...H.usageSnapshot!==void 0||le!==void 0||re!==void 0||pe!==void 0?{trailingEvents:[...H.usageSnapshot===void 0?[]:[H.usageSnapshot],...le===void 0?[]:[le],...re===void 0?[]:[re],...pe===void 0?[]:[pe]]}:{}})}catch(Fe){throw W(I,Fe)}let $e=await D(oe,Fe=>{if(Fe.updatedAt=new Date().toISOString(),H.lastSeq!==void 0&&Rh(Fe,{lastSeq:H.lastSeq,sealed:!1}),Th(Fe,je),H.runtimeCheckpoint!==void 0){let{messages:ft,...kt}=H.runtimeCheckpoint.query;Fe.serveRuntime={checkpoint:{...H.runtimeCheckpoint,query:kt},historyDigest:lt(Bt(ce))}}return!0},H.owner);$e!==null&&await Y.upsert(Bn($e))})})},async recordUsageSnapshot(O,I,q,H){let N=ym(structuredClone(q));if(N===void 0||N.snapshot.sessionId!==I)throw new Ze(I,"recordUsageSnapshot: invalid snapshot");let ie=Gt(O),U=p(ie),ce=`${U}|${I}`;return g(ce,async()=>{let le=zt(U,I);await Ul(Zt(le)).then(()=>!1,Y=>{if(typeof Y=="object"&&Y!==null&&"code"in Y&&Y.code==="ENOENT")return!0;throw Y})&&await A(U,ie,I);let pe=await l(le);if(pe===null||pe.sessionId!==I)throw new Ze(I,"recordUsageSnapshot: session not found");let j=T(U);return await j.warm(),J(P(ce,I,ie,le),H,async()=>{let Y;try{Y=await P(ce,I,ie,le).appendInternalEvents([N])}catch(Se){throw W(I,Se)}let oe=await D(le,Se=>(Th(Se,Y),!0),H);if(oe===null)throw new Ze(I,"recordUsageSnapshot: metadata disappeared");await j.upsert(Bn(oe))})})},delete(O,I){return C(Gt(O),I)},async sweepRetention(O){let I={scanned:0,deleted:[],failures:[]},q=re=>{let pe=Ks(re.maxAgeDays)!==void 0?re.maxAgeDays*864e5:void 0,j=Ks(re.maxPerEndUser),Y=Ks(re.maxBytes);return{...pe!==void 0?{maxAgeMs:pe}:{},...j!==void 0?{maxPerEndUser:j}:{},...Y!==void 0?{maxBytes:Y}:{}}},H=re=>re.maxAgeMs===void 0&&re.maxPerEndUser===void 0&&re.maxBytes===void 0,N=q(O.policy);if(O.policyFor===void 0&&H(N))return I;let ie=O.keep??new Set,U=$i.join(s,e?"offload-sessions":"agent-sessions"),ce;try{ce=(await Nl(U,{withFileTypes:!0})).filter(re=>re.isDirectory()).map(re=>re.name)}catch(re){if(re?.code==="ENOENT")return I;throw re}let le=async(re,pe,j)=>{try{await C(re,pe),I.deleted.push({endUserKey:re,sessionId:pe,reason:j})}catch(Y){I.failures.push({endUserKey:re,sessionId:pe,message:On(Y)})}};for(let re of ce.sort()){let pe=O.policyFor?.(re),{maxAgeMs:j,maxPerEndUser:Y,maxBytes:oe}=pe!==void 0?q(pe):N;if(j===void 0&&Y===void 0&&oe===void 0)continue;let Se=p(re),je=await T(Se).entries(),$e=[];for(let ze of je){if(I.scanned+=1,ie.has(ze.sessionId))continue;let it;try{it=zt(Se,ze.sessionId)}catch{continue}let It=await c(it),Wt=typeof It?.updatedAt=="string"?Date.parse(It.updatedAt):Number.NaN,un=Mh(It);$e.push({sessionId:ze.sessionId,updatedAtMs:Number.isFinite(Wt)?Wt:void 0,maxAgeMs:un!==void 0?un*864e5:j})}let Fe=$e,ft=Fe.filter(ze=>ze.updatedAtMs!==void 0&&ze.maxAgeMs!==void 0&&O.now-ze.updatedAtMs>ze.maxAgeMs);for(let ze of ft)await le(re,ze.sessionId,"max_age");Fe=Fe.filter(ze=>!ft.includes(ze));let kt=(ze,it)=>(it.updatedAtMs??Number.NEGATIVE_INFINITY)-(ze.updatedAtMs??Number.NEGATIVE_INFINITY);if(Fe.sort(kt),Y!==void 0&&Fe.length>Y){let ze=Fe.slice(Math.floor(Y));for(let it of ze)await le(re,it.sessionId,"max_per_end_user");Fe=Fe.slice(0,Math.floor(Y))}if(oe!==void 0&&Fe.length>0){let ze=[];for(let It of Fe)ze.push({sessionId:It.sessionId,bytes:await Bh(zt(Se,It.sessionId))});let it=ze.reduce((It,Wt)=>It+Wt.bytes,0);for(let It=ze.length-1;It>=0&&it>oe;It--){let Wt=ze[It];await le(re,Wt.sessionId,"max_bytes"),it-=Wt.bytes}}}return I},sessionDirOf(O,I){return zt(v(O),I)},async getHistoryPage(O,I,q){if(!Number.isFinite(q.offset)||q.offset<0||!Number.isFinite(q.limit)||q.limit<0)throw new RangeError(`getHistoryPage: "offset" and "limit" must be non-negative finite numbers (got offset=${String(q.offset)}, limit=${String(q.limit)}).`);let H=Math.floor(q.offset),N=Math.floor(q.limit),ie=Gt(O),U=p(ie),ce=`${U}|${I}`;return g(ce,async()=>{let le;try{le=zt(U,I)}catch{return null}let re=await c(le);if(re===null){if(!await A(U,ie,I))return null;re=await c(le)}let pe=Oh(re)!==void 0,j=Ih(re),Y=P(ce,I,ie,le);return re?.serveOwner!==void 0?Kn(await S(Y,I),H,N):t.recovery!==void 0?Kn(await S(Y,I),H,N):Y.withLock(async()=>{if(pe)return Kn(await S(Y,I),H,N);let oe=Math.max(N,1);for(;;){let Se;try{Se=await Y.readTail({minMessages:oe})}catch(it){throw K(I,it)}if(Se.integrityBreakAt!==void 0)throw Y.resetTail(),new Ze(I,`journal hash chain broken at record index ${Se.integrityBreakAt}`);let je=yr(Se.records);if(je.warnings.length>0)throw Y.resetTail(),new Ze(I,je.warnings.join("; "));let $e=je.messages;if(Se.fromSegment===1)return Kn($e,H,N);let Fe=j!==void 0&&j.lastHash===Se.cursor.lastHash&&j.records===Se.cursor.recordCount,ft;if(Fe)ft=j.messages;else if(Se.records.every(it=>it.producer==="serve"&&mc(it)))ft=Se.cursor.recordCount;else return Kn(await S(Y,I),H,N);let kt=ft-$e.length;if(N===0||H>=ft)return{messages:[],total:ft,offset:Math.min(H,ft),nextOffset:Math.min(H,ft)};if(H<kt){oe=ft-H;continue}let ze=So($e,H-kt,N);if(ze===null){oe=$e.length+1;continue}return{messages:$e.slice(ze.start,ze.end),total:ft,offset:kt+ze.start,nextOffset:kt+ze.end}}})})},async recordCwdChange(O,I,q,H){let N=v(O),ie=`${N}|${I}`;return g(ie,async()=>{let U=zt(N,I);return J(P(ie,I,Gt(O),U),H,async()=>{let ce=await D(U,le=>{le.cwd=q.to;let re=Array.isArray(le.cwdHistory)?le.cwdHistory:[];return le.cwdHistory=[...re,{at:q.at,from:q.from,to:q.to}],!0},H);if(ce===null)throw new Ze(I,"recordCwdChange: meta.json unreadable (session not found)");await T(N).upsert(Bn(ce))})})},async recordSeqWatermark(O,I,q,H){let N=v(O),ie=`${N}|${I}`;return g(ie,async()=>{let U=zt(N,I);return J(P(ie,I,Gt(O),U),H,async()=>{let ce=await D(U,le=>Rh(le,q),H);if(ce===null)throw new Ze(I,"recordSeqWatermark: meta.json unreadable (session not found)");await T(N).upsert(Bn(ce))})})},async fork(O,I){if(e)throw new ct("family_mismatch");let q=v(O),H=I.newSessionId??Sh(),N=`${q}|${H}`;return g(N,async()=>{let ie=T(q);await ie.warm();let U=I.title??Ki(I.checkpoint.messages),ce=await Dc({storageRoot:q,sourceSessionId:I.sourceSessionId,checkpoint:I.checkpoint,newSessionId:H,cwd:I.cwd,producer:"serve",...U!==void 0?{extra:{title:U}}:{}}),le=await D(ce.sessionDir,re=>(re.updatedAt=typeof re.createdAt=="string"?re.createdAt:new Date().toISOString(),!0));if(le===null)throw new Ze(H,"meta.json unreadable right after fork");return i.delete(N),await ie.upsert(Bn(le)),{sessionId:ce.sessionId}})},async flush(O){return await Promise.all([...n.values()]),h===void 0?!0:h.flush(O)},readiness(){return h===void 0||h.ready?{ready:!0}:{ready:!1,reason:"store_hot_full"}}};return vh(se),wb(se,{readBounded:F,cold:h!==void 0,...e?{family:e}:{},storageRoot:s,create(O,I){let q=Gt(O),H=p(q),N=I.sessionId,ie=zt(H,N);return g(`${H}|${N}`,async()=>{ti(se);let U=new Date().toISOString(),ce={...a,schemaVersion:1,sessionId:N,cwd:I.cwd??process.cwd(),createdAt:U,updatedAt:U,...I.title!==void 0?{title:I.title}:{},...I.platformSessionId!==void 0?{platformSessionId:I.platformSessionId}:{},...typeof I.retentionDays=="number"?{retentionDays:I.retentionDays}:{}};return dc({sessionDir:ie,raw:ce,register:async le=>{ti(se);let re=T(H);await re.warm();let pe=Bn(le);return await re.upsert(ms(le,pe)),ti(se),pe},publish:async le=>{ti(se),await T(H).upsert(le),ti(se)}})})}}),tc(se,{directory:(O,I)=>zt(v(I.endUserId),O),read:(O,I)=>se.get(I.endUserId,O),...t.ownership?.runtimeRecovery===!0?{readRuntimeCheckpoint:async(O,I)=>(await se.get(I.endUserId,O))?.runtimeCheckpoint??null}:{},readConfirmed:(O,I)=>{let q=Gt(I.endUserId),H=p(q),N=`${H}|${O}`;return g(N,async()=>{try{let ie=await P(N,O,q,zt(H,O)).readAllConfirmed(e?{allowCold:!0}:void 0),U=yr(ie.records);if(U.warnings.length>0)throw new Ze(O,U.warnings.join("; "));return{messages:U.messages}}catch(ie){throw K(O,ie)}})}}),se}import{createHash as Nh,timingSafeEqual as kb}from"node:crypto";var Rt=class extends Error{constructor(n){super(n);this.code=n;this.name="AuthenticationUnavailableError"}code};function Uh(t,e){let n=t.authentication??(e?{}:void 0);if(n===void 0)return{authenticate:c=>t.authenticate(c),close(){}};let i=n.maxPending??128,o=n.timeoutMs??1e4;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(o)||o<1||o>2147483647)throw new RangeError("Invalid authentication limits");let s=0,a=!1,d=new Set;return{authenticate(c,l){if(a||c.aborted||l.destroyed||l.writableEnded)throw new Rt("source_unavailable");if(s>=i)throw new Rt("overloaded");s++;let f,u;try{f=t.authenticate(c),u=f!==null&&typeof f.then=="function"}catch(g){throw s--,g}if(!u){if(s--,a||c.aborted||l.destroyed||l.writableEnded)throw new Rt("source_unavailable");return f}let m=Promise.resolve(f),h=()=>{s--};return m.then(h,h),new Promise((g,p)=>{let v=!1,b=(x,T)=>{v||(v=!0,clearTimeout(w),d.delete(R),c.removeListener("aborted",R),l.removeListener("close",R),x?g(T):p(T))},R=()=>b(!1,new Rt("source_unavailable")),w=setTimeout(R,o);w.unref(),d.add(R),c.once("aborted",R),l.once("close",R),(a||c.aborted||l.destroyed||l.writableEnded)&&R(),m.then(x=>{a||c.aborted||l.destroyed||l.writableEnded?R():b(!0,x)},x=>b(!1,x))})},close(){a=!0;for(let c of[...d])c()}}}function Gl(t){return t===void 0?void 0:/^Bearer\s+(\S+)$/i.exec(t.trim())?.[1]}function Wl(t,e){let n=Nh("sha256").update(t,"utf8").digest(),i=Nh("sha256").update(e,"utf8").digest();return kb(n,i)}function Ys(t,e){let n=Gl(t);return n===void 0?!1:Wl(n,e)}function ki(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 Qe(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 fe(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 Vl=1e3;function Rr(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,Vl);c.unref(),e.once("close",d)}function ui(t){try{return decodeURIComponent(t)}catch{return null}}function Xs(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 on(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 Zs(t){return`: ${$l(t)}
|
|
16
|
-
|
|
17
|
-
`}function ko(t){return on({id:String(t.seq),event:t.type,data:JSON.stringify(t)})}var Fh="v1",qe={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},Ql=/^[\x21-\x7E]{1,128}$/,Jl=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,Yl=/^[a-z][a-z0-9_]*$/,ea=/^image\/(png|jpeg|webp|gif)$/,_e={unauthorized:"unauthorized",forbidden:"forbidden",sessionNotFound:"session_not_found",sessionEnded:"session_ended",sessionLimitExceeded:"session_limit_exceeded",resumeUnavailable:"resume_unavailable",createFailed:"create_failed",validationFailed:"validation_failed",payloadTooLarge:"payload_too_large",midturnBlocksRejected:"midturn_blocks_rejected",callNotFound:"call_not_found",callAlreadyResolved:"call_already_resolved",callExpired:"call_expired",requestNotFound:"request_not_found",requestAlreadyResolved:"request_already_resolved",requestExpired:"request_expired",digestMismatch:"digest_mismatch",methodNotAllowed:"method_not_allowed",invalidJson:"invalid_json",notFound:"not_found",storeCorrupted:"store_corrupted",internalError:"internal_error",draining:"draining",rateLimited:"rate_limited",overloaded:"overloaded",upstreamUnavailable:"upstream_unavailable",turnRunning:"turn_running",checkpointNotFound:"checkpoint_not_found",sessionMismatch:"session_mismatch",checkpointsNotWired:"checkpoints_not_wired",cwdNotAllowed:"cwd_not_allowed",cwdInvalid:"cwd_invalid",cwdUnavailable:"cwd_unavailable",cwdSwitchUnsupported:"cwd_switch_unsupported",forkSourceNotFound:"fork_source_not_found",checkpointImportInvalid:"checkpoint_import_invalid",capabilityDisabled:"capability_disabled",platformUnavailable:"platform_unavailable"},sn={toolRequest:"server.tool.request",toolCancel:"server.tool.cancel",permissionRequest:"server.permission.request",permissionClosed:"server.permission.closed",questionRequest:"server.question.request",questionClosed:"server.question.closed",platformWarning:"server.platform.warning"},xb=new Set(Object.values(sn));function Tr(t){return xb.has(t)}var In="server.replay.gap",Ir={evicted:"evicted",aheadOfLog:"ahead_of_log"},XI=r.object({type:r.literal(In),sessionId:r.string(),requestedAfterSeq:r.number().int(),oldestRetainedSeq:r.number().int().optional(),reason:r.enum([Ir.evicted,Ir.aheadOfLog]).optional(),droppedEvents:r.number().int().nonnegative()}).strict(),ta="ts",na="x-tansr-signature",xo=r.lazy(()=>r.object({type:r.enum(["string","number","boolean","array","object"]),description:r.string().max(qe.toolDescriptionMaxChars).optional(),optional:r.boolean().optional(),items:xo.optional(),properties:r.record(xo).optional()}).strict());function Kl(t){let e=0;if(t.items!==void 0&&(e=Math.max(e,Kl(t.items))),t.properties!==void 0)for(let n of Object.values(t.properties))e=Math.max(e,Kl(n));return e+1}var Rb=r.enum(["irreversible","financial","external","affects-others"]),Ro=r.object({name:r.string().regex(Jl),description:r.string().min(1).max(qe.toolDescriptionMaxChars),parameters:r.record(xo).optional(),readOnly:r.boolean().optional(),effects:r.array(Rb).max(4).refine(t=>new Set(t).size===t.length,{message:"effects must not repeat"}).optional(),timeoutMs:r.number().int().min(qe.toolTimeoutMinMs).max(qe.toolTimeoutCapMs).optional()}).strict().superRefine((t,e)=>{if(t.parameters===void 0)return;let n=JSON.stringify(t.parameters);if(Buffer.byteLength(n,"utf8")>qe.toolParametersMaxBytes){e.addIssue({code:r.ZodIssueCode.custom,path:["parameters"],message:`parameters exceeds ${qe.toolParametersMaxBytes} bytes`});return}for(let[i,o]of Object.entries(t.parameters))Kl(o)>qe.toolParametersMaxDepth&&e.addIssue({code:r.ZodIssueCode.custom,path:["parameters",i],message:`parameter nesting exceeds depth ${qe.toolParametersMaxDepth}`})}),ia=r.object({prompt:r.string().optional(),model:r.string().optional(),profile:r.string().optional(),labels:ls.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(Ql)}).optional(),resume:r.object({sessionId:r.string().min(1)}).optional(),clientTools:r.array(Ro).max(qe.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()}),Xl=r.discriminatedUnion("t",[r.object({t:r.literal("text"),text:r.string().min(1).max(qe.textBlockMaxChars)}),r.object({t:r.literal("image"),mime:r.string().regex(ea),data:r.string().min(1)})]),ra=r.object({prompt:r.string().optional(),blocks:r.array(Xl).min(1).max(qe.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"})}),Zl=r.object({historyEpoch:r.string().min(1).max(128),turnId:r.string().min(1).max(128)}).strict(),Lh=r.object({inputId:r.string().min(1).max(128),target:Zl,content:r.union([r.object({text:r.string().min(1).max(qe.textBlockMaxChars)}).strict(),r.object({blocks:r.array(r.object({t:r.literal("text"),text:r.string().min(1).max(qe.textBlockMaxChars)}).strict()).min(1).max(qe.blocksMaxItems)}).strict()]),ack:r.enum(["memory","durable"]).optional()}).strict(),eu=Kf.superRefine((t,e)=>{t.t==="image"&&!ea.test(t.mime)&&e.addIssue({code:r.ZodIssueCode.custom,path:["mime"],message:"unsupported image mime"})}),Ar=r.discriminatedUnion("status",[r.object({status:r.literal("ok"),content:r.array(eu).min(1).max(qe.receiptContentMaxItems),isError:r.boolean().optional()}),r.object({status:r.literal("error"),message:r.string().min(1).max(qe.receiptErrorMessageMaxChars)})]),tu={expiredOnArrival:"expired_on_arrival"},oa=r.object({digest:r.string().min(1),verdict:r.enum(["allow","deny"]),reason:r.enum([tu.expiredOnArrival]).optional()}),sa=r.object({answers:r.array(r.object({questionId:r.string().min(1),selectedOptionIds:r.array(r.string()),freeText:r.string().max(qe.answerFreeTextMaxChars).optional()})).min(1)});function aa(t){if(t===null||t==="")return[];let e=t.split(",").map(n=>n.trim()).filter(n=>n!=="");if(e.length>qe.excludeTokensMax)return null;for(let n of e)if(!Yl.test(n))return null;return e}function Io(t,e){for(let n of e)if(t===n||t.startsWith(n+"."))return!0;return!1}var Qi=120,nu=4096,iu=r.union([r.boolean(),r.object({label:r.string().max(Qi).optional()})]),da=r.object({instructions:r.string().max(nu).optional(),checkpoint:iu.optional()}),ca=r.object({label:r.string().max(Qi).optional()}),la=r.object({checkpoint:r.boolean().optional()}),ua=r.object({cwd:r.string().min(1)}),To=32*1024*1024,fa="application/octet-stream",pa="import",Ao=32*1024*1024,ru=/^(data:audio\/[a-z0-9.+-]+;base64,|https?:\/\/)/i,ou=["wav","mp3"],su=16,au=64,du=2048,cu=2e4,ma=r.object({model:r.string().min(1).optional(),audio:r.string().regex(ru),language:r.string().min(2).max(su).optional(),diarize:r.boolean().optional(),prompt:r.string().max(du).optional()}),ha=r.object({model:r.string().min(1).optional(),input:r.string().max(cu).refine(t=>t.trim().length>0,{message:"input must not be blank"}),voice:r.string().min(1).max(au).optional(),format:r.enum(ou).optional(),speed:r.number().positive().optional()}),Hh=["transcriptions","speech"];var uu=15e3,fu=3e3,pu=20,Ib=Zs("hb");function Cr(t,e){return on({event:In,data:JSON.stringify({type:In,sessionId:t,requestedAfterSeq:-1,droppedEvents:e})})}var lu=class{#e;#n;#r;#s;#t=!1;#o;#i=[];#a=[];#c=0;#d;#f;#m=0;#p=!1;#w=0;#v=!1;#k=!1;#y=!1;#B=!1;#E=0;#z=0;#S=0;#g=0;constructor(e,n,i){this.#e=e,this.#n=n,this.#r=i.gapFrame,this.#s=i.beforeFlush}write(e){if(this.#y)return;if(this.#k){this.#p&&this.#_();return}let n=Buffer.byteLength(e,"utf8");if(this.#T(n)){if(this.#i.push(e),this.#a.push(n),this.#c+=n,this.#n.onQueued(n),this.#t){this.#i.length>1&&this.#c>this.#n.maxBufferBytes&&this.#U();return}if(this.#p){this.#_();return}if(this.#c>this.#n.maxBufferBytes){this.#N(),this.#t&&this.#i.length>1&&this.#c>this.#n.maxBufferBytes&&this.#U(),this.#p&&this.#i.length>0&&this.#_();return}this.#v||(this.#v=!0,this.#n.markDirty(this))}}replay(e){if(this.#y||this.#k)return;let n=e[Symbol.iterator]();if(this.#d!==void 0||this.#f!==void 0||this.#i.length>0){for(let i=n.next();i.done!==!0;i=n.next())if(this.write(i.value),this.#y||this.#k){n.return?.();return}return}this.#d=n,!this.#p&&!this.#v&&(this.#v=!0,this.#n.markDirty(this))}end(){if(!(this.#y||this.#k)){if(this.#k=!0,this.#s!==void 0){this.#N();return}if(this.#d!==void 0||this.#f!==void 0){this.#p||this.#j();return}for(;this.#i.length>0&&!this.#y;){let e=this.#Y();e!==void 0&&this.#u(e)}this.#y||this.#I()}}stats(){return{paused:this.#p,queuedBytes:this.#c,queuedFrames:this.#i.length,writes:this.#z,frames:this.#S,droppedFrames:this.#g,closed:this.#y,replaying:this.#d!==void 0||this.#f!==void 0}}writeNow(e){this.#y||this.#k||!this.#T(Buffer.byteLength(e,"utf8"))||(this.#S+=1,this.#n.onWrite(1),this.#u(e))}flush(){this.#v=!1,!(this.#y||this.#p)&&this.#N()}#N(){if(this.#y||this.#t||this.#p&&(!this.#k||this.#d!==void 0||this.#f!==void 0))return;if(this.#s===void 0){this.#j();return}this.#t=!0;let e;try{e=this.#s()}catch{this.#U();return}if(typeof e=="boolean"){this.#J(e);return}let n=this.#n.slowGraceMs;this.#o=setTimeout(()=>this.#U(),Number.isFinite(n)&&n>0?n:qe.slowSubscriberGraceMs),this.#o.unref(),Promise.resolve(e).then(i=>this.#J(i),()=>this.#U())}#J(e){if(!this.#y){if(this.#o!==void 0&&clearTimeout(this.#o),this.#o=void 0,this.#t=!1,!e){this.#U();return}if(this.#k&&this.#d===void 0&&this.#f===void 0){for(;this.#i.length>0&&!this.#y;){let n=this.#Y();n!==void 0&&this.#u(n)}this.#y||this.#I();return}this.#j()}}#U(){this.#y||(this.#y=!0,this.#P(),!this.#e.writableEnded&&!this.#e.destroyed&&this.#e.end())}onDrain(){if(this.#y||!this.#p)return;this.#p=!1,this.#w=0,this.#n.onResumed(),(this.#i.length>0||this.#d!==void 0||this.#f!==void 0||this.#k)&&!this.#v&&(this.#v=!0,this.#n.markDirty(this))}onClose(){this.#y=!0,this.#P()}#j(){for(;!this.#p&&!this.#y;){let e=this.#C();if(e===void 0)break;this.#u(e)}this.#k&&!this.#y&&!this.#p&&this.#d===void 0&&this.#f===void 0&&this.#i.length===0&&this.#I()}#C(){if(this.#d!==void 0||this.#f!==void 0){let e=this.#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.#m,this.#f=void 0,this.#m=0);i<e&&this.#d!==void 0;){let o;try{o=this.#d.next()}catch{this.#d=void 0,this.#y=!0,this.#P(),this.#e.destroy();return}if(o.done===!0){this.#d=void 0;break}let s=Buffer.byteLength(o.value,"utf8");if(!this.#T(s))return;if(i>0&&i+s>e){this.#f=o.value,this.#m=s;break}n.push(o.value),i+=s}if(n.length!==0)return this.#S+=n.length,this.#n.onWrite(n.length),n.length===1?n[0]:n.join("")}#Y(){let e=this.#n.maxBufferBytes,n="",i=0;if(Number.isFinite(this.#n.maxFrameBytes)&&this.#E>0){if(n=this.#r?.(this.#E)??"",i=Buffer.byteLength(n,"utf8"),!this.#T(i))return;if(this.#E=0,i+(this.#a[0]??0)>e)return n}let o=this.#i,s=this.#a,a=0,d=0;for(;a<o.length;){let f=s[a];if(a>0&&i+d+f>e||(d+=f,a+=1,i+d>=e))break}let c;a===o.length?(c=o,this.#i=[],this.#a=[]):(c=o.splice(0,a),s.splice(0,a));let l=n+(c.length===1?c[0]:c.join(""));return this.#E>0&&(this.#r!==void 0&&(l=this.#r(this.#E)+l),this.#E=0),this.#S+=c.length,this.#n.onWrite(c.length),this.#n.onDequeued(d),this.#c-=d,l}#I(){!this.#e.writableEnded&&!this.#e.destroyed&&this.#e.end(),this.#y=!0,this.#P()}#u(e){let n=this.#e;if(n.writableEnded||n.destroyed){this.#y=!0,this.#P();return}this.#z+=1;let i=n.socket;i?.cork();let o=n.write(e);i?.uncork(),!o&&!this.#p&&(this.#p=!0,this.#w=this.#n.now(),this.#n.onPaused())}#T(e){return e<=this.#n.maxFrameBytes?!0:(this.#g+=1,this.#n.onDropped(1),this.#K(),!1)}#_(){let{maxBufferBytes:e,slowGraceMs:n,policy:i}=this.#n;if(i==="drop-oldest"){let a=0;for(;this.#c>e&&this.#i.length>0;){this.#i.shift();let d=this.#a.shift();this.#c-=d,this.#n.onDequeued(d),a+=1}a>0&&(this.#E+=a,this.#g+=a,this.#n.onDropped(a));return}let o=this.#c>e,s=Number.isFinite(n)&&n>0&&this.#n.now()-this.#w>=n;(o||s)&&this.#K()}#K(){let e=this.#i.length;e>0&&(this.#g+=e,this.#n.onDropped(e)),this.#n.onSlowDisconnect(),this.#y=!0,this.#P(),this.#e.destroy()}#P(){if(this.#B)return;this.#B=!0,this.#o!==void 0&&clearTimeout(this.#o),this.#o=void 0,this.#t=!1,this.#c>0&&this.#n.onDequeued(this.#c),this.#i=[],this.#a=[],this.#c=0;let e=this.#d;if(this.#d=void 0,this.#f=void 0,this.#m=0,e!==void 0)try{e.return?.()}catch{}this.#p&&(this.#p=!1,this.#n.onResumed()),this.#n.detach(this)}},Er=class{#e=new Set;#n=[];#r=!1;#s;#t;#o;#i;#a;#c;#d;#f=0;#m=0;#p=0;#w=0;#v=0;#k=0;constructor(e={}){this.#t=e.heartbeatMs??uu,this.#o=e.flushSliceMs??pu,this.#c=e.retryMs??fu,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??qe.maxSubscriberBufferBytes,maxFrameBytes:n,slowGraceMs:e.slowGraceMs??qe.slowSubscriberGraceMs,policy:e.onSlowSubscriber??"disconnect",now:i,markDirty:o=>this.#B(o),onPaused:()=>{this.#f+=1},onResumed:()=>{this.#f-=1},onQueued:o=>{this.#m+=o},onDequeued:o=>{this.#m-=o},onWrite:o=>{this.#p+=1,this.#w+=o},onDropped:o=>{this.#v+=o},onSlowDisconnect:()=>{this.#k+=1},detach:o=>this.#z(o)}}get retryMs(){return this.#c}setRetryMs(e){if(!Number.isFinite(e)||e<0)throw new RangeError(`setRetryMs: expected a non-negative finite number, got ${e}`);this.#c=Math.floor(e)}attach(e,n={}){let i=new lu(e,this.#d,n);return this.#e.add(i),this.#e.size===1&&this.#S(),e.on("drain",()=>i.onDrain()),e.on("close",()=>i.onClose()),i.writeNow(on({retryMs:this.#y(),data:""})),i}stats(){return{activeSubscribers:this.#e.size,pausedSubscribers:this.#f,queuedBytes:this.#m,writes:this.#p,frames:this.#w,droppedFrames:this.#v,slowDisconnects:this.#k,heartbeatTimerActive:this.#s!==void 0,retryMs:this.#c}}#y(){return this.#i<=0?this.#c:this.#c+Math.round(this.#a()*this.#i)}#B(e){this.#n.push(e),this.#r||(this.#r=!0,setImmediate(this.#E))}#E=()=>{this.#r=!1;let e=this.#n;this.#n=[];let n=performance.now()+this.#o,i=0;for(;i<e.length&&(e[i].flush(),i+=1,!(performance.now()>=n)););i<e.length&&(this.#n=e.slice(i).concat(this.#n)),this.#n.length>0&&!this.#r&&(this.#r=!0,setImmediate(this.#E))};#z(e){this.#e.delete(e),this.#e.size===0&&this.#g()}#S(){this.#t<=0||this.#s!==void 0||(this.#s=setInterval(()=>this.#N(),this.#t),this.#s.unref())}#g(){this.#s!==void 0&&(clearInterval(this.#s),this.#s=void 0)}#N(){for(let e of this.#e)e.write(Ib)}};function ga(...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 xi=class{#e;#n;#r;#s=[];#t;#o=0;#i=0;#a=0;#c=0;#d;constructor(e,n={}){if(!Number.isInteger(e)||e<1)throw new RangeError(`eventBufferSize must be a positive integer, got ${e}`);let i=n.maxBytes??1/0;if(!(typeof i=="number"&&i>0))throw new RangeError(`eventBufferMaxBytes must be a positive number or Infinity, got ${String(i)}`);let o=n.maxEventBytes??1/0;if(o!==1/0&&(!Number.isSafeInteger(o)||o<1))throw new RangeError("maxEventBytes must be a positive safe integer or Infinity");this.#r=o,this.#e=e,this.#n=i,this.#t=i===1/0&&o===1/0?null:[]}append(e,n){let i=this.#t===null?0:n!==void 0&&n>=0?n:Number.isFinite(this.#r)?Buffer.byteLength(JSON.stringify(e),"utf8"):JSON.stringify(e).length;if(Number.isFinite(this.#r)&&(!Number.isSafeInteger(i)||i>this.#r||i>this.#n)){for(;this.#i>0;)this.#m();this.#c+=1,this.#d=e.seq;return}for(this.#i===this.#e&&this.#m();this.#i>0&&this.#a+i>this.#n;)this.#m();this.#f(e,i)}#f(e,n){let i=this.#s.length;if(this.#i<i){let o=(this.#o+this.#i)%i;this.#s[o]=e,this.#t!==null&&(this.#t[o]=n)}else this.#o===0?(this.#s.push(e),this.#t?.push(n)):(this.#s.splice(this.#o,0,e),this.#t?.splice(this.#o,0,n),this.#o+=1);this.#i+=1,this.#a+=n}#m(){let e=this.#s[this.#o];this.#d=e.seq,this.#c+=1,this.#s[this.#o]=void 0,this.#t!==null&&(this.#a-=this.#t[this.#o],this.#t[this.#o]=0),this.#o=(this.#o+1)%this.#s.length,this.#i-=1}eventsAfter(e){let n=[],i=this.#s.length;for(let o=0;o<this.#i;o++){let s=this.#s[(this.#o+o)%i];s.seq>e&&n.push(s)}return n}oldestSeq(){return this.#i===0?void 0:this.#s[this.#o].seq}hasGapAfter(e){return this.#d!==void 0&&e<this.#d}droppedCount(){return this.#c}size(){return this.#i}bytes(){return this.#a}stats(){return{size:this.#i,bytes:this.#a,dropped:this.#c}}};async function ya(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 Tb=6e4;function*Ab(t){for(let e of t)yield ko(e)}function mu(t,e){if(t.replay!==void 0){t.replay(e);return}for(let n of e)t.write(n)}var va=class{#e=new Map;#n=new WeakSet;#r=new Set;#s=[];#t=0;#o=!1;#i;#a=0;#c=[];#d=0;#f;#m;#p;#w;#v;#k=0;#y=0;constructor(e){this.#i=e,this.#m=e.retentionMs??1/0,this.#p=e.maxRetainedSessions??1/0,this.#w=e.now??Date.now,this.#f=this.#m!==1/0||this.#p!==1/0;let n=e.sweepIntervalMs??Tb;this.#m!==1/0&&n>0&&(this.#v=setInterval(()=>this.sweepNow(),n),this.#v.unref())}adopt(e){let n=e.sessionId;if(this.#o||this.#e.has(n)){try{e.close()}catch(o){this.#S(o)}throw this.#n.has(e)||(this.#n.add(e),this.#g(e,(async()=>{for await(let o of e.events);})())),new Error(this.#o?"session store is closed":`duplicate sessionId from factory: ${n}`)}let i={handle:e,buffer:new xi(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:In,sessionId:e,requestedAfterSeq:n,...s!==void 0?{oldestRetainedSeq:s}:{},droppedEvents:o.buffer.droppedCount()};i.write(on({event:In,data:JSON.stringify(a)}))}return mu(i,Ab(o.buffer.eventsAfter(n))),o.ended?(i.end(),()=>{}):(o.subscribers.add(i),()=>{o.subscribers.delete(i)})}}activeCount(){return this.#a}governanceStats(){return{retainedEnded:this.#e.size-this.#a,evictedByRetention:this.#k,evictedByCap:this.#y}}sweepNow(){if(this.#m===1/0)return;let e=this.#w();for(;;){let n=this.#E();if(n===void 0)break;let[i,o]=n;if(o.endedAt===void 0||e-o.endedAt<this.#m)break;this.#e.delete(i),this.#k+=1}this.#z()}#B(e){for(this.#c.push(e);this.#e.size-this.#a>this.#p;){let n=this.#E();if(n===void 0)break;this.#e.delete(n[0]),this.#y+=1}}#E(){for(;this.#d<this.#c.length;){let e=this.#c[this.#d],n=this.#e.get(e);if(n!==void 0&&n.ended)return[e,n];this.#d+=1}this.#z()}#z(){this.#d>1024&&this.#d*2>this.#c.length&&(this.#c=this.#c.slice(this.#d),this.#d=0)}ringStats(){let e=0,n=0,i=0;for(let o of this.#e.values()){let s=o.buffer.stats();e+=s.size,n+=s.bytes,i+=s.dropped}return{sessions:this.#e.size,size:e,bytes:n,dropped:i}}async closeAll(e={}){this.#o=!0,this.#v!==void 0&&(clearInterval(this.#v),this.#v=void 0);let n=[],i=[];for(let d of this.#e.values()){try{d.handle.close()}catch(c){i.push(c),this.#S(c)}n.push(d.pumpDone)}let{timedOut:o,pending:s,settled:a}=await ya(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?ko(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 Eb}from"node:perf_hooks";var Cb=5e3,_b=1e3,Pb=6e4,Mb=20;function Lt(t){return{"retry-after":String(Math.max(1,Math.ceil(t/1e3)))}}function fi(t,e){let n=t.headers["content-length"];if(typeof n=="string"&&/^\d+$/.test(n)){let i=Number.parseInt(n,10);if(Number.isFinite(i))return Math.min(i,e)}return e}function ni(t,e){let n=Lt(e.retryAfterMs);if(e.reason==="rate_limited"){fe(t,429,_e.rateLimited,ae.rateLimited,void 0,n);return}if(e.reason==="draining"){fe(t,503,_e.draining,ae.draining,void 0,n);return}fe(t,503,_e.overloaded,ae.overloaded,void 0,n)}function Ob(t){let e=Eb({resolution:Mb});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 zh(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??Cb,o=t.rejectLogIntervalMs??Pb,s=e.now??Date.now,a=e.logger,d,c=t.eldSampler;c===void 0&&t.eventLoopDelayP99Ms!==void 0&&(d=Ob(t.eventLoopDelayWindowMs??_b),c=d.p99Ms);let l=0,f=new Map,u=0,m=!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},p=new Map,v=(w,x,T=i)=>{if(g[w]+=1,w!=="draining"&&a!==void 0){let P=s(),W=p.get(w);if(W===void 0||P-W>=o){p.set(w,P);try{a.error(We(ae.admissionRejected,{reason:w,detail:x}))}catch{}}}return{admitted:!1,reason:w,retryAfterMs:T}},b=()=>c?.(),R=()=>m?{reason:"draining"}:c!==void 0&&c()>n.eventLoopDelayP99Ms?{reason:"event_loop_delay"}:null;return{tryAdmitSession(){let w=R();if(w!==null)return v(w.reason,w.reason==="event_loop_delay"?`p99=${(b()??0).toFixed(1)}ms max=${n.eventLoopDelayP99Ms}ms`:"draining");let x=e.activeSessions();return x>=n.maxActiveSessions?v("max_active_sessions",`active=${x} max=${n.maxActiveSessions}`):{admitted:!0}},tryAdmitSse(w){if(l>=n.maxSseConnections)return v("max_sse_connections",`connections=${l} max=${n.maxSseConnections}`);if(w!==void 0){let x=f.get(w)??0;if(x>=n.maxSseConnectionsPerEndUser)return v("max_sse_connections_per_end_user",`connections=${x} max=${n.maxSseConnectionsPerEndUser}`);f.set(w,x+1)}return l+=1,{admitted:!0}},releaseSse(w){if(l=Math.max(0,l-1),w===void 0)return;let x=f.get(w);x!==void 0&&(x<=1?f.delete(w):f.set(w,x-1))},reserveBody(w){return u+w>n.maxInflightBodyBytes?v("max_inflight_body_bytes",`inflight=${u} request=${w} max=${n.maxInflightBodyBytes}`):(u+=w,{admitted:!0})},releaseBody(w){u=Math.max(0,u-w)},async rateLimit(w,x){if(t.rateLimit===void 0)return{admitted:!0};let T;try{T=await t.rateLimit(w,x)}catch(W){try{a?.error(We(ae.requestUnhandled,{method:"rateLimit",path:"/v2/sessions",message:W instanceof Error?W.message:String(W)}))}catch{}return{admitted:!0}}if(T==="allow")return{admitted:!0};let P=Number.isFinite(T.retryAfterMs)&&T.retryAfterMs>0?T.retryAfterMs:i;return v("rate_limited",`retryAfterMs=${P}`,P)},overloaded:R,readiness(){let w=[];return m&&w.push("draining"),c!==void 0&&c()>n.eventLoopDelayP99Ms&&w.push("event_loop_delay"),{ready:w.length===0,reasons:w}},beginDrain(){m=!0},get draining(){return m},retryAfterMs:i,stats(){let w=b();return{activeSessions:e.activeSessions(),sseConnections:l,inflightBodyBytes:u,...w!==void 0?{eventLoopDelayP99Ms:w}:{},draining:m,rejected:{...g},limits:{...n}}},close(){h||(h=!0,d?.close(),d=void 0)}}}import{monitorEventLoopDelay as Xb}from"node:perf_hooks";import{randomUUID as Vb}from"node:crypto";var ba=["messages","inputs","input-capabilities","events","interrupt","history","tool-results","permission","questions","compact","checkpoints","cwd","audio"],Gh=new RegExp(`^\\/v2\\/sessions\\/([^/]+)(?:\\/(${ba.join("|")})(?:\\/([^/]+)(?:\\/(restore|export))?)?)?$`);function Bb(t){let e=t.split("/").map(n=>n.startsWith(":")?"[^/]+":n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\/");return new RegExp(`^${e}$`)}function st(t,e,n){return{method:t,endpoint:e,action:n,pattern:Bb(n)}}var Sa=[st("POST","SDK2-initialize","/v2/sessions/:id/initialize"),st("GET","SDK2-capabilities","/v2/sessions/:id/execution-capabilities"),st("GET","SDK2-boundary","/v2/sessions/:id/execution-boundary"),st("POST","SDK2-binding","/v2/sessions/:id/execution-bindings"),st("GET","SDK2-execution","/v2/sessions/:id/executions/:targetId"),st("POST","SDK2-executor","/v2/executors/connections"),st("POST","SDK2-heartbeat","/v2/executors/:id/heartbeats"),st("GET","SDK2-poll","/v2/executors/:id/operations"),st("POST","SDK2-receipt","/v2/executors/:id/receipts")],Ji=[st("POST","①","/v2/sessions"),st("GET","②","/v2/sessions"),st("GET","③","/v2/sessions/:id"),st("DELETE","④","/v2/sessions/:id"),st("POST","⑤","/v2/sessions/:id/messages"),st("GET","⑥","/v2/sessions/:id/events"),st("POST","⑦","/v2/sessions/:id/interrupt"),st("GET","⑧","/v2/sessions/:id/history"),st("POST","⑨","/v2/sessions/:id/tool-results/:targetId"),st("POST","⑩","/v2/sessions/:id/permission/:targetId"),st("POST","⑪","/v2/sessions/:id/questions/:targetId"),st("POST","⑫","/v2/sessions/:id/compact"),st("GET","⑬","/v2/sessions/:id/checkpoints"),st("POST","⑭","/v2/sessions/:id/checkpoints"),st("POST","⑱","/v2/sessions/:id/checkpoints/import"),st("POST","⑮","/v2/sessions/:id/checkpoints/:targetId/restore"),st("GET","⑰","/v2/sessions/:id/checkpoints/:targetId/export"),st("DELETE","⑯","/v2/sessions/:id/checkpoints/:targetId"),st("POST","⑲","/v2/sessions/:id/cwd"),st("POST","⑳","/v2/sessions/:id/audio/transcriptions"),st("POST","㉑","/v2/sessions/:id/audio/speech"),st("GET","INJ-capabilities","/v2/sessions/:id/input-capabilities"),st("POST","INJ-submit","/v2/sessions/:id/inputs"),st("GET","INJ-status","/v2/sessions/:id/inputs/:targetId")];function Wh(t){for(let e of[...Ji,...Sa])if(e.pattern.test(t))return e.action}var yn="unified-v1",pi={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 wa="/api/manifest",hu="/api/capabilities",Ri=t=>t[1]??"",qb=[{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${Ri(t)}`},{domain:"terminal-profile",match:/^\/api\/terminal\/profile(\/.*)?$/,rewrite:t=>`/v3/terminal-profile${Ri(t)}`},{domain:"terminal",match:/^\/api\/terminal(\/.*)?$/,rewrite:t=>`/v3/terminal${Ri(t)}`},{domain:"cache",match:/^\/api\/cache(\/.*)?$/,rewrite:t=>`/v3/sdk2/cache${Ri(t)}`},{domain:"archive-sync",match:/^\/api\/archive\/sync(\/.*)?$/,rewrite:t=>`/v3/sdk2/archive-sync${Ri(t)}`},{domain:"archive",match:/^\/api\/archive\/bindings(\/.*)?$/,rewrite:t=>`/v3/sdk2/bindings${Ri(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${Ri(t)}`},{domain:"execution",match:/^\/api\/executors(\/.*)?$/,rewrite:(t,e)=>`${e.offloadSessions?"/v3/sdk2":"/v2"}/executors${Ri(t)}`},{domain:"session",match:/^\/api\/approvals\/([^/]+)\/credential$/,rewrite:t=>`/v1/approvals/${t[1]}/credential`}];function Vh(t,e){for(let n of qb){let i=n.match.exec(t);if(i!==null)return{domain:n.domain,legacyPathname:n.rewrite(i,e)}}}function Db(t){let e=t.split("/").map(n=>n.startsWith(":")?"[^/]+":n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\/");return new RegExp(`^${e}$`)}var $h=t=>({template:t,pattern:Db(t)}),jb=[...new Set([...Ji,...Sa].map(t=>t.action.slice(3)))],Kh=["/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",...jb.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"],Nb=Kh.map($h),Ub=["/v1/approvals/:id/credential"];function Fb(t){return t.endsWith("/permission/:targetId")||t.endsWith("/questions/:targetId")?`${t.slice(0,-9)}:ticketId`:t}function gu(t){let e=Lb(t);return e===void 0?void 0:Fb(e)}function Lb(t){if(t==="/v1/approvals/:id/credential")return"/api/approvals/:id/credential";if(t==="/v3/sdk2/session-capabilities")return"/api/capabilities/sessions";if(t==="/v3/sdk2/capabilities")return"/api/capabilities/archive";if(t==="/v3/sdk2/cache/capabilities")return"/api/capabilities/cache";if(t==="/v3/terminal/capabilities")return"/api/capabilities/terminal";if(t==="/v3/sdk2/operations")return"/api/archive/operations";if(t.startsWith("/v3/terminal-observation/"))return`/api/terminal/observation${t.slice(24)}`;if(t.startsWith("/v3/terminal-profile/"))return`/api/terminal/profile${t.slice(20)}`;if(t.startsWith("/v3/terminal/"))return`/api/terminal${t.slice(12)}`;if(t.startsWith("/v3/sdk2/cache/"))return`/api/cache${t.slice(14)}`;if(t.startsWith("/v3/sdk2/archive-sync/"))return`/api/archive/sync${t.slice(21)}`;if(t==="/v3/sdk2/bindings"||t.startsWith("/v3/sdk2/bindings/"))return`/api/archive/bindings${t.slice(17)}`;if(t.startsWith("/v3/sdk2/sessions")||t.startsWith("/v3/sdk2/executors"))return`/api${t.slice(8)}`;if(t.startsWith("/v2/"))return`/api${t.slice(3)}`}var Hb="/api/sessions/:id/capabilities",zb=["/api/sessions/:id/memory/commands/:targetId","/api/sessions/:id/memory/commands","/api/sessions/:id/memory","/api/sessions/:id/configuration"],Gb=[wa,hu,Hb,...zb,...new Set([...Kh,...Ji.map(t=>t.action),...Sa.map(t=>t.action),...Ub].map(gu).filter(t=>t!==void 0))],Wb=Gb.map($h);function Qh(t){for(let e of Nb)if(e.pattern.test(t))return e.template}function Jh(t){for(let e of Wb)if(e.pattern.test(t))return e.template}var $b=/^\/v1\/sessions\/[^/]+\/(messages|events|abort)$/,Kb=/^\/v1\/approvals\/[^/]+\/credential$/,Tn={healthz:"/healthz",readyz:"/readyz",metrics:"/metrics"};function ka(t){if(t.startsWith("/api/"))return Jh(t)??"other";if(t.startsWith("/v3/"))return Qh(t)??"other";switch(t){case"/v1/sessions":case"/v1/status":case Tn.healthz:case Tn.readyz:case Tn.metrics:return t;default:break}let e=$b.exec(t);return e!==null?`/v1/sessions/:id/${e[1]}`:Kb.test(t)?"/v1/approvals/:id/credential":Wh(t)??"other"}var Eo="x-request-id",Qb=/^[A-Za-z0-9._-]{1,128}$/,Jb=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function Yh(t){if(t!==void 0)return Array.isArray(t)?t[0]:t}function xa(t){let e=Yh(t.headers[Eo])?.trim();if(e!==void 0&&Qb.test(e))return e;let n=Yh(t.headers.traceparent)?.trim().toLowerCase();if(n!==void 0){let i=Jb.exec(n);if(i!==null&&i[1]!=="ff"&&!/^0{32}$/.test(i[2]))return i[2]}return Vb()}var Xh=new WeakMap,Zh=new WeakMap;function eg(t,e,n){Xh.set(t,n),Zh.set(e,n)}function Ii(t){return Xh.get(t)}function tg(t){return Zh.get(t)}var Yb=mp.filter(t=>t<=3e4),ng=new WeakMap;function Qn(t=Si){let e=ng.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 ng.set(t,n),n}function Ra(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 ig(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 Ia(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:")?Ia(e.slice(7)):/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function Zb(){let t;try{t=Xb({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 eS(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 tS(t,e){return typeof t=="boolean"?{ready:t,reason:`probe_${e}`}:{ready:t.ready,reason:t.reason??`probe_${e}`}}function rg(t){let e=t.options??{},n=t.now??Date.now,i=e.metrics??Si,o=Qn(i);Ss(Si);let s=Ia(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=Zb(),m=new Set(e.readinessProbes??[]),h=new Set,g=0,p=0,v=!1,b=()=>u.sample(),R=()=>{let S=t.v1Active(),k=t.v2();o.sessionsActive.set(S,{face:"v1"}),o.sessionsActive.set(k?.active??0,{face:"v2"}),k?.pending!==void 0&&o.sessionsPending.set(k.pending),k?.retainedEnded!==void 0&&o.sessionsRetainedEnded.set(k.retainedEnded),o.sseConnectionsActive.set(g);let A=b();o.eventLoopDelayMs.set(A.p50,{stat:"p50"}),o.eventLoopDelayMs.set(A.p99,{stat:"p99"}),o.eventLoopDelayMs.set(A.max,{stat:"max"}),o.residentMemoryBytes.set(process.memoryUsage.rss());let C=t.notifierStats();C!==void 0&&(o.webhookDeliveries.set(C.delivered,{result:"delivered"}),o.webhookDeliveries.set(C.failed,{result:"failed"}),o.webhookDeliveries.set(C.droppedQueueFull,{result:"dropped_queue_full"}),o.webhookDeliveries.set(C.droppedCircuitOpen,{result:"dropped_circuit_open"}));let F=t.sseStats?.();F!==void 0&&o.sseFramesWritten.set(F.frames);let L=t.ringStats?.();L!==void 0&&o.ringEvictions.set(L.dropped);let Q=w();if(Q!==void 0){for(let se of Q.origins){let O={origin:se.origin};o.upstreamInflight.set(se.inflight,O),o.upstreamQueued.set(se.queued+se.tokenQueued,O),o.upstreamBreakerState.set(se.breakerStateCode,O);for(let[I,q]of Object.entries(se.rejected))o.upstreamRejections.set(q,{origin:se.origin,reason:I})}o.upstreamRetriesBudgeted.set(Q.totals.retriesBudgeted)}},w=()=>{if(t.governorStats!==void 0)try{return t.governorStats()}catch{return}},x=i.onCollect(R),T=()=>{let S=[];t.closing()&&S.push("closing");let k=0;for(let A of m){k+=1;try{let C=tS(A(),k);C.ready||S.push(C.reason)}catch{S.push(`probe_${k}_threw`)}}return{ready:S.length===0,reasons:S}},P=()=>{let S=t.v1Active(),k=t.v2(),A=process.memoryUsage(),C=t.notifierStats(),F=t.ringStats?.(),L=w();return{uptimeMs:n()-t.startedAt,closing:t.closing(),sessions:{active:S+(k?.active??0),byFace:{v1:S,v2:k?.active??0},...k?.pending!==void 0?{pending:k.pending}:{},...k?.retainedEnded!==void 0?{retainedEnded:k.retainedEnded}:{}},sse:{connectionsActive:g,framesWritten:t.sseStats?.()?.frames??o.sseFramesWritten.get()},http:{inflight:h.size,requestsTotal:p},replay:{gapTotal:o.replayGaps.get(),ringEvictionsTotal:F?.dropped??o.ringEvictions.get(),...F!==void 0?{ringEvents:F.size,ringBytes:F.bytes}:{}},eventLoopDelayMs:b(),memory:{rssBytes:A.rss,heapUsedBytes:A.heapUsed},...C!==void 0?{notifier:C}:{},...L!==void 0?{upstream:L}:{},readiness:T()}},W=(S,k)=>{let A;if(k.startsWith("/v1/sessions/:id")||k.startsWith("/v2/sessions/:id")||k.startsWith("/api/sessions/:id"))A=3;else if(k.startsWith("/v3/sdk2/sessions/:id"))A=4;else return;let C=S.split("/")[A];if(C===void 0)return;let F=ui(C)??C;return F.length>128?`${F.slice(0,125)}...`:F},K=(S,k)=>{let A=S.method??"GET",C=(S.url??"/").split("?",1)[0],F=ka(C),L={requestId:xa(S),startedAt:n(),method:A,route:F,sse:!1};eg(S,k,L),h.add(L),k.headersSent||k.setHeader(Eo,L.requestId);let Q=W(C,F),se=()=>({requestId:L.requestId,method:A,route:F,...Q!==void 0?{sessionId:Q}:{},...L.endUserId!==void 0?{endUserId:L.endUserId}:{}}),O=k.writeHead,I=!1,q=ie=>{if(I)return;I=!0;let U=eS(k,ie);U!==void 0&&U.startsWith("text/event-stream")&&(L.sse=!0,g+=1,t.log("info",rt.sseOpened,se()))};k.writeHead=function(...U){let ce=O.apply(this,U);return q(U),ce};let H=!1,N=()=>{if(H)return;H=!0,h.delete(L),p+=1,L.sse&&(g=Math.max(0,g-1));let ie=k.headersSent?k.statusCode:0,U=Math.max(0,n()-L.startedAt),ce={method:A,route:F,status:String(ie)};o.httpRequests.inc(ce),o.httpRequestDurationMs.observe(U,{route:F});let le=Ra(ie);le!==void 0&&o.rejections.inc({code:le}),L.sse&&t.log("info",rt.sseClosed,{...se(),reason:k.writableEnded?"ended":"aborted",durationMs:U}),f()&&t.log("info",rt.requestCompleted,{...se(),status:ie,durationMs:U,...L.sse?{sse:!0}:{}})};return k.once("close",N),L},D=(S,k,A,C)=>{let F=A===Tn.healthz||A===Tn.readyz,L=A===Tn.metrics;if(!(F&&a)&&!(L&&d))return!1;if(C!=="GET"&&C!=="HEAD")return fe(k,405,"method_not_allowed",ae.methodNotAllowed,{method:C,path:A},{allow:"GET"}),!0;if(A===Tn.healthz)return Qe(k,200,{status:"ok"}),!0;if(A===Tn.readyz){let se=T();return Qe(k,se.ready?200:503,se),!0}let Q=J();return k.writeHead(200,{"content-type":bs,"content-length":Buffer.byteLength(Q),"cache-control":"no-store"}),k.end(C==="HEAD"?void 0:Q),!0},J=()=>vs([Si,i]);return{metrics:o,registry:i,exposeHealth:a,exposeMetrics:d,trackRequest:K,handleEndpoint:D,stats:P,readiness:T,renderMetrics:J,addReadinessProbe:S=>(m.add(S),()=>{m.delete(S)}),sseActive:()=>g,close:()=>{v||(v=!0,x(),u.dispose())}}}var Co="TANSR_READY ",og=1,sg=["stdout","stderr","none"];function yu(t){let e={v:1,url:t.url,pid:t.pid,readyz:t.readyz};return`${Co}${JSON.stringify(e)}
|
|
18
|
-
`}function ag(t){let e=t.replace(/\r?\n$/u,"");if(!e.startsWith(Co))return;let n;try{n=JSON.parse(e.slice(Co.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 Ta(t,e){let n=t??"stdout";if(n==="none")return;let i=yu(e);try{typeof n=="function"?n(i):n==="stderr"?process.stderr.write(i):process.stdout.write(i)}catch{}}import{createHash as nS,createHmac as dg,randomUUID as iS}from"node:crypto";var cg=["v1","v2"],vu=["v2","v1"];function bu(t){let e=[],n={};for(let i of t.versions){if(i==="v1"){e.push(`v1=${dg("sha256",t.secret).update(t.body,"utf8").digest("hex")}`);continue}let o=[Xr.canonicalPrefix,(t.method??"POST").toUpperCase(),t.path,String(t.timestampMs),t.nonce,nS("sha256").update(t.body,"utf8").digest("hex")].join(`
|
|
19
|
-
`);e.push(`${Xr.prefix}${dg("sha256",t.secret).update(o).digest("hex")}`),n[Xr.headers.timestamp]=String(t.timestampMs),n[Xr.headers.nonce]=t.nonce}return e.length>0&&(n[na]=e.join(", ")),n}var _r=class{#e;#n;#r;#s;#t;#o;#i;#a;#c;#d;#f;#m;#p;#w;#v=new Set;#k=[];#y=new AbortController;#B=!1;#E="closed";#z=0;#S=0;#g=0;#N=0;#J=0;#U=0;constructor(e){this.#e=e.url,this.#n=e.secret,this.#r=[...new Set(e.signatureVersions??vu)],this.#s=(()=>{try{return new URL(e.url).pathname}catch{return""}})(),this.#t=e.maxRetries??qe.notifyMaxRetries,this.#o=e.timeoutMs??qe.notifyTimeoutMs,this.#i=e.backoffMs??qe.notifyBackoffMs,this.#a=e.maxInflight??qe.notifyMaxInflight,this.#c=e.maxQueue??qe.notifyMaxQueue,this.#d=e.breakerFailureThreshold??qe.notifyBreakerFailureThreshold,this.#f=e.breakerOpenMs??qe.notifyBreakerOpenMs,this.#m=e.fetchImpl??fetch,this.#p=e.now??Date.now,this.#w=e.onDeliveryFailure}notify(e){if(!this.#B){if(!this.#j()){this.#N+=1,this.#T(e,0,"circuit_open");return}if(this.#k.length===0&&this.#v.size<this.#a){this.#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.#C(),droppedQueueFull:this.#g,droppedCircuitOpen:this.#N,delivered:this.#J,failed:this.#U}}async close(){this.#B=!0,this.#y.abort(),this.#k.length=0,await Promise.all([...this.#v])}#j(){return this.#E==="closed"?!0:this.#E==="open"&&this.#p()>=this.#z?(this.#E="half_open",!0):!1}#C(){return this.#E==="open"&&this.#p()>=this.#z?"half_open":this.#E}#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.#E="closed"}#u(){if(this.#U+=1,this.#S+=1,!(this.#E!=="closed"||this.#S>=this.#d))return;this.#E="open",this.#z=this.#p()+this.#f;let n=this.#k.splice(0);for(let i of n)this.#N+=1,this.#T(i,0,"circuit_open")}#T(e,n,i){try{this.#w?.({sessionId:e.sessionId,...e.turnId!==void 0?{turnId:e.turnId}:{},url:this.#e,attempts:n,reason:i})}catch{}}async#_(e){let n=JSON.stringify(e),i={"content-type":"application/json"};this.#n!==void 0&&Object.assign(i,bu({secret:this.#n,body:n,versions:this.#r,path:this.#s,timestampMs:this.#p(),nonce:iS()}));let o="unknown";for(let s=1;s<=1+this.#t;s++){if(this.#B||s>1&&(await this.#K(this.#i*2**(s-2)),this.#B))return;try{let a=await this.#m(this.#e,{method:"POST",headers:i,body:n,signal:AbortSignal.any([this.#y.signal,AbortSignal.timeout(this.#o)])});if(await a.arrayBuffer().catch(()=>{}),a.ok){this.#I();return}o=`http_${a.status}`}catch(a){if(this.#B)return;o=a instanceof Error?`${a.name}: ${a.message}`:String(a)}}this.#T(e,1+this.#t,o),this.#u()}#K(e){return new Promise(n=>{let i=()=>{clearTimeout(o),n()},o=setTimeout(()=>{this.#y.signal.removeEventListener("abort",i),n()},e);o.unref(),this.#y.signal.addEventListener("abort",i,{once:!0})})}};var Pr=class{#e;#n;#r;constructor(e,n={}){let{floorSeq:i,...o}=n;if(this.#e=new xi(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 Ea(t){if(Tr(t.type)){let e=t;return on({id:String(t.seq),event:t.type,data:JSON.stringify({...e.payload,[ta]:e.ts})})}return on({id:String(t.seq),data:JSON.stringify(t)})}function*rS(t,e,n){for(let i of t)n&&i.seq<n()||!Tr(i.type)&&Io(i.type,e)||(yield Ea(i))}var Su=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()}},mi=class extends Error{constructor(){super("registry is closing; new sessions are not accepted"),this.name="RegistryClosingError"}},Aa=class{#e=new WeakSet;#n=new WeakMap;#r=new Set;#s=[];#t=new Set;#o=0;#i=new Map;#a=new Map;#c=new Map;#d=[];#f=0;#m=new Map;#p=new Map;#w=0;#v=0;#k;#y;#B;#E;#z;#S;#g;#N;#J;#U;#j;#C;#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.#E=e.eventLog,this.#z=e.retentionMs??qe.retentionMs,this.#S=e.idleTimeoutMs??qe.idleTimeoutMs,this.#g=e.maxSessionsPerEndUser??qe.maxSessionsPerEndUser,this.#N=e.maxRetainedSessions??1/0,this.#J=e.orphanGraceMs??qe.orphanGraceMs,this.#U=e.idleAfterGoneMs??qe.idleAfterGoneMs,this.#j=e.maxSessionLifetimeMs??1/0,this.#C=e.maxTurnsPerSession??1/0,this.#q=e.onSubscribersGone,this.#Y=e.notifyDeferMs??qe.notifyDeferMs,this.#I=e.now??Date.now,this.#u=e.onPumpError,this.#_=e.onSweep,this.#T=e.onTurnEndNotify;let n=e.sweepIntervalMs??qe.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 Su(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 mi;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.#m.set(i,c),a.ids.add(i),a.active+=1,this.#w+=1,c.pumpDone=this.#Te(i,c),i}get(e){let n=this.#i.get(e);if(n!==void 0)return{handle:n.handle,ended:n.ended}}entries(){return[...this.#i.values()].map(e=>({handle:e.handle,ended:e.ended}))}entriesFor(e){let n=this.#a.get(e);if(n===void 0)return[];let i=[];for(let o of n.ids){let s=this.#i.get(o);s!==void 0&&i.push({handle:s.handle,ended:s.ended})}return i}evictEnded(e){let n=this.#i.get(e);n!==void 0&&n.ended&&this.#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.#E!==void 0?this.#E({sessionId:e.sessionId,endUserId:e.endUserId,...n>0?{epochStartSeq:n}:{}}):new Pr(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.#pe(n,new Error("Event publication was evicted")),this.#i.delete(e),this.#m.delete(e),this.#p.delete(e),this.#A(e,n);let i=n.handle.endUserId,o=this.#a.get(i);o!==void 0&&(o.ids.delete(e),this.#b(i,o))}#de(e,n){let i=this.#a.get(n.handle.endUserId);for(i!==void 0&&(i.active=Math.max(0,i.active-1)),this.#w=Math.max(0,this.#w-1),this.#d.push(e);this.#ne()>this.#N;){let o=this.#X();if(o===void 0)break;this.#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.#m.delete(e),this.#m.set(e,n),n.goneSince!==void 0&&(n.goneSince=i,n.goneRunningDecided=!1,n.goneIdleDecided=!1,this.#p.delete(e),this.#p.set(e,n)))}#Re(e,n){n.ended||(n.goneSince=this.#I(),n.goneRunningDecided=!1,n.goneIdleDecided=!1,this.#p.delete(e),this.#p.set(e,n))}#Ie(e,n){n.goneSince=void 0,n.goneRunningDecided=!1,n.goneIdleDecided=!1,this.#p.delete(e),this.#m.delete(e),this.#m.set(e,n)}lastActivityAt(e){return this.#i.get(e)?.lastActivityAt}waitForReplayWatermark(e,n,i){if(e.owner===void 0)return Promise.resolve();let o=this.#i.get(e.sessionId);return!Number.isSafeInteger(n)||n<-1?Promise.reject(new Error("Invalid event publication watermark")):i?.aborted?Promise.reject(i.reason):this.#P?Promise.reject(new mi):!o||o.handle!==e?Promise.reject(new Error("Event publication is unavailable")):this.#ve(o)>=n?Promise.resolve():o.ended||o.logClosed?Promise.reject(new Error("Event publication ended before the requested watermark")):new Promise((s,a)=>{let d=()=>c.settle(i?.reason??new Error("Event publication wait aborted")),c={sequence:n,settle(l){o.replayWaiters.delete(c)&&(i?.removeEventListener("abort",d),l===void 0?s():a(l))}};o.replayWaiters.add(c),i?.addEventListener("abort",d,{once:!0})})}#pe(e,n){if(e.replayWaiters.size===0)return;let i=n===void 0?this.#ve(e):-1;for(let o of e.replayWaiters)(n!==void 0||i>=o.sequence)&&o.settle(n)}#ve(e,n=Math.max(e.epochStartSeq,e.handle.firstSeq?.()??e.epochStartSeq)){return Math.max(e.log.lastSeq(),n-1)}subscribe(e,n,i,o){let s=this.#i.get(e);if(s===void 0)return;let a=()=>{let 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,m=(n>=0||d>0)&&n<l-1;if(c.gap||u||m){let g={type:In,sessionId:e,requestedAfterSeq:n,...c.oldestRetainedSeq!==void 0&&c.oldestRetainedSeq>=d?{oldestRetainedSeq:c.oldestRetainedSeq}:{},droppedEvents:c.dropped,reason:u?Ir.aheadOfLog:Ir.evicted};i.write(on({event:In,data:JSON.stringify(g)}))}if(mu(i,rS(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.#z)break;this.#D(o,s),this.#Q.evictedByRetention+=1}this.#ye();for(let[i,o]of this.#m){if(o.ended){this.#m.delete(i);continue}if(e-o.lastActivityAt<this.#S)break;o.closeRequested||o.subscribers.size>0||this.#ce(i,o)==="idle"&&this.#se(i,o,"idleCloses")}let n=Math.min(this.#J,this.#U);for(let[i,o]of this.#p){if(o.ended){this.#p.delete(i);continue}let s=o.goneSince;if(s===void 0)continue;let a=e-s;if(a<n)break;if(o.closeRequested)continue;let d=this.#ce(i,o);d==="running"&&!o.goneRunningDecided&&a>=this.#J?(o.goneRunningDecided=!0,this.#le(i,o,this.#me(o,"running",a,"interrupt"))):d==="idle"&&!o.goneIdleDecided&&a>=this.#U&&(o.goneIdleDecided=!0,this.#le(i,o,this.#me(o,"idle",a,"close")))}if(this.#j!==1/0)for(let[i,o]of this.#i){if(e-o.adoptedAt<this.#j)break;o.ended||o.closeRequested||this.#se(i,o,"lifetimeCloses")}if(this.#_!==void 0)try{let i=this.#_({activeSessionIds:new Set(this.#i.keys())});i instanceof Promise&&i.catch(o=>this.#u?.("",o))}catch(i){this.#u?.("",i)}}#ce(e,n){try{return n.handle.status()}catch(i){return this.#u?.(e,i),"ended"}}#se(e,n,i,o){if(!n.closeRequested){n.closeRequested=!0,this.#Q[i]+=1;try{n.handle.close(o)}catch(s){n.closeFailure="close_failed",this.#te(s,"close_failed"),this.#u?.(e,s)}}}#me(e,n,i,o){if(this.#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.#Ee(e),e.replayWaiters.size>0&&this.#pe(e,new mi)}runningCount(){let e=0;for(let[n,i]of this.#m)!i.ended&&this.#ce(n,i)==="running"&&(e+=1);return e}interruptRunning(){let e=0;for(let[n,i]of this.#m)i.ended||this.#ce(n,i)!=="running"||(this.#L(n,i),e+=1);return e}broadcastRetry(e){let n=on({retryMs:e,data:""}),i=0;for(let o of this.#m.values())if(!o.ended)for(let s of[...o.subscribers])s.raw.write(n),i+=1;return i}async closeAll(e={}){this.beginClosing(),this.#K!==void 0&&(clearInterval(this.#K),this.#K=void 0);let n=[],i=[];for(let d of this.#i.values()){d.closeRequested=!0;try{d.handle.close()}catch(c){d.closeFailure="close_failed",i.push(c),this.#te(c,"close_failed")}n.push(d.pumpDone)}let{timedOut:o,pending:s,settled:a}=await ya(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=Tr(o.type),d=[...n.subscribers].filter(l=>a||!Io(o.type,l.excludes)),c=d.length>0||Number.isFinite(this.#B)?Ea(o):void 0;if(n.log.append(o,Number.isFinite(this.#B)?c===void 0?void 0:Buffer.byteLength(c,"utf8"):c?.length),c!==void 0)for(let l of d)l.raw.write(c);this.#pe(n)};n.handle.owner===void 0?s():n.handle.owner.publishEvent!==void 0?await n.handle.owner.publishEvent(o,s):await n.handle.owner.fence(s),o.type==="turn.started"?(n.turnEndDecided=!1,this.#Ee(n),n.turns+=1,n.turns>this.#C&&!n.closeRequested&&(this.#L(e,n),this.#se(e,n,"turnCapCloses"))):(o.type==="turn.completed"||o.type==="turn.aborted")&&(this.#be(n,o),n.turns>=this.#C&&!n.closeRequested&&this.#se(e,n,"turnCapCloses"))}}catch(o){i=o,n.closeFailure="publication_failed",n.closeRequested=!0,this.#pe(n,o),this.#Q.pumpErrors+=1;try{n.handle.close()}catch{}this.#u?.(e,o)}finally{n.replayWaiters.size>0&&this.#pe(n,i??new Error("Event publication ended before the requested watermark")),this.#he(n.handle),n.ended=!0,n.endedAt=this.#I(),this.#Ee(n),this.#de(e,n);for(let o of[...n.subscribers])o.raw.end();n.subscribers.clear()}}#Ee(e){e.deferredNotify!==void 0&&(clearTimeout(e.deferredNotify),e.deferredNotify=void 0)}#be(e,n){if(!e.turnEndDecided&&(e.turnEndDecided=!0,!(this.#T===void 0||this.#P))){if(e.subscribers.size===0){this.#je(e,n);return}this.#Y<=0||(this.#Ee(e),this.#Q.deferredNotifies+=1,e.deferredNotify=setTimeout(()=>{e.deferredNotify=void 0,!(this.#P||e.ended||e.subscribers.size>0)&&(this.#Q.deferredNotifySent+=1,this.#je(e,n))},this.#Y),e.deferredNotify.unref())}}#je(e,n){if(this.#T===void 0)return;let i=n.turnId,o=n.type==="turn.completed"||n.type==="turn.aborted"?n.reason:void 0;this.#T({sessionId:e.handle.sessionId,endUserId:e.handle.endUserId,...i!==void 0?{turnId:i}:{},status:n.type==="turn.completed"?"completed":"aborted",...o!==void 0?{reason:o}:{},lastSeq:n.seq,ts:this.#I()})}};import{setMaxListeners as ik}from"node:events";import{randomUUID as Ww}from"node:crypto";import{randomUUID as aS}from"node:crypto";import{types as dS}from"node:util";var _o=class extends Error{constructor(n){super(n);this.code=n;this.name="ArchiveHttpEventError"}code},oS=262317;function Yi(){let t=new Error("Archive event subscription aborted");return t.name="AbortError",t}async function wu(t,e){if(e.aborted)throw t.catch(()=>{}),Yi();let n,i=new Promise((o,s)=>{n=()=>s(Yi()),e.addEventListener("abort",n,{once:!0})});try{return await Promise.race([t,i])}finally{n&&e.removeEventListener("abort",n)}}function sS(t,e){return e.aborted||t.destroyed?Promise.reject(Yi()):new Promise((n,i)=>{let o=()=>{t.removeListener("drain",s),t.removeListener("close",a),e.removeEventListener("abort",a)},s=()=>{o(),n()},a=()=>{o(),i(Yi())};t.once("drain",s),t.once("close",a),e.addEventListener("abort",a,{once:!0})})}async function lg(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 wu(t.authorize(),o),o.aborted))throw Yi()};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(),Yi();return s=l,l});for(s=await wu(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 wu(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>oS)throw new _o("internal_error");n.write(f)||(await sS(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 ku={ackBytes:262144,requestEnvelopeBytes:1024,responseEnvelopeBytes:4096,requestBytes:263168,responseBytes:528384},He={};He.ArchiveAckRequest=r.object({protocol:r.literal("sdk2-ext-v1"),request:r.lazy(()=>He.RequestIdentity),bindingId:r.lazy(()=>He.Id),expectedRevision:r.lazy(()=>He.Sequence),generations:r.lazy(()=>He.Generations),sourceId:r.lazy(()=>He.Id),sourceGeneration:r.lazy(()=>He.Id),coverage:r.lazy(()=>He.Coverage),attachments:r.array(r.lazy(()=>He.ArchiveArtifactReceipt)).min(0).max(128).refine(t=>new Set(t.map(e=>JSON.stringify(e))).size===t.length),ackFormat:r.lazy(()=>He.ArchiveAckFormat),payloads:r.array(r.lazy(()=>He.ArchiveArtifactReceipt)).min(1).max(128).refine(t=>new Set(t.map(e=>JSON.stringify(e))).size===t.length)}).strict();He.RequestIdentity=r.object({requestId:r.lazy(()=>He.Id),operationEpoch:r.lazy(()=>He.Id)}).strict();He.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);He.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);He.Generations=r.object({historyEpoch:r.lazy(()=>He.LegacyId),deletionGeneration:r.lazy(()=>He.Sequence),projectionRevision:r.lazy(()=>He.Sequence)}).strict();He.LegacyId=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);He.Coverage=r.object({fromSequence:r.lazy(()=>He.RecordSequence),throughSequence:r.lazy(()=>He.RecordSequence),headDigest:r.lazy(()=>He.Digest)}).strict();He.RecordSequence=r.lazy(()=>He.Sequence).refine(t=>t!=="0");He.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));He.ArchiveArtifactReceipt=r.object({artifactId:r.lazy(()=>He.Id),sha256:r.lazy(()=>He.Digest),state:r.literal("durably-stored")}).strict();He.ArchiveAckFormat=r.literal("split-receipts-v1");He.MutationReceipt=r.object({protocol:r.literal("sdk2-ext-v1"),request:r.lazy(()=>He.RequestIdentity),bindingId:r.lazy(()=>He.Id),operation:r.union([r.literal("binding-create"),r.literal("archive-ack"),r.literal("material-response"),r.literal("binding-close")]),semanticDigest:r.lazy(()=>He.Digest),state:r.union([r.literal("accepted"),r.literal("completed"),r.literal("rejected")]),revision:r.lazy(()=>He.Sequence),outcomeRef:r.lazy(()=>He.Id)}).strict();He.AckRebaseRequest=r.object({protocol:r.literal("sdk2-ext-v1"),bindingId:r.lazy(()=>He.Id),previous:r.lazy(()=>He.ArchiveAckRequest),request:r.lazy(()=>He.RequestIdentity)}).strict();He.AckRebaseReceipt=r.object({protocol:r.literal("sdk2-ext-v1"),bindingId:r.lazy(()=>He.Id),previous:r.lazy(()=>He.ArchiveAckRequest),request:r.lazy(()=>He.RequestIdentity),next:r.lazy(()=>He.ArchiveAckRequest),receipt:r.lazy(()=>He.MutationReceipt)}).strict();function xu(t){let e=He[t];if(!e)throw new Error("Unknown archive recovery contract");return e}var Ti="sdk2-ext-v1",Ru=262144,cS=611+512*6+38+8+6+8+128+4*Math.ceil(262144/3),ut=r.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._~-]*$/),Po=r.string().min(1).refine(t=>[...t].length<=512),an=r.string().max(19).regex(/^(0|[1-9][0-9]*)$/).refine(t=>/^(0|[1-9][0-9]{0,18})$/.test(t)&&BigInt(t)<=9223372036854775807n),er=r.string().regex(/^[a-f0-9]{64}$/),Mo=r.object({historyEpoch:Po,deletionGeneration:an,projectionRevision:an}).strict(),Oo=r.object({sessionId:Po,generations:Mo,sourceSnapshotDigest:er}).strict(),Zi=r.object({operationEpoch:ut,requestId:ut}).strict(),tr={protocol:r.literal(Ti),bindingId:ut},St=(t,e)=>r.number().int().min(t).max(e),ug=r.object({artifactId:ut,sha256:er,state:r.literal("durably-stored")}).strict(),lS=r.object({...tr,request:Zi,ackFormat:r.literal("split-receipts-v1"),expectedRevision:an,generations:Mo,sourceId:ut,sourceGeneration:ut,coverage:r.object({fromSequence:an.refine(t=>t!=="0"),throughSequence:an.refine(t=>t!=="0"),headDigest:er}).strict(),payloads:r.array(ug).min(1).max(128),attachments:r.array(ug).max(128)}).strict(),uS=r.object({...tr,materialRequestId:ut,target:Oo,sourceId:ut,sourceGeneration:ut,artifactId:ut,offset:St(0,1048576),bytes:St(0,65536),chunkSha256:er,base64:r.string().max(87384).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict(),fg=r.object({uploadId:ut}).strict(),fS=r.object({...tr,request:Zi,materialRequestId:ut,target:Oo,sourceId:ut,sourceGeneration:ut,results:r.array(r.object({recordId:ut,digest:er,payload:fg,attachments:r.array(fg).max(128)}).strict()).min(1).max(32)}).strict(),yg=r.enum(["archive-transfer-v1","context-materials-v1"]),_a=t=>r.array(yg).min(t).max(2).refine(e=>new Set(e).size===e.length).readonly(),vg=r.object({controlBytes:St(1024,262144),recordBytes:St(1024,262144),pageRecords:St(1,128),pageBytes:St(1024,1048576),attachmentBytes:St(1024,33554432),chunkBytes:St(1024,262144),materialConcurrent:St(1,2),materialQueue:St(1,16),materialCandidates:St(1,32),materialBytes:St(1024,1048576),materialDeadlineMs:St(1e3,3e4),pendingRecords:St(1,4096),pendingBytes:St(1048576,67108864),inflightReserveBytes:St(1048576,16777216),offlineMs:St(1e3,864e5),eventRetentionMs:St(1e3,6e5),eventRetentionFrames:St(1,4096),eventRetentionBytes:St(1024,8388608),terminalReceiptRetentionMs:St(6e4,6048e5),epochLifetimeMs:St(6e4,864e5),materialChunkBytes:St(1,65536)}).strict().refine(t=>t.inflightReserveBytes<=t.pendingBytes),Iu=r.object({id:ut,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)),pS=r.object({applicationScopeId:ut,endUserId:Po,authorizationRevision:an}).strict(),bg=r.enum(["active","backpressured","closing","closed"]),mS=r.object({protocol:r.literal(Ti),availability:r.literal("legacy-complete"),capabilities:_a(1),limits:vg,operationEpoch:Iu,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)),hS=r.object({protocol:r.literal(Ti),target:Oo,revision:an,bindingId:ut.nullable(),operationEpoch:Iu.nullable()}).strict(),pg=r.object({...tr,scope:pS,target:Oo,revision:an,state:bg,sourceId:ut,acceptedCapabilities:_a(1),rejectedCapabilities:r.array(r.object({capability:yg,reason:r.enum(["unsupported_capability","not_authorized"])}).strict()).max(2).readonly(),availability:r.literal("legacy-complete"),operationEpoch:Iu.nullable(),limits:vg,archiveAckFormat:r.literal("split-receipts-v1").nullable()}).strict().refine(t=>t.archiveAckFormat===(t.acceptedCapabilities.includes("archive-transfer-v1")?"split-receipts-v1":null)),gS=r.object({fromSequence:an.refine(t=>t!=="0"),throughSequence:an.refine(t=>t!=="0"),headDigest:er}).strict(),yS=r.object({...tr,revision:an,generations:Mo,sourceId:ut,sourceGeneration:ut,publishedThroughSequence:an.nullable(),acknowledgedCoverage:gS.nullable(),releasableThroughSequence:an.nullable(),pendingBytes:St(0,67108864),pendingRecords:St(0,4096),sessionPersistence:r.literal("unchanged"),state:bg}).strict(),vS=r.object({protocol:r.literal(Ti),request:Zi,target:Oo,expectedRevision:an,requiredCapabilities:_a(1),optionalCapabilities:_a(0),archive:r.object({strategy:r.literal("single-authorized-source"),sourceId:ut,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))),bS=r.object({...tr,request:Zi,expectedRevision:an,generations:Mo}).strict(),mg=r.object({...tr,request:Zi,operation:r.enum(["binding-create","archive-ack","binding-close"]),semanticDigest:er,state:r.literal("completed"),revision:an,outcomeRef:ut}).strict(),Sg={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 Ma(t){return Sg[t]}var Pa=class extends Error{constructor(n){super(n);this.code=n;this.name="ArchiveHttpError"}code};function we(t){throw new Pa(t)}function qt(t,e){let n=t.safeParse(e);return n.success||we("invalid_request"),n.data}function Xi(t,e,n){try{let i=bi(nn(e,{maxBytes:n})),o=t.safeParse(i);if(o.success)return o.data}catch{}return we("internal_error")}function SS(t,e){try{(!t||typeof t!="object"||dS.isProxy(t)||Array.isArray(t)||![null,Object.prototype].includes(Object.getPrototypeOf(t)))&&we("internal_error");let n=Object.getOwnPropertyDescriptors(t),i={};for(let o of Reflect.ownKeys(n)){typeof o!="string"&&we("internal_error");let s=n[o];(!s.enumerable||!Object.hasOwn(s,"value"))&&we("internal_error"),i[o]=bi(nn(s.value))}return Tu(i,e),qt(xu("AckRebaseReceipt"),i)}catch{return we("internal_error")}}function wS(t){if(t instanceof Pa||t instanceof _o)return t.code;if(t instanceof nh)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 Tl&&t.code==="dependency_held")return"source_unavailable";if(t instanceof fs||t instanceof sp||t instanceof eh||t instanceof Tl)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 Tu(t,e){let n=JSON.stringify(t,(o,s)=>{if(typeof s=="number"&&(!Number.isSafeInteger(s)||s<0||Object.is(s,-0)))throw new TypeError("Invalid response integer");return s&&typeof s=="object"&&!Array.isArray(s)?Object.fromEntries(Object.entries(s).sort(([a],[d])=>a<d?-1:a>d?1:0)):s});if(n===void 0)throw new TypeError("Missing response");let i=Buffer.from(n);return i.length>e&&we("capacity_exceeded"),i}function ii(t,e,n,i=Ru){if(t.destroyed||t.writableEnded)return;let o=Tu(n,i);t.writeHead(e,{"content-type":"application/json; charset=utf-8","content-length":o.length,"cache-control":"no-store"}),t.end(o)}function wg(t){try{return decodeURIComponent(t)}catch{return we("invalid_request")}}function hi(t,e,n=[]){let i=Object.create(null);for(let o of t.split("&")){let s=o.indexOf("=");(s<1||o.includes("+"))&&we("invalid_request");let a=o.slice(0,s),d=wg(o.slice(s+1));(![...e,...n].includes(a)||Object.hasOwn(i,a)||d==="")&&we("invalid_request"),i[a]=d}return e.some(o=>!Object.hasOwn(i,o))&&we("invalid_request"),i.protocol!==Ti&&we("protocol_version_mismatch"),i}function Ca(t,e,n){return/^(0|[1-9][0-9]*)$/.test(t)||we("invalid_request"),qt(St(e,n),Number(t))}function hg(t){return qt(Mo,{historyEpoch:t.historyEpoch,deletionGeneration:t.deletionGeneration,projectionRevision:t.projectionRevision})}function gg(t,e){return t.historyEpoch===e.historyEpoch&&t.deletionGeneration===e.deletionGeneration&&t.projectionRevision===e.projectionRevision}async function kS(t,e,n=!1){let i=t.headers["content-type"]??"";(!/^application\/json(?:\s*;\s*charset\s*=\s*(?:utf-8|"utf-8"))?\s*$/i.test(i)||t.headers["content-encoding"]!==void 0&&t.headers["content-encoding"].toLowerCase()!=="identity")&&we("invalid_request");let o=[],s=0;for await(let d of t){let c=Buffer.isBuffer(d)?d:Buffer.from(d);s+=c.length,s>e&&we("payload_too_large"),o.push(c)}let a;try{let d=Buffer.concat(o);if(n){let c=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(d);a=JSON.parse(c),Tu(a,e).equals(d)||we("invalid_request")}else a=bi(d,{maxBytes:e})}catch{return we("invalid_request")}return(!a||typeof a!="object"||Array.isArray(a))&&we("invalid_request"),a.protocol!==Ti&&we("protocol_version_mismatch"),a}function kg(t){let e=t.host.controlBytes??Ru;qt(St(1024,Ru),e),qt(ut,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=aS(),f=(async()=>{(n>=128||t.admission.overloaded())&&we("capacity_exceeded"),n++,a=!0,Buffer.byteLength(s)>8192&&we("payload_too_large"),s.includes("#")&&we("invalid_request");let u=s.indexOf("?"),m=u<0?s:s.slice(0,u),h=u<0?"":s.slice(u+1),g=m.split("/").slice(3).map(wg),p=i.method??"GET";p!=="GET"&&p!=="POST"&&we("invalid_request"),p==="GET"&&(i.headers["transfer-encoding"]!==void 0||i.headers["content-length"]!==void 0&&i.headers["content-length"]!=="0")&&we("invalid_request"),p==="POST"&&u>=0&&we("invalid_request");let v=p==="POST"&&g.length===4&&g[0]==="bindings"&&g[2]==="archive"&&g[3]==="ack-rebases";v&&(c+=ku.requestEnvelopeBytes),p==="POST"&&(t.admission.reserveBody(c).admitted||we("capacity_exceeded"),d=!0);let b=p==="POST"?await kS(i,c,v):void 0,R=async I=>{let q;try{q=await t.authenticate(i,o)}catch(H){return H instanceof Rt?we(H.code==="overloaded"?"capacity_exceeded":"source_unavailable"):we("unauthorized")}return(!q?.endUserId||I!==void 0&&q.endUserId!==I)&&we("unauthorized"),(i.aborted||o.destroyed||o.writableEnded)&&we("unauthorized"),q.endUserId},w=async()=>{let I=await R();return(await t.admission.rateLimit(i,I)).admitted||we("capacity_exceeded"),await R(I),I};if(g.length===1&&g[0]==="capabilities"&&p==="GET"){u>=0&&we("invalid_request");let I=await w(),q=t.host.capabilities;q||we("unsupported_capability");let H=await q.call(t.host,I);await R(I),t.host.capabilities!==q&&we("forbidden"),ii(o,200,Xi(mS,H,e),e);return}let x=g.length===3&&g[0]==="sessions"&&g[2]==="binding-target"&&p==="GET",T=g.length===1&&g[0]==="bindings"&&p==="POST",P;if(g.length===1&&g[0]==="operations"&&p==="GET"){let I=hi(h,["protocol","operation","operationEpoch","requestId"],["bindingId","sessionId"]);I.operation==="binding-create"?((I.bindingId!==void 0||I.sessionId===void 0)&&we("invalid_request"),P=I):(I.sessionId!==void 0||I.bindingId===void 0)&&we("invalid_request")}if(x||T||P){let I,q,H;x?(hi(h,["protocol"]),I=qt(Po,g[1])):T?(q=qt(vS,b),I=q.target.sessionId,l=q.request.requestId):(I=qt(Po,P.sessionId),H=qt(Zi,{operationEpoch:P.operationEpoch,requestId:P.requestId}),l=H.requestId);let N=await w(),ie=t.host.resolveSession;ie||we("unsupported_capability");let U=ie.call(t.host,N,I);U||we("forbidden");let ce=async()=>{await R(N),(t.host.resolveSession!==ie||ie.call(t.host,N,I)!==U)&&we("forbidden")};if(x){let le=U.readTarget,re=await le.call(U);await ce(),U.readTarget!==le&&we("forbidden");let pe=Xi(hS,re,e);pe.target.sessionId!==I&&we("forbidden"),ii(o,200,pe,e)}else if(q){let le=U.create;le||we("unsupported_capability");let re=await le.call(U,q);await ce(),U.create!==le&&we("forbidden");let pe=Xi(pg,re,e);(pe.target.sessionId!==I||pe.scope.applicationScopeId!==t.host.applicationScopeId||pe.scope.endUserId!==N)&&we("forbidden"),ii(o,201,pe,e)}else{let le=U.queryCreate;le||we("unsupported_capability");let re=await le.call(U,H);await ce(),U.queryCreate!==le&&we("forbidden"),re===null&&we("receipt_expired");let pe=Xi(mg,re,e);(pe.operation!=="binding-create"||pe.request.operationEpoch!==H.operationEpoch||pe.request.requestId!==H.requestId)&&we("internal_error"),ii(o,200,pe,e)}return}let W=["historyEpoch","deletionGeneration","projectionRevision"],K,D,J,S=Object.create(null),k=b;if(g.length===1&&g[0]==="operations"&&p==="GET")S=hi(h,["protocol","operation","bindingId","operationEpoch","requestId"]),K=qt(ut,S.bindingId),qt(Zi,{operationEpoch:S.operationEpoch,requestId:S.requestId}),["archive-ack","material-response","binding-close"].includes(S.operation)||we("unsupported_capability"),l=S.requestId,D="operation";else if(g[0]!=="bindings"&&we("invalid_request"),K=qt(ut,g[1]),g.length===2&&p==="GET")hi(h,["protocol"]),D="view";else if(g.length===4&&g[2]==="archive"&&g[3]==="status"&&p==="GET")hi(h,["protocol"]),D="archive-status";else if(g.length===3&&g[2]==="close"&&p==="POST")k=qt(bS,b),D="close";else if(g.length===3&&g[2]==="events"&&p==="GET"){S=hi(h,["protocol"]);let I=[];for(let q=0;q<i.rawHeaders.length;q+=2)i.rawHeaders[q].toLowerCase()==="last-event-id"&&I.push(i.rawHeaders[q+1]);I.length>1&&we("invalid_request"),I.length===1&&(J=qt(ut,I[0])),D="events"}else if(g.length===4&&g[2]==="archive"&&g[3]==="records"&&p==="GET")S=hi(h,["protocol",...W,"limit","maxBytes"],["afterSequence"]),k={generations:hg(S),afterSequence:S.afterSequence===void 0?null:qt(an,S.afterSequence),limit:Ca(S.limit,1,128),maxBytes:Ca(S.maxBytes,1024,1048576)},D="records";else if(g.length===5&&g[2]==="archive"&&g[3]==="artifacts"&&p==="GET")S=hi(h,["protocol",...W,"offset","maxBytes"]),k={generations:hg(S),artifactId:qt(ut,g[4]),offset:Ca(S.offset,0,33554431),maxBytes:Ca(S.maxBytes,1,262144)},D="artifact";else if(g.length===4&&g[2]==="archive"&&g[3]==="acks"&&p==="POST")k=qt(lS,b),D="ack";else if(g.length===4&&g[2]==="archive"&&g[3]==="ack-rebases"&&p==="POST")k=qt(xu("AckRebaseRequest"),b),D="ack-rebase";else if(g.length===3&&g[2]==="material-responses"&&p==="POST")k=qt(fS,b),D="response";else if(g[2]==="materials"&&(g.length===4||g.length===6||g.length===7))if(qt(ut,g[3]),g.length>4&&(g[4]!=="uploads"&&we("invalid_request"),qt(ut,g[5])),g.length===7&&g[6]==="chunks"&&p==="POST")k=qt(uS,b),D="upload";else if(p==="GET"&&g.length!==7)hi(h,["protocol"]),D=g.length===4?"status":"upload-status";else return we("invalid_request");else return we("unsupported_capability");if(p==="POST"){let I=k;(I.bindingId!==K||D==="upload"&&(I.materialRequestId!==g[3]||I.artifactId!==g[5]))&&we("invalid_request"),I.request&&(l=I.request.requestId)}if(D==="upload"){let I=k,q=Buffer.from(I.base64,"base64");(q.length!==I.bytes||q.toString("base64")!==I.base64||ip(q)!==I.chunkSha256)&&we("invalid_request")}let A={endUserId:await w()},C=t.host.resolve(A.endUserId,K);C||we("forbidden");let F=C.control.read();if((!F||F.registration.bindingId!==K||F.registration.scope.endUserId!==A.endUserId||F.registration.scope.applicationScopeId!==t.host.applicationScopeId)&&we("forbidden"),F.state==="unbound"&&we("binding_closed"),D==="view"||D==="archive-status"||D==="close"||D==="ack-rebase"){let I=async()=>{await R(A.endUserId),t.host.resolve(A.endUserId,K)!==C&&we("forbidden");let q=C.control.read();(!q||q.registration.bindingId!==K||q.registration.scope.endUserId!==A.endUserId||q.registration.scope.applicationScopeId!==t.host.applicationScopeId)&&we("forbidden")};if(D==="view"){let q=C.readView;q||we("unsupported_capability");let H=await q.call(C);await I(),C.readView!==q&&we("forbidden");let N=Xi(pg,H,e);(N.bindingId!==K||N.scope.applicationScopeId!==t.host.applicationScopeId||N.scope.endUserId!==A.endUserId||N.target.sessionId!==F.registration.sessionId)&&we("forbidden"),ii(o,200,N,e)}else if(D==="archive-status"){F.acceptedCapabilities.includes("archive-transfer-v1")||we("unsupported_capability");let q=C.readArchiveStatus;q||we("unsupported_capability");let H=await q.call(C);await I(),C.readArchiveStatus!==q&&we("forbidden");let N=Xi(yS,H,e);(N.bindingId!==K||N.sourceId!==F.registration.sourceId||N.sourceGeneration!==F.registration.sourceGeneration)&&we("forbidden"),ii(o,200,N,e)}else if(D==="ack-rebase"){F.acceptedCapabilities.includes("archive-transfer-v1")||we("unsupported_capability");let q=C.rebaseAck;q||we("unsupported_capability");let H=k,N=await q.call(C,H);await I(),C.rebaseAck!==q&&we("forbidden");let ie=2*e+ku.responseEnvelopeBytes,U=SS(N,ie),ce=(le,re)=>nn(le).toString()===nn(re).toString();(U.bindingId!==K||!ce(U.previous,H.previous)||!ce(U.request,H.request)||!ce(U.next.request,H.request)||BigInt(U.next.expectedRevision)<=BigInt(H.previous.expectedRevision)||!ce({...U.next,request:H.previous.request,expectedRevision:H.previous.expectedRevision},H.previous)||U.receipt.operation!=="archive-ack"||!ce(U.receipt.request,U.next.request)||U.receipt.bindingId!==K)&&we("internal_error"),ii(o,200,U,ie)}else{let q=C.close;q||we("unsupported_capability");let H=k,N=await q.call(C,H);await I(),C.close!==q&&we("forbidden");let ie=Xi(mg,N,e);(ie.bindingId!==K||ie.operation!=="binding-close"||ie.request.operationEpoch!==H.request.operationEpoch||ie.request.requestId!==H.request.requestId)&&we("internal_error"),ii(o,200,ie,e)}return}if(D==="events"){let I=C.events;I||we("unsupported_capability");let q=A.endUserId;if(i.aborted||o.destroyed||o.writableEnded)return;t.admission.tryAdmitSse(q).admitted||we("capacity_exceeded"),o.once("close",()=>t.admission.releaseSse(q)),i.socket.setTimeout(0);let H=async()=>{let N;try{N=await t.authenticate(i,o)}catch(ce){return ce instanceof Rt?we(ce.code==="overloaded"?"capacity_exceeded":"source_unavailable"):we("unauthorized")}(!N?.endUserId||N.endUserId!==q)&&we("unauthorized");let ie=t.host.resolve(q,K);(!ie||ie.events!==I||ie.control!==C.control)&&we("forbidden");let U=ie.control.read();(!U||U.registration.bindingId!==K||U.registration.scope.endUserId!==q||U.registration.scope.applicationScopeId!==t.host.applicationScopeId)&&we("forbidden"),U.state==="unbound"&&we("binding_closed")};await lg({req:i,res:o,port:I,scope:{applicationScopeId:t.host.applicationScopeId,endUserId:q,bindingId:K},...J===void 0?{}:{lastEventId:J},authorize:H});return}let L=()=>{let I=C.materials;(!F.acceptedCapabilities.includes("context-materials-v1")||!I)&&we("unsupported_capability"),(I.bindingId!==K||!F.registration.relatedBindingIds.includes(I.storageBindingId))&&we("forbidden");let q=C.spool.bindingIdentity(I.storageBindingId);return(q.applicationScopeId!==t.host.applicationScopeId||q.endUserId!==A.endUserId)&&we("forbidden"),I};["records","artifact","ack"].includes(D)&&!F.acceptedCapabilities.includes("archive-transfer-v1")&&we("unsupported_capability");let Q,se=200,O=e;if(D==="records"){let I=k;gg(I.generations,F.target.generations)||we("stale_generation"),Q=C.journal.list(I),O=I.maxBytes}else if(D==="artifact"){let I=k;gg(I.generations,F.target.generations)||we("stale_generation");let q=C.journal.readArtifact(I);Q={protocol:Ti,bindingId:K,artifactId:q.artifact.artifactId,sourceId:q.artifact.sourceId,generations:I.generations,offset:q.offset,bytes:q.body.byteLength,totalBytes:q.artifact.bytes,sha256:q.artifact.sha256,chunkSha256:q.chunkSha256,base64:Buffer.from(q.body).toString("base64")},O=cS}else if(D==="ack")Q=C.acknowledger.acknowledge(k);else if(D==="upload")Q=L().uploadChunk(k);else if(D==="response")Q=L().respond(k),se=202;else if(D==="status")Q=L().status(g[3]);else if(D==="upload-status")Q=L().uploadStatus(g[3],g[5]);else{let I={operationEpoch:S.operationEpoch,requestId:S.requestId};Q=S.operation==="material-response"?L().queryResponse(I):C.control.query(S.operation,I)?.receipt,Q||we("receipt_expired")}if(!Q||typeof Q!="object"||Q.bindingId!==K)throw new Error("Mismatched host binding");ii(o,se,Q,O)})().catch(u=>{if(o.headersSent||o.destroyed||o.writableEnded)return;let m=wS(u),[h,g]=Sg[m];(h===429||h===503)&&o.setHeader("retry-after","5"),ii(o,h,{protocol:Ti,requestId:l,code:m,status:h,message:m,retryAction:g})}).finally(()=>{a&&n--,d&&t.admission.releaseBody(c)});return t.track(f),!0}}import{createHash as Ur,randomUUID as Ho}from"node:crypto";var nr="TansrTerminalShellSandbox",Bo="058f31335cbb45a6ffe1b5ede8466013462c544c8108d687f41fa18447d51b96",xe={};xe.BackgroundRequest=r.union([r.object({contract:r.lazy(()=>xe.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(()=>xe.BackgroundContract),action:r.literal("query"),identity:r.lazy(()=>xe.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>xe.BackgroundContract),action:r.literal("cancel"),identity:r.lazy(()=>xe.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>xe.BackgroundContract),action:r.literal("outputRead"),identity:r.lazy(()=>xe.BackgroundIdentity),artifact:r.lazy(()=>xe.ArtifactReference),offset:r.lazy(()=>xe.Sequence),length:r.number().int().safe().min(1).max(16384)}).strict(),r.object({contract:r.lazy(()=>xe.BackgroundContract),action:r.literal("artifactDelete"),identity:r.lazy(()=>xe.BackgroundIdentity),artifact:r.lazy(()=>xe.ArtifactReference)}).strict()]);xe.BackgroundContract=r.literal("terminal-services-v1");xe.BackgroundIdentity=r.object({taskId:r.lazy(()=>xe.Id),operationId:r.lazy(()=>xe.Id),requestDigest:r.lazy(()=>xe.Digest),runtimeInstanceId:r.lazy(()=>xe.Id),processInstanceId:r.lazy(()=>xe.Id)}).strict();xe.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);xe.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));xe.ArtifactReference=r.object({artifactId:r.lazy(()=>xe.Id),operationId:r.lazy(()=>xe.Id),requestDigest:r.lazy(()=>xe.Digest)}).strict();xe.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);xe.BackgroundResponse=r.union([r.object({contract:r.lazy(()=>xe.BackgroundContract),action:r.literal("launch"),task:r.lazy(()=>xe.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>xe.BackgroundContract),action:r.literal("query"),task:r.lazy(()=>xe.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>xe.BackgroundContract),action:r.literal("cancel"),task:r.lazy(()=>xe.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>xe.BackgroundContract),action:r.literal("outputRead"),identity:r.lazy(()=>xe.BackgroundIdentity),artifact:r.lazy(()=>xe.ArtifactReference),offset:r.lazy(()=>xe.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(()=>xe.Digest),nextOffset:r.lazy(()=>xe.Sequence),complete:r.boolean(),gap:r.boolean()}).strict(),r.object({contract:r.lazy(()=>xe.BackgroundContract),action:r.literal("artifactDelete"),identity:r.lazy(()=>xe.BackgroundIdentity),artifact:r.lazy(()=>xe.ArtifactReference),status:r.union([r.literal("deleted"),r.literal("already_deleted")])}).strict()]);xe.BackgroundTaskState=r.object({identity:r.lazy(()=>xe.BackgroundIdentity),artifact:r.lazy(()=>xe.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(()=>xe.Sequence),r.null()]),truncated:r.boolean()}).strict();xe.ExecutionInterpreter=r.object({id:r.lazy(()=>xe.Id),revision:r.lazy(()=>xe.Id),hostShell:r.union([r.literal("posix"),r.literal("powershell")])}).strict();xe.Contract=r.literal("terminal-shell-sandbox-v1");xe.Call=r.object({turnId:r.lazy(()=>xe.Id),toolCallId:r.lazy(()=>xe.Id)}).strict();xe.ApprovedCall=r.object({turnId:r.lazy(()=>xe.Id),toolCallId:r.lazy(()=>xe.Id),argsDigest:r.lazy(()=>xe.Digest)}).strict();xe.Escalation=r.object({previousDeniedOperationId:r.lazy(()=>xe.Id),approvedCall:r.lazy(()=>xe.ApprovedCall)}).strict();xe.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();xe.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();xe.Request=r.union([r.object({contract:r.lazy(()=>xe.Contract),action:r.literal("exec"),call:r.lazy(()=>xe.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(()=>xe.ExecutionInterpreter),escalation:r.lazy(()=>xe.Escalation).optional()}).strict(),r.object({contract:r.lazy(()=>xe.Contract),action:r.literal("background"),request:r.lazy(()=>xe.BackgroundRequest),call:r.lazy(()=>xe.Call).optional(),escalation:r.lazy(()=>xe.Escalation).optional()}).strict()]);xe.Response=r.union([r.object({contract:r.lazy(()=>xe.Contract),action:r.literal("exec"),result:r.union([r.lazy(()=>xe.ExecResult),r.null()]),sandbox:r.lazy(()=>xe.Sandbox),output:r.union([r.lazy(()=>xe.Output),r.null()])}).strict(),r.object({contract:r.lazy(()=>xe.Contract),action:r.literal("background"),result:r.union([r.lazy(()=>xe.BackgroundResponse),r.null()]),sandbox:r.lazy(()=>xe.Sandbox)}).strict()]);xe.OutputChannel=r.object({totalBytes:r.number().int().safe().min(0).max(65536),payloadDigest:r.lazy(()=>xe.Digest)}).strict();xe.Output=r.object({previewTruncated:r.boolean(),stdout:r.lazy(()=>xe.OutputChannel),stderr:r.lazy(()=>xe.OutputChannel)}).strict();function Au(t,e){if(!Object.hasOwn(xe,t))throw new TypeError("Unknown terminal shell sandbox contract type");return xe[t].parse(e)}function gi(){throw new TypeError("Invalid terminal shell sandbox semantics")}function qo(t){let e=Au("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))&&gi(),e.escalation&&(e.escalation.approvedCall.turnId!==e.call?.turnId||e.escalation.approvedCall.toolCallId!==e.call?.toolCallId)&&gi(),e}function xg(t,e){let n=Au("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)&&gi(),n.action==="exec"&&n.result?.exitCode!==null&&n.result!==null){let o=BigInt(n.result.exitCode);(o<-2147483648n||o>2147483647n)&&gi()}if(n.action==="exec"&&(n.result===null!=(n.output===null)&&gi(),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)&&gi()}return e&&((e.action!==n.action||i.escalated&&e.escalation===void 0)&&gi(),e.action==="exec"&&n.action==="exec"&&n.output&&n.output.stdout.totalBytes+n.output.stderr.totalBytes>e.maxOutputBytes&&gi(),e.action==="background"&&n.action==="background"&&n.result?.action!==void 0&&e.request.action!==n.result.action&&gi()),n}function ir(t){return t.operation==="tool.invoke"&&t.args.name===nr&&t.args.definitionDigest===Bo}function Mr(t){if(!ir(t)||t.operation!=="tool.invoke")throw new Error("Invalid shell sandbox profile");return qo(JSON.parse(t.args.argsJson))}function Oa(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 xg(JSON.parse(n.content[0].text),t)}function Do(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 me({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 Rg(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=Mr(n.request);if(o.escalation!==void 0||o.call?.toolCallId===t.call?.toolCallId||Do(o,n)!==Do(t,e))return!1;let s=Oa(o,i.result);return s.sandbox.isolationDenied&&!s.sandbox.escalated}catch{return!1}}import{createHash as xS}from"node:crypto";var Ig="8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",Tg="2026-09-26.candidate-7",Ai="TansrTerminalBackground",Or="03848c0c75af6e2e358ac64f81a61c79f595d8fc70442d06ae3c0576e39157b8",ri="TansrTerminalMemoryPublication",Ei="8532a582d40d2d8993a80db59412a89671670ed7f994eaf9bf972bd544a111b0",E={};E.Id=r.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._~-]*$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=128);E.LegacyId=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);E.Sequence=r.string().regex(new RegExp("^(0|[1-9][0-9]{0,17}|[1-8][0-9]{18}|9[0-1][0-9]{17}|92[0-1][0-9]{16}|922[0-2][0-9]{15}|9223[0-2][0-9]{14}|92233[0-6][0-9]{13}|922337[0-1][0-9]{12}|92233720[0-2][0-9]{10}|922337203[0-5][0-9]{9}|9223372036[0-7][0-9]{8}|92233720368[0-4][0-9]{7}|922337203685[0-3][0-9]{6}|9223372036854[0-6][0-9]{5}|92233720368547[0-6][0-9]{4}|922337203685477[0-4][0-9]{3}|9223372036854775[0-7][0-9]{2}|922337203685477580[0-6]|9223372036854775807)$","u")).refine(t=>[...t].length<=19);E.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));E.Scope=r.object({applicationScopeId:r.lazy(()=>E.Id),endUserId:r.lazy(()=>E.LegacyId),authorizationRevision:r.lazy(()=>E.Sequence)}).strict();E.ExecutionBinding=r.object({bindingId:r.lazy(()=>E.Id),revision:r.lazy(()=>E.Sequence),target:r.lazy(()=>E.ExecutionTarget)}).strict();E.ExecutionTarget=r.object({executorId:r.lazy(()=>E.Id),connectionId:r.lazy(()=>E.Id),connectionRevision:r.lazy(()=>E.Sequence),workspaceId:r.lazy(()=>E.Id),workspaceRevision:r.lazy(()=>E.Sequence),interpreter:r.lazy(()=>E.ExecutionInterpreter).optional()}).strict();E.ExecutionInterpreter=r.object({id:r.lazy(()=>E.Id),revision:r.lazy(()=>E.Id),hostShell:r.union([r.literal("posix"),r.literal("powershell")])}).strict();E.Contract=r.literal("terminal-services-v1");E.SchemaRevision=r.literal("2026-09-26.candidate-7");E.SessionContract=r.union([r.literal("sdk1"),r.literal("sdk2-offload-v1")]);E.Feature=r.union([r.literal("execution-stream-v1"),r.literal("execution-background-v1"),r.literal("memory-lifecycle-v1"),r.literal("session-configuration-v1")]);E.SessionReference=r.object({sessionContract:r.lazy(()=>E.SessionContract),sessionId:r.lazy(()=>E.LegacyId)}).strict();E.FeatureAvailability=r.object({feature:r.lazy(()=>E.Feature),supported:r.boolean(),installed:r.boolean(),authorization:r.union([r.literal("allowed"),r.literal("denied"),r.literal("unconfirmed")]),device:r.union([r.literal("available"),r.literal("unavailable"),r.literal("not-required"),r.literal("unconfirmed")])}).strict();E.Limits=r.object({maxControlBytes:r.number().int().safe().min(1).max(262144),maxBlockBytes:r.number().int().safe().min(1).max(16384),maxBatchBytes:r.number().int().safe().min(1).max(65536),maxPendingBytes:r.number().int().safe().min(1).max(2097152),maxRetainedBytes:r.number().int().safe().min(1).max(8388608)}).strict();E.CapabilitiesResponse=r.object({contract:r.lazy(()=>E.Contract),schemaRevision:r.lazy(()=>E.SchemaRevision),schemaSha256:r.lazy(()=>E.Digest),sessionContracts:r.array(r.lazy(()=>E.SessionContract)).min(1).max(2).refine(t=>new Set(t).size===t.length),features:r.array(r.lazy(()=>E.FeatureAvailability)).min(4).max(4),limits:r.lazy(()=>E.Limits)}).strict();E.BindingRequest=r.object({contract:r.lazy(()=>E.Contract),requestId:r.lazy(()=>E.Id),session:r.lazy(()=>E.SessionReference),executionBinding:r.union([r.lazy(()=>E.ExecutionBinding),r.null()]),required:r.array(r.lazy(()=>E.Feature)).min(0).max(4).refine(t=>new Set(t).size===t.length),optional:r.array(r.lazy(()=>E.Feature)).min(0).max(4).refine(t=>new Set(t).size===t.length)}).strict();E.BindingResponse=r.object({contract:r.lazy(()=>E.Contract),requestId:r.lazy(()=>E.Id),session:r.lazy(()=>E.SessionReference),scope:r.lazy(()=>E.Scope),executionBinding:r.union([r.lazy(()=>E.ExecutionBinding),r.null()]),accepted:r.array(r.lazy(()=>E.Feature)).min(0).max(4).refine(t=>new Set(t).size===t.length),unavailable:r.array(r.lazy(()=>E.FeatureAvailability)).min(0).max(4),outputAuthority:r.union([r.literal("session-events"),r.literal("tool-output")]),limits:r.lazy(()=>E.Limits)}).strict();E.OperationReference=r.object({operationId:r.lazy(()=>E.Id),requestDigest:r.lazy(()=>E.Digest)}).strict();E.OutputBlock=r.object({seq:r.lazy(()=>E.Sequence),byteOffset:r.lazy(()=>E.Sequence),channel:r.union([r.literal("stdout"),r.literal("stderr")]),encoding:r.union([r.literal("utf-8"),r.literal("binary")]),byteLength:r.number().int().safe().min(1).max(16384),payloadDigest:r.lazy(()=>E.Digest),base64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length>=4).refine(t=>[...t].length<=21848)}).strict();E.OutputSeal=r.object({lastSeq:r.union([r.lazy(()=>E.Sequence),r.null()]),totalBytes:r.lazy(()=>E.Sequence),payloadDigest:r.lazy(()=>E.Digest),truncated:r.boolean()}).strict();E.OutputBatchRequest=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),operation:r.lazy(()=>E.OperationReference),executorId:r.lazy(()=>E.Id),connectionId:r.lazy(()=>E.Id),blocks:r.array(r.lazy(()=>E.OutputBlock)).min(0).max(32),seal:r.union([r.lazy(()=>E.OutputSeal),r.null()])}).strict();E.OutputStatus=r.object({contract:r.lazy(()=>E.Contract),operation:r.lazy(()=>E.OperationReference),state:r.union([r.literal("available"),r.literal("receiving"),r.literal("complete"),r.literal("truncated"),r.literal("gap"),r.literal("unavailable")]),acceptedThrough:r.union([r.lazy(()=>E.Sequence),r.null()]),durableThrough:r.union([r.lazy(()=>E.Sequence),r.null()]),retainedFrom:r.union([r.lazy(()=>E.Sequence),r.null()]),nextByteOffset:r.union([r.lazy(()=>E.Sequence),r.null()]),seal:r.union([r.lazy(()=>E.OutputSeal),r.null()])}).strict();E.OutputEvent=r.union([r.object({contract:r.lazy(()=>E.Contract),type:r.literal("output.block"),operation:r.lazy(()=>E.OperationReference),block:r.lazy(()=>E.OutputBlock)}).strict(),r.object({contract:r.lazy(()=>E.Contract),type:r.literal("output.status"),status:r.lazy(()=>E.OutputStatus)}).strict()]);E.ExecutorEvent=r.object({contract:r.lazy(()=>E.Contract),eventId:r.lazy(()=>E.Sequence),type:r.union([r.literal("operations-available"),r.literal("operation-cancelled"),r.literal("reconcile-required")]),executorId:r.lazy(()=>E.Id),connectionId:r.lazy(()=>E.Id),operation:r.union([r.lazy(()=>E.OperationReference),r.null()])}).strict();E.OutputCorrelation=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),toolCallId:r.lazy(()=>E.LegacyId),operation:r.lazy(()=>E.OperationReference),outputAuthority:r.union([r.literal("session-events"),r.literal("tool-output")])}).strict();E.ErrorCode=r.union([r.literal("invalid_request"),r.literal("protocol_version_mismatch"),r.literal("unauthorized"),r.literal("forbidden"),r.literal("not_found"),r.literal("unsupported_capability"),r.literal("capability_unconfirmed"),r.literal("source_unavailable"),r.literal("stale_generation"),r.literal("binding_conflict"),r.literal("revision_conflict"),r.literal("busy"),r.literal("capacity_exceeded"),r.literal("payload_too_large"),r.literal("output_gap"),r.literal("integrity_mismatch"),r.literal("commit_unknown"),r.literal("context_transition_required"),r.literal("request_conflict"),r.literal("request_limit")]);E.ErrorResponse=r.object({contract:r.lazy(()=>E.Contract),requestId:r.lazy(()=>E.Id),code:r.lazy(()=>E.ErrorCode),status:r.union([r.literal(400),r.literal(401),r.literal(403),r.literal(404),r.literal(409),r.literal(413),r.literal(429),r.literal(503)]),retryAction:r.union([r.literal("none"),r.literal("discover"),r.literal("refresh"),r.literal("reconcile"),r.literal("backoff")])}).strict();E.ConfigurationRevision=r.number().int().safe().min(0).max(9007199254740991);E.Thinking=r.object({budget:r.number().int().safe().min(0).max(9007199254740991).optional()}).strict();E.SessionConfiguration=r.object({revision:r.lazy(()=>E.ConfigurationRevision),model:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512),r.null()]),thinking:r.union([r.lazy(()=>E.Thinking),r.null()])}).strict();E.ConfigurationChanges=r.object({model:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512).optional(),thinking:r.union([r.lazy(()=>E.Thinking),r.null()]).optional()}).strict();E.ConfigurationRequest=r.object({contract:r.lazy(()=>E.Contract),requestId:r.lazy(()=>E.Id),session:r.lazy(()=>E.SessionReference),expectedRevision:r.lazy(()=>E.ConfigurationRevision),changes:r.lazy(()=>E.ConfigurationChanges)}).strict();E.ConfigurationResponse=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),configuration:r.lazy(()=>E.SessionConfiguration)}).strict();E.ConfigurationCommitResponse=r.object({contract:r.lazy(()=>E.Contract),requestId:r.lazy(()=>E.Id),session:r.lazy(()=>E.SessionReference),status:r.union([r.literal("changed"),r.literal("replayed")]),configuration:r.lazy(()=>E.SessionConfiguration)}).strict();E.ExecutionStatus=r.object({protocol:r.literal("sdk2-ext-v1"),operation:r.lazy(()=>E.ExecutionOperation),status:r.union([r.literal("pending"),r.literal("completed"),r.literal("failed"),r.literal("unknown")]),receipt:r.union([r.lazy(()=>E.ExecutionReceiptRequest),r.null()])}).strict();E.ExecutionOperation=r.object({protocol:r.literal("sdk2-ext-v1"),operationId:r.lazy(()=>E.Id),sessionId:r.lazy(()=>E.LegacyId),scope:r.lazy(()=>E.Scope),binding:r.lazy(()=>E.ExecutionBinding),toolName:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),request:r.lazy(()=>E.ResourceRequest),digest:r.lazy(()=>E.Digest),expiresAt:r.string().datetime({offset:!0})}).strict();E.ResourceRequest=r.union([r.object({operation:r.literal("fs.inspect"),args:r.object({path:r.string().refine(t=>[...t].length<=4096),followLinks:r.boolean()}).strict()}).strict(),r.object({operation:r.literal("fs.read"),args:r.object({path:r.string().refine(t=>[...t].length<=4096),offset:r.number().int().safe().min(0).max(9007199254740991),length:r.number().int().safe().min(1).max(65536)}).strict()}).strict(),r.object({operation:r.literal("fs.write"),args:r.object({path:r.string().refine(t=>[...t].length<=4096),expectedHash:r.union([r.lazy(()=>E.Digest),r.null()]),bytesBase64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=174764)}).strict()}).strict(),r.object({operation:r.literal("fs.mkdir"),args:r.object({path:r.string().refine(t=>[...t].length<=4096)}).strict()}).strict(),r.object({operation:r.literal("fs.list"),args:r.object({path:r.string().refine(t=>[...t].length<=4096)}).strict()}).strict(),r.object({operation:r.literal("process.exec"),args:r.object({command:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768),cwd:r.string().refine(t=>[...t].length<=4096),timeoutMs:r.number().int().safe().min(1).max(12e4),maxOutputBytes:r.number().int().safe().min(1).max(65536),interpreter:r.lazy(()=>E.ExecutionInterpreter)}).strict()}).strict(),r.object({operation:r.literal("tool.invoke"),args:r.object({name:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),definitionDigest:r.lazy(()=>E.Digest),argsJson:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768)}).strict()}).strict()]);E.ExecutionReceiptRequest=r.object({protocol:r.literal("sdk2-ext-v1"),executorId:r.lazy(()=>E.Id),connectionId:r.lazy(()=>E.Id),operationId:r.lazy(()=>E.Id),digest:r.lazy(()=>E.Digest),status:r.union([r.literal("completed"),r.literal("failed"),r.literal("unknown")]),result:r.union([r.lazy(()=>E.ResourceResult),r.null()]),errorCode:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=128),r.null()])}).strict();E.ResourceResult=r.union([r.object({operation:r.literal("fs.inspect"),args:r.object({kind:r.union([r.literal("file"),r.literal("directory"),r.literal("symlink")]),size:r.number().int().safe().min(0).max(9007199254740991),mtimeMs:r.string().regex(new RegExp("^(0|[1-9][0-9]*)(\\.[0-9]+)?$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=32),realpath:r.string().refine(t=>[...t].length<=4096)}).strict()}).strict(),r.object({operation:r.literal("fs.read"),args:r.object({bytesBase64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=87384)}).strict()}).strict(),r.object({operation:r.literal("fs.write"),args:r.object({hash:r.lazy(()=>E.Digest)}).strict()}).strict(),r.object({operation:r.literal("fs.mkdir"),args:r.object({}).strict()}).strict(),r.object({operation:r.literal("fs.list"),args:r.object({entries:r.array(r.object({name:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=255),kind:r.union([r.literal("file"),r.literal("directory"),r.literal("symlink")])}).strict()).max(501)}).strict()}).strict(),r.object({operation:r.literal("process.exec"),args:r.object({stdout:r.string().refine(t=>[...t].length<=65536),stderr:r.string().refine(t=>[...t].length<=65536),exitCode:r.union([r.string().regex(new RegExp("^(0|[1-9][0-9]*|-[1-9][0-9]*)$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=11),r.null()]),signalName:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32),r.null()]),durationMs:r.number().int().safe().min(0).max(9007199254740991),timedOut:r.boolean(),aborted:r.boolean()}).strict()}).strict(),r.object({operation:r.literal("tool.invoke"),args:r.object({resultJson:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=32768)}).strict()}).strict()]);E.ExecutionState=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),execution:r.lazy(()=>E.ExecutionStatus)}).strict();E.BackgroundIdentity=r.object({taskId:r.lazy(()=>E.Id),operationId:r.lazy(()=>E.Id),requestDigest:r.lazy(()=>E.Digest),runtimeInstanceId:r.lazy(()=>E.Id),processInstanceId:r.lazy(()=>E.Id)}).strict();E.ArtifactReference=r.object({artifactId:r.lazy(()=>E.Id),operationId:r.lazy(()=>E.Id),requestDigest:r.lazy(()=>E.Digest)}).strict();E.BackgroundRequest=r.union([r.object({contract:r.lazy(()=>E.Contract),action:r.literal("launch"),command:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=8192),cwd:r.string().refine(t=>[...t].length<=4096),mode:r.union([r.literal("background"),r.literal("foreground-handoff")]),timeoutMs:r.number().int().safe().min(1).max(864e5),foregroundTimeoutMs:r.number().int().safe().min(1).max(12e4).optional()}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("query"),identity:r.lazy(()=>E.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("cancel"),identity:r.lazy(()=>E.BackgroundIdentity)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("outputRead"),identity:r.lazy(()=>E.BackgroundIdentity),artifact:r.lazy(()=>E.ArtifactReference),offset:r.lazy(()=>E.Sequence),length:r.number().int().safe().min(1).max(16384)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("artifactDelete"),identity:r.lazy(()=>E.BackgroundIdentity),artifact:r.lazy(()=>E.ArtifactReference)}).strict()]);E.BackgroundTaskState=r.object({identity:r.lazy(()=>E.BackgroundIdentity),artifact:r.lazy(()=>E.ArtifactReference),state:r.union([r.literal("running"),r.literal("completed"),r.literal("failed"),r.literal("cancelled"),r.literal("unknown")]),exitCode:r.union([r.number().int().safe().min(-2147483648).max(2147483647),r.null()]),signalName:r.union([r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=64),r.null()]),totalBytes:r.union([r.lazy(()=>E.Sequence),r.null()]),truncated:r.boolean()}).strict();E.BackgroundResponse=r.union([r.object({contract:r.lazy(()=>E.Contract),action:r.literal("launch"),task:r.lazy(()=>E.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("query"),task:r.lazy(()=>E.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("cancel"),task:r.lazy(()=>E.BackgroundTaskState)}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("outputRead"),identity:r.lazy(()=>E.BackgroundIdentity),artifact:r.lazy(()=>E.ArtifactReference),offset:r.lazy(()=>E.Sequence),base64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=21848),byteLength:r.number().int().safe().min(0).max(16384),payloadDigest:r.lazy(()=>E.Digest),nextOffset:r.lazy(()=>E.Sequence),complete:r.boolean(),gap:r.boolean()}).strict(),r.object({contract:r.lazy(()=>E.Contract),action:r.literal("artifactDelete"),identity:r.lazy(()=>E.BackgroundIdentity),artifact:r.lazy(()=>E.ArtifactReference),status:r.union([r.literal("deleted"),r.literal("already_deleted")])}).strict()]);E.MemoryIdentity=r.object({kind:r.union([r.literal("server-managed"),r.literal("client-managed"),r.literal("developer-managed")]),domain:r.lazy(()=>E.MemoryIdentifier),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),applicationScopeId:r.lazy(()=>E.Id),endUserId:r.lazy(()=>E.LegacyId)}).strict();E.MemoryCommand=r.union([r.object({kind:r.literal("pin"),text:r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=4096)}).strict(),r.object({kind:r.literal("remember")}).strict(),r.object({kind:r.literal("forget"),topic:r.lazy(()=>E.MemoryIdentifier)}).strict()]);E.MemoryCommandRequest=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),requestId:r.lazy(()=>E.MemoryIdentifier),operationId:r.lazy(()=>E.MemoryIdentifier),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),expectedRevision:r.lazy(()=>E.Sequence),command:r.lazy(()=>E.MemoryCommand)}).strict();E.MemoryReceipt=r.object({requestId:r.lazy(()=>E.MemoryIdentifier),operationId:r.lazy(()=>E.MemoryIdentifier),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),expectedRevision:r.lazy(()=>E.Sequence),status:r.union([r.literal("pending"),r.literal("unknown"),r.literal("committed"),r.literal("failed")]),publishedRevision:r.lazy(()=>E.Sequence).optional(),errorCode:r.union([r.literal("operation_failed"),r.literal("commit_unknown")]).optional(),executionComplete:r.boolean(),durable:r.boolean(),consumed:r.boolean()}).strict();E.MemoryState=r.object({identity:r.lazy(()=>E.MemoryIdentity),revision:r.lazy(()=>E.Sequence),deletionGeneration:r.lazy(()=>E.Sequence),available:r.boolean()}).strict();E.MemoryStateResponse=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),memory:r.lazy(()=>E.MemoryState)}).strict();E.MemoryReceiptResponse=r.object({contract:r.lazy(()=>E.Contract),session:r.lazy(()=>E.SessionReference),receipt:r.union([r.lazy(()=>E.MemoryReceipt),r.null()])}).strict();E.MemoryIdentifier=r.string().regex(new RegExp("^[^\\u0000-\\u001f\\u007f]+$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=256);E.MemoryPublicationEtag=r.string().regex(new RegExp("^[^\\u0000-\\u001f\\u007f]+$","u")).refine(t=>[...t].length>=1).refine(t=>[...t].length<=256);E.MemoryPublicationHead=r.object({etag:r.lazy(()=>E.MemoryPublicationEtag),byteLength:r.number().int().safe().min(1).max(4194304),sha256:r.lazy(()=>E.Digest)}).strict();E.MemoryPublicationTransfer=r.object({transferId:r.lazy(()=>E.Id),status:r.union([r.literal("staging"),r.literal("committed"),r.literal("conflict"),r.literal("unknown")]),receivedBytes:r.union([r.number().int().safe().min(0).max(4194304),r.null()]),etag:r.union([r.lazy(()=>E.MemoryPublicationEtag),r.null()])}).strict();E.MemoryPublicationRequest=r.union([r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("head")}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("read"),etag:r.lazy(()=>E.MemoryPublicationEtag),offset:r.number().int().safe().min(0).max(4194304),length:r.number().int().safe().min(1).max(12288)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("begin"),transferId:r.lazy(()=>E.Id),expectedEtag:r.union([r.lazy(()=>E.MemoryPublicationEtag),r.null()]),byteLength:r.number().int().safe().min(1).max(4194304),sha256:r.lazy(()=>E.Digest)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("chunk"),transferId:r.lazy(()=>E.Id),offset:r.number().int().safe().min(0).max(4194304),base64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=16384),byteLength:r.number().int().safe().min(1).max(12288),payloadDigest:r.lazy(()=>E.Digest)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("commit"),transferId:r.lazy(()=>E.Id)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("query"),transferId:r.lazy(()=>E.Id)}).strict()]);E.MemoryPublicationResponse=r.union([r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("head"),publication:r.union([r.lazy(()=>E.MemoryPublicationHead),r.null()])}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("read"),etag:r.lazy(()=>E.MemoryPublicationEtag),offset:r.number().int().safe().min(0).max(4194304),base64:r.string().regex(new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$","u")).refine(t=>[...t].length<=16384),byteLength:r.number().int().safe().min(0).max(12288),payloadDigest:r.lazy(()=>E.Digest),nextOffset:r.number().int().safe().min(0).max(4194304),complete:r.boolean()}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("begin"),transfer:r.lazy(()=>E.MemoryPublicationTransfer)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("chunk"),transfer:r.lazy(()=>E.MemoryPublicationTransfer)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("commit"),transfer:r.lazy(()=>E.MemoryPublicationTransfer)}).strict(),r.object({contract:r.lazy(()=>E.Contract),sourceId:r.lazy(()=>E.MemoryIdentifier),sourceGeneration:r.lazy(()=>E.Sequence),domainKey:r.lazy(()=>E.MemoryIdentifier),action:r.literal("query"),transfer:r.lazy(()=>E.MemoryPublicationTransfer)}).strict()]);function yt(t,e){if(!Object.hasOwn(E,t))throw new TypeError("Unknown terminal contract type");return E[t].parse(e)}function Ba(t,e){return me(t)===me(e)}function qn(){throw new Error("Invalid terminal background response.")}function Ag(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 Yp({signal:t.signal,maxTasks:128}),d=g=>me([g.toolCallId,g.executionTarget]);async function c(g,p,v){if((p.waiting??0)>=4)throw new Error("Background control capacity exceeded.");let b=p.tail??Promise.resolve(),R,w=new Promise(x=>{R=x});p.tail=w,p.waiting=(p.waiting??0)+1;try{return await new Promise((x,T)=>{let P=()=>{v.removeEventListener("abort",P),T(v.reason)};v.addEventListener("abort",P,{once:!0}),b.then(()=>{v.removeEventListener("abort",P),x()}),v.aborted&&P()}),v.throwIfAborted(),await l(g,p,v)}finally{b.then(()=>{p.waiting=(p.waiting??1)-1,R()})}}async function l(g,p,v){if(s||!t.enabled())throw new Error("Background capability is no longer available.");if(!p.launch)throw new Error("Missing original background launch identity.");let b=await t.invoke(g,p.call.executionTarget,v,p.launch),R=yt("BackgroundResponse","response"in b?b.response:b);if(g.action==="launch"&&"response"in b&&(p.sandbox=Object.freeze({...b.sandbox})),g.action!=="launch"&&v.throwIfAborted(),R.action!==g.action&&qn(),g.action!=="launch"){let w="task"in R?R.task.identity:R.identity;Ba(w,g.identity)||qn(),"artifact"in g&&(!("artifact"in R)||!Ba(R.artifact,g.artifact))&&qn()}return R}async function f(g,p){if(!g.task)throw new Error("Background launch has not been confirmed.");let v=p.signal?AbortSignal.any([p.signal,t.signal]):t.signal,b=await c({contract:"terminal-services-v1",action:"outputRead",identity:g.task.identity,artifact:g.task.artifact,offset:String(p.offset),length:Math.min(p.length,16384)},g,v);b.action!=="outputRead"&&qn();let R=Buffer.from(b.base64,"base64");return(R.toString("base64")!==b.base64||R.length!==b.byteLength||R.length>Math.min(p.length,16384)||b.offset!==String(p.offset)||BigInt(b.nextOffset)!==p.offset+BigInt(R.length)||xS("sha256").update(R).digest("hex")!==b.payloadDigest||b.gap&&b.complete)&&qn(),{offset:p.offset,bytes:R,nextOffset:BigInt(b.nextOffset),complete:b.complete,gap:b.gap}}let u=g=>{if(t.signal.throwIfAborted(),s)throw new Error("Background runtime is closed.");let p=d(g);if(i.has(p)||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(p)},read:b=>f(v,b),async remove(b){if(!v.task||v.task.state==="running"||v.task.state==="unknown")throw new Error("Output deletion requires a confirmed terminal process.");let R=await c({contract:"terminal-services-v1",action:"artifactDelete",identity:v.task.identity,artifact:v.task.artifact},v,AbortSignal.any([b,t.signal]));return R.action!=="artifactDelete"&&qn(),R.status}},i.set(p,v),v.port};async function m(g,p,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 R;try{R=await c({contract:"terminal-services-v1",action:"launch",command:g.command,cwd:g.cwd,mode:p===void 0?"background":"foreground-handoff",timeoutMs:e,...p===void 0?{}:{foregroundTimeoutMs:Math.min(p,12e4)}},b,g.signal)}catch(N){throw i.delete(d(g)),N}R.action!=="launch"&&qn();let w=Qp(R.task.identity);(R.task.artifact.operationId!==w.operationId||R.task.artifact.requestDigest!==w.requestDigest||R.task.state==="unknown")&&qn(),b.task=R.task,i.delete(d(g)),R.task.truncated&&(b.error="Background output is incomplete.");let x=!1,T,P=0n,W,K,D=Date.now(),J=new Promise(N=>{K=N}),S=v&&p!==void 0?D+p:void 0,k=p===void 0?n:Math.min(n,Math.max(1,Math.floor(p/4))),A=S!==void 0,C=new AbortController,F=N=>{if(x)return;x=!0,C.abort(),o.delete(L);let ie=N===void 0||N.state==="unknown";K({exitCode:ie?null:N.exitCode,signalName:ie?null:N.signalName,durationMs:Date.now()-D,...ie?{outcomeUnknown:!0}:{},...N?.state==="failed"?{executionFailed:!0}:{},...N?.state==="cancelled"?{cancelled:!0}:{}})},L={close:()=>F()};o.add(L);let Q=N=>{(!Ba(N.identity,w)||!Ba(N.artifact,b.task?.artifact))&&qn(),N.truncated&&(b.error="Background output is incomplete."),b.task=N},se=AbortSignal.any([C.signal,t.signal]),O=async(N,ie)=>{let U=await c({contract:"terminal-services-v1",action:N,identity:w},b,AbortSignal.any([ie,t.signal]));return(U.action!==N||!("task"in U))&&qn(),Q(U.task),U.task.state==="unknown"&&F(U.task),{state:U.task.state,exitCode:U.task.exitCode,signalName:U.task.signalName}},I=()=>{x||W||(W=c({contract:"terminal-services-v1",action:"cancel",identity:w},b,se).then(N=>{N.action!=="cancel"&&qn(),Q(N.task),N.task.state==="unknown"&&F(N.task)}).catch(()=>F()).finally(()=>{W=void 0}))},q={identity:w,pid:void 0,startedAt:D,...b.sandbox?{sandbox:b.sandbox}:{},get lastOutputAt(){return T},get settled(){return x},exit:J,kill:I,control:{query:N=>O("query",N),cancel:N=>O("cancel",N)},killSync:()=>F()};g.signal.aborted&&I();let H=new TextDecoder;return(async()=>{try{for(;!x;){se.throwIfAborted();let N=b.task;if(N.state==="unknown"){F(N);break}for(let U=0;U<16&&N.totalBytes!==null&&P<BigInt(N.totalBytes);U++){let ce=await f(b,{offset:P,length:16384,signal:se});if(ce.gap||ce.bytes.length===0){b.error="Background output gap.";break}P=ce.nextOffset,T=Date.now();let le=H.decode(ce.bytes,{stream:!0});le&&g.onChunk?.(le,"stdout")}if(N.state!=="running"){if(N.totalBytes!==null&&P<BigInt(N.totalBytes)&&!b.error)continue;let U=H.decode();U&&g.onChunk?.(U,"stdout"),F(N);break}if(!A){let U=S!==void 0&&Date.now()<S?k:n;await new Promise((ce,le)=>{let re=setTimeout(()=>{se.removeEventListener("abort",pe),ce()},U);re.unref();let pe=()=>{clearTimeout(re),se.removeEventListener("abort",pe),le(se.reason)};se.addEventListener("abort",pe,{once:!0}),se.aborted&&pe()})}A=!1;let ie=await c({contract:"terminal-services-v1",action:"query",identity:w},b,se);ie.action!=="query"&&qn(),Q(ie.task)}}catch{F()}})(),q}return{runtime:{enabled:t.enabled,createOutput:u,launch:m,registry:a,timeoutHandoff:!0},registry:a,async exec(g){if(!g.executionTarget||!g.toolCallId)throw new Error("Missing bound execution identity.");let p=await m({...g,executionTarget:g.executionTarget,toolCallId:g.toolCallId},g.timeoutMs,g.timeoutHandoff!==void 0),v=await Jp(g,p);return"sandbox"in p&&p.sandbox?{...v,sandbox:p.sandbox}:v},close(){s=!0;for(let g of o)g.close();i.clear()}}}import Eg from"node:path";var AA=Eg.resolve(Eg.sep,".tansr-sdk-no-discovery");function RS(t){let e=[];for(let[n,i]of Object.entries(t)){if(!mm.test(n)||n.includes("__"))throw new gt("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=hm.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 gt("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 Br=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=RS(e.servers),this.#n=e}manager(){return this.#s?Promise.reject(new gt("invalid_options","This McpHost has been disposed; create a new host, or pass { servers } for a session-scoped host.")):(this.#r??=gm({registry:new Wn,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 um&&(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 qa(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($c(i)),e.toolDefs.push(om),{segment:fm(n.catalog),discoverToolFactory:o=>$c(n.forToolset(o))})}function jo(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 TS="Skill",AS="TodoWrite";function Ci(t,e,n){let{cwd:i,hooks:o}=n;return{decide(s,a){let d=a?.executionTarget,c=d?.kind==="device"?`/workspace/${d.workspaceId??"__unbound__"}`:i,l=d===void 0?{}:{executionTarget:d},f=e.get(s.name),u=f?.isReadOnly??!1,m=f!==void 0?{description:f.description,...f.effects!==void 0?{effects:f.effects}:{}}:void 0,h=a?.suppressClassifierSoften===!0,g=Mp(a),p=Op(a),v=!1,b=t.decide({toolName:s.name,args:s.args,isReadOnly:u,cwd:c,...l}),R=s.name===tm&&b.decision==="ask"&&b.source==="mode"&&b.matchedRule===void 0,w=!R&&s.name===TS&&(b.decision==="ask"||b.decision==="deny")&&b.source==="mode"&&b.matchedRule===void 0&&u,x=!R&&!w&&s.name===rm&&(b.decision==="ask"||b.decision==="deny")&&b.source==="mode"&&b.matchedRule===void 0&&u,T=!R&&!w&&!x&&s.name===AS&&(b.decision==="ask"||b.decision==="deny")&&b.source==="mode"&&b.matchedRule===void 0&&u,P=R?{decision:"allow",source:"policy"}:w?{decision:"allow",source:"policy",matchedRule:"skill(default-allow)"}:x?{decision:"allow",source:"policy",matchedRule:"mcp-discover(default-allow)"}:T?{decision:"allow",source:"policy",matchedRule:"todo-write(default-allow)"}:{decision:b.decision,source:b.source,...b.matchedRule!==void 0?{matchedRule:b.matchedRule}:{},...b.sourceLayer!==void 0?{sourceLayer:b.sourceLayer}:{},...b.reason!==void 0?{reason:b.reason}:{}},W=(K,D)=>{if(!Pp(K,v)||p)return K;let J=t.consultClassifier({...a?.signal!==void 0?{signal:a.signal}:{},toolName:s.name,args:D,isReadOnly:u,cwd:c,...l,...h?{suppressClassifierSoften:!0}:{},...m!==void 0?{toolMeta:m}:{}},{decision:K.decision,source:K.source,...K.matchedRule!==void 0?{matchedRule:K.matchedRule}:{}}),S=k=>k.decision==="ask"?k.source==="classifier"?{...K,source:"classifier",...k.reason!==void 0?{reason:k.reason}:{},...k.adjudication!==void 0?{classifierAdjudication:k.adjudication}:{}}:k.adjudication!==void 0?{...K,classifierAdjudication:k.adjudication}:K:{decision:k.decision,source:k.source,...k.matchedRule!==void 0?{matchedRule:k.matchedRule}:{},...k.sourceLayer!==void 0?{sourceLayer:k.sourceLayer}:{},...k.reason!==void 0?{reason:k.reason}:{},...k.adjudication!==void 0?{classifierAdjudication:k.adjudication}:{},...k.decision==="allow"&&K.updatedArgs!==void 0?{updatedArgs:K.updatedArgs}:{}};return J instanceof Promise?J.then(S):S(J)};return P.decision==="deny"||g||o===void 0||!o.hasHooks("PreToolUse",s.name)?W(P,s.args):(async()=>{let D=(await o.run({event:"PreToolUse",tool_name:s.name,tool_input:s.args,tool_use_id:s.id})).preToolUse??{},J=D.decision;v=J==="ask";let S=J!==void 0&&xc[J]>xc[P.decision]?{decision:J,source:"hook"}:{...P};if(D.updatedInput!==void 0&&S.decision!=="deny"){let k=t.decide({toolName:s.name,args:D.updatedInput,isReadOnly:u,cwd:c,...l});return S=_p(S,k),S.decision==="deny"?S:W({...S,updatedArgs:D.updatedInput},D.updatedInput)}return W(S,s.args)})()}}}var Cg="tansr-platform";function ES(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 Da(t){let e=t.baseUrl.replace(/\/+$/,""),n=t.fetchImpl??fetch,i=t.token;return{name:Cg,async search(o,s){let a;try{a=await n(`${e}/t1/websearch`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",[Vn]: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}.${ES(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 vn(t){let e=Lm(t.inputSchema),{$schema:n,...i}=e;return{name:t.name,description:t.description,inputSchema:i}}function qr(t,e,n){try{let{client:i,resolved:o}=Nm(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 gt("assembly_failed",`Failed to assemble model client for "${e}": ${o}`,{cause:i})}}import{createHash as OS}from"node:crypto";var Dn=class extends gt{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 _u(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 Dr(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 Dn)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"}:_u(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 ja(t){let e=Dr(t),n=e.stage==="turn_start"?"start":e.stage==="credential_refresh"?"credentials":"config";return`${hr(`sdk.prompt_failure.${n}`)} ${hr(`sdk.prompt_failure.${e.reason}`)} ${hr(`sdk.prompt_retry.${e.retry}`)}`.trim()}var Mg=new WeakMap;function Na(t){return Mg.get(t)}function No(t,e){return e===void 0?OS("sha256").update(JSON.stringify(t)).digest("hex"):e.replace(/^W\//,"").replace(/^"|"$/g,"")}var BS=[as,ds,Wf,Vf,$f];function Og(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 BS)a.delete(d);return a.set(Vn,t),n(o,{...s,headers:a})}}var qS="session_archived";function Pu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Ua(t,e,n,i,o=br){try{let s=await n(`${t}${cs.heartbeat}`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",[Vn]:e,[Ls]: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===qS){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 Bg(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 oi(t,e,n,i,o=br,s=!1){let a=`${t}${cs.config}`,d;try{d=await n(a,{method:"GET",headers:{accept:"application/json",[Vn]:e,[Ls]:o.join(","),...i!==void 0?{"if-none-match":i}:{}}})}catch(m){let h=Dr(m);throw new Dn(h.reason==="unknown"?{stage:"app_config",reason:"network",retry:"retry"}:h,{cause:m})}let c=d.headers.get("etag")??void 0,l=Bg(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 Dn(_u(d.status));let f;try{f=await d.json()}catch(m){throw new Dn({stage:"app_config",reason:"invalid_config",retry:"check_configuration"},{cause:m})}let u=ao(f);if(u===null||s&&(typeof f!="object"||f===null||!Object.hasOwn(f,"capabilities")||u.capabilitiesIssues!==null))throw new Dn({stage:"app_config",reason:"invalid_config",retry:"check_configuration"});return{bundle:u,status:d.status,etag:c,maxAgeMs:l}}function Fa(t,e){return DS(t,e)}async function DS(t,e){let n=t.baseUrl.replace(/\/+$/,""),i=t.fetchImpl??fetch,o,s,a,d;if(t.bundleCache!==void 0){let g=t.sessionId?.(),p=await t.bundleCache.resolve({baseUrl:n,token:t.token,fetchImpl:i,...t.appId!==void 0?{appId:t.appId}:{},...g!==void 0?{sessionId:g}:{}});o=p.bundle,d=p.etag,s=p.features,a=p.registryConfig,p.archivedSessionId!==void 0&&t.onSessionArchived?.(p.archivedSessionId)}else{let g=Ua(n,t.token,i,t.sessionId?.()),p=await oi(n,t.token,i);if(p.bundle===null)throw new gt("assembly_failed",`App config bundle request to ${n}${cs.config} returned 304 without a conditional request. Check that "baseUrl" points to the tansr API.`);o=p.bundle,d=p.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],p=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${p}; all capability bits were forced off (zero-capability profile) instead of falling back to the platform defaults. Check console → app → capabilities, or upgrade @tansr/sdk if the platform changed the section shape.`,detail:{issues:o.capabilitiesIssues}})}let c=Og(t.token,t.fetchImpl),l=e?.gatewayCache===void 0?void 0:t.sessionId?.();if(e?.gatewayCache!==void 0&&!l)throw new gt("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:No(o,d),fetchImpl:c});if(f!==void 0&&(!l||f.runtimeSessionId!==l))throw new gt("assembly_failed","Gateway cache must bind the current platform session.");let u=new rl(a??Sr(o,n),{env:{[cl]:Gi},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={...qr(u,t.model??"main",t.onProviderSelected),registry:u,capabilities:o.capabilities,platformModels:o.platformModels,pricingUpdates:ll(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&&Mg.set(h,{revision:No(o,d),...d===void 0?{}:{etag:d}}),h}function Uo(t,e){let n=sm({...e,agents:Os,toolset:{registry:t.registry,toolDefs:t.toolDefs}});t.registry.register(n),t.toolDefs.push(vn(n))}function La(t,e){let n=t.baseUrl.replace(/\/+$/,""),i=t.fetchImpl??fetch,o={...t.initial},s=e?.initial.etag??t.etag,a=e?.initial.revision,d=!1;return async c=>{c.throwIfAborted();let l=(u,m)=>{let h=new Headers(m?.headers);h.set("cache-control","no-cache");let g=m?.signal??(u instanceof Request?u.signal:void 0);return i(u,{...m,headers:h,cache:"no-cache",signal:g?AbortSignal.any([c,g]):c})},f=await oi(n,t.token,l,s);if(c.throwIfAborted(),e){let u=f.bundle===null?a:No(f.bundle,f.etag);if(u!==a||d||e.refreshRequired?.()){d=!0,await e.refreshConfiguration(c),c.throwIfAborted();let m=await oi(n,t.token,l,f.etag??s);if((m.bundle!==null||m.etag!==void 0)&&No(m.bundle,m.etag)!==u)throw new Error("Application configuration changed during cache refresh");if(c.throwIfAborted(),u===void 0)throw new Error("Application configuration revision unavailable");e.confirmConfiguration?.(u),d=!1}a=u}return f.bundle!==null?(o={...f.bundle.systemPrompt!==void 0?{systemPrompt:f.bundle.systemPrompt}:{},...f.bundle.systemPromptPolicy!==void 0?{systemPromptPolicy:f.bundle.systemPromptPolicy}:{}},s=f.etag):s=f.etag??s,{...o}}}import{randomUUID as JS}from"node:crypto";function Ha(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=JS(),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,p=setTimeout(()=>{s="timeout",e.abort(s)},a);p.unref?.();try{try{let v=new Promise((R,w)=>{g=()=>w(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(R=>({...R})));for(let R of n)i.enqueueUserInput(R);n.length=0}catch(v){if(yield u({type:"turn.started"}),!e.signal.aborted||e.signal.reason==="timeout"){let b=h?e.signal.aborted?new Dn({stage:"app_config",reason:"timeout",retry:"retry"}):v:new Dn({stage:"turn_start",reason:"unknown",retry:"retry"});yield u({type:"turn.error",scope:t.errorScope??"sdk",message:(t.errorMessage??ja)(b),recoverable:!1,errorKind:h?"application_prompt_refresh_failed":"turn_start_failed",detail:{...Dr(b)}})}yield u({type:"turn.aborted",reason:e.signal.aborted?s:"model_error"});return}finally{clearTimeout(p),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 Mu(t){let e=t.baseUrl.replace(/\/+$/,""),n=t.fetchImpl??fetch,i;try{let s=Fm(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",[Vn]: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 Ou(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=lm(n.error?.detail);return{code:i,message:o,...s?{detail:s}:{}}}var O_=Object.freeze({maxEvents:1e3,maxBytes:2*1024*1024});var Fo=["unauthorized"];var Lo=["check_unavailable"];function Ga(t){return Fo.includes(t)}function Wa(t){return typeof t=="string"&&Lo.includes(t)}import{createHash as Qg}from"node:crypto";var _i=6e4,hw=16,gw=1e5,yw=5e3,vw=36e5,qu="app_user",$a=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 bw(t){return Qg("sha256").update(t,"utf8").digest("hex")}function Va(t=br){return Qg("sha256").update(t.join(","),"utf8").digest("hex").slice(0,8)}function Du(t,e,n,i){return`${t}\0${e??""}\0${n}\0${i}`}function ju(t){let e=t.trim().replace(/^W\//,"");return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function rr(t={}){let e=t.now??Date.now,n=Math.max(0,t.ttlMs??_i),i=new $a(t.maxEntries??hw),o=new $a(t.maxFeatureEntries??gw),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 p=i.peek(h);p===void 0||p.etag===void 0||ju(p.etag)!==ju(g)&&(p.expiresAt<=e()||(p.expiresAt=0,d.etagInvalidations+=1))},f=h=>Math.min(vw,h===void 0?n:Math.min(h,n)),u=(h,g,p,v,b)=>{let R=i.get(g);if(R!==void 0&&R.expiresAt>e())return d.hits+=1,Promise.resolve(R);let w=s.get(g);if(w!==void 0)return d.inflightDedup+=1,w;let x=(async()=>{R===void 0?d.misses+=1:d.revalidations+=1;let T=await oi(h,p,v,R?.etag,b),P=f(T.maxAgeMs);if(T.bundle===null){if(R===void 0){let K=await oi(h,p,v,void 0,b);if(K.bundle===null)throw new Error("bundle cache: unconditional request returned 304");let D={bundle:K.bundle,registryConfig:Sr(K.bundle,h),etag:K.etag,expiresAt:e()+f(K.maxAgeMs)};return i.set(g,D),D}return d.notModified+=1,R.expiresAt=e()+P,T.etag!==void 0&&(R.etag=T.etag),i.set(g,R),R}let W={bundle:T.bundle,registryConfig:Sr(T.bundle,h),etag:T.etag,expiresAt:e()+P};return i.set(g,W),W})().finally(()=>s.delete(g));return s.set(g,x),x},m=(h,g,p,v,b,R)=>{let w=`${h}\0${bw(p)}\0${Va(R)}`,x=o.get(w);if(x!==void 0&&x.expiresAt>e())return d.featureHits+=1,Promise.resolve({features:x.features});let T=a.get(w);if(T!==void 0)return d.inflightDedup+=1,T;d.featureMisses+=1;let P=(async()=>{let W=await Ua(h,p,v,b,R),K=W.features,D=K===void 0?Math.min(yw,n):n;return o.set(w,{features:K,expiresAt:e()+D}),l(g,W.bundleEtag),{features:K,...W.archived!==void 0?{archived:W.archived}:{}}})().finally(()=>a.delete(w));return a.set(w,P),P};return{async resolve(h){let g=h.baseUrl.replace(/\/+$/,""),p=h.fetchImpl??t.fetchImpl??fetch,v=Du(g,h.appId,h.scope??qu,Va(h.clientFeatures)),[b,R]=await Promise.all([u(g,v,h.token,p,h.clientFeatures),m(g,v,h.token,p,h.sessionId,h.clientFeatures)]),w=R.archived!==void 0&&h.sessionId!==void 0&&(R.archived.sessionId===void 0||R.archived.sessionId===h.sessionId)?h.sessionId:void 0;return{bundle:b.bundle,registryConfig:b.registryConfig,etag:b.etag,features:R.features,...w!==void 0?{archivedSessionId:w}:{}}},invalidate(h){if(h===void 0){i.clear(),o.clear();return}c(Du(h.baseUrl.replace(/\/+$/,""),h.appId,h.scope??qu,Va(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 _t(t,e){return ye[t].parse(e)}var jr=262144,Tw=8*1048576,Aw=4096,Ka=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:jr});if(!d||!d.complete||d.body===null||d.bodyState!=="retained")throw this.#s(s.operationKey),new Error("Execution fact unavailable");let c=this.#e.get(s.operationKey),l=Buffer.from(d.body);if(c?.commitDigest===a.receipt.commitDigest&&c.body.equals(l))return structuredClone(c.value);this.#s(s.operationKey);let f=_t(i,JSON.parse(l.toString("utf8")));return!(i==="ExecutionReceiptRequest"&&f.status==="unknown")&&this.#e.size<Aw&&this.#n+l.length<=Tw&&(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!==lt(me(o))||i.operationId!==s.operationId||i.digest!==s.digest||i.executorId!==s.binding.target.executorId||i.connectionId!==s.binding.target.connectionId)throw new Error("Execution reconciliation identity mismatch");return i}reconcile(e,n){let i=_t("ExecutionReceiptRequest",e.receipt),o=this.receipt(i.operationId),s=this.operation(i.operationId);if(o?.status!=="unknown"||!s||i.status==="unknown"||e.unknownReceiptDigest!==lt(me(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=me({source:"trusted-host",evidenceId:e.evidenceId,authorizationRevision:n,operationDigest:s.digest,unknownReceiptDigest:e.unknownReceiptDigest}),c=Buffer.from(me(i));if(c.length>jr||Buffer.byteLength(d)>1024)throw new Error("Execution reconciliation exceeds bound");if(a!==null)return me(a)===me(i);let l=this.#r("reconciliation",i.operationId);return this.storage.spool.reserve({...l,intentDigest:e.unknownReceiptDigest,originalMax:{bytes:jr+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=ec(this.storage.spool,{bindingId:this.storage.bindingId,operationKeyPrefix:"execution-",maxBodyBytes:jr}),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=ec(this.storage.spool,{bindingId:this.storage.bindingId,operationKeyPrefix:"execution-",maxBodyBytes:jr}),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:jr+128,records:1}},o=Buffer.from(me(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(lt(me(n))!==lt(me(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(me(e))}]})}};import{randomUUID as Ew}from"node:crypto";function Jn(t,e){return me(t)===me(e)}function Nr(t){if(!/^[a-zA-Z0-9_-]{1,128}$/.test(t))throw new TypeError("Invalid execution operation id");return`operation:${t}`}function Nu(t,e){return t.sessionId===e.sessionId&&t.scope.applicationScopeId===e.applicationScopeId&&t.scope.endUserId===e.endUserId}function Pi(t,e){let n=t.executions[Nr(e)];if(n&&(n.generation!==t.generation||!Nu(n.operation,t.scope)))throw new Error("Execution fact scope mismatch");return n}function Qa(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(me(e))>262144)throw new RangeError("Execution receipt exceeds bound")}function m0(t,e){let n={transactional:!0,scope:Object.freeze({...t}),acceptsOwner:e.acceptsOwner,operation:i=>e.read(o=>structuredClone(Pi(o,i)?.operation??null)),receipt:i=>e.read(o=>structuredClone(Pi(o,i)?.receipt??null)),reconciledReceipt:i=>e.read(o=>{let s=Pi(o,i);if(s?.reconciled&&(s.receipt?.status!=="unknown"||s.reconciled.status==="unknown"||s.observation?.unknownReceiptDigest!==lt(me(s.receipt))))throw new Error("Execution reconciliation identity mismatch");return structuredClone(s?.reconciled??null)}),recoverableOperations:i=>e.read(o=>{if(!Jn(i,t))throw new Error("Execution fact scope mismatch");let s=Object.values(o.executions);if(s.length>8192)throw new RangeError("Execution recovery inventory exceeds bound");return s.filter(a=>a.operation.toolName==="MemoryPublication").map(a=>{if(Pi(o,a.operation.operationId)!==a)throw new Error("Execution fact unavailable");if(a.receipt&&Qa(a,a.receipt),a.reconciled&&(Qa(a,a.reconciled),a.receipt?.status!=="unknown"||a.reconciled.status==="unknown"||a.observation?.unknownReceiptDigest!==lt(me(a.receipt))))throw new Error("Execution reconciliation identity mismatch");return structuredClone({operation:a.operation,receipt:a.reconciled??a.receipt??null})})}),hasUnreconciled:(i,o)=>e.read(s=>{if(!Jn(i,t))throw new Error("Execution fact scope mismatch");return Object.values(s.serviceExecutions??{}).some(a=>(Uu(s,a),!a.receipt&&o?.activeOperationIds.has(a.operation.operationId)&&a.claimId===s.owner?.claimId&&a.attempt===s.owner.attempt?!1:Xg(a)))||Object.values(s.executions).some(a=>{if(!Nu(a.operation,t)||a.generation!==s.generation)throw new Error("Execution fact scope mismatch");let d=a.reconciled??a.receipt;return o&&(["fs.inspect","fs.read","fs.list"].includes(a.operation.request.operation)||!d&&o.activeOperationIds.has(a.operation.operationId))?!1:!d||d.status==="unknown"})}),async prepare(i){let o=_t("ExecutionOperation",structuredClone(i));if(!Nu(o,t)||Buffer.byteLength(me(o))>262144)throw new Error("Execution request scope or bound mismatch");await e.write(s=>{if(!s.owner)throw new Error("Execution ownership missing");let a=Pi(s,o.operationId);if(a){if(!Jn(a.operation,o)||a.claimId!==s.owner.claimId||a.attempt!==s.owner.attempt)throw new Error("Conflicting execution preparation");return}s.executions[Nr(o.operationId)]={operation:o,generation:s.generation,claimId:s.owner.claimId,attempt:s.owner.attempt}})},async dispatch(i){await e.write((o,s)=>{let a=Pi(o,i.operationId);if(!a||!Jn(a.operation,i)||a.receipt||a.claimId!==o.owner?.claimId||a.attempt!==o.owner.attempt||Date.parse(i.expiresAt)<=s)throw new Error("Stale execution dispatch");a.dispatchedAt??=s})},async accept(i){let o=_t("ExecutionReceiptRequest",structuredClone(i));await e.write(s=>{let a=Pi(s,o.operationId);if(!a)throw new Error("Execution request missing");if(Qa(a,o),a.receipt&&!Jn(a.receipt,o))throw new Error("Conflicting execution receipt");a.receipt=o})},async reconcile(i,o){let s=_t("ExecutionReceiptRequest",structuredClone(i.receipt));return e.write(a=>{let d=Pi(a,s.operationId);if(!d||d.receipt?.status!=="unknown"||s.status==="unknown"||i.operationDigest!==d.operation.digest||i.unknownReceiptDigest!==lt(me(d.receipt)))throw new Error("Execution reconciliation identity mismatch");Qa(d,s);let c={evidenceId:i.evidenceId,unknownReceiptDigest:i.unknownReceiptDigest,authorizationRevision:o};if(Buffer.byteLength(me(c))>1024)throw new RangeError("Execution reconciliation exceeds bound");return d.reconciled?Jn(d.reconciled,s):(d.reconciled=s,d.observation=c,!0)})}};return Object.assign(n,{services:Cw(t,e)}),Object.freeze(n)}var Ja=262144;function Jg(t){return lt(`tansr.service.execution.v1\0${me(t)}`)}function Yg(t,e){let{digest:n,...i}=t;if(Nr(t.operationId),!Jn(t.scope,e)||!t.callId||!t.toolName||t.target.kind!=="controlled-service"||!t.target.authorizationRevision||!/^[a-f0-9]{64}$/.test(t.argumentsDigest)||n!==Jg(i)||Buffer.byteLength(me(t))>4096)throw new Error("Service execution identity mismatch")}function Ya(t,e){if(e.operationId!==t.operation.operationId||e.digest!==t.operation.digest||!["completed","cancelled","unknown"].includes(e.status)||e.resultJson!==null&&typeof e.resultJson!="string"||e.status==="cancelled"&&e.resultJson!==null||e.status==="completed"&&t.dispatchedAt===void 0||e.resultDigest!==void 0&&!/^[a-f0-9]{64}$/.test(e.resultDigest)||Buffer.byteLength(Bt(e))>Ja)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!==lt(e.resultJson))throw new Error("Service result digest mismatch")}}function Uu(t,e){if(Yg(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&&Ya(e,e.receipt),e.reconciled&&(Ya(e,e.reconciled),e.reconciled.status==="unknown"||e.receipt&&e.receipt.status!=="unknown"||e.observation?.unknownReceiptDigest!==lt(me(e.receipt??null))))throw new Error("Service reconciliation identity mismatch")}function Xg(t){let e=t.reconciled??t.receipt;return!e||e.status==="unknown"}function h0(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(Uu(t,s),o!==Nr(s.operation.operationId))throw new Error("Service fact key mismatch");s.receipt||(e+=Ja),Xg(s)&&(e+=Ja+1024,n=!0)}return{count:i.length,reserved:e,unsettled:n}}function Cw(t,e){let n=(i,o)=>{let s=i.serviceExecutions?.[Nr(o)];return s&&Uu(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);Yg(o,t),await e.write(s=>{if(!s.owner)throw new Error("Service execution ownership missing");let a=n(s,o.operationId);if(a){if(!Jn(a.operation,o)||a.claimId!==s.owner.claimId||a.attempt!==s.owner.attempt)throw new Error("Conflicting service preparation");return}s.serviceExecutions??={},s.serviceExecutions[Nr(o.operationId)]={operation:o,generation:s.generation,claimId:s.owner.claimId,attempt:s.owner.attempt}})},async dispatch(i){await e.write((o,s)=>{let a=n(o,i.operationId);if(!a||!Jn(a.operation,i)||a.receipt||a.dispatchedAt!==void 0||a.claimId!==o.owner?.claimId||a.attempt!==o.owner.attempt)throw new Error("Stale service dispatch");a.dispatchedAt=s})},async settle(i){let o=structuredClone(i);await e.write(s=>{let a=n(s,o.operationId);if(!a||a.claimId!==s.owner?.claimId||a.attempt!==s.owner.attempt)throw new Error("Stale service completion");if(Ya(a,o),a.receipt&&!Jn(a.receipt,o))throw new Error("Conflicting service receipt");a.receipt=o})},async reconcile(i){let o=structuredClone(i);await e.write(s=>{let a=n(s,o.receipt.operationId);if(!a||o.receipt.status==="unknown"||a.receipt&&a.receipt.status!=="unknown"||o.unknownReceiptDigest!==lt(me(a.receipt??null))||!/^[A-Za-z0-9][A-Za-z0-9._~:-]{0,127}$/.test(o.evidenceId))throw new Error("Service observation identity mismatch");if(Ya(a,o.receipt),a.reconciled&&!Jn(a.reconciled,o.receipt))throw new Error("Conflicting service reconciliation");a.reconciled=o.receipt,a.observation={evidenceId:o.evidenceId,unknownReceiptDigest:o.unknownReceiptDigest}})}})}async function Fu(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:Ew(),callId:t.callId,toolName:t.toolName,scope:n.scope,target:structuredClone(t.target),argumentsDigest:lt(Bt(t.args))},c={...d,digest:Jg(d)};await i.write(async()=>{if(o.throwIfAborted(),await n.hasUnreconciled(n.scope,{activeOperationIds:new Set([...s,...t.otherActiveOperationIds?.()??[]])}))throw new Error("Service execution requires reconciliation");await a.prepare(c)}),s.add(c.operationId);let l=!1,f=!1,u=(m,h,g)=>{let p=h===null?null:Bt(h);return{operationId:c.operationId,digest:c.digest,status:m,resultJson:p,...p===null?{}:{resultDigest:lt(p)},...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 m=await e(),h=u(m?.isError===!0?"unknown":"completed",m);if(Buffer.byteLength(Bt(h))>Ja&&(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(),m}catch(m){throw f||await i.write(()=>a.settle(u(l?"unknown":"cancelled",null,o.aborted?"aborted":"execution_error"))),m}finally{s.delete(c.operationId)}}import{createHash as Uw,randomUUID as Fw}from"node:crypto";import{createHash as _w,randomUUID as Pw}from"node:crypto";import{realpathSync as Mw}from"node:fs";import Ct from"node:path";import Ow from"node:os";var ty=9223372036854775807n,sr=4*1024*1024,Zg=1024*1024,ey=256,bn=r.string().regex(/^(0|[1-9][0-9]{0,18})$/).refine(t=>BigInt(t)<=ty),Hu=t=>r.string().refine(e=>[...e].length<=t),Dt=Hu(256).refine(t=>t.length>0&&!/[\u0000-\u001f\u007f]/.test(t)),zu=r.object({kind:r.enum(["server-managed","client-managed","developer-managed"]),domain:Dt,sourceId:Dt,sourceGeneration:bn,applicationScopeId:Dt,endUserId:Hu(512).refine(t=>t.length>0)}).strict(),ny=new WeakMap;function Gu(t){return ny.get(t)}var Bw=r.discriminatedUnion("kind",[r.object({kind:r.literal("pin"),text:Hu(4096).refine(t=>t.length>0)}).strict(),r.object({kind:r.literal("remember")}).strict(),r.object({kind:r.literal("forget"),topic:Dt}).strict()]),qw=r.object({requestId:Dt,operationId:Dt,sourceId:Dt,sourceGeneration:bn,expectedRevision:bn,command:Bw}).strict(),Dw=r.object({requestId:Dt,operationId:Dt,sourceId:Dt,sourceGeneration:bn,expectedRevision:bn,status:r.enum(["pending","unknown","committed","failed"]),publishedRevision:bn.optional(),errorCode:r.enum(["operation_failed","commit_unknown"]).optional(),executionComplete:r.boolean(),durable:r.boolean(),consumed:r.boolean()}).strict(),jw=r.object({text:r.string(),sha256:r.string().regex(/^[a-f0-9]{64}$/),modifiedAt:r.number().int().nonnegative(),provenance:r.array(Dt).max(256),deletionGeneration:bn}).strict(),iy=r.object({turn:r.number().int().optional(),text:r.string().max(32768),queuedAt:Dt,owner:Dt.optional()}).strict(),Lu=r.object({version:r.literal(1),identity:zu,epoch:bn,revision:bn,deletionGeneration:bn,files:r.record(jw),indexValid:r.boolean(),invites:r.array(iy).max(256),consolidation:r.string().nullable(),tombstones:r.record(bn),receipts:r.record(r.object({digest:r.string(),receipt:Dw}).strict()),activeOperation:Dt.nullable(),lease:r.object({owner:Dt,fence:bn}).strict().nullable(),fence:bn}).strict(),at=class extends Error{constructor(n){super(n);this.code=n;this.name="MemoryManagementError"}code};function Te(t){throw new at(t)}var Yn=t=>_w("sha256").update(t).digest("hex"),en=t=>structuredClone(t),or=t=>(BigInt(t)>=ty&&Te("capacity_exceeded"),(BigInt(t)+1n).toString()),pn=t=>Yn(t),yi=(t,e)=>Bt(t)===Bt(e);function Nw(){let t=Ow.tmpdir();try{return Mw.native(t)}catch{return t}}function ar(t){return Yn(Bt({...zu.parse(t),sourceGeneration:void 0}))}async function x0(t){(!Ct.isAbsolute(t)||t===":memory:")&&Te("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&&Te("source_unavailable");let a=i.get(s);return a!==void 0&&Yn(a.body)!==a.etag&&Te("integrity_mismatch"),a===void 0?null:{...a}},async compareAndSwap(s,a,d){o&&Te("source_unavailable"),Buffer.byteLength(d)>sr&&Te("capacity_exceeded"),n.exec("BEGIN IMMEDIATE");try{(i.get(s)?.etag??null)!==a&&Te("revision_conflict"),n.prepare("INSERT INTO memory_publication(domain_key,etag,body) VALUES(?,?,?) ON CONFLICT(domain_key) DO UPDATE SET etag=excluded.etag,body=excluded.body").run(s,Yn(d),d),n.exec("COMMIT")}catch(c){try{n.exec("ROLLBACK")}catch{}throw c}},close(){o||(n.close(),o=!0)}}}function R0(t,e){return(e.atomicDurablePublication!==!0||t.capabilities.consistency!=="strong"||!t.capabilities.conditionalPut||t.capabilities.maxObjectBytes<sr)&&Te("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>sr)&&Te("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>sr&&Te("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&&Te("revision_conflict"),(c.length!==o.bytes||Yn(c)!==o.sha256)&&Te("integrity_mismatch"),{etag:o.etag,body:c.toString("utf8")}},async compareAndSwap(n,i,o){let s=Buffer.from(o);s.length>sr&&Te("capacity_exceeded");try{await t.put(`memory/${n}/manifest.json`,new ReadableStream({start(a){a.enqueue(s),a.close()}}),{bytes:s.length,contentType:"application/json",sha256:Yn(s)},i===null?{ifNoneMatch:"*"}:{ifMatch:i})}catch(a){throw a?.kind==="precondition_failed"&&Te("revision_conflict"),a}}}}var Xa=class t{identity;#e;#n;#r="0";#s=new WeakMap;#t=new WeakMap;constructor(e){this.#e=e,this.identity=Object.freeze(zu.parse(e.identity)),this.#n=ar(this.identity)}static async open(e){e.store.atomicDurablePublication!==!0&&Te("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"&&Te("source_unavailable");let o={version:1,identity:en(n.identity),epoch:"0",revision:"0",deletionGeneration:"0",files:{},indexValid:!1,invites:[],consolidation:null,tombstones:{},receipts:{},activeOperation:null,lease:null,fence:"0"};n.#o(o.deletionGeneration),await e.store.compareAndSwap(n.#n,null,Bt(o))}else e.mode==="create"&&Te("revision_conflict");return await n.#i(),n}assertCurrent(){this.#e.assertCurrent()}#o(e){let n=this.#e.minimumDeletionGeneration?.();BigInt(e)<BigInt(this.#r)&&Te("stale_generation"),n!==void 0&&BigInt(e)<BigInt(bn.parse(n))&&Te("stale_generation")}async#i(){this.assertCurrent();let e=await this.#e.store.read(this.#n);this.assertCurrent(),e===null&&Te("source_unavailable"),Buffer.byteLength(e.body)>sr&&Te("capacity_exceeded");let n;try{n=Lu.parse(JSON.parse(e.body))}catch{return Te("integrity_mismatch")}yi(n.identity,this.identity)||Te("stale_generation"),this.#o(n.deletionGeneration);for(let i of Object.values(n.files))(Yn(i.text)!==i.sha256||Buffer.byteLength(i.text)>Zg)&&Te("integrity_mismatch");return(Object.keys(n.files).length>256||Object.keys(n.receipts).length>ey||Object.keys(n.tombstones).length>512)&&Te("capacity_exceeded"),this.#r=n.deletionGeneration,{state:n,etag:e.etag}}async#a(e,n){this.assertCurrent(),n.epoch=or(e.state.epoch),this.#o(n.deletionGeneration),Lu.parse(n);let i=Bt(n);Buffer.byteLength(i)>sr&&Te("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){Dt.parse(e),n!==void 0&&Dt.parse(n);let{state:i}=await this.#i(),o=i.receipts[pn(e)];return o?(n!==void 0&&o.receipt.requestId!==n&&Te("request_conflict"),en(o.receipt)):null}async consume(e){let n=await this.#i(),i=en(n.state),o=i.receipts[pn(e)];return(!o||o.receipt.status!=="committed")&&Te("invalid_request"),(i.activeOperation!==null||i.lease!==null)&&Te("busy"),o.receipt.consumed||(o.receipt.consumed=!0,await this.#a(n,i)),en(o.receipt)}async prepareReconciliation(e,n){Dt.parse(e),Dt.parse(n);let i=await this.#i(),o=i.state.receipts[pn(e)];if(!o||(o.receipt.requestId!==n&&Te("request_conflict"),!["pending","unknown"].includes(o.receipt.status)))return null;i.state.activeOperation!==e&&Te("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||Te("forbidden"),n.signal?.throwIfAborted(),await n.beforeCommit?.(),n.signal?.throwIfAborted();let o=await this.#i(),s=o.state.receipts[pn(e.operationId)];(o.etag!==i.etag||o.state.epoch!==e.publicationEpoch||o.state.fence!==e.fence||o.state.activeOperation!==e.operationId||s?.receipt.requestId!==e.requestId)&&Te("stale_generation");let a=en(o.state),d=a.receipts[pn(e.operationId)].receipt;a.fence=or(a.fence),a.activeOperation=null,a.lease=null,d.status="failed",d.errorCode="operation_failed",d.durable=!1;try{return await this.#a(o,a),this.#s.delete(e),en(d)}catch(c){if(c instanceof at&&c.code==="revision_conflict")throw c;let l=await this.status(e.operationId,e.requestId).catch(()=>null);return l?.status==="failed"?l:{...d,status:"unknown",errorCode:"commit_unknown"}}}async prepareLeaseReconciliation(){let e=await this.#i();if(e.state.activeOperation!==null&&Te("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||Te("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||!yi(o.state.lease,{owner:e.owner,fence:e.fence}))&&Te("stale_generation");let s=en(o.state);s.fence=or(s.fence),s.lease=null;try{await this.#a(o,s),this.#t.delete(e)}catch(a){if(a instanceof at&&a.code==="revision_conflict")throw a;Te("commit_unknown")}}async createHost(e={}){return this.#d(e)}async execute(e,n,i={},o={}){let s=qw.parse(e);(s.sourceId!==this.identity.sourceId||s.sourceGeneration!==this.identity.sourceGeneration)&&Te("stale_generation");let a=async()=>{o.signal?.throwIfAborted(),await o.beforeCommit?.(),o.signal?.throwIfAborted(),this.assertCurrent()};await a();let d=await this.#i(),c=en(d.state),l=Yn(Bt(s)),f=c.receipts[pn(s.operationId)];if(f)return f.digest!==l&&Te("request_conflict"),en(f.receipt);Object.values(c.receipts).some(v=>v.receipt.requestId===s.requestId)&&Te("request_conflict"),c.revision!==s.expectedRevision&&Te("revision_conflict"),(c.activeOperation!==null||c.lease!==null)&&Te("busy"),Object.keys(c.receipts).length>=ey&&Te("capacity_exceeded");let u={requestId:s.requestId,operationId:s.operationId,sourceId:s.sourceId,sourceGeneration:s.sourceGeneration,expectedRevision:s.expectedRevision,status:"pending",executionComplete:!1,durable:!1,consumed:!1};c.receipts[pn(s.operationId)]={digest:l,receipt:u},c.activeOperation=s.operationId;try{await this.#a(d,c)}catch(v){if(v instanceof at&&v.code==="revision_conflict")throw v;return{...u,status:"unknown",errorCode:"commit_unknown"}}let m;try{m=await this.#i()}catch{return{...u,status:"unknown",errorCode:"commit_unknown"}}let h=m.state.receipts[pn(s.operationId)];if((!h||h.digest!==l)&&Te("integrity_mismatch"),h.receipt.status==="committed"||h.receipt.status==="failed")return en(h.receipt);(m.state.activeOperation!==s.operationId||m.state.fence!==c.fence)&&Te("stale_generation");let g=en(m.state),p=!0;try{o.signal?.throwIfAborted();let v=await this.#d({...i,provenance:()=>{let R=i.provenance?.();return{deletionGeneration:R?.deletionGeneration??g.deletionGeneration,origins:[...R?.origins??[],"operation:"+pn(s.operationId)]}}},{state:g,assertActive:()=>{p||Te("stale_generation"),o.signal?.throwIfAborted()},verifyCurrent:async()=>{let R=await this.#i();(R.etag!==m.etag||R.state.activeOperation!==s.operationId)&&Te("stale_generation")}});await n(v),v.assertCurrent(),s.command.kind==="forget"&&this.#c(g,v,s.command.topic),g.revision=or(g.revision),g.activeOperation=null,g.lease=null;let b=g.receipts[pn(s.operationId)].receipt;b.status="committed",b.executionComplete=!0,b.durable=!0,b.publishedRevision=g.revision,await a();try{return await this.#a(m,g),en(b)}catch{let R=await this.status(s.operationId,s.requestId).catch(()=>null);return R?.status==="committed"||R?.status==="failed"?R:{...u,status:"unknown",executionComplete:!0,errorCode:"commit_unknown"}}}catch{let v=en(m.state),b=v.receipts[pn(s.operationId)].receipt;b.status="failed",b.executionComplete=!0,b.errorCode="operation_failed",v.activeOperation=null;try{return await this.#a(m,v),en(b)}catch{let R=await this.status(s.operationId,s.requestId).catch(()=>null);return R?.status==="committed"||R?.status==="failed"?R:{...u,status:"unknown",errorCode:"commit_unknown"}}}finally{p=!1}}#c(e,n,i){(!/^[^/\\\u0000]+\.md$/i.test(i)||["memory.md","pending-anchors.md"].includes(i.toLowerCase()))&&Te("invalid_request");let o=Ct.relative(n.rootDir,Ct.join(n.memoryDir,i)).split(Ct.sep).join("/"),s=process.platform==="win32"?o.toLowerCase():o,a=Ct.relative(n.rootDir,Ct.join(n.memoryDir,"MEMORY.md")).split(Ct.sep).join("/"),d=process.platform==="win32"?a.toLowerCase():a,c=Ct.relative(n.rootDir,Ct.join(n.memoryDir,"pending-anchors.md")).split(Ct.sep).join("/"),l=process.platform==="win32"?c.toLowerCase():c,f=new Set([s,d]),u=!0;for(;u;){u=!1;for(let[m,h]of Object.entries(e.files))!f.has(m)&&h.provenance.some(g=>f.has(g))&&(f.add(m),u=!0)}e.deletionGeneration=or(e.deletionGeneration);for(let m of f)delete e.files[m],m!==d&&m!==l&&(e.tombstones[pn(m)]=e.deletionGeneration);e.indexValid=!1,e.invites=[],e.consolidation=null,Object.keys(e.tombstones).length>512&&Te("capacity_exceeded")}async#d(e,n){let i=e.rootDir??Ct.join(Nw(),"tansr-memory-world",this.#n),o=e.memoryDir??Ct.join(i,"memory");(!Ct.isAbsolute(i)||!Ct.isAbsolute(o)||Ct.resolve(i)!==i||Ct.resolve(o)!==o||!o.startsWith(i+Ct.sep))&&Te("invalid_request");let s=n?.state??(await this.#i()).state,a=s.deletionGeneration,d=en(s.invites),c=null,l=new Set,f=()=>{this.assertCurrent(),this.#o(a),n?.assertActive()},u=k=>{f(),(!Ct.isAbsolute(k)||/\u0000/.test(k))&&Te("forbidden");let A=Ct.relative(i,Ct.resolve(k));(A.startsWith("..")||Ct.isAbsolute(A))&&Te("forbidden");let C=A.split(Ct.sep).join("/"),F=process.platform==="win32"?C.toLowerCase():C;return[C,F].some(L=>L.split("/").some(Q=>Object.hasOwn(Object.prototype,Q)))&&Te("forbidden"),F},m=u(o),h=u(Ct.join(o,"MEMORY.md")),g=m+"/pending-anchors.md",p=k=>{let A=u(k),C=A.slice(m.length+1);return(A===""||A===m)&&Te("forbidden"),Dt.parse(A),A.startsWith(m+"/")&&xp.includes(C.toLowerCase())&&Te("forbidden"),A},v=async()=>{f(),await n?.verifyCurrent();let k=n?.state??(await this.#i()).state;return k.deletionGeneration!==a&&Te("stale_generation"),!n&&k.activeOperation!==null&&Te("busy"),c!==null&&!yi(k.lease,c)&&Te("stale_generation"),k.lease!==null&&(!c||!yi(k.lease,c))&&Te("busy"),k},b=async(k,A=!1)=>{if(f(),n){await v();let Q=k(n.state);return Lu.parse(n.state),Q}let C=await this.#i();C.state.deletionGeneration!==a&&Te("stale_generation"),c!==null&&!yi(C.state.lease,c)&&Te("stale_generation"),(C.state.activeOperation!==null||C.state.lease!==null&&(!c||!yi(C.state.lease,c)))&&Te("busy");let F=en(C.state),L=k(F);return A&&(F.revision=or(F.revision)),await this.#a(C,F),L},R=async k=>{let A=p(k),C=await v();if(A===h&&!C.indexValid)throw Object.assign(new Error("Memory index unavailable"),{code:"ENOENT"});let F=C.files[A];if(!F)throw Object.assign(new Error("Memory file absent"),{code:"ENOENT"});return l.add(A),F.provenance.forEach(L=>l.add(L)),Buffer.from(F.text)},w=async(k,A,C)=>{let F=p(k);(A.length>Zg||!A.equals(Buffer.from(A.toString("utf8"))))&&Te("invalid_request");let L=e.provenance?.();(!L||L.deletionGeneration!==a||L.origins.length===0)&&Te("stale_generation");let Q=[...new Set([...L.origins,...l])];Q.forEach(se=>Dt.parse(se)),await b(se=>{Object.keys(se.files).some(I=>I!==F&&(I.startsWith(F+"/")||F.startsWith(I+"/")))&&Te("invalid_request"),C!==void 0&&(se.files[F]?.sha256??null)!==C&&Te("revision_conflict"),(se.tombstones[pn(F)]||Q.some(I=>se.tombstones[pn(I)]!==void 0))&&Te("stale_generation");let O={text:A.toString("utf8"),sha256:Yn(A),modifiedAt:Date.now(),provenance:Q,deletionGeneration:a};se.files[F]=O,se.indexValid=F===h,F!==h&&delete se.files[h],Object.keys(se.files).length>256&&Te("capacity_exceeded")},!0)},x=async k=>{let A=u(k),C=await v(),F=A===""||A===m||Object.keys(C.files).some(Q=>Q.startsWith(A+"/")),L=C.files[A];if(!F&&(!L||A===h&&!C.indexValid))throw Object.assign(new Error("Memory file absent"),{code:"ENOENT"});return{size:F?0:Buffer.byteLength(L.text),mtimeMs:L?.modifiedAt??0,isFile:()=>!F,isDirectory:()=>F,isSymbolicLink:()=>!1}},T={stat:x,lstat:x,realpath:async k=>(await x(k),Ct.resolve(k)),readFile:R,readFilePrefix:async(k,A)=>(await R(k)).subarray(0,A),readFileRange:async(k,A,C)=>(await R(k)).subarray(A,A+C),writeFile:(k,A)=>w(k,A),compareAndWrite:(k,A,C)=>w(k,C,A),appendFile:async(k,A)=>{let C=null,F=await R(k).then(L=>(C=Yn(L),L)).catch(L=>{if(L.code==="ENOENT")return Buffer.alloc(0);throw L});await w(k,Buffer.concat([F,A]),C)},mkdir:async k=>{u(k),await v()},readdir:async k=>{let A=u(k),C=await v(),F=A?A+"/":"",L=new Map;A===""&&L.set(m.split("/")[0],!0);for(let Q of Object.keys(C.files))if(Q.startsWith(F)&&!(Q===h&&!C.indexValid)){let se=Q.slice(F.length),O=se.split("/")[0];L.set(O,se.includes("/"))}return[...L].map(([Q,se])=>({name:Q,isFile:()=>!se,isDirectory:()=>se,isSymbolicLink:()=>!1}))}},P=async()=>{if(c)return null;let k;try{await b(C=>{C.lease!==null&&Te("busy"),C.fence=or(C.fence),k={owner:Pw(),fence:C.fence},C.lease=k})}catch(C){if(C instanceof at&&["busy","revision_conflict"].includes(C.code))return null;throw C}c=k;let A=!1;return{release:async()=>{A||(await b(C=>{yi(C.lease,c)||Te("stale_generation"),C.lease=null}),c=null,A=!0)}}},W=k=>Rm(k.files[g]?.text??""),K=(k,A,C=[])=>{if(!A.length){delete k.files[g];return}let F=Im(A),L=[...new Set([...k.files[g]?.provenance??[],...C])];L.forEach(Q=>Dt.parse(Q)),k.files[g]={text:F,sha256:Yn(F),modifiedAt:Date.now(),provenance:L,deletionGeneration:a}},D={acquireLock:P,pendingInvitesLocation:`memory:${this.identity.sourceId}:pending-invites`,readInitialPendingInvites:()=>(f(),en(d)),persistPendingInvites:async(k,A)=>{await b(C=>{let F=A.map(Q=>iy.parse({...Q,owner:k})),L=new Set(F.map(Q=>Q.queuedAt+"\0"+Q.text));C.invites=[...C.invites.filter(Q=>Q.owner!==k&&!L.has(Q.queuedAt+"\0"+Q.text)),...F],C.invites.length>256&&Te("capacity_exceeded")})},readIndexSnapshot:async k=>{let A=await v();if(!A.indexValid||!A.files[h])return null;let C=A.files[h];if(!(Buffer.byteLength(C.text)>k))return l.add(h),C.provenance.forEach(F=>l.add(F)),C.text}},J={acquireLock:P,readConsolidationMeta:async()=>{let k=(await v()).consolidation;return k===null?null:Xc(k)},writeConsolidationMeta:async k=>{Xc(JSON.stringify(k))||Te("invalid_request"),await b(A=>{A.consolidation=JSON.stringify(k)})},readPendingAnchors:async()=>{let k=await v(),A=W(k);return A.length&&(l.add(g),k.files[g]?.provenance.forEach(C=>l.add(C))),A.length===0?null:{content:A.map(C=>`- [${C.date}] ${C.text}`).join(`
|
|
20
|
-
`),keys:new Set(A.map(C=>Zc(C.text)))}},clearPendingAnchors:async k=>{await b(A=>{K(A,W(A).filter(C=>!k.has(Zc(C.text))))},!0)}},S={authority:this,rootDir:i,memoryDir:o,fs:T,source:{fs:T,pathStyle:process.platform==="win32"?"win32":"posix"},extractionHost:D,consolidationHost:J,provenance:e.provenance,assertCurrent:f,refresh:async()=>{f(),await n?.verifyCurrent();let k=n?.state??(await this.#i()).state;(k.activeOperation!==null&&!n||k.lease!==null&&(!c||!yi(k.lease,c)))&&Te("busy"),c!==null&&!yi(k.lease,c)&&Te("stale_generation"),a!==k.deletionGeneration&&Te("stale_generation"),d=en(k.invites)},appendPendingAnchors:async k=>b(A=>{let C=e.provenance?.();C!==void 0&&C.deletionGeneration!==a&&Te("stale_generation");let F=[...new Set([...C?.origins??[],...l])];F.some(Q=>A.tombstones[pn(Q)]!==void 0)&&Te("stale_generation");let L=Am(W(A),k,new Date().toISOString().slice(0,10));return K(A,L.entries,F),L.added},!0)};return ny.set(S,a),S}};var ry=4*1024*1024,Za=12288,ed=t=>Uw("sha256").update(t).digest("hex"),Tt=t=>{throw new at(t)};function oy(t){let e=ar(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 m=yt("MemoryPublicationRequest",u),h=yt("MemoryPublicationResponse",await t.invoke(m,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>ry)&&Tt("capacity_exceeded"),u.publication)}let a=(u,m,h)=>{if(!("transfer"in u)||u.transfer.transferId!==m)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=>{yt("MemoryPublicationRequest",{...n,action:"begin",...u});let m=c(u),h=d.get(m);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(m,{...u})};async function f(u){i(u);let m=await s();if(m===null)return null;let h=[],g=0;for(;g<m.byteLength;){let R=Math.min(Za,m.byteLength-g),w=await o({...n,action:"read",etag:m.etag,offset:g,length:R});if(w.action!=="read")return Tt("integrity_mismatch");let x=Buffer.from(w.base64,"base64");(w.etag!==m.etag||w.offset!==g||x.toString("base64")!==w.base64||x.length!==w.byteLength||x.length!==R||ed(x)!==w.payloadDigest||w.nextOffset!==g+x.length||w.complete!==(g+x.length===m.byteLength))&&Tt("integrity_mismatch"),h.push(x),g+=x.length}let p=await s();if(p===null||p.etag!==m.etag)return Tt("revision_conflict");(p.byteLength!==m.byteLength||p.sha256!==m.sha256)&&Tt("integrity_mismatch");let v=Buffer.concat(h);(v.length!==m.byteLength||ed(v)!==m.sha256)&&Tt("integrity_mismatch");let b;try{b=new TextDecoder("utf-8",{fatal:!0}).decode(v)}catch{return Tt("integrity_mismatch")}return{etag:m.etag,body:b}}return{atomicDurablePublication:!0,pendingTransfers:()=>[...d.values()].map(u=>({...u})),restorePendingTransfer:l,async read(u){for(let m=0;m<3;m++)try{return await f(u)}catch(h){if(!(h instanceof at)||h.code!=="revision_conflict"||m===2)throw h}return Tt("revision_conflict")},async compareAndSwap(u,m,h){i(u);let g=Buffer.from(h);(g.length<1||g.length>ry)&&Tt("capacity_exceeded");let p=ed(g),v=c({expectedEtag:m,sha256:p}),b=d.get(v),R=b??{transferId:Fw(),expectedEtag:m,byteLength:g.length,sha256:p};R.byteLength!==g.length&&Tt("integrity_mismatch"),l(R);let{transferId:w}=R,x=T=>{let P=a(T,w,g.length);return P.status==="committed"&&(P.etag!==p&&Tt("integrity_mismatch"),d.delete(v)),P};try{let T=x(await o(b?{...n,action:"query",transferId:w}:{...n,action:"begin",...R}));if(T.status==="committed")return;if(T.receivedBytes===null||T.receivedBytes!==g.length&&T.receivedBytes%Za!==0)return Tt("integrity_mismatch");for(let W=T.receivedBytes;W<g.length;W+=Za){let K=g.subarray(W,Math.min(W+Za,g.length)),D=x(await o({...n,action:"chunk",transferId:w,offset:W,base64:K.toString("base64"),byteLength:K.length,payloadDigest:ed(K)}));(D.status!=="staging"||D.receivedBytes!==W+K.length)&&Tt("integrity_mismatch")}x(await o({...n,action:"commit",transferId:w})).status!=="committed"&&Tt("commit_unknown")}catch(T){if(T instanceof at&&T.code==="revision_conflict")throw d.delete(v),T;if(T instanceof at&&T.code==="integrity_mismatch")throw T;try{if(x(await o({...n,action:"query",transferId:w})).status==="committed")return}catch(P){if(P instanceof at&&(P.code==="revision_conflict"||P.code==="integrity_mismatch"))throw P}return Tt("commit_unknown")}}}}import{createHash as ay}from"node:crypto";var sy=t=>ay("sha256").update(t).digest("hex"),Wu=(t,e)=>me(t)===me(e),vi=()=>{throw new at("integrity_mismatch")};function Vu(t,e){if(t.length>8192)throw new at("capacity_exceeded");let n=ar(e.identity),i=new Map;for(let s of t){let a=_t("ExecutionOperation",s.operation);if(a.toolName!=="MemoryPublication")continue;let d=e.allowPriorAuthority?.(a)===!0;if(!d&&s.receipt!==null&&s.receipt.status!=="unknown"&&(!Wu(a.binding,e.binding)||a.scope.authorizationRevision!==e.authorizationRevision))continue;let{digest:c,...l}=a;if((sy("tansr.sdk2.execution.v1\0"+me(l))!==c||a.sessionId!==e.sessionId||a.scope.applicationScopeId!==e.identity.applicationScopeId||a.scope.endUserId!==e.identity.endUserId||!d&&(a.scope.authorizationRevision!==e.authorizationRevision||!Wu(a.binding,e.binding))||a.request.operation!=="tool.invoke"||a.request.args.name!==ri||a.request.args.definitionDigest!==Ei)&&vi(),a.request.operation!=="tool.invoke")return vi();let f=yt("MemoryPublicationRequest",JSON.parse(a.request.args.argsJson));if((f.sourceId!==e.identity.sourceId||f.sourceGeneration!==e.identity.sourceGeneration||f.domainKey!==n)&&vi(),!["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)&&vi();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&&!Wu(u.begin,f)&&vi(),u.begin=f;else if(f.action==="chunk"){let m=Buffer.from(f.base64,"base64"),h=u.chunks.get(f.offset);(m.toString("base64")!==f.base64||m.length!==f.byteLength||sy(m)!==f.payloadDigest||h!==void 0&&!Buffer.from(h).equals(m))&&vi(),u.chunks.set(f.offset,m)}else f.action==="commit"&&(u.commits=!0)}let o=[];for(let[s,a]of i){if(a.unresolved.length===0)continue;let d=a.begin??vi(),c=[...a.chunks].sort(([u],[m])=>u-m),l=ay("sha256"),f=0;for(let[u,m]of c)(u!==f||f+m.length>d.byteLength)&&vi(),f+=m.length,l.update(m);a.commits&&(f!==d.byteLength||l.digest("hex")!==d.sha256)&&vi(),o.push({transfer:{transferId:s,expectedEtag:d.expectedEtag,byteLength:d.byteLength,sha256:d.sha256},unresolvedOperationIds:a.unresolved})}return o}var Oi="sdk2-ext-v1",Lw=16,Hw=1e4,zw={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"]},dy={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"},cy={ImageGen:"imageGen",VideoGen:"videoGen",SpeechToText:"speechToText",TextToSpeech:"textToSpeech"},Ve=class extends Error{constructor(n,i=Ma(n)[0]){super(n);this.code=n;this.status=i}code;status};function V(t,e){throw new Ve(t,e)}function pt(t,e){return me(t)===me(e)}function jn(t){let e=JSON.parse(me(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 dr(t){return(t.startsWith("/")||/[\\:\u0000-\u001f\u007f]/.test(t)||t.split("/").some(e=>e==="."||e===".."))&&V("invalid_request",400),t}function Gw(t){return Ur("sha256").update("tansr.sdk2.client-tool.v1\0").update(Bt(Ro.parse(t))).digest("hex")}function cr(t){Buffer.byteLength(t)>32768&&V("payload_too_large");let e;try{e=JSON.parse(t)}catch{V("invalid_request")}let n=(i,o)=>{if((o>32||typeof i=="number"&&!Number.isFinite(i))&&V("invalid_request"),i!==null&&typeof i=="object")for(let s of Object.values(i))n(s,o+1)};return n(e,0),(e===null||typeof e!="object"||Array.isArray(e))&&V("invalid_request"),e}function td(t){let e=Ar.safeParse(cr(t));return e.success||V("invalid_request"),e.data}function nd(t,e,n){if(t.operation!==e.operation&&V("invalid_request",400),e.operation==="tool.invoke"){let i=td(e.args.resultJson);if(ir(t)){(!n||n.toolName!=="Shell")&&V("invalid_request");let o,s;try{o=Mr(t),s=Oa(o,e)}catch{V("invalid_request")}o.action==="exec"&&s.action==="exec"&&s.result!==null?nd({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&&nd({operation:"tool.invoke",args:{name:Ai,definitionDigest:Or,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===ri&&t.args.definitionDigest===Ei&&((!n||n.toolName!=="MemoryPublication")&&V("invalid_request"),i.status==="ok")){(i.isError||i.content.length!==1||i.content[0]?.t!=="text")&&V("invalid_request");let o,s;try{o=yt("MemoryPublicationRequest",cr(t.args.argsJson)),s=yt("MemoryPublicationResponse",JSON.parse(i.content[0].text))}catch{V("invalid_request")}if((o.action!==s.action||o.sourceId!==s.sourceId||o.sourceGeneration!==s.sourceGeneration||o.domainKey!==s.domainKey||"transferId"in o&&(!("transfer"in s)||o.transferId!==s.transfer.transferId))&&V("binding_conflict"),o.action==="read"&&s.action==="read"){let a=Buffer.from(s.base64,"base64");(s.etag!==o.etag||s.offset!==o.offset||a.toString("base64")!==s.base64||a.length!==s.byteLength||a.length>o.length||s.nextOffset!==o.offset+a.length||Ur("sha256").update(a).digest("hex")!==s.payloadDigest)&&V("invalid_request")}}if(t.operation==="tool.invoke"&&t.args.name===Ai&&t.args.definitionDigest===Or){(!n||n.toolName!=="Shell"||i.status!=="ok"||i.isError||i.content.length!==1||i.content[0]?.t!=="text")&&V("invalid_request");let o,s;try{o=yt("BackgroundRequest",cr(t.args.argsJson)),s=yt("BackgroundResponse",JSON.parse(i.content[0].text))}catch{V("invalid_request")}s.action!==o.action&&V("binding_conflict");let a="task"in s?s.task.identity:s.identity,d="task"in s?s.task.artifact:s.artifact;if((d.operationId!==a.operationId||d.requestDigest!==a.requestDigest)&&V("binding_conflict"),o.action==="launch"?(a.operationId!==n.operationId||a.requestDigest!==n.digest)&&V("binding_conflict"):(!pt(o.identity,a)||"artifact"in o&&!pt(o.artifact,d))&&V("binding_conflict"),o.action==="outputRead"&&s.action==="outputRead"){let c=Buffer.from(s.base64,"base64");(s.offset!==o.offset||c.toString("base64")!==s.base64||c.length!==s.byteLength||c.length>o.length||BigInt(s.nextOffset)!==BigInt(o.offset)+BigInt(c.length)||Ur("sha256").update(c).digest("hex")!==s.payloadDigest||s.complete&&s.gap)&&V("invalid_request")}}}if(t.operation==="fs.read"&&e.operation==="fs.read"){let i=Buffer.from(e.args.bytesBase64,"base64");(i.toString("base64")!==e.args.bytesBase64||i.length>t.args.length)&&V("invalid_request",400)}if(t.operation==="fs.write"&&e.operation==="fs.write"&&e.args.hash!==Ur("sha256").update(Buffer.from(t.args.bytesBase64,"base64")).digest("hex")&&V("invalid_request",400),e.operation==="fs.inspect"&&(dr(e.args.realpath),Number.isFinite(Number(e.args.mtimeMs))||V("invalid_request",400)),e.operation==="fs.list"){let i=new Set;for(let o of e.args.entries)dr(o.name),(o.name.includes("/")||i.has(o.name))&&V("invalid_request",400),i.add(o.name)}if(t.operation==="process.exec"&&e.operation==="process.exec"){let i=e.args.exitCode===null?null:Number(e.args.exitCode);(i!==null&&(!Number.isInteger(i)||i<-2147483648||i>2147483647)||Buffer.byteLength(e.args.stdout)+Buffer.byteLength(e.args.stderr)>t.args.maxOutputBytes)&&V("invalid_request",400)}}function ly(t,e){return JSON.stringify([t,e])}function Mi(t,e){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new TypeError("Execution capacity must be a positive safe integer");return n}var zo=class{constructor(e){this.options=e;if(e.shellSandbox!==void 0&&typeof e.shellSandbox!="boolean")throw new TypeError("Invalid shell sandbox option");if("spoolFor"in e=="factsFor"in e)throw new TypeError("Configure exactly one execution fact backend");_t("Scope",{applicationScopeId:e.applicationScopeId,endUserId:"validation",authorizationRevision:"0"}),Mi(e.maxConnections,256),Mi(e.maxConnectionsPerEndUser,16),Mi(e.maxSessions,512),Mi(e.maxSessionsPerEndUser,qe.maxSessionsPerEndUser),this.now=e.now??Date.now}options;#e=0n;#n=new Map;sessions=new Map;connections=new Map;now;cleanup=new Set;cleanupErrors=[];#r=new Set;trackClose(e){let n=e.catch(i=>{this.cleanupErrors.push(i)});this.cleanup.add(n),n.finally(()=>this.cleanup.delete(n))}async settle(){for(;this.cleanup.size;)await Promise.all([...this.cleanup]);if(this.cleanupErrors.length)throw new AggregateError(this.cleanupErrors,"Execution resources did not close")}observeChanges(e){return this.#r.size>=64&&V("capacity_exceeded",429),this.#r.add(e),()=>{this.#r.delete(e)}}changed(e){if(this.#r.size===0)return;let n=jn(e);for(let i of this.#r)try{i(n)}catch{}}connection(e,n,i){let o=this.connections.get(ly(e,n));return(!o||o.user!==e||o.connection.connectionId!==i||Date.parse(o.connection.expiresAt)<=this.now())&&V("stale_generation"),o}register(e,n,i){n.executorId!==i.executorId&&V("forbidden",403),i=_t("ExecutorRegistrationRequest",JSON.parse(me(i))),new Set(i.workspaces.map(f=>f.workspaceId)).size!==i.workspaces.length&&V("invalid_request",400);let o=i.tools??[];(new Set(o.map(f=>f.name)).size!==o.length||new Set(i.operations).size!==i.operations.length||o.length>0&&!i.operations.includes("tool.invoke"))&&V("invalid_request");for(let[f,u]of this.connections)Date.parse(u.connection.expiresAt)<=this.now()&&this.connections.delete(f);let s=ly(e,i.executorId),a=this.connections.get(s),d=Mi(this.options.maxConnections,256),c=Mi(this.options.maxConnectionsPerEndUser,16);!a&&(this.connections.size>=d||[...this.connections.values()].filter(f=>f.user===e).length>=c)&&V("capacity_exceeded",429),this.#e>=9223372036854775807n&&V("capacity_exceeded",429);let l={protocol:Oi,executorId:i.executorId,connectionId:Ho(),connectionRevision:String(++this.#e),expiresAt:new Date(this.now()+6e4).toISOString(),heartbeatAfterMs:15e3};return this.connections.set(s,{user:e,registration:i,connection:l}),this.changed({kind:"connection-changed",user:e,executorId:i.executorId}),l}heartbeat(e,n,i,o){n.executorId!==i&&V("forbidden",403);let s=this.connection(e,i,o);return s.connection={...s.connection,expiresAt:new Date(this.now()+6e4).toISOString()},this.changed({kind:"connection-changed",user:e,executorId:i}),s.connection}open(e,n,i,o){(this.sessions.has(n)||this.#n.has(n))&&V("binding_conflict");let s=Mi(this.options.maxSessions,512),a=Mi(this.options.maxSessionsPerEndUser,qe.maxSessionsPerEndUser),d=[...this.sessions.values()].filter(c=>c.user===e).length+[...this.#n.values()].filter(c=>c===e).length;(this.sessions.size+this.#n.size>=s||d>=a)&&V("capacity_exceeded",429),this.#n.set(n,e);try{let c;if("factsFor"in this.options)c=this.options.factsFor({endUserId:e,sessionId:n}),(c.transactional!==!0||!pt(c.scope,{applicationScopeId:this.options.applicationScopeId,endUserId:e,sessionId:n}))&&V("forbidden",403);else{let f=this.options.spoolFor({endUserId:e,sessionId:n});pt(f.spool.bindingIdentity(f.bindingId),{applicationScopeId:this.options.applicationScopeId,endUserId:e})||V("forbidden",403),c=new Ka(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)&&V("source_unavailable"),i}async poll(e,n,i,o){n.executorId!==i&&V("forbidden",403),this.connection(e,i,o);let s=[];for(let a of this.sessions.values()){if(a.user!==e)continue;await a.refresh(new AbortController().signal);let d=await a.pollOperation(i,o);if(d!==void 0&&s.push(d),s.length)break}return{protocol:Oi,executorId:i,connectionId:o,operations:s}}async receipt(e,n,i){n.executorId!==i.executorId&&V("forbidden",403);for(let o of this.sessions.values()){if(o.user!==e)continue;let s=await o.store.operation(i.operationId);if(s&&s.sessionId===o.sessionId&&s.scope.endUserId===e&&s.scope.applicationScopeId===this.options.applicationScopeId)return o.accept(i,s)}return V("source_unavailable")}},$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)&&V("invalid_request",400);for(let f of d){(!f||!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(f.name)||typeof f.execute!="function"||f.name in dy||f.name in cy||f.name.startsWith("mcp__")||["Skill","McpDiscover","SearchMemory","ShellOutput","ShellTask","MemoryPublication",Ai,ri,nr].includes(f.name)||this.#a.has(f.name))&&V("binding_conflict");let u=Object.freeze({...f,execute:f.execute.bind(f)});this.#a.set(u.name,{tool:u,def:jn(vn(u))})}let c=e.options.skillsFor?.({endUserId:n,sessionId:i});this.#c=c===void 0?void 0:{registry:new el(c.registry.list()),execution:c.execution},this.#d=this.#c===void 0?void 0:nl(this.#c.registry),this.#f=e.options.mcpFor?.({endUserId:n,sessionId:i}),this.#ee=Ag({enabled:()=>this.backgroundEnabled(),signal:this.#K.signal,...e.options.backgroundRuntimeMs===void 0?{}:{timeoutMs:e.options.backgroundRuntimeMs},invoke:(f,u,m,h)=>this.#se(f,u,m,h)});let l={exec:async f=>{if(this.backgroundEnabled())return this.#ee.exec(f);let u=this.binding,m=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!==m||!u.target.interpreter||!h.interpreter||!pt(h.interpreter,u.target.interpreter))&&V("stale_generation");let g=this.root(),p=f.cwd===g?"":f.cwd.startsWith(`${g}/`)?f.cwd.slice(g.length+1):V("forbidden",403),v=await this.#ie("Shell",{operation:"process.exec",args:{command:f.command,cwd:dr(p),timeoutMs:Math.min(12e4,f.timeoutMs),maxOutputBytes:65536,interpreter:u.target.interpreter}},f.signal,u,m,3e4,!1,void 0,!1,!1,f.toolCallId);v.operation!=="process.exec"&&V("invalid_request",400),f.onChunk?.(v.args.stdout,"stdout"),f.onChunk?.(v.args.stderr,"stderr");let{stdout:b,stderr:R,...w}=v.args,x=w.exitCode===null?null:Number(w.exitCode);return x!==null&&(!Number.isSafeInteger(x)||x<-2147483648||x>2147483647)&&V("invalid_request",400),{...w,exitCode:x,signalName:w.signalName}}};this.#t=[Nc(),ro,oo,Hc,Fc,Lc,zc({executor:l,outputStorage:"memory",boundBackground:this.#ee.runtime,boundSandbox:{enabled:()=>this.shellSandboxEnabled(),exec:f=>this.#pe(f),launch:async f=>{let u=await this.#ee.runtime.launch(f);return(!("sandbox"in u)||!u.sandbox)&&V("invalid_request"),u}}}),Xp(this.#ee.registry),Zp(this.#ee.registry)]}host;user;sessionId;bridge;store;allowedTools;#e;bindOwner(e){if(this.#e!==void 0)throw new Error("Execution ownership already bound");e.transactional===!0!=(this.transactional!==void 0)&&V("unsupported_capability"),this.transactional&&!this.transactional.acceptsOwner(e)&&V("forbidden",403),this.#e=e}get transactional(){return"transactional"in this.store?this.store:void 0}ownershipStable(){return this.pending.size===0&&this.#s.size===0&&(this.transactional!==void 0||!this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId}))}async#n(e){return this.#e===void 0?{value:e()}:this.#e.fence(e)}async#r(e){return this.transactional?((!this.#e||!this.transactional.acceptsOwner(this.#e))&&V("forbidden",403),this.#e.write(async()=>e())):(await this.#n(e)).value}async pollOperation(e,n){if(this.pending.size!==0)return this.transactional?this.#r(async()=>{for(let i of this.pending.values())if(i.binding.target.executorId===e&&i.binding.target.connectionId===n&&this.isCurrent(i))return await this.transactional.dispatch(i),i}):(await this.#n(()=>{for(let i of this.pending.values())if(i.binding.target.executorId===e&&i.binding.target.connectionId===n&&this.isCurrent(i))return i})).value}platform=null;binding=null;policy={authorizationRevision:"0",tools:[]};attachmentSource=null;attachmentSourceRevision=0;requested;pending=new Map;#s=new Set;#t;#o=[];#i=new Map;#a=new Map;#c;#d;#f;#m;#p=null;#w=new Wn;#v=[];#k=!1;#y;#B=new WeakMap;#E=new Map;#z;#S;#g=!0;#N=()=>!1;#J;#U;#j=Promise.resolve();#C=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())&&V("binding_conflict")}bindApplicationCapabilities(e){this.#T=e}close(){if(!this.#g)return;let e=[...this.pending.values()];this.#g=!1,this.#K.abort(),this.#ee.close(),this.#b=void 0,this.#P=void 0,this.#Q.clear(),this.#ne.clear(),this.#A.clear(),this.#de.clear(),this.pending.clear(),this.host.sessions.get(this.sessionId)===this&&this.host.sessions.delete(this.sessionId);for(let n of e)this.host.changed({kind:"operation-cancelled",user:this.user,sessionId:this.sessionId,operation:n});this.host.changed({kind:"session-closed",user:this.user,sessionId:this.sessionId}),this.#m!==void 0&&this.host.trackClose(this.#m.dispose())}serviceTools(){return[...Array.from(this.#a.values(),e=>e.tool),...this.#c?.execution==="managed-service"&&this.#d?[this.#d]:[],...this.#w.names().map(e=>this.#w.get(e))]}systemSegments(){let e=this.#c&&this.available("Skill")?tl(this.#c.registry.list()):null;return[...e?[e]:[],...this.#p&&this.available("McpDiscover")?[this.#p]:[]]}async prepareMcp(e,n,i=!1){this.transactional&&!this.transactional.services||!this.#g||this.#k||!this.#f||!this.#u?.tools.mcp||!i&&!this.platform||!this.policy.tools.some(o=>(o==="McpDiscover"||o.startsWith("mcp__"))&&(n===void 0||n.includes(o))&&(this.allowedTools===void 0||this.allowedTools.includes(o)))||(this.#z??=(async()=>{let o,s=async()=>(o=await this.attachMcp(),null);this.transactional?(this.#e||V("forbidden",403),await Fu({facts:this.transactional,owner:this.#e,callId:`mcp-initialize-${Ho()}`,toolName:"McpDiscover",target:{kind:"controlled-service",executorId:"managed-service",bindingId:this.sessionId,bindingRevision:"0",authorizationRevision:this.policy.authorizationRevision},args:this.#f,signal:AbortSignal.any([e,this.#K.signal]),activeOperationIds:this.#s,otherActiveOperationIds:()=>this.pending.keys()},s)):await s(),e.throwIfAborted(),(!this.#g||o===void 0)&&V("source_unavailable"),this.#p=o.segment,this.#y=o.discoverToolFactory,this.#k=!0})(),await this.#z,e.throwIfAborted(),this.#g||V("source_unavailable"))}async attachMcp(){return this.#f||V("unsupported_capability"),this.#m??=new Br({servers:this.#f.servers,baseEnv:{},connectFactory:pm({client:to({env:{}}),allowedUrls:this.#f.allowedUrls,authorize:async(e,n,i)=>{if(i==="DELETE")return;(!this.#g||this.#T===void 0)&&V("forbidden");let o=n??new AbortController().signal,s=await this.#T(o),a=await this.host.options.readPolicy(this.user,o);o.throwIfAborted(),this.#e?.assertCurrent();let d=this.#S===void 0?this.requested:this.#S.requested;(!this.#g||!this.policyCurrent(a)||!s.tools.mcp||a.authorizationRevision!==this.policy.authorizationRevision||!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))))&&V("forbidden")}})}),qa(this.#m,{registry:this.#w,toolDefs:this.#v})}childMcpDiscover(e){this.#y===void 0&&V("unsupported_capability");let n={registry:new Wn,toolDefs:[]},i=this.#y(n),o=new Set;this.#B.set(e.registry,o);let s=new Set(this.policy.tools.filter(a=>(!this.requested||this.requested.includes(a))&&(!this.allowedTools||this.allowedTools.includes(a))));return{...i,execute:async(a,d)=>{let c=await i.execute(a,d);for(let l of n.toolDefs){let f=n.registry.get(l.name);if(!s.has(f.name))continue;let u=e.registry.get(f.name);u!==void 0&&u!==f||(u===void 0&&e.registry.register(f),e.toolDefs.some(m=>m.name===f.name)||e.toolDefs.push(l),o.add(f),this.#E.set(f.name,f))}return c}}}isChildMcpTool(e,n){return this.#B.get(e)?.has(n)===!0}root(){return`/workspace/${this.binding?.target.workspaceId??"unbound"}`}refresh(e,n=!0){if(e.aborted)return Promise.reject(e.reason);if(!this.#g||this.#q?.signal.aborted)return Promise.reject(new Ve("source_unavailable"));if(this.#C>=Lw)return Promise.reject(new Ve("capacity_exceeded",429));this.#C++;let i=new AbortController,o=AbortSignal.any([e,this.#K.signal,i.signal]),s=setTimeout(()=>i.abort(new Ve("source_unavailable")),Hw),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)&&V("source_unavailable");let f=this.refreshNow(o,n),u={work:f,signal:o};this.#q=u;let m=()=>{this.#q===u&&(this.#q=void 0)};return f.then(m,m),f}),l=Promise.race([c,d]);return this.#j=l.catch(()=>{}),l.finally(()=>{clearTimeout(s),o.removeEventListener("abort",a),this.#C--})}policyCurrent(e=this.policy){return e.expiresAt===void 0||Number.isSafeInteger(e.expiresAt)&&e.expiresAt>this.host.now()}async refreshNow(e,n){let i=this.policy,o=this.#u;try{this.#e?.assertCurrent(),e.throwIfAborted(),this.#T===void 0&&V("unsupported_capability");let s=await this.#T(e);e.throwIfAborted();let a=await this.host.options.readPolicy(this.user,e);e.throwIfAborted(),this.#e?.assertCurrent(),this.policyCurrent(a)||V("source_unavailable"),_t("Scope",{applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,authorizationRevision:a.authorizationRevision}),(!Array.isArray(a.tools)||a.tools.length>128||a.tools.some(u=>typeof u!="string")||BigInt(a.authorizationRevision)>9223372036854775807n||BigInt(a.authorizationRevision)<BigInt(this.policy.authorizationRevision))&&V("stale_generation"),this.#Y&&a.authorizationRevision===this.policy.authorizationRevision&&!pt(a.tools,this.policy.tools)&&V("stale_generation");let d=!1,c=this.binding,l=null;if(c!==null&&this.host.options.readAttachmentSource!==void 0)try{let u=Promise.resolve(this.host.options.readAttachmentSource({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId,binding:jn(c),authorizationRevision:a.authorizationRevision},e));this.host.trackClose(u.then(()=>{},()=>{}));let m=await u;e.throwIfAborted(),(this.binding!==c||!this.#g||this.policy!==i)&&V("stale_generation"),this.host.connection(this.user,c.target.executorId,c.target.connectionId),m!==null&&(l=Object.freeze({source:ph(m),executorId:c.target.executorId,workspaceId:c.target.workspaceId,workspaceRevision:c.target.workspaceRevision,authorizationRevision:a.authorizationRevision}))}catch{e.throwIfAborted()}if(c?.target.interpreter&&this.host.options.confirmInterpreter){let u=c.target,m=await this.host.options.confirmInterpreter({endUserId:this.user,executorId:u.executorId,workspaceId:u.workspaceId,interpreter:Object.freeze({...u.interpreter})},e);e.throwIfAborted(),d=m===!0&&this.#g&&this.binding===c}this.#e?.assertCurrent(),e.throwIfAborted(),(!this.#g||this.binding!==c||this.policy!==i)&&V("stale_generation"),this.policyCurrent(a)||V("source_unavailable");let f=wi(l)!==wi(this.attachmentSource);f&&this.attachmentSourceRevision===Number.MAX_SAFE_INTEGER&&V("capacity_exceeded"),this.policy={authorizationRevision:a.authorizationRevision,tools:[...a.tools],...a.expiresAt===void 0?{}:{expiresAt:a.expiresAt}},this.#Y=!0,this.#u=s,this.#I=d,f&&this.attachmentSourceRevision++,this.attachmentSource=l,n&&this.#S===void 0&&await this.prepareMcp(e,this.requested),this.#e?.assertCurrent(),e.throwIfAborted(),this.policyCurrent()||V("source_unavailable"),(!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===nr||e.name===Ai||e.name===ri||e.name==="MemoryPublication"||this.#a.has(e.name)||this.#i.has(e.name)||this.#t.some(i=>i.name===e.name))&&V("binding_conflict"),this.#i.set(e.name,{...n,digest:Gw(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?vn(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"]:zw[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===nr&&n.definitionDigest===Bo)}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||V("source_unavailable"),jn([...this.#de.values()].filter(n=>e===void 0||n.toolCallId===e))}#Re(e){return(!e.turnId||!e.toolCallId)&&V("invalid_request"),{turnId:e.turnId,toolCallId:e.toolCallId}}#Ie(e){let n=this.binding,i=this.policy.authorizationRevision,o=e.executionTarget;(!this.shellSandboxEnabled()||!n||!o||o.kind!=="device"||o.bindingId!==n.bindingId||o.bindingRevision!==n.revision||o.executorId!==n.target.executorId||o.workspaceId!==n.target.workspaceId||o.workspaceRevision!==n.target.workspaceRevision||o.authorizationRevision!==i||!n.target.interpreter||!pt(o.interpreter,n.target.interpreter))&&V("stale_generation");let s=this.root(),a=e.cwd===s?"":e.cwd.startsWith(`${s}/`)?e.cwd.slice(s.length+1):V("forbidden");return{binding:n,revision:i,cwd:dr(a)}}async#pe(e){let{binding:n,revision:i,cwd:o}=this.#Ie(e);if(this.backgroundEnabled()){let m=await this.#ee.exec(e);return m.sandbox||V("invalid_request"),m}let{response:s,operation:a}=await this.#ve({contract:"terminal-shell-sandbox-v1",action:"exec",call:this.#Re(e),command:e.command,cwd:o,timeoutMs:Math.min(12e4,e.timeoutMs),maxOutputBytes:65536,interpreter:n.target.interpreter},e.signal,n,i,e,!1);if(s.action!=="exec"&&V("invalid_request"),s.result===null)return{exitCode:null,signalName:null,durationMs:0,timedOut:!1,aborted:!1,sandbox:s.sandbox};let d=s.output;d||V("invalid_request");let c={stdout:s.result.stdout,stderr:s.result.stderr};if(d.previewTruncated){this.#D||V("source_unavailable");try{c=await this.#D(a,e.signal)}catch{V("source_unavailable")}}e.signal.throwIfAborted(),this.#e?.assertCurrent(),(!this.shellSandboxEnabled()||!pt(this.binding,a.binding)||this.policy.authorizationRevision!==a.scope.authorizationRevision)&&V("stale_generation");for(let m of["stdout","stderr"]){typeof c[m]!="string"&&V("invalid_request");let h=Buffer.from(c[m],"utf8");(!c[m].startsWith(s.result[m])||h.length>65536||h.length!==d[m].totalBytes||Ur("sha256").update(h).digest("hex")!==d[m].payloadDigest)&&V("source_unavailable")}e.onChunk?.(c.stdout,"stdout"),e.onChunk?.(c.stderr,"stderr");let{stdout:l,stderr:f,...u}=s.result;return{...u,exitCode:u.exitCode===null?null:Number(u.exitCode),signalName:u.signalName,sandbox:s.sandbox}}async#ve(e,n,i,o,s,a){this.shellSandboxEnabled()||V("unsupported_capability");let d=e.action==="exec"||e.request.action==="launch",c=qo(e),l={sessionId:this.sessionId,scope:{applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,authorizationRevision:o},binding:i};if(d&&s.escalationApproval!==void 0){vp(s.escalationApproval,s);let h=this.#A.get(Do(c,l));(!h||!Rg(c,l,await this.store.operation(h),await this.store.receipt(h)))&&V("forbidden"),c=qo({...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:nr,definitionDigest:Bo,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),m=Oa(c,u);if(d&&f&&c.escalation===void 0&&m.sandbox.isolationDenied)for(this.#A.set(Do(c,f),f.operationId);this.#A.size>1024;)this.#A.delete(this.#A.keys().next().value);return f||V("source_unavailable"),{response:m,operation:f}}backgroundSupported(){if(!this.available("Shell")||!this.binding)return!1;try{let e=this.host.connection(this.user,this.binding.target.executorId,this.binding.target.connectionId);return this.shellSandboxEnabled()||e.registration.operations.includes("tool.invoke")&&(e.registration.tools??[]).some(n=>n.name===Ai&&n.definitionDigest===Or)}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())&&V("unsupported_capability"),this.#b=e?{binding:jn(this.binding),authorizationRevision:this.policy.authorizationRevision}:void 0}#ce(e){return e.operation==="tool.invoke"&&e.args.name===Ai&&e.args.definitionDigest===Or}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))&&V("stale_generation");let d=yt("BackgroundRequest",e);if(d.action==="launch"){let p=this.root(),v=d.cwd===p?"":d.cwd.startsWith(`${p}/`)?d.cwd.slice(p.length+1):V("forbidden");d={...d,cwd:dr(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))&&V("binding_conflict"),d.action==="launch"?this.shellSandboxEnabled():ir(c.request)){this.shellSandboxEnabled()||V("unsupported_capability");let{response:p}=await this.#ve({contract:"terminal-shell-sandbox-v1",action:"background",request:d,...d.action==="launch"?{call:this.#Re(o)}:{}},i,s,a,o,!0);if(p.action!=="background"&&V("invalid_request"),p.result===null)throw new Kp(p.sandbox);return{response:p.result,sandbox:p.sandbox}}(o.escalationApproval!==void 0||o.turnId!==void 0&&this.host.options.shellSandbox===!0)&&V("unsupported_capability");let f=JSON.stringify(d);cr(f);let u,m=await this.#ie("Shell",{operation:"tool.invoke",args:{name:Ai,definitionDigest:Or,argsJson:f}},i,s,a,3e4,!0,p=>{u=p});m.operation!=="tool.invoke"&&V("invalid_request");let h=td(m.args.resultJson);(h.status!=="ok"||h.isError||h.content.length!==1||h.content[0]?.t!=="text")&&V("source_unavailable");let g=yt("BackgroundResponse",JSON.parse(h.content[0].text));return g.action!==d.action&&V("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)&&V("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())&&V("forbidden");let i=ar(e),o=jn(this.binding);this.#P&&(!pt(this.#P.identity,e)||!pt(this.#P.binding,o))&&V("binding_conflict"),this.#P={identity:jn(e),domainKey:i,binding:o,authorizationRevision:this.policy.authorizationRevision,enabled:n.enabled},this.memoryPublicationAvailable()||(this.#P=void 0,V("unsupported_capability"));let s=oy({identity:e,signal:AbortSignal.any([n.signal,this.#K.signal]),assertCurrent:()=>{this.memoryPublicationAvailable()||V("source_unavailable")},invoke:(d,c)=>this.#he(d,c)});this.store.recoverableOperations===void 0&&V("unsupported_capability");let a=await this.store.recoverableOperations({applicationScopeId:e.applicationScopeId,endUserId:e.endUserId,sessionId:this.sessionId});n.signal.throwIfAborted(),this.memoryPublicationAvailable()||V("source_unavailable");for(let d of Vu(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")&&V("forbidden");let n=()=>{e.signal.throwIfAborted(),this.#e?.assertCurrent(),(!this.#g||!e.enabled()||!this.#N()||this.pending.size!==0||this.#s.size!==0)&&V("binding_conflict")};this.#V=!0;let i=this.binding,o=this.#P;try{n(),await this.#e.assertIdle(),await this.#X(),await this.refresh(e.signal),n();let s=this.policy.authorizationRevision,a=await this.store.recoverableOperations({applicationScopeId:e.identity.applicationScopeId,endUserId:e.identity.endUserId,sessionId:this.sessionId}),d=a.find(g=>g.operation.toolName==="MemoryPublication"&&(g.receipt===null||g.receipt.status==="unknown"));d||V("binding_conflict");let c=d.operation;Vu(a,{identity:e.identity,sessionId:this.sessionId,binding:c.binding,authorizationRevision:c.scope.authorizationRevision}).length===0&&V("binding_conflict");let f=this.host.connection(this.user,e.executorId,e.connectionId),u=f.registration.workspaces.find(g=>g.workspaceId===e.workspaceId);u||V("forbidden");let m={bindingId:Ho(),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(jn({identity:e.identity,original:a,currentBinding:m,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))&&V("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)&&V("stale_generation")}),n(),this.binding=m,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)&&V("binding_conflict")}memoryPublicationSupported(){if(!this.#g||!this.platform||!this.binding||!this.policyCurrent())return!1;try{this.#e?.assertCurrent();let e=this.binding,n=this.host.connection(this.user,e.target.executorId,e.target.connectionId);return n.connection.connectionRevision===e.target.connectionRevision&&n.registration.workspaces.some(i=>i.workspaceId===e.target.workspaceId&&i.revision===e.target.workspaceRevision)&&n.registration.operations.includes("tool.invoke")&&(n.registration.tools??[]).some(i=>i.name===ri&&i.definitionDigest===Ei)}catch{return!1}}#me;bindMemorySearch(e){if(this.#me)throw new Error("Memory search already bound");this.#me=e}memoryPublicationAvailable(){let e=this.#P;if(!e||!this.#g||!this.platform||!this.policyCurrent()||!e.enabled()||!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===ri&&i.definitionDigest===Ei)}catch{return!1}}#le(e){if(!(e.operation!=="tool.invoke"||e.args.name!==ri||e.args.definitionDigest!==Ei))try{return yt("MemoryPublicationRequest",cr(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:ri,definitionDigest:Ei,argsJson:JSON.stringify(e)}};this.#L(i)||V("source_unavailable"),this.#F&&!["head","read","query"].includes(e.action)&&V("forbidden");let o;try{let s=await this.#ie("MemoryPublication",i,n,this.binding,this.policy.authorizationRevision,3e4,!1,c=>{o=c},!0);s.operation!=="tool.invoke"&&V("invalid_request");let a=td(s.args.resultJson);if(e.action==="read"&&a.status==="error"&&a.message==="revision_conflict")throw new at("revision_conflict");(a.status!=="ok"||a.isError||a.content.length!==1||a.content[0]?.t!=="text")&&V("source_unavailable");let d=yt("MemoryPublicationResponse",JSON.parse(a.content[0].text));return(d.action!==e.action||d.sourceId!==e.sourceId||d.sourceGeneration!==e.sourceGeneration||d.domainKey!==e.domainKey||"transferId"in e&&(!("transfer"in d)||d.transfer.transferId!==e.transferId))&&V("binding_conflict"),d}catch(s){throw["begin","chunk","commit"].includes(e.action)&&"transferId"in e&&o&&this.#Q.set(e.transferId,o.operationId),s}}async invokeClientTool(e,n,i){let o=this.#i.get(e.name),s=i.executionTarget,a=this.binding;(!o||!s||!a||s.kind!=="device"||s.bindingId!==a.bindingId||s.bindingRevision!==a.revision||s.executorId!==a.target.executorId||s.workspaceId!==a.target.workspaceId||s.workspaceRevision!==a.target.workspaceRevision||s.authorizationRevision!==this.policy.authorizationRevision)&&V("stale_generation");let d=JSON.stringify(n);cr(d);let c=await this.execute(e.name,{operation:"tool.invoke",args:{name:e.name,definitionDigest:o.digest,argsJson:d}},i.signal,a,s.authorizationRevision,o.tool.timeoutMs);c.operation!=="tool.invoke"&&V("invalid_request");let l=td(c.args.resultJson);return l.status==="ok"?{content:l.content,...l.isError===!0?{isError:!0}:{}}:{content:[{t:"text",text:l.message}],isError:!0}}available(e,n=!0){if(e==="SearchMemory")return this.#g&&this.policyCurrent()&&this.#me?.()===!0&&(this.requested===void 0||this.requested.includes(e));if(this.isShellAuxiliary(e))return this.backgroundEnabled();if(this.sharedDispatchUnsupported(e)||e==="Shell"&&(!this.binding?.target.interpreter||n&&!this.#I)||!this.#g||!this.policyCurrent()||!this.platform||!this.policy.tools.includes(e)||this.requested&&!this.requested.includes(e)||this.allowedTools&&!this.allowedTools.includes(e)&&!this.#i.has(e))return!1;let i=dy[e],o=cy[e],s=this.#u,a=this.#i.get(e),d=e==="Skill"&&this.#d!==void 0,c=this.#w.has(e)||this.#E.has(e),l=this.operations(e)!==void 0,f=s?.execution?.version==="bound-device-v1"?s.execution.boundDevice.tools:void 0,u=l?(d?f?.skills:a?f?.customTools:i?f?.[i]:!1)===!0:s&&(d?s.tools.skills:c?s.tools.mcp:this.#a.has(e)?s.tools.customTools:i?s.tools[i]:o?s.platform[o]:!1);if(!s||!u||e==="WebSearch"&&!s.platform.webSearch)return!1;let m=this.operations(e);if(!m)return[...this.#o,...this.serviceTools()].some(h=>h.name===e)||this.#E.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(p=>p.workspaceId===h.workspaceId&&p.revision===h.workspaceRevision)&&m.every(p=>g.registration.operations.includes(p))&&(e!=="Shell"||pt(g.registration.interpreter,h.interpreter))&&(!a||(g.registration.tools??[]).some(p=>p.name===e&&p.definitionDigest===a.digest))}catch{return!1}}filterTools(e){return e.filter(n=>this.available(n.name))}capabilities(e=this.platform){let n=this.effectiveTools(),i={protocol:Oi,sessionId:this.sessionId,effectiveTools:n,binding:this.binding};return{...i,platform:e,capabilityRevision:lt(me({...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:sl.filter(a=>this.#u?.platform[a]===!0),executionProfile:this.#u?.execution?.version??"legacy"},s={protocol:Oi,sessionId:this.sessionId,clientPlatform:e,application:o,requestedTools:this.requested===void 0?null:[...this.requested],executor:n,effectiveTools:this.effectiveTools(),binding:i};return{...s,revision:lt(me(s))}}effectiveTools(){let e=[...this.#o,...this.deviceTools(),...this.serviceTools()].map(n=>n.name);if(this.transactional)for(let n of this.policy.tools)this.sharedDispatchUnsupported(n)&&!e.includes(n)&&e.push(n);return e.map(n=>({name:n,executionKind:this.operations(n)?"bound-device":"managed-service",available:this.available(n),unavailableReason:this.sharedDispatchUnsupported(n)?"transactional_dispatch_unavailable":this.available(n)?null:n==="Shell"?"executor_shell_unconfirmed":"capability_unconfirmed"}))}sharedDispatchUnsupported(e){return this.transactional!==void 0&&this.transactional.services===void 0&&this.serviceDispatchRequired(e)}serviceDispatchRequired(e){return this.operations(e)===void 0&&(this.#a.has(e)||["Http","WebFetch","WebSearch","ImageGen","VideoGen","SpeechToText","TextToSpeech","McpDiscover"].includes(e)||e.startsWith("mcp__"))}assertReady(){(!this.#g||this.platform===null)&&V("unsupported_capability"),(this.#S!==void 0||this.#V)&&V("binding_conflict")}async initialize(e){e.sessionId!==this.sessionId&&V("invalid_request",400),(!this.#g||this.#S!==void 0||this.#V||this.#F)&&V("binding_conflict");let n=e.requestedTools??this.requested;if(n?.some(i=>this.sharedDispatchUnsupported(i))&&V("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))&&V("binding_conflict"),this.capabilities(e.platform);this.#S={requested:n};try{return await this.#X(),await this.refresh(new AbortController().signal,!1),await this.prepareMcp(new AbortController().signal,n,!0),await this.#X(),this.#g||V("binding_conflict"),this.platform??=e.platform,this.requested=n,this.capabilities(e.platform)}finally{this.#S=void 0}}async bind(e){this.assertReady(),(e.sessionId!==this.sessionId||!this.platform)&&V("invalid_request",400),await this.#X(),await this.refresh(new AbortController().signal),await this.#X(),await this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId})&&V("binding_conflict"),e.expectedCapabilityRevision!==this.capabilities().capabilityRevision&&V("stale_generation");let n=this.host.connection(this.user,e.executorId,e.connectionId),i=n.registration.workspaces.find(a=>a.workspaceId===e.workspaceId);i||V("binding_conflict");let o=n.registration.interpreter,s=o&&await this.host.options.confirmInterpreter?.({endUserId:this.user,executorId:e.executorId,workspaceId:i.workspaceId,interpreter:Object.freeze({...o})},new AbortController().signal)===!0?{...o}:void 0;if(await this.#X(),this.assertReady(),(!this.#g||!this.#N()||this.host.connection(this.user,e.executorId,e.connectionId)!==n||e.expectedCapabilityRevision!==this.capabilities().capabilityRevision)&&V("stale_generation"),await this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId})&&V("binding_conflict"),this.binding={bindingId:Ho(),revision:String(BigInt(this.binding?.revision??"0")+1n),target:{executorId:e.executorId,connectionId:e.connectionId,connectionRevision:n.connection.connectionRevision,workspaceId:i.workspaceId,workspaceRevision:i.revision,...s?{interpreter:s}:{}}},this.#I=s!==void 0,this.#U!==void 0){let a=this.binding;try{await this.#U()}catch(d){throw this.binding===a&&(this.binding=null),this.attachmentSource=null,d}(!this.#g||this.binding!==a||this.host.connection(this.user,e.executorId,e.connectionId)!==n)&&V("stale_generation")}return this.capabilities()}boundary(e){return this.#o=Object.freeze([...e]),{resolve:n=>{let i=this.deviceTools().includes(n),o=this.#o.includes(n);if(!i&&o&&this.deviceTools().some(l=>l.name===n.name)||!i&&!o&&!this.serviceTools().includes(n)&&this.#E.get(n.name)!==n||!this.available(n.name))return;let s=this.binding,a=this.policy.authorizationRevision,d=me(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&&me(this.binding)!==d)&&V("stale_generation")},...i?{cwd:this.root(),fsForCall:(l,f,u)=>Zf({root:this.root(),callId:l,toolName:f,signal:u,execute:async m=>{let{kind:h,...g}=m,p=await this.execute(f,{operation:h,args:g},u,s,a);return p.operation==="fs.inspect"?{...p.args,mtimeMs:Number(p.args.mtimeMs)}:((p.operation==="process.exec"||p.operation==="tool.invoke")&&V("invalid_request",400),p.args)}})}:{}};return this.transactional&&!i&&this.serviceDispatchRequired(n.name)&&(c.executeService=(l,f,u)=>((!this.#e||!this.transactional)&&V("forbidden",403),Fu({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(ir(e.request)){if(!this.shellSandboxEnabled(n))return!1;try{if(n&&Mr(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)&&V("forbidden"),await this.refresh(i),(!pt(this.binding,o)||s!==this.policy.authorizationRevision)&&V("stale_generation"),(!(l?e==="MemoryPublication"&&this.#L(n):this.available(e))||!this.binding||!d&&!l&&!f&&!this.operations(e)?.includes(n.operation))&&V("forbidden",403),d&&(e!=="Shell"||!this.backgroundEnabled()||!(f?ir(n):this.#ce(n)))&&V("forbidden"),f&&(e!=="Shell"||!this.shellSandboxEnabled()||!ir(n))&&V("forbidden"),_t("ResourceRequest",n),n.operation==="tool.invoke"?(!d&&!l&&!f&&(n.args.name!==e||n.args.definitionDigest!==this.#i.get(e)?.digest)&&V("forbidden"),cr(n.args.argsJson)):n.operation==="process.exec"?((!this.binding.target.interpreter||!pt(n.args.interpreter,this.binding.target.interpreter))&&V("stale_generation"),dr(n.args.cwd)):dr(n.args.path);let m=l&&await this.#te(n);!m&&await this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId},{activeOperationIds:new Set([...this.#s,...[...this.pending.values()].filter(P=>this.isCurrent(P)).map(P=>P.operationId)])})&&V("binding_conflict"),this.pending.size>=64&&V("capacity_exceeded",429);let h=this.host.now()+(n.operation==="process.exec"?n.args.timeoutMs+5e3:a),g={protocol:Oi,operationId:Ho(),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()},p={...g,digest:Ur("sha256").update("tansr.sdk2.execution.v1\0").update(me(g)).digest("hex")};c?.(p);let v=P=>this.bridge.registerToolCall(p.operationId,e,{},h,i,h-this.host.now(),P).then(W=>({value:W}),W=>({error:W})),b,R=!1;if(this.transactional?(await this.#r(async()=>{i.throwIfAborted(),!(m&&await this.#te(n))&&await this.store.hasUnreconciled({applicationScopeId:this.host.options.applicationScopeId,endUserId:this.user,sessionId:this.sessionId},{activeOperationIds:new Set([...this.#s,...this.pending.keys()])})&&V("binding_conflict"),await this.store.prepare(p)}),R=!0,b={value:v(()=>{i.throwIfAborted(),this.pending.set(p.operationId,p)})}):b=await this.#n(()=>v(()=>{i.throwIfAborted(),this.store.prepare(p),R=!0,this.pending.set(p.operationId,p)})),R&&!d&&u)for(this.#de.set(p.operationId,jn({toolCallId:u,operation:{operationId:p.operationId,requestDigest:p.digest},binding:p.binding}));this.#de.size>1024;)this.#de.delete(this.#de.keys().next().value);this.pending.has(p.operationId)&&this.host.changed({kind:"operation-available",user:this.user,sessionId:this.sessionId,operation:p});let w=await b.value.finally(()=>{this.pending.delete(p.operationId)&&this.host.changed({kind:i.aborted||this.host.now()>=h?"operation-cancelled":"operation-removed",user:this.user,sessionId:this.sessionId,operation:p})});if("error"in w)throw w.error;let x=w.value,T=await this.store.receipt(p.operationId);if(T?.status==="failed"&&T.errorCode&&["ENOENT","EACCES","ESTALE","EFBIG","ENOTSUP","EEXIST","ENOTDIR"].includes(T.errorCode))throw Object.assign(new Error(T.errorCode),{code:T.errorCode});return(x.isError||x.content[0]?.t!=="text")&&V("source_unavailable"),(T?.status!=="completed"||!T.result)&&V("source_unavailable"),T.result}status(e){if(this.transactional)throw new Error("Shared execution facts require readStatus");let n=this.store,i=n.operation(e);(!i||i.sessionId!==this.sessionId||i.scope.endUserId!==this.user)&&V("source_unavailable");let o=n.reconciledReceipt(e)??n.receipt(e);return{protocol:Oi,operation:i,status:o?.status??(this.pending.has(e)&&this.isCurrent(i)?"pending":"unknown"),receipt:o}}async readStatus(e){if(!this.transactional)return this.status(e);let n=await this.store.operation(e);(!n||n.sessionId!==this.sessionId||n.scope.endUserId!==this.user)&&V("source_unavailable");let i=await this.store.reconciledReceipt(e)??await this.store.receipt(e);return{protocol:Oi,operation:n,status:i?.status??"unknown",receipt:i}}async readOperation(e){this.#e?.assertCurrent();let n=await this.store.operation(e);return this.#e?.assertCurrent(),(!this.#g||this.host.sessions.get(this.sessionId)!==this||!n||n.sessionId!==this.sessionId||n.scope.endUserId!==this.user||n.scope.applicationScopeId!==this.host.options.applicationScopeId)&&V("source_unavailable"),jn(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=jn({operation:o.operation,unknownReceipt:a,unknownReceiptDigest:lt(me(a)),currentAuthorizationRevision:this.policy.authorizationRevision}),c=await s(d,this.#K.signal);if((!this.#g||this.host.sessions.get(this.sessionId)!==this)&&V("source_unavailable"),(!pt(await this.store.operation(e),d.operation)||!pt(await this.store.receipt(e),a))&&V("binding_conflict"),c===null)return this.readStatus(e);let l=jn(c);(l.operationDigest!==d.operation.digest||l.unknownReceiptDigest!==d.unknownReceiptDigest||typeof l.evidenceId!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~:-]{0,127}$/.test(l.evidenceId))&&V("binding_conflict");let f=_t("ExecutionReceiptRequest",l.receipt);return(f.operationId!==e||f.digest!==d.operation.digest||f.executorId!==d.operation.binding.target.executorId||f.connectionId!==d.operation.binding.target.connectionId||f.status==="unknown")&&V("binding_conflict"),(f.status==="completed"?f.result===null||f.errorCode!==null:f.result!==null||f.errorCode===null)&&V("invalid_request",400),f.result!==null&&nd(d.operation.request,f.result,d.operation),await this.#r(()=>this.store.reconcile(l,d.currentAuthorizationRevision))||V("binding_conflict"),this.readStatus(e)}).finally(()=>{this.#_.get(e)===i&&this.#_.delete(e)});return this.#_.set(e,i),i}async accept(e,n){this.pending.has(n.operationId)&&await this.refresh(new AbortController().signal),(!this.#g||this.host.sessions.get(this.sessionId)!==this||n.sessionId!==this.sessionId||n.scope.applicationScopeId!==this.host.options.applicationScopeId||n.scope.endUserId!==this.user)&&V("source_unavailable"),(e.digest!==n.digest||e.executorId!==n.binding.target.executorId||e.connectionId!==n.binding.target.connectionId)&&V("binding_conflict");let i=!0;try{this.host.connection(this.user,e.executorId,e.connectionId)}catch(a){if(!(a instanceof Ve)||a.code!=="stale_generation")throw a;i=!1}let o=this.pending.has(n.operationId);!i&&o&&V("stale_generation"),!pt(n.binding,this.binding)&&(this.binding!==null||o)&&V("stale_generation"),o&&(n.scope.authorizationRevision!==this.policy.authorizationRevision&&V("stale_generation"),this.operationAvailable(n,i)||V("forbidden")),(e.status==="completed"?e.result===null||e.errorCode!==null||e.result.operation!==n.request.operation:e.result!==null)&&V("invalid_request",400),e.result!==null&&nd(n.request,e.result,n);let s=await this.store.receipt(e.operationId);return s&&!pt(s,e)&&V("binding_conflict"),await this.#r(()=>this.store.accept(e)),o&&this.bridge.submitToolResult(e.operationId,e.status==="completed"?{status:"ok",content:[{t:"text",text:"{}"}]}:{status:"error",message:e.errorCode??"source_unavailable"}),this.pending.delete(e.operationId)&&this.host.changed({kind:"operation-removed",user:this.user,sessionId:this.sessionId,operation:n}),{protocol:Oi,operation:n,status:e.status,receipt:e}}};var Vw=128,$w=16,Kw=1e4,uy=new WeakMap;async function Ku(t,e,n,i){if(e.aborted||n.destroyed)throw new Ve("source_unavailable");let o=uy.get(t);o||(o={total:0,users:new Map},uy.set(t,o));let s=o.users.get(i)??0;if(o.total>=Vw||s>=$w)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}),m=setTimeout(f,Kw);m.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(m),e.removeListener("aborted",f),n.removeListener("close",f)}}function si(t,e,n){let i=me(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 fy(t){let{host:e,req:n,res:i,pathname:o,method:s,endUserId:a}=t,d=m=>{let h=e.sessions.get(m);if(t.sessionFamily===void 0&&h!==void 0&&h.user!==a)throw new Ve("forbidden",403);return e.session(a,m)},c=/^\/v2\/executors\/([^/]+)\/(heartbeats|operations|receipts)$/.exec(o),l=/^\/v2\/sessions\/([^/]+)\/(initialize|execution-capabilities|execution-boundary|execution-bindings|executions)(?:\/([^/]+))?$/.exec(o),f=o==="/v2/executors/connections",u=c!==null||l!==null||f;try{let m=await Ku(e,n,i,a);if(!u){if(!m.controller&&s!=="GET"||/\/(tool-results|cwd)(?:\/|$)/.test(o))throw new Ve("forbidden",403);let R=/^\/v2\/sessions\/([^/]+)\/(messages|inputs)$/.exec(o);R&&s==="POST"&&d(decodeURIComponent(R[1])).assertReady();let w=/^\/v2\/sessions\/([^/]+)\/audio\/(transcriptions|speech)$/.exec(o);if(w&&s==="POST"){let x=d(decodeURIComponent(w[1]));if(await x.refresh(new AbortController().signal),!x.available(w[2]==="transcriptions"?"SpeechToText":"TextToSpeech"))throw new Ve("forbidden")}return!1}let 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(R=>R!=="protocol"&&!(c&&R==="connectionId"))||[...new Set(g.keys())].some(R=>g.getAll(R).length!==1)))throw new Ve("invalid_request",400);let p;if(s==="POST"){if(!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(n.headers["content-type"]??"")||n.headers["content-encoding"])throw new Ve("invalid_request",400);let R=await t.readBody();if(R==="rejected")return!0;if(!R.ok)throw R.reason==="too_large"?(i.setHeader("connection","close"),i.once("finish",()=>n.destroy()),new Ve("payload_too_large")):new Ve("invalid_request",400);p=R.value}if(f)return si(i,201,e.register(a,m,_t("ExecutorRegistrationRequest",p))),!0;if(c){let R=decodeURIComponent(c[1]);if(c[2]==="operations")si(i,200,await e.poll(a,m,R,_t("Id",g.get("connectionId"))));else if(c[2]==="heartbeats"){let w=_t("ExecutorHeartbeatRequest",p);if(w.executorId!==R)throw new Ve("invalid_request",400);si(i,200,e.heartbeat(a,m,R,w.connectionId))}else{let w=_t("ExecutionReceiptRequest",p);if(w.executorId!==R)throw new Ve("invalid_request",400);let x=await e.receipt(a,m,w);(x.status==="unknown"||x.status==="failed")&&t.log?.("warn","execution.result",{endUserId:a,sessionId:x.operation.sessionId,operationId:w.operationId,status:x.status,code:w.errorCode??x.status}),si(i,200,x)}return!0}if(!m.controller)throw new Ve("forbidden",403);let v=decodeURIComponent(l[1]),b=d(v);if(l[2]!=="executions"&&l[3]!==void 0)throw new Ve("invalid_request",400);switch(l[2]){case"initialize":si(i,200,await b.initialize(_t("SessionInitializeRequest",p)));break;case"execution-capabilities":await b.refresh(new AbortController().signal),si(i,200,b.capabilities());break;case"execution-boundary":await b.refresh(new AbortController().signal),si(i,200,b.executionBoundary());break;case"execution-bindings":si(i,200,await b.bind(_t("ExecutionBindingRequest",p)));break;case"executions":{let R=decodeURIComponent(l[3]??"");_t("Id",R),await b.refresh(new AbortController().signal);let w=await b.reconcileStatus(R);w.status==="unknown"&&t.log?.("warn","execution.result",{endUserId:a,sessionId:v,operationId:R,status:"unknown",code:"unknown"}),si(i,200,w);break}}return!0}catch(m){if(i.destroyed||i.writableEnded)return!0;let h=m instanceof Ve,g=m instanceof URIError||m instanceof Error&&m.name==="ZodError",p=h?m.code:g?"invalid_request":"source_unavailable";t.log?.("warn","execution.rejected",{endUserId:a,code:p});let[v,b]=Ma(p);if(v===429)for(let[R,w]of Object.entries(Lt(t.retryAfterMs??5e3)))i.setHeader(R,w);if(!u){let R=p==="forbidden"?ae.v2Forbidden:p==="source_unavailable"?ae.internalError:ae.v2ValidationFailed;return fe(i,v,p,R,{detail:p},{"cache-control":"no-store"}),!0}return si(i,v,{protocol:"sdk2-ext-v1",requestId:Ww(),code:p,status:v,message:p,retryAction:b}),!0}}import{types as Go}from"node:util";import{randomUUID as Sy}from"node:crypto";import{randomUUID as id}from"node:crypto";function py(t,e){return t.sessionId===e.sessionId&&t.sourceSnapshotDigest===e.sourceSnapshotDigest&&t.localHistoryGeneration===e.localHistoryGeneration}var rd=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||!py(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??id(),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")):py(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:id(),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:id(),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:id(),storeIdentity:this.#e.storeIdentity,target:this.runtime.targetFor(e.original),localHistoryGeneration:e.source.localHistoryGeneration,start:()=>{let n=this.#n({history:e.original,rewritten:!0,commitId:e.compensationInput.commitId,observation:e.source});return e.compensationCompletion=n.completion,n.receipt.outcome}},e.ticket.compensateHistory(e.compensationInput),await e.compensationCompletion),e.ticket.status().legacyStore==="not-started"&&e.ticket.status().publication==="not-started"&&e.ticket.concludeUnchanged(),(await this.runtime.rewrite.settle()).status!=="completed")throw new Error("Archive rewrite reconciliation required");this.#t===e&&(this.#t=void 0)}catch(n){throw this.#r.has(e)||this.#r.set(e,n),n}}retry(){if(this.#o!==void 0)return this.#o;let e=(async()=>{let n=this.#s,i=this.#t;if(n!==void 0){let s=n.continuation;if(s===void 0)return!1;s.work===void 0?(s.unadmitted?await n.ticket.retryUnadmittedInput():await this.runtime.capture.awaitReady(),await this.#i(n)):(await s.work.catch(()=>{}),s.receipt!==void 0&&n.ticket.status().stage!=="settled"&&this.#a(n))}await this.runtime.run.retryOriginal();let o=await this.runtime.rewrite.retryOriginal();return i!==void 0&&o.status!=="completed"&&(i.commitInput!==void 0&&i.receipt===void 0&&(i.ticket.commitHistory(i.commitInput),await i.completion),await this.endRewrite(i),o=await this.runtime.rewrite.retryOriginal()),o.status!=="completed"||(await this.runtime.run.settle()).status!=="completed"?!1:(n!==void 0&&this.#r.delete(n),i!==void 0&&this.#r.delete(i),this.#s=void 0,this.#t=void 0,!0)})().finally(()=>{this.#o=void 0});return this.#o=e,e}#c(e){let n=this.#e.read().observation;return rn(n.sessionId,e,n.localHistoryGeneration+1)}};var my=/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/;function Qw(t){let e=me(t);if(Buffer.byteLength(e)>262144)throw new Error("Archive lineage capacity exceeded");let n=JSON.parse(e);Mn(n,["format","storeCommitId","sourceSnapshotDigest","workId","baselineSequence","retentionRevision","origins"]);let i=o=>typeof o=="string"&&/^(0|[1-9][0-9]{0,18})$/.test(o)&&BigInt(o)<=9223372036854775807n;if(n.format!=="serve-archive-lineage-v1"||typeof n.storeCommitId!="string"||!my.test(n.storeCommitId)||typeof n.workId!="string"||!n.workId||Buffer.byteLength(n.workId)>256||n.workId.includes("\0")||typeof n.sourceSnapshotDigest!="string"||!/^[a-f0-9]{64}$/.test(n.sourceSnapshotDigest)||!i(n.baselineSequence)||!i(n.retentionRevision)||!Array.isArray(n.origins)||n.origins.length>4096)throw new Error("Invalid archive lineage");for(let o of n.origins){if(Mn(o,["recordIds","throughSequence"]),!Array.isArray(o.recordIds)||o.recordIds.length>128||new Set(o.recordIds).size!==o.recordIds.length||o.recordIds.some(s=>typeof s!="string"||!my.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 Qu(t,e,n,i,o){if(o.length!==t.history.length)throw new Error("Archive lineage snapshot length changed");return Qw({format:"serve-archive-lineage-v1",storeCommitId:t.commitId,sourceSnapshotDigest:t.observation.sourceSnapshotDigest,workId:e,baselineSequence:n,retentionRevision:i,origins:o})}function hy(t,e,n,i,o){return yy(t,e,n,i,o)}function gy(t,e,n){return yy(t,e,void 0,n,!0)}function yy(t,e,n,i,o){let s=n===void 0?[]:[n];return t.initialIndices.map((a,d)=>{if(a.length){let c=new Set,l=null;for(let f of a){let u=e[f]??{recordIds:s,throughSequence:null};for(let m of u.recordIds)c.add(m);u.throughSequence!==null&&BigInt(u.throughSequence)>BigInt(l??"0")&&(l=u.throughSequence)}return{recordIds:[...c],throughSequence:l}}return{recordIds:s,throughSequence:o||t.messages[d]?.role==="user"?i?.sequence??null:null}})}var wt={turnRunning:"server.v2.error.turn_running",checkpointNotFound:"server.v2.error.checkpoint_not_found",sessionMismatch:"server.v2.error.session_mismatch",checkpointsNotWired:"server.v2.error.checkpoints_not_wired",cwdNotAllowed:"server.v2.error.cwd_not_allowed",cwdInvalid:"server.v2.error.cwd_invalid",cwdUnavailable:"server.v2.error.cwd_unavailable",cwdMismatchOnResume:"server.v2.warning.cwd_mismatch_on_resume",cwdMismatchOnResumeStored:"server.v2.warning.cwd_mismatch_on_resume_stored",cwdMismatchOnRestore:"server.v2.warning.cwd_mismatch_on_restore",usageSnapshotStale:"server.v2.warning.usage_snapshot_stale",recoveryDegraded:"server.v2.warning.recovery_degraded",compactHookBlocked:"server.v2.compaction.hook_blocked",cwdSwitchUnsupported:"server.v2.error.cwd_switch_unsupported",forkSourceNotFound:"server.v2.error.fork_source_not_found",checkpointImportInvalid:"server.v2.error.checkpoint_import_invalid",storeCommitFailed:"server.v2.persistence.store_commit_failed",storeCreateFailed:"server.v2.persistence.store_create_failed"},vy=Object.values(wt);function by(t){return t instanceof Error?t.message:String(t)}async function od(t){let{manager:e,compaction:n,view:i,hooks:o,signal:s}=t,a=[],d=t.sessionCapture===void 0?void 0:await vr({capture:t.governanceCapture??t.sessionCapture,messages:i.messages,signal:s,isCurrent:t.isCurrent??(()=>!1),...t.onPending===void 0?{}:{onPending:t.onPending}}),c,l=!1,f=u=>{let m=Hi({messages:[],transform:{ops:[],usage:u},usageAttribution:{model:n.model??t.model,contextWindowTokens:t.contextWindowTokens}}).events;t.onAbandonedUsage?.(m)};try{let u=[];if(o?.preCompact!==void 0)try{let T=await o.preCompact({signal:s,trigger:"manual",...t.instructions!==void 0?{customInstructions:t.instructions}:{}});if(T.blocked===!0)return a.push({type:"turn.error",scope:"hooks",message:We(wt.compactHookBlocked,{reason:T.blockReason??"-"}),recoverable:!0}),{status:"rejected",reason:"hook_blocked",events:a};u=T.additionalContexts??[]}catch(T){a.push({type:"turn.error",scope:"hooks",message:by(T),recoverable:!0})}let m=[...t.instructions!==void 0?[t.instructions]:[],...u].filter(T=>T.trim().length>0),h=m.length>0?m.join(`
|
|
21
|
-
|
|
22
|
-
`):void 0,g=n.model??t.model;d?.assertSourceCurrent();let p=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:T=>{l?f(T):c=T}});if(d?.assertSourceCurrent(),!p.ok){let T=p.usage??c;return a.push(...Hi({messages:[...i.messages],transform:{ops:[],failure:p,...T!==void 0?{usage:T}:{}},usageAttribution:{model:g,contextWindowTokens:t.contextWindowTokens}}).events),a.push({type:"turn.error",scope:"compaction",message:p.message,recoverable:!0}),c=void 0,{status:"failed",outcome:p,events:a}}let v=[...i.messages],b=e.compactionObserver,R=p.compactionUsage??c,w={messages:v,transform:{ops:[bc(p,i.messages)],...R!==void 0?{usage:R}:{},outcome:p,invalidations:"strategy"},usageAttribution:{model:g,...t.contextWindowTokens!==void 0?{contextWindowTokens:t.contextWindowTokens}:{}},...b!==void 0?{observation:{observer:b,trigger:"manual"}}:{}},x;if(d===void 0)x=Hi(w);else{let T=vc({...w,afterPublishBeforeNotifications:()=>{t.publishHistory(P),d.accept()}}),P=Object.freeze(structuredClone([...T.nextMessages]));t.beforePublish!==void 0&&await t.beforePublish(P,p.messages);let W=()=>T.commit(()=>(d.assertSourceCurrent(),t.publishHistory!==void 0));x=t.commitPrepared===void 0?W():Al(P,W,t.commitPrepared)}if(a.push(...x.events),c=void 0,o?.postCompact!==void 0)try{await o.postCompact({signal:s,trigger:"manual",summaryText:p.summaryText,removedCount:p.removedIndices.length})}catch(T){a.push({type:"turn.error",scope:"hooks",message:by(T),recoverable:!0})}return{status:"compacted",outcome:p,messages:v,events:a}}catch(u){throw c!==void 0&&f(c),u}finally{l=!0}}function Jw(){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 ai=class{#e=null;#n=null;#r=null;#s=Jw();#t;#o;#i;#a;#c;#d;#f;#m;#p;#w;#v;#k;#y;#B;#E;#z=!1;#S;#g;#N;#J;#U;#j;#C;#q;#Y;#I;#u;#T;#_=!1;#K;#P;#Q;#ne;#V;#F;#b;#ee;#A=null;#D=[];#de;#X;#ye;#Re;#Ie;#pe;#ve;#ce;#se;#me;#le;#L;#te;#he=null;#ie;#Te;#Ee;#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;#He;#x;#ze=!1;#Ve;#Be;#tt;#H=0;#xe=0;#ue=new AbortController;#re=new Tp;#Ce=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.#E=zn({async*stream(s,a){yield*i().stream(s,a)}},e.client),this.#O=e.sessionCapture,this.#G=e.contextMaterials,this.#t=e.executor,this.#o=e.cwd,this.#a=e.system,this.#c=e.applicationPromptInfo,this.#d=e.prepareSystem,this.#v=e.runtimeCostSnapshot,this.#k=e.tools,this.#j=e.model,this.#C=e.contextWindowTokens,this.#q=e.maxOutputTokens,this.#Y=e.maxTokens??Li,this.#I=e.thinking,this.#u=e.sessionId??Sy(),this.#T=new wc(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:Ap(e.compaction,e.compactionManagerOptions),this.#de=e.reminders,this.#X=e.budget,this.#ye=e.toolResultBudget,this.#Re=e.onEvent,this.#Ie=e.queryHooks,this.#pe=e.onClosed,this.#ve=e.requestMeasurement,this.#ce=e.sessionEvents,this.#se=e.onTurnStart,this.#me=e.onInputsConsumed,this.#le=e.onTurnEnd,this.#Ee=e.getMemorySelectionCheckpoint,this.#L=e.attachmentPersistence?.scope,this.#te=e.attachmentPersistence?.verifySource===!0,this.#je=e.runQueryImpl??ks,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=Bl(s.sourceCheckpoint),l=Fi(s.checkpoint,{scope:this.#L,messages:this.#h});c!==null&&hh(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=Fi(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.#C===void 0)return;let{manager:n,...i}=this.#F,o=Ep(i,void 0,{client:this.#E,contextWindowTokens:this.#C}),s=lp(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:Fi(this.#be,{...i,invalidateReferences:this.#be.historyDigest!==Zr(e)}));return o!==void 0&&n&&(o=Fi(o,{...i,invalidateReferences:!0})),this.#b===void 0&&(this.#be=o),this.#m===void 0&&o?.injectedBytes===0&&o.rejectedCount===0&&o.entries.length===0?void 0:o}invalidateAttachmentReferences(){this.#ie=void 0,this.#b?.runPostCompactInvalidations(),this.#be!==void 0&&this.#L!==void 0&&(this.#be=Fi(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:mh(this.#L,e,n,this.#he)}updateAttachmentSource(e){this.#te&&(wi(e)!==wi(this.#he)&&this.invalidateAttachmentReferences(),this.#he=e)}confirmAttachmentSource(e){if(!this.#te)return Promise.resolve();if(this.status()!=="idle")return Promise.reject(new Error("Attachment source confirmation requires idle session"));let n=new AbortController;this.#Te=n;let i=this.#h,o=this.#H,s=AbortSignal.any([this.#ue.signal,n.signal]),a=Promise.resolve().then(async()=>{await xn(this.#Xe(),s),this.#ke!==void 0&&await xn(this.#ke(),s);let d=e(s);this.#re.track(d.then(()=>{},()=>{}));let c=await xn(d,s);if(s.aborted||this.#R||this.#h!==i||this.#H!==o||this.#M!==null)throw new Error("Attachment source confirmation changed");let l=this.#ie;this.#ie=void 0,(c===null||l===void 0||this.#oe!==0||wi(c)!==wi(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.#Ee?.()}get sessionId(){return this.#u}applicationPrompt(){let e=this.#c?.get(this.#a);return e===void 0?void 0:{policy:e.policy,source:e.source}}contextState(){let e={model:{provider:this.#j.provider,model:this.#j.model},alias:null,contextWindowTokens:this.#C??null};return{selected:e,active:this.#M===null?null:structuredClone(e),lastObserved:structuredClone(this.#e),lastUsage:structuredClone(this.#n),fallback:structuredClone(this.#r),budget:As({system:this.#a,tools:this.#k,messages:this.#M?.messages()??this.#h},{contextWindowTokens:this.#C,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.#C===void 0?"unknown":"model"}),sampledAt:Date.now(),history:this.#M===null?"committed":"live",transition:{status:"idle",target:null}}}#Je(e){let n=()=>{this.#f?.assertCurrent(),this.#N?.()};return zn({async*stream(i,o){n(),yield*e.stream(i,o)}},e)}#ft(){let e=this.#F;return!this.#z||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.#Ce.size>0||!this.#re.isSettled()||this.#ge!==void 0||this.#p!==void 0||this.#Te!==void 0)return{status:"rejected",reason:"turn_running"};this.#f?.assertCurrent(),ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),li(this.#x?.storeIdentity,this.#u,this.#l?.runtime),this.#l?.assertReady(),this.#O?.assertReady()}modelBinding(){return{client:this.#U,model:{...this.#j},...this.#C===void 0?{}:{contextWindowTokens:this.#C},...this.#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=p=>p===void 0||Number.isSafeInteger(p)&&p>0;if(e!==void 0&&(!e||typeof e.client?.stream!="function"||typeof e.model?.provider!="string"||!e.model.provider.trim()||typeof e.model.model!="string"||!e.model.model.trim()||!i(e.contextWindowTokens)||!i(e.maxOutputTokens))||n!==void 0&&(!n||typeof n!="object"||!i(n.budget)))return{status:"rejected",reason:"invalid_configuration"};let o=e===void 0?this.#B:this.#J?.(e.client)??e.client,s={...e?.model??this.#j},a=e===void 0?this.#C:e.contextWindowTokens,d=e===void 0?this.#q:e.maxOutputTokens,c=n===void 0?void 0:{...n.budget===void 0?{}:{budget:n.budget}},l=o!==this.#B||me(s)!==me(this.#j)||a!==this.#C||d!==this.#q;if(!l&&me(c??null)===me(this.#I??null)){let p=this.#H;return{status:"ready",isCurrent:()=>!this.#R&&this.#H===p,publish(){}}}if(l&&(this.#b!==void 0&&(a===void 0||this.#b.thresholds.contextWindow>a)||this.#b===void 0&&this.#F!==void 0&&a!==void 0))return{status:"rejected",reason:"context_transition_required"};let f=As({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.#C!==void 0&&a===void 0))return{status:"rejected",reason:"context_transition_required"};let u=this.#H,m=l?this.#Je(o):this.#y,h=e===void 0?this.#U:this.#Je(e.client),g=()=>!this.#R&&!this.#W&&this.#H===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,m),this.#F?.model===void 0&&zn(this.#E,o),this.#y=m,this.#U=h,this.#B=o,this.#j=s,this.#C=a,this.#q=d,this.#z=!0),(l||me(c??null)!==me(this.#I??null))&&(this.#I=c,this.#H++)}}}}setModel(e){let n=this.#Ye();if(n)return n;let i={...this.#j},o=this.#ot(e,this.#I);return o.status==="rejected"?o:(o.publish(),{status:"changed",from:i,to:{...this.#j}})}setThinking(e){let n=this.#Ye();if(n)return n;let i=this.thinking()??null,o=this.#ot(void 0,e);return o.status==="rejected"?o:(o.publish(),{status:"changed",from:i,to:this.thinking()??null})}configurationRejection(){return this.#Ye()}async configure(e,n={}){let i=this.#Ye();if(i)return i;let o;this.#S=new Promise(s=>{o=s});try{if(this.#g&&!await this.#g())return{status:"rejected",reason:"turn_running"};if(this.#R||this.#W)return{status:"rejected",reason:"session_ended"};let s=n.signal===void 0?this.#ue.signal:AbortSignal.any([this.#ue.signal,n.signal]);return s.throwIfAborted(),await e((a,d)=>this.#ot(a,d),s)}finally{if(this.#S=void 0,o(),this.#R)this.#Se();else if(this.#l)this.#Ae();else if(this.#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||(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),li(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"):(gs(this.#G),this.#we([e]),"started")}sendMessage(e){return this.#ae||(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),li(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":(gs(this.#G),this.#we([structuredClone(e)]),"started")}inputCapabilities(){return this.#T.inputCapabilities()}getInputTarget(){return this.#T.getInputTarget()}submitInput(e){return this.#T.submitInput(e)}getInputStatus(e,n){return this.#T.getInputStatus(e,n)}status(){return this.#W||this.#R?"ended":this.#S!==void 0||this.#M!==null||this.#A!==null||this.#_||this.#$!==null||this.#l?.busy?"running":"idle"}trackHistoryDeletionSettlement(){this.#dt=!0,this.#pt()}historyDeletionReady(){return this.#W&&this.#lt}#pt(){!this.#dt||!this.#W||this.#ct||(this.#ct=!0,Promise.resolve().then(()=>this.settleResources()).then(()=>{this.#lt=!0},()=>{}))}lastSeq(){return this.#fe-1}firstSeq(){return this.#$e}bindOnEnded(e){this.#nt=e}bindOwner(e){if(this.#f!==void 0||this.#M!==null)throw new Error("Session ownership already active");this.#f=e;let n=this.#d;this.#d=async i=>(await e.beginTurn(),i.throwIfAborted(),n===void 0?this.#a:n(i))}bindRuntimeRecovery(e,n){if(!this.#f||this.#M||this.#m||this.#O!==void 0&&!cp(this.#O))throw new Error("Runtime recovery unavailable");if(this.#b!==void 0&&this.#L===void 0)throw new Qt("reconciliation_required");if(this.#Ie!==void 0||this.#ce!==void 0||this.#G!==void 0&&!ap(this.#G)||this.#se!==void 0||this.#me!==void 0)throw new Qt("reconciliation_required");if(this.#X!==void 0&&this.#v===void 0)throw new Error("Runtime recovery requires the original cost tracker");if(n!==void 0){if(n.deadline===void 0!=(this.#Pe===void 0))throw new Qt("reconciliation_required");let i=JSON.parse(n.query.configuration),o=this.#X===void 0?void 0:{maxUsd:this.#X.maxUsd,maxTotalTokens:this.#X.maxTotalTokens,onExceeded:this.#X.onExceeded};if(JSON.stringify(i.model)!==JSON.stringify(this.#j)||JSON.stringify(i.tools)!==JSON.stringify(this.#k)||JSON.stringify(i.budget)!==JSON.stringify(o)||!Array.isArray(i.system)||!i.system.every(s=>s!==null&&typeof s=="object"&&typeof s.text=="string"))throw new Qt("reconciliation_required");this.#a=structuredClone(i.system)}this.#m=e,this.#p=n}resumeRuntime(){if(!this.#p||!this.#m||this.#M||this.#R)throw new Error("Runtime recovery unavailable");this.#we([])}prepareArchiveRuntimeRecovery(){if(!this.#p||!this.#m||this.#l||this.#M||this.#R||this.#oe!==0)throw new Error("Archive runtime recovery unavailable");let e=zs(this.#p);if(e.query.sessionId!==this.#u||me(e.query.messages)!==me(this.#h))throw new Qt("reconciliation_required");this.#h=structuredClone(e.archive.messages),this.#H=e.archive.history.observation.localHistoryGeneration,this.#xe=e.archive.history.observation.localHistoryGeneration}resumeArchiveRuntime(e){if(!this.#l||!this.#p||me(e)!==me(this.#p))throw new Qt("reconciliation_required");zs(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.#mt({...e,sessionId:this.#u,seq:this.#fe++,ts:Date.now(),v:"v0",source:n})}pushControl(e,n){let i=this.#fe++;return this.#s.push({type:e,sessionId:this.#u,seq:i,ts:Date.now(),payload:n}),i}async settleResources(){if(this.#S&&await this.#S,this.#$!==null&&await this.#$.catch(()=>{}),await this.#Xe(),await this.#l?.settle(),this.#Le)throw this.#et}async#Xe(){for(;this.#Ce.size>0||this.#A!==null||this.#ge!==void 0;)await Promise.allSettled([...this.#Ce,...this.#A===null?[]:[this.#A.promise],...this.#ge===void 0?[]:[this.#ge]]);if(this.#O===void 0)await this.#re.settle();else{let n=(await Promise.allSettled([this.#re.settle(),this.#O.settle()])).flatMap(i=>i.status==="rejected"?[i.reason]:[]);if(n.length>0)throw new AggregateError(n,"Session capture resource settlement failed")}}close(e){if(!this.#R){if(this.#R=!0,this.#l?.runtime.stopAdmission(),this.#ue.abort(),this.#H+=1,this.#M!==null){this.#M.abort(e?.source);return}if(this.#A!==null){this.#A.ac.abort();return}this.#S||this.#_||this.#ge!==void 0||this.#Se()}}get model(){return this.#j}bindBeforeCompact(e){this.#ee=e}bindArchivePersistenceBarrier(e){if(this.#ke!==e){if(this.#ke!==void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive persistence barrier must be bound before execution");this.#ke=e}}bindArchiveSourceReadCheck(e){if(this.#He!==e){if(this.#He!==void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive source read check must be bound before execution");this.#He=e}}withArchiveSourceObservation(e){let n=this.#h,i=this.#H,o=this.#b;return wl(this,()=>rn(this.#u,this.#h,this.#xe),()=>{if(this.#R||this.#W||this.#S!==void 0||this.#M!==null||this.#A!==null||this.#_||this.#$!==null||this.#ge!==void 0||this.#l?.busy||this.#Ce.size>0||!this.#re.isSettled()||this.#Le||this.#h!==n||this.#H!==i||this.#b!==o||this.#He!==void 0&&this.#He()!==!0)throw new Error("Archive source observation requires an idle, settled session")},e)}archiveHistoryObservation(){return rn(this.#u,this.#h,this.#xe)}assertArchiveContextMaterialsAvailable(){if(this.#b===void 0)throw new Error("Archive context materials require the original context manager")}bindArchiveHistoryPort(e,n,i){if(!(this.#x===e&&this.#Ve===n)){if(this.#x!==void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive history port must be bound before execution");this.#x=e,this.#Ve=n,this.#tt=i}}bindArchiveColdHistory(e){if(this.#Be!==e){if(this.#Be!==void 0||this.#x===void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive cold history initializer must be bound before execution");this.#Be=e}}bindArchiveHistoryCommit(e){if(this.#Ue!==e){if(this.#Ue!==void 0||this.#oe!==0||this.#R||this.#$!==null)throw new Error("Archive commit must be bound before execution");this.#Ue=e}}bindArchiveLineage(e){if(this.#Z)throw new Error("Archive lineage already installed");if(this.status()!=="idle"||!this.#x)throw new Error("Archive lineage requires original idle history");let n=this.#x.read();if(!n.confirmedCommit)throw new Error("Archive lineage requires confirmed Store");let i=e.read(n.confirmedCommit.commitId,n.observation.sourceSnapshotDigest,this.#h.length);this.#Z=e,this.#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(Qu({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(Qu(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 xn(this.#Xe(),o),this.#ke!==void 0&&await xn(this.#ke(),o)),o.aborted||this.#R||this.#W)throw new Error("Archive binding cancelled");!i&&n===void 0&&this.#Ve!==void 0&&(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime,!0),this.#ze=!0,await xn(this.#Ve(),o));let d=c=>{if(o.aborted||this.#R||this.#W||this.#S!==void 0||this.#M!==null||this.#A!==null)throw new Error("Archive binding cancelled");let l=this.#h,f=this.#H,u=this.#b,m=rn(this.#u,l,f),h=!1,g=this.#l,p=this.#O,v=this.#G,b=()=>{if(h&&(this.#l!==g||this.#O!==p||this.#G!==v)||!s||o.aborted||this.#R||this.#W||this.#h!==l||this.#H!==f||this.#b!==u||this.#M!==null||rn(this.#u,this.#h,f).sourceSnapshotDigest!==m.sourceSnapshotDigest)throw new Error("Archive binding source changed")};b();let R={observation:m,signal:o,assertCurrent:b,...this.#x===void 0?{}:{historyPort:this.#x}};if(c!==void 0){if(this.#Be===void 0)throw new Error("Archive cold history initializer unavailable");this.#Be(c),this.#ze=!0,b()}let w=()=>{let x=bl(e(R));if(i)return(async()=>{let P=await x.value;if(b(),Object.keys(x).some(W=>W!=="value"))throw new Error("Archive committed read cannot install state");return P})();x.installation!==void 0&&Rl(x.installation,{lease:R,storeIdentity:this.#x?.storeIdentity,contextMaterials:x.contextMaterials??this.#G});let T=x.installation!==void 0&&this.#l!==void 0;if(x.lifecycle!==void 0){if(!T&&(this.#l!==void 0||this.#O!==void 0)||x.capture!==void 0||this.#Ue===void 0||this.#x===void 0)throw new Error("Complete archive lifecycle requires exclusive factory ownership");if(x.contextMaterials!==void 0&&this.#G!==void 0&&x.contextMaterials!==this.#G)throw new Error("Archive binding cannot replace existing ownership");if(b(),T){if(h=!0,gl(x.lifecycle,{lease:R,storeIdentity:this.#x.storeIdentity})!==this.#l.runtime)throw new Error("Archive installation runtime ownership changed")}else{let P=yl(x.lifecycle,{lease:R,storeIdentity:this.#x.storeIdentity});this.#l=new rd(P,this.#x,this.#gt),this.#O=P.capture,x.contextMaterials!==void 0&&(this.#G=x.contextMaterials)}return x.installation!==void 0&&(g=this.#l,p=this.#O,v=this.#G,h=!0,hl(x.lifecycle,{lease:R,storeIdentity:this.#x.storeIdentity,runtime:this.#l.runtime}),Il(x.installation,x.lifecycle,R,this.#G),b()),x.value}if(b(),x.capture!==void 0&&this.#O!==void 0&&x.capture!==this.#O||x.contextMaterials!==void 0&&this.#G!==void 0&&x.contextMaterials!==this.#G)throw new Error("Archive binding cannot replace existing ownership");return Sl(x.capture),b(),x.capture!==void 0&&(this.#O=x.capture),x.contextMaterials!==void 0&&(this.#G=x.contextMaterials),x.value};return c===void 0?w():xl(c,R,w)};if(n===void 0)return d();if(this.#x===void 0||this.#Be===void 0)throw new Error("Archive cold binding requires original factory history");return xn(kl(n,{storeIdentity:this.#x.storeIdentity,sessionId:this.#u},(c,l)=>d(l)),o)}).finally(()=>{if(s=!1,this.#$===a&&(this.#$=null),ho(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"));ml(this.#x.storeIdentity,this.#u);let n=this.#ue.signal,i=!0,o=Promise.resolve().then(async()=>{if(await xn(this.#Xe(),n),this.#ke!==void 0&&await xn(this.#ke(),n),this.#l!==void 0&&await xn(this.#l.settle(),n),this.#G!==void 0&&(await xn(this.#G.settle(),n)).status!=="completed")throw new Error("Archive retirement requires settled materials");if(this.#O!==void 0&&yc(this.#O),this.#Le)throw new Error("Archive retirement requires settled inputs");let s=this.#h,a=this.#H,d=this.#b,c=this.#l,l=this.#O,f=this.#G,u=this.#x;if(c===void 0?l!==void 0||f!==void 0:l!==c.runtime.capture)throw new Error("Archive detachment cannot remove foreign resources");let m=this.#tt,h=rn(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.#H!==a||this.#b!==d||this.#l!==c||this.#O!==l||this.#G!==f||this.#x!==u||rn(this.#u,this.#h,a).sourceSnapshotDigest!==h.sourceSnapshotDigest)throw new Error("Archive detachment source changed")};return vl({observation:h,signal:n,assertCurrent:g,historyPort:u},{runtime:c?.runtime??null,contextMaterials:f,prepareDetach:()=>{g(),m.detach(),m.assertDetached()},detachOwnedState:()=>{this.#l=void 0,this.#O=void 0,this.#G=void 0,this.#ze=!1,this.#x=void 0},assertDetached:()=>{if(this.#l!==void 0||this.#O!==void 0||this.#G!==void 0||this.#ze||this.#x!==void 0)throw new Error("Archive detachment is incomplete")}},e)}).finally(()=>{if(i=!1,this.#$===o&&(this.#$=null),ho(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.#H,o=this.#b;return vr({capture:e,messages:n,signal:this.#ue.signal,isCurrent:()=>!this.#R&&!this.#W&&this.#M===null&&this.#A===null&&this.#h===n&&this.#H===i&&this.#b===o,onPending:s=>this.#re.track(s.then(()=>{},()=>{}))})})}compactIdle(e={}){if(this.#ae)return Promise.reject(new Error("Archive deletion blocks compaction"));if(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),li(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.#H,a=this.#h,d=this.#a,c=this.#O,l=this.#l,f=this.#Z?gp(a):void 0,u=l?.beginRewrite("compaction",{signal:AbortSignal.any([e.signal,this.#ue.signal]),history:a,resources:i,assertCurrent:()=>{if(e.signal.throwIfAborted(),this.#ue.signal.throwIfAborted(),this.#h!==a||this.#H!==s||this.#b!==i||this.#a!==d)throw new Error("Archive compaction source changed")}}),m;try{let h=this.#ee,g=h!==void 0&&o.checkpoint!==!1?v=>h(v,{trigger:"manual",...o.checkpoint!==void 0?{checkpoint:o.checkpoint}:{}}):void 0,p=await od({manager:i,compaction:n,view:{system:d,messages:a,tools:this.#k},model:this.#j,...this.#C!==void 0?{contextWindowTokens:this.#C}:{},...o.instructions!==void 0?{instructions:o.instructions}:{},...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 R=f(b);if(rn(this.#u,R.messages,0).sourceSnapshotDigest!==rn(this.#u,v,0).sourceSnapshotDigest)throw new Error("Archive compaction lineage changed");this.#Oe.set(v,{origins:gy(R,this.#Me,this.#Z.head()),workId:u.ticket.rewriteId})}m=await l.persistRewrite(u,v)},commitPrepared:((v,b)=>{let R;return m(()=>{R=b()}),R})},isCurrent:()=>!this.#R&&!this.#W&&this.#H===s&&this.#h===a&&this.#a===d&&this.#b===i,publishHistory:v=>{this.#h=v,this.#H+=1,this.#xe+=1},onPending:v=>this.#re.track(v.then(()=>{},()=>{}))}}).catch(v=>{if(c!==void 0&&(this.#R||this.#W))return{status:"rejected",reason:"session_ended",events:[]};throw v});if(this.#R||this.#W){for(let v of p.events)v.type==="cost.usage.updated"&&this.pushBody(v,"server");return{status:"rejected",reason:"session_ended"}}if(p.status==="compacted"){c===void 0&&(this.#h=Object.freeze(structuredClone(p.messages)),this.#H+=1,this.#xe+=1);for(let v of p.events)this.pushBody(v,"server");return this.#_e=this.#fe-1,{status:"compacted",outcome:p.outcome,...p.outcome.checkpointId!==void 0?{checkpointId:p.outcome.checkpointId}:{}}}for(let v of p.events)this.pushBody(v,"server");return p.status==="failed"?{status:"failed",outcome:p.outcome}:{status:"rejected",reason:p.reason}}finally{u!==void 0&&await l.endRewrite(u)}}withArchiveRestore(e,n=!1,i){if(this.#ae&&!n)throw new Error("Archive deletion blocks checkpoint restoration");ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),li(this.#x?.storeIdentity,this.#u,this.#l?.runtime);let o=this.#l;if(o===void 0)return;if(this.status()!=="idle")return Promise.reject(new Error("Archive restore requires an idle session"));let s=this.#h,a=this.#H,d=this.#b,c=this.#ue.signal,l=()=>!this.#R&&!this.#W&&this.#h===s&&this.#H===a&&this.#b===d,f=o.beginRewrite("restore",{signal:c,history:s,resources:new gr,assertCurrent:()=>{if(c.throwIfAborted(),!l())throw new Error("Archive restore source changed")}}),u=(async()=>{try{let m=await vr({capture:f.ticket.governanceCapture,messages:s,signal:c,isCurrent:l});return await e(async(h,g)=>{m.assertSourceCurrent();let p=Object.freeze(structuredClone([...h]));i&&this.#Oe.set(p,{origins:i,workId:g});let v=this.#rt(!0),b=await o.persistRewrite(f,p);return m.assertSourceCurrent(),b(()=>{this.#h=p,this.#H++,this.#xe++,this.#T.reset(),this.#b=v,this.#L!==void 0&&this.#b===void 0&&this.invalidateAttachmentReferences(),m.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(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),li(this.#x?.storeIdentity,this.#u,this.#l?.runtime),this.#R||this.#W)return{status:"rejected",reason:"session_ended"};if(this.#S!==void 0||this.#M!==null||this.#A!==null||this.#_||this.#l?.busy||this.#$!==null)return{status:"rejected",reason:"turn_running"};if(this.#O?.assertReady(),this.#O!==void 0&&i===void 0)throw new Error("Captured restore requires prepared original history");i?.assertSourceCurrent();let o=Object.freeze(structuredClone([...e])),s=this.#rt(!0);i?.assertSourceCurrent();let a=this.#h.length;return this.#h=o,this.#H+=1,this.#xe+=1,this.#T.reset(),this.#b=s,this.#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.#H+=1,this.pushBody({type:"session.cwd_changed",from:n,to:e},"server"),{status:"changed",from:n,to:e})}#Se(){if(!this.#W){if(this.#W=!0,this.pushBody({type:"session.ended"},"server"),this.#s.end(),this.#nt!==void 0)try{this.#nt(this.#fe-1)}catch(e){this.#De("onEnded",e)}if(this.#pe!==void 0)try{let e=Promise.resolve(this.#pe()).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.#pt()}}#vt(e){this.#mt({...e,seq:this.#fe++})}#mt(e){if(e.type==="cost.usage.updated"&&e.agentId===void 0&&e.toolUseId===void 0&&typeof e.provider=="string"&&(e.purpose===void 0||e.purpose==="main")){let i={provider:e.provider,model:e.model};this.#e={model:i,observedAt:e.ts,evidence:"usage"},this.#n={model:i,observedAt:e.ts,usage:structuredClone(e.usage)}}e.type==="cost.provider.switched"&&(this.#r={from:e.from,to:e.to,observedAt:e.ts});let n;if(this.#Re!==void 0)try{this.#Re(e)}catch(i){n={err:i}}this.#s.push(e),n!==void 0&&this.#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:ky(wy.callbackFailed,{callback:e,message:sd(n)},`Assembly callback ${e} threw (${sd(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(ho(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.#p;if(this.#w=n?.deadline??(this.#Pe===void 0?void 0:(this.#f?.now?.()??Date.now())+this.#Pe),this.#ae)throw new Error("Archive deletion blocks new runs");if(ei(this.#x?.storeIdentity,this.#u,this.#l?.runtime),li(this.#x?.storeIdentity,this.#u,this.#l?.runtime),n?.archive){if(!this.#l)throw new Qt("reconciliation_required");zs(n)}else this.#l?.assertReady();let i=this.#O===void 0?void 0:this.#h.length,o=n?.query.messages??[...this.#h,...e.map(p=>typeof p=="string"?{role:"user",blocks:[{t:"text",text:p}]}:p)],s=e.map(p=>typeof p=="string"?p:p.blocks.flatMap(v=>v.t==="text"?[v.text]:[]).join(`
|
|
23
|
-
`));this.#qe=[],this.#oe=n?.turn??this.#oe+1,this.#Ke=[],this.#Qe=!1,this.#Ge=n?.archive!==void 0&&me(n.query.messages.slice(0,this.#h.length))!==me(this.#h);let a=this.#oe;if(n===void 0&&this.#l===void 0&&this.#se!==void 0){let p=this.#se;this.#We("onTurnStart",()=>p(a,s))}let d=this.#ht(s),c={client:this.#y,executor:this.#t,system:this.#a,tools:this.#k,model:this.#j,maxTokens:this.#Y,...this.#q!==void 0?{maxOutputTokens:this.#q}:{},maxTokensEscalation:{ceilingTokens:pp},...this.#I!==void 0?{thinking:this.#I}:{},sessionId:this.#u,initialMessages:o,...this.#m===void 0?{}:{recovery:{scope:this.#L??this.#u,...n===void 0?{}:{resume:n.query},...n===void 0||this.#d===void 0?{}:{prepare:async p=>{await this.#d(p)}},checkpoint:p=>{let v=this.#T.historyEpoch(),b=this.#oe,R=this.#l===void 0?void 0:this.#x?.read().confirmedCommit;if(this.#l&&!R)throw new Qt("reconciliation_required");return this.#m({query:p,historyEpoch:v,turn:b,...R===void 0?{}:{archive:{version:1,history:n?.archive?.history??R,messages:structuredClone(this.#h),queryDigest:lt(me(p)),historyEpoch:v,turn:b}},...this.#w===void 0?{}:{deadline:this.#w}},this.#v?.())},leaveCheckpoint:()=>this.#f.beginTurn()}},...this.#Z?{observeHistorySources:!0}:{},...this.#O===void 0?{}:{sessionCapture:this.#O,sessionCaptureInputStart:i},...this.#G!==void 0?{contextMaterials:this.#G}:{},...this.#me!==void 0?{onInputsConsumed:p=>{this.#We("onInputsConsumed",()=>this.#me?.(p.map(v=>v.text)))}}:{},...this.#C!==void 0?{contextWindowTokens:this.#C}:{},...this.#F!==void 0&&this.#b!==void 0?{...this.#v===void 0?{}:{onReportedUsage:p=>{if(p.purpose!=="compaction")return;let v=Hi({messages:[],transform:{ops:[],usage:p.usage},usageAttribution:{model:{model:p.model,provider:p.provider},contextWindowTokens:this.#C}});for(let b of v.events)this.pushBody(b,"server")}},compaction:{...this.#ft(),manager:this.#b,...this.#ee!==void 0?{beforeCompact:this.#ee}:{}}}:{},...this.#K!==void 0?{maxTurns:this.#K}:{},...this.#P===void 0?{}:{temperature:this.#P},...this.#Q===void 0?{}:{stopSequences:[...this.#Q]},...this.#ne===void 0?{}:{maxToolRounds:this.#ne},...this.#V===void 0?{}:{maxConsecutiveErrors:this.#V},...this.#de!==void 0?{reminders:this.#de}:{},...this.#ce!==void 0?{sessionEvents:this.#ce}:{},...this.#X!==void 0?{budget:this.#X}:{},...this.#ye!==void 0?{toolResultBudget:this.#ye}:{},...d!==void 0?{hooks:d}:{},...this.#ve!==void 0?{requestMeasurement:this.#ve}:{},...this.#Ze!==void 0?{queryTimeouts:this.#Ze}:{}},l,f,u=p=>{let v=n?.archive?this.#l.runtime.run.resumeRun(n.query.capture):this.#l?.runtime.run.planRun({turnId:Sy(),onAdmitted:()=>{this.#se!==void 0&&this.#We("onTurnStart",()=>this.#se(a,s))}}),b=this.#je(v===void 0?p:{...p,turnId:v.turnId});if(this.#ze){let R=this.#re.registerWithReceipt(b);l=R.markEventsEnded,v!==void 0&&(v.bindQuery({handle:b,receipt:R.receipt}),f={ticket:v,query:b,events:n?.archive?b.events:v.armUnadmittedInput({capture:this.#O,inputStart:i})})}else l=this.#re.register(b);return b},m,h=n!==void 0||this.#d===void 0?u(c):Ha({sessionId:this.#u,history:this.#h,prepare:async p=>(m=await this.#d(p),m),start:p=>{n!==void 0&&(p=this.#a),p.length===this.#a.length&&p.every((R,w)=>{let x=this.#a[w];return x?.text===R.text&&x.cacheable===R.cacheable&&x.label===R.label})||this.#b?.invalidateRequestBasis();let b=m===void 0?void 0:this.#c?.get(m);return b!==void 0&&this.#c.set(p,b),this.#a=p,u({...c,system:p})},...this.#l===void 0?{}:{eventsFor:p=>f?.query===p?f.events:p.events},errorScope:"server"});this.#M=h,this.#T.bind(h),n!==void 0&&(this.#T.restoreIdentity(n.historyEpoch,n.query.inputs),this.#p=void 0),this.#bt(h);let g=this.#St(h,a,()=>f,()=>l?.()).catch(p=>this.#wt(h,p)).finally(()=>l?.());this.#Ce.add(g),this.#re.track(g),g.then(()=>{this.#Ce.delete(g)},()=>{this.#Ce.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?yp(f.query):void 0;if(this.#Z&&!s&&!u)throw new Error("Archive query source snapshot unavailable");let m=s?this.#h:Object.freeze(u?[...u.messages]:e.messages());if(this.#Z&&u){let g=f.ticket.status();if(!g.captureRunKey)throw new Error("Archive captured run source unavailable");let p=this.#Z.turnRecord(g.captureRunKey,g.turnId),v=hy(u,this.#Me,p,this.#Z.head(),this.#Ge);this.#Oe.set(m,{origins:v,workId:g.captureRunKey})}let h={turn:n,history:m,toolNames:[...this.#Ke],aborted:this.#Qe,...d===void 0?{}:{abortReason:d},isCurrentTurn:()=>this.#oe===n,system:this.#a,rewritten:this.#Ge};await this.#l.finishTurn(f,m,h.rewritten,()=>{this.#h=m,this.#H++,this.#xe++,this.#_e=this.#fe-1,!s&&this.#le!==void 0&&this.#We("onTurnEnd",()=>{this.#L!==void 0&&(h.attachmentCheckpoint=this.attachmentCheckpoint(m)),h.attachmentSourceCheckpoint=this.attachmentSourceCheckpoint(m),h.memorySelectionCheckpoint=this.memorySelectionCheckpoint(),this.#le(h)})},s)}}finally{this.#_=!1,this.#Ae()}}else{if(!s&&(this.#h=Object.freeze(e.messages()),this.#H+=1,this.#xe+=1,this.#_e=this.#fe-1,this.#le!==void 0)){let u=this.#le,m={turn:n,history:this.#h,toolNames:[...this.#Ke],aborted:this.#Qe,...d===void 0?{}:{abortReason:d},isCurrentTurn:()=>this.#oe===n,system:this.#a,rewritten:this.#Ge};this.#We("onTurnEnd",()=>{this.#L!==void 0&&(m.attachmentCheckpoint=this.attachmentCheckpoint(m.history)),m.attachmentSourceCheckpoint=this.attachmentSourceCheckpoint(m.history),m.memorySelectionCheckpoint=this.memorySelectionCheckpoint(),u(m)})}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:ky(wy.pumpFailed,{message:sd(n)},`Internal error in the session driver (${sd(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()}},wy={callbackFailed:"server.v2.session.callback_failed",pumpFailed:"server.v2.session.pump_failed",promptRefreshFailed:"server.v2.session.prompt_refresh_failed"};function ky(t,e,n){let i=We(t,e);return i===t?n:i}function sd(t){let e=t instanceof Error?t.message:String(t);return Qf(e).slice(0,400)}var Ju=new WeakMap;function W2(t,e,n){dd(t,e);let i={import:Object.freeze({}),restore:Object.freeze({checkpoint:!1})},o=Object.freeze({...n,handle:e});return Ju.set(i.import,o),Ju.set(i.restore,o),i}function Wo(t,e){let n=Ju.get(t);return n&&(n.handle!==e&&jt(),n.assertCurrent()),n}var Zu=new WeakMap,ad=new WeakMap,cd=new WeakMap,Yw=["withArchiveBinding","withArchiveColdBinding","withArchiveDetachment","archiveHistoryObservation","assertArchiveContextMaterialsAvailable","historySnapshot","bindArchiveHistoryPort","bindArchiveHistoryCommit","bindArchivePersistenceBarrier","bindArchiveColdHistory","prepareArchiveRuntimeRecovery","resumeArchiveRuntime","send","close","status","settleResources"],Xw=Yw.map(t=>({key:t,value:ai.prototype[t]})),Zw=ai.prototype.status;function jt(){throw new Error("Serve archive factory identity or lifecycle mismatch")}function lr(t){(!t||Go.isProxy(t))&&jt();let e=Zu.get(t),n=Object.getOwnPropertyDescriptor(t,"create");return(!e||!n||!("value"in n)||n.value!==e.create)&&jt(),qh(e.store),e}function Vo(t){t.inCallback&&(t.reentered=!0,jt())}function Yu(t,e,n=[]){Vo(t),t.inCallback=!0,t.reentered=!1;try{let i=Reflect.apply(e,void 0,n);i!==void 0&&(rp(i),jt()),t.reentered&&jt()}finally{t.inCallback=!1}}function Xu(t){(typeof t!="function"||Go.isProxy(t))&&jt()}function xy(t,e){let n=t;for(;n!==null;){Go.isProxy(n)&&jt();let i=Object.getOwnPropertyDescriptor(n,e);if(i!==void 0)return"value"in i||jt(),i.value;n=Object.getPrototypeOf(n)}}function Ry(t,e){e!==void 0&&Zu.set(t,{factory:t,create:t.create,store:e,inCallback:!1,reentered:!1})}function Iy(t,e){let n=Zu.get(t);n!==void 0&&Vo(n);let i=ad.get(e);return i&&i.owner!==lr(t)&&jt(),i}function ld(t){(!t||Go.isProxy(t)||Xw.some(({key:e,value:n})=>xy(t,e)!==n))&&jt(),Reflect.apply(Zw,t,[])}function Ty(t,e,n,i,o){let s=ad.get(e);(!s||s.owner!==lr(t))&&jt(),ld(i),(n.sessionId!==o.sessionId||n.endUserId!==e.endUserId)&&jt(),cd.set(n,{owner:s.owner,driver:i,handle:n,registration:Object.freeze({...o}),request:s,close:n.close,attempted:!1})}async function V2(t,e,n){let i=lr(t);Vo(i),(!n||Go.isProxy(n))&&jt();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)&&jt();let s=o.mode?.value,a=o.assertCurrent?.value,d=o.onRegistered?.value;s!=="fresh"&&s!=="resume"&&jt(),Xu(a),d!==void 0&&Xu(d);let c=Mn(e,["endUserId"],["prompt","model","profile","labels","budget","tools","clientTools","capabilitiesProfile","resume","thinking","sessionId","cwd","fork"]),{prompt:l,...f}=c;l!==void 0&&typeof l!="string"&&jt();let u=JSON.parse(me(f));(u.fork!==void 0||s==="fresh"!=(u.resume===void 0)||typeof u.endUserId!="string"||u.endUserId.length===0)&&jt();let m={owner:i,mode:s,prompt:l,assertCurrent(){lr(t),Yu(i,a),lr(t)},registered(h){this.assertCurrent(),d!==void 0&&Yu(i,d,[Object.freeze({...h})]),this.assertCurrent()}};ad.set(u,m);try{return m.assertCurrent(),await Reflect.apply(i.create,t,[u])}finally{ad.delete(u)}}function dd(t,e){let n=lr(t),i=cd.get(e);return(!i||i.owner!==n||xy(e,"close")!==i.close)&&jt(),ld(i.driver),Object.freeze({driver:i.driver,store:n.store,registration:i.registration})}function $2(t,e,n){let i=lr(t);Vo(i),Xu(n),dd(t,e);let o=cd.get(e);(o.attempted||o.adoption!==void 0)&&jt(),o.adoption=n}function Ay(t){let e=cd.get(t);if(!e)return;let n=e.owner;Vo(n),e.attempted&&jt(),e.attempted=!0;try{dd(n.factory,t),e.adoption||jt(),e.request.assertCurrent(),Yu(n,e.adoption),dd(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 ek="<system-reminder>",tk="</system-reminder>";function Ey(t){return t.t==="text"&&t.text.startsWith(ek)&&t.text.endsWith(tk)}function Fr(t){let e=[];for(let n of t){if(n.role!=="user"||!n.blocks.some(Ey)){e.push(n);continue}let i=n.blocks.filter(o=>!Ey(o));i.length!==0&&e.push({...n,blocks:i})}return e}var Ye=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 nk}from"node:crypto";var Lr=255;function $o(t){if(!Number.isInteger(t)||t<0||t>Lr)throw new RangeError(`sessionIdShard must be an integer in [0, ${Lr}], got ${String(t)}`)}function ef(t){return $o(t),t.toString(16).padStart(2,"0")}function ud(t,e=nk){return ef(t)+e().slice(2)}function Cy(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 fd=class extends Error{cause;constructor(e){super(e instanceof Error?e.message:String(e)),this.name="AdoptFailure",this.cause=e}};function rk(t){switch(t){case"not_found":return 404;case"already_resolved":case"digest_mismatch":return 409;case"expired":return 410}}function tf(t){let{options:e,registry:n,admission:i}=t,o=t.sessionFamily??"sdk1",s=t.sessionFamily?{contract:t.sessionFamily,availability:"source-required"}:{},a=_=>Wi(_)===o,d=t.authenticate??(_=>e.authenticate(_)),c=e.mediaMaxBodyBytes??qe.mediaMaxBodyBytes,l=e.sessionIdShard;l!==void 0&&$o(l);let f=async(_,y,M,$=!1)=>{let ne=fi(_,M),G=i.reserveBody(ne);return G.admitted?(y.once("close",()=>i.releaseBody(ne)),ki(_,M,$?Z=>bi(Z,{maxBytes:M}):void 0)):(ni(y,G),"rejected")},u=(_,y,M,$)=>{M==="too_large"?Rr(_,y,_e.payloadTooLarge,ae.v2PayloadTooLarge,{maxBytes:$}):fe(y,400,_e.invalidJson,ae.invalidJson)},m=_=>{fe(_,503,_e.draining,ae.draining,void 0,Lt(i.retryAfterMs))},h=(_,y)=>{fe(_,400,_e.validationFailed,ae.v2ValidationFailed,{detail:y})},g=(_,y)=>{fe(_,404,_e.sessionNotFound,ae.sessionNotFound,{sessionId:y})},p=_=>{fe(_,403,_e.forbidden,ae.v2Forbidden)},v=$n(t.logger),b=(_,y,M)=>{v("error",rt.storeError,{op:_,code:_e.storeCorrupted,message:On(y),...M!==void 0?{sessionId:M}:{}})},R=(_,y,M,$)=>{v("warn",rt.sessionRejected,{status:_,code:y,message:On(M),...$!==void 0?{sessionId:$}:{}})},w=(_,y,M,$,ne)=>{v("warn",rt.upstreamRejected,{face:_,sessionId:y,...M!==void 0?{upstreamStatus:M}:{},upstreamCode:$,message:ne,status:503})},x=(_,y,M)=>{if(t.sessionFamily&&y instanceof Gn&&y.kind==="transient"){fe(_,503,"source_unavailable",ae.v2StoreCorrupted);return}b("read",y,M),fe(_,500,_e.storeCorrupted,ae.v2StoreCorrupted)},T=(_,y,M)=>{let $=M instanceof Error?M.message:String(M);try{t.logger?.error(We(ae.requestUnhandled,{method:y,path:_,message:$}))}catch{}},P=(_,y)=>{try{t.logger?.log?.("warn",rt.sessionIdHintIgnored,{hintedSessionId:_,sessionId:y,shard:l})}catch{}},W=(_,y,M)=>{try{let $=_.detail??{},ne=G=>{let Z=$[G];return typeof Z=="string"||typeof Z=="number"||typeof Z=="boolean"?Z:void 0};t.logger?.log?.("warn",rt.sessionRejected,{status:y,code:M,scope:"plan",platformCode:typeof _.params?.code=="string"?_.params.code:void 0,tier:ne("tier"),cap:ne("cap"),hardCap:ne("hardCap"),current:ne("current"),limit:ne("limit"),used:ne("used"),retryAfterMs:_.retryAfterMs,upgradeUrl:ne("upgradeUrl")})}catch{}},K=(_,y,M,$)=>{T(y,M,$);try{if(_.destroyed||_.writableEnded)return;if(!_.headersSent){fe(_,500,_e.internalError,ae.internalError);return}_.end()}catch{_.destroy()}},D=(_,y,M,$)=>{fe(_,405,_e.methodNotAllowed,ae.methodNotAllowed,{method:y,path:M},{allow:$})},J=(_,y,M)=>{let $=n.get(y);return $===void 0||!a($.handle)?"absent":$.handle.endUserId!==M?(p(_),"forbidden"):$},S=async(_,y,M)=>{if(y.destroyed)return!1;let $=new AbortController;ik(Math.max(10,M.length),$.signal);let ne=()=>$.abort();y.once("close",ne);try{await Promise.all(M.map(({handle:G,lastSeq:Z})=>n.waitForReplayWatermark(G,Z,$.signal)));for(let{handle:G}of M){let Z=n.get(G.sessionId);if(!Z||Z.handle!==G)throw new Error("Event publication identity changed");!Z.ended&&G.status()!=="ended"&&G.owner?.assertCurrent()}return!y.destroyed}catch(G){return $.signal.aborted||(G instanceof mi?m(y):(T(new URL(_.url??"/","http://local").pathname,_.method??"GET",G),fe(y,500,_e.internalError,ae.internalError))),!1}finally{$.abort(),y.removeListener("close",ne)}},k=_=>{let y=_.handle,M=n.lastActivityAt(y.sessionId)??y.createdAt,$=y.title(),ne=y.mediaState?.();return{...s,sessionId:y.sessionId,endUserId:y.endUserId,status:_.ended?"ended":y.status(),live:!_.ended,lastSeq:y.lastSeq(),createdAt:new Date(y.createdAt).toISOString(),lastActivityAt:new Date(M).toISOString(),...$!==void 0?{title:$}:{},...y.contextState?{context:y.contextState()}:{},...ne?{media:ne}:{}}},A=_=>{let y=_?.lastSeq;return typeof y=="number"&&Number.isSafeInteger(y)&&y>=0?y:0},C=(_,y,M)=>_.getMeta(y,M).then(A),F=(_,y)=>({...s,sessionId:_.sessionId,endUserId:y,status:"ended",live:!1,lastSeq:A(_),createdAt:_.createdAt,lastActivityAt:_.updatedAt,..._.title!==void 0?{title:_.title}:{}}),L=async(_,y,M)=>{let $=await f(_,y,t.maxBodyBytes);if($==="rejected")return;if(!$.ok){u(_,y,$.reason,t.maxBodyBytes);return}let ne=ia.safeParse($.value);if(!ne.success){h(y,ne.error.issues[0]?.message??"invalid body");return}let G=ne.data,Z;if(G.endUser!==void 0&&G.endUser.id!==M){p(y);return}if(t.sessionFamily&&!G.resume){let Pe=$.value.requestId;if(typeof Pe!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(Pe)||G.fork||!t.prepareCreate){h(y,"offload creation requires requestId");return}try{Z=t.prepareCreate(M,Pe,G)}catch(z){if(z instanceof ct){fe(y,z.code==="rollback_pending"?503:409,z.code,ae.v2CreateFailed);return}throw z}if(Z.resume){let{prompt:z,...B}=G;G={...B,resume:{sessionId:Z.sessionId}}}}if(G.fork!==void 0){if(G.resume!==void 0){h(y,'"fork" and "resume" are mutually exclusive');return}let Pe=n.get(G.fork.sessionId);if(Pe&&!a(Pe.handle)){g(y,G.fork.sessionId);return}if(Pe!==void 0&&Pe.handle.endUserId!==M){p(y);return}}let be=G.resume?.sessionId;if(be!==void 0){let Pe=n.get(be);if(Pe&&!a(Pe.handle)){g(y,be);return}if(Pe!==void 0){if(Pe.handle.endUserId!==M){p(y);return}if(!Pe.ended){await O(_,y,Pe.handle,()=>Z?.assertCurrent());return}}if(e.store===void 0){fe(y,409,_e.resumeUnavailable,ae.v2ResumeUnavailable);return}}let ue=await i.rateLimit(_,M);if(!ue.admitted){ni(y,ue);return}let ke=i.tryAdmitSession();if(!ke.admitted){ni(y,ke);return}let ve=n.beginCreate(be??Z?.sessionId,M);if(ve.kind==="ticket"){let Pe=ve.ticket,z=Pe.run(()=>Q(Pe,G,Z)),B;try{B=await z,Z?.assertCurrent()}catch(de){I(y,de,be);return}let ee=B.handle.lastSeq();if(!await S(_,y,[{handle:B.handle,lastSeq:ee}]))return;Z?.assertCurrent(),Qe(y,201,{...s,sessionId:B.handle.sessionId,resumed:B.resumed,lastSeq:ee});return}switch(ve.kind){case"live":if(!a(ve.handle)){g(y,be??"");return}try{Z?.assertCurrent()}catch(Pe){I(y,Pe,be,!1);return}await O(_,y,ve.handle,()=>Z?.assertCurrent());return;case"joined":{try{let Pe=await ve.outcome;if(Z?.assertCurrent(),!a(Pe.handle)){g(y,be??"");return}await O(_,y,Pe.handle,()=>Z?.assertCurrent())}catch(Pe){I(y,Pe,be,!1)}return}case"forbidden":p(y);return;case"closing":m(y);return;case"reserve_rejected":fe(y,429,_e.sessionLimitExceeded,ae.v2SessionLimit,{max:ve.max},Lt(i.retryAfterMs));return}},Q=async(_,y,M)=>{let ne={endUserId:_.endUserId,...y.prompt!==void 0&&y.prompt!==""?{prompt:y.prompt}:{},...y.model!==void 0&&y.model!==""?{model:y.model}:{},...y.profile!==void 0&&y.profile!==""?{profile:y.profile}:{},...y.labels!==void 0?{labels:y.labels}:{},...y.budget!==void 0?{budget:y.budget}:{},...y.tools!==void 0?{tools:y.tools}:{},...y.clientTools!==void 0?{clientTools:y.clientTools}:{},...y.capabilitiesProfile!==void 0?{capabilitiesProfile:y.capabilitiesProfile}:{},...y.resume!==void 0?{resume:y.resume}:{},...y.thinking!==void 0?{thinking:y.thinking}:{},...y.cwd!==void 0?{cwd:y.cwd}:{},...y.fork!==void 0?{fork:y.fork}:{},...l!==void 0&&y.resume===void 0?{sessionId:ud(l)}:{}};M&&!M.resume&&(ne.sessionId=M.sessionId),M?.apply(ne);let G=_.id,Z=await e.createSession.create(ne);if(!a(Z.handle))throw Z.handle.close(),await Z.handle.settleResources?.(),new Error("Session family mismatch");ne.sessionId!==void 0&&Z.handle.sessionId!==ne.sessionId&&P(ne.sessionId,Z.handle.sessionId),G!==void 0&&n.evictEnded(G);try{_.adopt(Z.handle),Ay(Z.handle)}catch(be){throw be instanceof mi?be:(T("/v2/sessions","POST",be),new fd(be))}return Z},se=_=>({...s,sessionId:_.sessionId,resumed:!1,lastSeq:_.lastSeq()}),O=async(_,y,M,$)=>{let ne=se(M);await S(_,y,[{handle:M,lastSeq:ne.lastSeq}])&&($(),Qe(y,200,ne))},I=(_,y,M,$=!0)=>{if(t.sessionFamily&&y instanceof ct){fe(_,y.code==="rollback_pending"?503:409,y.code,ae.v2CreateFailed);return}if(y instanceof Ye){if(y.code==="session_not_found"){g(_,M??"");return}if(y.code==="resume_unavailable"){fe(_,409,_e.resumeUnavailable,ae.v2ResumeUnavailable);return}if(y.code==="store_corrupted"){$&&b("create",y,M),fe(_,500,_e.storeCorrupted,ae.v2StoreCorrupted);return}let ne=Lt(y.retryAfterMs??i.retryAfterMs);if(y.code==="upstream_unavailable"){$&&R(503,_e.upstreamUnavailable,y,M),fe(_,503,_e.upstreamUnavailable,ae.v2UpstreamUnavailable,void 0,ne);return}if(y.code==="overloaded"){fe(_,503,_e.overloaded,ae.overloaded,void 0,ne);return}if(y.code==="plan_limited"){W(y,429,_e.rateLimited),fe(_,429,_e.rateLimited,ae.v2PlanConcurrencyLimited,void 0,ne,{scope:"plan"});return}if(y.code==="plan_denied"){let G=typeof y.params?.code=="string"?y.params.code:"plan_required";W(y,403,G),fe(_,403,G,ae.v2PlanDenied,{code:G},void 0,{scope:"plan"});return}if(y.code==="cwd_not_allowed"){fe(_,400,_e.cwdNotAllowed,wt.cwdNotAllowed,{detail:y.message,...y.params??{}});return}if(y.code==="cwd_invalid"){fe(_,400,_e.cwdInvalid,wt.cwdInvalid,{reason:"invalid",detail:y.message,...y.params??{}});return}if(y.code==="cwd_unavailable"){let G=y.params?.reason;fe(_,409,_e.cwdUnavailable,wt.cwdUnavailable,{cwd:y.message,...y.params??{}},void 0,typeof G=="string"?{cwd:y.params?.cwd??y.message,reason:G}:void 0);return}if(y.code==="fork_source_not_found"){fe(_,404,_e.forkSourceNotFound,wt.forkSourceNotFound,{sessionId:"",checkpointId:"",...y.params??{}});return}if(y.code==="checkpoints_not_wired"){fe(_,409,_e.checkpointsNotWired,wt.checkpointsNotWired);return}h(_,y.message);return}if(y instanceof mi){m(_);return}if(y instanceof fd){fe(_,500,_e.internalError,ae.internalError);return}$&&R(400,_e.createFailed,y,M),fe(_,400,_e.createFailed,ae.v2CreateFailed)},q=async(_,y,M)=>{let $=new URL(_.url??"/","http://local").searchParams,ne=$.get("limit"),G=$.get("offset"),Z=qe.listLimitDefault,be=0;if(ne!==null){if(!/^\d+$/.test(ne)){h(y,"limit must be a positive integer");return}if(Z=Number.parseInt(ne,10),Z<1||Z>qe.listLimitMax){h(y,`limit must be within 1..${qe.listLimitMax}`);return}}if(G!==null){if(!/^\d+$/.test(G)){h(y,"offset must be a non-negative integer");return}be=Number.parseInt(G,10)}let ue=new Map;if(e.store!==void 0){let B;try{B=await e.store.list(M)}catch(ee){x(y,ee);return}for(let ee of B)ue.set(ee.sessionId,F(ee,M))}let ke=new Map;for(let B of n.entriesFor(M))a(B.handle)&&(ue.set(B.handle.sessionId,k(B)),ke.set(B.handle.sessionId,B.handle));if(t.filterSessionReads){let B=new Set(await t.filterSessionReads(M,[...ue.keys()]));for(let ee of ue.keys())B.has(ee)||ue.delete(ee)}let ve=[...ue.values()].sort((B,ee)=>ee.lastActivityAt.localeCompare(B.lastActivityAt)),Pe=ve.slice(be,be+Z),z=Pe.flatMap(B=>{let ee=ke.get(B.sessionId);return ee?[{handle:ee,lastSeq:B.lastSeq}]:[]});if(await S(_,y,z))if(t.filterSessionReads){let B=new Set(await t.filterSessionReads(M,[...ue.keys()]));Qe(y,200,{sessions:Pe.filter(ee=>B.has(ee.sessionId)),total:ve.filter(ee=>B.has(ee.sessionId)).length})}else Qe(y,200,{sessions:Pe,total:ve.length})},H=(_,y)=>{try{return y()}catch(M){if(M instanceof dp)return fe(_,503,_e.overloaded,ae.materialRequired,void 0,Lt(i.retryAfterMs),{scope:"context.materials",reason:M.code}),null;if(!(M instanceof fs)||M.code!=="capacity_exceeded")throw M;return fe(_,503,_e.overloaded,ae.overloaded,void 0,Lt(i.retryAfterMs),{scope:"archive",reason:"capacity_exceeded"}),null}},N=async(_,y,M,$)=>{let ne=J(y,M,$);if(ne==="forbidden")return;if(ne==="absent"){g(y,M);return}let G=await f(_,y,c);if(G==="rejected")return;if(!G.ok){u(_,y,G.reason,c);return}let Z=ra.safeParse(G.value);if(!Z.success){h(y,Z.error.issues[0]?.message??"invalid body");return}if(ne.ended){fe(y,409,_e.sessionEnded,ae.sessionEnded,{sessionId:M});return}if(Z.data.prompt!==void 0){let ke=H(y,()=>ne.handle.send(Z.data.prompt));if(ke===null)return;if(ke==="ended"){fe(y,409,_e.sessionEnded,ae.sessionEnded,{sessionId:M});return}n.touch(M),Qe(y,202,{sessionId:M,accepted:!0});return}let be={role:"user",blocks:(Z.data.blocks??[]).map(ke=>ke.t==="text"?{t:"text",text:ke.text}:{t:"image",mime:ke.mime,data:ke.data})},ue=H(y,()=>ne.handle.sendMessage(be));if(ue!==null){if(ue==="midturn"){fe(y,422,_e.midturnBlocksRejected,ae.v2MidturnBlocks);return}if(ue==="ended"){fe(y,409,_e.sessionEnded,ae.sessionEnded,{sessionId:M});return}n.touch(M),Qe(y,202,{sessionId:M,accepted:!0})}},ie=async(_,y,M,$,ne,G)=>{let Z=J(y,M,$);if(Z==="forbidden")return;if(Z==="absent"){g(y,M);return}let be=Z.handle;if(ne==="input-capabilities"){Qe(y,200,be.inputCapabilities?.()??{version:1,text:!1,textBlocks:!1,image:!1,memoryAck:!1,durableAck:!1,receiptRetention:"current-and-last-turn",target:null});return}if(G!==void 0){let Pe=new URL(_.url??"/","http://local").searchParams,z=Zl.safeParse({historyEpoch:Pe.get("historyEpoch"),turnId:Pe.get("turnId")});if(!z.success){h(y,z.error.issues[0]?.message??"invalid target");return}let B=be.getInputStatus?.(G,z.data)??null;Qe(y,B===null?404:200,B===null?{outcome:"rejected",code:"input_not_found"}:{receipt:B});return}let ue=await f(_,y,c);if(ue==="rejected")return;if(!ue.ok){u(_,y,ue.reason,c);return}let ke=Lh.safeParse(ue.value);if(!ke.success){h(y,ke.error.issues[0]?.message??"invalid input");return}if(be.submitInput===void 0){Qe(y,422,{outcome:"rejected",code:"input_unsupported"});return}let ve=await be.submitInput({inputId:ke.data.inputId,target:ke.data.target,content:ke.data.content,...ke.data.ack!==void 0?{ack:ke.data.ack}:{}});ve.outcome==="accepted"&&n.touch(M),Qe(y,ve.outcome==="accepted"?202:ve.outcome==="closed"?409:ve.code==="injection_limit"?429:ve.code==="input_conflict"?409:422,ve)},U=(_,y,M,$)=>{let ne=i.tryAdmitSse($);if(!ne.admitted){ni(y,ne);return}y.once("close",()=>i.releaseSse($)),t.sseKeepAliveMs>0&&_.socket.setKeepAlive(!0,t.sseKeepAliveMs),_.socket.setTimeout(0);let G=J(y,M,$);if(G==="forbidden")return;if(G==="absent"){g(y,M);return}let Z=Xs(_.headers["last-event-id"]);if(Z===void 0){h(y,"invalid Last-Event-ID");return}let be=new URL(_.url??"/","http://local").searchParams,ue=aa(be.get("exclude"));if(ue===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 ke=G.handle.firstSeq?.()??0,ve=()=>(G.handle.firstSeq?.()??0)===ke,Pe=t.sse.attach(y,{gapFrame:B=>Cr(M,B),beforeFlush:()=>{if(!ve())return!1;let B=d(_,y);return t.filterSessionReads?Promise.resolve(B).then(async ee=>ee?.endUserId===$&&(await t.filterSessionReads($,[M])).includes(M)&&ve()):B!==null&&"then"in B?Promise.resolve(B).then(ee=>ee?.endUserId===$&&ve()):B?.endUserId===$&&ve()}}),z=n.subscribe(M,Z,Pe,ue);y.on("close",()=>{z?.()})},ce=async(_,y,M,$)=>{let ne=new URL(_.url??"/","http://local").searchParams.getAll("include");if(ne.length>1||ne.length===1&&ne[0]!=="applicationPrompt"){h(y,"include must be applicationPrompt and occur once");return}let G=J(y,M,$);if(G==="forbidden")return;if(G!=="absent"){let ue=k(G);if(!await S(_,y,[{handle:G.handle,lastSeq:ue.lastSeq}]))return;let ke=t.readHistoryOrigin?{historyOrigin:await t.readHistoryOrigin($,M)}:{},ve=ne.length===1&&!G.ended&&G.handle.status()!=="ended"?G.handle.applicationPrompt?.():void 0,z=ve!=null&&Object.keys(ve).length===2&&(ve.policy==="fallback"||ve.policy==="prepend")&&["none","platform","sdk","platform+sdk"].includes(ve.source)&&!(ve.policy==="fallback"&&ve.source==="platform+sdk")?{applicationPrompt:{policy:ve.policy,source:ve.source}}:{};if(t.filterSessionReads&&!(await t.filterSessionReads($,[M])).includes(M)){g(y,M);return}Qe(y,200,{...ue,...ke,...z});return}let Z;try{Z=await e.store?.getMeta($,M)}catch(ue){x(y,ue,M);return}if(Z==null){g(y,M);return}let be=t.readHistoryOrigin?{historyOrigin:await t.readHistoryOrigin($,M)}:{};Qe(y,200,{...F(Z,$),...be})},le=async(_,y,M,$)=>{let ne=J(y,M,$);if(ne==="forbidden")return;let G=Vs(new URL(_.url??"/","http://local").searchParams);if(!G.ok){h(y,G.detail);return}let Z=G.page,{offset:be=0,limit:ue}=Z??{};if(ne!=="absent"){let B=ne.handle.historySnapshot();if(Z===null){Qe(y,200,{sessionId:M,lastSeq:B.lastSeq,messages:Fr(B.messages)});return}let ee=Kn(B.messages,be,ue);Qe(y,200,{sessionId:M,lastSeq:B.lastSeq,messages:Fr(ee.messages),total:ee.total,offset:ee.offset,nextOffset:ee.nextOffset});return}let ke=e.store;if(Z!==null&&ue!==void 0&&ke?.getHistoryPage!==void 0){let B;try{B=await ke.getHistoryPage($,M,{offset:be,limit:ue})}catch(de){x(y,de,M);return}if(B===null){g(y,M);return}let ee;try{ee=await C(ke,$,M)}catch(de){x(y,de,M);return}Qe(y,200,{sessionId:M,lastSeq:ee,messages:Fr(B.messages),total:B.total,offset:B.offset,nextOffset:B.nextOffset});return}if(ke===void 0){g(y,M);return}let ve;try{ve=await ke.getHistory($,M)}catch(B){x(y,B,M);return}if(ve===null){g(y,M);return}let Pe;try{Pe=await C(ke,$,M)}catch(B){x(y,B,M);return}if(Z===null){Qe(y,200,{sessionId:M,lastSeq:Pe,messages:Fr(ve)});return}let z=Kn(ve,be,ue);Qe(y,200,{sessionId:M,lastSeq:Pe,messages:Fr(z.messages),total:z.total,offset:z.offset,nextOffset:z.nextOffset})},re=_=>{fe(_,409,_e.turnRunning,wt.turnRunning)},pe=_=>{fe(_,409,_e.checkpointsNotWired,wt.checkpointsNotWired)},j=(_,y)=>{fe(_,404,_e.checkpointNotFound,wt.checkpointNotFound,{checkpointId:y})},Y=(_,y)=>{fe(_,409,_e.sessionEnded,ae.sessionEnded,{sessionId:y})},oe=(_,y)=>{if(y instanceof Ze){x(_,y);return}throw y},Se=async(_,y,M,$)=>{let ne=J(y,M,$);if(ne==="forbidden")return;if(ne==="absent"){g(y,M);return}let G=await f(_,y,t.maxBodyBytes);if(G==="rejected")return;if(!G.ok){u(_,y,G.reason,t.maxBodyBytes);return}let Z=da.safeParse(G.value);if(!Z.success){h(y,Z.error.issues[0]?.message??"invalid body");return}if(ne.ended){Y(y,M);return}if(ne.handle.compact===void 0){Qe(y,200,{status:"rejected",reason:"not_configured"});return}let be;try{be=await ne.handle.compact(Z.data)}catch(ue){oe(y,ue);return}if(n.touch(M),be.status==="rejected"&&be.reason==="turn_running"){re(y);return}if(be.status==="rejected"&&be.reason==="session_ended"){Y(y,M);return}if(be.status==="rejected"&&be.reason==="checkpoints_not_wired"){pe(y);return}Qe(y,200,be)},je=async(_,y,M)=>{let $=J(_,y,M);if($==="forbidden")return;if($==="absent"){g(_,y);return}if($.handle.listCheckpoints===void 0){pe(_);return}let ne;try{ne=await $.handle.listCheckpoints()}catch(G){oe(_,G);return}if(ne.status==="rejected"){pe(_);return}Qe(_,200,{checkpoints:ne.checkpoints})},$e=async(_,y,M,$)=>{let ne=J(y,M,$);if(ne==="forbidden")return;if(ne==="absent"){g(y,M);return}let G=await f(_,y,t.maxBodyBytes);if(G==="rejected")return;if(!G.ok){u(_,y,G.reason,t.maxBodyBytes);return}let Z=ca.safeParse(G.value);if(!Z.success){h(y,Z.error.issues[0]?.message??"invalid body");return}if(ne.ended){Y(y,M);return}if(ne.handle.checkpoint===void 0){pe(y);return}let be;try{be=await ne.handle.checkpoint(Z.data)}catch(ue){oe(y,ue);return}if(n.touch(M),be.status==="created"){Qe(y,201,be.checkpoint);return}be.reason==="turn_running"?re(y):be.reason==="session_ended"?Y(y,M):pe(y)},Fe=async(_,y,M,$,ne)=>{let G=J(y,M,$);if(G==="forbidden")return;if(G==="absent"){g(y,M);return}let Z=await f(_,y,t.maxBodyBytes);if(Z==="rejected")return;if(!Z.ok){u(_,y,Z.reason,t.maxBodyBytes);return}let be=la.safeParse(Z.value);if(!be.success){h(y,be.error.issues[0]?.message??"invalid body");return}if(G.ended){Y(y,M);return}if(G.handle.restore===void 0){pe(y);return}let ue;try{ue=await G.handle.restore(ne,be.data)}catch(ke){oe(y,ke);return}if(n.touch(M),ue.status==="restored"){Qe(y,200,ue);return}switch(ue.reason){case"turn_running":re(y);return;case"session_ended":Y(y,M);return;case"not_found":j(y,ne);return;case"session_mismatch":fe(y,409,_e.sessionMismatch,wt.sessionMismatch,{checkpointId:ne});return;case"checkpoints_not_wired":pe(y);return}},ft=async(_,y,M,$)=>{let ne=J(_,y,M);if(ne==="forbidden")return;if(ne==="absent"){g(_,y);return}if(ne.handle.deleteCheckpoint===void 0){pe(_);return}let G;try{G=await ne.handle.deleteCheckpoint($)}catch(Z){oe(_,Z);return}if(G==="deleted"){_.writeHead(204),_.end();return}G==="not_found"?j(_,$):pe(_)},kt=async(_,y,M,$)=>{let ne=J(y,M,$);if(ne==="forbidden")return;if(ne==="absent"){g(y,M);return}let G=await f(_,y,t.maxBodyBytes);if(G==="rejected")return;if(!G.ok){u(_,y,G.reason,t.maxBodyBytes);return}let Z=ua.safeParse(G.value);if(!Z.success){h(y,Z.error.issues[0]?.message??"invalid body");return}if(ne.ended){Y(y,M);return}let be=()=>{fe(y,409,_e.cwdSwitchUnsupported,wt.cwdSwitchUnsupported)};if(ne.handle.setCwd===void 0){be();return}let ue;try{ue=await ne.handle.setCwd(Z.data.cwd)}catch(ve){oe(y,ve);return}if(n.touch(M),ue.status==="changed"){Qe(y,200,{cwd:ue.cwd,from:ue.from});return}let ke=ue.detail??ue.reason;switch(ue.reason){case"turn_running":re(y);return;case"session_ended":Y(y,M);return;case"not_allowed":fe(y,400,_e.cwdNotAllowed,wt.cwdNotAllowed,{detail:ke});return;case"not_absolute":case"not_found":case"not_directory":fe(y,400,_e.cwdInvalid,wt.cwdInvalid,{reason:ue.reason,detail:ke});return;case"unsupported":be();return}},ze=async(_,y,M,$,ne)=>{let G=J(y,M,$);if(G==="forbidden")return;if(G==="absent"){g(y,M);return}let Z=G.handle.platformAudio;if(Z===void 0){fe(y,409,_e.platformUnavailable,ae.v2PlatformUnavailable);return}if(G.ended){Y(y,M);return}let be=ne==="transcriptions"?"speechToText":"textToSpeech";if(!Z.capabilities[be]){fe(y,403,_e.capabilityDisabled,ae.v2PlatformCapabilityDisabled,{bit:be});return}let ue=await f(_,y,Ao);if(ue==="rejected")return;if(!ue.ok){u(_,y,ue.reason,Ao);return}let ke=ne==="transcriptions"?ma.safeParse(ue.value):ha.safeParse(ue.value);if(!ke.success){h(y,ke.error.issues[0]?.message??"invalid body");return}let ve=new AbortController;y.once("close",()=>{y.writableEnded||ve.abort()});let Pe=ne==="transcriptions"?"asr":"tts",z=await Z.request(Pe,ke.data,ve.signal);if(n.touch(M),z.kind==="transport_error"){w(Pe,M,void 0,"transport_error",z.message),fe(y,503,_e.upstreamUnavailable,ae.v2UpstreamUnavailable,void 0,Lt(i.retryAfterMs));return}if(z.status<200||z.status>=300){let{code:de,message:Ne,detail:Ce}=Ou(z.body,z.status);if(z.status===401||z.status===403||z.status>=500){w(Pe,M,z.status,de,Ne),fe(y,503,_e.upstreamUnavailable,ae.v2UpstreamUnavailable,void 0,Lt(i.retryAfterMs));return}fe(y,z.status,de,ae.v2PlatformAudioRejected,{code:de,message:Ne},void 0,Ce);return}let B=ke.data.model??"(default)",ee=ne==="transcriptions"?uo(z.body,B):po(z.body,B);if(ee===null){fe(y,503,_e.upstreamUnavailable,ae.v2PlatformAudioUnexpected,void 0,Lt(i.retryAfterMs));return}Qe(y,200,ee)},it=async(_,y,M)=>{let $=fi(_,M),ne=i.reserveBody($);return ne.admitted?(y.once("close",()=>i.releaseBody($)),new Promise(G=>{let Z=[],be=0,ue=!1,ke=Pe=>{ue||(ue=!0,G(Pe))},ve=Pe=>{if(be+=Pe.length,be>M){Z.length=0,_.off("data",ve),_.pause(),ke("too_large");return}Z.push(Pe)};_.on("data",ve),_.on("end",()=>ke(new Uint8Array(Buffer.concat(Z)))),_.on("error",()=>ke(new Uint8Array))})):(ni(y,ne),"rejected")},It=async(_,y,M,$)=>{let ne=J(_,y,M);if(ne==="forbidden")return;if(ne==="absent"){g(_,y);return}if(ne.handle.exportCheckpoint===void 0){pe(_);return}let G;try{G=await ne.handle.exportCheckpoint($)}catch(Z){oe(_,Z);return}if(G.status==="rejected"){G.reason==="not_found"?j(_,$):pe(_);return}_.writeHead(200,{"content-type":fa,"content-length":G.bytes.byteLength,"content-disposition":`attachment; filename="${y}-${$}.tansr-checkpoint.json"`}),_.end(Buffer.from(G.bytes.buffer,G.bytes.byteOffset,G.bytes.byteLength))},Wt=async(_,y,M,$)=>{let ne=J(y,M,$);if(ne==="forbidden")return;if(ne==="absent"){g(y,M);return}if(ne.handle.importCheckpoint===void 0){pe(y);return}if(ne.ended){Y(y,M);return}let G=await it(_,y,To);if(G==="rejected")return;if(G==="too_large"){Rr(_,y,_e.payloadTooLarge,ae.v2PayloadTooLarge,{maxBytes:To});return}let Z=new URL(_.url??"/","http://local").searchParams.get("label");if(Z!==null&&Z.length>Qi){h(y,`label must be at most ${Qi} characters`);return}let be;try{be=await ne.handle.importCheckpoint(G,Z!==null&&Z!==""?{label:Z}:{})}catch(ue){oe(y,ue);return}if(n.touch(M),be.status==="imported"){Qe(y,201,be.checkpoint);return}if(be.reason==="invalid"){fe(y,400,_e.checkpointImportInvalid,wt.checkpointImportInvalid,{detail:be.detail});return}be.reason==="session_ended"?Y(y,M):pe(y)},un=(_,y,M)=>{let $=J(_,y,M);if($!=="forbidden"){if($==="absent"){g(_,y);return}$.handle.interrupt(),n.touch(y),Qe(_,202,{sessionId:y,accepted:!0})}},_n=async(_,y,M)=>{let $=J(_,y,M);if($==="forbidden")return;if($!=="absent"){n.requestClose(y),Qe(_,202,{sessionId:y,accepted:!0});return}let ne;try{ne=await e.store?.getMeta(M,y)}catch(G){x(_,G,y);return}if(ne==null){g(_,y);return}Qe(_,202,{sessionId:y,accepted:!0})},Nt=async(_,y,M,$,ne,G)=>{let Z=J(y,M,$);if(Z==="forbidden")return;if(Z==="absent"){g(y,M);return}let be=ne==="tool-results"?c:t.maxBodyBytes,ue=await f(_,y,be);if(ue==="rejected")return;if(!ue.ok){u(_,y,ue.reason,be);return}let ke,ve;if(ne==="tool-results"){ve="call";let z=Ar.safeParse(ue.value);if(!z.success){h(y,z.error.issues[0]?.message??"invalid receipt");return}ke=Z.handle.submitToolResult(G,z.data)}else if(ne==="permission"){ve="request";let z=oa.safeParse(ue.value);if(!z.success){h(y,z.error.issues[0]?.message??"invalid receipt");return}ke=Z.handle.submitPermission(G,z.data)}else{ve="request";let z=sa.safeParse(ue.value);if(!z.success){h(y,z.error.issues[0]?.message??"invalid receipt");return}ke=Z.handle.submitQuestionAnswers(G,z.data)}if(n.touch(M),ke==="accepted"){Qe(y,200,{accepted:!0});return}if(ke==="invalid"){h(y,"receipt does not match the pending request");return}let Pe=ke==="digest_mismatch"?_e.digestMismatch:`${ve}_${ke}`;fe(y,rk(ke),Pe,ae.v2ReceiptRejected,{code:Pe})},hn=async(_,y,M,$)=>{let ne;try{ne=await d(_,y)}catch(ue){if(y.destroyed||y.writableEnded)return;if(ue instanceof Rt){fe(y,503,ue.code,ue.code==="overloaded"?ae.overloaded:ae.internalError,{},Lt(i.retryAfterMs));return}ne=null}if(_.aborted||y.destroyed||y.writableEnded)return;if(ne===null){fe(y,401,_e.unauthorized,ae.unauthorized);return}let G=ne.endUserId;if(M==="/v3/sdk2/session-capabilities"){if($!=="GET"){D(y,$,M,"GET");return}if(_.headers["transfer-encoding"]!==void 0||_.headers["content-length"]!==void 0&&_.headers["content-length"]!=="0"){fe(y,400,"invalid_request",ae.v2ValidationFailed);return}let ue=new URL(_.url??"","http://serve").searchParams;if([...ue.keys()].some(ve=>ve!=="protocol")||ue.getAll("protocol").length>1){fe(y,400,"invalid_request",ae.v2ValidationFailed);return}if(ue.getAll("protocol").length!==1||ue.get("protocol")!=="sdk2-ext-v1"){fe(y,400,"protocol_version_mismatch",ae.v2ValidationFailed);return}let ke=nn({protocol:"sdk2-ext-v1",contracts:t.sessionContracts??[{contract:"sdk1",availability:"legacy-complete"}]},{maxBytes:262144});y.writeHead(200,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),y.end(ke);return}let Z=e.createSession.execution??e.createSession.transactionalExecution;if(Z!==void 0&&await fy({host:Z,req:_,res:y,pathname:M,method:$,endUserId:G,log:v,retryAfterMs:i.retryAfterMs,...t.sessionFamily===void 0?{}:{sessionFamily:t.sessionFamily},readBody:()=>f(_,y,Math.min(t.maxBodyBytes,262144),!0)}))return;if(M==="/v2/sessions"){if($==="POST"){await L(_,y,G);return}if($==="GET"){await q(_,y,G);return}D(y,$,M,"POST, GET");return}let be=Gh.exec(M);if(be!==null){let ue=ui(be[1]),ke=be[3]!==void 0?ui(be[3]):void 0;if(ue===null||ke===null){fe(y,404,_e.notFound,ae.notFound,{path:M});return}if($==="GET"&&t.filterSessionReads&&!(await t.filterSessionReads(G,[ue])).includes(ue)){g(y,ue);return}let ve=be[2],Pe=be[4];if(ve==="inputs"||ve==="input-capabilities"){let z=ve==="input-capabilities"||ke!==void 0?"GET":"POST";if(Pe!==void 0||ve==="input-capabilities"&&ke!==void 0){fe(y,404,_e.notFound,ae.notFound,{path:M});return}if($!==z){D(y,$,M,z);return}await ie(_,y,ue,G,ve,ke);return}if(ve==="audio"){if(ke!=="transcriptions"&&ke!=="speech"||Pe!==void 0){fe(y,404,_e.notFound,ae.notFound,{path:M});return}if($!=="POST"){D(y,$,M,"POST");return}await ze(_,y,ue,G,ke);return}if(ve==="cwd"){if(ke!==void 0){fe(y,404,_e.notFound,ae.notFound,{path:M});return}if($!=="POST"){D(y,$,M,"POST");return}await kt(_,y,ue,G);return}if(ve==="compact"||ve==="checkpoints"){if(ve==="compact"){if(ke!==void 0){fe(y,404,_e.notFound,ae.notFound,{path:M});return}if($!=="POST"){D(y,$,M,"POST");return}await Se(_,y,ue,G);return}if(ke===void 0){if($==="GET"){await je(y,ue,G);return}if($==="POST"){await $e(_,y,ue,G);return}D(y,$,M,"GET, POST");return}if(ke===pa&&Pe===void 0){if($!=="POST"){D(y,$,M,"POST");return}await Wt(_,y,ue,G);return}if(Pe==="restore"){if($!=="POST"){D(y,$,M,"POST");return}await Fe(_,y,ue,G,ke);return}if(Pe==="export"){if($!=="GET"){D(y,$,M,"GET");return}await It(y,ue,G,ke);return}if($!=="DELETE"){D(y,$,M,"DELETE");return}await ft(y,ue,G,ke);return}if(Pe!==void 0){fe(y,404,_e.notFound,ae.notFound,{path:M});return}if(ve===void 0){if(ke!==void 0){fe(y,404,_e.notFound,ae.notFound,{path:M});return}if($==="GET"){await ce(_,y,ue,G);return}if($==="DELETE"){await _n(y,ue,G);return}D(y,$,M,"GET, DELETE");return}if(ve==="tool-results"||ve==="permission"||ve==="questions"){if(ke===void 0){fe(y,404,_e.notFound,ae.notFound,{path:M});return}if($!=="POST"){D(y,$,M,"POST");return}await Nt(_,y,ue,G,ve,ke);return}if(ke!==void 0){fe(y,404,_e.notFound,ae.notFound,{path:M});return}if(ve==="events"||ve==="history"){if($!=="GET"){D(y,$,M,"GET");return}ve==="events"?U(_,y,ue,G):await le(_,y,ue,G);return}if($!=="POST"){D(y,$,M,"POST");return}ve==="messages"?await N(_,y,ue,G):un(y,ue,G);return}fe(y,404,_e.notFound,ae.notFound,{path:M})};return(_,y,M,$)=>{if(M!=="/v3/sdk2/session-capabilities"){if(t.sessionFamily)if(M==="/v3/sdk2/executors"||M.startsWith("/v3/sdk2/executors/"))M="/v2"+M.slice(8);else{if(M!=="/v3/sdk2/sessions"&&!M.startsWith("/v3/sdk2/sessions/")||/^\/v3\/sdk2\/sessions\/[^/]+\/binding-target$/.test(M))return!1;M="/v2/sessions"+M.slice(17)}else if(M!=="/v2"&&!M.startsWith("/v2/"))return!1}let ne=hn(_,y,M,$);return t.trackRequestWork?.(ne),ne.catch(G=>{K(y,M,$,G)}),!0}}var Hr=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}},pd=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 Hr("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 Hr("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())}}},zr=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}}},md=class{#e;#n;#r;constructor(e){this.#e=new zr(e.maxEntries),this.#n=e.ttlMs,this.#r=e.now??Date.now}has(e){let n=this.#e.peek(e);return n===void 0?!1:n<=this.#r()?(this.#e.delete(e),!1):!0}add(e){return this.#e.set(e,this.#r()+this.#n),this}get size(){return this.#e.size}stats(){return this.#e.stats()}};var tn={memorySourceUnavailable:"server.v2.warning.memory_source_unavailable",backgroundUsageStoreRequired:"server.v2.error.background_usage_store_required",executionPermissionTarget:"server.v2.execution.permission_target",executionInitializeRequired:"server.v2.execution.initialize_required",unknownCapabilitiesProfile:"cli.serve.v2.error.unknown_capabilities_profile",clientToolConflict:"cli.serve.v2.error.client_tool_conflict",mintFailed:"cli.serve.v2.error.mint_failed",platformProfileUnsupported:"server.v2.error.platform_profile_unsupported",capabilityDisabled:"cli.serve.v2.error.capability_disabled",appPlatformMismatch:"server.v2.warning.app_platform_mismatch",profileNarrowedCapabilities:"server.v2.warning.profile_narrowed_capabilities"},_y=Object.values(tn);var Py="/v1/app-tokens",ok=16*1024,sk=3e5,ak=32,dk=1024,ck=1e4,lk=.15,My=5e3,uk=6e4,fk=1e5,pk=36e5,mk=1e4,nf=new Set(["adjudicator_evidence_drifted","adjudicator_budget_exhausted","adjudicator_breaker_tripped","adjudicator_unavailable","adjudicator_posture_overridden","adjudicator_budget_unenforced"]),hk=6e5,Oy=Lo[0],By="unknown",An=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 gk(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,hk)}function qy(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 Dy(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 yk(t){let e;try{e=await t.clone().json()}catch{return}let n=qy(e);if(!Ga(n))return;let o=Dy(e)?.reason,s=typeof o=="string"&&o!==""?o:By;if(!Wa(s))return{code:n,reason:s}}function vk(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 hd(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(sk,s*1e3/2),d=Math.min(.99,Math.max(0,t.expiryJitterRatio??lk)),c=Math.max(0,t.negativeCacheInitialMs??My),l=Math.max(c,t.negativeCacheMaxMs??uk),f=t.maxCachedTokens??fk,u=_m(t.appKey),m=Qn(t.metrics),h=new pd({maxConcurrent:t.maxConcurrentMints??ak,maxQueued:t.maxQueuedMints??dk,queueTimeoutMs:t.mintQueueTimeoutMs??ck}),g=new zr(f),p=new zr(f),v=new Map,b={mints:0,hits:0,negativeHits:0,staleServed:0,failures:{rate_limited:0,unavailable:0,network:0,rejected:0,saturated:0},invalidations:{}},R=(D,J)=>We(tn.mintFailed,{status:D,code:J}),w=D=>{let J=g.get(D);if(J!==void 0){if(J.expiresAtMs<=i()){g.delete(D);return}return J}},x=(D,J)=>{if(b.failures[J.kind]+=1,J.kind==="saturated")return;m.tokenMintFailures.inc();let S=p.peek(D),k=S===void 0?c:Math.min(l,S.backoffMs*2),A=Math.max(k,Math.min(J.retryAfterMs??0,l));p.set(D,{until:i()+A,backoffMs:k,kind:J.kind,status:J.status,message:J.message,code:J.code,detail:J.detail})},T=async D=>{b.mints+=1;let J=JSON.stringify({endUserId:D,ttlSeconds:s}),S;try{S=await n(`${e}${Py}`,{method:"POST",headers:{"content-type":"application/json",[as]:t.appId,[ds]:t.appKey,...Pm({signingKey:u,method:"POST",pathWithQuery:Py,body:J,now:i})},body:J})}catch(Q){throw new An("network",R("network",Q instanceof Error?Q.message:String(Q)),{cause:Q})}let k=await S.json().catch(()=>null);if(!S.ok){let Q=qy(k),se=Dy(k),O=gk(S.headers.get("retry-after"),i()),I=S.status===429?"rate_limited":S.status>=500?"unavailable":"rejected";throw new An(I,R(String(S.status),Q),{status:S.status,...O!==void 0?{retryAfterMs:O}:{},code:Q,...se!==void 0?{detail:se}:{}})}let A=typeof k=="object"&&k!==null?k:{};if(typeof A.token!="string"||A.token==="")throw new An("unavailable",R(String(S.status),"malformed_response"),{status:S.status});let C=typeof A.expiresAt=="string"&&!Number.isNaN(Date.parse(A.expiresAt))?Date.parse(A.expiresAt):i()+s*1e3,F=Math.max(0,C-i()),L=i()+F*(1-o()*d);return g.set(D,{token:A.token,expiresAtMs:L}),p.delete(D),A.token},P=async D=>{let J;try{J=await h.acquire()}catch(S){let k=S instanceof Hr?S.reason:"queue_full",A=new An("saturated",R("saturated",k),{retryAfterMs:My});throw x(D,A),A}try{let S=w(D);return S!==void 0&&S.expiresAtMs-i()>a?S.token:await T(D)}catch(S){let k=S instanceof An?S:new An("network",R("network",S instanceof Error?S.message:String(S)),{cause:S});x(D,k);let A=w(D);if(A!==void 0)return b.staleServed+=1,A.token;throw k}finally{J()}},W=D=>{let J=w(D);if(J!==void 0&&J.expiresAtMs-i()>a)return b.hits+=1,Promise.resolve(J.token);let S=p.peek(D);if(S!==void 0&&S.until>i())return b.negativeHits+=1,J!==void 0?(b.staleServed+=1,Promise.resolve(J.token)):Promise.reject(new An(S.kind,S.message,{...S.status!==void 0?{status:S.status}:{},retryAfterMs:Math.max(1,S.until-i()),...S.code!==void 0?{code:S.code}:{},...S.detail!==void 0?{detail:S.detail}:{}}));let k=v.get(D);if(k!==void 0)return k;let A=P(D).finally(()=>v.delete(D));return v.set(D,A),A};return{tokenFor:W,invalidate:(D,J={})=>{let S=g.peek(D);if(S===void 0||J.token!==void 0&&S.token!==J.token)return!1;g.delete(D);let k=J.reason??By;return b.invalidations[k]=(b.invalidations[k]??0)+1,!0},async warm(D){let J={minted:0,cached:0,failed:0},S=await Promise.allSettled([...D].map(async k=>{let A=w(k),C=A!==void 0&&A.expiresAtMs-i()>a;return await W(k),C}));for(let k of S)k.status==="rejected"?J.failed+=1:k.value?J.cached+=1:J.minted+=1;return J},stats(){let D=h.stats();return{inflight:D.active,queued:D.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 bk(t){if(t===void 0)return n=>{console.warn(`[tansr-serve] platform warning ${n.code} (endUser=${n.endUserId}): ${n.message}`)};let e=$n(t);return n=>{e("warn",rt.platformWarning,{endUserId:n.endUserId,sessionId:n.sessionId,code:n.code,message:n.message})}}function Sk(t){if(t.bundleCache!==void 0)return t.bundleCache;let e=t.bundleCacheTtlMs??_i;if(!(e<=0))return rr({ttlMs:e,...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{},...t.now!==void 0?{now:t.now}:{}})}function jy(t){return Uy(t)}function Ny(t,e){return Uy(t,e)}function Uy(t,e){let n=new md({ttlMs:pk,maxEntries:mk,...t.now!==void 0?{now:t.now}:{}}),i=bk(t.logger),o=t.onPlatformWarning??(c=>{let l=`${c.endUserId}\0${c.code}`;n.has(l)||(n.add(l),i(c))}),s=Sk(t),a=Qn(t.metrics),d=t.fetchImpl??fetch;return async c=>{let l=await t.minter.tokenFor(c.endUserId),f=c.platformSessionId??zi(),u=(async(k,A)=>{let C=await t.minter.tokenFor(c.endUserId),F=O=>{let I=new Headers(A?.headers??(k instanceof Request?k.headers:void 0));return I.set(Vn,O),d(k,{...A,headers:I})},L=await F(C);if(L.status!==401)return L;let Q=await yk(L);if(Q===void 0||(a.tokenInvalidations.inc({reason:Q.reason}),t.minter.invalidate===void 0)||(t.minter.invalidate(c.endUserId,{token:C,reason:Q.reason}),!vk(k,A)))return L;let se;try{se=await t.minter.tokenFor(c.endUserId)}catch{return L}return se===C?L:F(se)}),m=e?.gatewayCache?.({endUserId:c.endUserId,sessionId:c.sessionId}),h=await Fa({token:l,baseUrl:t.apiBaseUrl,...c.model!==void 0?{model:c.model}:{},fetchImpl:u,sessionId:()=>f,onSessionArchived:k=>{if(k!==void 0&&k!==f)return;s?.invalidate();let A=f,C=m===void 0?void 0:e?.archivedRuntime?.({endUserId:c.endUserId,sessionId:c.sessionId,previous:A});if(m!==void 0&&C===void 0)throw new Et("session_archived",void 0,410);f=c.onSessionArchived?.(A,C)??C??zi();let F={code:"platform_session_archived",message:`platform session "${A}" was archived by the platform (410 session_archived); a new platform session "${f}" starts with the next exchange (no retry against the archived id).`};o({endUserId:c.endUserId,sessionId:c.sessionId,...F}),c.onWarning?.(F)},...s!==void 0?{bundleCache:s}:{},...t.appId!==void 0?{appId:t.appId}:{},onWarn:k=>{o({endUserId:c.endUserId,sessionId:c.sessionId,code:k.code,message:k.message}),c.onWarning?.({code:k.code,message:k.message})}},m===void 0?{}:{gatewayCache:m}),g=Na(h),p=La({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:k=>e.confirmCacheConfiguration?.({endUserId:c.endUserId,sessionId:c.sessionId},k),refreshConfiguration:k=>e.refreshCacheConfiguration({endUserId:c.endUserId,sessionId:c.sessionId},k)}:void 0),v,b,R=async(k,A)=>{k.throwIfAborted();let C=(L,Q)=>u(L,{...Q,cache:"no-cache",headers:{...Object.fromEntries(new Headers(Q?.headers)),"cache-control":"no-cache"},signal:Q?.signal?AbortSignal.any([Q.signal,k]):k}),F=await oi(t.apiBaseUrl.replace(/\/+$/,""),l,C,A,void 0,!0);return k.throwIfAborted(),F},w=async k=>{let A=await R(k,b);if(A.bundle!==null&&(v=A.bundle.capabilities),b=A.etag??b,v===void 0)throw new Error("Application capabilities are unconfirmed");return v},x,T,P=async k=>{let A=await R(k,T);if(A.bundle!==null){let C=A.bundle.models.map(({handle:Q,displayName:se,manufacturer:O,family:I,adapterDiagnostics:q})=>({handle:Q,displayName:se,manufacturer:O,family:I,...q===void 0?{}:{adapterDiagnostics:structuredClone(q)}})),F=new Set(C.map(Q=>Q.handle)),L=Object.fromEntries(Object.entries(A.bundle.aliases).flatMap(([Q,se])=>{let O=F.has(se)?se:se.startsWith("tansr/")?se.slice(6):void 0;return O!==void 0&&F.has(O)?[[Q,O]]:[]}));x={models:C,aliases:L,capabilities:A.bundle.capabilities},T=A.etag}else T=A.etag??T;if(x===void 0)throw new Error("Platform catalog is unconfirmed");return structuredClone(x)},W=async k=>{k.throwIfAborted();let A=await u(`${t.apiBaseUrl.replace(/\/+$/,"")}/v1/my-usage?window=1d`,{method:"GET",headers:{accept:"application/json","cache-control":"no-cache"},cache:"no-cache",signal:k});if(k.throwIfAborted(),!A.ok)throw A.body?.cancel().catch(()=>{}),new Error("Platform usage is unavailable");let{bytes:C,truncated:F}=await nm(A,ok,k);if(F)throw new Error("Platform usage response exceeded the size limit");let L;try{L=JSON.parse(new TextDecoder().decode(C))}catch{throw new Error("Platform usage is unconfirmed")}let Q=dl.safeParse(L);if(k.throwIfAborted(),!Q.success||Q.data.endUserId!==c.endUserId||Q.data.window!=="1d")throw new Error("Platform usage is unconfirmed");return Q.data},K;h.pricingUpdates.length>0&&(K=Jc(),K.refreshPricing(h.pricingUpdates,"refreshed"));let D=h.adjudicator,J=k=>{o({endUserId:c.endUserId,sessionId:c.sessionId,...k}),!nf.has(k.code)&&c.onWarning?.(k)},S=zp(h.contextScheme,k=>o({endUserId:c.endUserId,sessionId:c.sessionId,code:Hp,message:`${k.reason}: ${k.detail}`}));return(k,A)=>{let C=qr(h.registry,k,A);return{client:C.client,model:C.model,...C.contextWindowTokens!==void 0?{contextWindowTokens:C.contextWindowTokens}:{},...C.maxOutputTokens!==void 0?{maxOutputTokens:C.maxOutputTokens}:{},...K!==void 0?{pricing:K}:{},...S!==void 0?{compactionManagerOptions:S}:{},...h.governance.sessionRetentionDays!==void 0?{sessionRetentionDays:h.governance.sessionRetentionDays}:{},resolveSubagentModel:(F,L)=>{try{let Q=h.registry.resolveAlias(F);return{provider:Q.providerId,model:Q.modelName}}catch{return L}},capabilities:h.capabilities,...h.systemPrompt!==void 0?{systemPrompt:h.systemPrompt}:{},...h.systemPromptPolicy!==void 0?{systemPromptPolicy:h.systemPromptPolicy}:{},refreshApplicationPrompt:p,refreshApplicationCapabilities:w,readPlatformCatalog:P,readPlatformUsage:W,platform:h.platform,platformTools:{baseUrl:t.apiBaseUrl,fetchImpl:u,platformModels:h.platformModels},onAdjudicationWarning:J,...D!==null?{assembleAdjudicator:F=>fl({registry:h.registry,mainModel:C.model,adjudicator:D,app:{...h.app,endUser:c.endUserId},posture:F.posture,...F.postureExplicit!==void 0?{postureExplicit:F.postureExplicit}:{},pricing:h.pricingUpdates,...F.callBudget!==void 0?{callBudget:F.callBudget}:{},onWarn:J})}:{}}}}}function Gr(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 gd(t){return async e=>{try{return await t(e)}catch(n){throw rf(n)}}}var wk=new Set(["plan_concurrency_exceeded","plan_end_users_exceeded"]),kk=new Set(["plan_required","plan_tier_insufficient"]),xk=3e4;function rf(t){if(!(t instanceof An))return t;let e=t.retryAfterMs!==void 0?{retryAfterMs:t.retryAfterMs}:{};if(t.code!==void 0&&wk.has(t.code))return new Ye("plan_limited",t.message,{retryAfterMs:t.retryAfterMs??xk,params:{code:t.code},...t.detail!==void 0?{detail:t.detail}:{}});if(t.code!==void 0&&kk.has(t.code))return new Ye("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 Ye("upstream_unavailable",t.message,e);case"saturated":return new Ye("overloaded",t.message,e);case"rejected":return t}}import{randomUUID as Rk}from"node:crypto";function Fy(t,e,n){if(t.destroyed||t.writableEnded)return;let i=Jd(n);t.writeHead(e,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":i.length}),t.end(i)}async function Ly(t){if(t.headers["content-type"]?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new Et("invalid_request",void 0,400);let e=[],n=0;for await(let i of t){let o=Buffer.isBuffer(i)?i:Buffer.from(i);if(n+=o.length,n>65536)throw new Et("payload_too_large",void 0,413);e.push(o)}try{return Yd(Buffer.concat(e))}catch{throw new Et("invalid_request",void 0,400)}}function of(t,e,n=[]){let i=t.searchParams;for(let o of i.keys())if(![...e,...n].includes(o)||i.getAll(o).length!==1)throw new Et("invalid_request",void 0,400);if(e.some(o=>!i.has(o))||i.get("protocol")!==il)throw new Et("invalid_request",void 0,400);return i}function Hy(t){let e=0;return(n,i,o,s)=>{if(!o.startsWith("/v3/sdk2/cache/"))return!1;let a=0,d=!1,c=(async()=>{if(e>=128||t.admission.overloaded())throw new Et("capacity_exceeded",void 0,503);e++,d=!0;let l;try{l=await t.authenticate(n,i)}catch(v){if(v instanceof Rt)throw new Et("capacity_exceeded",void 0,503,"same-request");l=null}if(n.aborted||i.destroyed||i.writableEnded)return;if(!l||!l.endUserId)throw new Et("unauthorized",void 0,401);if(!(await t.admission.rateLimit(n,l.endUserId)).admitted)throw new Et("capacity_exceeded",void 0,429);if(s==="POST"){let v=fi(n,65536);if(!t.admission.reserveBody(v).admitted)throw new Et("capacity_exceeded",void 0,503);a=v}let u=l.endUserId,m=new URL(n.url??"/","http://serve.invalid"),h=o.slice(14),g,p=/^\/core\/v1\/bindings\/([A-Za-z0-9][A-Za-z0-9._~-]{0,127})\/diagnostics$/.exec(h);if(s==="GET"&&p){let v=m.searchParams;if([...v.keys()].some(R=>!["protocol","limit","after"].includes(R)||v.getAll(R).length!==1)||v.get("protocol")!=="sdk2-cache-core-v1")throw new Et("invalid_request",void 0,400);let b=v.get("limit")??"100";if(!/^[1-9][0-9]{0,2}$/.test(b)||Number(b)>100)throw new Et("invalid_request",void 0,400);g=await t.link.coreDiagnostics(u,p[1],v.get("after"),Number(b))}else if(s==="GET"&&h==="/capabilities"){if(m.search)throw new Et("invalid_request",void 0,400);g=await t.link.capabilities(u)}else if(s==="POST"&&h==="/bindings"){if(m.search)throw new Et("invalid_request",void 0,400);g=await t.link.execute(u,"open",await Ly(n))}else if(s==="GET"&&h==="/operations"){let v=of(m,["protocol","operation","operationEpoch","requestId"],["bindingId"]),b=v.get("operation");if(b!=="open"&&b!=="renew"&&b!=="rebind"&&b!=="rotate"&&b!=="close")throw new Et("invalid_request",void 0,400);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 Et("mapping_unavailable",void 0,404);let b=v[1],R=v[2];if(s==="GET"&&R===void 0)of(m,["protocol"]),g=await t.link.read(u,b);else if(s==="GET"&&R==="diagnostics"){let w=of(m,["protocol"],["after","limit"]),x=w.get("limit")??"100";if(!/^[1-9][0-9]{0,2}$/.test(x)||Number(x)>100)throw new Et("invalid_request",void 0,400);g=await t.link.diagnostics(u,b,w.get("after"),Number(x))}else if(s==="POST"&&(R==="renew"||R==="rebind"||R==="rotate"||R==="close")){if(m.search)throw new Et("invalid_request",void 0,400);let w=await Ly(n);if(!w||typeof w!="object"||w.bindingId!==b)throw new Et("invalid_request",void 0,400);g=await t.link.execute(u,R,w)}else throw new Et("invalid_request",void 0,400)}Fy(i,200,g)})().catch(l=>{if(i.destroyed||i.writableEnded)return;let f=l instanceof Et,u=f?l.status??503:l instanceof Gd?400:503,m=f?l.code:l instanceof Gd?"invalid_request":"result_unknown",h={protocol:il,requestId:Rk(),code:m,status:u,retryAction:f?l.retryAction:m==="result_unknown"?"query-status":"none",fallback:"none",message:m},g=Mm.safeParse(h);(u===429||u===503)&&i.setHeader("retry-after","5"),Fy(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 Ik}from"node:util";var Tk=new Set(["receive","confirm","pending","head","coverage","identity","operation","records","body-chunk","sync-page","retention","retention-page","apply-retention","reconcile"]),Ak=new Set(["head","coverage","identity","records","body-chunk","sync-page","retention","retention-page"]),Ek=new Set(["invalid_input","identity_mismatch","integrity_mismatch","capacity_exceeded","pending_ack","receipt_mismatch","context_changed","reentrant","closed","storage_error","reconciliation_required"]),sf=class extends Error{constructor(n){super(n);this.code=n}code};function vt(t,e="invalid_input"){if(!t)throw new sf(e)}function af(t,e){let n=0,i=0,o=new Set,s=d=>(i+=Buffer.byteLength(d),vt(i<=e,"capacity_exceeded"),d),a=(d,c)=>{if(vt(c<=32&&++n<=1e5),d===null||typeof d=="boolean")return s(String(d));if(typeof d=="number")return vt(Number.isSafeInteger(d)&&d>=0&&!Object.is(d,-0)),s(String(d));if(typeof d=="string")return vt(Buffer.from(d).toString("utf8")===d),s(JSON.stringify(d));vt(d&&typeof d=="object"&&!Ik.isProxy(d)&&!o.has(d)),o.add(d);try{let l=Object.getOwnPropertyDescriptors(d);if(Array.isArray(d)){let m=l.length?.value;vt(Number.isSafeInteger(m)&&m<=1e5&&Reflect.ownKeys(l).length===m+1);let h=[s("[")];for(let g=0;g<m;g++){let p=l[g];vt(p&&Object.hasOwn(p,"value")&&p.enumerable),g&&h.push(s(",")),h.push(a(p.value,c+1))}return h.push(s("]")),h.join("")}vt(Object.getPrototypeOf(d)===Object.prototype||Object.getPrototypeOf(d)===null);let f=Reflect.ownKeys(l);vt(f.every(m=>typeof m=="string"&&/^[\x21-\x7e]+$/.test(m)));let u=[s("{")];for(let[m,h]of f.sort().entries()){let g=l[h];vt(Object.hasOwn(g,"value")&&g.enumerable),m&&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 Ck(t,e){let n=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t),i=JSON.parse(n);return vt(af(i,e).equals(t)),i}function yd(t,e){return JSON.parse(af(t,e).toString("utf8"))}function zy(t,e,n){if(t.destroyed||t.writableEnded)return;let i=af(n,1638400);t.writeHead(e,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":i.length}),t.end(i)}function Gy(t){vt(/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(t.host.applicationScopeId));let e=0;return(n,i)=>{let o=n.url??"";if(!o.startsWith("/v3/sdk2/archive-sync/"))return!1;let s=!1,a=!1,d=0,c=null,l="unknown",f=(async()=>{vt(e<32&&!t.admission.overloaded(),"capacity_exceeded"),e++,s=!0,vt(n.method==="POST"&&/^\/v3\/sdk2\/archive-sync\/[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(o)),vt(n.headers["content-type"]?.split(";")[0]==="application/json");let u=o.slice(22),m=await t.authenticate(n,i);vt(m?.endUserId,"context_changed"),vt((await t.admission.rateLimit(n,m.endUserId)).admitted,"capacity_exceeded");let h=t.host.resolve(m.endUserId,u),g=h?null:t.host.resolveReadOnly?.(m.endUserId,u),p=h??g?.binding;vt(p,"identity_mismatch"),c=yd(p.identity,65536);let v=g?yd(g.grant,65536):null;v&&(Mn(v,["actor","owner","grantRevision"]),Mn(v.actor,["applicationScopeId","endUserId","authorizationRevision"]),Mn(v.owner,["scope","bindingId","target","sourceId","sourceGeneration"]),Mn(v.owner.target,["sessionId","generations"]),Mn(v.owner.target.generations,["historyEpoch","deletionGeneration","projectionRevision"]),vt(v.actor.endUserId===m.endUserId&&v.actor.applicationScopeId===t.host.applicationScopeId&&/^[0-9]{1,19}$/.test(v.actor.authorizationRevision)&&/^[0-9]{1,19}$/.test(v.grantRevision)&&me(v.owner)===me(c),"identity_mismatch")),vt(p.identity.bindingId===u&&(v!==null||p.identity.scope.endUserId===m.endUserId)&&p.identity.scope.applicationScopeId===t.host.applicationScopeId,"identity_mismatch"),vt(Number.isSafeInteger(p.maxRequestBytes)&&p.maxRequestBytes>0&&p.maxRequestBytes<=94371840),vt(Number.isSafeInteger(p.maxResponseBytes)&&p.maxResponseBytes>0&&p.maxResponseBytes<=1572864),d=p.maxRequestBytes+65536,vt(t.admission.reserveBody(d).admitted,"capacity_exceeded"),a=!0;let b=async()=>{let T=await t.authenticate(n,i),P=v?t.host.resolveReadOnly?.(m.endUserId,u):null;vt(!n.aborted&&!i.destroyed&&T?.endUserId===m.endUserId&&(v?P?.binding===p&&me(yd(P.grant,65536))===me(v):t.host.resolve(m.endUserId,u)===p)&&me(p.identity)===me(c),"context_changed")};await b();let R=await ki(n,d,T=>Ck(T,d));vt(R.ok,R.ok===!1&&R.reason==="too_large"?"capacity_exceeded":"invalid_input");let w=Mn(R.value,["format","identity","method","value"]);vt(w.format==="archive-sync-v1"&&me(w.identity)===me(c),"identity_mismatch"),vt(typeof w.method=="string"&&Tk.has(w.method)),l=w.method,vt(!v||Ak.has(l),"context_changed"),await b();let x=await p.dispatch(l,w.value);await b(),zy(i,200,{format:"archive-sync-v1",identity:c,method:l,value:yd(x,p.maxResponseBytes)})})().catch(u=>{let m=u&&typeof u=="object"?Object.getOwnPropertyDescriptor(u,"code"):void 0,h=typeof m?.value=="string"&&Ek.has(m.value)?m.value:"storage_error";zy(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 Nx}from"node:crypto";import{createHash as _k}from"node:crypto";import{types as Pk}from"node:util";var pB=Object.freeze(["session","execution","archive","archive-sync","cache","terminal","terminal-observation","terminal-profile"]),Mk=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"}),Ae=(t,e,n,i,o=null)=>Object.freeze({name:t,domain:e,kind:n,lifecycle:i,requires:o}),nt=Mk,Ok=Object.freeze([Ae("session.create","session","write","independent"),Ae("session.list","session","read","independent"),Ae("session.get","session","read","session"),Ae("session.close","session","write","session"),Ae("session.message.send","session","write","session"),Ae("session.events.observe","session","stream","session"),Ae("session.interrupt","session","write","session"),Ae("session.history.read","session","read","session"),Ae("session.tool.result","session","write","session"),Ae("session.permission.decide","session","write","session"),Ae("session.question.answer","session","write","session"),Ae("session.compact","session","write","session"),Ae("session.checkpoint.list","session","read","session"),Ae("session.checkpoint.create","session","write","session"),Ae("session.checkpoint.import","session","write","session"),Ae("session.checkpoint.restore","session","write","session"),Ae("session.checkpoint.export","session","read","session"),Ae("session.checkpoint.delete","session","write","session"),Ae("session.cwd.set","session","write","session"),Ae("session.audio.transcribe","session","write","session",nt.audioTranscribe),Ae("session.audio.speak","session","write","session",nt.audioSpeak),Ae("session.input.capabilities","session","read","session"),Ae("session.input.submit","session","write","session",nt.inputAccepts),Ae("session.input.status","session","read","session"),Ae("approval.credential.submit","session","write","independent"),Ae("execution.initialize","execution","write","session"),Ae("execution.capabilities","execution","read","session"),Ae("execution.boundary","execution","read","session"),Ae("execution.binding.create","execution","write","session",nt.executionBoundDevice),Ae("execution.status","execution","read","session"),Ae("executor.register","execution","write","independent"),Ae("executor.heartbeat","execution","write","independent"),Ae("executor.operations.poll","execution","read","independent"),Ae("executor.receipt.submit","execution","write","independent"),Ae("archive.capabilities","archive","read","independent"),Ae("archive.binding.target","archive","read","independent"),Ae("archive.binding.create","archive","write","independent"),Ae("archive.binding.get","archive","read","independent"),Ae("archive.binding.close","archive","write","independent"),Ae("archive.status","archive","read","independent",nt.archiveTransfer),Ae("archive.events.observe","archive","stream","independent"),Ae("archive.records.read","archive","read","independent",nt.archiveTransfer),Ae("archive.artifact.read","archive","read","independent",nt.archiveTransfer),Ae("archive.ack.commit","archive","write","independent",nt.archiveTransfer),Ae("archive.ack.rebase","archive","write","independent",nt.archiveTransfer),Ae("archive.operation.query","archive","read","independent"),Ae("archive.sync","archive-sync","write","independent"),Ae("material.response.submit","archive","write","independent",nt.archiveMaterials),Ae("material.status","archive","read","independent",nt.archiveMaterials),Ae("material.upload.status","archive","read","independent",nt.archiveMaterials),Ae("material.upload.chunk","archive","write","independent",nt.archiveMaterials),Ae("cache.capabilities","cache","read","independent"),Ae("cache.binding.open","cache","write","independent",nt.cacheFeature),Ae("cache.binding.get","cache","read","independent",nt.cacheFeature),Ae("cache.binding.renew","cache","write","independent",nt.cacheFeature),Ae("cache.binding.rebind","cache","write","independent",nt.cacheFeature),Ae("cache.binding.rotate","cache","write","independent",nt.cacheFeature),Ae("cache.binding.close","cache","write","independent",nt.cacheFeature),Ae("cache.operation.query","cache","read","independent",nt.cacheFeature),Ae("cache.diagnostics","cache","read","independent",nt.cacheFeature),Ae("cache.core.diagnostics","cache","read","independent",nt.cacheFeature),Ae("terminal.capabilities","terminal","read","independent"),Ae("terminal.binding.create","terminal","write","session"),Ae("terminal.executor.events.observe","terminal","stream","independent",nt.terminalStream),Ae("terminal.output.batch","terminal","write","session",nt.terminalStream),Ae("terminal.execution.state","terminal","read","session",nt.terminalStream),Ae("terminal.output.observe","terminal","stream","session",nt.terminalStream),Ae("terminal.output.status","terminal","read","session",nt.terminalStream),Ae("terminal.configuration.read","terminal","read","session",nt.terminalConfiguration),Ae("terminal.configuration.commit","terminal","write","session",nt.terminalConfiguration),Ae("terminal.memory.read","terminal","read","session",nt.terminalMemory),Ae("terminal.memory.command","terminal","write","session",nt.terminalMemory),Ae("terminal.memory.receipt","terminal","read","session",nt.terminalMemory),Ae("terminal.observation.resources","terminal-observation","read","session"),Ae("terminal.observation.correlations","terminal-observation","read","session"),Ae("terminal.profile.catalog","terminal-profile","read","session"),Ae("terminal.profile.usage","terminal-profile","read","session")]),Bk="tansr.unified.closure.v1";var qk=t=>t!==null&&(t.state==="ended"||t.state==="closing");function Dk(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 jk(t){let e=new Set,n=new Set;t.input!==null&&t.input.accepts.some(s=>Gk.includes(s))&&n.add(nt.inputAccepts),t.audio?.speechToText===!0&&n.add(nt.audioTranscribe),t.audio?.textToSpeech===!0&&n.add(nt.audioSpeak);let i=new Set;t.execution?.effectiveTools.some(s=>s.executionKind==="bound-device"&&s.available)===!0&&i.add(nt.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 Nk(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 Uk(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"&&qk(e.session)||t.domain==="archive"&&e.archive!==null&&e.archive.epochId===null)?"disabled":"enabled"}var Fk=262144,Lk=t=>new Uint8Array(_k("sha256").update(t).digest());function Hk(t){let e=us({authorizationRevision:t.authorizationRevision,domains:t.domains,operations:t.operations},{maxBytes:Fk,isProxy:Pk.isProxy});return np(tp(Bk,e,Lk))}function Wy(t){let e=Dk(t),n=jk(t),i=Nk(t),o={};for(let a of Ok)o[a.name]=Uk(a,t,e,n);let s=t.authorizationRevision;return{contract:yn,closureId:Hk({authorizationRevision:s,domains:i,operations:o}),authorizationRevision:s,domains:i,operations:o}}function Vy(t,e){return t===void 0||t===e.closureId?{ok:!0}:{ok:!1,code:"closure_stale",status:412,retryAction:"rediscover",closureId:e.closureId}}function zk(t){return t.supported?t.installed?t.authorization!=="allowed"||t.device==="unavailable"||t.device==="unconfirmed"?"unconfirmed":"installed":"supported":"unconfirmed"}function $y(t){let e={};for(let n of t)e[n.feature]=zk(n);return e}var Gk=["text","textBlocks","image"];function Ky(t){let e=["text","textBlocks","image"];return{version:t.version,accepts:e.filter(n=>t[n]===!0)}}import{randomUUID as Vk}from"node:crypto";var vd={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 bd={"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"}},Qy={"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 Wk=Object.keys(bd);function Jy(t){return Object.hasOwn(bd,t)}function wd(t,e){let n=bd[t];return Object.hasOwn(n,e)?n[e]??null:null}function Yy(t){let e=new Set;for(let n of Wk){let i=wd(n,t);i!==null&&e.add(i)}return e.size===1?[...e][0]??null:null}function Sd(t,e){let n=Qy[t];return Object.hasOwn(n,e)?n[e]??null:null}function df(t,e,n){let i=n??null,o=wd(t,e);if(o===null)return{code:"internal_error",status:500,retryAction:(i===null?null:Sd(t,i))??"none",domainCode:e,domainRetryAction:i};let s=vd[o],a=i===null?null:Sd(t,i);return{code:o,status:s.status,retryAction:a??s.retryAction,domainCode:e,domainRetryAction:i}}function $k(t){let e=pi[t];return Jy(e)?e:t==="terminal-observation"||t==="terminal-profile"?"terminal-services-v1":null}var Kk={invalid_request:[400,422],conflict:[409,412],gap:[409,410],capability_unavailable:[404,403],capacity_exceeded:[429,503]};function Xy(t,e,n){let i=Kk[t];return i!==void 0&&i.includes(n)?n:e}function Qk(t,e,n,i){if(wd(t,e)!==null){let a=df(t,e,n);return{code:a.code,status:Xy(a.code,a.status,i),retryAction:a.retryAction}}let o=Yy(e);if(o!==null){let a=vd[o],d=n===null?null:Sd(t,n);return{code:o,status:Xy(o,a.status,i),retryAction:d??a.retryAction}}let s=df(t,e,n);return{code:s.code,status:i,retryAction:s.retryAction}}function kd(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Jk(t){if(!kd(t)||t.contract===yn)return null;let e=t.error;return kd(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:kd(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 Xk(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:gu(o)??t;return{path:i,text:o=>o.replace(Yk,s=>i(s))}}var Zk=new Set(["domainCode","domainStatus","domainRetryAction","fallback","retryAfterMs"]);function ex(t){let e=Jk(t.body);if(e===null)return null;let n=Xk(t.apiPathname,t.legacyPathname),i=Qk(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))Zk.has(s)||(o[s]=s==="path"&&typeof a=="string"?n.path(a):a);return{contract:yn,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 tx=/^application\/json(?:\s*;.*)?$/i,Zy=1024*1024;function nx(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 ix(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:nx(i)}}function ev(t){if(t!==void 0)return Array.isArray(t)?t.length>0?String(t[0]):void 0:String(t)}function rx(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 tv(t,e,n){let i=$k(n.domain);if(i===null)return;let o=(t.url??"").split("?",1)[0],s=n.legacyPathname,a=e.writeHead,d=e.write,c=e.end,l="idle",f=null,u=[],m=0,h=w=>{if(w.status<400)return!1;let T=ev(w.headers["content-type"])??ev(e.getHeader("content-type"));return T!==void 0&&tx.test(T)},g=(w,x,T)=>{w.statusMessage===void 0?a.call(e,x,T):a.call(e,x,w.statusMessage,T)},p=(w,x)=>{let T=f;l="passthrough";let P=Buffer.concat(u);u.length=0,!e.destroyed&&(g(T,T.status,T.headers),w?c.call(e,P,x):d.call(e,P,x))},v=(w,x)=>{let T=f,P;try{P=JSON.parse(Buffer.concat(u).toString("utf8"))}catch{return w?(p(!0,x),!0):!1}let W=kd(P)?ex({family:i,status:T.status,body:P,apiPathname:o,legacyPathname:s,traceId:Ii(t)?.requestId??Vk()}):null;if(W===null)return w?(p(!0,x),!0):!1;l="passthrough",u.length=0;let K=Buffer.from(JSON.stringify(W),"utf8"),D={...T.headers,"content-length":K.length};return W.status===401&&D["www-authenticate"]===void 0&&e.getHeader("www-authenticate")===void 0&&(D["www-authenticate"]="Bearer"),e.destroyed||(g(T,W.status,D),w?c.call(e,K,x):d.call(e,K,x)),!0},b=(w,x)=>{let T=rx(w,x);T!==null&&(u.push(T),m+=T.length)},R=()=>{let w={status:e.statusCode,statusMessage:void 0,headers:{}};h(w)?(l="buffering",f=w):l="passthrough"};e.writeHead=function(...x){if(l==="passthrough")return a.apply(this,x);let T=ix(x);return l==="buffering"?(f=T,this):h(T)?(l="buffering",f=T,this):(l="passthrough",a.apply(this,x))},e.write=function(x,T,P){if(l==="idle"&&R(),l!=="buffering")return d.call(this,x,T,P);let W=typeof T=="function"?T:P;return b(x,T),m>Zy?(p(!1,W),!0):(!v(!1,W)&&typeof W=="function"&&process.nextTick(W),!0)},e.end=function(x,T,P){if(l==="idle"&&R(),l!=="buffering")return c.call(this,x,T,P);let W=[x,T,P].find(K=>typeof K=="function");return typeof x!="function"&&b(x,T),m>Zy?p(!0,W):v(!0,W),this}}var Qo="tansr-event-envelope",Id="unified-v1",IB=Object.freeze(["contract","eventId","domain","type","cursorSet","terminalStatus","raw"]);function ox(t){let e=t.headers[Qo],n=Array.isArray(e)?e.length===1?e[0]:void 0:e;return e===void 0?"absent":n===Id?"unified-v1":"invalid"}var nv=Object.freeze({eventCursor:null,archiveCoverage:null,outputWatermark:null,materialConsumed:null,ackReceipt:null});function Ko(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xd(t){return typeof t=="string"?t:null}function sx(t,e,n,i){let o=i===null?nv:{...nv,eventCursor:i},s=null,a=Ko(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&&Ko(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:xd(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"&&Ko(n.block)?o={...o,outputWatermark:xd(n.block.seq)}:e==="output.status"&&Ko(n.status)&&n.status.state==="complete"&&(s="completed");break;default:break}return{cursorSet:o,terminalStatus:s}}var Rd=10,rv=13;function ax(t){let e=[],n=0;for(let i=0;i<t.length;i+=1){let o=t.charCodeAt(i);if(o===Rd)e.push({text:t.slice(n,i),eol:`
|
|
24
|
-
`}),n=i+1;else if(o===rv){let s=t.charCodeAt(i+1)===Rd;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 dx(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 cx(t,e){let n=ax(t.toString("utf8")),i,o,s=new Set,a=[];for(let v=0;v<n.length;v+=1){let b=n[v];if(b.text==="")continue;let R=dx(b.text);R!=="comment"&&(R.field==="data"?(s.add(v),a.push(R.value)):R.field==="event"?i=R.value:R.field==="id"&&!R.value.includes("\0")&&(o=R.value))}if(s.size===0)return t;let d=a.join(`
|
|
26
|
-
`),c;try{c=JSON.parse(d)}catch{return t}if(!Ko(c))return t;let l=i??xd(c.type)??xd(c.eventType),f=o??null,u=sx(e,l,c,f),m=`{"contract":${JSON.stringify(yn)},"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,p="";for(let v=0;v<n.length;v+=1){let b=n[v];if(v===h)for(let R of m.split(`
|
|
28
|
-
`))p+=`data: ${R}${g}`;else s.has(v)||(p+=b.text+b.eol)}return Buffer.from(p,"utf8")}var lx=1<<20,Wr=Buffer.alloc(0),cf=class{#e;#n;#r=Wr;#s=0;#t=0;#o=!1;constructor(e){this.#e=e.domain,this.#n=e.maxCarryBytes??lx}get carryBytes(){return this.#r.length}push(e){if(e.length===0)return Wr;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===Rd)l=a+1;else if(c===rv){if(a+1>=n.length)break;l=n[a+1]===Rd?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:cx(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)):Wr,this.#s=s-o-l,this.#t=0}else this.#r=d.length===0?Wr:Buffer.from(d),this.#s=s-o,this.#t=a-o;return i.length===0?Wr:i.length===1?i[0]:Buffer.concat(i)}flush(){let e=this.#r;return this.#r=Wr,this.#s=0,this.#t=0,this.#o=!1,e}};function iv(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 ux(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 fx(t){return t!==void 0&&/^\s*text\/event-stream(?:\s*;|\s*$)/i.test(t)}function px(t,e){let n=t.writeHead,i=t.write,o=t.end,s=!1,a,d=c=>{s||t.headersSent||(s=!0,fx(ux(t,c))&&(t.setHeader(Qo,Id),a=new cf({domain:e})))};t.writeHead=function(...l){return d(l),n.apply(this,l)},t.write=function(l,f,u){s||d([]);let m=i;if(a===void 0)return m.call(this,l,f,u);let h=typeof f=="string"?f:void 0,g=typeof f=="function"?f:u,p=iv(l,h);if(p===void 0)return m.call(this,l,f,u);let v=a.push(p);return v.length===0?(g!==void 0&&process.nextTick(g),!this.writableNeedDrain):g===void 0?m.call(this,v):m.call(this,v,g)},t.end=function(l,f,u){s||d([]);let m=o;if(a===void 0)return m.call(this,l,f,u);let h=typeof l=="function"?void 0:l,g=typeof l=="function"?l:typeof f=="function"?f:u,p=typeof f=="string"?f:void 0,v=[];if(h!=null){let R=iv(h,p);if(R===void 0)return m.call(this,l,f,u);v.push(a.push(R))}v.push(a.flush()),a=void 0;let b=Buffer.concat(v);return b.length===0?g===void 0?m.call(this):m.call(this,g):g===void 0?m.call(this,b):m.call(this,b,g)}}function ov(t,e,n){let i=ox(t);return i==="unified-v1"&&px(e,n),i}var En={format:"tansr-api-manifest-v1",contract:"unified-v1",revision:7,schemaHash:"b60e77ffcbf08d985a993dbdbd4cf610f12f7c7e70f090aee5ff8d523f70bb57",families:[{id:"agent-session-v1",domains:["session"],status:"frozen",rfc:"doc/98-Agent会话服务v2契约冻结件.md",source:"packages/server/src/v2/contract.ts",sha256:"6e1876edc476322e2fc3613958f5b44700bb80ea23550fa794f5729220674f3e",golden:{"packages/cli/test/fixtures/agent-v2-frames/frames.json":"5d3a40dcfea3709a06b78dd9a0066f68194efff96ebc4defc79476a589161d50","packages/protocol/schemas/kernel-event.schema.json":"54b587ade59bf20a3d55647a160c3d857dbf2fa73730d82cf7811b7ee4097501"},generated:[],legacyEntries:["/v2/sessions","/v2/sessions/:id/**"],apiEntries:["/api/sessions","/api/sessions/:id/**","/api/capabilities/sessions"],clients:[{client:"node",repo:"tansr-cli",lock:"source",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"contract/session-compatibility.json",lock:"route-vectors",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",file:"core/src/test/resources/contract/vendored.json",lock:"MANIFEST-revision-9",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",file:"Tests/TansrCoreTests/Fixtures/contract/vendored.json",lock:"MANIFEST-revision-9",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",file:"tests/fixtures/PROVENANCE.json",lock:"sourceCommit-ad43a96d",observed:"2026-10-01",drift:!1}],requestIdPath:null,sessionManifestRevision:9,sessionManifestSha256:"6e1876edc476322e2fc3613958f5b44700bb80ea23550fa794f5729220674f3e"},{id:"sdk2-ext-v1",domains:["archive","execution"],status:"final",rfc:"doc/rfc/RFC-SDK2-1-兼容SDK1的扩展协议.md",source:"doc/rfc/sdk2-ext-v1.schema.json",sha256:"969273844ca9196f19dd71b292b65a49307d63be0d20a0caf557e105ba6d8605",golden:{"scripts/sdk2/fixtures/sdk2-wire-v1.json":"d911959c91182834af396e09c523a14f223a65871588561dff5faf1d0ba27930"},generated:["packages/api-client/src/sdk2/wire-schema-generated.ts","packages/api-client/src/sdk2/wire-types-generated.ts","packages/api-client/src/sdk2/wire-limits-generated.ts","packages/server/src/v2/execution-contract.generated.ts"],legacyEntries:["/v3/sdk2/capabilities","/v3/sdk2/session-capabilities","/v3/sdk2/sessions/:id/binding-target","/v3/sdk2/bindings","/v3/sdk2/bindings/:id/**","/v3/sdk2/operations","/v3/sdk2/sessions/**","/v3/sdk2/executors/**","/v2/sessions/:id/initialize","/v2/sessions/:id/execution-capabilities","/v2/sessions/:id/execution-boundary","/v2/sessions/:id/execution-bindings","/v2/sessions/:id/executions/:targetId","/v2/executors/connections","/v2/executors/:id/heartbeats","/v2/executors/:id/operations","/v2/executors/:id/receipts"],apiEntries:["/api/capabilities/archive","/api/capabilities/sessions","/api/sessions/:id/binding-target","/api/archive/bindings","/api/archive/bindings/:id/**","/api/archive/operations","/api/executors/**","/api/sessions/:id/initialize","/api/sessions/:id/execution-capabilities","/api/sessions/:id/execution-boundary","/api/sessions/:id/execution-bindings","/api/sessions/:id/executions/:targetId"],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Protocol/WireContract.cs",lock:"969273844ca9196f19dd71b292b65a49307d63be0d20a0caf557e105ba6d8605",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",file:"core/src/main/kotlin/com/tansr/sdk/sdk2/Sdk2NamedSchema.kt",lock:"969273844ca9196f19dd71b292b65a49307d63be0d20a0caf557e105ba6d8605",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",file:"Sources/TansrCore/SDK2/Sdk2SchemaResource.swift",lock:"969273844ca9196f19dd71b292b65a49307d63be0d20a0caf557e105ba6d8605",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",file:"tansr/src/main/ets/core/sdk2/client/SchemaGenerated.ets",lock:"969273844ca9196f19dd71b292b65a49307d63be0d20a0caf557e105ba6d8605",observed:"2026-10-01",drift:!1}],requestIdPath:["request","requestId"]},{id:"sdk2-archive-recovery-v1",domains:["archive"],status:"additive",rfc:"doc/rfc/RFC-SDK2-ACK-recovery-v1.md",source:"doc/rfc/sdk2-archive-recovery-v1.schema.json",sha256:"f530de1096b4f5d56ea688b7f2cec9ae66deb7d3719db85ab1f48287d3bd7ad4",golden:{"doc/rfc/sdk2-archive-recovery-v1.golden.json":"614adf2088585a6213d010acde29598d40757d0f2d7b4608f1670ccbde3a5553","doc/rfc/sdk2-archive-recovery-v1.sqlite.sql":"a6fcfef2458cb0dcf9788af2385573c85b238dc875dee7ffc144f27dcc28028b"},generated:["packages/api-client/src/sdk2/archive-recovery-schema-generated.ts","packages/api-client/src/sdk2/archive-recovery-types-generated.ts","packages/server/src/sdk2/archive-recovery-contract.generated.ts"],legacyEntries:["/v3/sdk2/bindings/:id/archive/ack-rebases"],apiEntries:["/api/archive/bindings/:id/archive/ack-rebases"],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Archive/Recovery",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",lock:"absent",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",lock:"absent",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",lock:"absent",observed:"2026-10-01",drift:!1}],requestIdPath:["request","requestId"]},{id:"archive-sync-v1",domains:["archive-sync"],status:"additive",rfc:"doc/rfc/SDK2-档案同步与保留扩展.md",source:"doc/rfc/archive-sync-v1.schema.json",sha256:"7468fb72c80ce8d0bbe298219c894578020f249d7532c63cad91e8dad4a412bb",golden:{},generated:[],legacyEntries:["/v3/sdk2/archive-sync/:id"],apiEntries:["/api/archive/sync/:id"],clients:[{client:"node",repo:"tansr-cli",file:"packages/api-client/src/sdk2/receiver-sync-client.ts",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Archive/Replication/ArchiveSyncClient.cs",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",file:"core/src/main/kotlin/com/tansr/sdk/sdk2/receiver/Sdk2ArchiveSyncClient.kt",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",file:"Sources/TansrCore/SDK2/Sdk2ArchiveSync.swift",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",file:"tansr/src/main/ets/core/sdk2/client/ArchiveSync.ets",lock:"hand-written",observed:"2026-10-01",drift:!1}],requestIdPath:null},{id:"sdk2-cache-v1",domains:["cache"],status:"drafted",rfc:"doc/rfc/RFC-SDK2-缓存连续性.md",source:"doc/rfc/sdk2-cache-v1.schema.json",sha256:"88e7941861fab1a6380b9226e3a42adb8c872efdf720dc36e92ffa42da43d818",golden:{},generated:[],legacyEntries:["/v3/sdk2/cache/capabilities","/v3/sdk2/cache/bindings","/v3/sdk2/cache/bindings/:id/**","/v3/sdk2/cache/operations"],apiEntries:["/api/capabilities/cache","/api/cache/bindings","/api/cache/bindings/:id/**","/api/cache/operations"],clients:[{client:"node",repo:"tansr-cli",file:"packages/providers/src/twp/cache-wire.ts",lock:"88e7941861fab1a6380b9226e3a42adb8c872efdf720dc36e92ffa42da43d818",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Cache/CacheClient.cs",lock:"hand-written-internal",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",lock:"absent",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",lock:"absent",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",lock:"absent",observed:"2026-10-01",drift:!1}],requestIdPath:["request","requestId"]},{id:"sdk2-cache-core-v1",domains:["cache"],status:"additive",rfc:"doc/rfc/sdk2-cache-core-v1.md",source:"doc/rfc/sdk2-cache-core-v1.schema.json",sha256:"5b052117919f3ef751310a36db3a2c1dac96daeda2f10a4bb78028edc0d5cbff",golden:{},generated:[],legacyEntries:["/v3/sdk2/cache/core/v1/bindings/:id/diagnostics"],apiEntries:["/api/cache/core/v1/bindings/:id/diagnostics"],clients:[{client:"node",repo:"tansr-cli",file:"packages/providers/src/twp/cache-core-wire.ts",lock:"5b052117919f3ef751310a36db3a2c1dac96daeda2f10a4bb78028edc0d5cbff",observed:"2026-10-01",drift:!1}],requestIdPath:["request","requestId"]},{id:"terminal-services-v1",domains:["terminal"],status:"candidate",rfc:"doc/rfc/RFC-SERVE-NET-1-终端增量工具与记忆协议.md",source:"doc/rfc/terminal-services-v1.schema.json",sha256:"8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",golden:{"doc/rfc/terminal-services-v1.golden.json":"a19ee430360ca883723bb5836e8966e51e83f9831c57b1da3c1368cd3ef5e66a"},generated:["packages/api-client/src/terminal/wire-schema-generated.ts","packages/api-client/src/terminal/wire-types-generated.ts","packages/server/src/v2/terminal-contract.generated.ts"],legacyEntries:["/v3/terminal/capabilities","/v3/terminal/bindings","/v3/terminal/executors/:id/**","/v3/terminal/sessions/:id/**"],apiEntries:["/api/capabilities/terminal","/api/terminal/bindings","/api/terminal/executors/:id/**","/api/terminal/sessions/:id/**"],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Terminal/Contract/manifest.json",lock:"8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",file:"core/src/main/resources/terminal/terminal-services-v1.schema.json",lock:"8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",file:"Sources/TansrCore/Terminal/TerminalSchemaResource.swift",lock:"8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",file:"tansr/src/main/ets/core/terminal/SchemaGenerated.ets",lock:"8cd8c7c55a84c5700373aed75d5653a0737d718bfe0546641be367bda1a11896",observed:"2026-10-01",drift:!1}],requestIdPath:["requestId"]},{id:"terminal-observation-v1",domains:["terminal-observation"],status:"additive",rfc:"doc/rfc/RFC-SERVE-NET-1-终端增量工具与记忆协议.md",source:"doc/rfc/terminal-observation-v1.schema.json",sha256:"b6668463458e78b2cfe23baa72d9d9ac6263a248467dd8aeb60387fc2f67c28a",golden:{"doc/rfc/terminal-observation-v1.golden.json":"2148eb11fb4538736cd244b17e5ba135bc26919081105fd1018ff884ab364e1a"},generated:["packages/api-client/src/terminal/observation-wire-schema-generated.ts","packages/api-client/src/terminal/observation-wire-types-generated.ts","packages/server/src/v2/terminal-observation-contract.generated.ts"],legacyEntries:["/v3/terminal-observation/sessions/:id/resources","/v3/terminal-observation/sessions/:id/output-correlations"],apiEntries:["/api/terminal/observation/sessions/:id/resources","/api/terminal/observation/sessions/:id/output-correlations"],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Terminal/TerminalObservationClient.cs",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",lock:"absent",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",lock:"absent",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",lock:"absent",observed:"2026-10-01",drift:!1}],requestIdPath:["requestId"]},{id:"terminal-profile-v1",domains:["terminal-profile"],status:"additive",rfc:"doc/rfc/RFC-SERVE-NET-1-终端增量工具与记忆协议.md",source:"doc/rfc/terminal-profile-v1.schema.json",sha256:"560ad136f0619a2a0592151d56e10871c3799ca438163c4e2872381bf5f5159a",golden:{"doc/rfc/terminal-profile-v1.golden.json":"6ecfea5872a8cb2052d35cb908839c7ab07c11d77f65dc7e9a230494a2cf8ea4"},generated:["packages/api-client/src/terminal/profile-wire-schema-generated.ts","packages/api-client/src/terminal/profile-wire-types-generated.ts","packages/server/src/v2/terminal-profile-contract.generated.ts"],legacyEntries:["/v3/terminal-profile/sessions/:id/catalog","/v3/terminal-profile/sessions/:id/usage"],apiEntries:["/api/terminal/profile/sessions/:id/catalog","/api/terminal/profile/sessions/:id/usage"],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"src/Tansr.Sdk/Terminal/TerminalProfileClient.cs",lock:"hand-written",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",lock:"absent",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",lock:"absent",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",lock:"absent",observed:"2026-10-01",drift:!1}],requestIdPath:["requestId"]},{id:"terminal-shell-sandbox-v1",domains:["terminal"],status:"additive",rfc:"doc/rfc/RFC-SERVE-NET-1-终端增量工具与记忆协议.md",source:"doc/rfc/terminal-shell-sandbox-v1.schema.json",sha256:"be3ebcf6dc650844319a18a15f6abbefb9316f704410b591f9ba6dcab7620fe1",golden:{"doc/rfc/terminal-shell-sandbox-v1.golden.json":"ad76d8eae6970835a0995475ce4cb6e0a58ded5bc7b4e50bf01a3e5dc0212563"},generated:["packages/api-client/src/terminal/shell-sandbox-schema-generated.ts","packages/api-client/src/terminal/shell-sandbox-types-generated.ts","packages/server/src/v2/terminal-shell-sandbox-contract.generated.ts","packages/server/src/v2/terminal-shell-sandbox-codec.generated.ts"],legacyEntries:[],apiEntries:[],clients:[{client:"node",repo:"tansr-cli",lock:"generated",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",lock:"hand-written",observed:"2026-10-01",drift:!1}],requestIdPath:null},{id:"unified-v1",domains:["discovery"],status:"candidate",rfc:"doc/rfc/RFC-UAPI-1-统一信封与canonical单模块.md",source:"doc/rfc/unified-v1.schema.json",sha256:"fd07962916f7662ecc69c3f8c8d2b79aa5b99f542cbfd310a50f56777e51f117",golden:{"doc/rfc/unified-v1.golden.json":"42531a3937563d8c0d719c5970629b25bbabf3a8ea8436550db5bfddf9d206fd"},generated:[],legacyEntries:[],apiEntries:["/api/manifest","/api/capabilities","/api/sessions/:id/capabilities"],clients:[{client:"node",repo:"tansr-cli",file:"packages/api-client/src/api/operations-generated.ts",lock:"generated",observed:"2026-10-01",drift:!1},{client:"go",repo:"tansr-go",file:"contract/PROVENANCE.json",lock:"manifest-sha256",observed:"2026-10-01",drift:!1},{client:"csharp",repo:"tansr-net",file:"contract/manifest.json",lock:"manifest-sha256",observed:"2026-10-01",drift:!1},{client:"android",repo:"tansr-android",file:"contract/api-contract.lock.json",lock:"manifest-sha256",observed:"2026-10-01",drift:!1},{client:"ios",repo:"tansr-ios",file:"contract/api-contract.lock.json",lock:"manifest-sha256",observed:"2026-10-01",drift:!1},{client:"harmony",repo:"tansr-harmony",file:"contract/api-contract.lock.json",lock:"manifest-sha256",observed:"2026-10-01",drift:!1}],requestIdPath:null}],operations:[{name:"discovery.manifest",domain:"discovery",family:null,method:"GET",apiPath:"/api/manifest",aliases:[],legacyPath:null,legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:null,query:[],notes:"门面自答:本 manifest + runtime.installed(已装配域);无领域 schema",etagPath:null,expectedRevision:null},{name:"discovery.capabilities",domain:"discovery",family:null,method:"GET",apiPath:"/api/capabilities",aliases:[],legacyPath:null,legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:null,query:[],notes:"门面自答:域可用性 / 族与 schemaHash / 会话族 preferred+available(部署级;不含 URL 导航字段,RFC-SDK2-1 §10.5)",etagPath:null,expectedRevision:null},{name:"discovery.session.capabilities",domain:"discovery",family:null,method:"GET",apiPath:"/api/sessions/:id/capabilities",aliases:[],legacyPath:null,legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:null,query:[],notes:"会话级能力闭合围栏(方案 §3.6 / RFC-UAPI-1 §1.4):{ contract, closureId, authorizationRevision, domains, operations } + 响应头 tansr-closure-id;写操作可携 tansr-closure-id 作前置(412 closure_stale)",etagPath:null,expectedRevision:null},{name:"session.capabilities",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/capabilities/sessions",aliases:[],legacyPath:"/v3/sdk2/session-capabilities",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:null,query:["protocol"],notes:"会话族发现 { protocol, contracts[{ contract, availability }] } 内联于 v2/routes.ts,无命名 schema",etagPath:null,expectedRevision:null},{name:"session.create",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions",aliases:[],legacyPath:"/v2/sessions",legacyOffloadPath:"/v3/sdk2/sessions",kind:"write",sse:!1,request:"agent-session-v1#CreateSessionBodySchema",response:null,query:[],notes:"201 { sessionId, resumed, lastSeq, ...familyView } 无命名响应 schema;attach / resume / fork 同端点",etagPath:null,expectedRevision:null},{name:"session.list",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions",aliases:[],legacyPath:"/v2/sessions",legacyOffloadPath:"/v3/sdk2/sessions",kind:"read",sse:!1,request:null,response:null,query:["limit","offset"],notes:"响应 { sessions: V2SessionMetaView[], total } 无命名 schema",etagPath:null,expectedRevision:null},{name:"session.get",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id",aliases:[],legacyPath:"/v2/sessions/:id",legacyOffloadPath:"/v3/sdk2/sessions/:id",kind:"read",sse:!1,request:null,response:"agent-session-v1#V2SessionMetaView",query:["include"],notes:null,etagPath:null,expectedRevision:null},{name:"session.close",domain:"session",family:"agent-session-v1",method:"DELETE",apiPath:"/api/sessions/:id",aliases:[],legacyPath:"/v2/sessions/:id",legacyOffloadPath:"/v3/sdk2/sessions/:id",kind:"write",sse:!1,request:null,response:null,query:[],notes:"202 { sessionId, accepted: true };休眠会话幂等 202",etagPath:null,expectedRevision:null},{name:"session.message.send",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/messages",aliases:[],legacyPath:"/v2/sessions/:id/messages",legacyOffloadPath:"/v3/sdk2/sessions/:id/messages",kind:"write",sse:!1,request:"agent-session-v1#MessagesBodySchema",response:null,query:[],notes:"202 { sessionId, accepted: true };事件经 session.events.observe",etagPath:null,expectedRevision:null},{name:"session.events.observe",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/events",aliases:[],legacyPath:"/v2/sessions/:id/events",legacyOffloadPath:"/v3/sdk2/sessions/:id/events",kind:"stream",sse:!0,request:null,response:null,query:["exclude"],notes:"Last-Event-ID 续订;帧 = KernelEvent(golden kernel-event.schema.json)+ 控制帧 CONTROL_FRAME",etagPath:null,expectedRevision:null},{name:"session.interrupt",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/interrupt",aliases:[],legacyPath:"/v2/sessions/:id/interrupt",legacyOffloadPath:"/v3/sdk2/sessions/:id/interrupt",kind:"write",sse:!1,request:null,response:null,query:[],notes:"202 { sessionId, accepted: true }",etagPath:null,expectedRevision:null},{name:"session.history.read",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/history",aliases:[],legacyPath:"/v2/sessions/:id/history",legacyOffloadPath:"/v3/sdk2/sessions/:id/history",kind:"read",sse:!1,request:null,response:null,query:["offset","limit"],notes:"响应 { sessionId, lastSeq, messages[, total, offset] } 无命名 schema",etagPath:null,expectedRevision:null},{name:"session.tool.result",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/tool-results/:targetId",aliases:[],legacyPath:"/v2/sessions/:id/tool-results/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/tool-results/:targetId",kind:"write",sse:!1,request:"agent-session-v1#ToolResultReceiptSchema",response:null,query:[],notes:":targetId = toolCallId(doc/98 ⑨ :callId);200 { accepted: true }",etagPath:null,expectedRevision:null},{name:"session.permission.decide",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/permission/:ticketId",aliases:[],legacyPath:"/v2/sessions/:id/permission/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/permission/:targetId",kind:"write",sse:!1,request:"agent-session-v1#PermissionReceiptSchema",response:null,query:[],notes:"wire 仍为 requestId(/v2 ⑩⑪ 服务端签发票据);统一层按 RFC-UAPI-1 §3 消歧命名 :ticketId(D26 代拍 2026-10-03:/api 观测模板同口径),内部 /v2 / /v3 模板占位为 :targetId",etagPath:null,expectedRevision:null},{name:"session.question.answer",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/questions/:ticketId",aliases:[],legacyPath:"/v2/sessions/:id/questions/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/questions/:targetId",kind:"write",sse:!1,request:"agent-session-v1#QuestionReceiptSchema",response:null,query:[],notes:"wire 仍为 requestId(/v2 ⑩⑪ 服务端签发票据);统一层按 RFC-UAPI-1 §3 消歧命名 :ticketId(D26 代拍 2026-10-03:/api 观测模板同口径),内部 /v2 / /v3 模板占位为 :targetId",etagPath:null,expectedRevision:null},{name:"session.compact",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/compact",aliases:[],legacyPath:"/v2/sessions/:id/compact",legacyOffloadPath:"/v3/sdk2/sessions/:id/compact",kind:"write",sse:!1,request:"agent-session-v1#CompactBodySchema",response:"agent-session-v1#V2CompactResult",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"session.checkpoint.list",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/checkpoints",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints",kind:"read",sse:!1,request:null,response:"agent-session-v1#V2CheckpointList",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"session.checkpoint.create",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/checkpoints",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints",kind:"write",sse:!1,request:"agent-session-v1#CheckpointBodySchema",response:"agent-session-v1#V2CheckpointMeta",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"session.checkpoint.import",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/checkpoints/import",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints/import",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints/import",kind:"write",sse:!1,request:null,response:"agent-session-v1#V2CheckpointMeta",query:["label"],notes:"体 = checkpoint.export 原字节(application/octet-stream,≤ 32 MiB),非 JSON schema;201",etagPath:null,expectedRevision:null},{name:"session.checkpoint.restore",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/checkpoints/:targetId/restore",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints/:targetId/restore",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints/:targetId/restore",kind:"write",sse:!1,request:"agent-session-v1#RestoreBodySchema",response:"agent-session-v1#V2RestoreResult",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"session.checkpoint.export",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/checkpoints/:targetId/export",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints/:targetId/export",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints/:targetId/export",kind:"read",sse:!1,request:null,response:null,query:[],notes:'200 application/octet-stream:{ format: "tansr-checkpoint/1", checkpoint, attachments },非 JSON schema',etagPath:null,expectedRevision:null},{name:"session.checkpoint.delete",domain:"session",family:"agent-session-v1",method:"DELETE",apiPath:"/api/sessions/:id/checkpoints/:targetId",aliases:[],legacyPath:"/v2/sessions/:id/checkpoints/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/checkpoints/:targetId",kind:"write",sse:!1,request:null,response:null,query:[],notes:"204 无体",etagPath:null,expectedRevision:null},{name:"session.cwd.set",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/cwd",aliases:[],legacyPath:"/v2/sessions/:id/cwd",legacyOffloadPath:"/v3/sdk2/sessions/:id/cwd",kind:"write",sse:!1,request:"agent-session-v1#SetCwdBodySchema",response:"agent-session-v1#V2SetCwdResult",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"session.audio.transcribe",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/audio/transcriptions",aliases:[],legacyPath:"/v2/sessions/:id/audio/transcriptions",legacyOffloadPath:"/v3/sdk2/sessions/:id/audio/transcriptions",kind:"write",sse:!1,request:"agent-session-v1#AudioTranscriptionsBodySchema",response:null,query:[],notes:"响应为平台转写结果透传(doc/123 §3.1),无本仓命名 schema",etagPath:null,expectedRevision:null},{name:"session.audio.speak",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/audio/speech",aliases:[],legacyPath:"/v2/sessions/:id/audio/speech",legacyOffloadPath:"/v3/sdk2/sessions/:id/audio/speech",kind:"write",sse:!1,request:"agent-session-v1#AudioSpeechBodySchema",response:null,query:[],notes:"响应为平台合成结果透传(doc/123 §3.2),无本仓命名 schema",etagPath:null,expectedRevision:null},{name:"session.input.capabilities",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/input-capabilities",aliases:[],legacyPath:"/v2/sessions/:id/input-capabilities",legacyOffloadPath:"/v3/sdk2/sessions/:id/input-capabilities",kind:"read",sse:!1,request:null,response:null,query:[],notes:"响应 = kernel SessionInputCapabilities(字段见 CAPABILITIES session.input.*),contract.ts 无命名 schema",etagPath:null,expectedRevision:null},{name:"session.input.submit",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/sessions/:id/inputs",aliases:[],legacyPath:"/v2/sessions/:id/inputs",legacyOffloadPath:"/v3/sdk2/sessions/:id/inputs",kind:"write",sse:!1,request:"agent-session-v1#SubmitInputBodySchema",response:null,query:[],notes:"响应 = kernel SessionInputResult(accepted 携 SessionInputReceipt),contract.ts 无命名 schema",etagPath:null,expectedRevision:null},{name:"session.input.status",domain:"session",family:"agent-session-v1",method:"GET",apiPath:"/api/sessions/:id/inputs/:targetId",aliases:[],legacyPath:"/v2/sessions/:id/inputs/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/inputs/:targetId",kind:"read",sse:!1,request:null,response:null,query:["historyEpoch","turnId"],notes:":targetId = inputId;响应 = kernel SessionInputReceipt,contract.ts 无命名 schema",etagPath:null,expectedRevision:null},{name:"approval.credential.submit",domain:"session",family:"agent-session-v1",method:"POST",apiPath:"/api/approvals/:id/credential",aliases:[],legacyPath:"/v1/approvals/:id/credential",legacyOffloadPath:null,kind:"write",sse:!1,request:null,response:null,query:[],notes:':id = challengeId;体 { digest, verdict: approve|deny, approver }(RFC-K11 §3.2,无命名 schema);200 { challengeId, result: "accepted" };拒绝经统一信封:unknown_challenge → not_found 404、expired → gone 410、digest_mismatch / already_resolved → conflict 409(detail.submitCode 留原 SubmitCode);approvals 缝未接线 → 404 capability_unavailable',etagPath:null,expectedRevision:null},{name:"execution.initialize",domain:"execution",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/sessions/:id/initialize",aliases:[],legacyPath:"/v2/sessions/:id/initialize",legacyOffloadPath:"/v3/sdk2/sessions/:id/initialize",kind:"write",sse:!1,request:"sdk2-ext-v1#SessionInitializeRequest",response:"sdk2-ext-v1#SessionExecutionCapabilities",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"execution.capabilities",domain:"execution",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/sessions/:id/execution-capabilities",aliases:[],legacyPath:"/v2/sessions/:id/execution-capabilities",legacyOffloadPath:"/v3/sdk2/sessions/:id/execution-capabilities",kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#SessionExecutionCapabilities",query:["protocol"],notes:null,etagPath:null,expectedRevision:null},{name:"execution.boundary",domain:"execution",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/sessions/:id/execution-boundary",aliases:[],legacyPath:"/v2/sessions/:id/execution-boundary",legacyOffloadPath:"/v3/sdk2/sessions/:id/execution-boundary",kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#ExecutionBoundary",query:["protocol"],notes:null,etagPath:null,expectedRevision:null},{name:"execution.binding.create",domain:"execution",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/sessions/:id/execution-bindings",aliases:[],legacyPath:"/v2/sessions/:id/execution-bindings",legacyOffloadPath:"/v3/sdk2/sessions/:id/execution-bindings",kind:"write",sse:!1,request:"sdk2-ext-v1#ExecutionBindingRequest",response:"sdk2-ext-v1#SessionExecutionCapabilities",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"execution.status",domain:"execution",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/sessions/:id/executions/:targetId",aliases:[],legacyPath:"/v2/sessions/:id/executions/:targetId",legacyOffloadPath:"/v3/sdk2/sessions/:id/executions/:targetId",kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#ExecutionStatus",query:["protocol"],notes:":targetId = operationId",etagPath:null,expectedRevision:null},{name:"executor.register",domain:"execution",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/executors/connections",aliases:[],legacyPath:"/v2/executors/connections",legacyOffloadPath:"/v3/sdk2/executors/connections",kind:"write",sse:!1,request:"sdk2-ext-v1#ExecutorRegistrationRequest",response:"sdk2-ext-v1#ExecutorConnection",query:[],notes:"201",etagPath:null,expectedRevision:null},{name:"executor.heartbeat",domain:"execution",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/executors/:id/heartbeats",aliases:[],legacyPath:"/v2/executors/:id/heartbeats",legacyOffloadPath:"/v3/sdk2/executors/:id/heartbeats",kind:"write",sse:!1,request:"sdk2-ext-v1#ExecutorHeartbeatRequest",response:"sdk2-ext-v1#ExecutorConnection",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"executor.operations.poll",domain:"execution",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/executors/:id/operations",aliases:[],legacyPath:"/v2/executors/:id/operations",legacyOffloadPath:"/v3/sdk2/executors/:id/operations",kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#ExecutionBatch",query:["protocol","connectionId"],notes:null,etagPath:null,expectedRevision:null},{name:"executor.receipt.submit",domain:"execution",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/executors/:id/receipts",aliases:[],legacyPath:"/v2/executors/:id/receipts",legacyOffloadPath:"/v3/sdk2/executors/:id/receipts",kind:"write",sse:!1,request:"sdk2-ext-v1#ExecutionReceiptRequest",response:"sdk2-ext-v1#ExecutionStatus",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"archive.capabilities",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/capabilities/archive",aliases:[],legacyPath:"/v3/sdk2/capabilities",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#CapabilitiesResponse",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"archive.binding.target",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/sessions/:id/binding-target",aliases:[],legacyPath:"/v3/sdk2/sessions/:id/binding-target",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#BindingTargetRequest",response:"sdk2-ext-v1#BindingTargetView",query:["protocol"],notes:null,etagPath:["revision"],expectedRevision:null},{name:"archive.binding.create",domain:"archive",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/archive/bindings",aliases:[],legacyPath:"/v3/sdk2/bindings",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-ext-v1#BindingCreateRequest",response:"sdk2-ext-v1#BindingView",query:[],notes:"201",etagPath:["revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"archive.binding.get",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id",aliases:[],legacyPath:"/v3/sdk2/bindings/:id",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#BindingView",query:["protocol"],notes:null,etagPath:["revision"],expectedRevision:null},{name:"archive.binding.close",domain:"archive",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/archive/bindings/:id/close",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/close",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-ext-v1#BindingCloseRequest",response:"sdk2-ext-v1#MutationReceipt",query:[],notes:null,etagPath:["revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"archive.status",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/archive/status",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/archive/status",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"sdk2-ext-v1#ArchiveStatus",query:["protocol"],notes:null,etagPath:["revision"],expectedRevision:null},{name:"archive.events.observe",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/events",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/events",legacyOffloadPath:null,kind:"stream",sse:!0,request:null,response:"sdk2-ext-v1#EventFrame",query:["protocol"],notes:"Last-Event-ID 续订(独立重放日志 / 游标)",etagPath:null,expectedRevision:null},{name:"archive.records.read",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/archive/records",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/archive/records",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#ArchiveReadRequest",response:"sdk2-ext-v1#ArchivePage",query:["protocol","historyEpoch","deletionGeneration","projectionRevision","limit","maxBytes","afterSequence"],notes:null,etagPath:null,expectedRevision:null},{name:"archive.artifact.read",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/archive/artifacts/:targetId",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/archive/artifacts/:targetId",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#ArtifactReadRequest",response:"sdk2-ext-v1#ArtifactChunk",query:["protocol","historyEpoch","deletionGeneration","projectionRevision","offset","maxBytes"],notes:":targetId = artifactId",etagPath:null,expectedRevision:null},{name:"archive.ack.commit",domain:"archive",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/archive/bindings/:id/archive/acks",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/archive/acks",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-ext-v1#ArchiveAckRequest",response:"sdk2-ext-v1#MutationReceipt",query:[],notes:null,etagPath:["revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"archive.ack.rebase",domain:"archive",family:"sdk2-archive-recovery-v1",method:"POST",apiPath:"/api/archive/bindings/:id/archive/ack-rebases",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/archive/ack-rebases",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-archive-recovery-v1#AckRebaseRequest",response:"sdk2-archive-recovery-v1#AckRebaseReceipt",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"archive.operation.query",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/operations",aliases:[],legacyPath:"/v3/sdk2/operations",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#OperationStatusRequest",response:"sdk2-ext-v1#MutationReceipt",query:["protocol","operation","operationEpoch","requestId","bindingId","sessionId"],notes:"operation ∈ binding-create(携 sessionId)| archive-ack | material-response | binding-close(携 bindingId);material-response 回 MaterialReceipt",etagPath:null,expectedRevision:null},{name:"archive.sync",domain:"archive-sync",family:"archive-sync-v1",method:"POST",apiPath:"/api/archive/sync/:id",aliases:[],legacyPath:"/v3/sdk2/archive-sync/:id",legacyOffloadPath:null,kind:"write",sse:!1,request:"archive-sync-v1#Request",response:"archive-sync-v1#Response",query:[],notes:"单入口多方法:method 词表 archive-sync-v1#Method(= sdk2/archive-sync.ts methods);value 形随方法;错误形 archive-sync-v1#ErrorResponse(不在统一错误矩阵,经 /api 原样透传);:id = bindingId",etagPath:null,expectedRevision:null},{name:"material.response.submit",domain:"archive",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/archive/bindings/:id/material-responses",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/material-responses",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-ext-v1#MaterialResponseRequest",response:"sdk2-ext-v1#MaterialReceipt",query:[],notes:"202",etagPath:null,expectedRevision:null},{name:"material.status",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/materials/:targetId",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/materials/:targetId",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#MaterialStatusRequest",response:"sdk2-ext-v1#MaterialReceipt",query:["protocol"],notes:":targetId = materialRequestId",etagPath:null,expectedRevision:null},{name:"material.upload.status",domain:"archive",family:"sdk2-ext-v1",method:"GET",apiPath:"/api/archive/bindings/:id/materials/:targetId/uploads/:uploadId",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/materials/:targetId/uploads/:uploadId",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-ext-v1#MaterialUploadStatusRequest",response:"sdk2-ext-v1#MaterialUploadStatus",query:["protocol"],notes:":uploadId = artifactId",etagPath:null,expectedRevision:null},{name:"material.upload.chunk",domain:"archive",family:"sdk2-ext-v1",method:"POST",apiPath:"/api/archive/bindings/:id/materials/:targetId/uploads/:uploadId/chunks",aliases:[],legacyPath:"/v3/sdk2/bindings/:id/materials/:targetId/uploads/:uploadId/chunks",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-ext-v1#MaterialUploadChunkRequest",response:"sdk2-ext-v1#MaterialUploadStatus",query:[],notes:":uploadId = artifactId",etagPath:null,expectedRevision:null},{name:"cache.capabilities",domain:"cache",family:"sdk2-cache-v1",method:"GET",apiPath:"/api/capabilities/cache",aliases:[],legacyPath:"/v3/sdk2/cache/capabilities",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"sdk2-cache-v1#CapabilitiesResponse",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"cache.binding.open",domain:"cache",family:"sdk2-cache-v1",method:"POST",apiPath:"/api/cache/bindings",aliases:[],legacyPath:"/v3/sdk2/cache/bindings",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-cache-v1#OpenRequest",response:"sdk2-cache-v1#OpenResponse",query:[],notes:null,etagPath:["binding","revision"],expectedRevision:null},{name:"cache.binding.get",domain:"cache",family:"sdk2-cache-v1",method:"GET",apiPath:"/api/cache/bindings/:id",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-cache-v1#BindingQuery",response:"sdk2-cache-v1#BindingView",query:["protocol"],notes:null,etagPath:["revision"],expectedRevision:null},{name:"cache.binding.renew",domain:"cache",family:"sdk2-cache-v1",method:"POST",apiPath:"/api/cache/bindings/:id/renew",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id/renew",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-cache-v1#RenewRequest",response:"sdk2-cache-v1#MutationReceipt",query:[],notes:null,etagPath:["binding","revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"cache.binding.rebind",domain:"cache",family:"sdk2-cache-v1",method:"POST",apiPath:"/api/cache/bindings/:id/rebind",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id/rebind",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-cache-v1#RebindRequest",response:"sdk2-cache-v1#MutationReceipt",query:[],notes:null,etagPath:["binding","revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"cache.binding.rotate",domain:"cache",family:"sdk2-cache-v1",method:"POST",apiPath:"/api/cache/bindings/:id/rotate",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id/rotate",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-cache-v1#RotateRequest",response:"sdk2-cache-v1#MutationReceipt",query:[],notes:null,etagPath:["binding","revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"cache.binding.close",domain:"cache",family:"sdk2-cache-v1",method:"POST",apiPath:"/api/cache/bindings/:id/close",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id/close",legacyOffloadPath:null,kind:"write",sse:!1,request:"sdk2-cache-v1#CloseRequest",response:"sdk2-cache-v1#MutationReceipt",query:[],notes:null,etagPath:["binding","revision"],expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"cache.operation.query",domain:"cache",family:"sdk2-cache-v1",method:"GET",apiPath:"/api/cache/operations",aliases:[],legacyPath:"/v3/sdk2/cache/operations",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-cache-v1#OperationQuery",response:"sdk2-cache-v1#MutationReceipt",query:["protocol","operation","operationEpoch","requestId","bindingId"],notes:"operation ∈ open | renew | rebind | rotate | close",etagPath:null,expectedRevision:null},{name:"cache.diagnostics",domain:"cache",family:"sdk2-cache-v1",method:"GET",apiPath:"/api/cache/bindings/:id/diagnostics",aliases:[],legacyPath:"/v3/sdk2/cache/bindings/:id/diagnostics",legacyOffloadPath:null,kind:"read",sse:!1,request:"sdk2-cache-v1#DiagnosticQuery",response:"sdk2-cache-v1#DiagnosticPage",query:["protocol","after","limit"],notes:null,etagPath:null,expectedRevision:null},{name:"cache.core.diagnostics",domain:"cache",family:"sdk2-cache-core-v1",method:"GET",apiPath:"/api/cache/core/v1/bindings/:id/diagnostics",aliases:[],legacyPath:"/v3/sdk2/cache/core/v1/bindings/:id/diagnostics",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"sdk2-cache-core-v1#Diagnostics",query:["protocol","limit","after"],notes:"protocol = sdk2-cache-core-v1",etagPath:null,expectedRevision:null},{name:"terminal.capabilities",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/capabilities/terminal",aliases:[],legacyPath:"/v3/terminal/capabilities",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#CapabilitiesResponse",query:["contract"],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.binding.create",domain:"terminal",family:"terminal-services-v1",method:"POST",apiPath:"/api/terminal/bindings",aliases:[],legacyPath:"/v3/terminal/bindings",legacyOffloadPath:null,kind:"write",sse:!1,request:"terminal-services-v1#BindingRequest",response:"terminal-services-v1#BindingResponse",query:[],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.executor.events.observe",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/executors/:id/events",aliases:[],legacyPath:"/v3/terminal/executors/:id/events",legacyOffloadPath:null,kind:"stream",sse:!0,request:null,response:"terminal-services-v1#ExecutorEvent",query:["contract","sessionContract","connectionId"],notes:":id = executorId;Last-Event-ID = Sequence 游标",etagPath:null,expectedRevision:null},{name:"terminal.output.batch",domain:"terminal",family:"terminal-services-v1",method:"POST",apiPath:"/api/terminal/executors/:id/output-batches",aliases:[],legacyPath:"/v3/terminal/executors/:id/output-batches",legacyOffloadPath:null,kind:"write",sse:!1,request:"terminal-services-v1#OutputBatchRequest",response:"terminal-services-v1#OutputStatus",query:[],notes:":id = executorId",etagPath:null,expectedRevision:null},{name:"terminal.execution.state",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/executors/:id/operations/:targetId",aliases:[],legacyPath:"/v3/terminal/executors/:id/operations/:targetId",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#ExecutionState",query:["contract","sessionContract","sessionId","requestDigest","connectionId"],notes:":id = executorId;:targetId = operationId",etagPath:null,expectedRevision:null},{name:"terminal.output.observe",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/sessions/:id/tool-output",aliases:[],legacyPath:"/v3/terminal/sessions/:id/tool-output",legacyOffloadPath:null,kind:"stream",sse:!0,request:null,response:"terminal-services-v1#OutputEvent",query:["contract","sessionContract","operationId","requestDigest","afterSeq"],notes:"输出水位以 afterSeq 续订,不接受 Last-Event-ID",etagPath:null,expectedRevision:null},{name:"terminal.output.status",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/sessions/:id/tool-output-status",aliases:[],legacyPath:"/v3/terminal/sessions/:id/tool-output-status",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#OutputStatus",query:["contract","sessionContract","operationId","requestDigest"],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.configuration.read",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/sessions/:id/configuration",aliases:["/api/sessions/:id/configuration"],legacyPath:"/v3/terminal/sessions/:id/configuration",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#ConfigurationResponse",query:["contract","sessionContract"],notes:null,etagPath:["configuration","revision"],expectedRevision:null},{name:"terminal.configuration.commit",domain:"terminal",family:"terminal-services-v1",method:"POST",apiPath:"/api/terminal/sessions/:id/configuration",aliases:["/api/sessions/:id/configuration"],legacyPath:"/v3/terminal/sessions/:id/configuration",legacyOffloadPath:null,kind:"write",sse:!1,request:"terminal-services-v1#ConfigurationRequest",response:"terminal-services-v1#ConfigurationCommitResponse",query:[],notes:null,etagPath:["configuration","revision"],expectedRevision:{path:["expectedRevision"],kind:"integer"}},{name:"terminal.memory.read",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/sessions/:id/memory",aliases:["/api/sessions/:id/memory"],legacyPath:"/v3/terminal/sessions/:id/memory",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#MemoryStateResponse",query:["contract","sessionContract"],notes:null,etagPath:["memory","revision"],expectedRevision:null},{name:"terminal.memory.command",domain:"terminal",family:"terminal-services-v1",method:"POST",apiPath:"/api/terminal/sessions/:id/memory/commands",aliases:["/api/sessions/:id/memory/commands"],legacyPath:"/v3/terminal/sessions/:id/memory/commands",legacyOffloadPath:null,kind:"write",sse:!1,request:"terminal-services-v1#MemoryCommandRequest",response:"terminal-services-v1#MemoryReceiptResponse",query:[],notes:null,etagPath:null,expectedRevision:{path:["expectedRevision"],kind:"sequence"}},{name:"terminal.memory.receipt",domain:"terminal",family:"terminal-services-v1",method:"GET",apiPath:"/api/terminal/sessions/:id/memory/commands/:targetId",aliases:["/api/sessions/:id/memory/commands/:targetId"],legacyPath:"/v3/terminal/sessions/:id/memory/commands/:targetId",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-services-v1#MemoryReceiptResponse",query:["contract","sessionContract","requestId"],notes:":targetId = operationId",etagPath:null,expectedRevision:null},{name:"terminal.observation.resources",domain:"terminal-observation",family:"terminal-observation-v1",method:"GET",apiPath:"/api/terminal/observation/sessions/:id/resources",aliases:[],legacyPath:"/v3/terminal-observation/sessions/:id/resources",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-observation-v1#ResourcesResponse",query:["contract","sessionContract"],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.observation.correlations",domain:"terminal-observation",family:"terminal-observation-v1",method:"GET",apiPath:"/api/terminal/observation/sessions/:id/output-correlations",aliases:[],legacyPath:"/v3/terminal-observation/sessions/:id/output-correlations",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-observation-v1#CorrelationsResponse",query:["contract","sessionContract","toolCallId"],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.profile.catalog",domain:"terminal-profile",family:"terminal-profile-v1",method:"GET",apiPath:"/api/terminal/profile/sessions/:id/catalog",aliases:[],legacyPath:"/v3/terminal-profile/sessions/:id/catalog",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-profile-v1#CatalogResponse",query:["contract","sessionContract"],notes:null,etagPath:null,expectedRevision:null},{name:"terminal.profile.usage",domain:"terminal-profile",family:"terminal-profile-v1",method:"GET",apiPath:"/api/terminal/profile/sessions/:id/usage",aliases:[],legacyPath:"/v3/terminal-profile/sessions/:id/usage",legacyOffloadPath:null,kind:"read",sse:!1,request:null,response:"terminal-profile-v1#UsageResponse",query:["contract","sessionContract"],notes:null,etagPath:null,expectedRevision:null}],capabilities:[{id:"archive.limit.controlBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:262144,default:262144}},{id:"archive.limit.recordBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:262144,default:262144}},{id:"archive.limit.pageRecords",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:128,default:128}},{id:"archive.limit.pageBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:1048576,default:1048576}},{id:"archive.limit.attachmentBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:33554432,default:33554432}},{id:"archive.limit.chunkBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:262144,default:262144}},{id:"archive.limit.materialConcurrent",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:2,default:2}},{id:"archive.limit.materialQueue",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:16,default:16}},{id:"archive.limit.materialCandidates",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:32,default:32}},{id:"archive.limit.materialBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:1048576,default:1048576}},{id:"archive.limit.materialDeadlineMs",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1e3,max:3e4,default:3e4}},{id:"archive.limit.pendingRecords",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:4096,default:4096}},{id:"archive.limit.pendingBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1048576,max:67108864,default:67108864}},{id:"archive.limit.inflightReserveBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1048576,max:16777216,default:16777216}},{id:"archive.limit.offlineMs",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1e3,max:864e5,default:864e5}},{id:"archive.limit.eventRetentionMs",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1e3,max:6e5,default:6e5}},{id:"archive.limit.eventRetentionFrames",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:4096,default:4096}},{id:"archive.limit.eventRetentionBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1024,max:8388608,default:8388608}},{id:"archive.limit.terminalReceiptRetentionMs",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:6e4,max:6048e5,default:6048e5}},{id:"archive.limit.epochLifetimeMs",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:6e4,max:864e5,default:36e5}},{id:"archive.limit.materialChunkBytes",domain:"archive",family:"sdk2-ext-v1",kind:"limit",source:"packages/api-client/src/sdk2/wire-limits-generated.ts#SDK2_LIMIT_RANGES",value:{min:1,max:65536,default:65536}},{id:"archive.capability.archive-transfer-v1",domain:"archive",family:"sdk2-ext-v1",kind:"capability",source:"doc/rfc/sdk2-ext-v1.schema.json#Capability",value:"archive-transfer-v1"},{id:"archive.capability.context-materials-v1",domain:"archive",family:"sdk2-ext-v1",kind:"capability",source:"doc/rfc/sdk2-ext-v1.schema.json#Capability",value:"context-materials-v1"},{id:"cache.feature.private-logical-cache-v1",domain:"cache",family:"sdk2-cache-v1",kind:"feature",source:"doc/rfc/sdk2-cache-v1.schema.json#Feature",value:"private-logical-cache-v1"},{id:"cache.feature.trusted-core-projection-v1",domain:"cache",family:"sdk2-cache-core-v1",kind:"feature",source:"doc/rfc/sdk2-cache-core-v1.schema.json#Capabilities",value:"trusted-core-projection-v1"},{id:"cache.feature.bounded-diagnostics-v1",domain:"cache",family:"sdk2-cache-core-v1",kind:"feature",source:"doc/rfc/sdk2-cache-core-v1.schema.json#Capabilities",value:"bounded-diagnostics-v1"},{id:"terminal.feature.execution-stream-v1",domain:"terminal",family:"terminal-services-v1",kind:"feature",source:"doc/rfc/terminal-services-v1.schema.json#Feature",value:"execution-stream-v1"},{id:"terminal.feature.execution-background-v1",domain:"terminal",family:"terminal-services-v1",kind:"feature",source:"doc/rfc/terminal-services-v1.schema.json#Feature",value:"execution-background-v1"},{id:"terminal.feature.memory-lifecycle-v1",domain:"terminal",family:"terminal-services-v1",kind:"feature",source:"doc/rfc/terminal-services-v1.schema.json#Feature",value:"memory-lifecycle-v1"},{id:"terminal.feature.session-configuration-v1",domain:"terminal",family:"terminal-services-v1",kind:"feature",source:"doc/rfc/terminal-services-v1.schema.json#Feature",value:"session-configuration-v1"},{id:"session.input.version",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"1"},{id:"session.input.text",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"boolean"},{id:"session.input.textBlocks",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"boolean"},{id:"session.input.image",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"false"},{id:"session.input.memoryAck",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"boolean"},{id:"session.input.durableAck",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"false"},{id:"session.input.receiptRetention",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"'current-and-last-turn'"},{id:"session.input.target",domain:"session",family:"agent-session-v1",kind:"capability",source:"packages/kernel/src/query/session-input-delivery.ts#SessionInputCapabilities",value:"SessionInputTarget | null"}],platformApi:[{id:"sdk-cross-repo-contract-v1",doc:"doc/89-SDK跨仓契约v1.md",host:"tansr-api",entries:["/t1/*","/v1/app-tokens","/v1/my-usage"],vendored:"packages/sdk/contract/openapi.json"},{id:"sdk2-cache-v1",doc:"doc/rfc/RFC-SDK2-缓存连续性.md",host:"tansr-api",entries:["/t1/cache/v1/*"],vendored:null},{id:"sdk2-cache-core-v1",doc:"doc/rfc/sdk2-cache-core-v1.md",host:"tansr-api",entries:["/t1/cache/core/v1/*"],vendored:null}]};import{createHash as mx,randomUUID as hx}from"node:crypto";import{Readable as gx}from"node:stream";var ur="idempotency-key",Td="if-match",yx="etag",pf="deadline",vx=/^[\x21-\x7e]{1,128}$/,bx=/^"(0|[1-9][0-9]{0,18})"$/,Sx=/^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:[Zz]|[+-]\d{2}:\d{2})$/,Jo=1024*1024,cv=/^application\/json(?:\s*;.*)?$/i,lf=Object.freeze({perUser:qe.receiptTombstones,total:4096,ttlMs:10*6e4}),wx=new Set(["binding_conflict","stale_revision","revision_conflict"]),kx=Object.freeze(Object.fromEntries(En.operations.flatMap(t=>{let e=t.etagPath,n=t.expectedRevision;return e===null&&n===null?[]:[[t.name,Object.freeze({...e===null?{}:{etag:e},...n===null?{}:{expected:n}})]]}))),xx=Object.freeze(Object.fromEntries(En.families.map(t=>[t.id,t.requestIdPath]))),Rx=new Set(["sdk2-ext-v1","sdk2-archive-recovery-v1","archive-sync-v1","sdk2-cache-v1","sdk2-cache-core-v1","terminal-services-v1","terminal-observation-v1","terminal-profile-v1"]),Ix=En.operations.flatMap(t=>[t.apiPath,...t.aliases].map(e=>({name:t.name,kind:t.kind,family:t.family,method:t.method,pattern:new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/:[A-Za-z]+/g,"[^/]+")}$`)})));function Tx(t,e){return Ix.find(n=>n.method===t&&n.pattern.test(e))}var mf=class{#e=new Map;#n=new Map;#r;#s;constructor(e={}){this.#r={perUser:e.perUser??lf.perUser,total:e.total??lf.total,ttlMs:e.ttlMs??lf.ttlMs},this.#s=e.now??Date.now}get size(){return this.#e.size}#t(e,n){this.#e.delete(e);let i=(this.#n.get(n.owner)??1)-1;i<=0?this.#n.delete(n.owner):this.#n.set(n.owner,i),n.state==="pending"&&(n.state="unretained",n.settle())}#o(){let e=this.#s();for(let[n,i]of this.#e)i.state!=="pending"&&i.expiresAt<=e&&this.#t(n,i)}lookup(e){let n=this.#e.get(e);if(n!==void 0){if(n.state!=="pending"&&n.expiresAt<=this.#s()){this.#t(e,n);return}return n}}begin(e,n,i){this.#o();let o=this.#n.get(n)??0;if(o>=this.#r.perUser){let c=[...this.#e].find(([,l])=>l.owner===n&&l.state!=="pending");if(c===void 0)return null;this.#t(c[0],c[1])}if(this.#e.size>=this.#r.total){let c=[...this.#e].find(([,l])=>l.state!=="pending");if(c===void 0)return null;this.#t(c[0],c[1])}let s=()=>{},a=new Promise(c=>{s=c}),d={owner:n,fingerprint:i,expiresAt:Number.POSITIVE_INFINITY,state:"pending",receipt:null,settled:a,settle:s};return this.#e.set(e,d),this.#n.set(n,o+1),d}complete(e,n,i){if(this.#e.get(e)!==n){n.state==="pending"&&(n.state="unretained",n.settle());return}n.receipt=i,n.state=i===null?"unretained":"stored",n.expiresAt=this.#s()+this.#r.ttlMs,n.settle()}abandon(e,n){this.#e.get(e)===n?this.#t(e,n):n.state==="pending"&&(n.state="unretained",n.settle())}},Ax=new mf;function Vr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Yo(t,e){let n=t.headers[e];return Array.isArray(n)?n.join(", "):n}function Ex(t){return Ii(t)?.requestId??hx()}function hf(t,e){let n=t;for(let i of e){if(!Vr(n))return;n=n[i]}return n}function Cx(t){if(typeof t=="number")return Number.isSafeInteger(t)&&t>=0?`"${t}"`:void 0;if(typeof t=="string"&&/^(0|[1-9][0-9]{0,18})$/.test(t))return`"${t}"`}function _x(t){let e=bx.exec(t.trim());return e===null?null:e[1]}function Px(t){let e=t.trim();if(!Sx.test(e))return null;let n=Date.parse(e.toUpperCase());return Number.isFinite(n)?n:null}function Bi(t,e,n){if(e.destroyed||e.writableEnded)return;let i=Buffer.from(JSON.stringify({contract:yn,traceId:Ex(t),requestId:n.requestId,code:n.code,status:n.status,retryAction:n.retryAction,message:n.message,detail:n.detail}),"utf8");e.writeHead(n.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":i.length,...n.headers??{}}),e.end(i)}var $r=class extends Error{constructor(){super("request body exceeds header processing limit"),this.name="BodyTooLargeError"}};function uf(t){let e=[];for(;t.readableLength>0;){let n=t.read();if(n===null)break;e.push(Buffer.isBuffer(n)?n:Buffer.from(n))}return Buffer.concat(e)}function Mx(t,e){return new Promise((n,i)=>{let o=[],s=0,a=gx.prototype.push,d=t,c=!1,l=()=>{c&&(delete d.push,c=!1)},f=p=>(s+=p.length,s>e?!1:(o.push(p),!0));if(t.complete){let p=uf(t);if(p.length>0&&t.unshift(p),p.length>e){i(new $r);return}n({bytes:p,refeed:v=>{v.equals(p)||(uf(t),v.length>0&&t.unshift(v))}});return}let u=uf(t);if(u.length>0&&!f(u)){i(new $r);return}let m=()=>{l(),t.removeListener("error",h),t.removeListener("close",g),n({bytes:Buffer.concat(o),refeed:p=>{p.length>0&&a.call(t,p),a.call(t,null)}})},h=p=>{l(),i(p)},g=()=>{l(),i(new Error("request closed before body was received"))};t.once("error",h),t.once("close",g),c=!0,d.push=function(v,b){if(v==null)return m(),!1;let R=Buffer.isBuffer(v)?v:v instanceof Uint8Array?Buffer.from(v.buffer,v.byteOffset,v.byteLength):Buffer.from(String(v),b);return f(R)?!0:(l(),t.removeListener("error",h),t.removeListener("close",g),i(new $r),!1)}})}function Ox(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 sv(t){if(t!==void 0)return Array.isArray(t)?t.length>0?String(t[0]):void 0:String(t)}function av(t,e){return t==null?null:Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength):typeof t=="string"?Buffer.from(t,typeof e=="string"?e:"utf8"):null}var Bx=new Set(["x-request-id","date","connection","keep-alive","transfer-encoding","content-length","set-cookie"]);function qx(t){return t<500&&t!==408&&t!==429}function ff(t,e,n){let i=e.writeHead,o=e.write,s=e.end,a="idle",d=null,c=[],l=0,f=!1,u=w=>{f||(f=!0,e.removeListener("close",m),n.onFinal(w))},m=()=>u(null);e.once("close",m);let h=w=>{let T=sv(w["content-type"])??sv(e.getHeader("content-type"));return T!==void 0&&cv.test(T)},g=(w,x)=>{let T=d;T.statusMessage===void 0?i.call(e,w,x):i.call(e,w,T.statusMessage,x)},p=(w,x)=>{let T=d;a="passthrough";let P=Buffer.concat(c);c.length=0,u(null),!e.destroyed&&(g(T.status,T.headers),w?s.call(e,P,x):o.call(e,P,x))},v=w=>{let x=d;a="passthrough";let T=Buffer.concat(c);c.length=0;let P=x.status,W={...x.headers},K;try{K=JSON.parse(T.toString("utf8"))}catch{K=void 0}if(K!==void 0&&(n.ifMatch&&P>=400&&Vr(K)&&K.contract===yn&&Vr(K.detail)&&typeof K.detail.domainCode=="string"&&wx.has(K.detail.domainCode)&&(P=412,T=Buffer.from(JSON.stringify({...K,code:"precondition_failed",status:P,retryAction:"refresh",detail:{...K.detail,reason:"if_match_stale"}}),"utf8"),W["content-length"]=T.length),n.etagPath!==void 0&&P>=200&&P<300)){let D=Cx(hf(K,n.etagPath));D!==void 0&&(W[yx]=D)}if(e.destroyed){u(null);return}if(qx(P)){let D={},J={...Object.fromEntries(Object.entries(e.getHeaders()).map(([S,k])=>[S.toLowerCase(),k])),...W};for(let[S,k]of Object.entries(J))Bx.has(S)||k===void 0||(D[S]=Array.isArray(k)?k.map(String):String(k));u({status:P,headers:D,body:T})}else u(null);g(P,W),s.call(e,T,w)},b=(w,x)=>{let T=av(w,x);T!==null&&(c.push(T),l+=T.length)},R=(w,x=!1)=>(d=w,a=x||h(w.headers)?"buffering":"passthrough",a);e.writeHead=function(...x){if(a==="passthrough")return i.apply(this,x);let T=typeof x[0]=="number"?x[0]:Number(x[0]),P=typeof x[1]=="string"?x[1]:void 0,W=typeof x[1]=="string"?x[2]:x[1],K={status:T,statusMessage:P,headers:Ox(W)};return a==="buffering"?(d=K,this):R(K)==="passthrough"?(u(null),i.apply(this,x)):this},e.write=function(x,T,P){if(a==="idle"&&R({status:e.statusCode,statusMessage:void 0,headers:{}})==="passthrough"&&u(null),a!=="buffering")return o.call(this,x,T,P);let W=typeof T=="function"?T:P;return b(x,T),l>Jo?(p(!1,W),!0):(typeof W=="function"&&process.nextTick(W),!0)},e.end=function(x,T,P){if(a==="idle"){let K=typeof x=="function"||(av(x,T)?.length??0)===0;R({status:e.statusCode,statusMessage:void 0,headers:{}},K)==="passthrough"&&u(null)}if(a!=="buffering")return s.call(this,x,T,P);let W=[x,T,P].find(K=>typeof K=="function");return typeof x!="function"&&b(x,T),l>Jo?p(!0,W):v(W),this}}var dv=new WeakSet;function Dx(t){return{idempotencyKey:Yo(t,ur),ifMatch:Yo(t,Td),deadline:Yo(t,pf)}}function jx(t,e,n,i,o){let s=mx("sha256");return s.update(t),s.update("\0"),s.update(e),s.update("\0"),s.update(Yo(n,"content-type")??""),s.update("\0"),s.update(i??""),s.update("\0"),s.update(o),s.digest("hex")}function lv(t,e,n,i,o,s={}){if(dv.has(t))return!1;dv.add(t);let a=s.receipts??Ax,d=s.now??Date.now,c=t.url??"",l=c.split("?",1)[0],f=Tx(i,l),u=f===void 0?void 0:kx[f.name],m=Dx(t),h=f?.family??pi[n.domain],g=f===void 0?i!=="GET"&&i!=="HEAD":f.kind==="write";if(m.idempotencyKey===void 0&&m.ifMatch===void 0&&m.deadline===void 0)return u?.etag!==void 0&&ff(t,e,{ifMatch:!1,etagPath:u.etag,onFinal:()=>{}}),!1;let p=m.idempotencyKey!==void 0&&vx.test(m.idempotencyKey)?m.idempotencyKey:null,v=async w=>{await o.authenticated(t,e)!==null&&Bi(t,e,{...w,requestId:p})},b=(w,x,T,P=400)=>v({code:"invalid_request",status:P,retryAction:"none",message:T,detail:{reason:w,header:x}}),R=async()=>{if(m.idempotencyKey!==void 0){if(p===null)return b("idempotency_key_invalid",ur,"Idempotency-Key must be 1-128 printable ASCII characters");if(!g)return b("idempotency_key_not_applicable",ur,"Idempotency-Key applies to write operations only")}let w=null;if(m.ifMatch!==void 0){if(w=_x(m.ifMatch),w===null)return b("if_match_invalid",Td,"If-Match must be a single strong entity-tag derived from the resource revision");if(!g||u?.expected===void 0)return b("if_match_not_applicable",Td,"If-Match applies to write operations on versioned resources only")}if(m.deadline!==void 0){let C=Px(m.deadline);if(C===null)return b("deadline_invalid",pf,"deadline must be an RFC-3339 date-time");if(C<=d())return b("deadline_exceeded",pf,"request deadline has already passed",408)}if(p===null&&w===null){u?.etag!==void 0&&ff(t,e,{ifMatch:!1,etagPath:u.etag,onFinal:()=>{}}),o.next();return}let x=null;if(p!==null&&(x=await o.authenticated(t,e),x===null)||t.destroyed||e.destroyed||e.writableEnded)return;let T;try{T=await Mx(t,Jo)}catch(C){return e.destroyed||e.writableEnded||t.destroyed?void 0:C instanceof $r?v({code:"payload_too_large",status:413,retryAction:"none",message:"request body exceeds the header processing limit",detail:{reason:"header_body_limit",limitBytes:Jo},headers:{connection:"close"}}):void 0}if(t.destroyed||e.destroyed||e.writableEnded)return;let P=null,W=null;if(p!==null){let C=jx(i,c,t,m.ifMatch,T.bytes);P=`${x}\0${f?.name??`${i} ${l}`}\0${En.revision}\0${p}`;let F=a.lookup(P);if(F!==void 0){if(F.fingerprint!==C)return Bi(t,e,{code:"conflict",status:409,retryAction:"none",requestId:p,message:"Idempotency-Key was already used for a different request",detail:{domainCode:"request_id_conflict",reason:"idempotency_key_reused",header:ur}});if(F.state==="pending"){let L=()=>{},Q=new Promise(se=>{L=se,e.once("close",L)});try{await Promise.race([F.settled,Q])}finally{e.removeListener("close",L)}if(e.destroyed||e.writableEnded)return}if(F.state==="stored"&&F.receipt!==null){let L=F.receipt,Q=L.status===204||L.status===304;e.writeHead(L.status,{...L.headers,...Q?{}:{"content-length":L.body.length}}),e.end(Q?void 0:L.body);return}return Bi(t,e,{code:"result_unknown",status:503,retryAction:"query-status",requestId:p,message:"the original request with this Idempotency-Key was executed but its receipt was not retained; query its status instead of replaying",detail:{reason:"receipt_not_retained",header:ur}})}if(W=a.begin(P,x,C),W===null)return Bi(t,e,{code:"result_unknown",status:503,retryAction:"query-status",requestId:p,message:"idempotency receipt window is full of in-flight requests; query status before replaying",detail:{reason:"receipt_window_full",header:ur},headers:{"retry-after":"1"}})}let K=()=>{P!==null&&W!==null&&a.abandon(P,W)},D=T.bytes,J=Yo(t,"content-type");if(J!==void 0&&cv.test(J)&&D.length>0&&(p!==null||w!==null)){let C;try{C=JSON.parse(D.toString("utf8"))}catch{C=void 0}if(Vr(C)){let F=!1,L=xx[h]??null;if(p!==null&&L!==null){let Q=L.length===1?C:hf(C,L.slice(0,-1)),se=L[L.length-1];if(Vr(Q)){if(Q[se]===void 0)Q[se]=p,F=!0;else if(Q[se]!==p)return K(),Bi(t,e,{code:"conflict",status:409,retryAction:"none",requestId:p,message:"Idempotency-Key differs from the requestId carried in the body",detail:{domainCode:"request_id_conflict",reason:"idempotency_key_mismatch",header:ur}})}}if(w!==null&&u?.expected!==void 0){let{path:Q,kind:se}=u.expected,O=Q.length===1?C:hf(C,Q.slice(0,-1)),I=Q[Q.length-1],q=se==="integer"?Number(w):w;if(Vr(O)){if(O[I]===void 0)O[I]=q,F=!0;else if(O[I]!==q)return K(),Bi(t,e,{code:"precondition_failed",status:412,retryAction:"refresh",requestId:p,message:"If-Match differs from the expectedRevision carried in the body",detail:{domainCode:"revision_conflict",reason:"if_match_body_mismatch",header:Td}})}}if(F){try{D=Rx.has(h)?Buffer.from(us(C,{maxBytes:Jo})):Buffer.from(JSON.stringify(C),"utf8")}catch{return K(),Bi(t,e,{code:"invalid_request",status:400,retryAction:"none",requestId:p,message:"request body cannot be re-encoded after header mapping",detail:{reason:"header_body_not_canonical"}})}t.headers["content-length"]!==void 0&&(t.headers["content-length"]=String(D.length))}}}if(t.destroyed||e.destroyed||e.writableEnded){K();return}T.refeed(D);let k=P,A=W;ff(t,e,{ifMatch:w!==null,etagPath:u?.etag,onFinal:C=>{k!==null&&A!==null&&a.complete(k,A,C)}}),o.next()};return o.track(R().catch(w=>{if(!(e.destroyed||e.writableEnded)){if(e.headersSent){e.destroy();return}Bi(t,e,{code:"internal_error",status:500,retryAction:"none",requestId:p,message:w instanceof Error?w.message:"request header processing failed",detail:{reason:"header_processing_failed"}})}})),!0}var gf="tansr-session-family",Kr="tansr-closure-id",Ux=/^\/api\/sessions\/([^/]+)\/capabilities$/,Fx=/^\/api\/sessions\/([^/]+)(?:\/|$)/,Lx=En.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 Hx(t,e){return Lx.find(n=>n.method===t&&n.pattern.test(e))?.name}var zx={unauthorized:401,not_found:404,method_not_allowed:405,invalid_request:400,capability_unavailable:404,capacity_exceeded:503,precondition_failed:412,upstream_unavailable:503},Gx={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 fv(t){return En.families.find(e=>e.id===t)}function pv(t){if(t==="discovery")return`sha256:${En.schemaHash}`;let e=fv(pi[t]);return e===void 0?"none":`sha256:${e.sha256}`}function Ad(t,e){t.setHeader("tansr-contract",yn),t.setHeader("tansr-manifest-revision",String(En.revision)),t.setHeader("tansr-domain",e),t.setHeader("tansr-schema-hash",pv(e))}function Wx(t){return Ii(t)?.requestId??Nx()}function yf(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 Cn(t,e,n,i,o={},s={}){let a=s.status??zx[n];yf(e,a,{contract:yn,traceId:Wx(t),requestId:null,code:n,status:a,retryAction:Gx[n],message:i,...s.detail!==void 0?{detail:s.detail}:{}},o)}function uv(t){return t.headers["transfer-encoding"]!==void 0||t.headers["content-length"]!==void 0&&t.headers["content-length"]!=="0"}function mv(t){let{authenticate:e,delegate:n,installed:i,track:o,sessionFamilies:s}=t,a=()=>{let w=t.retryAfterMs?.()??5e3;return{"retry-after":String(Math.max(1,Math.ceil(w/1e3)))}},d=async(w,x)=>{let T;try{T=await e(w,x)}catch(P){if(x.destroyed||x.writableEnded)return null;if(P instanceof Rt)return Cn(w,x,"capacity_exceeded","authentication source unavailable",a()),null;T=null}return w.aborted||x.destroyed||x.writableEnded?null:T===null||typeof T.endUserId!="string"||T.endUserId===""?(Cn(w,x,"unauthorized","authentication required",{"www-authenticate":"Bearer"}),null):T.endUserId},c=()=>{let w={};for(let x of Object.keys(pi)){let T=fv(pi[x]),P=i[x];w[x]={installed:x==="session"?P!==null:P===!0,...x==="session"?{family:{preferred:P,available:s}}:{},contract:pi[x],status:T?.status??"unregistered",schemaHash:pv(x)}}return{contract:yn,manifestRevision:En.revision,schemaHash:`sha256:${En.schemaHash}`,domains:w}},l=w=>{let x=w.headers[gf],T=Array.isArray(x)?x[0]:x;return T===void 0?{family:i.session}:T!=="sdk1"&&T!=="sdk2-offload-v1"?{family:null,error:"invalid"}:s.includes(T)?{family:T}:{family:null,error:"not_installed"}},f=()=>({...En,runtime:{installed:i}}),u=async(w,x,T,P)=>{if(P!=="GET"){if(await d(w,x)===null)return;Cn(w,x,"method_not_allowed",`${P} not allowed`,{allow:"GET"});return}if((w.url??"").includes("?")||uv(w)){if(await d(w,x)===null)return;Cn(w,x,"invalid_request","discovery endpoints accept no query string or body");return}await d(w,x)!==null&&yf(x,200,T===wa?f():c())},m=async(w,x,T,P,W)=>{await d(w,x)!==null&&Cn(w,x,T,P,{},W===void 0?{}:{detail:W})},h=w=>w==="session"?i.session!==null:i[w]===!0,g=async(w,x,T,P)=>{if(t.sessionClosure===void 0||i.session===null){Cn(w,x,"capability_unavailable","session capability closure is not installed on this serve",{},{detail:{reason:"not_installed"}});return}let W;try{W=decodeURIComponent(T)}catch{Cn(w,x,"not_found","no such api resource");return}let K;try{K=await t.sessionClosure(W,P,w)}catch{if(x.destroyed||x.writableEnded)return;Cn(w,x,"upstream_unavailable","capability closure source unavailable",a());return}if(!(w.aborted||x.destroyed||x.writableEnded)){if(K===null){Cn(w,x,"not_found","no such api resource");return}return K}},p=async(w,x,T,P)=>{let W=await d(w,x);if(W===null)return;if(P!=="GET"){Cn(w,x,"method_not_allowed",`${P} not allowed`,{allow:"GET"});return}if((w.url??"").includes("?")||uv(w)){Cn(w,x,"invalid_request","capabilities accept no query string or body");return}let K=await g(w,x,T,W);K!==void 0&&yf(x,200,K,{[Kr]:K.closureId})},v=(w,x,T,P)=>{if(lv(w,x,T,P,{authenticated:d,track:o,next:()=>v(w,x,T,P)}))return;if(ov(w,x,T.domain)==="invalid"){o(m(w,x,"invalid_request",`${Qo} must be ${Id}`,{header:Qo}));return}tv(w,x,T);let W=w.url??"",K=W.indexOf("?");w.url=K<0?T.legacyPathname:`${T.legacyPathname}${W.slice(K)}`,!n(w,x,T.legacyPathname,P)&&o(m(w,x,"capability_unavailable",`${T.domain} does not serve this resource`,{reason:"not_installed"}))},b=async(w,x,T,P,W,K,D)=>{let J=await d(w,x);if(J===null)return;let S=await g(w,x,K,J);if(S===void 0)return;let k=Vy(D,S);if(!k.ok){Cn(w,x,"precondition_failed","capability closure is stale; rediscover before retrying",{[Kr]:k.closureId},{detail:{domainCode:k.code,closureId:k.closureId}});return}let A=Hx(W,P),C=A===void 0?void 0:S.operations[A];if(C==="disabled"||C==="unavailable"){Cn(w,x,"capability_unavailable",`${A} is ${C} for this session`,{[Kr]:S.closureId},{status:C==="disabled"?403:404,detail:{reason:"outside_closure",operation:A,state:C,closureId:S.closureId}});return}v(w,x,T,W)},R=w=>{let x=w.headers[Kr];return Array.isArray(x)?x[0]:x};return(w,x,T,P)=>{if(T!=="/api"&&!T.startsWith("/api/"))return!1;if(T===wa||T===hu)return Ad(x,"discovery"),o(u(w,x,T,P)),!0;let W=Ux.exec(T);if(W!==null)return Ad(x,"discovery"),o(p(w,x,W[1],P)),!0;let K=l(w),D=Vh(T,{offloadSessions:K.family==="sdk2-offload-v1"});if(D===void 0)return Ad(x,"discovery"),o(m(w,x,"not_found","no such api resource")),!0;if(Ad(x,D.domain),!h(D.domain))return o(m(w,x,"capability_unavailable",`${D.domain} is not installed on this serve`,{reason:"not_installed"})),!0;if((D.domain==="session"||D.domain==="execution")&&K.error!==void 0)return o(K.error==="invalid"?m(w,x,"invalid_request",`${gf} must be sdk1 or sdk2-offload-v1`):m(w,x,"capability_unavailable","requested session family is not installed on this serve",{reason:"not_installed",header:gf})),!0;let J=R(w);if(J!==void 0){let S=Fx.exec(T);return S===null||P==="GET"||P==="HEAD"?(o(m(w,x,"invalid_request",`${Kr} applies to session-scoped write operations only`,{header:Kr})),!0):(o(b(w,x,D,T,P,S[1],J)),!0)}return v(w,x,D,P),!0}}var Vx=5e3;async function vf(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 $x(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 Kx(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 hv(t){let{registry:e,installed:n}=t,i=t.timeoutMs??Vx,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=Wi(l),u=AbortSignal.timeout(i),m=null,h=null;if(t.execution!==void 0&&n.execution){let P=await vf(t.execution.options.readPolicy(a,u),u,i);if(P.expiresAt!==void 0&&(!Number.isSafeInteger(P.expiresAt)||P.expiresAt<=o()))throw new Error("policy source expired");m=P.authorizationRevision;try{let W=t.execution.session(a,s).executionBoundary();h={boundaryRevision:W.revision,effectiveTools:W.effectiveTools}}catch{h=null}}let g=null;if(t.archive?.capabilities!==void 0&&n.archive){let P=await vf(t.archive.capabilities(a),u,i);g={epochId:P.operationEpoch.id,capabilities:P.capabilities}}let p=null;if(t.terminal!==void 0&&n.terminal)try{let P=t.terminal.sessionFeatures(a,{sessionContract:f,sessionId:s});p={schemaRevision:t.terminal.capabilities().schemaRevision,features:$y(P)}}catch{p=null}let v=l.inputCapabilities?.(),b=v===void 0?null:Ky(v),R=l.platformAudio,w=R===void 0?null:{speechToText:R.capabilities.speechToText===!0,textToSpeech:R.capabilities.textToSpeech===!0},x=null;t.cache!==void 0&&n.cache&&(x=Kx(await vf(t.cache.capabilities(a),u,i)));let T=e.get(s);return T===void 0||T.handle!==l?null:Wy({installed:n,authorizationRevision:m,session:{family:f,state:$x(T)},execution:h,archive:g,terminal:p,input:b,audio:w,cache:x})}}import{lstatSync as bf,realpathSync as gv}from"node:fs";import Jt from"node:path";var yv=new WeakMap;function Ed(t,e){yv.set(t,e)}function fr(t){return yv.get(t)}var vv=new WeakMap;function Qr(t,e){vv.set(t,e)}function Nn(t){return vv.get(t)}var Sf=new WeakMap;function bv(t,e){if(Sf.has(t))throw new Error("Memory command runner already bound");Sf.set(t,e)}function Sv(t){return Sf.get(t)}function wv(t){let e=t,n=wf(t),i=t.config.management;if(!i||!t.config.host||Gu(t.config.host)===void 0)return n;let o=!1,s=!1,a=!1,d,c,l,f,u=new gr,m=()=>l||(l=(async()=>{if(s)throw new at("source_unavailable");try{await n.verifyAvailable()}catch(v){if(!(v instanceof at)||v.code!=="stale_generation")throw v;let b=e.config.host,R=Gu(b),w=await i.read();if(R===void 0||BigInt(w.deletionGeneration)<=BigInt(R))throw v;if(a&&d===n||!(await n.settleResources({timeoutMs:0})).every(T=>T.status==="completed"))throw new at("busy");let x=await i.createHost({rootDir:b.rootDir,memoryDir:b.memoryDir,...b.provenance===void 0?{}:{provenance:b.provenance}});if(await x.refresh(),s||!e.config.enabled())throw new at("source_unavailable");if(a&&d===n)throw new at("busy");if(await n.retireDeletedSource(),s||!e.config.enabled())throw new at("source_unavailable");x.assertCurrent(),e={...e,config:{...e.config,host:x}},n=wf(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(p,v)=>(await m(),n.searchTool.execute(p,v))},g=async p=>{let v=performance.now(),b=p?.timeoutMs??3e4,R=()=>({...p,timeoutMs:Math.max(0,b-(performance.now()-v))}),w=[];for(;;){let x=await u.settle(R()),T=n,W=[...await T.settleResources(R()),x];if(T===n&&l===void 0||W.some(K=>K.status!=="completed"))return[...w,...W];w.push(...W.filter(K=>K.failureCount>0))}};return{searchTool:h,management:i,assertAvailable:()=>n.assertAvailable(),verifyAvailable:m,executeManagedCommand:async(p,v)=>(await m(),n.executeManagedCommand(p,v)),status:()=>n.status(),start:()=>{o=!0,n.start()},prepare:async p=>{await m();let v=n,b=await v.prepare(p);return d=v,b},onTurnStart:p=>{a=!0,d===n?n.onTurnStart(p):c=[...p]},onTurnEnd:p=>{a=!1,d=void 0,c=void 0,n.onTurnEnd(p)},noteBalanceLow:()=>n.noteBalanceLow(),observeTouched:p=>n.observeTouched(p),compactionObserver:{onCompactionFinished:p=>n.compactionObserver.onCompactionFinished?.(p)},prepareReminders:async p=>{await m(),await n.prepareReminders(p)},drainReminders:()=>n.drainReminders(),drainSelections:()=>n.drainSelections(),pin:async p=>(await m(),n.pin(p)),remember:()=>n.remember(),rememberAndWait:async()=>{await m(),await n.rememberAndWait()},readyForModelChange:async()=>!s&&(await g({timeoutMs:0})).every(p=>p.status==="completed"),close:()=>f??=(async()=>{s=!0,await l?.catch(()=>{}),await n.close()})(),settleResources:g}}function wf(t){let e=t.config;if(!["server-managed","client-managed","developer-managed"].includes(e.kind)||!e.domain.trim()||!Jt.isAbsolute(e.rootDir)||!Jt.isAbsolute(e.memoryDir)||typeof e.enabled!="function"||typeof e.balance!="function")throw new TypeError("Invalid trusted memory domain");if(e.kind!=="server-managed"&&e.host===void 0)throw new TypeError("Managed memory requires a trusted prepared host");if(e.host!==void 0&&(e.host.authority.identity.kind!==e.kind||e.host.authority.identity.domain!==e.domain))throw new TypeError("Memory host identity does not match");if(e.management!==void 0&&(e.host===void 0||e.host.authority!==e.management||e.management.identity.kind!==e.kind||e.management.identity.domain!==e.domain))throw new TypeError("Memory management must share the configured source authority");let n=Jt.resolve(e.rootDir),i=Jt.resolve(e.memoryDir);if(e.host!==void 0&&(e.host.rootDir!==n||e.host.memoryDir!==i))throw new TypeError("Memory host namespace does not match");let o=j=>process.platform==="win32"?j.toLowerCase():j,s=(j,Y)=>o(Y)===o(j)||o(Y).startsWith(o(j+Jt.sep));if(!s(n,i)||o(n)===o(i)||e.host===void 0&&(o(gv(n))!==o(n)||!bf(n).isDirectory()))throw new TypeError("Memory domain requires an explicit real root and child directory");let a=[e.projectAgentsPath,e.userAgentsPath].filter(j=>j!==void 0);if(a.some(j=>!Jt.isAbsolute(j)||!s(n,Jt.resolve(j))||s(i,Jt.resolve(j))))throw new TypeError("Promotion targets must be explicit paths within the trusted root, outside auto-memory");let d=!1,c=!1,l,f=new gr,u=new Set,m=()=>{if(c||!e.enabled())throw new Error("Memory source unavailable");e.host?.assertCurrent()},h=async()=>{m(),await e.host?.refresh(),m()},g=j=>a.some(Y=>o(Jt.resolve(Y))===o(j)),p=(j,Y=!1)=>{if(m(),!Jt.isAbsolute(j))throw new Error("Memory path must be absolute");let oe=Jt.resolve(j);if(!(s(i,oe)||g(oe)||Y&&s(n,oe)&&(s(oe,i)||a.some($e=>s(oe,Jt.resolve($e))))))throw new Error("Memory path outside trusted domain");if(e.host!==void 0)return oe;let je=n;for(let $e of Jt.relative(n,oe).split(Jt.sep).filter(Boolean)){je=Jt.join(je,$e);try{if(bf(je).isSymbolicLink())throw new Error("Memory links are not permitted")}catch(Fe){if(Fe.code!=="ENOENT")throw Fe}}if(o(gv(n))!==o(n))throw new Error("Memory root changed");return oe};if(p(i,!0),e.host===void 0&&!bf(i).isDirectory())throw new TypeError("Memory directory must already exist");let v=e.host?.fs??Xf,b={...v.compareAndWrite===void 0?{}:{compareAndWrite:async(j,Y,oe)=>v.compareAndWrite(p(j),Y,oe)},stat:async j=>v.stat(p(j,!0)),lstat:async j=>v.lstat(p(j,!0)),realpath:async j=>v.realpath(p(j,!0)),readFile:async j=>v.readFile(p(j)),readFilePrefix:async(j,Y)=>v.readFilePrefix(p(j),Y),...v.readFileRange===void 0?{}:{readFileRange:async(j,Y,oe)=>v.readFileRange(p(j),Y,oe)},writeFile:async(j,Y)=>v.writeFile(p(j),Y),appendFile:async(j,Y)=>v.appendFile(p(j),Y),mkdir:async(j,Y)=>v.mkdir(p(j,!0),Y),readdir:async j=>{let Y=await v.readdir(p(j,!0));if(Y.length>500||Y.some(oe=>oe.isSymbolicLink()))throw new Error("Memory directory cannot be admitted");return Y}},R={...e.host?.source,pathStyle:process.platform==="win32"?"win32":"posix",fs:b},w=e.host?.extractionHost??Em(i),x=e.host?.consolidationHost??Cm(i),T=j=>{p(Jt.join(i,j)),p(Jt.join(i,"lock"))},P=new eo({homedir:n,memoryWriteCarveOut:{dirs:[i]}}),W=new Wn;for(let j of[Uc,ro,oo])W.register({...j,execute:async(Y,oe)=>{let Se=Y&&typeof Y=="object"?Y.file_path:void 0;if(typeof Se!="string")return{isError:!0,content:[{t:"text",text:"A memory file path is required."}]};try{return p(Se),await j.execute(Y,{...oe,fs:b,cwd:n})}catch{return{isError:!0,content:[{t:"text",text:"Memory access denied or unavailable."}]}}}});let K=Ci(P,W,{cwd:n}),D={decide:async(j,Y)=>{try{m();let oe=j.args&&typeof j.args=="object"?j.args.file_path:void 0;if(typeof oe!="string")throw new Error("Missing path");return p(oe),g(Jt.resolve(oe))&&["Write","Edit"].includes(j.name)?{decision:"ask",source:"policy",reason:"Memory promotion requires approval"}:await K.decide(j,Y)}catch{return{decision:"deny",source:"policy",reason:"Memory source unavailable or outside scope"}}}},J=()=>{m();let j=t.modelTier(),Y=j.client;return{...j,client:zn({async*stream(oe,Se){await h(),yield*Y.stream(oe,Se)}},Y)}},S=(j,Y)=>{try{e.onObservation?.(j,Y)}catch{}},k=W.names().map(j=>vn(W.get(j))),A={memoryDir:i,cwd:n,modelTier:J,registry:W,tools:k,permissionGate:D,...t.budget===void 0?{}:{budget:t.budget},onUsage:t.onUsage,...t.onDecision?{onDecision:t.onDecision}:{},...t.requestMeasurement?{requestMeasurement:t.requestMeasurement}:{}},C=bm({...A,interactive:!0,sessionId:()=>t.sessionId,balance:e.balance,...e.extraction,host:{pendingInvitesLocation:w.pendingInvitesLocation,readInitialPendingInvites:()=>(T("pending-invites.json"),w.readInitialPendingInvites()),persistPendingInvites:async(j,Y)=>{T("pending-invites.json"),await w.persistPendingInvites(j,Y)},acquireLock:async j=>(T("lock"),w.acquireLock(j)),readIndexSnapshot:async j=>(T("MEMORY.md"),w.readIndexSnapshot(j))},writePlanePreflight:vm(P,i,n),probeWrite:j=>S("write.extract",j),probeInvite:j=>S("invite",j),probeExtraction:j=>S("extraction",j),notifySaved:j=>S("saved",{count:j})}),F=Sm({...A,interactive:!0,sessionId:t.sessionId,balance:e.balance,system:t.system,host:{acquireLock:async j=>(T("lock"),x.acquireLock(j)),readConsolidationMeta:async()=>(T("consolidation.json"),x.readConsolidationMeta()),writeConsolidationMeta:async j=>{T("consolidation.json"),await x.writeConsolidationMeta(j)},readPendingAnchors:async()=>(T("pending-anchors.md"),x.readPendingAnchors()),clearPendingAnchors:async j=>{T("pending-anchors.md"),await x.clearPendingAnchors(j)}},probeWrite:j=>S("write.consolidate",j),notifyConsolidated:j=>S("consolidated",{count:j})}),L=!1,Q=e.projectAgentsPath!==void 0&&e.userAgentsPath!==void 0&&t.askUser!==void 0?wm({...A,sessionId:t.sessionId,system:t.system,history:t.history,projectAgentsPath:e.projectAgentsPath,userAgentsPath:e.userAgentsPath,askUser:t.askUser,notifyReport:j=>S("promotion.report",{text:j}),probePromotion:j=>S("promotion",j),onOutcome:j=>{L=j.kind==="completed"}}):void 0,se=Es({dir:i,roots:[n],source:R}),O=e.recallSelector?Cs({dir:i,source:R,...t.budget===void 0?{}:{budget:t.budget},onBudgetWarning:j=>S("budget.warning",{reason:j}),excludeFiles:["pending-anchors.md"],modelTier:J,onUsage:(j,Y)=>t.onUsage({model:Y.model,provider:Y.provider,usage:j})}):void 0,I=Gp({forceEngine:"js"}),q={source:"local",async search(j,Y){m();let oe=Wp(),Se=[];if(j.kind!==void 0&&j.kind!=="memory")return{hits:Se};for await(let je of I.search({root:i,pattern:Vp(j.query),caseInsensitive:!0,collectLines:!0,contextLines:2,glob:"*.md"},{signal:Y,stats:oe,fs:b})){if(m(),["pending-anchors.md","quarantine.md"].includes(Jt.basename(je.abs)))continue;let $e=je.lines.slice(0,30);if(Se.push({kind:"memory",key:je.rel,title:je.rel,occurredAt:"",lineStart:$e[0]?.line??1,lineEnd:$e.at(-1)?.line??1,score:1,text:$e.map(Fe=>Fe.text).join(`
|
|
29
|
-
`).slice(0,4096)}),Se.length>=j.limit)break}return{hits:Se,truncated:oe.limitHit||Se.length>=j.limit}}},H=$p({projectKey:e.domain,searcher:q,enabled:()=>!c&&e.enabled()});H.description="Search the authorized memory source. Returns bounded memory snippets from the configured domain only; never falls back to host files.";let N=new fp,ie=()=>{if(m(),d)throw new Error("Memory is closing")},U=()=>{if(ie(),!Q)throw new Error("Memory promotion requires explicit targets and approval bridge");if(Q.promotionInFlight())throw new Error("Memory busy");L=!1,Q.run()},ce=j=>{let Y=(async()=>{ie(),T("lock");let oe=await w.acquireLock({staleMs:6e5});if(!oe)throw new Error("Memory busy");try{return ie(),await j()}finally{let Se=oe.release();f.track(Se,"tool_executor"),await Se}})();return f.track(Y,"tool_executor",{reportFailure:!1}),Y},le=async j=>(await Promise.all([f.settle(j),C.settleResources(j),F.settleResources(j),Q?.settleResources(j),se.settleResources?.(j),O?.settleResources?.(j)])).filter(oe=>oe!==void 0),re=(j=!1)=>l??=(async()=>{d=!0,await Promise.all([...u].map(oe=>oe.close())),await f.settle({timeoutMs:1/0}),!j&&e.enabled()&&C.handleSessionClose(),await Promise.all([C.drain(),F.drain(),Q?.drain()]),se.dispose?.(),O?.dispose();let Y=await le({timeoutMs:1/0});if(c=!0,Y.some(oe=>oe.status!=="completed"))throw new Error("Memory cleanup did not complete")})();return{searchTool:H,assertAvailable:m,verifyAvailable:h,...e.management===void 0?{}:{management:e.management},executeManagedCommand:(j,Y)=>{let oe=(async()=>{if(ie(),e.management===void 0||e.host===void 0)throw new Error("Memory management is not configured");let Se=[],je=await e.management.execute(j,async $e=>{ie(),Y?.signal?.throwIfAborted();let Fe=wf({...t,config:{...e,host:$e,rootDir:$e.rootDir,memoryDir:$e.memoryDir,onObservation:(kt,ze)=>Se.push({kind:kt,value:ze})}});u.add(Fe);let ft=()=>{f.track(Fe.close(),"tool_executor")};Y?.signal?.addEventListener("abort",ft,{once:!0});try{Y?.signal?.throwIfAborted(),j.command.kind==="pin"?await Fe.pin(j.command.text):j.command.kind==="remember"&&await Fe.rememberAndWait(),Y?.signal?.throwIfAborted()}finally{try{await Fe.close()}finally{Y?.signal?.removeEventListener("abort",ft),u.delete(Fe)}}},{rootDir:n,memoryDir:i,...e.host.provenance===void 0?{}:{provenance:e.host.provenance}},{...Y?.signal===void 0?{}:{signal:Y.signal},beforeCommit:async()=>{ie(),await Y?.beforeCommit?.(),ie()}});if(je.status==="committed"){se.invalidate?.({dir:i,roots:[n],source:R}),O?.invalidateSource({dir:i,source:R});for(let $e of Se)S($e.kind,$e.value)}return S("management",{operationId:j.operationId,status:je.status,durable:je.durable}),je})();return f.track(oe,"tool_executor",{reportFailure:!1}),oe},status:()=>({kind:e.kind,domain:e.domain,enabled:!c&&e.enabled(),extractionInFlight:C.extractionInFlight(),consolidationInFlight:F.consolidationInFlight(),promotionInFlight:Q?.promotionInFlight()??!1,closing:d}),start:()=>{m(),F.start()},prepare:async j=>{m(),j.throwIfAborted(),await h();let Y=await wp(i,{source:R,signal:j});return m(),[{text:Sp,cacheable:!0},...Y.content===null?[]:[{text:`${bp}
|
|
30
|
-
|
|
31
|
-
${Y.content}`,cacheable:!1}]]},onTurnStart:j=>{C.noteTurnStart(),e.enabled()&&O?.prefetch(j.join(`
|
|
32
|
-
`))},onTurnEnd:j=>{!e.enabled()||d||(C.noteInviteParse(km(xm(j.history)),j.turn),C.handleTurnEnd(j))},noteBalanceLow:()=>{C.noteBalanceLow(),F.noteBalanceLow()},observeTouched:j=>{e.enabled()&&se.observeTouched(j)},compactionObserver:{onCompactionFinished:j=>{j.agentId===void 0&&j.mechanism===void 0&&j.outcome?.ok===!0&&C.noteCompactionSummary(j.outcome.summaryText)}},prepareReminders:async j=>{m(),await se.prepareReminders?.(j)},drainReminders:()=>e.enabled()?se.drainReminderEntries?.()??[]:[],drainSelections:()=>e.enabled()?O?.drainReminderEntries?.()??[]:[],pin:async j=>ce(async()=>{if(Rp(j).length>0)throw new Error("Memory pin contains protected secret material");let Y=N.pin(j,0,oe=>oe.length);if(!Y)throw new Error("Invalid memory pin");return T("pending-anchors.md"),{added:e.host===void 0?await Tm(i,[Y.entry]):await e.host.appendPendingAnchors([Y.entry])}}),remember:U,rememberAndWait:async()=>{U();let j=await Q.settleResources({timeoutMs:1/0});if(m(),j.status!=="completed"||!L)throw new Error("Memory promotion did not complete")},readyForModelChange:async()=>!d&&(await le({timeoutMs:0})).every(j=>j.status==="completed"),close:()=>re(),retireDeletedSource:()=>re(!0),settleResources:le}}var qi=Object.freeze(["execution-stream-v1","execution-background-v1","memory-lifecycle-v1","session-configuration-v1"]),Di=Object.freeze({maxControlBytes:262144,maxBlockBytes:16384,maxBatchBytes:65536,maxPendingBytes:2097152,maxRetainedBytes:8388608}),Le=class extends Error{constructor(n){super(n);this.code=n;this.name="TerminalCapabilityError"}code};function Xn(t){throw new Le(t)}function kf(t,e){try{return yt(t,e)}catch{return Xn("invalid_request")}}function Qx(t){let e=new Set(t.map(n=>n.feature));return(e.size!==qi.length||qi.some(n=>!e.has(n))||t.some(n=>n.installed&&!n.supported))&&Xn("invalid_request"),t}function Jx(t){(t.maxBlockBytes>t.maxBatchBytes||t.maxBatchBytes>t.maxPendingBytes||t.maxBatchBytes>t.maxRetainedBytes)&&Xn("invalid_request")}function Xo(t){let e=kf("CapabilitiesResponse",{...t,contract:"terminal-services-v1",schemaRevision:Tg,schemaSha256:Ig});return Qx(e.features),Jx(e.limits),e}function Cd(t,e){let n=kf("BindingRequest",t),i=Xo({sessionContracts:[e.session.sessionContract],features:e.features,limits:e.limits});(n.required.some(d=>n.optional.includes(d))||n.required.length+n.optional.length===0)&&Xn("invalid_request"),me(n.session)!==me(e.session)&&Xn("not_found"),me(n.executionBinding)!==me(e.executionBinding)&&Xn("stale_generation");let s=[],a=[];for(let d of[...n.required,...n.optional]){let c=i.features.find(l=>l.feature===d);if(!c.supported||!c.installed){n.required.includes(d)&&Xn("unsupported_capability"),a.push(c);continue}c.authorization==="denied"&&Xn("forbidden"),(c.authorization==="unconfirmed"||c.device==="unconfirmed")&&Xn("capability_unconfirmed"),c.device==="unavailable"&&Xn("source_unavailable"),(d==="execution-stream-v1"||d==="execution-background-v1")&&e.executionBinding===null&&Xn("stale_generation"),s.push(d)}return kf("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 kv}from"node:crypto";var xv=9223372036854775807n,Yx=65536,Rv=8*1024*1024,Iv=4096,Zo=class extends Error{constructor(n){super(n);this.code=n;this.name="TerminalOutputError"}code};function mn(t){throw new Zo(t)}function xf(t,e){try{return yt(t,e)}catch{return mn("invalid_request")}}function Xx(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 Zx(t,e){return t.lastSeq===e.lastSeq&&t.totalBytes===e.totalBytes&&t.payloadDigest===e.payloadDigest&&t.truncated===e.truncated}var _d=class{#e;#n;#r;#s=new Map;#t=new Map;#o=0;#i=0n;#a=0n;#c=kv("sha256");#d=null;#f=!1;constructor(e,n={}){let i=xf("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??Rv,this.#r=n.maxRetainedBlocks??Iv,(!Number.isSafeInteger(this.#n)||this.#n<1||this.#n>Rv||!Number.isSafeInteger(this.#r)||this.#r<1||this.#r>Iv)&&mn("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=xf("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)&&mn("binding_conflict"),n.blocks.reduce((m,h)=>m+h.byteLength,0)>Yx&&mn("payload_too_large");let o=new Map(this.#s),s=new Map(this.#t),a=this.#c.copy(),d=this.#i,c=this.#a,l=this.#o,f=this.#d,u=this.#f;for(let m of n.blocks){let h=Buffer.from(m.base64,"base64");(h.toString("base64")!==m.base64||h.length!==m.byteLength||kv("sha256").update(h).digest("hex")!==m.payloadDigest)&&mn("integrity_mismatch");let g=BigInt(m.seq);if(g<d){let b=o.get(g);b||mn("output_gap"),Xx(b,m)||mn("revision_conflict");continue}f&&mn("revision_conflict"),g!==d&&mn("output_gap"),BigInt(m.byteOffset)!==c&&mn("integrity_mismatch");let p=s.get(m.channel);p!==void 0&&p!==m.encoding&&mn("revision_conflict"),s.set(m.channel,m.encoding);let v=c+BigInt(h.length);(d>xv||v>xv)&&mn("capacity_exceeded"),a.update(h),o.set(g,Object.freeze({...m})),d++,c=v,l+=h.length}for(n.seal&&(f?Zx(f,n.seal)||mn("revision_conflict"):((n.seal.lastSeq!==(d?String(d-1n):null)||n.seal.totalBytes!==String(c)||n.seal.payloadDigest!==a.copy().digest("hex"))&&mn("integrity_mismatch"),f=Object.freeze({...n.seal})));o.size>this.#r||l>this.#n;){let m=o.entries().next().value;o.delete(m[0]),l-=m[1].byteLength,u=!0}return this.#s=o,this.#t=s,this.#c=a,this.#i=d,this.#a=c,this.#o=l,this.#d=f,this.#f=u,this.status()}observe(e=null){let n=e===null?-1n:BigInt(xf("Sequence",e));(n>=this.#i||n+1n<(this.#s.keys().next().value??this.#i))&&mn("output_gap");let i=Object.freeze([...this.#s].filter(([o])=>o>n).map(([,o])=>o));return Object.freeze({blocks:i,status:this.status()})}};function Zn(t,e){return me(t)===me(e)}function Pd(t){let e=t.request;if(e.operation==="process.exec")return e.args.maxOutputBytes;try{let n=Mr(e);return n.action==="exec"?n.maxOutputBytes:void 0}catch{return}}function et(t){throw new Le(t)}function Un(t,e){try{return yt(t,e)}catch{return et("invalid_request")}}function Fn(t,e){let n=t??e;return(!Number.isSafeInteger(n)||n<1)&&et("invalid_request"),n}function es(t,e){return JSON.stringify([t,e.sessionContract,e.sessionId])}function Md(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 ts(t){let e=t?.code;return["forbidden","stale_generation","source_unavailable","capacity_exceeded","binding_conflict","output_gap"].includes(e??"")?e:"source_unavailable"}var Od=class{#e;#n;#r=new Map;#s=new WeakSet;#t=new Map;#o=new Set;#i;#a;#c;#d;#f;#m;#p;#w;#v;#k;#y;#B;#E;#z=0;#S=0;#g=0n;#N=!1;constructor(e){this.#e=e.host,this.#n=e,this.#a=Fn(e.maxBindings,256),this.#c=Fn(e.maxOperations,256),this.#d=Fn(e.maxOperationsPerSession,64),this.#f=Fn(e.maxSubscriptions,64),this.#m=Fn(e.maxSubscriptionsPerSession,8),this.#p=Fn(e.maxSubscriptionsPerExecutor,8),this.#w=Fn(e.maxRetainedBytes,64*1048576),this.#v=Fn(e.maxRetainedBlocks,16384),this.#k=Fn(e.maxRetainedBytesPerSession,Math.min(this.#w,16*1048576)),this.#y=Fn(e.maxRetainedBlocksPerSession,Math.min(this.#v,8192)),this.#B=Fn(e.maxRetainedBytesPerOperation,Di.maxRetainedBytes),this.#E=Fn(e.retentionMs,3e5),(this.#B>Di.maxRetainedBytes||this.#B>this.#k||this.#k>this.#w||this.#y>this.#v)&&et("invalid_request"),this.capabilities(),this.#i=this.#e.observeChanges(n=>this.#D(n))}capabilities(){return Xo({sessionContracts:this.#n.sessionContracts,limits:Di,features:this.#J("unconfirmed","unconfirmed")})}#J(e,n){return qi.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&&et("source_unavailable")}async#j(e,n,i){this.#U(),i.throwIfAborted();let o=Un("SessionReference",n);this.#n.sessionContracts.includes(o.sessionContract)||et("not_found");let s=await this.#n.resolveSession(e,o);return i.throwIfAborted(),this.#U(),s!==this.#e.session(e,o.sessionId)&&et("not_found"),await s.refresh(i,!1),i.throwIfAborted(),s!==this.#e.session(e,o.sessionId)&&et("source_unavailable"),s}#C(e,n,i=!0,o=!0){this.#U();let s=this.#r.get(es(e,n));(!s||!(s.response.accepted.includes("execution-stream-v1")||!o&&s.response.accepted.includes("execution-background-v1")))&&et("unsupported_capability");let a=this.#e.session(e,n.sessionId),d=s.response.executionBinding?.target;return(a!==s.session||!d||!Zn(a.binding,s.response.executionBinding)||a.policy.authorizationRevision!==s.response.scope.authorizationRevision)&&et("stale_generation"),this.#e.connection(e,d.executorId,d.connectionId),i&&!a.available("Shell")&&et("forbidden"),s}#q(e,n){!e.controller&&e.executorId!==n.response.executionBinding.target.executorId&&et("forbidden")}async bind(e,n,i,o=new AbortController().signal){n.controller||et("forbidden");let s=Un("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=Cd(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:Di}),f=es(e,l.session),u=this.#r.get(f);return!u&&this.#r.size>=this.#a&&et("capacity_exceeded"),u&&(!Zn(u.response.scope,l.scope)||!Zn(u.response.executionBinding,l.executionBinding)||!Zn(u.response.accepted,l.accepted))&&this.#A(f,"stale_generation"),a.configureBackground(l.accepted.includes("execution-background-v1")),this.#r.set(f,{user:e,response:Un("BindingResponse",l),session:a}),this.#e.options.shellSandbox===!0&&!this.#s.has(a)&&(a.attachShellOutputReader((m,h)=>this.readCompletedOutput(e,l.session,m,h)),this.#s.add(a)),Un("BindingResponse",l)}checkExecutor(e,n,i,o){this.#U(),n.executorId!==i&&et("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)||et("unsupported_capability")}async#I(e,n,i,o,s,a=!0){i=Un("SessionReference",i);let d=Un("OperationReference",o),c=await this.#j(e,i,s),l=this.#C(e,i,a,a);this.#q(n,l);let f=await c.readOperation(d.operationId);return s.throwIfAborted(),this.#C(e,i,a,a),this.#q(n,l),(f.digest!==d.requestDigest||!Zn(f.binding,l.response.executionBinding)||!Zn(f.scope,l.response.scope))&&et("stale_generation"),a&&Pd(f)===void 0&&et("unsupported_capability"),!a&&!c.operationAvailable(f)&&et("forbidden"),{binding:l,operation:f}}async executionState(e,n,i,o,s,a,d=new AbortController().signal){n.executorId!==i&&et("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)&&et("stale_generation");let l=await c.binding.session.reconcileStatus(c.operation.operationId);return d.throwIfAborted(),this.#e.connection(e,i,o),this.#C(e,c.binding.response.session,!1,!1),(!Zn(l.operation,c.operation)||!c.binding.session.operationAvailable(c.operation))&&et("stale_generation"),{contract:"terminal-services-v1",session:{...c.binding.response.session},execution:JSON.parse(JSON.stringify(l))}}#u(e,n){return JSON.stringify([es(e.user,e.response.session),n])}async readCompletedOutput(e,n,i,o){let s={operationId:i.operationId,requestDigest:i.digest},a=new AbortController,d=AbortSignal.any([o,a.signal]),c=setTimeout(()=>a.abort(),1e4);c.unref();let l,f,u,m=new Promise((p,v)=>{f=p,u=v}),h=()=>u(new Le("source_unavailable"));d.addEventListener("abort",h,{once:!0}),m.catch(()=>{});let g=()=>{try{d.throwIfAborted();let p=this.#C(e,n),v=this.#t.get(this.#u(p,i.operationId));v?.window||et("source_unavailable");let b=v.window.status();if((b.state==="gap"||b.state==="truncated"||b.state==="unavailable")&&et("output_gap"),b.state!=="complete")return;let R=Pd(i);(R===void 0||!b.seal||b.seal.truncated||BigInt(b.seal.totalBytes)>BigInt(R))&&et("integrity_mismatch");let w=v.window.observe(null).blocks,x=[],T=[];for(let D of w)(D.channel==="stdout"?x:T).push(Buffer.from(D.base64,"base64"));let P=Buffer.concat(x),W=Buffer.concat(T);BigInt(P.length+W.length)!==BigInt(b.seal.totalBytes)&&et("integrity_mismatch");let K=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});f({stdout:K.decode(P),stderr:K.decode(W)})}catch(p){u(p)}};try{let p=await this.#I(e,{controller:!0},n,s,d);Zn(p.operation,i)||et("integrity_mismatch"),l=await this.subscribeOutput(e,{controller:!0},n,s,null,{event:b=>{b.type==="output.status"&&g()},close:b=>u(new Le(b))},d),g();let v=await m;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=Un("SessionReference",i);o!==void 0&&Un("LegacyId",o);let d=await this.#j(e,a,s),c=this.#C(e,a);return this.#q(n,c),d.readOutputCorrelations(o).filter(l=>Zn(l.binding,c.response.executionBinding)).map(l=>Un("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=Un("OutputBatchRequest",i);n.executorId!==s.executorId&&et("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)&&et("stale_generation");let c=Pd(d);c===void 0&&et("unsupported_capability");let l=BigInt(c);(s.blocks.some(b=>BigInt(b.byteOffset)+BigInt(b.byteLength)>l)||s.seal&&BigInt(s.seal.totalBytes)>l)&&et("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||et("source_unavailable");let m=u.window.receive(s),h=m.retainedFrom===null?m.acceptedThrough:m.retainedFrom==="0"?null:String(BigInt(m.retainedFrom)-1n),g=u.window.observe(h).blocks;this.#z-=u.retainedBytes,this.#S-=u.retainedBlocks,u.retainedBytes=g.reduce((b,R)=>b+R.byteLength,0),u.retainedBlocks=g.length,this.#z+=u.retainedBytes,this.#S+=u.retainedBlocks,u.status=m,this.#t.delete(f),this.#t.set(f,u);let p=0,v=0;for(let b of this.#t.values())b.bindingKey===u.bindingKey&&(p+=b.retainedBytes,v+=b.retainedBlocks);for(let[b,R]of this.#t){if(p<=this.#k&&v<=this.#y)break;b!==f&&R.bindingKey===u.bindingKey&&R.window&&(p-=R.retainedBytes,v-=R.retainedBlocks,this.#_(R))}for(let[b,R]of this.#t){if(this.#z<=this.#w&&this.#S<=this.#v)break;b!==f&&R.window&&this.#_(R)}(v>this.#y||this.#S>this.#v)&&this.#_(u);for(let b of this.#o)b.kind==="output"&&b.bindingKey===u.bindingKey&&b.reference?.operationId===d.operationId&&this.#ne(b,u);return u.status}async outputStatus(e,n,i,o,s=new AbortController().signal){let a=await this.#I(e,n,i,o,s);return this.#T(),this.#t.get(this.#u(a.binding,a.operation.operationId))?.status??Md({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&&Un("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??Md({operationId:d.operation.operationId,requestDigest:d.operation.digest})})}#T(){for(let[e,n]of this.#t)n.expiresAt<=this.#e.now()&&(this.#_(n),this.#t.delete(e))}#_(e){this.#z-=e.retainedBytes,this.#S-=e.retainedBlocks,e.retainedBytes=0,e.retainedBlocks=0,e.window=null,e.status=Md(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(Pd(n)===void 0||!Zn(n.binding,e.response.executionBinding)||!Zn(n.scope,e.response.scope))return;let i=this.#u(e,n.operationId);if(this.#t.has(i))return;this.#T();let o=es(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 _d({session:e.response.session,operation:s,executorId:n.binding.target.executorId,connectionId:n.binding.target.connectionId},{maxRetainedBytes:this.#B});this.#t.set(i,{bindingKey:o,reference:s,window:a,status:a.status(),retainedBytes:0,retainedBlocks:0,expiresAt:Date.parse(n.expiresAt)+this.#E})}#P(e,n){if(!e.closed)try{e.listener.event(n)}catch{this.#V(e,"source_unavailable")}}#Q(e,n,i=null){if(this.#g>9223372036854775807n){this.#V(e,"capacity_exceeded");return}this.#P(e,Object.freeze({contract:"terminal-services-v1",eventId:String(this.#g++),type:n,executorId:e.executorId,connectionId:e.connectionId,operation:i?Object.freeze({operationId:i.operationId,requestDigest:i.digest}):null}))}#ne(e,n,i=!1){try{let o=n.window?.observe(e.afterSeq),s=e.listener;if(i&&s.replay){let a=o?.blocks??[],d=n.reference,c=n.status;a.length&&(e.afterSeq=a.at(-1).seq),s.replay((function*(){for(let l of a)yield Object.freeze({contract:"terminal-services-v1",type:"output.block",operation:d,block:l});yield Object.freeze({contract:"terminal-services-v1",type:"output.status",status:c})})());return}for(let a of o?.blocks??[]){if(this.#P(e,Object.freeze({contract:"terminal-services-v1",type:"output.block",operation:n.reference,block:a})),e.closed)return;e.afterSeq=a.seq}this.#P(e,Object.freeze({contract:"terminal-services-v1",type:"output.status",status:n.status}))}catch(o){this.#V(e,ts(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&&et("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||et("stale_generation"),this.#q(n,s)}}catch(s){throw this.#V(e,ts(s)),s}e.authority={...n};let o=async()=>{let s=i?AbortSignal.any([e.stop.signal,e.signal,i]):AbortSignal.any([e.stop.signal,e.signal]);if(e.kind==="executor"){this.checkExecutor(e.user,e.authority,e.executorId,e.connectionId);for(let a of this.#r.values())a.user===e.user&&a.response.executionBinding?.target.executorId===e.executorId&&a.response.executionBinding.target.connectionId===e.connectionId&&a.response.accepted.includes("execution-stream-v1")&&(await this.#j(e.user,a.response.session,s),this.#C(e.user,a.response.session,!1));this.checkExecutor(e.user,e.authority,e.executorId,e.connectionId)}else{let a=this.#r.get(e.bindingKey);a||et("stale_generation"),await this.#I(e.user,e.authority,a.response.session,e.reference,s),this.#q(e.authority,a)}s.throwIfAborted(),e.closed&&et("source_unavailable"),this.#F(e)};return e.checking||(e.checking=o().catch(s=>{throw this.#V(e,ts(s)),s}).finally(()=>{e.checking=void 0})),e.checking}#ee(e){return(this.#o.size>=this.#f||[...this.#o].filter(n=>n.user===e.user&&n.executorId===e.executorId&&n.connectionId===e.connectionId).length>=this.#p||e.bindingKey&&[...this.#o].filter(n=>n.bindingKey===e.bindingKey).length>=this.#m)&&et("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&&Un("Sequence",s),this.#T();let f=l.response.executionBinding.target,u={kind:"output",user:e,authority:{...n},executorId:f.executorId,connectionId:f.connectionId,bindingKey:es(e,i),reference:Object.freeze({...o}),afterSeq:s,listener:a,signal:d,stop:new AbortController,closed:!1,abort:()=>this.#V(u)},m=this.#ee(u),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:Md(o)})),m}#A(e,n){this.#r.get(e)?.session.configureBackground(!1),this.#r.delete(e);for(let[i,o]of this.#t)o.bindingKey===e&&(this.#z-=o.retainedBytes,this.#S-=o.retainedBlocks,this.#t.delete(i));for(let i of this.#o)i.bindingKey===e&&this.#V(i,n)}#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.#C(i.user,i.response.session,!1,!1)}catch(o){this.#A(n,ts(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||et("stale_generation"),this.#C(n.user,i.response.session,!1),this.#q(n.authority,i)}this.#F(n)}catch(i){this.#V(n,ts(i));continue}n.kind!=="executor"||!e.operation||e.operation.binding.target.executorId!==n.executorId||e.operation.binding.target.connectionId!==n.connectionId||(e.kind==="operation-available"?this.#Q(n,"operations-available",e.operation):e.kind==="operation-cancelled"?this.#Q(n,"operation-cancelled",e.operation):e.kind==="operation-removed"&&this.#Q(n,"reconcile-required",e.operation))}}}close(){if(!this.#N){this.#N=!0,this.#i();for(let e of this.#o)this.#V(e,"source_unavailable");for(let e of this.#r.values())e.session.configureBackground(!1);this.#t.clear(),this.#r.clear(),this.#z=0,this.#S=0}}};function Tv(t){let e=new Map,n=new Map,i=!1;function o(u,m){if(i)throw new Le("source_unavailable");if(!t.families.has(m.sessionContract))throw new Le("unsupported_capability");let h=t.registry.get(m.sessionId);if(!h||h.handle.endUserId!==u||Wi(h.handle)!==m.sessionContract)throw new Le("not_found");if(h.ended)throw new Le("stale_generation");return h.handle}function s(u,m){if(i)throw new Le("source_unavailable");if(!t.families.has(m.sessionContract))throw new Le("unsupported_capability");let h=t.registry.get(m.sessionId);if(!h||h.handle.endUserId!==u||Wi(h.handle)!==m.sessionContract)throw new Le("not_found");return{handle:h.handle,registry:t.registry}}function a(u,m,h){if(u.endUserId!==m)throw new Le("forbidden");let g=Nn(h)?.management?.identity;if(g&&(g.applicationScopeId!==u.applicationScopeId||g.endUserId!==u.endUserId))throw new Le("forbidden");return u}function d(u,m,h,g){if(!t.scopeFor)throw new Le("capability_unconfirmed");g.throwIfAborted();let p=t.scopeFor({endUserId:u,...m}),v;try{v=yt("Scope",p)}catch{throw new Le("capability_unconfirmed")}return g.throwIfAborted(),a(v,u,h)}function c(u,m,h,g){let p=d(u,m,h,g);if(o(u,m)!==h)throw new Le("stale_generation");return p}function l(u){return qi.map(m=>{let h=m==="session-configuration-v1"?u.configuration?.()!==void 0&&u.configure!==void 0:m==="memory-lifecycle-v1"&&Nn(u)?.management!==void 0;return{feature:m,supported:h,installed:h,authorization:h?"allowed":"unconfirmed",device:h?"not-required":"unconfirmed"}})}let f=new Map;for(let[u,m]of t.families){if(m.execution&&m.transactionalExecution)throw new TypeError("Conflicting terminal execution backends");let h=m.execution??m.transactionalExecution;if(!h)continue;e.set(u,h);let g=(p,v)=>{let b=o(p,{sessionContract:u,sessionId:v.sessionId}),R="unavailable";if(v.binding)try{h.connection(p,v.binding.target.executorId,v.binding.target.connectionId),R="available"}catch{}let w=fr(b),x=v.deviceTools().some(T=>v.available(T.name))||w?.capability()===!0;return qi.map(T=>{let P=T==="execution-stream-v1"||T==="execution-background-v1"&&v.backgroundSupported()||T==="memory-lifecycle-v1"&&(w!==void 0||Nn(b)?.management!==void 0)||T==="session-configuration-v1"&&b.configuration?.()!==void 0&&b.configure!==void 0;return{feature:T,supported:P,installed:P,authorization:T==="execution-stream-v1"?x?"allowed":"denied":T==="execution-background-v1"?v.available("Shell")?"allowed":"denied":T==="memory-lifecycle-v1"&&w?w.capability()?"allowed":"unconfirmed":P?"allowed":"unconfirmed",device:T==="execution-stream-v1"||T==="execution-background-v1"||T==="memory-lifecycle-v1"&&w?R:P?"not-required":"unconfirmed"}})};f.set(u,g),n.set(u,new Od({host:h,sessionContracts:[u],resolveSession(p,v){return o(p,v),h.session(p,v.sessionId)},sessionFeatures:g}))}return{resolve:o,resolveObservation:s,sessionFeatures(u,m){let h=o(u,m),g=e.get(m.sessionContract),p=f.get(m.sessionContract);return!g||!p?l(h):p(u,g.session(u,m.sessionId))},async checkObservation(u,m,h){h.throwIfAborted();let{handle:g}=s(u,m),p=()=>{if(h.throwIfAborted(),s(u,m).handle!==g)throw new Le("stale_generation");!t.registry.get(m.sessionId).ended&&g.status()!=="ended"&&g.owner?.assertCurrent()};if(p(),t.filterObservationReads&&!await t.filterObservationReads(u,m))throw new Le("not_found");p();let v=e.get(m.sessionContract);if(v){let b=await v.options.readPolicy(u,h);if(p(),b.expiresAt!==void 0&&(!Number.isSafeInteger(b.expiresAt)||b.expiresAt<=v.now()))throw new Le("source_unavailable");let R;try{R=yt("Scope",{applicationScopeId:v.options.applicationScopeId,endUserId:u,authorizationRevision:b.authorizationRevision})}catch{throw new Le("capability_unconfirmed")}a(R,u,g);let w=v.sessions.get(m.sessionId);if(w&&(w.user!==u||BigInt(R.authorizationRevision)<BigInt(w.policy.authorizationRevision)))throw new Le("stale_generation")}else d(u,m,g,h);if(p(),t.filterObservationReads&&!await t.filterObservationReads(u,m))throw new Le("not_found");p()},async check(u,m,h){let g=o(u,m),p=e.get(m.sessionContract);if(p?await p.session(u,m.sessionId).refresh(h,!1):(await g.owner?.assertCurrent(),c(u,m,g,h)),h.throwIfAborted(),g!==o(u,m))throw new Le("stale_generation")},async bindControl(u,m,h,g){if(!m.controller)throw new Le("forbidden");if(!t.scopeFor||h.executionBinding!==null)throw new Le("capability_unconfirmed");let p=o(u,h.session);await p.owner?.assertCurrent(),g.throwIfAborted();let v=c(u,h.session,p,g);return Cd(h,{session:h.session,scope:v,executionBinding:null,features:l(p),limits:Di})},serviceFor:u=>n.get(u),async authorize(u,m,h,g){if(i)throw new Le("source_unavailable");if(!t.families.has(g))throw new Le("unsupported_capability");let p=e.get(g);return p?Ku(p,u,m,h):{controller:!0}},capabilities(){let u=qi.map(m=>({feature:m,supported:(m==="execution-stream-v1"||m==="execution-background-v1")&&n.size>0||(m==="session-configuration-v1"||m==="memory-lifecycle-v1")&&[...t.families.values()].some(h=>h.terminalCapabilities?.includes(m)),installed:(m==="execution-stream-v1"||m==="execution-background-v1")&&n.size>0||(m==="session-configuration-v1"||m==="memory-lifecycle-v1")&&[...t.families.values()].some(h=>h.terminalCapabilities?.includes(m)),authorization:"unconfirmed",device:"unconfirmed"}));return Xo({sessionContracts:[...t.families.keys()],features:u,limits:Di})},close(){if(!i){i=!0;for(let u of n.values())u.close();n.clear(),e.clear()}}}}import{randomUUID as eR}from"node:crypto";var Av="terminal-services-v1",ns=262144,tR=128;function Pt(t){throw new Le(t)}function Mt(t,e){try{return yt(t,e)}catch{return Pt("invalid_request")}}function di(t,e,n=[]){let i=new URL(t.url??"/","http://serve.invalid").searchParams;return[...i.keys()].some(o=>![...e,...n].includes(o)||i.getAll(o).length!==1)&&Pt("invalid_request"),e.includes("contract")&&i.get("contract")!==Av&&Pt("protocol_version_mismatch"),e.some(o=>!i.has(o))&&Pt("invalid_request"),i}function nR(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 pr(t,e,n,i=200){if(t.destroyed||t.writableEnded)return;let o=nn(Mt(e,n),{maxBytes:ns});t.writeHead(i,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length}),t.end(o)}function iR(t){return t instanceof Le||t instanceof Zo?t.code:t instanceof Ve?t.code==="request_expired"?"stale_generation":t.code:t instanceof URIError||t instanceof Error&&t.name==="ZodError"?"invalid_request":t instanceof Rt&&t.code==="overloaded"?"capacity_exceeded":"source_unavailable"}function Ev(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,ns),i=0;async function o(l,f){let u;try{u=await t.authenticate(l,f)}catch(m){if(m instanceof Rt)throw m;return Pt("unauthorized")}return u?.endUserId||Pt("unauthorized"),(l.aborted||f.destroyed||f.writableEnded)&&Pt("source_unavailable"),u.endUserId}async function s(l,f){(!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(l.headers["content-type"]??"")||l.headers["content-encoding"])&&Pt("invalid_request");let u=fi(l,n);t.admission.reserveBody(u).admitted||Pt("capacity_exceeded");try{let m=await ki(l,n,h=>bi(h,{maxBytes:n}));return m.ok||(m.reason==="too_large"&&f.setHeader("connection","close"),Pt(m.reason==="too_large"?"payload_too_large":"invalid_request")),m.value}finally{t.admission.releaseBody(u)}}function a(l){return t.serviceFor(l)??Pt("unsupported_capability")}async function d(l,f,u,m,h){t.admission.tryAdmitSse(u).admitted||Pt("capacity_exceeded");let p=new AbortController,v,b,R,w,x=!1,T=[],P=0,W,K,D=C=>{let F="eventId"in C,L=Mt(F?"ExecutorEvent":"OutputEvent",C);return on({event:C.type,...F?{id:C.eventId}:{},data:Buffer.from(nn(L,{maxBytes:ns})).toString("utf8")})},J=C=>{w||(w=C,p.abort(),v?.close(),f.headersSent&&!f.destroyed&&f.destroy())},S=()=>{x||(x=!0,R&&clearInterval(R),p.abort(),v?.close(),T=[],P=0,K=void 0,t.admission.releaseSse(u),l.removeListener("aborted",k))},k=()=>{J("source_unavailable"),S()};l.once("aborted",k),f.once("close",S);let A=()=>W||(W=(async()=>{if(p.signal.aborted||await o(l,f)!==u)return!1;let C=await t.authorize(l,f,u,m);return await v.check(C,p.signal),!p.signal.aborted})().catch(()=>!1).then(C=>(C||J("forbidden"),C)).finally(()=>{W=void 0}),W);try{let C=await t.authorize(l,f,u,m);v=await h(C,Q=>{if(p.signal.aborted)return;let se=D(Q);if(b)b.write(se);else{if(P+=Buffer.byteLength(se),T.length>=32||P>ns){J("capacity_exceeded");return}T.push(se)}},Q=>{if(K!==void 0||b!==void 0){J("invalid_request");return}K=Q},J,p.signal),(w||p.signal.aborted||f.destroyed)&&(v.close(),Pt(w??"source_unavailable")),t.sseKeepAliveMs>0&&l.socket.setKeepAlive(!0,t.sseKeepAliveMs),l.socket.setTimeout(0),f.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no"}),b=t.sse.attach(f,{beforeFlush:A,gapFrame:()=>(J("output_gap"),"")});let F=K,L=T;if(b.replay((function*(){for(let Q of F??[])yield D(Q);yield*L})()),T=[],P=0,K=void 0,x||p.signal.aborted||f.destroyed){S();return}R=setInterval(()=>{A()},e),R.unref()}catch(C){throw S(),C}}async function c(l,f,u,m,h){let g=await o(l,f);t.admission.overloaded()&&Pt("source_unavailable"),m==="GET"&&(l.headers["transfer-encoding"]!==void 0||l.headers["content-length"]!==void 0&&l.headers["content-length"]!=="0")&&Pt("invalid_request");let p=/^\/v3\/terminal\/executors\/([^/]+)\/(events|output-batches)$/.exec(u),v=/^\/v3\/terminal\/executors\/([^/]+)\/operations\/([^/]+)$/.exec(u),b=/^\/v3\/terminal\/sessions\/([^/]+)\/(tool-output|tool-output-status)$/.exec(u),R=u==="/v3/terminal/capabilities",w=u==="/v3/terminal/bindings";if(!p&&!v&&!b&&!R&&!w){let J;if(await t.control?.({req:l,res:f,pathname:u,method:m,endUserId:g,signal:h,readBody:()=>J??=s(l,f),authorize:async S=>{h.throwIfAborted(),await o(l,f)!==g&&Pt("unauthorized");let k=await t.authorize(l,f,g,S);return h.throwIfAborted(),k},reply:(S,k,A)=>pr(f,S,k,A)}))return;Pt("not_found")}let x=w||p?.[2]==="output-batches"?"POST":"GET";if(m!==x&&Pt("invalid_request"),R){di(l,["contract"]),pr(f,"CapabilitiesResponse",t.capabilities());return}if(v){let J=di(l,["contract","sessionContract","sessionId","requestDigest","connectionId"]),S=Mt("SessionReference",{sessionContract:J.get("sessionContract"),sessionId:J.get("sessionId")}),k=Mt("OperationReference",{operationId:decodeURIComponent(v[2]),requestDigest:J.get("requestDigest")}),A=Mt("Id",decodeURIComponent(v[1])),C=Mt("Id",J.get("connectionId")),F=await t.authorize(l,f,g,S.sessionContract);pr(f,"ExecutionState",await a(S.sessionContract).executionState(g,F,A,C,S,k,h));return}if(m==="POST"){di(l,[]);let J=await s(l,f);if(await o(l,f)!==g&&Pt("unauthorized"),w){let S=Mt("BindingRequest",J),k=S.session.sessionContract,A=t.serviceFor(k),C=await t.authorize(l,f,g,k),F=A?await A.bind(g,C,S,h):await t.bindControl?.(g,C,S,h);F||Pt("unsupported_capability"),pr(f,"BindingResponse",F)}else{let S=Mt("OutputBatchRequest",J),k=S.session.sessionContract;S.executorId!==decodeURIComponent(p[1])&&Pt("invalid_request");let A=a(k),C=await t.authorize(l,f,g,k);pr(f,"OutputStatus",await A.receive(g,C,S,h))}return}if(p){let J=di(l,["contract","sessionContract","connectionId"]),S=Mt("SessionContract",J.get("sessionContract")),k=a(S),A=Mt("Id",decodeURIComponent(p[1])),C=Mt("Id",J.get("connectionId")),F=l.headers["last-event-id"];F!==void 0&&Mt("Sequence",F),await d(l,f,g,S,(L,Q,se,O,I)=>k.subscribeExecutor(g,L,A,C,{event:Q,close:O},I));return}let T=b[2]==="tool-output",P=di(l,["contract","sessionContract","operationId","requestDigest"],T?["afterSeq"]:[]);l.headers["last-event-id"]!==void 0&&Pt("invalid_request");let W=Mt("SessionReference",{sessionContract:P.get("sessionContract"),sessionId:decodeURIComponent(b[1])}),K=a(W.sessionContract),D=Mt("OperationReference",{operationId:P.get("operationId"),requestDigest:P.get("requestDigest")});if(T){let J=P.has("afterSeq")?Mt("Sequence",P.get("afterSeq")):null;await d(l,f,g,W.sessionContract,(S,k,A,C,F)=>K.subscribeOutput(g,S,W,D,J,{event:k,replay:A,close:C},F))}else pr(f,"OutputStatus",await K.outputStatus(g,await t.authorize(l,f,g,W.sessionContract),W,D,h))}return(l,f,u,m)=>{if(u!=="/v3/terminal"&&!u.startsWith("/v3/terminal/"))return!1;let h=i<tR;h&&i++;let g=new AbortController,p=()=>g.abort();l.once("aborted",p),f.once("close",p);let v=(async()=>{h||Pt("capacity_exceeded"),await c(l,f,u,m,g.signal)})().catch(b=>{if(f.destroyed||f.writableEnded)return;if(f.headersSent){f.destroy();return}let R=iR(b),[w,x]=nR(R);if(w===429||w===503)for(let[P,W]of Object.entries(Lt(t.admission.retryAfterMs)))f.setHeader(P,W);let T={contract:Av,requestId:eR(),code:R,status:w,retryAction:x};if(w===413&&!l.complete){let P=nn(Mt("ErrorResponse",T),{maxBytes:ns});f.writeHead(w,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":P.length,connection:"close"}),f.write(P);let W=setTimeout(()=>{f.destroyed||f.end()},Vl);W.unref(),f.once("close",()=>clearTimeout(W))}else pr(f,"ErrorResponse",T,w)}).finally(()=>{h&&i--,l.removeListener("aborted",p),f.removeListener("close",p)});return t.trackRequestWork(v),!0}}function Ht(t){throw new Le(t)}function rR(t){let e=t.reason;switch(e){case"turn_running":return Ht("busy");case"session_ended":return Ht("stale_generation");case"invalid_configuration":return Ht("invalid_request");case"unsupported":return Ht("unsupported_capability");case"context_transition_required":case"revision_conflict":case"request_conflict":case"request_limit":return Ht(e)}}function Cv(t){return async e=>{let n=/^\/v3\/terminal\/sessions\/([^/]+)\/memory(?:\/commands(?:\/([^/]+))?)?$/.exec(e.pathname);if(n)return oR(e,t,n);let i=/^\/v3\/terminal\/sessions\/([^/]+)\/configuration$/.exec(e.pathname);if(!i)return!1;e.method!=="GET"&&e.method!=="POST"&&Ht("invalid_request");let o,s,a=decodeURIComponent(i[1]);if(e.method==="GET"){let f=di(e.req,["contract","sessionContract"]);o=Mt("SessionReference",{sessionContract:f.get("sessionContract"),sessionId:a})}else di(e.req,[]),s=Mt("ConfigurationRequest",await e.readBody()),(s.session.sessionId!==a||Object.keys(s.changes).length===0)&&Ht("invalid_request"),o=s.session;(await e.authorize(o.sessionContract)).controller||Ht("forbidden"),e.signal.throwIfAborted();let c=t.resolve(e.endUserId,o);await t.check(e.endUserId,o,e.signal),c!==t.resolve(e.endUserId,o)&&Ht("stale_generation"),e.signal.throwIfAborted();let l=c.configuration?.();if((!l||!c.configure)&&Ht("unsupported_capability"),s===void 0)e.reply("ConfigurationResponse",{contract:"terminal-services-v1",session:o,configuration:l});else{let f=await c.configure({requestId:s.requestId,expectedRevision:s.expectedRevision,changes:s.changes},{signal:e.signal,beforeCommit:async()=>{(await e.authorize(o.sessionContract)).controller||Ht("forbidden"),await t.check(e.endUserId,o,e.signal),c!==t.resolve(e.endUserId,o)&&Ht("stale_generation"),e.signal.throwIfAborted()}});f.status==="rejected"&&rR(f),e.reply("ConfigurationCommitResponse",{contract:s.contract,requestId:s.requestId,session:o,status:f.status,configuration:f.configuration})}return!0}}async function oR(t,e,n){try{let i=decodeURIComponent(n[1]),o=t.pathname.endsWith("/memory/commands"),s=n[2]===void 0?void 0:decodeURIComponent(n[2]);t.method!==(o?"POST":"GET")&&Ht("invalid_request");let a,d,c;if(o)di(t.req,[]),d=Mt("MemoryCommandRequest",await t.readBody()),d.session.sessionId!==i&&Ht("invalid_request"),a=d.session;else{let g=di(t.req,["contract","sessionContract",...s?["requestId"]:[]]);a=Mt("SessionReference",{sessionContract:g.get("sessionContract"),sessionId:i}),s!==void 0&&(Mt("MemoryIdentifier",s),c=Mt("MemoryIdentifier",g.get("requestId")))}let l=e.resolve(t.endUserId,a),f=async()=>{(await t.authorize(a.sessionContract)).controller||Ht("forbidden"),await e.check(t.endUserId,a,t.signal),l!==e.resolve(t.endUserId,a)&&Ht("stale_generation"),t.signal.throwIfAborted()};await f(),(d!==void 0||Nn(l)?.management===void 0)&&await fr(l)?.prepare(t.signal),await f();let u=Nn(l),m=u?.management;(!u||!m)&&Ht("unsupported_capability");let h=()=>{(Nn(l)!==u||u.management!==m)&&Ht("stale_generation"),u.status().enabled||Ht("source_unavailable"),m.assertCurrent()};if(h(),m.identity.endUserId!==t.endUserId&&Ht("forbidden"),d!==void 0){let g=Sv(l);g||Ht("unsupported_capability");let{contract:p,session:v,...b}=d,R=await g(b,{signal:t.signal,beforeCommit:f});await m.read(),await f(),h(),t.reply("MemoryReceiptResponse",{contract:"terminal-services-v1",session:a,receipt:R})}else if(s!==void 0){let g=await m.status(s,c);await f(),h(),t.reply("MemoryReceiptResponse",{contract:"terminal-services-v1",session:a,receipt:g})}else{let g=await m.read();await f(),h(),t.reply("MemoryStateResponse",{contract:"terminal-services-v1",session:a,memory:g})}return!0}catch(i){throw i instanceof at?new Le(i.code):i}}import{randomUUID as sR}from"node:crypto";var tt={};tt.OutputCorrelation=r.object({contract:r.lazy(()=>tt.LegacyContract),session:r.lazy(()=>tt.SessionReference),toolCallId:r.lazy(()=>tt.LegacyId),operation:r.lazy(()=>tt.OperationReference),outputAuthority:r.union([r.literal("session-events"),r.literal("tool-output")])}).strict();tt.Contract=r.literal("terminal-observation-v1");tt.SessionReference=r.object({sessionContract:r.lazy(()=>tt.SessionContract),sessionId:r.lazy(()=>tt.LegacyId)}).strict();tt.SessionContract=r.union([r.literal("sdk1"),r.literal("sdk2-offload-v1")]);tt.LegacyId=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);tt.OperationReference=r.object({operationId:r.lazy(()=>tt.Id),requestDigest:r.lazy(()=>tt.Digest)}).strict();tt.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);tt.Digest=r.string().regex(new RegExp("^[a-f0-9]{64}$","u"));tt.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")]);tt.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);tt.ResourceState=r.union([r.literal("active"),r.literal("accepted"),r.literal("draining"),r.literal("completed"),r.literal("failed"),r.literal("unknown")]);tt.ResourceError=r.union([r.literal("close_failed"),r.literal("publication_failed"),r.literal("settlement_failed"),r.literal("settlement_unavailable")]);tt.ResourcesResponse=r.object({contract:r.lazy(()=>tt.Contract),session:r.lazy(()=>tt.SessionReference),epochStartSeq:r.lazy(()=>tt.Sequence),state:r.lazy(()=>tt.ResourceState),closeRequested:r.boolean(),executionEnded:r.boolean(),errorCode:r.union([r.lazy(()=>tt.ResourceError),r.null()])}).strict();tt.CorrelationsResponse=r.object({contract:r.lazy(()=>tt.Contract),session:r.lazy(()=>tt.SessionReference),correlations:r.array(r.lazy(()=>tt.OutputCorrelation)).max(32),truncated:r.boolean()}).strict();tt.ErrorResponse=r.object({contract:r.lazy(()=>tt.Contract),requestId:r.lazy(()=>tt.Id),code:r.lazy(()=>tt.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();tt.LegacyContract=r.literal("terminal-services-v1");function _v(t,e){if(!Object.hasOwn(tt,t))throw new TypeError("Unknown terminal observation type");return tt[t].parse(e)}var Bd="terminal-observation-v1",aR=262144;function ln(t){throw new Le(t)}function If(t,e){try{return _v(t,e)}catch{return ln("invalid_request")}}function Rf(t,e,n,i=200){if(t.destroyed||t.writableEnded)return;let o=nn(If(e,n),{maxBytes:aR});t.writeHead(i,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length}),t.end(o)}function dR(t){return t instanceof Le?t.code:t instanceof Ve?t.code==="request_expired"?"stale_generation":t.code:t instanceof URIError?"invalid_request":t instanceof Rt&&t.code==="overloaded"?"capacity_exceeded":"source_unavailable"}function cR(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 Pv(t){let e=0,n=new Map;async function i(s,a,d){let c;try{c=await t.authenticate(s,a)}catch(l){if(l instanceof Rt)throw l;return ln("unauthorized")}return d.throwIfAborted(),c?.endUserId||ln("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"&&ln("source_unavailable"),u>=16&&ln("capacity_exceeded"),n.set(f,u+1);try{let m=/^\/v3\/terminal-observation\/sessions\/([^/]+)\/(resources|output-correlations)$/.exec(d);m||ln("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"])&&ln("invalid_request");let h=new URL(s.url??"/","http://serve.invalid").searchParams,g=["contract","sessionContract",...m[2]==="output-correlations"?["toolCallId"]:[]];[...h.keys()].some(T=>!g.includes(T)||h.getAll(T).length!==1)&&ln("invalid_request"),h.get("contract")!==Bd&&ln("protocol_version_mismatch");let p=If("SessionReference",{sessionContract:h.get("sessionContract"),sessionId:decodeURIComponent(m[1])}),v=h.has("toolCallId")?If("LegacyId",h.get("toolCallId")):void 0,b=await t.authorize(s,a,f,p.sessionContract);l.throwIfAborted(),b.controller||ln("forbidden");let R=t.resolve(f,p);await t.check(f,p,l),l.throwIfAborted();let w=m[2]==="output-correlations"?await t.readOutputCorrelations(f,b,p,v,l):void 0;await i(s,a,l)!==f&&ln("unauthorized");let x=await t.authorize(s,a,f,p.sessionContract);if(l.throwIfAborted(),x.controller||ln("forbidden"),await t.check(f,p,l),l.throwIfAborted(),(R.handle!==t.resolve(f,p).handle||R.registry.get(p.sessionId)?.handle!==R.handle)&&ln("stale_generation"),w)w.some(T=>T.session.sessionContract!==p.sessionContract||T.session.sessionId!==p.sessionId||v!==void 0&&T.toolCallId!==v)&&ln("integrity_mismatch"),Rf(a,"CorrelationsResponse",{contract:Bd,session:p,correlations:w.slice(-32),truncated:w.length>32});else{let T=R.registry.resourceObservation(p.sessionId);T||ln("not_found"),Rf(a,"ResourcesResponse",{contract:Bd,session:p,...T})}}finally{let m=n.get(f)-1;m===0?n.delete(f):n.set(f,m)}}return(s,a,d,c)=>{if(d!=="/v3/terminal-observation"&&!d.startsWith("/v3/terminal-observation/"))return!1;let l=new AbortController,f=()=>l.abort();s.once("aborted",f),a.once("close",f);let u,m=new Promise((w,x)=>{u=x}),h=()=>u(new Le("source_unavailable"));l.signal.addEventListener("abort",h,{once:!0});let g=setTimeout(f,1e4);g.unref(),(s.aborted||a.destroyed||a.writableEnded)&&f();let p=e<128;p&&e++;let v=(async()=>{p||ln("capacity_exceeded"),await o(s,a,d,c,l.signal)})(),b=v.then(()=>{},()=>{}).finally(()=>{p&&e--});t.trackRequestWork(b);let R=Promise.race([v,m]).catch(w=>{if(a.destroyed||a.writableEnded)return;if(a.headersSent){a.destroy();return}let x=dR(w),[T,P]=cR(x);if(T===429||T===503)for(let[W,K]of Object.entries(Lt(t.admission.retryAfterMs)))a.setHeader(W,K);Rf(a,"ErrorResponse",{contract:Bd,requestId:sR(),code:x,status:T,retryAction:P},T)}).finally(()=>{clearTimeout(g),s.removeListener("aborted",f),a.removeListener("close",f),l.signal.removeEventListener("abort",h)});return t.trackRequestWork(R),!0}}import{randomUUID as lR}from"node:crypto";var De={};De.Contract=r.literal("terminal-profile-v1");De.Text=r.string().refine(t=>[...t].length>=1).refine(t=>[...t].length<=512);De.NullableText=r.union([r.lazy(()=>De.Text),r.null()]);De.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);De.SessionContract=r.union([r.literal("sdk1"),r.literal("sdk2-offload-v1")]);De.SessionReference=r.object({sessionContract:r.lazy(()=>De.SessionContract),sessionId:r.lazy(()=>De.Text)}).strict();De.Model=r.object({handle:r.lazy(()=>De.Text),displayName:r.lazy(()=>De.Text),manufacturer:r.lazy(()=>De.NullableText),family:r.lazy(()=>De.NullableText)}).strict();De.Aliases=r.record(r.lazy(()=>De.Text),r.lazy(()=>De.Text)).refine(t=>Object.keys(t).length<=1024);De.Catalog=r.object({models:r.array(r.lazy(()=>De.Model)).max(1024),aliases:r.lazy(()=>De.Aliases),capabilities:r.lazy(()=>De.Capabilities)}).strict();De.Quota=r.object({state:r.literal("not_exposed"),enforcement:r.literal("gateway")}).strict();De.Counter=r.number().int().safe().min(0).max(9007199254740991);De.Usage=r.object({window:r.literal("1d"),endUserId:r.lazy(()=>De.Text),requests:r.lazy(()=>De.Counter),inTokens:r.lazy(()=>De.Counter),outTokens:r.lazy(()=>De.Counter),cacheRTokens:r.lazy(()=>De.Counter),cacheWTokens:r.lazy(()=>De.Counter)}).strict();De.CatalogResponse=r.object({contract:r.lazy(()=>De.Contract),session:r.lazy(()=>De.SessionReference),models:r.array(r.lazy(()=>De.Model)).max(1024),aliases:r.lazy(()=>De.Aliases),quota:r.lazy(()=>De.Quota),capabilities:r.lazy(()=>De.Capabilities)}).strict();De.UsageResponse=r.object({contract:r.lazy(()=>De.Contract),session:r.lazy(()=>De.SessionReference),usage:r.lazy(()=>De.Usage),quota:r.lazy(()=>De.Quota)}).strict();De.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")]);De.ErrorResponse=r.object({contract:r.lazy(()=>De.Contract),requestId:r.lazy(()=>De.Id),code:r.lazy(()=>De.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();De.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();De.CapabilityPlatform=r.object({imageGen:r.boolean(),videoGen:r.boolean(),webSearch:r.boolean(),speechToText:r.boolean(),textToSpeech:r.boolean()}).strict();De.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();De.ExecutionCapabilities=r.object({version:r.literal("bound-device-v1"),boundDevice:r.object({tools:r.lazy(()=>De.BoundDeviceTools)}).strict()}).strict();De.Capabilities=r.object({tools:r.lazy(()=>De.CapabilityTools),platform:r.lazy(()=>De.CapabilityPlatform),execution:r.lazy(()=>De.ExecutionCapabilities).optional()}).strict();function qd(t,e){if(!Object.hasOwn(De,t))throw new TypeError("Unknown terminal profile type");return De[t].parse(e)}var Dd="terminal-profile-v1",uR=262144;function dn(t){throw new Le(t)}function Mv(t,e){try{return qd(t,e)}catch{return dn("invalid_request")}}function Tf(t,e,n,i=200){if(t.destroyed||t.writableEnded)return;let o=nn(Mv(e,n),{maxBytes:uR});t.writeHead(i,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","content-length":o.length}),t.end(o)}function fR(t){return t instanceof Le?t.code:t instanceof Ve?t.code==="request_expired"?"stale_generation":t.code:t instanceof URIError?"invalid_request":t instanceof Rt&&t.code==="overloaded"?"capacity_exceeded":"source_unavailable"}function pR(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 Ov(t){let e=0,n=new Map;async function i(s,a,d){let c;try{c=await t.authenticate(s,a)}catch(l){if(l instanceof Rt)throw l;return dn("unauthorized")}return d.throwIfAborted(),c?.endUserId||dn("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"&&dn("source_unavailable"),u>=16&&dn("capacity_exceeded"),n.set(f,u+1);try{let m=/^\/v3\/terminal-profile\/sessions\/([^/]+)\/(catalog|usage)$/.exec(d);m||dn("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"])&&dn("invalid_request");let h=new URL(s.url??"/","http://serve.invalid").searchParams,g=["contract","sessionContract"];[...h.keys()].some(P=>!g.includes(P)||h.getAll(P).length!==1)&&dn("invalid_request"),h.get("contract")!==Dd&&dn("protocol_version_mismatch");let p=Mv("SessionReference",{sessionContract:h.get("sessionContract"),sessionId:decodeURIComponent(m[1])}),v=await t.authorize(s,a,f,p.sessionContract);l.throwIfAborted(),v.controller||dn("forbidden");let b=t.resolve(f,p);await t.check(f,p,l),l.throwIfAborted();let R=m[2]==="catalog"?await t.readCatalog(f,p,l):void 0,w=m[2]==="usage"?await t.readUsage(f,p,l):void 0;await i(s,a,l)!==f&&dn("unauthorized");let x=await t.authorize(s,a,f,p.sessionContract);l.throwIfAborted(),x.controller||dn("forbidden"),await t.check(f,p,l),l.throwIfAborted(),(b.handle!==t.resolve(f,p).handle||b.registry.get(p.sessionId)?.handle!==b.handle)&&dn("stale_generation");let T={state:"not_exposed",enforcement:"gateway"};if(R!==void 0){let P=qd("Catalog",R),W=new Set(P.models.map(K=>K.handle));(W.size!==P.models.length||Object.values(P.aliases).some(K=>!W.has(K)))&&dn("integrity_mismatch"),Tf(a,"CatalogResponse",{contract:Dd,session:p,...P,quota:T})}else if(w!==void 0){let P=qd("Usage",w);(P.endUserId!==f||P.endUserId!==b.handle.endUserId)&&dn("integrity_mismatch"),Tf(a,"UsageResponse",{contract:Dd,session:p,usage:P,quota:T})}else dn("unsupported_capability")}finally{let m=n.get(f)-1;m===0?n.delete(f):n.set(f,m)}}return(s,a,d,c)=>{if(d!=="/v3/terminal-profile"&&!d.startsWith("/v3/terminal-profile/"))return!1;let l=new AbortController,f=()=>l.abort();s.once("aborted",f),a.once("close",f);let u,m=new Promise((w,x)=>{u=x}),h=()=>u(new Le("source_unavailable"));l.signal.addEventListener("abort",h,{once:!0});let g=setTimeout(f,1e4);g.unref(),(s.aborted||a.destroyed||a.writableEnded)&&f();let p=e<128;p&&e++;let v=(async()=>{p||dn("capacity_exceeded"),await o(s,a,d,c,l.signal)})(),b=v.then(()=>{},()=>{}).finally(()=>{p&&e--});t.trackRequestWork(b);let R=Promise.race([v,m]).catch(w=>{if(a.destroyed||a.writableEnded)return;if(a.headersSent){a.destroy();return}let x=fR(w),[T,P]=pR(x);if(T===429||T===503)for(let[W,K]of Object.entries(Lt(t.admission.retryAfterMs)))a.setHeader(W,K);Tf(a,"ErrorResponse",{contract:Dd,requestId:lR(),code:x,status:T,retryAction:P},T)}).finally(()=>{clearTimeout(g),s.removeListener("aborted",f),a.removeListener("close",f),l.signal.removeEventListener("abort",h)});return t.trackRequestWork(R),!0}}var Bv=new WeakMap;function qv(t,e){Bv.set(t,e)}function Af(t){let e=Bv.get(t)?.();if(e===void 0)throw new Le("unsupported_capability");return e}var mR="127.0.0.1",Dv=1024,hR=15e3,gR=1024*1024,yR=3e4,vR=3e4,bR=1e4,SR=3e4,wR=5e3,kR=5e3,Ef=50,jv=5e3,xR=/^\/v1\/sessions\/([^/]+)\/(messages|events|abort)$/,Nv=/^\/v1\/approvals\/([^/]+)\/credential$/,Uv={unknown_challenge:404,expired:410,digest_mismatch:409,already_resolved:409},RR={unknown_challenge:"request_not_found",expired:"request_expired",digest_mismatch:"digest_mismatch",already_resolved:"request_already_resolved"};async function Fv(t){return jd(t)}async function ND(t,e){if(t.v2===void 0)throw new TypeError("Cache routes require v2 end-user authentication");return jd(t,e)}async function UD(t,e,n,i){if(t.v2===void 0)throw new TypeError("Archive routes require v2 end-user authentication");return jd(t,n,e,i)}async function FD(t,e,n){if(t.v2===void 0)throw new TypeError("Archive sync requires v2 end-user authentication");return jd(t,void 0,n,{disableV1:!0},e)}async function jd(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??mR,d=t.heartbeatMs??hR;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 z of[u.maxFrameBytes??2097152,u.maxBufferBytes??2097152])if(!Number.isSafeInteger(z)||z<1||z>2097152)throw new RangeError("Terminal SSE budgets must be finite and no greater than 2 MiB")}let m=t.v2===void 0?void 0:Uh(t.v2,f),h=t.eventBufferMaxBytes??(f?4*1024*1024:void 0),g=new Er({...u,heartbeatMs:u.heartbeatMs??d}),p=t.maxBodyBytes??gR,v=t.version??"0.0.0-dev",b=t.logger,R=$n(b),w=Date.now(),x=!1,T=new Set,P=z=>{T.add(z);let B=()=>{T.delete(z)};z.then(B,B)},W=new va({eventBufferSize:t.eventBufferSize??Dv,...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:(z,B)=>{b?.error(We(ae.createFailed,{message:`[${z}] ${B instanceof Error?B.message:String(B)}`}))}}),K=0,D,J=zh(t.admission??{},{activeSessions:()=>W.activeCount()+K+(D?.activeCount()??0)+(D?.pendingCount()??0),...b!==void 0?{logger:b}:{}}),S=t.sse?.keepAliveMs??vR,k=t.sse?.drainRetryMs??bR,A=new Set,C,F,L;if(t.v2!==void 0){let z=t.v2.onTurnEndNotify;if(z!==void 0){let Ne=Gr({governor:t.governor});C=new _r({...Ne!==void 0?{fetchImpl:Ne}:{},...z,onDeliveryFailure:Ce=>{R("error",rt.notifyDeliveryFailed,{sessionId:Ce.sessionId,...Ce.turnId!==void 0?{turnId:Ce.turnId}:{},attempts:Ce.attempts,reason:Ce.reason},We(ae.v2NotifyFailed,{sessionId:Ce.sessionId,attempts:Ce.attempts,reason:Ce.reason})),z.onDeliveryFailure?.(Ce)}})}let B=C,ee=t.v2.createSession,de=ee.sweepRetention?.bind(ee);D=new Aa({eventBufferSize:t.eventBufferSize??Dv,...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}:{},...B!==void 0?{onTurnEndNotify:Ne=>B.notify(Ne)}:{},...de!==void 0?{onSweep:de}:{},onPumpError:(Ne,Ce)=>{Qn(t.observability?.metrics).pumpErrors.inc(),b?.error(We(ae.createFailed,{message:`[v2:${Ne}] ${Ce instanceof Error?Ce.message:String(Ce)}`}))}}),L=i?.offload?.only?void 0:tf({...!i?.offload&&i?.filterSessionReads?{filterSessionReads:i.filterSessionReads}:{},options:t.v2,authenticate:m.authenticate,registry:D,admission:J,maxBodyBytes:p,sse:g,sseKeepAliveMs:S,trackRequestWork:P,...b!==void 0?{logger:b}:{}}),i?.offload&&(F=tf({sessionFamily:"sdk2-offload-v1",options:i.offload.options,prepareCreate:i.offload.prepareCreate,sessionContracts:[...i.offload.only?[]:[{contract:"sdk1",availability:"legacy-complete"}],{contract:"sdk2-offload-v1",availability:"source-required"}],...i.offload.readHistoryOrigin?{readHistoryOrigin:i.offload.readHistoryOrigin}:{},...i.filterSessionReads?{filterSessionReads:i.filterSessionReads}:{},authenticate:m.authenticate,registry:D,admission:J,maxBodyBytes:p,sse:g,sseKeepAliveMs:S,trackRequestWork:P,...b!==void 0?{logger:b}:{}}))}let Q=new Map;t.v2&&!i?.offload?.only&&Q.set("sdk1",t.v2.createSession),i?.offload&&Q.set("sdk2-offload-v1",i.offload.options.createSession);let se=t.terminal!==void 0&&D!==void 0?Tv({registry:D,families:Q,scopeFor:t.terminal.scopeFor,...i?.filterSessionReads?{filterObservationReads:async(z,B)=>i.offload&&B.sessionContract!=="sdk2-offload-v1"?!0:(await i.filterSessionReads(z,[B.sessionId])).includes(B.sessionId)}:{}}):void 0,O=se===void 0?void 0:Ev({...se,control:Cv(se),authenticate:m.authenticate,admission:J,sse:g,maxBodyBytes:p,sseKeepAliveMs:S,trackRequestWork:P,...t.terminal?.revalidateMs===void 0?{}:{revalidateMs:t.terminal.revalidateMs}}),I=se===void 0?void 0:Pv({authenticate:m.authenticate,authorize:se.authorize,resolve:se.resolveObservation,check:se.checkObservation,admission:J,trackRequestWork:P,readOutputCorrelations:(z,B,ee,de,Ne)=>{let Ce=se.serviceFor(ee.sessionContract);if(!Ce)throw new Le("unsupported_capability");return Ce.readOutputCorrelations(z,B,ee,de,Ne)}}),q=se===void 0?void 0:Ov({authenticate:m.authenticate,authorize:se.authorize,resolve:se.resolveObservation,check:se.checkObservation,admission:J,trackRequestWork:P,readCatalog:(z,B,ee)=>{let de=Af(se.resolveObservation(z,B).handle).readPlatformCatalog;if(de===void 0)throw new Le("unsupported_capability");return de(ee)},readUsage:(z,B,ee)=>{let de=Af(se.resolveObservation(z,B).handle).readPlatformUsage;if(de===void 0)throw new Le("unsupported_capability");return de(ee)}}),H=e!==void 0&&t.v2!==void 0?Hy({link:e,admission:J,authenticate:m.authenticate,track:P}):void 0,N=n!==void 0&&t.v2!==void 0?kg({host:n,admission:J,authenticate:m.authenticate,track:P}):void 0,ie=o!==void 0&&t.v2!==void 0?Gy({host:o,admission:J,authenticate:m.authenticate,track:P}):void 0,U=(z,B,ee,de)=>!!(I?.(z,B,ee,de)||q?.(z,B,ee,de)||O?.(z,B,ee,de)||H?.(z,B,ee,de)||ie?.(z,B)||F!==void 0&&F(z,B,ee,de)||N?.(z,B)||L!==void 0&&L(z,B,ee,de)),ce={session:F!==void 0?"sdk2-offload-v1":L!==void 0?"sdk1":null,execution:c!==void 0&&(F!==void 0||L!==void 0),archive:N!==void 0,"archive-sync":ie!==void 0,cache:H!==void 0,terminal:O!==void 0,"terminal-observation":I!==void 0,"terminal-profile":q!==void 0},le=(z,B,ee,de)=>U(z,B,ee,de)||_n(z,B,ee,de),re=t.v2===void 0?void 0:mv({authenticate:m.authenticate,delegate:le,sessionFamilies:[...L!==void 0?["sdk1"]:[],...F!==void 0?["sdk2-offload-v1"]:[]],installed:ce,track:P,retryAfterMs:()=>J.retryAfterMs,...D===void 0?{}:{sessionClosure:hv({registry:D,installed:ce,...c===void 0?{}:{execution:c},...n===void 0?{}:{archive:n},...se===void 0?{}:{terminal:se},...e===void 0?{}:{cache:e}})}}),pe=D,j=C,Y=rg({host:a,options:t.observability,startedAt:w,log:R,v1Active:()=>W.activeCount(),v2:()=>pe===void 0?void 0:ig(pe),notifierStats:()=>j?.stats(),sseStats:()=>g.stats(),ringStats:()=>ga(W.ringStats(),pe?.ringStats()),...t.governor!==void 0?{governorStats:()=>t.governor?.stats()}:{},closing:()=>x});Y.addReadinessProbe(()=>{let z=J.readiness();return z.ready?!0:{ready:!1,reason:z.reasons.join(",")||"admission"}});let oe=i?.offload?.options.store;oe?.readiness!==void 0&&oe!==t.v2?.store&&Y.addReadinessProbe(()=>oe.readiness?.()??!0);let Se=t.v2?.store;Se?.readiness!==void 0&&Y.addReadinessProbe(()=>Se.readiness?.()??!0);let je=(z,B,ee,de)=>{let Ne=On(de),Ce=tg(z);R("error",rt.requestUnhandled,{...Ce!==void 0?{requestId:Ce.requestId,route:Ce.route}:{},method:ee,message:Ne},We(ae.requestUnhandled,{method:ee,path:B,message:Ne}));try{if(z.destroyed||z.writableEnded)return;if(!z.headersSent){fe(z,500,"internal_error",ae.internalError);return}z.end()}catch{z.destroy()}},$e=async(z,B)=>{let ee=fi(z,p),de=J.reserveBody(ee);return de.admitted?(B.once("close",()=>J.releaseBody(ee)),ki(z,p)):(ni(B,de),"rejected")},Fe=(z,B,ee)=>{ee==="too_large"?Rr(z,B,"body_too_large",ae.bodyTooLarge,{maxBytes:p}):fe(B,400,"invalid_json",ae.invalidJson)},ft=async(z,B)=>{let ee=await $e(z,B);if(ee==="rejected")return;if(!ee.ok){Fe(z,B,ee.reason);return}if(typeof ee.value!="object"||ee.value===null||Array.isArray(ee.value)){fe(B,400,"invalid_body",ae.invalidBody);return}let de=ee.value;if(de.prompt!==void 0&&typeof de.prompt!="string"){fe(B,400,"invalid_body",ae.invalidBody);return}if(de.model!==void 0&&typeof de.model!="string"){fe(B,400,"invalid_body",ae.invalidBody);return}if(de.profile!==void 0&&typeof de.profile!="string"){fe(B,400,"invalid_body",ae.invalidBody);return}if(de.tools!==void 0&&(!Array.isArray(de.tools)||de.tools.some(Re=>typeof Re!="string"))){fe(B,400,"invalid_body",ae.invalidBody);return}let Ne;if(de.labels!==void 0){let Re=ls.safeParse(de.labels);if(!Re.success){fe(B,400,"invalid_body",ae.invalidBody);return}Ne=Re.data}let Ce;if(de.budget!==void 0){if(typeof de.budget!="object"||de.budget===null||Array.isArray(de.budget)){fe(B,400,"invalid_body",ae.invalidBody);return}let Re=de.budget,Be=Me=>typeof Me=="number"&&Number.isFinite(Me)&&Me>0;if(Re.maxUsd!==void 0&&!Be(Re.maxUsd)||Re.maxTokens!==void 0&&(!Be(Re.maxTokens)||!Number.isInteger(Re.maxTokens))){fe(B,400,"invalid_body",ae.invalidBody);return}Ce={...Re.maxUsd!==void 0?{maxUsd:Re.maxUsd}:{},...Re.maxTokens!==void 0?{maxTokens:Re.maxTokens}:{}}}let Xe={...typeof de.prompt=="string"&&de.prompt!==""?{prompt:de.prompt}:{},...typeof de.model=="string"&&de.model!==""?{model:de.model}:{},...typeof de.profile=="string"&&de.profile!==""?{profile:de.profile}:{},...de.tools!==void 0?{tools:de.tools}:{},...Ne!==void 0?{labels:Ne}:{},...Ce!==void 0?{budget:Ce}:{}},X=x?{admitted:!1,reason:"draining",retryAfterMs:J.retryAfterMs}:J.tryAdmitSession();if(!X.admitted){ni(B,X);return}K+=1;let ge;try{let Re=await t.createSession.create(Xe);ge=W.adopt(Re)}catch(Re){fe(B,400,"create_failed",ae.createFailed,{message:Re instanceof Error?Re.message:String(Re)});return}finally{K-=1}Qe(B,201,{sessionId:ge})},kt=async(z,B,ee)=>{if(W.get(ee)===void 0){fe(B,404,"session_not_found",ae.sessionNotFound,{sessionId:ee});return}let Ne=await $e(z,B);if(Ne==="rejected")return;if(!Ne.ok){Fe(z,B,Ne.reason);return}let Ce=typeof Ne.value=="object"&&Ne.value!==null?Ne.value:{};if(typeof Ce.prompt!="string"||Ce.prompt.trim()===""){fe(B,400,"prompt_required",ae.promptRequired);return}if(!W.send(ee,Ce.prompt)){fe(B,409,"session_ended",ae.sessionEnded,{sessionId:ee});return}Qe(B,202,{sessionId:ee,accepted:!0})},ze=(z,B)=>{if(!W.interrupt(B)){fe(z,404,"session_not_found",ae.sessionNotFound,{sessionId:B});return}Qe(z,202,{sessionId:B,accepted:!0})},it=(z,B,ee)=>{let de=J.tryAdmitSse();if(!de.admitted){ni(B,de);return}if(B.once("close",()=>{J.releaseSse()}),S>0&&z.socket.setKeepAlive(!0,S),z.socket.setTimeout(0),W.get(ee)===void 0){fe(B,404,"session_not_found",ae.sessionNotFound,{sessionId:ee});return}let Ne=Xs(z.headers["last-event-id"]);if(Ne===void 0){fe(B,400,"invalid_last_event_id",ae.invalidLastEventId);return}B.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no"});let Ce=g.attach(B,{gapFrame:X=>Cr(ee,X)});A.add(Ce);let Xe=W.subscribe(ee,Ne,Ce);B.on("close",()=>{A.delete(Ce),Xe?.()})},It=()=>W.activeCount()+(D?.activeCount()??0),Wt=z=>{Qe(z,200,{version:v,protocolVersion:Yf,activeSessions:It(),uptimeMs:Date.now()-w})},un=async(z,B,ee,de,Ne="v1")=>{let Ce=await $e(z,B);if(Ce==="rejected")return;if(!Ce.ok){Ne==="api"&&Ce.reason==="too_large"?Rr(z,B,"payload_too_large",ae.bodyTooLarge,{maxBytes:p}):Fe(z,B,Ce.reason);return}let Xe=Ne==="api"?"validation_failed":"invalid_body";if(typeof Ce.value!="object"||Ce.value===null||Array.isArray(Ce.value)){fe(B,400,Xe,ae.approvalInvalidBody);return}let X=Ce.value;if(typeof X.digest!="string"||X.digest===""||X.verdict!=="approve"&&X.verdict!=="deny"||typeof X.approver!="string"||X.approver.trim()===""){fe(B,400,Xe,ae.approvalInvalidBody);return}let ge=ee.submit({challengeId:de,digest:X.digest,verdict:X.verdict,approver:X.approver});if(ge.code==="accepted"){Qe(B,200,{challengeId:de,result:"accepted"});return}if(Ne==="api"){fe(B,Uv[ge.code]??409,RR[ge.code]??`approval_${ge.code}`,ae.approvalRejected,{code:ge.code,challengeId:de},void 0,{submitCode:ge.code,challengeId:de});return}fe(B,Uv[ge.code]??409,`approval_${ge.code}`,ae.approvalRejected,{code:ge.code,challengeId:de})},_n=(z,B,ee,de)=>{let Ne=t.approvals;if(Ne===void 0||m===void 0)return!1;let Ce=Nv.exec(ee);if(Ce===null)return!1;let Xe=(async()=>{let X;try{X=await m.authenticate(z,B)}catch(Re){if(B.destroyed||B.writableEnded)return;if(Re instanceof Rt){fe(B,503,Re.code,Re.code==="overloaded"?ae.overloaded:ae.internalError,{},Lt(J.retryAfterMs));return}X=null}if(z.aborted||B.destroyed||B.writableEnded)return;if(X===null||typeof X.endUserId!="string"||X.endUserId===""){fe(B,401,"unauthorized",ae.unauthorized,void 0,{"www-authenticate":"Bearer"});return}if(de!=="POST"){fe(B,405,"method_not_allowed",ae.methodNotAllowed,{method:de,path:ee},{allow:"POST"});return}let ge=ui(Ce[1]);if(ge===null){fe(B,404,"not_found",ae.notFound,{path:ee});return}await un(z,B,Ne,ge,"api")})();return P(Xe),Xe.catch(X=>je(B,ee,de,X)),!0},Nt=(z,B,ee,de)=>{if(re!==void 0&&re(z,B,ee,de))return;if(l&&(ee==="/v1"||ee.startsWith("/v1/"))){fe(B,404,"not_found",ae.notFound,{path:ee});return}if(i?.offload?.only&&(ee==="/v2"||ee.startsWith("/v2/"))){fe(B,404,"not_found",ae.notFound);return}if(U(z,B,ee,de))return;if(!Ys(z.headers.authorization,s)){fe(B,401,"unauthorized",ae.unauthorized,void 0,{"www-authenticate":"Bearer"});return}let Ne=X=>{P(X),X.catch(ge=>je(B,ee,de,ge))};if(ee==="/v1/sessions"){if(de!=="POST"){fe(B,405,"method_not_allowed",ae.methodNotAllowed,{method:de,path:ee},{allow:"POST"});return}Ne(ft(z,B));return}if(ee==="/v1/status"){if(de!=="GET"){fe(B,405,"method_not_allowed",ae.methodNotAllowed,{method:de,path:ee},{allow:"GET"});return}Wt(B);return}let Ce=xR.exec(ee);if(Ce!==null){let X=ui(Ce[1]);if(X===null){fe(B,404,"not_found",ae.notFound,{path:ee});return}let ge=Ce[2];if(ge==="events"){if(de!=="GET"){fe(B,405,"method_not_allowed",ae.methodNotAllowed,{method:de,path:ee},{allow:"GET"});return}it(z,B,X);return}if(de!=="POST"){fe(B,405,"method_not_allowed",ae.methodNotAllowed,{method:de,path:ee},{allow:"POST"});return}ge==="messages"?Ne(kt(z,B,X)):ze(B,X);return}let Xe=Nv.exec(ee);if(Xe!==null&&t.approvals!==void 0){if(de!=="POST"){fe(B,405,"method_not_allowed",ae.methodNotAllowed,{method:de,path:ee},{allow:"POST"});return}let X=ui(Xe[1]);if(X===null){fe(B,404,"not_found",ae.notFound,{path:ee});return}Ne(un(z,B,t.approvals,X));return}fe(B,404,"not_found",ae.notFound,{path:ee})},hn=(z,B)=>{let ee=z.method??"GET",de=(z.url??"/").split("?",1)[0];try{Y.trackRequest(z,B)}catch{}try{if(Y.handleEndpoint(z,B,de,ee))return;Nt(z,B,de,ee)}catch(Ne){je(B,de,ee,Ne)}},_=t.http??{},y=Zm.createServer({requestTimeout:_.requestTimeout??yR,..._.headersTimeout!==void 0?{headersTimeout:_.headersTimeout}:{},..._.keepAliveTimeout!==void 0?{keepAliveTimeout:_.keepAliveTimeout}:{},..._.connectionsCheckingInterval!==void 0?{connectionsCheckingInterval:_.connectionsCheckingInterval}:{}},hn);_.maxConnections!==void 0&&(y.maxConnections=_.maxConnections),_.maxRequestsPerSocket!==void 0&&(y.maxRequestsPerSocket=_.maxRequestsPerSocket),_.socketTimeoutMs!==void 0&&y.setTimeout(_.socketTimeoutMs);try{await new Promise((z,B)=>{let ee=de=>B(de);y.once("error",ee),y.listen(t.port,a,()=>{y.removeListener("error",ee),z()})})}catch(z){throw se?.close(),m?.close(),D?.beginClosing(),await Promise.allSettled([D?.closeAll({timeoutMs:t.closeAllTimeoutMs??jv}),C?.close(),Promise.resolve(J.close()),Promise.resolve(Y.close())]),z}let M=y.address(),$=typeof M=="object"&&M!==null?M.port:t.port,ne=a==="0.0.0.0"||a==="::"?"127.0.0.1":a,G=`http://${ne.includes(":")?`[${ne}]`:ne}:${$}`;R("info",rt.serverListening,{url:G,host:a,port:$},We(ae.listening,{url:G})),Ta(t.readyFrame,{url:G,pid:process.pid,readyz:Tn.readyz});let Z=z=>new Promise(B=>setTimeout(B,z)),be=()=>new Promise(z=>y.getConnections((B,ee)=>z(ee??0))),ue=async z=>{x=!0,m?.close(),se?.close(),D?.beginClosing();let B=[],ee=async Xe=>{try{await Xe()}catch(X){B.push(X)}},de=t.closeAllTimeoutMs??jv,Ne=async(Xe,X)=>{await ee(async()=>{let ge=await X();ge?.timedOut===!0&&R("warn",rt.serverCloseTimeout,{face:Xe,pending:ge.pending,timeoutMs:de})})};await Ne("v1",()=>W.closeAll({timeoutMs:de})),await Ne("v2",()=>D?.closeAll({timeoutMs:de})),await ee(()=>C?.close()),await ee(()=>J.close());let Ce=new Promise((Xe,X)=>{y.close(ge=>ge!==void 0?X(ge):Xe())});if(Ce.catch(()=>{}),z){let Xe=Date.now()+kR;for(y.closeIdleConnections();await be()>0&&Date.now()<Xe;)await Z(Ef),y.closeIdleConnections()}if(y.closeAllConnections(),await ee(()=>Ce),await ee(()=>Y.close()),R("info",rt.serverClosed,{host:a,port:$},We(ae.closed)),B.length>0)throw new AggregateError(B,"Server shutdown failed.")},ke=!1,ve,Pe=async(z={})=>{let B=z.timeoutMs??SR,ee=Date.now();x=!0,J.beginDrain(),D?.beginClosing();let de=on({retryMs:k,data:""}),Ne=0;for(let Ge of A)Ge.stats().closed||(Ge.write(de),Ne+=1);Ne+=D?.broadcastRetry(k)??0;let Ce=D?.runningCount()??0;b?.info(We(ae.drainStarted,{running:Ce,subscribers:Ne,timeoutMs:B}));let Xe=ee+B;for(;(D?.runningCount()??0)>0&&Date.now()<Xe;)await Z(Ef);let X=0;if(D!==void 0&&D.runningCount()>0){X=D.interruptRunning();let Ge=Date.now()+wR;for(;D.runningCount()>0&&Date.now()<Ge;)await Z(Ef)}let ge=Math.max(0,Ce-X),Re=0,Be=[];try{Re+=await t.v2?.createSession.flush?.()??0}catch(Ge){Be.push(Ge)}try{Re+=await t.createSession.flush?.()??0}catch(Ge){Be.push(Ge)}try{await ue(!0)}catch(Ge){Be.push(Ge)}if(ke=!0,Be.length>0)throw new AggregateError(Be,"Server drain failed.");let Me={completedTurns:ge,abortedTurns:X,flushedCommits:Re,durationMs:Date.now()-ee};return b?.info(We(ae.drained,{...Me})),Me};return{port:$,host:a,url:G,activeSessionCount:()=>It(),stats:()=>Y.stats(),setSseRetryMs:z=>g.setRetryMs(z),sseStats:()=>g.stats(),readiness:()=>J.readiness(),settleResources:async()=>{for(;T.size>0;)await Promise.allSettled([...T]);let B=(await Promise.allSettled([W.settleResources(),D?.settleResources()])).flatMap(ee=>ee.status==="rejected"?[ee.reason]:[]);if(B.length>0)throw new AggregateError(B,"Server resource cleanup failed.")},drain:z=>(ve===void 0&&(ve=ke?Promise.resolve({completedTurns:0,abortedTurns:0,flushedCommits:0,durationMs:0}):Pe(z)),ve),close:async()=>{if(ve!==void 0){await ve;return}ke||(ke=!0,await ue(!1))}}}var is=[{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:Lr},{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:[...Hs]},{name:"TANSR_SERVE_READY_STREAM",group:"process",target:"readyFrame",kind:"enum",values:[...sg]},{name:"TANSR_SERVE_CWD_ON_RESUME",group:"factory",target:"factory.cwdOnResume",kind:"enum",values:["current","stored"]},{name:"TANSR_SERVE_SESSION_MAX_AGE_DAYS",group:"factory",target:"factory.sessions.retention.maxAgeDays",kind:"int",min:1,unit:"days"},{name:"TANSR_SERVE_SESSION_MAX_PER_END_USER",group:"factory",target:"factory.sessions.retention.maxPerEndUser",kind:"int",min:1}],zv=is.map(t=>t.name),Cf="(set)",IR=64,TR=new Set(["1","true","yes","on"]),AR=new Set(["0","false","no","off"]);function ER(t){let e=t?.trim();return e===void 0||e===""?void 0:e}function CR(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 TR.has(n)?{ok:!0,value:!0}:AR.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:Lv}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{ok:!1,expected:Lv}}return{ok:!0,value:e}}case"secret":return{ok:!0,value:e}}}var Lv="absolute http(s) URL";function Hv(t,e){return t.kind==="secret"?Cf:(t.kind==="string"&&t.format==="http-url"?e.replace(/\/\/[^/@?#]*@/u,"//…@").replace(/\?.*$/su,"?…"):e).slice(0,IR)}function _R(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 ji(t){return Object.keys(t).length>0}function Gv(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 is){let c=ER(t[d.name]);if(c===void 0)continue;let l=CR(d,c);if(!l.ok){i.push({name:d.name,value:Hv(d,c),expected:l.expected});continue}if(d.requires!==void 0&&!n.includes(d.requires)){i.push({name:d.name,value:Hv(d,c),expected:`${d.requires} to be set and valid (ignored without it)`});continue}_R(e,d,l.value),n.push(d.name)}let o={...ji(e.admission)?{admission:e.admission}:{},...ji(e.http)?{http:e.http}:{},...ji(e.sse)?{sse:e.sse}:{},...ji(e.observability)?{observability:e.observability}:{},...e.eventBufferMaxBytes!==void 0?{eventBufferMaxBytes:e.eventBufferMaxBytes}:{},...e.readyFrame!==void 0?{readyFrame:e.readyFrame}:{},...e.disableV1!==void 0?{disableV1:e.disableV1}:{}},s={...ji(e.timeouts)?{timeouts:e.timeouts}:{},...e.maxTurnWallClockMs!==void 0?{maxTurnWallClockMs:e.maxTurnWallClockMs}:{},...e.hostShell!==void 0?{hostShell:e.hostShell}:{}},a={...ji(e.authentication)?{authentication:e.authentication}:{},...ji(e.governance)?{governance:e.governance}:{},...e.sessionIdShard!==void 0?{sessionIdShard:e.sessionIdShard}:{},...e.notifyUrl!==void 0?{onTurnEndNotify:{url:e.notifyUrl,...e.notifySecret!==void 0?{secret:e.notifySecret}:{}}}:{}};return{server:o,v2:a,upstreamGovernor:ji(e.bulkhead)?{bulkhead:e.bulkhead}:void 0,session:s,factory:e.factory,logFormat:e.logFormat??"text",logLevel:e.logLevel??"warn",onUnhandled:e.onUnhandled,applied:n,warnings:i}}function Wv(t,...e){let n=new Set(e),i=new Set(is.filter(o=>n.has(o.group)).map(o=>o.name));return t.applied.filter(o=>i.has(o))}import{randomUUID as Ld}from"node:crypto";import{rm as HR}from"node:fs/promises";import zR from"node:path";import{randomUUID as _f}from"node:crypto";var rs=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 Vv(t){return t.reason??new DOMException("The request was aborted","AbortError")}var Jr=class{#e;#n;#r;#s;#t;#o=new Map;#i=new Map;#a=new Map;#c=new rs(qe.receiptTombstones);#d=new rs(qe.receiptTombstones);#f=new rs(qe.receiptTombstones);#m=null;#p=0;constructor(e){this.#e=e.cwd,this.#n=e.permissionTimeoutMs??qe.permissionTimeoutMs,this.#r=e.questionGraceMs??qe.questionGraceMs,this.#s=e.now??Date.now,this.#t=e.onPermissionReceipt}bindEmitter(e){this.#m=e}setCwd(e){this.#e=e}noteSubscribers(e){if(this.#p=e,e>0){for(let n of this.#a.values())n.graceTimer!==void 0&&(clearTimeout(n.graceTimer),delete n.graceTimer);return}for(let[n,i]of this.#a)i.graceTimer===void 0&&this.#v(n,i)}#w(e,n){this.#m?.(e,n)}emitPlatformWarning(e){this.#w(sn.platformWarning,e)}registerToolCall(e,n,i,o,s,a=Math.max(0,o-this.#s()),d){return this.#o.has(e)||this.#c.get(e)!==void 0?Promise.reject(new Error(`duplicate remote tool call ${e}`)):new Promise((c,l)=>{let f=setTimeout(()=>{h(new Error(`remote tool call ${e} timed out`))},Math.max(0,o-this.#s()));f.unref();let u=()=>{h(Vv(s))},m=()=>{clearTimeout(f),s.removeEventListener("abort",u),this.#o.delete(e)},h=g=>{this.#o.has(e)&&(m(),this.#c.set(e,"expired"),this.#w(sn.toolCancel,{callId:e}),l(g))};if(this.#o.set(e,{resolve:g=>{m(),this.#c.set(e,"resolved"),c(g)},cleanup:m}),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(sn.toolRequest,{callId:e,name:n,args:i,deadlineAt:o,ttlMs:a})})}submitToolResult(e,n){let i=this.#o.get(e);if(i!==void 0)return i.resolve(n.status==="ok"?{content:n.content,...n.isError===!0?{isError:!0}:{}}:{content:[{t:"text",text:n.message}],isError:!0}),"accepted";let o=this.#c.get(e);return o==="resolved"?"already_resolved":o==="expired"?"expired":"not_found"}createAskUser(){return(e,n,i)=>new Promise(o=>{let s=_f(),a=Bp({toolName:e.name,args:e.args,cwd:this.#e}),d=this.#s()+this.#n,c=setTimeout(()=>u("expired","deny"),this.#n);c.unref();let l=()=>u("expired","deny"),f=()=>{clearTimeout(c),n?.removeEventListener("abort",l),this.#i.delete(s)},u=(b,R)=>{this.#i.has(s)&&(f(),this.#d.set(s,b),this.#w(sn.permissionClosed,{requestId:s}),o(R))};if(this.#i.set(s,{digest:a,resolve:(b,R)=>{u("resolved",b);try{this.#t?.({requestId:s,verdict:b,...R!==void 0?{reason:R}:{}})}catch{}},cleanup:f}),n?.aborted===!0){l();return}n?.addEventListener("abort",l,{once:!0});let m=Ip(e.args),h=i?.executionTarget,g=h?.kind==="device"?We(tn.executionPermissionTarget,{executor:h.executorId,workspace:h.workspaceId??"",revision:h.bindingRevision}):void 0,p=g===void 0?m:[g,m].filter(Boolean).join(`
|
|
33
|
-
`),v=i??{decision:"ask",source:"mode"};this.#w(sn.permissionRequest,Jf({requestId:s,name:e.name,...p!==void 0?{summary:p}:{},attribution:{decision:v.decision,source:v.source,...v.matchedRule!==void 0?{matchedRule:v.matchedRule}:{},...v.reason!==void 0?{reason:v.reason}:{}},digest:a,expiresAt:d,ttlMs:this.#n}))})}submitPermission(e,n){let i=this.#i.get(e);if(i!==void 0)return n.digest!==i.digest?"digest_mismatch":(i.resolve(n.verdict,n.verdict==="deny"?n.reason:void 0),"accepted");let o=this.#d.get(e);return o==="resolved"?"already_resolved":o==="expired"?"expired":"not_found"}#v(e,n){n.graceTimer=setTimeout(()=>{this.#a.has(e)&&(n.cleanup(),this.#f.set(e,"expired"),this.#w(sn.questionClosed,{requestId:e}),n.reject(new em))},this.#r),n.graceTimer.unref()}createPromptChannel(){return{ask:(e,n)=>new Promise((i,o)=>{let s=_f(),a=()=>{this.#a.has(s)&&(d.cleanup(),this.#f.set(s,"expired"),this.#w(sn.questionClosed,{requestId:s}),o(Vv(n)))},d={questions:e,resolve:l=>{d.cleanup(),this.#f.set(s,"resolved"),this.#w(sn.questionClosed,{requestId:s}),i(l)},reject:o,cleanup:()=>{d.graceTimer!==void 0&&clearTimeout(d.graceTimer),n.removeEventListener("abort",a),this.#a.delete(s)}};if(this.#a.set(s,d),n.aborted){a();return}n.addEventListener("abort",a,{once:!0});let c=this.#p===0;c&&this.#v(s,d),this.#w(sn.questionRequest,{requestId:s,questions:e.map(l=>({id:l.id,prompt:l.prompt,options:l.options.map(f=>({id:f.id,label:f.label})),...l.allowMultiple!==void 0?{allowMultiple:l.allowMultiple}:{}})),...c?{expiresAt:this.#s()+this.#r,ttlMs:this.#r}:{}})})}}submitQuestionAnswers(e,n){let i=this.#a.get(e);if(i!==void 0){let s=PR(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 PR(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 $v(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?$v(t.items):r.unknown());break;case"object":e=t.properties!==void 0?Kv(t.properties):r.record(r.unknown());break}return t.description!==void 0&&(e=e.describe(t.description)),e}function Kv(t){let e={};for(let[n,i]of Object.entries(t)){let o=$v(i);e[n]=i.optional===!0?o.optional():o}return r.object(e)}function Pf(t){let e={type:t.type};if(t.description!==void 0&&(e.description=t.description),t.type==="array"&&t.items!==void 0&&(e.items=Pf(t.items)),t.type==="object"&&t.properties!==void 0){e.properties=Object.fromEntries(Object.entries(t.properties).map(([i,o])=>[i,Pf(o)]));let n=Object.entries(t.properties).filter(([,i])=>i.optional!==!0).map(([i])=>i);n.length>0&&(e.required=n)}return e}function Nd(t,e,n=Date.now,i){let o=Math.min(Math.max(t.timeoutMs??qe.toolTimeoutDefaultMs,qe.toolTimeoutMinMs),qe.toolTimeoutCapMs),s=t.parameters!==void 0?Kv(t.parameters):r.object({}),a={name:t.name,description:t.description,inputSchema:s,argsValidation:"remote",isReadOnly:t.readOnly??!1,...t.effects!==void 0?{effects:t.effects}:{},isConcurrencySafe:!0,timeoutMs:o,async execute(c,l){let f=s.safeParse(c);if(!f.success){let m=f.error.issues.map(h=>h.path.length>0?`${h.path.join(".")}: ${h.message}`:h.message).join("; ");return{content:[{t:"text",text:`invalid ${t.name} args: ${m}`}],isError:!0}}if(i!==void 0)return i(f.data,l);let u=l.toolCallId??_f();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,Pf(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 MR from"node:path";function Qv(t){return t instanceof gn&&t.code==="INVALID_CHECKPOINT_ID"}function os(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=>MR.join(t.dir,"agent-checkpoints",Gt(i))),n={...t.max!==void 0?{max:t.max}:{},...t.retention!==void 0?{retention:t.retention}:{}};return{put(i,o,s){return Mc(e(i,o.sessionId),o,{...n,...s?.attachmentsFrom!==void 0?{attachmentsFrom:s.attachmentsFrom}:{}})},async get(i,o,s){try{return await Oc(e(i,o),o,s)}catch(a){if(Qv(a))return null;throw a}},list(i,o){return Bc(e(i,o),o)},async delete(i,o,s){try{return await qc(e(i,o),o,s)}catch(a){if(Qv(a))return!1;throw a}}}}function mr(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 Jv(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 Ln=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 Zv,{posix as eb}from"node:path";var Mf="adjudicator_unavailable",Of="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 Ud(t,e,n){if(ul("createAgentSessionFactory",e),e?.enabled===!1)return;if(t.assembleAdjudicator===void 0){e!==void 0&&t.onAdjudicationWarning?.({code:Mf,message:Of});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=Cp(i,n);return t.assembleAdjudicator({posture:o,postureExplicit:i!==void 0,...e?.callBudget!==void 0?{callBudget:e.callBudget}:{}})}function OR(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 Yv(t,e){let n=t.timeoutMs??1e4;if(!Number.isSafeInteger(n)||n<1||n>12e4)throw new RangeError("Invalid trusted hook timeout");let i=new AbortController,o=new Set,s;async function a(l,f){let u=new AbortController,m=AbortSignal.any([f,i.signal,u.signal]);m.throwIfAborted();let h=setTimeout(()=>u.abort(new Error("Trusted hook timed out")),n),g,p=new Promise((R,w)=>{g=()=>w(m.reason),m.addEventListener("abort",g,{once:!0})}),v=Promise.resolve().then(()=>(m.throwIfAborted(),l(m))),b=v.catch(()=>{});o.add(b),b.finally(()=>o.delete(b));try{let R=await Promise.race([v,p]);return m.throwIfAborted(),R}finally{clearTimeout(h),m.removeEventListener("abort",g)}}let d=()=>(e(),{blocked:!0});async function c(l,f){try{return OR(await a(l,f))}catch{return d()}}return{queryHooks(l){let f;try{i.signal.throwIfAborted();let u=t.queryHooks===void 0?{}:t.queryHooks(Object.freeze([...l]));if(!u||typeof u!="object"||Array.isArray(u))throw new TypeError("Invalid trusted query hooks");let m={};for(let g of["userPromptSubmit","postToolUse","stop","preCompact","postCompact"]){let p=u[g];if(p!==void 0){if(typeof p!="function")throw new TypeError("Invalid trusted query hook callback");Object.defineProperty(m,g,{value:p,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");m.maxConsecutiveStopBlocks=h}f=Object.freeze(m)}catch{return{userPromptSubmit:d,preCompact:d,stop:d}}return{...f.userPromptSubmit===void 0?{}:{userPromptSubmit:u=>c(m=>f.userPromptSubmit({...u,signal:m}),u.signal)},...f.postToolUse===void 0?{}:{postToolUse:u=>c(m=>f.postToolUse({...u,signal:m}),u.signal)},...f.stop===void 0?{}:{stop:u=>c(m=>f.stop({...u,signal:m}),u.signal)},...f.preCompact===void 0?{}:{preCompact:u=>c(m=>f.preCompact({...u,signal:m}),u.signal)},...f.postCompact===void 0?{}:{postCompact:u=>a(m=>f.postCompact({...u,signal:m}),u.signal)},...f.maxConsecutiveStopBlocks===void 0?{}:{maxConsecutiveStopBlocks:f.maxConsecutiveStopBlocks}}},async system(l,f){return BR(await a(l,f))},boundary(l){return t.beforeTool?{resolve(f,u){let m=l.resolve(f,u);if(m)return{...m,executeService:async(h,g,p)=>{let v=structuredClone(h),b=await c(R=>t.beforeTool(v,{signal:R}),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 m.assertCurrent(),g.throwIfAborted(),i.signal.throwIfAborted(),m.executeService?m.executeService(h,g,p):p())}}}}:l},stop(){i.abort()},close(){return s||(i.abort(),s=(async()=>{for(;o.size;)await Promise.all([...o]);await t.onClosed?.()})(),s)}}}function BR(t){if(!t||typeof t!="object")throw new TypeError("Invalid trusted system configuration");for(let e of[t.system,t.systemAppend])if(e!==void 0&&(!Array.isArray(e)||e.some(n=>!n||typeof n.text!="string")))throw new TypeError("Invalid trusted system segments");return structuredClone(t)}var qR=1e4,DR=1e3,jR=12e4;function NR(t,e){return Sc(t===void 0?void 0:{...t.maxUsd!==void 0?{maxUsd:t.maxUsd}:{},...t.maxTokens!==void 0?{maxTotalTokens:t.maxTokens}:{}},e)}function UR(t,e){return ol(t,e)?.quirks?.reasoningTokens}var FR;function LR(t,e){let n=t.capabilities;if(n===void 0)return[_s(e.todoStore),Ms(e.channel)];let i=[];if(n.tools.todoWrite&&i.push(_s(e.todoStore)),n.tools.askUser&&i.push(Ms(e.channel)),n.tools.webFetch||n.tools.http){let a=FR??=to({env:process.env});n.tools.webFetch&&i.push(Gc({client:a})),n.tools.http&&i.push(Vc({client:a,env:{},allowedAuthEnvVars:[],allowPrivate:!1}))}let o=t.platformTools;if(o===void 0)return i;let s={baseUrl:o.baseUrl,token:Gi,fetchImpl:o.fetchImpl};return n.tools.webSearch&&n.platform.webSearch&&i.push(Wc({provider:Da(s)})),n.platform.imageGen&&i.push(Bs({provider:co({...s,models:o.platformModels.imageGen})})),n.platform.videoGen&&i.push(qs({provider:lo({...s,models:o.platformModels.videoGen})})),n.platform.speechToText&&i.push(Ds({provider:fo({...s,models:o.platformModels.speechToText})})),n.platform.textToSpeech&&i.push(js({provider:mo({...s,models:o.platformModels.textToSpeech})})),i}function Fd(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 Ye("validation_failed",We(tn.platformProfileUnsupported,{profile:n.profile}));let o=i?.assembleModel;if(o===void 0)throw new Error("platform serve session factory requires extras.assembleModel (per-endUser platform token assembly)");let s=null,a=i?.trustedScope;if((t.trustedExtensionsFor||t.systemFor)&&!a)throw new TypeError("Trusted host extensions require an authenticated scope");let d=t.trustedExtensionsFor?.(Object.freeze({...a})),c=d?.decorateModelClient;if(c!==void 0&&typeof c!="function")throw new TypeError("Invalid trusted model client decorator");let l=d===void 0&&t.systemFor===void 0?void 0:Yv(d??{},()=>s?.interrupt()),f=n.model??"main",u=o(f,X=>{let ge=so(X);ge!==null&&s?.pushBody(ge,"provider")}),m=e===void 0?u.maxOutputTokens:Math.min(e,u.maxOutputTokens??e),h=e===void 0?t.maxTokens??Li:Math.min(t.maxTokens??Li,m),g=e===void 0?u.compaction??{}:{...u.compaction,maxOutputTokens:Math.min(u.compaction?.maxOutputTokens??1/0,m)};if(i?.execution!==void 0){if(u.refreshApplicationCapabilities===void 0)throw new Error("Remote execution requires authoritative application capabilities");i.execution.bindApplicationCapabilities(u.refreshApplicationCapabilities)}let p=t.system?.map(X=>({...X})),v=t.systemAppend?.map(X=>({...X}))??[],b,R=[],w,x=new WeakMap,T=X=>{let ge=jo(X,p),Re=[...ge.system,...v.map(Be=>({...Be})),...i?.execution?.systemSegments()??[],...R];return x.set(Re,Object.freeze({...ge.info})),Re},P=new ys({onChange:X=>s?.pushBody({type:"plan.todo.updated",items:X},"tool")});b=T(u);let W=i?.promptChannel??new Ps,K=LR(u,{todoStore:P,channel:W});if(u.capabilities!==void 0&&!u.capabilities.tools.customTools&&i?.sessionTools!==void 0&&i.sessionTools.length>0)throw new Ye("validation_failed",We(tn.capabilityDisabled,{bit:"customTools"}));let D=n.tools!==void 0?new Set(n.tools):void 0,J=D!==void 0?K.filter(X=>D.has(X.name)):K,S=i?.capabilityProfile,k=S!==void 0?K.map(X=>X.name).filter(X=>!S.tools.includes(X)):[],A=i?.execution,C=()=>me([A?.binding,A?.policy.authorizationRevision,A?.attachmentSourceRevision,A?.attachmentSource]),F=()=>{},L=new Wn,Q=[];for(let X of J)L.register(X),Q.push(vn(X));if(i?.sessionTools!==void 0)for(let{tool:X,def:ge}of i.sessionTools){if(K.some(Re=>Re.name===X.name))throw new Ln(X.name);L.register(X),Q.push(ge)}let se=A?.boundary(J);if(d?.beforeTool&&!se)throw new TypeError("Trusted tool control requires an explicit execution host");let O=se===void 0||l===void 0?se:{...l.boundary(se),registerBuiltin:se.registerBuiltin},I,q=async X=>{if(A===void 0)return;await A.refresh(X),X.throwIfAborted();let ge=C();ge!==I&&((I!==void 0||A.binding!==null)&&s?.invalidateAttachmentReferences(),F(),I=ge),s?.updateAttachmentSource(A.attachmentSource);let Re=[...J],Be=new Set(K.map(Ue=>Ue.name));for(let Ue of[...A.deviceTools(),...A.serviceTools()]){if(Be.has(Ue.name))throw new Ln(Ue.name);Be.add(Ue.name),(D===void 0||D.has(Ue.name)||A.isClientTool(Ue.name)||A.isShellAuxiliary(Ue.name)&&D.has("Shell"))&&Re.push(Ue)}let Me=A.filterTools(Re.map(Ue=>A.definition(Ue)??vn(Ue))),Ge=new Set(Me.map(Ue=>Ue.name));if(Ge.size!==Me.length||Me.some(Ue=>!Re.some(Oe=>Oe.name===Ue.name)))throw new Error("Execution policy returned invalid tool definitions.");let he=new Map(Re.filter(Ue=>Ge.has(Ue.name)).map(Ue=>[Ue.name,Ue]));for(let Ue of L.names())L.get(Ue)!==he.get(Ue)&&L.unregister(Ue);for(let Ue of he.values())L.has(Ue.name)||L.register(Ue);Q.splice(0,Q.length,...Me)},H=X=>{let ge=c===void 0?X:c(X);if(!ge||typeof ge.stream!="function")throw new TypeError("Invalid trusted model client");let Re=zn(ge,X);return A===void 0&&t.memoryFor===void 0&&t.memoryPublicationFor===void 0?Re:zn({async*stream(Be,Me){let Ge=Me?.signal??new AbortController().signal;if(await q(Ge),A?.assertModelRequestsAllowed(),await re?.verifyAvailable(),Ge.throwIfAborted(),w!==void 0&&w!==C())throw new Ve("stale_generation");let he=Be.tools.length===0?[]:Q,Ue=Xd(X)?Zd(Be,he):{...Be,tools:he};yield*Re.stream(Ue,Me)}},X)},N=H(u.client),ie=i?.cwd??t.cwd,U=Ud(u,t.adjudication,i?.askUser!==void 0),ce=new eo({...U!==void 0?{mode:kc({posture:U.posture,tier:U.tier}),classifier:U.config}:{},...t.hostShell!==void 0?{hostShell:t.hostShell}:{}}),le=Ci(ce,L,{cwd:ie}),re,pe=new ws({registry:L,cwd:ie,permissionGate:le,...O===void 0?{}:{executionBoundary:O},...i?.askUser!==void 0?{askUser:i.askUser}:{},...t.onDecision!==void 0?{onDecision:t.onDecision}:{},...A?.host.options.memoryFor===void 0?{}:{onBoundToolSucceeded:(X,ge)=>{let Re=A.binding,Be=_;if(!Nt||Be===void 0||Re===null||ge.kind!=="device"||ge.bindingId!==Re.bindingId||ge.bindingRevision!==Re.revision||ge.authorizationRevision!==A.policy.authorizationRevision||!A.available("Read")||!A.available("List")||!["Read","Write","Edit"].includes(X.name))return;let Me=X.args!==null&&typeof X.args=="object"?X.args.file_path:void 0;if(typeof Me!="string"||/[\\\u0000]/.test(Me))return;let Ge=eb.resolve(Be.root,Me);Ge!==Be.root&&!Ge.startsWith(Be.root+"/")||ze?.observeTouched([{toolName:X.name,paths:[Ge]}])}}}),j=i?.sessionId??Xv(),Y=i?.memoryScope??{sessionId:j,...A===void 0?{}:{applicationScopeId:A.host.options.applicationScopeId,endUserId:A.user}},oe=D===void 0||D.has("SearchMemory")?t.memoryFor?.(Y):void 0,Se=D===void 0||D.has("SearchMemory")?t.memoryPublicationFor?.(Y):void 0,je=oe!==void 0||Se!==void 0;if(oe&&Se)throw new Ye("validation_failed","Choose one trusted memory source per session");if(Se&&(!A||Se.identity.kind!=="client-managed"))throw new Ye("validation_failed","Client memory requires execution");let $e=oe?.host?.authority.identity??Se?.identity;if($e!==void 0&&(Y.applicationScopeId!==void 0&&$e.applicationScopeId!==Y.applicationScopeId||Y.endUserId!==void 0&&$e.endUserId!==Y.endUserId))throw new Ye("validation_failed","Memory source ownership mismatch");if(je&&A?.host.options.memoryFor!==void 0)throw new Ye("validation_failed","Choose one trusted memory source per session");if(je&&i?.persistBackgroundUsage===null)throw new Ye("validation_failed","Memory requires background usage persistence");let Fe=new Set,ft=[],kt=X=>{Fe.add(X),X.finally(()=>Fe.delete(X)).catch(()=>{})},ze,it,It=i?.memorySelectionPersistence?.checkpoint===void 0?void 0:Fp(i.memorySelectionPersistence.checkpoint,i.memorySelectionPersistence.scope),Wt,un="",_n=!1,Nt=!1,hn=!1,_,y=new AbortController;F=()=>{Nt=!1,hn=!1,_?.cancel(),_=void 0,ze?.invalidate?.(),it?.invalidateSource()};let M=(X,ge,Re,Be)=>{if(_?.key===X)return _;F();let Me,Ge=Oe=>{if(Oe.throwIfAborted(),ge!==C())throw new Ve("stale_generation")},he=async(Oe,Je,ot)=>{let Ot=Me;if(Ot===void 0||A===void 0)throw new Ve("source_unavailable");let Yt=Ot.signal;await A.refresh(Yt),Ge(Yt);let Xt=L.get(Oe),Sn=Oe==="Read"?{file_path:Je}:{path:Je},xt={id:"memory-"+Xv(),name:Oe,args:Sn,blockIndex:0};if(!A.available(Oe)||!Xt||!Xt.isReadOnly)throw Object.assign(new Error("Memory resource unavailable"),{code:"EACCES"});let cn,Hn,Vt={...Xt,async execute(mt,Ut){if(Ge(Yt),me(mt)!==me(Sn)||Ut.executionTarget?.kind!=="device"||!Ut.fs)throw Object.assign(new Error("Memory resource identity changed"),{code:"EACCES"});let $t=performance.now(),te=setTimeout(()=>Ot.deadline.abort(),Math.max(1,Ot.remainingMs));try{return cn={value:await ot(Ut.fs)},Ge(Yt),{content:[]}}catch(Ie){throw Hn=Ie,Ie}finally{clearTimeout(te),Ot.remainingMs-=performance.now()-$t,Ot.remainingMs<=0&&Ot.deadline.abort()}}},wn=new Wn;wn.register(Vt);let bt=new ws({registry:wn,cwd:Re,permissionGate:le,executionBoundary:{resolve(mt,Ut){if(Ge(Yt),!(mt!==Vt||L.get(Oe)!==Xt))return O?.resolve(Xt,Ut)}},...i?.askUser===void 0?{}:{askUser:i.askUser},...t.onDecision===void 0?{}:{onDecision:t.onDecision}}),At=(async()=>{let mt=bt.execute([xt],{sessionId:j,turnId:xt.id,toolRound:0,signal:Yt,registerOperation:kt});for(;;){let Ut=await mt.next();if(Ut.done){if(await A.refresh(Yt),Ge(Yt),Hn!==void 0)throw Hn;if(Ut.value.aborted||Ut.value.results[0]?.isError||cn===void 0)throw Object.assign(new Error("Memory permission or execution denied"),{code:"EACCES"});return cn.value}Ut.value.t==="event"&&s?.pushBody(Ut.value.body,"tool")}})();return kt(At),At};return _={key:X,scope:ge,root:Re,source:{pathStyle:"posix",orgMemoryGate:()=>({inject:Be}),fs:{lstat:Oe=>he("Read",Oe,Je=>Je.lstat(Oe)),readFilePrefix:(Oe,Je)=>he("Read",Oe,ot=>ot.readFilePrefix(Oe,Je)),readdir:Oe=>he("List",Oe,Je=>Je.readdir(Oe))}},begin(Oe,Je){Me?.deadline.abort();let ot=new AbortController;return Me={signal:AbortSignal.any([Oe,ot.signal,y.signal]),deadline:ot,remainingMs:Je},Me.signal},cancel(){Me?.deadline.abort(),Me=void 0}},_},$=async X=>{if(R=[],w=void 0,Nt=!1,hn=!1,!A?.binding||!A.host.options.memoryFor||!A.available("Read")){F();return}let ge=C(),Re=A.binding.target,Be=A.root(),Me=A.host.options.memoryFor({applicationScopeId:A.host.options.applicationScopeId,endUserId:A.user,sessionId:j,workspaceId:Re.workspaceId,workspaceRevision:Re.workspaceRevision});if(!Me){F();return}let Ge=xt=>{if(typeof xt!="string"||xt.startsWith("/")||/[\\:\u0000-\u001f\u007f]/.test(xt)||xt!==""&&xt.split("/").some(cn=>cn===""||cn==="."||cn===".."))throw new Ve("invalid_request",400);return eb.join(Be,xt)},he=Ge(Me.cwd??""),Ue=Me.userDir===void 0?void 0:Ge(Me.userDir),Oe=Me.autoMemoryDir===void 0||Me.autoMemory===!1?void 0:Ge(Me.autoMemoryDir),Je=Me.deviceIoBudgetMs??qR;if(!Number.isInteger(Je)||Je<DR||Je>jR)throw new Ve("invalid_request",400);let ot=me([ge,he,Ue??null,Oe??null,Me.orgMemory===!0]),Ot=_?.key!==ot,Yt=M(ot,ge,Be,Me.orgMemory===!0),Xt=Yt.begin(X,Je),Sn=Yt.source;w=ge;try{let xt=await kp(he,Be,{boundary:Be,source:Sn,signal:Xt,...Ue===void 0?{}:{userDir:Ue},...Oe===void 0?{}:{autoMemory:{dir:Oe}}});if(await A.refresh(Xt),Xt.throwIfAborted(),ge!==C())throw new Ve("stale_generation");if(xt.warnings.length&&s?.pushControl(sn.platformWarning,{code:"memory_source_partial",message:xt.warnings.join(`
|
|
34
|
-
`)}),xt.segments.length&&(R=[{text:Dp(xt.segments),cacheable:!1}]),Oe!==void 0&&A.available("List")){let cn={dir:Oe,roots:[he,Be],source:Sn};if(ze===void 0?ze=Es(cn):Ot&&ze.invalidate?.(cn),Nt=!0,Me.recallSelector===!0){if(i?.persistBackgroundUsage===null||i?.persistBackgroundUsage!==void 0&&i.memorySelectionPersistence===void 0)throw new Ve("invalid_request",400);let Hn={fileBytes:Me.recallBudgets?.fileBytes??jp,roundBytes:Me.recallBudgets?.roundBytes??Np,sessionBytes:Me.recallBudgets?.sessionBytes??Up},Vt=me(Hn);if(Wt!==void 0&&Wt!==Vt)throw new Ve("invalid_request",400);if(it===void 0){Wt=Vt;let wn=Cs({dir:Oe,source:Sn,budgets:Hn,...Z===void 0?{}:{budget:Z},excludeFiles:["pending-anchors.md"],modelTier:()=>{let At=u.memoryModel??s?.modelBinding()??{client:u.client,model:u.model},mt=_;return{...At,client:zn({async*stream(Ut,$t){let te=$t?.signal??new AbortController().signal;if(await A.refresh(te),te.throwIfAborted(),mt===void 0||mt.scope!==C())throw new Ve("stale_generation");yield*At.client.stream(Ut,$t)}},At.client)}},onUsage:(At,mt)=>{G?.record({provider:mt.provider,model:mt.model,usage:At,purpose:"memory"})?.accepted&&(be++,kt(ve().catch($t=>{ft.push($t)})))}}),bt=i?.memorySelectionPersistence;try{It!==void 0&&bt!==void 0&&wn.restoreCheckpoint(It,bt.scope)}catch{throw wn.dispose(),new Ve("invalid_request",400)}it=wn}else Ot&&it.invalidateSource({dir:Oe,source:Sn});hn=!0}else it?.invalidateSource()}else ze?.invalidate?.(),it?.invalidateSource()}catch(xt){if(X.throwIfAborted(),F(),R=[],xt instanceof Ve&&xt.code==="invalid_request")throw xt;s?.pushControl(sn.platformWarning,{code:"memory_source_unavailable",message:We(tn.memorySourceUnavailable)})}},ne={sessionId:j,...u.pricing!==void 0?{pricing:u.pricing}:{},resolveReasoningTokens:UR},G=n.budget!==void 0||A?.host.options.memoryFor!==void 0||je?i?.usageSnapshot!==void 0?Us.fromSnapshot(i.usageSnapshot,ne):new Us(ne):void 0,Z=G!==void 0?NR(n.budget,()=>G.snapshot()):void 0,be=0,ue=0,ke=Promise.resolve(),ve=()=>(ke=ke.catch(()=>{}).then(async()=>{if(G===void 0||typeof i?.persistBackgroundUsage!="function"||be===ue)return;let X=be;await i.persistBackgroundUsage(G.snapshot()),ue=X}),ke),Pe=i?.onTurnEnd!==void 0||je?X=>{re?.onTurnEnd(X),i?.onTurnEnd?.(G===void 0?X:{...X,costSnapshot:G.snapshot()})}:void 0,z;if(A!==void 0&&O!==void 0&&u.capabilities?.tools.agent){if(L.has("Task"))throw new Ln("Task");let X=(Oe,Je)=>ot=>{let Ot=()=>me({binding:A.binding,revision:A.policy.authorizationRevision,tools:A.policy.tools}),Yt=Je??Ot(),Xt=()=>{if(Yt!==Ot()||!A.available("Task")&&!A.available("SpawnAgent"))throw new Ve("stale_generation")};Xt();let Sn=new Map(ot.replacements.map(bt=>[bt.replacement,bt.original])),xt=new Map,cn=new Set(A.policy.tools),Hn=new Set(ot.localTools),Vt=async()=>{await A.refresh(new AbortController().signal),Xt()};for(let bt of ot.toolset.registry.names()){let At=ot.toolset.registry.get(bt),mt=At,Ut=new Set;if(Hn.has(At)){xt.set(At,{target:{kind:"controlled-service",executorId:"managed-service",bindingId:j,bindingRevision:"0",authorizationRevision:A.policy.authorizationRevision},assertCurrent:Vt});continue}let $t;for(;$t=Oe.resolve(mt,{id:"subagent-scope",name:mt.name,args:{},blockIndex:0}),!($t!==void 0||Ut.has(mt)||!Sn.has(mt));)Ut.add(mt),mt=Sn.get(mt);$t!==void 0&&xt.set(At,$t)}let wn={resolve:bt=>{if(ot.toolset.registry.get(bt.name)!==bt)return;let At=xt.get(bt)??(cn.has(bt.name)&&A.isChildMcpTool(ot.toolset.registry,bt)?O.resolve(bt,{id:"subagent-mcp",name:bt.name,args:{},blockIndex:0}):void 0);if(At!==void 0)return{...At,assertCurrent:async()=>{Xt(),await At.assertCurrent(),Xt()}}}};return{executionBoundary:wn,derive:X(wn,Yt),permissionGate:Ci(ce,ot.toolset.registry,{cwd:ie}),wrapClient:bt=>zn({async*stream(At,mt){let Ut=mt?.signal??new AbortController().signal;await q(Ut),A.assertModelRequestsAllowed(),Xt(),await re?.verifyAvailable(),Ut.throwIfAborted();let $t=At.tools.filter(Ie=>{let Ee=ot.toolset.registry.get(Ie.name);return Ee!==void 0&&(xt.has(Ee)&&(A.available(Ie.name)||Hn.has(Ee))||cn.has(Ee.name)&&A.isChildMcpTool(ot.toolset.registry,Ee)&&A.available(Ee.name))}),te=Xd(bt)?Zd(At,$t):{...At,tools:$t};yield*bt.stream(te,mt)}},bt)}},ge=A.host.options.subagentsFor?.({applicationScopeId:A.host.options.applicationScopeId,endUserId:A.user,sessionId:j});if(ge!==void 0&&(typeof ge.onNotification!="function"||ge.background!==void 0&&(typeof ge.background.outputFile!="function"||typeof ge.background.writeFileImpl!="function")))throw new TypeError("Subagent notification and report storage callbacks are required");if(G!==void 0&&i?.persistBackgroundUsage===null&&(ge?.continuableAgents===!0||ge?.background!==void 0))throw new Ye("validation_failed",We(tn.backgroundUsageStoreRequired));let Re=ge===void 0?void 0:async Oe=>{Oe.channel==="settled"&&await ve(),await ge.onNotification(Oe)},Be=ge?.background===void 0?void 0:new im({emit:Oe=>s?.pushBody(Oe,"agent"),onNotification:Re,writeFileImpl:ge.background.writeFileImpl}),Me=()=>{let Oe=s?.modelBinding()??{client:u.client,model:u.model,maxOutputTokens:m};return{client:Oe.client,parentModel:Oe.model,maxTokens:Math.min(t.maxTokens??Li,e??1/0,Oe.maxOutputTokens??1/0)}},Ge={client:N,system:()=>b,parentModel:u.model,parentBinding:Me,maxTokens:h,sessionId:j,permissionGate:le,mcpDiscover:Oe=>A.childMcpDiscover(Oe),execution:X(O),...Z===void 0?{}:{budget:Z},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:()=>ce.getMode()==="default",...i?.askUser===void 0?{}:{askUser:i.askUser},...G===void 0?{}:{onQueryUsage:(Oe,Je)=>{G.record({provider:(Je??u.model).provider,model:(Je??u.model).model,usage:Oe,purpose:"other"}).accepted&&be++}},budget:()=>{if(ce.getClassifierBreakerState().tripped!=="none")return"breaker_open";if(Z!==void 0&&(Z.onExceeded??"block")==="block"){let Oe=Z.getSpend();if(Z.maxTotalTokens!==void 0&&Oe.totalTokens>=Z.maxTotalTokens||Z.maxUsd!==void 0&&Oe.usdNano>=Z.maxUsd*1e9)return"budget_exhausted"}return ce.tryConsumeSharedConsult()?"ok":"budget_exhausted"}},...Be===void 0?{}:{background:{runner:Be,outputFile:ge.background.outputFile}}};Uo({registry:L,toolDefs:Q},Ge);let he=L.get("Task");K.push(he),O.registerBuiltin?.(he),J!==K&&(D===void 0||D.has("Task"))&&J.push(he),D!==void 0&&!D.has("Task")&&(L.unregister("Task"),Q.splice(Q.findIndex(Oe=>Oe.name==="Task"),1));let Ue=ge?.continuableAgents!==!0?void 0:new am({client:N,model:u.model,maxTokens:h,sessionId:j,cwd:ie,modelBinding:()=>{let Oe=s?.modelBinding()??u;return{client:Oe.client,model:Oe.model,maxTokens:Me().maxTokens,...Oe.contextWindowTokens===void 0?{}:{contextWindowTokens:Oe.contextWindowTokens}}},permissionGate:le,execution:Ge.execution,...Z===void 0?{}:{budget:Z},...u.contextWindowTokens===void 0?{}:{contextWindowTokens:u.contextWindowTokens},emit:Oe=>s?.pushBody(Oe,"agent"),onNotification:Re});if(Ue!==void 0){let Oe=[dm({manager:Ue,client:N,parentModel:u.model,parentBinding:Me,system:()=>b,toolset:{registry:L,toolDefs:Q},agents:Os,nestedTask:Ge,adjudication:Ge.adjudication,mcpDiscover:Je=>A.childMcpDiscover(Je)}),cm({manager:Ue})];for(let Je of Oe){if(L.has(Je.name))throw new Ln(Je.name);K.push(Je),O.registerBuiltin?.(Je),!(D!==void 0&&!D.has(Je.name))&&(J!==K&&J.push(Je),L.register(Je),Q.push(vn(Je)))}}(Ue!==void 0||Be!==void 0)&&(A.attachChildrenIdle(async()=>{let Oe=()=>(Be?.size??0)>0||Ue?.list().some(ot=>ot.status!=="settled"||ot.queuedMessages>0)===!0;if(Oe())return!1;let Je=await Promise.all([Ue?.settleResources({timeoutMs:0}),Be?.settleResources({timeoutMs:0})]);return!Oe()&&Je.every(ot=>ot===void 0||ot.status==="completed")}),z=async()=>{let Oe=await Promise.allSettled([Ue?.drain(),Be?.drain()]),Je=await Promise.all([Ue?.settleResources({timeoutMs:1/0}),Be?.settleResources({timeoutMs:1/0})]),ot=Oe.flatMap(Ot=>Ot.status==="rejected"?[Ot.reason]:[]);ot.push(...Je.flatMap(Ot=>Ot?.failures.map(Yt=>Yt.cause)??[]));try{await ve()}catch(Ot){ot.push(Ot)}if(ot.length)throw new AggregateError(ot,"Subagent resource cleanup failed")})}let B,ee=!1,de,Ne=X=>{if(ee)throw new Error("Memory is closed");re=wv({config:X,sessionId:j,...Z===void 0?{}:{budget:Z},modelTier:()=>(A?.assertModelRequestsAllowed(),u.memoryModel!==void 0?{...u.memoryModel,modelSource:u.memoryModel.source??"main"}:{...s?.modelBinding()??{client:u.client,model:u.model},modelSource:"main"}),system:()=>b,history:()=>s?.historySnapshot().messages??[],...i?.askUser===void 0?{}:{askUser:i.askUser},...t.onDecision===void 0?{}:{onDecision:t.onDecision},onUsage:Re=>{G?.record({provider:Re.provider??u.model.provider,model:Re.model,usage:Re.usage,purpose:"memory"})?.accepted&&(be++,kt(ve().catch(Me=>{ft.push(Me)})))}});let ge=re.searchTool;if(L.has(ge.name))throw new Ln(ge.name);return L.register(ge),Q.push(vn(ge)),J.push(ge),O?.registerBuiltin?.(ge),s&&Qr(s,re),de&&(re.onTurnStart(de),de=void 0),re.start(),re};oe&&Ne(oe);let Ce=Se===void 0?void 0:{capability:()=>!ee&&Se.enabled()&&A?.memoryPublicationSupported()===!0,prepare:async X=>{if(X.throwIfAborted(),ee||!Se.enabled())throw new Error("Memory source unavailable");return re?(await re.verifyAvailable(),re):(B??=(async()=>{let ge=AbortSignal.any([X,y.signal]);await A.refresh(ge),ge.throwIfAborted();let Re=await A.createMemoryPublicationStore(Se.identity,{signal:y.signal,enabled:Se.enabled}),Be=await Xa.open({identity:Se.identity,store:Re,mode:Se.mode,assertCurrent:()=>{if(ee||!Se.enabled()||!A.memoryPublicationAvailable())throw new Error("Memory source unavailable")},...Se.minimumDeletionGeneration?{minimumDeletionGeneration:Se.minimumDeletionGeneration}:{}});ge.throwIfAborted();let Me=await Be.createHost({...Se.provenance?{provenance:Se.provenance}:{}}),Ge=he=>{if(Zv.isAbsolute(he)||he.split(/[\\/]/).some(Ue=>Ue===".."||Ue===""))throw new Error("Invalid promotion target");return Zv.join(Me.rootDir,he)};return ge.throwIfAborted(),Ne({kind:"client-managed",domain:Se.identity.domain,host:Me,management:Be,rootDir:Me.rootDir,memoryDir:Me.memoryDir,enabled:Se.enabled,balance:Se.balance,...Se.promotion?{projectAgentsPath:Ge(Se.promotion.projectFile),userAgentsPath:Ge(Se.promotion.userFile)}:{},...Se.extraction?{extraction:Se.extraction}:{},...Se.recallSelector===void 0?{}:{recallSelector:Se.recallSelector},...Se.onObservation?{onObservation:Se.onObservation}:{}})})(),B)}};je&&A?.bindMemorySearch(()=>re!==void 0&&re.status().enabled);let Xe=new ai({client:N,executor:pe,...z===void 0&&A?.host.options.memoryFor===void 0&&!je&&l===void 0?{}:{onClosed:async()=>{let X=[];l?.stop(),ee=!0,y.abort();let ge=z?.().catch(Me=>{X.push(Me)});ze?.dispose?.(),it?.dispose();try{await B?.catch(()=>{}),await re?.close()}catch(Me){X.push(Me)}let Re=await Promise.all([ze?.settleResources?.({timeoutMs:1/0}),it?.settleResources?.({timeoutMs:1/0})]);for(;Fe.size;)await Promise.allSettled([...Fe]);await ge;let Be=[...X,...Re.flatMap(Me=>Me?.failures.map(Ge=>Ge.cause)??[])];try{await ve()}catch(Me){Be.push(Me)}try{await l?.close()}catch(Me){Be.push(Me)}if(Be.push(...ft),Be.length)throw new AggregateError(Be,"Memory resource cleanup failed")}},system:b,applicationPromptInfo:x,...d?.queryHooks===void 0?{}:{queryHooks:X=>l.queryHooks(X)},...i?.attachmentPersistence===void 0?{}:{attachmentPersistence:i.attachmentPersistence},...i?.memorySelectionPersistence===void 0?{}:{getMemorySelectionCheckpoint:()=>it?.snapshotCheckpoint(i.memorySelectionPersistence.scope)??It},...u.refreshApplicationPrompt!==void 0||A!==void 0||je||t.systemFor!==void 0?{prepareSystem:async X=>{let ge=u.refreshApplicationPrompt===void 0?u:await u.refreshApplicationPrompt(X);if(t.systemFor!==void 0){let Re=await l.system(Be=>t.systemFor(Object.freeze({...a}),Be),X);X.throwIfAborted(),p=(Re.system??t.system)?.map(Be=>({...Be})),v=(Re.systemAppend??t.systemAppend??[]).map(Be=>({...Be}))}return await q(X),await $(X),await Ce?.prepare(X),re!==void 0&&(R=await re.prepare(X)),b=T(ge),b}}:{},tools:Q,model:u.model,cwd:ie,...u.contextWindowTokens!==void 0?{contextWindowTokens:u.contextWindowTokens}:{},...m!==void 0?{maxOutputTokens:m}:{},...t.maxTokens!==void 0?{maxTokens:t.maxTokens}:{},sessionId:j,...Z!==void 0?{budget:Z}:{},...G!==void 0?{runtimeCostSnapshot:()=>G.snapshot(),onEvent:X=>{G.consume(X)?.accepted&&(be++,X.type==="cost.usage.updated"&&X.purpose==="compaction"&&typeof i?.persistBackgroundUsage=="function"&&s?.retainCostPersistence(ve()))}}:{},...i?.initialHistory!==void 0?{initialHistory:i.initialHistory}:{},...i?.initialSeq!==void 0?{initialSeq:i.initialSeq}:{},maxTurnsPerQuery:t.maxTurnsPerQuery??ep,...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:je?{...g,observer:{...g.observer,onCompactionFinished:X=>{g.observer?.onCompactionFinished?.(X),re?.compactionObserver.onCompactionFinished?.(X)}}}:g,...u.compactionManagerOptions!==void 0?{compactionManagerOptions:u.compactionManagerOptions}:{},reminders:up({todoStore:P,...A?.host.options.memoryFor===void 0&&!je?{}:{prepareMemoryRecalls:async X=>{await q(X),await re?.prepareReminders(X),_n&&(_n=!1,hn&&it?.prefetch(un)),Nt&&(await ze?.prepareReminders?.(X),await q(X))},drainMemoryRecalls:()=>[...re?.drainReminders()??[],...Nt?ze?.drainReminderEntries?.()??[]:[]],drainMemorySelections:()=>[...re?.drainSelections()??[],...hn?it?.drainReminderEntries?.()??[]:[]]}}),...i?.configurationThinking!==void 0?i.configurationThinking===null?{}:{thinking:i.configurationThinking}:n.thinking!==void 0?{thinking:n.thinking}:t.thinking!==void 0?{thinking:t.thinking}:{},...Pe!==void 0?{onTurnEnd:Pe}:{},...t.runQueryImpl!==void 0?{runQueryImpl:t.runQueryImpl}:{},...U!==void 0||A?.host.options.memoryFor!==void 0||je?{onTurnStart:(X,ge)=>{un=ge.join(`
|
|
35
|
-
`),_n=!0,re?re.onTurnStart(ge):je&&(de=[...ge]),U?.transcript.noteTurn(ge)},onInputsConsumed:X=>{U?.transcript.noteInput(X),hn&&it?.supplement?.(X.join(`
|
|
36
|
-
`))}}:{}});return s=Xe,Xe.bindModelClientWrapper(H,u.client),re!==void 0&&Qr(Xe,re),Ce&&Ed(Xe,Ce),(je||A!==void 0)&&Xe.bindModelRequestGuard(()=>{A?.assertModelRequestsAllowed(),re?.assertAvailable()}),je&&Xe.bindConfigurationReadiness(async()=>B!==void 0&&re===void 0?!1:await re?.readyForModelChange()??!0),i?.attachmentPersistence?.verifySource===!0&&A!==void 0&&A.attachAttachmentSourceConfirmation(()=>Xe.confirmAttachmentSource(async X=>(await A.refresh(X),X.throwIfAborted(),I=C(),F(),A.attachmentSource))),S!==void 0&&k.length>0&&Xe.pushControl(sn.platformWarning,{code:"profile_narrowed_capabilities",message:We(tn.profileNarrowedCapabilities,{profile:S.name,dropped:k.join(", ")}),dropped:k}),Xe.bindCwdRebinder(X=>pe.withCwd(X,{permissionGate:Ci(ce,L,{cwd:X})})),Xe}}}var Df={"mobile-default":al()},jf=30,Nf=36e5,Bf=class{#e;#n;owner;#r;#s;sessionId;endUserId;createdAt;#t;#o;#i;#a;#c;platformAudio;#d;title$;#f=Promise.resolve();constructor(e){this.sessionId=e.sessionId,this.#e=e.configuration,this.#n=e.configure,this.owner=e.owner,this.#r=e.settleOwner,this.#s=e.checkpointOwner,this.endUserId=e.endUserId,this.createdAt=e.createdAt,this.#t=e.driver,this.#o=e.bridge,this.#i=e.persistence,this.#a=e.resolveCwd,this.#c=e.onCwdChanged,this.platformAudio=e.platformAudio,this.#d=e.media,this.title$=e.initialTitle}get events(){return this.#t.events}send(e){return this.owner?.assertCurrent(),this.#t.send(e)}sendMessage(e){return this.owner?.assertCurrent(),this.#t.sendMessage(e)}inputCapabilities(){return this.#t.inputCapabilities()}getInputTarget(){return this.#t.getInputTarget()}submitInput(e){return this.owner?.assertCurrent(),this.#t.submitInput(e)}getInputStatus(...e){return this.#t.getInputStatus(...e)}interrupt(e){this.#t.interrupt(e)}close(e){this.#t.close(e)}async settleResources(){await this.#t.settleResources(),this.#t.status()==="ended"&&await this.#r?.()}status(){return this.#t.status()}contextState(){return this.#t.contextState()}applicationPrompt(){return this.#t.applicationPrompt()}setModel(e){return this.owner?.assertCurrent(),this.#e?.()!==void 0?{status:"rejected",reason:"unsupported"}:typeof this.#t.setModel=="function"?this.#t.setModel(e):{status:"rejected",reason:"unsupported"}}setThinking(e){return this.owner?.assertCurrent(),this.#e?.()!==void 0?{status:"rejected",reason:"unsupported"}:typeof this.#t.setThinking=="function"?this.#t.setThinking(e):{status:"rejected",reason:"unsupported"}}configuration(){let e=this.#e?.();return e===void 0?void 0:structuredClone(e)}configure(e,n){return this.owner?.assertCurrent(),this.#n?.(e,n)??Promise.resolve({status:"rejected",reason:"unsupported"})}mediaState(){return this.#d?structuredClone(this.#d):void 0}lastSeq(){return this.#t.lastSeq()}firstSeq(){return this.#t.firstSeq()}historySnapshot(){return this.#t.historySnapshot()}title(){return this.title$}submitToolResult(e,n){return this.owner?.assertCurrent(),this.#o.submitToolResult(e,n)}submitPermission(e,n){return this.owner?.assertCurrent(),this.#o.submitPermission(e,n)}submitQuestionAnswers(e,n){return this.owner?.assertCurrent(),this.#o.submitQuestionAnswers(e,n)}noteSubscribers(e){this.#o.noteSubscribers(e)}async compact(e={}){if(this.owner?.assertCurrent(),e.checkpoint!==void 0&&e.checkpoint!==!1&&this.#i?.checkpoints===void 0)return{status:"rejected",reason:"checkpoints_not_wired"};let n=await this.#t.compactIdle({...e.instructions!==void 0?{instructions:e.instructions}:{},...e.checkpoint!==void 0?{checkpoint:e.checkpoint}:{}});if(n.status==="compacted"){this.#t.ownsArchiveHistoryCommit?.()!==!0&&this.#i?.commitRewritten(this.#t.historySnapshot().messages),await this.#s?.();let i=n.outcome;return{status:"compacted",compactionId:i.compactionId??i.observation?.compactionId??"",removedRange:i.removedRange,...n.checkpointId!==void 0?{checkpointId:n.checkpointId}:{}}}return n.status==="failed"?{status:"failed",reason:n.outcome.reason,message:n.outcome.message,...n.outcome.checkpointId!==void 0?{checkpointId:n.outcome.checkpointId}:{}}:{status:"rejected",reason:n.reason}}#m(e){let n=this.#f.then(()=>(this.owner?.assertCurrent(),e()));return this.#f=n.then(()=>{},()=>{}),n}#p(e){return this.owner===void 0?e():this.owner.write(e)}checkpoint(e={}){return this.#m(async()=>{if(this.#i?.checkpoints===void 0)return{status:"rejected",reason:"checkpoints_not_wired"};let n=this.#t.status();if(n==="ended")return{status:"rejected",reason:"session_ended"};if(n==="running")return{status:"rejected",reason:"turn_running"};let i=await this.#k("manual",this.#t.historySnapshot().messages,e.label);return{status:"created",checkpoint:mr(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(mr)}}restore(e,n={}){return this.owner===void 0?this.#w(e,n):(this.owner.assertCurrent(),this.#w(e,n).then(async i=>(i.status==="restored"&&await this.#s?.(),i)))}#w(e,n){if(this.#t.ownsArchiveHistoryCommit?.()===!0&&typeof this.#t.withArchiveRestore=="function"){if(this.#i?.checkpoints===void 0)return Promise.resolve({status:"rejected",reason:"checkpoints_not_wired"});let o=this.#t.status();return o==="ended"?Promise.resolve({status:"rejected",reason:"session_ended"}):o==="running"?Promise.resolve({status:"rejected",reason:"turn_running"}):this.#t.withArchiveRestore(s=>this.#v(e,n,void 0,s))}let i=this.#t.prepareHistoryRestore?.();return i!==void 0?i.then(o=>this.#v(e,n,o)):this.#v(e,n)}#v(e,n,i,o){return this.#m(async()=>{let s=this.#i;if(s?.checkpoints===void 0)return{status:"rejected",reason:"checkpoints_not_wired"};let a=this.#t.status();if(a==="ended")return{status:"rejected",reason:"session_ended"};if(a==="running"&&o===void 0)return{status:"rejected",reason:"turn_running"};let d;try{d=await s.checkpoints.store.get(this.endUserId,this.sessionId,e)}catch(f){throw f instanceof gn&&f.code==="CHECKPOINT_INVALID"?new Ze(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"};Wo(n,this),await this.owner?.beginTurn();let c;n.checkpoint!==!1&&(c=(await this.#k("pre_restore",this.#t.historySnapshot().messages)).checkpointId),Wo(n,this);let l=o===void 0?this.#t.restoreHistory(d.messages,e,i):await o(d.messages,e);return l.status==="rejected"?{status:"rejected",reason:l.reason}:(o===void 0&&s.commitRewritten(this.#t.historySnapshot().messages),d.cwd!==s.cwd&&this.#o.emitPlatformWarning({code:"cwd_mismatch_on_restore",message:We(wt.cwdMismatchOnRestore,{stored:d.cwd,current:s.cwd})}),{status:"restored",checkpointId:e,fromMessages:l.fromMessages,toMessages:l.toMessages,...c!==void 0?{preRestoreCheckpointId:c}:{}})})}deleteCheckpoint(e){return this.#m(async()=>{let n=this.#i?.checkpoints;return n===void 0?"checkpoints_not_wired":await this.#p(()=>n.store.delete(this.endUserId,this.sessionId,e))?"deleted":"not_found"})}async setCwd(e){let n=this.#t.status();if(n==="ended")return{status:"rejected",reason:"session_ended"};if(n==="running")return{status:"rejected",reason:"turn_running"};let i=this.#a;if(i===void 0)return{status:"rejected",reason:"unsupported"};let o=this.#t.cwd,s=await i(e,o);if(!s.ok)return{status:"rejected",reason:s.reason,...s.detail!==void 0?{detail:s.detail}:{}};let a=this.#t.setCwd(s.cwd);return a.status==="rejected"?{status:"rejected",reason:a.reason}:(a.to!==a.from&&(this.#i!==void 0&&(this.#i.cwd=a.to),this.#o.setCwd(a.to),this.#c?.({at:new Date().toISOString(),from:a.from,to:a.to})),{status:"changed",cwd:a.to,from:a.from})}async exportCheckpoint(e){let n=this.#i?.checkpoints;if(n===void 0)return{status:"rejected",reason:"checkpoints_not_wired"};let i;try{i=await n.store.get(this.endUserId,this.sessionId,e)}catch(o){throw o instanceof gn&&o.code==="CHECKPOINT_INVALID"?new Ze(this.sessionId,o.message,o):o}return i===null||i.sessionId!==this.sessionId?{status:"rejected",reason:"not_found"}:{status:"exported",bytes:Is(i)}}importCheckpoint(e,n={}){return this.#m(async()=>{let i=this.#i;if(i?.checkpoints===void 0)return{status:"rejected",reason:"checkpoints_not_wired"};if(this.#t.status()==="ended")return{status:"rejected",reason:"session_ended"};let o=Wo(n,this),s;try{s=Ts(e,{sessionId:this.sessionId,checkpointId:o?.checkpointId??Rs(i.now()),createdAt:o?.createdAt??new Date(i.now()).toISOString(),...n.label!==void 0?{label:n.label}:{}})}catch(d){if(d instanceof gn&&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(Wo(n,this),d){let c=Ts(Is(d),{sessionId:this.sessionId,checkpointId:o.checkpointId,createdAt:o.createdAt});if(Bt(c)!==Bt(s))throw new Error("Archive checkpoint import conflict");return{status:"imported",checkpoint:mr(d)}}}let a=await this.#p(()=>i.checkpoints.store.put(this.endUserId,s));return this.#t.pushBody({type:"session.checkpointed",checkpointId:a.checkpointId,trigger:a.trigger,...a.label!==void 0?{label:a.label}:{},messageCount:a.messageCount},"server"),{status:"imported",checkpoint:mr(a)}})}beforeCompactHook(){let e=this.#i?.checkpoints;if(e!==void 0)return async(n,i)=>{if(i.checkpoint===!1||i.checkpoint===void 0&&!e.autoBeforeCompact)return;let o=typeof i.checkpoint=="object"?i.checkpoint.label:void 0;return{checkpointId:(await this.#m(()=>this.#k("pre_compaction",n.messages,o))).checkpointId}}}async#k(e,n,i){let o=this.#i,s=o.checkpoints,a=await this.#p(()=>s.store.put(this.endUserId,Jv({checkpointId:Rs(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 GR(t,e){let n=Date.parse(t);return Number.isNaN(n)?e:n}function WR(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 tb(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 zo(t.execution),i=t.transactionalExecution===void 0?void 0:new zo(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??Df,a=t.now??Date.now,d=t.store,c=$n(t.logger),l=Qn(),f=(S,k,A,C)=>{if((S==="commit"?l.storeCommitErrors:l.storeCreateErrors).inc(),C!==void 0)try{C.status()!=="ended"&&C.pushBody({type:"turn.error",scope:"server.persistence",message:We(S==="commit"?wt.storeCommitFailed:wt.storeCreateFailed),recoverable:!0,errorKind:S==="commit"?"store_commit_failed":"store_create_failed"},"server")}catch{}try{if(t.onStoreError!==void 0){t.onStoreError(k,A);return}console.error(JSON.stringify({level:"error",event:S==="commit"?rt.storeCommitFailed:rt.storeCreateFailed,sessionId:k,message:On(A)}))}catch{}},u=new Set,m=S=>{let k=S.then(()=>{},()=>{});u.add(k),k.then(()=>u.delete(k))},h=async()=>{let S=0;for(;u.size>0;){let k=[...u];S+=k.length,await Promise.all(k)}return await o?.settle(),S};if(t.factory===void 0==(t.platform===void 0))throw new Error('createAgentSessionFactory requires exactly one of "factory" (custom inner assembly) or "platform" (built-in tansr platform assembly)');if(t.platform!==void 0&&t.assembleEndUserModel!==void 0)throw new Error('"assembleEndUserModel" cannot be combined with "platform" (the built-in form wires the per-endUser assembly seam itself)');let g,p=t.assembleEndUserModel,v;if(t.platform!==void 0){let S=t.platform,k=Gr({governor:S.governor,fetchImpl:S.fetchImpl}),A=hd({apiBaseUrl:S.apiBaseUrl,appId:S.appId,appKey:S.appKey,...S.ttlSeconds!==void 0?{ttlSeconds:S.ttlSeconds}:{},...k!==void 0?{fetchImpl:k}:{},now:a,...S.tokenMinter??{}});t.cacheHost?.connectPlatform({appId:S.appId,apiBaseUrl:S.apiBaseUrl,tokenFor:L=>A.tokenFor(L),...k?{fetchImpl:k}:{}});let C=S.bundleCacheTtlMs??_i,F=S.bundleCache??(C>0?rr({ttlMs:C,...k!==void 0?{fetchImpl:k}:{},now:a}):void 0);p=Ny({minter:A,apiBaseUrl:S.apiBaseUrl,appId:S.appId,...k!==void 0?{fetchImpl:k}:{},...S.onPlatformWarning!==void 0?{onPlatformWarning:S.onPlatformWarning}:{},...t.logger!==void 0?{logger:t.logger}:{},now:a,...F!==void 0?{bundleCache:F}:{bundleCacheTtlMs:0}},{...e===void 0?{}:{remoteExecution:!0},...t.cacheHost!==void 0?{gatewayCache:L=>t.cacheHost.assembler(L),refreshCacheConfiguration:(L,Q)=>t.cacheHost.refreshConfiguration(L.endUserId,L.sessionId,Q),cacheConfigurationRefreshRequired:L=>t.cacheHost.configurationRefreshRequired(L.endUserId,L.sessionId),confirmCacheConfiguration:(L,Q)=>t.cacheHost.confirmConfiguration(L.endUserId,L.sessionId,Q),archivedRuntime:L=>t.cacheHost.archivedRuntime(L.endUserId,L.sessionId,L.previous)}:t.gatewayCache===void 0?{}:{gatewayCache:t.gatewayCache}}),v=()=>({tokenMinter:A.stats(),...F!==void 0?{bundleCache:F.stats()}:{}}),g=Fd({...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;p!==void 0&&(p=gd(p));let b=$R(t.checkpoints,d);d!==void 0&&t.cacheHost?.connectStore(d);let R=VR(t.sessions?.retention),w=new Map,x=(S,k)=>{if(k===void 0)return;let A=Gt(S);k.sessionRetentionDays!==void 0?w.set(A,k.sessionRetentionDays):w.delete(A)},T,P=async(S={})=>{if(R===void 0||d?.sweepRetention===void 0)return;let k=a();if(!S.force&&T!==void 0&&k-T<R.sweepIntervalMs)return;T=k;let A=R.policy,C=await d.sweepRetention({policy:A,policyFor:L=>({...A,maxAgeDays:w.get(L)??A.maxAgeDays}),now:k,...S.activeSessionIds!==void 0?{keep:S.activeSessionIds}:{}}),F=t.checkpoints?.dir;if(F!==void 0)for(let{endUserKey:L,sessionId:Q}of C.deleted)await HR(zR.join(F,"agent-checkpoints",L,Q),{recursive:!0,force:!0}).catch(se=>C.failures.push({endUserKey:L,sessionId:Q,message:`checkpoints: ${On(se)}`}));return(C.deleted.length>0||C.failures.length>0)&&t.logger?.log?.("info",rt.sessionRetentionSwept,{scanned:C.scanned,deleted:C.deleted.length,failures:C.failures.length,byReason:C.deleted.reduce((L,Q)=>({...L,[Q.reason]:(L[Q.reason]??0)+1}),{})}),C},W=!1,K={get terminalCapabilities(){let S=[];return t.configuration!==void 0&&d?.claimOwner!==void 0&&d.initializeConfiguration!==void 0&&d.inspectConfiguration!==void 0&&d.commitConfiguration!==void 0&&S.push("session-configuration-v1"),W&&S.push("memory-lifecycle-v1"),S},...n!==void 0?{execution:n}:{},...i!==void 0?{transactionalExecution:i}:{},async create(S){let k,A,C,F,L,Q=!1,se,O=!1,I=le=>{C===void 0&&(C=setInterval(()=>{if(Q||(Q=!0,le.renew().then(void 0,re=>{L??=re,F?.close(),ce?.close()}).finally(()=>{Q=!1})),!O&&se!==void 0){let re=se;se=void 0,O=!0,re().then(void 0,pe=>c("error",rt.storeCommitFailed,{message:On(pe)})).finally(()=>{O=!1})}},Math.max(250,Math.floor(le.leaseMs/3))),C.unref())},q=Iy(K,S),H,N,ie=q===void 0,U,ce;try{if(o!==void 0&&(S.prompt!==void 0||S.cwd!==void 0))throw new Ye("validation_failed",We(tn.executionInitializeRequired));q?.assertCurrent();let le=S.tools,re;if(S.capabilitiesProfile!==void 0){let te=s[S.capabilitiesProfile];if(te===void 0)throw new Ye("validation_failed",We(tn.unknownCapabilitiesProfile,{profile:S.capabilitiesProfile,available:Object.keys(s).join(", ")}));le=S.tools!==void 0?S.tools.filter(Ie=>te.includes(Ie)):[...te],re={name:S.capabilitiesProfile,tools:te}}let pe=o===void 0?await KR(S,t):"/workspace/unbound",j,Y,oe,Se,je=S.model,$e=S.thinking,Fe=!1,ft,kt,ze,it,It,Wt=!1,un=a(),_n,Nt,hn,_,y;if(S.resume!==void 0){if(d===void 0)throw new Ye("resume_unavailable","session store is not wired");let te;try{U=t.cacheHost?.beginSessionCreation(S.endUserId,S.resume.sessionId),k=await d.claimOwner?.(S.endUserId,S.resume.sessionId),k!==void 0&&I(k);let Ke=1e3;for(let dt=0;;dt+=1)try{te=await d.get(S.endUserId,S.resume.sessionId);break}catch(Kt){if(!(Kt instanceof gn)||Kt.code!=="SESSION_LOCKED"||dt>=Ke-1)throw Kt;await new Promise(fn=>setTimeout(fn,5))}q?.assertCurrent()}catch(Ke){throw Ke instanceof Ze?new Ye("store_corrupted",Ke.message):Ke}if(te===null)throw new Ye("session_not_found",`session not found in store: ${S.resume.sessionId}`);if(te.ownershipRequired&&k===void 0)throw new Ye("resume_unavailable","Session requires durable ownership");if(oe=S.resume.sessionId,N=te.meta,Fe=!0,Se=te.configuration,Se!==void 0&&(je=Se.model??void 0,$e=Se.thinking??void 0),A=te.runtimeCheckpoint,A!==void 0&&(d.runtimeCheckpoints!==!0||k===void 0||S.prompt!==void 0))throw new Ye("resume_unavailable","Runtime checkpoint requires the original trusted Store");let Ie=A===void 0?xs(te.messages):{messages:te.messages,synthesizedResults:0,droppedMessages:0};ft=Ie.messages,Wt=Ie.synthesizedResults>0||Ie.droppedMessages>0||te.recovery!==void 0,te.recovery!==void 0&&(Y={code:"session_recovery_degraded",message:We(wt.recoveryDegraded,{dropped:te.recovery.droppedMessages,retained:te.recovery.recoveredMessages,synthesized:te.recovery.synthesizedToolResults})}),kt=te.usageSnapshot,ze=te.attachmentCheckpoint,d.attachmentSourceCheckpoints===!0&&(it=te.attachmentSourceCheckpoint),It=te.memorySelectionCheckpoint,un=GR(te.meta.createdAt,un),_n=te.meta.title,Nt=te.meta.platformSessionId,hn=te.meta.retentionDays,y=WR(te.meta,a());let Ee=o!==void 0?{cwd:"/workspace/unbound",warning:void 0}:await JR(te.meta.cwd,pe,{mode:t.cwdOnResume??(t.cwdPolicy!==void 0?"stored":"current"),policy:qf(t,S.endUserId)});pe=Ee.cwd,Wt||=o!==void 0&&(o.options.readAttachmentSource===void 0||d.attachmentSourceCheckpoints!==!0)||o===void 0&&te.meta.cwd!==void 0&&te.meta.cwd!==pe,j=Ee.warning}else if(S.fork!==void 0){let te=await YR({init:S,fork:S.fork,checkpointStore:b,store:d,cwd:pe});oe=te.sessionId,ft=te.history,_n=te.title,_={sourceSessionId:S.fork.sessionId,checkpointId:S.fork.checkpointId}}else oe=S.sessionId??Ld();let M=!1;d?.claimOwner!==void 0&&k===void 0&&(q?.mode==="fresh"?(q.assertCurrent(),await zl(d,S.endUserId,{sessionId:oe,cwd:pe}),q.assertCurrent(),M=!0):await d.create(S.endUserId,{sessionId:oe,cwd:pe}),k=await d.claimOwner(S.endUserId,oe),I(k)),o!==void 0&&(pe="/workspace/unbound");let $=new Jr({cwd:pe,...t.permissionTimeoutMs!==void 0?{permissionTimeoutMs:t.permissionTimeoutMs}:{},...t.questionGraceMs!==void 0?{questionGraceMs:t.questionGraceMs}:{},now:a,onPermissionReceipt:te=>{c(te.reason!==void 0?"warn":"info",rt.bridgePermissionReceipt,{sessionId:oe,requestId:te.requestId,verdict:te.verdict,...te.reason!==void 0?{reason:te.reason}:{}})}}),ne=[];if(S.clientTools!==void 0){let te=new Set;for(let Ie of S.clientTools){if(te.has(Ie.name))throw new Ye("validation_failed",We(tn.clientToolConflict,{name:Ie.name}));te.add(Ie.name),ne.push(Nd(Ie,$,a,o===void 0?void 0:async(Ee,Ke)=>{if(ce===void 0)throw new Error("Execution session is not ready");return ce.invokeClientTool(Ie,Ee,Ke)}))}}let G,Z,be=!1,ue=[],ke=!1,ve,Pe;if(p!==void 0){Fe&&Nt!==void 0&&t.cacheHost!==void 0&&await t.cacheHost.recoverConfiguration(S.endUserId,oe,Nt,()=>{k?.assertCurrent(),q?.assertCurrent()}),Z=t.cacheHost?.selectRuntime(S.endUserId,oe,Nt,Fe)??Nt??zi();let te=t.cacheHost?.prepareArchivedRecovery(S.endUserId,oe,Z);te!==void 0&&await te;let Ie=await p({endUserId:S.endUserId,sessionId:oe,...je!==void 0?{model:je}:{},onWarning:Ee=>{ke?$.emitPlatformWarning(Ee):ue.push(Ee)},platformSessionId:Z,onSessionArchived:(Ee,Ke)=>{if(Ee!==Z)throw new Error("Platform runtime changed during assembly");return be=!0,Z=Ke??zi(),Z}});G=(Ee,Ke)=>{let dt=Ie(Ee,Ke);return Pe={...dt.readPlatformCatalog===void 0?{}:{readPlatformCatalog:dt.readPlatformCatalog},...dt.readPlatformUsage===void 0?{}:{readPlatformUsage:dt.readPlatformUsage}},ve={capabilities:dt.capabilities,platformTools:dt.platformTools,...dt.sessionRetentionDays!==void 0?{sessionRetentionDays:dt.sessionRetentionDays}:{}},dt}}let z=!1,B=!1,ee=!1,de=!0,Ne=0,Ce=!1,Xe=null,X=null,ge,Re=new Set,Be=(te,Ie,Ee,Ke,dt)=>{if(d===void 0)return;if(ee)return f("commit",oe,new Error("Archive Store completion remains unobservable"),he),Promise.resolve(!1);let Kt=++Ne,fn=Ce?{commitId:Ke?.commitId??Ld(),observation:Ke?.observation??rn(oe,te,he.archiveHistoryObservation().localHistoryGeneration)}:null,Ft=Ie||z;z=Ft;let Yr;Ce&&(X=null);try{let ht=Ee??he?.currentCostSnapshot?.();Yr=d.commit(S.endUserId,oe,te,{...k===void 0?{}:{owner:k},rewritten:Ft,lastSeq:he.lastSeq(),...ht!==void 0?{usageSnapshot:Ns(ht)}:{},...d.attachmentCheckpoints===!0?{attachmentCheckpoint:dt===void 0?he.attachmentCheckpoint?.(te,Ie):dt.attachmentCheckpoint}:{},...d.attachmentSourceCheckpoints===!0&&o?.options.readAttachmentSource!==void 0?{attachmentSourceCheckpoint:Ie?null:dt===void 0?he.attachmentSourceCheckpoint?.(te):dt.attachmentSourceCheckpoint}:{},...d.memorySelectionCheckpoints===!0?{memorySelectionCheckpoint:dt===void 0?he.memorySelectionCheckpoint?.():dt.memorySelectionCheckpoint}:{}})}catch(ht){return Ce&&(ee=!0),z=!0,B=!0,f("commit",oe,ht,he),Promise.resolve(!1)}let Ni=Yr;if(Ce)try{X=pl({...fn,storeIdentity:d,original:Yr}),Ni=X.completion,Ke?.onReceipt(X)}catch(ht){return ee=!0,z=!0,B=!0,f("commit",oe,ht,he),Promise.resolve(!1)}let kn=Ni.then(()=>{let ht=Kt===Ne;return(Ft||!ht)&&(z=!ht,B=!ht),fn!==null&&Kt===Ne&&(Xe=fn),!0},ht=>(z=!0,B=!0,f("commit",oe,ht,he),!1));return Re.add(kn),kn.then(()=>Re.delete(kn),()=>Re.delete(kn)),m(kn),kn};if(ce=o?.open(S.endUserId,oe,$,le),k!==void 0&&ce?.bindOwner(k),ce!==void 0)for(let te=0;te<ne.length;te++)ce.registerClientTool(S.clientTools[te],ne[te]);let Me=t.sessionCapture?.({endUserId:S.endUserId,sessionId:oe}),Ge=t.contextMaterials?.({endUserId:S.endUserId,sessionId:oe}),he,Ue=Promise.resolve(),Oe=async te=>{await he.settleResources();let Ie=Nn(he);if(Ie!==void 0){let Ee=await Ie.settleResources({timeoutMs:1/0});if(Ee.some(Ke=>Ke.status!=="completed"))throw new AggregateError(Ee.flatMap(Ke=>Ke.failures.map(dt=>dt.cause)),"Memory resources did not settle")}await Promise.all([...Re]),await d?.flush?.(),await k?.checkpoint(()=>te?.()!==!1&&(he.status()==="idle"||he.status()==="ended")&&!z&&!B&&(ce?.ownershipStable()??!0)),te?.()!==!1&&A!==void 0&&Se===void 0&&t.configuration!==void 0&&k!==void 0&&he.status()==="idle"&&d?.initializeConfiguration!==void 0&&d.inspectConfiguration!==void 0&&d.commitConfiguration!==void 0&&(Se=await d.initializeConfiguration(S.endUserId,oe,{model:je??null,thinking:he.thinking()??null},k))},Je=te=>{let Ie=Ue.then(()=>Oe(te));return Ue=Ie.then(()=>{},()=>{}),Ie},ot=3,Ot=te=>te instanceof Qt&&(te.code==="owner_stale"||te.code==="owner_corrupted"),Yt=(te,Ie,Ee)=>{if(f("commit",oe,te,he),Ot(te)||Ee>=ot){he.close();return}let Ke=async()=>{if(he.status()==="running"){se??=Ke;return}await Je(Ie).catch(dt=>Xt(dt,Ie,Ee+1))};se=Ke},Xt=(te,Ie,Ee)=>{try{Yt(te,Ie,Ee)}catch(Ke){f("commit",oe,Ke)}};try{if(he=g.create({...je!==void 0?{model:je}:{},...S.profile!==void 0?{profile:S.profile}:{},...S.labels!==void 0?{labels:S.labels}:{},...S.budget!==void 0?{budget:S.budget}:{},...le!==void 0?{tools:[...le]}:{},...$e!==void 0?{thinking:$e}:{}},{sessionId:oe,...t.platform===void 0?{}:{trustedScope:{applicationScopeId:t.platform.appId,endUserId:S.endUserId,sessionId:oe}},...Se===void 0?{}:{configurationThinking:Se.thinking},...t.platform?.memoryFor===void 0&&t.platform?.memoryPublicationFor===void 0?{}:{memoryScope:{sessionId:oe,applicationScopeId:t.platform.appId,endUserId:S.endUserId}},...ce!==void 0?{execution:ce}:{},cwd:pe,...re!==void 0?{capabilityProfile:re}:{},...G!==void 0?{assembleModel:G}:{},...ft!==void 0?{initialHistory:ft}:{},...d?.attachmentCheckpoints===!0?{attachmentPersistence:{scope:me({application:o?.options.applicationScopeId??t.platform?.appId??null,endUserId:S.endUserId,sessionId:oe}),...ze===void 0?{}:{checkpoint:ze},...Wt?{invalidateReferences:!0}:{},...o?.options.readAttachmentSource!==void 0&&d.attachmentSourceCheckpoints===!0?{verifySource:!0,...it===void 0?{}:{sourceCheckpoint:it}}:{}}}:{},...d?.memorySelectionCheckpoints===!0?{memorySelectionPersistence:{scope:me({application:o?.options.applicationScopeId??t.platform?.appId??null,endUserId:S.endUserId,sessionId:oe}),...It===void 0?{}:{checkpoint:It}}}:{},...y!==void 0?{initialSeq:y}:{},...kt!==void 0&&(A!==void 0||S.budget!==void 0||o?.options.memoryFor!==void 0||t.platform?.memoryFor!==void 0||t.platform?.memoryPublicationFor!==void 0)?{usageSnapshot:kt.payload.snapshot}:{},...d===void 0||S.budget===void 0&&o?.options.memoryFor===void 0&&t.platform?.memoryFor===void 0&&t.platform?.memoryPublicationFor===void 0?{}:{persistBackgroundUsage:d.recordUsageSnapshot===void 0?null:te=>{let Ie;try{Ie=d.recordUsageSnapshot(S.endUserId,oe,Ns(te),k)}catch(Ee){Ie=Promise.reject(Ee)}return m(Ie.catch(Ee=>{f("commit",oe,Ee,he)})),Ie}},...ne.length>0?{sessionTools:ne}:{},promptChannel:$.createPromptChannel(),askUser:$.createAskUser(),onTurnEnd:te=>{Vt.title$=Ki(te.history)??Vt.title$,he.ownsArchiveHistoryCommit?.()===!0?ge=te:Be(te.history,te.rewritten,te.costSnapshot,void 0,te),k!==void 0&&(!te.aborted||te.abortReason==="budget_exceeded")&&Je(te.isCurrentTurn).catch(Ie=>Xt(Ie,te.isCurrentTurn,0))}}),F=he,L!==void 0)throw he.close(),L}catch(te){throw te instanceof Ln?new Ye("validation_failed",We(tn.clientToolConflict,{name:te.toolName})):te}k!==void 0&&he.bindOwner(k),q!==void 0&&(H=he,ld(he),q.assertCurrent()),x(S.endUserId,ve),$.bindEmitter((te,Ie)=>he.pushControl(te,Ie)),ke=!0,_!==void 0&&he.pushBody({type:"session.forked",..._,sessionId:oe},"server"),j!==void 0&&ue.push(j),Y!==void 0&&ue.push(Y),kt!==void 0&&(S.budget!==void 0||o?.options.memoryFor!==void 0||t.platform?.memoryFor!==void 0||t.platform?.memoryPublicationFor!==void 0)&&kt.staleMessages>0&&ue.push({code:"usage_snapshot_stale",message:We(wt.usageSnapshotStale,{count:kt.staleMessages})});for(let te of ue)$.emitPlatformWarning(te);ue.length=0;let Sn=ZR(ve),xt=XR(ve,un),cn=t.configuration!==void 0&&k!==void 0&&d?.initializeConfiguration!==void 0&&d.inspectConfiguration!==void 0&&d.commitConfiguration!==void 0&&typeof he.configure=="function";cn&&(A===void 0||Se!==void 0)&&(Se=await d.initializeConfiguration(S.endUserId,oe,{model:je??null,thinking:he.thinking()??null},k));let Hn=async(te,Ie={})=>{if(!cn)return{status:"rejected",reason:"unsupported"};let Ee=wo(te);if(!Ee)return{status:"rejected",reason:"invalid_configuration"};let Ke=he.configurationRejection();return Ke||(await Ue,await Promise.all([...Re]),he.configure(async(dt,Kt)=>{let fn=await d.inspectConfiguration(S.endUserId,oe,Ee,k);if(fn.status!=="ready")return fn;let Ft;if(Ee.changes.model!==void 0){try{if(t.configuration?.resolveModel!==void 0)Ft=await t.configuration.resolveModel({endUserId:S.endUserId,sessionId:oe,model:Ee.changes.model,signal:Kt});else if(G!==void 0){let ht=G(Ee.changes.model,zd=>{let Ff=so(zd);Ff&&he.pushBody(Ff,"provider")}),Pn=t.platform?.maxOutputTokens;Ft={client:ht.client,model:ht.model,...ht.contextWindowTokens===void 0?{}:{contextWindowTokens:ht.contextWindowTokens},...Pn===void 0&&ht.maxOutputTokens===void 0?{}:{maxOutputTokens:Math.min(Pn??1/0,ht.maxOutputTokens??1/0)}}}else return{status:"rejected",reason:"unsupported"}}catch(ht){let Pn=ht instanceof gt&&ht.code==="assembly_failed"?ht.cause:ht;if(Pn instanceof Om&&Pn.alias===Ee.changes.model||Pn instanceof Bm&&Ee.changes.model.includes("/")&&Pn.ref===Ee.changes.model)return{status:"rejected",reason:"invalid_configuration"};throw ht}Ft!==void 0&&t.platform?.maxOutputTokens!==void 0&&(Ft={...Ft,maxOutputTokens:Math.min(t.platform.maxOutputTokens,Ft.maxOutputTokens??1/0)})}Kt.throwIfAborted(),await Ie.beforeCommit?.(),Kt.throwIfAborted();let Yr=Object.hasOwn(Ee.changes,"thinking")?Ee.changes.thinking:fn.configuration.thinking,Ni=dt(Ft,Yr??void 0);if(Ni.status==="rejected")return Ni;let kn;try{kn=await d.commitConfiguration(S.endUserId,oe,Ee,k,()=>!Kt.aborted&&Ni.isCurrent())}catch(ht){let Pn;try{Pn=await d.inspectConfiguration(S.endUserId,oe,Ee,k)}catch(zd){throw he.close(),new AggregateError([ht,zd],"Configuration outcome is unknown")}if(Pn.status!=="replayed")throw Pn.status!=="ready"&&he.close(),ht;kn=Pn}return(kn.status==="changed"||kn.status==="replayed")&&(Se=kn.configuration,Ni.publish()),kn},Ie))},Vt=new Bf({configuration:()=>Se,configure:Hn,...k===void 0?{}:{owner:k,checkpointOwner:Oe,settleOwner:async()=>{try{await Ue;let te=se;se=void 0,te!==void 0&&await te(),await Ue,await Promise.all([...Re]),await d?.flush?.();try{await k.release()}catch{}}finally{C!==void 0&&(clearInterval(C),C=void 0)}}},sessionId:oe,endUserId:S.endUserId,createdAt:un,driver:he,bridge:$,..._n!==void 0?{initialTitle:_n}:{},...Sn!==void 0?{platformAudio:Sn}:{},...xt!==void 0?{media:xt}:{},persistence:eI({checkpointStore:b,checkpointsOptions:t.checkpoints,cwd:pe,now:a,commitRewritten:te=>Be(te,!0)}),resolveCwd:(te,Ie)=>{let Ee=qf(t,S.endUserId);return no({requested:te,fallback:Ie,...Ee!==void 0?{policy:Ee}:{}})},...d?.recordCwdChange!==void 0?{onCwdChanged:te=>{m(d.recordCwdChange.call(d,S.endUserId,oe,te,k).catch(Ie=>f("commit",oe,Ie,he)))}}:{}});qv(Vt,()=>Pe);let wn=Nn(he);wn&&Qr(Vt,wn);let bt=fr(he);bt&&Ed(Vt,{capability:()=>bt.capability(),async prepare(te){let Ie=await bt.prepare(te);return Qr(Vt,Ie),Ie}}),(wn?.management!==void 0||bt!==void 0)&&(W=!0,bv(Vt,async(te,Ie={})=>{if(k!==void 0&&k.assertIdle===void 0)throw new at("unsupported_capability");let Ee=he.configurationRejection();if(Ee)throw new at(Ee.reason==="turn_running"?"busy":"source_unavailable");await Ue,await Promise.all([...Re]);let Ke=await he.configure(async(dt,Kt)=>{try{await k?.assertIdle?.()}catch(Ft){throw Ft instanceof Qt&&["reconciliation_required","owner_busy","owner_stale"].includes(Ft.code)?Object.assign(new at(Ft.code==="owner_stale"?"stale_generation":"busy"),{cause:Ft}):Ft}Kt.throwIfAborted();let fn=bt===void 0?Nn(he):await fr(Vt).prepare(Kt);if(fn?.management===void 0)throw new at("unsupported_capability");return Kt.throwIfAborted(),fn.executeManagedCommand(te,{...Ie,signal:Kt})},Ie);if(Ke.status==="rejected")throw new at(Ke.reason==="turn_running"?"busy":"source_unavailable");return Ke}));let At=Vt.beforeCompactHook();if(At!==void 0&&he.bindBeforeCompact(At),d!==void 0&&(typeof he.bindArchiveSourceReadCheck=="function"&&he.bindArchiveSourceReadCheck(()=>Re.size===0&&de&&!B&&!z&&!ee),typeof he.bindArchivePersistenceBarrier=="function"&&he.bindArchivePersistenceBarrier(async()=>{for(;Re.size>0;)await Promise.all([...Re]);if(!de||B||z)throw new Error("Archive binding requires confirmed legacy history")}),typeof he.bindArchiveHistoryPort=="function"&&typeof he.archiveHistoryObservation=="function"&&typeof he.bindArchivePersistenceBarrier=="function")){let te=Object.freeze({storeIdentity:d,latestCommit:()=>X,read(){let Ie=he.archiveHistoryObservation(),Ee=Xe,Ke=Re.size===0&&de&&!B&&!z&&Ee!==null&&Ee.observation.localHistoryGeneration===Ie.localHistoryGeneration&&Ee.observation.sourceSnapshotDigest===Ie.sourceSnapshotDigest;return Object.freeze({observation:Ie,confirmedCommit:Ke?Object.freeze({commitId:Ee.commitId,observation:Object.freeze({...Ee.observation})}):null})}});typeof he.bindArchiveHistoryCommit=="function"&&he.bindArchiveHistoryCommit(Ie=>{if(!Ce)throw new Error("Archive original Store observation is not enabled");let Ee,Ke=ge?.history===Ie.history?ge.costSnapshot:void 0,dt=ge?.history===Ie.history?ge:void 0;ge=void 0;let Kt=Be(Ie.history,Ie.rewritten,Ke,{commitId:Ie.commitId,observation:Ie.observation,onReceipt:Ft=>{Ee=Ft}},dt);if(Ee===void 0||Kt===void 0)throw new Error("Archive original Store receipt unavailable");let fn=Kt.then(Ft=>{if(!Ft)throw new Error("Archive original Store failed")});return fn.catch(()=>{}),{receipt:Ee,completion:fn}}),he.bindArchiveHistoryPort(te,async()=>{if(Ce&&te.read().confirmedCommit!==null)return;if(Ce=!0,!await Be(he.historySnapshot().messages,!0)||te.read().confirmedCommit===null)throw new Error("Archive binding requires confirmed legacy history")},{detach(){if(Re.size!==0||!de||B||z||ee)throw new Error("Archive original Store remains unsettled");Ce=!1},assertDetached(){if(Ce||ge!==void 0)throw new Error("Archive original Store responsibility was not released")}}),typeof he.bindArchiveColdHistory=="function"&&he.bindArchiveColdHistory(Ie=>{let Ee=th(Ie,{storeIdentity:d,sessionId:oe});if(Re.size!==0||!de||B||z||ee||Ne!==0||X!==null||ge!==void 0)throw new Error("Archive cold history requires an untouched, settled original Store");let Ke=he.archiveHistoryObservation(),dt=Ee.details.runtime===void 0?0:Ee.details.history.observation.localHistoryGeneration;if(Ke.localHistoryGeneration!==dt||Ke.sessionId!==Ee.details.history.observation.sessionId||Ke.sourceSnapshotDigest!==Ee.details.history.observation.sourceSnapshotDigest)throw new Error("Archive cold history differs from the confirmed Store");Ee.assertCurrent(),Xe=Object.freeze({commitId:Ee.details.history.commitId,observation:Ke}),Ce=!0})}if(Me!==void 0||Ge!==void 0)try{Me!==void 0&&he.bindSessionCapture(Me),Ge!==void 0&&he.bindContextMaterials(Ge)}catch(te){throw he.close(),await he.settleResources(),te}if(d?.recordSeqWatermark!==void 0){let te=d.recordSeqWatermark;he.bindOnEnded(Ie=>{ce?.close(),ie&&m(te.call(d,S.endUserId,oe,{lastSeq:Ie,sealed:!0},k).catch(Ee=>f("commit",oe,Ee,he)))})}let mt=ve===void 0?void 0:ve.sessionRetentionDays??null;if(d!==void 0&&(!Fe||Z!==void 0&&Nt===void 0||be||mt!==void 0&&(mt===null?hn!==void 0:mt!==hn))){de=!1;let te={sessionId:oe,...Z!==void 0?{platformSessionId:t.cacheHost!==void 0&&Fe&&Nt!==void 0?Nt:Z}:{},...k===void 0?{}:{owner:k},cwd:pe,...mt!==void 0?{retentionDays:mt}:{}};if(q!==void 0||be){if(q?.assertCurrent(),N=await(q?.mode==="fresh"&&!M?zl(d,S.endUserId,te):d.create(S.endUserId,te)),q?.assertCurrent(),be&&t.cacheHost===void 0&&N.platformSessionId!==Z)throw new Error("Platform runtime metadata unconfirmed");de=!0}else{let Ie=d.create(S.endUserId,te).then(()=>{de=!0},Ee=>f("create",oe,Ee,he));Re.add(Ie),Ie.then(()=>Re.delete(Ie),()=>Re.delete(Ie)),m(Ie)}}if(t.cacheHost!==void 0&&Z!==void 0&&d!==void 0)try{if(t.cacheHost.registerSession({endUserId:S.endUserId,sessionId:oe,runtimeSessionId:Z,driver:he,store:d,configurationRefreshRequired:Fe&&Nt===Z}),await t.cacheHost.restoreSession(S.endUserId,oe),Fe&&Nt!==Z||t.cacheHost.needsStoreRuntime(S.endUserId,oe,Z)){let te=await d.create(S.endUserId,{sessionId:oe,platformSessionId:Z,...k===void 0?{}:{owner:k}});if(q?.assertCurrent(),q!==void 0&&(N=te),te.platformSessionId!==Z)throw new Error("Cache host runtime metadata unconfirmed");t.cacheHost.confirmStoreRuntime(S.endUserId,oe,Z)}}catch(te){throw he.close(),await he.settleResources(),te}if(q!==void 0){if(N===void 0)throw new Error("Archive factory registration is not confirmed");ie=!0,q.registered(N),Ty(K,S,Vt,he,N)}if(ce!==void 0){let te=ce;te.attach(()=>he.status()==="idle"),d?.recordSeqWatermark===void 0&&he.bindOnEnded(()=>te.close())}let $t=d?.runtimeCheckpoints===!0?he.historySnapshot().messages:void 0;return k!==void 0&&d?.runtimeCheckpoints===!0&&he.bindRuntimeRecovery(async(te,Ie)=>{if(await Promise.all([...Re]),z||B||!(ce?.ownershipStable()??!0))throw new Qt("reconciliation_required");let Ee=$t!==void 0&&($t.length>te.query.messages.length||$t.some((Ke,dt)=>me(Ke)!==me(te.query.messages[dt])));await d.commit(S.endUserId,oe,te.query.messages,{owner:k,rewritten:Ee,lastSeq:he.lastSeq(),runtimeCheckpoint:te,...Ie===void 0?{}:{usageSnapshot:Ns(Ie)},...d.attachmentCheckpoints===!0?{attachmentCheckpoint:he.attachmentCheckpoint(te.query.messages)}:{},...d.attachmentSourceCheckpoints===!0?{attachmentSourceCheckpoint:he.attachmentSourceCheckpoint(te.query.messages)}:{},...d.memorySelectionCheckpoints===!0?{memorySelectionCheckpoint:he.memorySelectionCheckpoint()}:{}}),$t=structuredClone(te.query.messages)},A),A!==void 0&&(q!==void 0?he.prepareArchiveRuntimeRecovery():he.resumeRuntime()),S.prompt!==void 0&&he.send(S.prompt),{handle:Vt,resumed:Fe}}catch(le){C!==void 0&&clearInterval(C);try{await k?.release()}catch{}if(ce?.close(),H!==void 0)try{H.close(),await H.settleResources()}catch(re){throw new AggregateError([le,re],"Archive factory creation and driver cleanup failed")}throw le instanceof Qt?new Ye(le.code==="owner_corrupted"?"store_corrupted":le.code==="reconciliation_required"?"resume_unavailable":"overloaded",le.message,{retryAfterMs:1e3,detail:{reason:le.code}}):le}finally{U?.()}},flush:h,sweepRetention:S=>P({activeSessionIds:S.activeSessionIds})};Ry(K,d);let D=S=>({sessionId:S.sessionId,createdAt:S.createdAt,updatedAt:S.updatedAt,...S.title!==void 0?{title:S.title}:{},...S.lastSeq!==void 0?{lastSeq:S.lastSeq}:{}}),J=d!==void 0?{async list(S){return(await d.list(S)).map(D)},async getMeta(S,k){let A=d.getMeta!==void 0?await d.getMeta(S,k):(await d.list(S)).find(C=>C.sessionId===k);return A==null?null:D(A)},async getHistory(S,k){let A=await d.get(S,k);return A===null?null:xs(A.messages).messages},...d.getHistoryPage!==void 0?{getHistoryPage:(S,k,A)=>d.getHistoryPage.call(d,S,k,A)}:{}}:void 0;return{factory:K,flush:h,sweepSessionRetention:P,...J!==void 0?{storeReader:J}:{},...v!==void 0?{upstreamStats:v}:{}}}function VR(t){if(t!==void 0)return{policy:{maxAgeDays:t.maxAgeDays??jf,...t.maxPerEndUser!==void 0?{maxPerEndUser:t.maxPerEndUser}:{},...t.maxBytes!==void 0?{maxBytes:t.maxBytes}:{}},sweepIntervalMs:t.sweepIntervalMs??Nf}}function $R(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 os({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 os({rootOf:(o,s)=>cc(i.call(e,o,s)),...n})}function qf(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 KR(t,e){let n=qf(e,t.endUserId),i=await no({...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 Ye("cwd_not_allowed",`cwd not allowed: ${o}`,{params:{detail:o}}):new Ye("cwd_invalid",`cwd invalid (${i.reason}): ${o}`,{params:{reason:i.reason,detail:o}})}async function QR(t){return qp(await no({requested:t.requested,fallback:t.fallback,...t.policy!==void 0?{policy:t.policy}:{}}),{onResume:!0})}async function JR(t,e,n){if(t===void 0||t===e)return{cwd:e};if(n.mode==="current")return{cwd:e,warning:{code:"cwd_mismatch_on_resume",message:We(wt.cwdMismatchOnResume,{stored:t,current:e})}};let i=await QR({requested:t,fallback:e,policy:n.policy});if("error"in i)throw new Ye("cwd_unavailable",`stored cwd unavailable (${i.reason}): ${i.detail??t}`,{params:{cwd:t,reason:i.reason}});return{cwd:i.cwd,warning:{code:"cwd_mismatch_on_resume",message:We(wt.cwdMismatchOnResumeStored,{stored:t,current:e})}}}async function YR(t){let{init:e,fork:n,checkpointStore:i,store:o}=t;if(i===void 0)throw new Ye("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 gn&&f.code==="CHECKPOINT_INVALID"?new Ye("store_corrupted",f.message):f}if(s===null||s.sessionId!==n.sessionId)throw new Ye("fork_source_not_found",`fork source not found: session ${n.sessionId} / checkpoint ${n.checkpointId}`,{params:{sessionId:n.sessionId,checkpointId:n.checkpointId}});let a=xs(s.messages).messages,d=Ki(a);if(o===void 0)return{sessionId:e.sessionId??Ld(),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??Ld(),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 Ze?new Ye("store_corrupted",f.message):f}return{sessionId:l,history:a,title:d}}function XR(t,e){if(!t?.capabilities||!t.platformTools)return;let n=t.capabilities.platform,i=ao({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 ZR(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)=>Mu({baseUrl:n.baseUrl,face:i,payload:o,token:Gi,fetchImpl:n.fetchImpl,...s!==void 0?{signal:s}:{}})}}function eI(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 tI={};nb(tI,{ADJUDICATOR_UNAVAILABLE_CODE:()=>Mf,ADJUDICATOR_UNAVAILABLE_MESSAGE:()=>Of,AGENT_SESSION_CONTRACT_VERSION:()=>Fh,AUDIO_INPUT_PATTERN:()=>ru,AUDIO_LANGUAGE_MAX_CHARS:()=>su,AUDIO_MAX_BODY_BYTES:()=>Ao,AUDIO_PROMPT_MAX_CHARS:()=>du,AUDIO_ROUTE_SEGMENTS:()=>Hh,AUDIO_SPEECH_FORMATS:()=>ou,AUDIO_SPEECH_INPUT_MAX_CHARS:()=>cu,AUDIO_VOICE_MAX_CHARS:()=>au,AgentSessionBridge:()=>Jr,AgentSessionCreateError:()=>Ye,AgentSessionStoreError:()=>Ze,AppTokenMintError:()=>An,AudioSpeechBodySchema:()=>ha,AudioTranscriptionsBodySchema:()=>ma,BUILTIN_CAPABILITY_PROFILES:()=>Df,CHECKPOINT_EXPORT_CONTENT_TYPE:()=>fa,CHECKPOINT_IMPORT_MAX_BODY_BYTES:()=>To,CHECKPOINT_IMPORT_SEGMENT:()=>pa,CHECKPOINT_LABEL_MAX_CHARS:()=>Qi,CLIENT_TOOL_NAME_PATTERN:()=>Jl,COMPACT_INSTRUCTIONS_MAX_CHARS:()=>nu,CONTROL_FRAME:()=>sn,CONTROL_FRAME_TS_KEY:()=>ta,CheckpointBodySchema:()=>ca,CheckpointOptionSchema:()=>iu,ClientToolDeclSchema:()=>Ro,ClientToolNameConflictError:()=>Ln,CompactBodySchema:()=>da,CreateSessionBodySchema:()=>ia,DEFAULT_BUNDLE_CACHE_TTL_MS:()=>_i,DEFAULT_PROCESS_GUARD_DRAIN_TIMEOUT_MS:()=>Jm,DEFAULT_SESSION_MAX_AGE_DAYS:()=>jf,DEFAULT_SESSION_RETENTION_SWEEP_INTERVAL_MS:()=>Nf,DEFAULT_SSE_FLUSH_SLICE_MS:()=>pu,DEFAULT_SSE_HEARTBEAT_MS:()=>uu,DEFAULT_SSE_RETRY_MS:()=>fu,DEFAULT_WEBHOOK_SIGNATURE_VERSIONS:()=>vu,DEVELOPER_ONLY_ADJUDICATOR_WARNINGS:()=>nf,END_USER_ID_PATTERN:()=>Ql,EXCLUDE_TOKEN_PATTERN:()=>Yl,EventRingBuffer:()=>xi,IMAGE_MIME_PATTERN:()=>ea,ImageGenDataSchema:()=>Wd,LOG_EVENT:()=>rt,LOG_EVENT_NAMES:()=>$m,MemorySessionEventLog:()=>Pr,MessageBlockSchema:()=>Xl,MessagesBodySchema:()=>ra,OBSERVABILITY_PATHS:()=>Tn,OPENMETRICS_CONTENT_TYPE:()=>bs,PERMISSION_DENY_REASON:()=>tu,PROCESS_GUARD_POLICIES:()=>Hs,PROCESS_GUARD_STACK_MAX_CHARS:()=>Qm,PermissionReceiptSchema:()=>oa,QuestionReceiptSchema:()=>sa,REPLAY_GAP_EVENT:()=>In,REQUEST_ID_HEADER:()=>Eo,ReceiptContentSchema:()=>eu,RestoreBodySchema:()=>la,SECRET_WARNING_VALUE:()=>Cf,SEGMENTED_STORE_DEFAULTS:()=>ic,SERVER_MESSAGE_KEY:()=>ae,SERVER_MESSAGE_KEYS:()=>Vm,SERVE_RUNTIME_ENV:()=>is,SERVE_RUNTIME_ENV_NAMES:()=>zv,SESSION_ID_SHARD_MAX:()=>Lr,SESSION_RECOVERY_VERSION:()=>Rc,SESSION_STORE_CORE_ENV:()=>Hl,ServeSessionDriver:()=>ai,SetCwdBodySchema:()=>ua,SpeechDataSchema:()=>Kd,SseTransport:()=>Er,StoreError:()=>Gn,TANSR_READY_FRAME_VERSION:()=>og,TANSR_READY_PREFIX:()=>Co,TOKEN_CHECK_UNAVAILABLE_REASON:()=>Oy,TOKEN_INVALIDATING_CODES:()=>Fo,TURN_END_NOTIFY_SIGNATURE_HEADER:()=>na,ToolParameterSpecSchema:()=>xo,ToolResultReceiptSchema:()=>Ar,TranscriptDataSchema:()=>$d,TurnEndNotifier:()=>_r,V2_ASSEMBLY_MESSAGE_KEY:()=>tn,V2_ASSEMBLY_MESSAGE_KEYS:()=>_y,V2_CTX_PERSIST_MESSAGE_KEY:()=>wt,V2_CTX_PERSIST_MESSAGE_KEYS:()=>vy,V2_ERROR_CODE:()=>_e,V2_LIMITS:()=>qe,V2_ROUTE_TABLE:()=>Ji,V2_SESSION_ACTIONS:()=>ba,VideoGenDataSchema:()=>Vd,WEBHOOK_SIGNATURE_VERSIONS:()=>cg,alignHistoryPage:()=>So,appliedRuntimeEnvByGroup:()=>Wv,assertSessionIdShard:()=>$o,buildRemoteTool:()=>Nd,countSpeechCharacters:()=>Kc,createAgentSessionFactory:()=>tb,createAppTokenMinter:()=>hd,createBundleCache:()=>rr,createChaosBlobStore:()=>Cc,createFsBlobStore:()=>Ac,createMemoryBlobStore:()=>Tc,createMetricsRegistry:()=>hp,createPlatformServeSessionFactory:()=>Fd,createPlatformSessionAssembler:()=>jy,createServeAgentSessionStore:()=>Dh,createServeCheckpointStore:()=>os,createServeLogger:()=>Km,createUpstreamGovernor:()=>Dm,defaultMetrics:()=>Si,emitReadyFrame:()=>Ta,encodeAgentStreamFrame:()=>Ea,encodeKernelEventFrame:()=>ko,encodeSseComment:()=>Zs,encodeSseFrame:()=>on,endUserKeyOf:()=>Gt,extractBearerToken:()=>Gl,formatReadyFrame:()=>yu,getRequestContext:()=>Ii,installProcessGuards:()=>Xm,isAuthorized:()=>Ys,isControlFrameType:()=>Tr,isExcluded:()=>Io,isLoopbackHost:()=>Ia,isSessionHistoryStore:()=>rc,kernelMetricsFor:()=>Ss,negotiateLocale:()=>zf,parseExcludeTokens:()=>aa,parseHistoryPageQuery:()=>Vs,parseMediaArtifact:()=>Qd,parseReadyFrame:()=>ag,planSpeechInput:()=>Qc,processGuardRecordOf:()=>Ym,registerBuiltinLocales:()=>Lf,rejectionCodeOf:()=>Ra,renderOpenMetrics:()=>vs,resolvePlatformAdjudicator:()=>Ud,resolveRequestId:()=>xa,resolveServeRuntimeOptions:()=>Gv,resolveUpstreamFetch:()=>Gr,routeTemplateOf:()=>ka,runIdleCompaction:()=>od,runStorageConformance:()=>Ec,serveMetricsFor:()=>Qn,sessionIdShardOf:()=>Cy,sessionIdShardPrefix:()=>ef,sessionTitleOf:()=>Ki,setLocale:()=>Hf,shardedSessionId:()=>ud,signWebhookDelivery:()=>bu,sliceHistoryPage:()=>Kn,slowSubscriberGapFrame:()=>Cr,startServer:()=>Fv,sumRingStats:()=>ga,toCheckpointMetaView:()=>mr,toStoreError:()=>nc,tokenMatches:()=>Wl,translateMintError:()=>rf,translateUpstreamAssemblyErrors:()=>gd,upstreamAgentOptions:()=>jm,upstreamOriginOf:()=>qm});import{mkdirSync as nI,statSync as iI}from"node:fs";import ss from"node:path";var Uf=class extends Error{code="memory_project_mismatch";constructor(){let e=Fs.memoryProjectMismatch;super(`memory_project_mismatch: ${hr(e)}`),this.name="SessionMemoryProjectMismatchError"}};function Hd(t,e){try{let n=iI(t);return e==="dir"?n.isDirectory():n.isFile()}catch{return!1}}function cU(t){let e=Um(t.env),n=new Set,i;return(o,s)=>{let a;if(s!==void 0){a=io(o);let d=io(s);if(a.key!==d.key)throw new Uf}if(Hm()!=="deny"&&(t.autoMemoryEnabled?.()??t.autoMemory!==void 0))try{if(a??=io(o),t.autoMemory!==void 0&&t.autoMemoryEnabled===void 0&&(i??=io(t.cwd),i.key===a.key))return{...t.autoMemory,injection:{...t.autoMemory.injection},projectKey:a.key,canonicalRoot:a.canonicalRoot};let d=ss.join(e,"projects",a.key,"memory");if(!n.has(a.key)||!Hd(d,"dir")){nI(d,{recursive:!0});let f=ss.join(d,zm);Hd(f,"file")||Wm(f,JSON.stringify({path:a.canonicalRoot,createdAt:new Date().toISOString()},null,2)+`
|
|
37
|
-
`),n.size>=256&&n.clear(),n.add(a.key)}try{Gm(e,a.key,d)}catch(f){t.onMemoryNotice?.({key:Fs.autoMemoryLegacyMergeFailed,params:{detail:f instanceof Error?f.message:String(f)}})}let c=d,l=Gf(e);if(l!==null&&!Hd(ss.join(d,"MEMORY.md"),"file")){let f=ss.join(l,"projects",a.key,"memory");Hd(f,"dir")&&(c=f)}return{dir:d,readDir:c,...c!==d?{legacyReadDir:c}:{},projectKey:a.key,canonicalRoot:a.canonicalRoot,injection:{indexPath:ss.join(c,"MEMORY.md"),present:!1,bytes:0,lines:0,truncated:!1}}}catch(d){t.onMemoryNotice?.({key:Fs.autoMemorySetupFailed,params:{detail:d instanceof Error?d.message:String(d)}});return}}}function uU(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{Pa as a,Ig as b,Tg as c,m0 as d,h0 as e,at as f,ar as g,x0 as h,R0 as i,Xa as j,oy as k,Vu as l,Gw as m,dI as n,ct as o,cI as p,lI as q,sb as r,ab as s,Qt as t,Kn as u,xI as v,Ze as w,Gt as x,Ki as y,wo as z,xr as A,Fl as B,hb as C,gb as D,wb as E,FI as F,LI as G,HI as H,Dh as I,zI as J,Qw as K,ai as L,W2 as M,V2 as N,dd as O,$2 as P,ud as Q,wv as R,Fv as S,ND as T,UD as U,FD as V,Gv as W,Wv as X,Ln as Y,tb as Z,tI as _,Uf as $,cU as aa,uU as ba};
|
|
38
|
-
//# sourceMappingURL=tansr-chunk-LLW6GX7K.mjs.map
|