@tansr/cli 0.10.2 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/tansr-artifacts.json +1222 -830
- package/tansr-bg-A35DNHK2.mjs +5 -0
- package/tansr-chunk-2CIB4KCJ.mjs +5 -0
- package/{tansr-chunk-XXBNISJJ.mjs → tansr-chunk-2HZJSKHM.mjs} +2 -2
- package/{tansr-chunk-E67N3BDI.mjs → tansr-chunk-2PB54HDR.mjs} +2 -2
- package/tansr-chunk-33QZBUL6.mjs +6 -0
- package/tansr-chunk-3YSQG6KY.mjs +5 -0
- package/tansr-chunk-4DAH4AIH.mjs +7 -0
- package/{tansr-chunk-S77B4PI7.mjs → tansr-chunk-4IWNKAT5.mjs} +2 -2
- package/tansr-chunk-4YAEV3T6.mjs +9 -0
- package/tansr-chunk-546BDI3V.mjs +7 -0
- package/tansr-chunk-6N333TUL.mjs +241 -0
- package/{tansr-chunk-ZY3IR67Q.mjs → tansr-chunk-6QKU3GNA.mjs} +2 -2
- package/tansr-chunk-AHUB2IHT.mjs +5 -0
- package/tansr-chunk-AOH7YPF3.mjs +8 -0
- package/{tansr-chunk-C6COFFZK.mjs → tansr-chunk-B2O4DB4K.mjs} +2 -2
- package/tansr-chunk-C2NTVBEY.mjs +5 -0
- package/{tansr-chunk-UCG4D6ER.mjs → tansr-chunk-C75DEEUJ.mjs} +2 -2
- package/tansr-chunk-ECYZ457U.mjs +5 -0
- package/tansr-chunk-EFN24XG3.mjs +25 -0
- package/tansr-chunk-ENRIN7EG.mjs +7 -0
- package/{tansr-chunk-RVSBSUXE.mjs → tansr-chunk-ITZBYACC.mjs} +2 -2
- package/{tansr-chunk-J72JGEKH.mjs → tansr-chunk-IZZYKHSW.mjs} +3 -3
- package/tansr-chunk-JIC3VWLQ.mjs +252 -0
- package/tansr-chunk-JTGWG4BG.mjs +32 -0
- package/tansr-chunk-LA3LGOYQ.mjs +11 -0
- package/tansr-chunk-MAMODDQN.mjs +5 -0
- package/tansr-chunk-N644DEOO.mjs +5 -0
- package/tansr-chunk-NQOYEFEE.mjs +5 -0
- package/tansr-chunk-O7P4OFK7.mjs +7 -0
- package/tansr-chunk-OEHA7T4Q.mjs +26 -0
- package/{tansr-chunk-CI7LFRTK.mjs → tansr-chunk-OKNSOZDU.mjs} +7 -7
- package/tansr-chunk-OT4KIQLR.mjs +9 -0
- package/tansr-chunk-OUOTEH4A.mjs +5 -0
- package/tansr-chunk-Q3XDAUKT.mjs +65 -0
- package/tansr-chunk-RFH7OCN6.mjs +5 -0
- package/tansr-chunk-RUYIVG72.mjs +12 -0
- package/tansr-chunk-SCFXBKV6.mjs +8 -0
- package/tansr-chunk-SHLU4JN2.mjs +5 -0
- package/{tansr-chunk-M774GK3P.mjs → tansr-chunk-SIV2666W.mjs} +2 -2
- package/tansr-chunk-SX3XZNN6.mjs +6 -0
- package/tansr-chunk-SXNTYWJY.mjs +8 -0
- package/tansr-chunk-UVL2XWKL.mjs +5 -0
- package/tansr-chunk-V4HGMAJS.mjs +375 -0
- package/{tansr-chunk-OB47UYHK.mjs → tansr-chunk-W2WIN3M2.mjs} +2 -2
- package/tansr-chunk-WAYVH5ON.mjs +5 -0
- package/tansr-chunk-WPKFARCU.mjs +11 -0
- package/{tansr-chunk-726Y5F3M.mjs → tansr-chunk-YEYFEVYF.mjs} +2 -2
- package/tansr-chunk-YK3CE3JM.mjs +5 -0
- package/tansr-chunk-YOSRXZWY.mjs +5 -0
- package/tansr-compaction-history-LZXZTWBV.mjs +5 -0
- package/tansr-compaction-log-H2SPLK24.mjs +5 -0
- package/tansr-indexed-CPYJVPFI.mjs +5 -0
- package/tansr-lock-XWDVZMLY.mjs +5 -0
- package/tansr-main-6GDLXIRQ.mjs +7 -0
- package/tansr-render-SVMDLHLN.mjs +6 -0
- package/tansr-restore-7PS7WCJR.mjs +5 -0
- package/tansr-run-acp-entry-EQGUKZ5R.mjs +68 -0
- package/tansr-run-approvals-entry-SEYBHLS2.mjs +12 -0
- package/{tansr-run-auth-entry-X3SXNPOI.mjs → tansr-run-auth-entry-R3GKGKWX.mjs} +2 -2
- package/tansr-run-doctor-B3XK72DW.mjs +11 -0
- package/tansr-run-headless-entry-4XTAVPTW.mjs +84 -0
- package/tansr-run-init-entry-GH2KDGI6.mjs +5 -0
- package/tansr-run-logout-entry-PLGYDEOB.mjs +5 -0
- package/tansr-run-mcp-serve-entry-UHK4WSKL.mjs +14 -0
- package/tansr-run-orchestrate-entry-M7R3433X.mjs +11 -0
- package/tansr-run-org-entry-UONLGJIJ.mjs +17 -0
- package/tansr-run-policy-entry-NNQCV5WS.mjs +16 -0
- package/tansr-run-profile-entry-PV6OO7FV.mjs +14 -0
- package/tansr-run-serve-entry-GWZQZ37P.mjs +16 -0
- package/tansr-run-sessions-entry-WL7YLRJL.mjs +25 -0
- package/tansr-run-update-entry-YI47IPCC.mjs +5 -0
- package/tansr-spill-YVUTIFOS.mjs +5 -0
- package/tansr-src-LPMSGRKO.mjs +5 -0
- package/{tansr-src-JAODAP53.mjs → tansr-src-RQJPOVDN.mjs} +50 -50
- package/tansr-startup-account-MYFJ3NOL.mjs +7 -0
- package/{tansr-startup-model-SREG5HNN.mjs → tansr-startup-model-BCGEYUM4.mjs} +3 -3
- package/tansr-storage-journal-4E274MUA.mjs +5 -0
- package/tansr-todos-replay-TVQKP7OD.mjs +5 -0
- package/tansr-tui-3Q7Z3ALV.mjs +73 -0
- package/tansr.mjs +1 -1
- package/tansrd.mjs +444 -265
- package/tansr-bg-QY4G2SNZ.mjs +0 -5
- package/tansr-chunk-2C6JKHKM.mjs +0 -25
- package/tansr-chunk-53SL6W6G.mjs +0 -6
- package/tansr-chunk-5T7X32UX.mjs +0 -6
- package/tansr-chunk-6OXR4F5Y.mjs +0 -67
- package/tansr-chunk-BCOFZJWA.mjs +0 -279
- package/tansr-chunk-BX7CF5RQ.mjs +0 -25
- package/tansr-chunk-F7C6ITED.mjs +0 -5
- package/tansr-chunk-H6JYYWPW.mjs +0 -35
- package/tansr-chunk-HRKJLVKC.mjs +0 -7
- package/tansr-chunk-I3TOVAA6.mjs +0 -5
- package/tansr-chunk-J2ED6CI4.mjs +0 -5
- package/tansr-chunk-KSBP64Q5.mjs +0 -12
- package/tansr-chunk-LSYPDTQG.mjs +0 -22
- package/tansr-chunk-MWHLITGY.mjs +0 -11
- package/tansr-chunk-NA22YT73.mjs +0 -5
- package/tansr-chunk-NCIMR6LB.mjs +0 -5
- package/tansr-chunk-OSK64SU3.mjs +0 -5
- package/tansr-chunk-Q6MUMULP.mjs +0 -5
- package/tansr-chunk-QEKVLX7W.mjs +0 -5
- package/tansr-chunk-QHEQQ2JB.mjs +0 -9
- package/tansr-chunk-QNHXB55W.mjs +0 -11
- package/tansr-chunk-QWGSXFEJ.mjs +0 -7
- package/tansr-chunk-SJFDQLLC.mjs +0 -5
- package/tansr-chunk-TYJWMSVW.mjs +0 -5
- package/tansr-chunk-TZJHQ3TT.mjs +0 -38
- package/tansr-chunk-UAEARRRH.mjs +0 -8
- package/tansr-chunk-WGXWBU37.mjs +0 -8
- package/tansr-chunk-ZQ3ZK7IL.mjs +0 -37
- package/tansr-main-5V46X7QH.mjs +0 -7
- package/tansr-render-PUEISX75.mjs +0 -6
- package/tansr-run-acp-entry-ANNUR7IB.mjs +0 -63
- package/tansr-run-approvals-entry-SLLTFTSX.mjs +0 -12
- package/tansr-run-doctor-RYIQQOOK.mjs +0 -10
- package/tansr-run-headless-entry-I53HJDNX.mjs +0 -78
- package/tansr-run-init-entry-USPWKDRI.mjs +0 -5
- package/tansr-run-logout-entry-KO7ZL2M5.mjs +0 -5
- package/tansr-run-mcp-serve-entry-YMQH7WSF.mjs +0 -14
- package/tansr-run-orchestrate-entry-YN3M6BWY.mjs +0 -11
- package/tansr-run-org-entry-STRRZVI4.mjs +0 -17
- package/tansr-run-policy-entry-4ENHRAMQ.mjs +0 -16
- package/tansr-run-profile-entry-THJMZ7ZA.mjs +0 -14
- package/tansr-run-serve-entry-N5PK7ACI.mjs +0 -99
- package/tansr-run-sessions-entry-KIT7PALM.mjs +0 -23
- package/tansr-run-update-entry-HYSKHBB6.mjs +0 -5
- package/tansr-sqlite-event-store-UQLSSZKP.mjs +0 -26
- package/tansr-sqlite-spool-implementation-LHEIRSUX.mjs +0 -29
- package/tansr-src-KOEPYVXX.mjs +0 -5
- package/tansr-startup-account-QUJKOV6V.mjs +0 -7
- package/tansr-tui-DXGFMSII.mjs +0 -75
package/tansr-chunk-BX7CF5RQ.mjs
DELETED
|
@@ -1,25 +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{b as Sn,d as ws,e as Ss,g as Rs,h as ks}from"./tansr-chunk-SJFDQLLC.mjs";import{Ba as gs,Ca as Ir,Da as hs,Ea as ms,Ia as Ut,Ja as vs,Ka as fi,La as bs,Na as Is,Pa as As,e as ls,f as us,fa as ys,g as mr,h as ps,ia as cn,ja as fs,ka as mt,la as vr,ma as br}from"./tansr-chunk-ZQ3ZK7IL.mjs";import{E as yi,F as et,G as Gt,H as Nt,I as _e,J as lt,N as _,O as z,P,Q as ss,R as gr,S as an,T as tt,U as ze,V as as,W as Ge,X as cs,Y as nt,_ as ds,a as Me,ba as hr,c as Ee,d as yr,f as Lt,g as sn,h as Kn,i as es,j as fr,k as Ce,l as R,o as Je,p as ts,q as ns,u as rs,v as is,w as os}from"./tansr-chunk-I3TOVAA6.mjs";import{w as Qo,xb as pi}from"./tansr-chunk-QWGSXFEJ.mjs";var gi=class extends Error{constructor(n){super(`Archive capacity: ${n}`);this.code=n;this.name="ArchiveCapacityError"}code},dn=()=>({bytes:0,records:0});function Pe(t){throw new gi(t)}var Rt=t=>{(typeof t!="string"||t.length===0)&&Pe("invalid_input")},hi=(t,e)=>{(!Number.isSafeInteger(t)||Object.is(t,-0)||t<e)&&Pe("invalid_input")},vt=(t,e,n)=>(hi(t.bytes,e),hi(t.records,n),{bytes:t.bytes,records:t.records}),Rn=(t,e)=>vt({bytes:t.bytes+e.bytes,records:t.records+e.records},0,0),Cs=(t,e)=>t.bytes<=e.bytes&&t.records<=e.records,Ar=t=>({limit:vt(t,1,1),used:dn()}),_s=(t,e)=>t.bytes===e.bytes&&t.records===e.records,Bs=t=>({bindingId:t.bindingId,operationKey:t.operationKey,state:t.state,originalMax:{...t.originalMax},terminalReserve:{...t.terminalReserve}}),mi=class{#n;#i;#t=new Map;#p=new Map;#y=new Map;#c=new Map;#s=new Map;#a=0;constructor(e){e.inventory.status!=="known"&&Pe("inventory_unknown"),hi(e.maxReservations,1),this.#i=e.maxReservations,this.#n=Ar(e.globalLimit);for(let r of e.bindings){Rt(r.bindingId),Rt(r.applicationScopeId),Rt(r.endUserId),this.#t.has(r.bindingId)&&Pe("invalid_input");let i={bindingId:r.bindingId,applicationScopeId:r.applicationScopeId,endUserId:r.endUserId,limits:{binding:vt(r.limits.binding,1,1),application:vt(r.limits.application,1,1),endUser:vt(r.limits.endUser,1,1)}},o=this.#p.get(i.applicationScopeId);o&&!_s(o.limit,i.limits.application)&&Pe("invalid_input"),o||(o=Ar(i.limits.application),this.#p.set(i.applicationScopeId,o));let s=this.#y.get(i.applicationScopeId);s||(s=new Map,this.#y.set(i.applicationScopeId,s));let c=s.get(i.endUserId);c&&!_s(c.limit,i.limits.endUser)&&Pe("invalid_input"),c||(c=Ar(i.limits.endUser),s.set(i.endUserId,c)),this.#t.set(i.bindingId,{config:i,own:Ar(i.limits.binding),app:o,user:c}),this.#c.set(i.bindingId,new Map),this.#s.set(i.bindingId,new Map)}let n=e.inventory;(!["initial","restored"].includes(n.kind)||n.kind==="initial"&&(n.entries.length>0||n.reservations.length>0))&&Pe("invalid_input");for(let r of n.entries){Rt(r.entryId);let i=this.#o(r.bindingId);r.basket!=="original"&&r.basket!=="terminal"&&Pe("invalid_input");let o=vt(r,0,1),s=this.#s.get(r.bindingId);s.has(r.entryId)&&Pe("entry_exists"),this.#r(i,dn(),o)!==void 0&&Pe("capacity_exceeded"),s.set(r.entryId,{bindingId:r.bindingId,entryId:r.entryId,basket:r.basket,...o})}for(let r of n.reservations)r.state!=="reserved"&&r.state!=="unknown"&&Pe("invalid_input"),this.reserve(r).status==="rejected"&&Pe("capacity_exceeded"),r.state==="unknown"&&this.settle(r,{status:"unknown"})}#o(e){return Rt(e),this.#t.get(e)??Pe("binding_not_registered")}#r(e,n,r){let i=[["binding",e.own],["application",e.app],["endUser",e.user],["global",this.#n]],o=[];for(let[s,c]of i){let d=Rn(vt({bytes:c.used.bytes-n.bytes,records:c.used.records-n.records},0,0),r);if(!Cs(d,c.limit))return s;o.push(d)}i.forEach(([,s],c)=>{s.used=o[c]})}reserve(e){let n=this.#o(e.bindingId);Rt(e.operationKey);let r=this.#c.get(e.bindingId);r.has(e.operationKey)&&Pe("reservation_exists");let i=vt(e.originalMax,1,1),o=vt(e.terminalReserve,1,1),s=Rn(i,o);if(this.#a>=this.#i)return{status:"rejected",scope:"reservations"};let c=this.#r(n,dn(),s);if(c)return{status:"rejected",scope:c};let d={bindingId:e.bindingId,operationKey:e.operationKey,originalMax:i,terminalReserve:o,state:"reserved"};return r.set(e.operationKey,d),this.#a++,{status:"reserved",reservation:Bs(d)}}settle(e,n){let r=this.#o(e.bindingId);Rt(e.operationKey);let i=this.#c.get(e.bindingId),o=i.get(e.operationKey)??Pe("reservation_not_found");if(n.status==="unknown"){i.set(e.operationKey,{...o,state:"unknown"});return}n.status!=="known"&&Pe("invalid_input");let s=this.#s.get(e.bindingId),c=[],d=new Set,l=dn();for(let[u,v,g]of[["original",n.originalEntries,o.originalMax],["terminal",n.terminalEntries,o.terminalReserve]]){let b=dn();for(let A of v){Rt(A.entryId),(d.has(A.entryId)||s.has(A.entryId))&&Pe("entry_exists");let S=vt(A,0,1);b=Rn(b,S),Cs(b,g)||Pe("capacity_exceeded"),d.add(A.entryId),c.push({bindingId:e.bindingId,entryId:A.entryId,basket:u,...S})}l=Rn(l,b)}this.#r(r,Rn(o.originalMax,o.terminalReserve),l)&&Pe("capacity_exceeded");for(let u of c)s.set(u.entryId,u);i.delete(e.operationKey),this.#a--}releaseConfirmed(e){let n=this.#o(e.bindingId),r=this.#s.get(e.bindingId),i=new Set,o=dn();for(let s of e.entryIds){Rt(s),i.has(s)&&Pe("invalid_input");let c=r.get(s)??Pe("entry_not_found");i.add(s),o=Rn(o,c)}this.#r(n,o,dn());for(let s of i)r.delete(s);return{...o}}snapshot(){return{inventory:{status:"known",kind:"restored",reservations:[...this.#c.values()].flatMap(e=>[...e.values()].map(Bs)),entries:[...this.#s.values()].flatMap(e=>[...e.values()].map(n=>({...n})))},reservationCount:this.#a,usage:{global:{...this.#n.used},bindings:[...this.#t].map(([e,n])=>({bindingId:e,usage:{...n.own.used}})),applications:[...this.#p].map(([e,n])=>({applicationScopeId:e,usage:{...n.used}})),endUsers:[...this.#y].flatMap(([e,n])=>[...n].map(([r,i])=>({applicationScopeId:e,endUserId:r,usage:{...i.used}})))}}}};function wr(t){return new mi(t)}var xs="sdk2-spool-v1",Os="sdk2-spool-v2";function vi(t){throw new R(t)}function Ln(t){(typeof t!="string"||t.length===0||t.includes("\0")||bi(t)>256)&&vi("invalid_input")}function Ps(t,e=0){(!Number.isSafeInteger(t)||Object.is(t,-0)||t<e)&&vi("invalid_input")}function bi(t){return(typeof t!="string"||Buffer.from(t,"utf8").toString("utf8")!==t)&&vi("invalid_input"),Buffer.byteLength(t,"utf8")}var Vc=_,Sr=()=>{throw new R("reconciliation_required")},Xc=128,Yc=(t,e=!1)=>`host-record-retention-${t}${e?"-complete":""}`;function Ii(t){let e=P(t,["format","requestId","subject","identity","expectedHead","previousRevision","revision","requestedRecordIds","records","originalCommitId","originalDigest","candidateDigest","removedMessages"]),n=g=>typeof g=="string"&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(g),r=g=>typeof g=="string"&&/^[a-f0-9]{64}$/.test(g),i=g=>typeof g=="string"&&/^(0|[1-9][0-9]{0,18})$/.test(g)&&BigInt(g)<=9223372036854775807n;(e.format!=="serve-archive-record-delete-v1"||Buffer.byteLength(Vc(e))>16e3||!n(e.requestId)||!n(e.originalCommitId)||!r(e.originalDigest)||!r(e.candidateDigest)||!i(e.previousRevision)||!i(e.revision)||BigInt(e.revision)!==BigInt(e.previousRevision)+1n||BigInt(e.revision)>BigInt(Xc)||typeof e.removedMessages!="number"||!Number.isSafeInteger(e.removedMessages)||e.removedMessages<0||e.removedMessages>4096)&&Sr();let o=P(e.subject,["endUserId","sessionId"]),s=P(e.identity,["scope","bindingId","target","sourceId","sourceGeneration"]),c=P(s.scope,["applicationScopeId","endUserId"]),d=P(s.target,["sessionId","generations"]),l=P(d.generations,["historyEpoch","deletionGeneration","projectionRevision"]),p=P(e.expectedHead,["sequence","recordDigest"]);(Object.values(o).some(g=>typeof g!="string"||!g||Buffer.byteLength(g)>2048)||c.endUserId!==o.endUserId||d.sessionId!==o.sessionId||!n(c.applicationScopeId)||!n(s.bindingId)||!n(s.sourceId)||!n(s.sourceGeneration)||!n(l.historyEpoch)||!i(l.deletionGeneration)||!i(l.projectionRevision)||!i(p.sequence)||p.sequence==="0"||!r(p.recordDigest)||!Array.isArray(e.requestedRecordIds)||e.requestedRecordIds.length<1||e.requestedRecordIds.length>32||e.requestedRecordIds.some(g=>!n(g))||new Set(e.requestedRecordIds).size!==e.requestedRecordIds.length||!Array.isArray(e.records)||e.records.length<1||e.records.length>64)&&Sr();let u=0n,v=new Set;for(let g of e.records){let b=P(g,["recordId","sequence","recordDigest"]);(!n(b.recordId)||!i(b.sequence)||BigInt(b.sequence)<=u||BigInt(b.sequence)>BigInt(p.sequence)||!r(b.recordDigest)||v.has(b.recordId))&&Sr(),u=BigInt(b.sequence),v.add(b.recordId)}return e.requestedRecordIds.some(g=>!v.has(g))&&Sr(),e}function Es(t){return{format:"archive-record-deletion-v1",requestId:t.requestId,bindingId:t.identity.bindingId,retentionRevision:t.revision,state:"completed",removedMessages:t.removedMessages,recordIds:t.records.map(e=>e.recordId)}}function Bl(t,e){let n=Ii(t),r=_(n);return{bindingId:"control",operationKey:Yc(n.revision,e),intentDigest:z(r),originalMax:{bytes:16384,records:1},terminalReserve:{bytes:1,records:1}}}function xl(t,e){if(e.state!=="active"||e.fence!==null)return!1;let n=t.identity,r=e.registration;return e.storageBindingId==="control"&&t.subject.sessionId===e.target.sessionId&&t.subject.endUserId===r.scope.endUserId&&n.bindingId===r.bindingId&&n.scope.applicationScopeId===r.scope.applicationScopeId&&n.scope.endUserId===r.scope.endUserId&&n.sourceId===r.sourceId&&n.sourceGeneration===r.sourceGeneration&&_(n.target.generations)===_(e.target.generations)&&t.originalDigest===e.target.sourceSnapshotDigest}var qs=()=>{throw new R("reconciliation_required")},Gn=Object.freeze({intent:"offload-history-import",completed:"offload-history-import-completed"}),Rr=new WeakMap;function kn(t){let e=P(t,["format","subject","requestId","checkpointId","createdAt","contentSha256","initialSourceSnapshotDigest","identity","origin"]),n=v=>typeof v=="string"&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(v),r=v=>typeof v=="string"&&/^[a-f0-9]{64}$/.test(v),i=v=>typeof v=="string"&&/^(0|[1-9][0-9]{0,18})$/.test(v)&&BigInt(v)<=9223372036854775807n,o=P(e.subject,["endUserId","sessionId"]),s=P(e.identity,["scope","bindingId","target","sourceId","sourceGeneration"]),c=P(s.scope,["applicationScopeId","endUserId","authorizationRevision"]),d=P(s.target,["sessionId","sourceSnapshotDigest","generations"]),l=P(d.generations,["historyEpoch","deletionGeneration","projectionRevision"]),p=P(e.origin,["protocol","sessionId","history","originalArchive","sourceHandling","sourceSnapshotDigest","retentionRevision","source","notMigrated"]),u=P(p.source,["kind","checkpointId","contentSha256","exportedSessionId","exportedCheckpointId"]);return(e.format!=="sdk2-effective-history-import-v1"||!n(e.requestId)||!n(e.checkpointId)||typeof e.createdAt!="string"||!Number.isFinite(Date.parse(e.createdAt))||!r(e.contentSha256)||!r(e.initialSourceSnapshotDigest)||Object.values(o).some(v=>typeof v!="string"||!v||Buffer.byteLength(v)>2048)||!n(c.applicationScopeId)||!i(c.authorizationRevision)||c.endUserId!==o.endUserId||!n(s.bindingId)||!n(s.sourceId)||!n(s.sourceGeneration)||d.sessionId!==o.sessionId||d.sourceSnapshotDigest!==e.initialSourceSnapshotDigest||!n(l.historyEpoch)||!i(l.deletionGeneration)||!i(l.projectionRevision)||p.protocol!=="sdk2-ext-v1"||p.sessionId!==o.sessionId||p.history!=="effective-history"||p.originalArchive!=="not-proven-before-import"||p.sourceHandling!=="untouched-by-import"||!r(p.sourceSnapshotDigest)||!i(p.retentionRevision)||u.kind!=="checkpoint-import"||u.checkpointId!==e.checkpointId||u.contentSha256!==e.contentSha256||!n(u.exportedCheckpointId)||typeof u.exportedSessionId!="string"||!u.exportedSessionId||Buffer.byteLength(u.exportedSessionId)>2048||_(p.notMigrated)!==_(["usage","runtime-checkpoint","memory-selection","external-attachment-source"])||Buffer.byteLength(_(e))>16e3)&&qs(),e}function Ai(t,e){let n=kn(t);return{bindingId:"control",operationKey:e?Gn.completed:Gn.intent,intentDigest:z(_(n)),originalMax:{bytes:16384,records:1},terminalReserve:{bytes:1,records:1}}}function Ts(t){let e=kn(t);return{format:e.format,state:"completed",requestId:e.requestId,origin:e.origin}}async function ql(t,e,n){let r=kn(e),i=Ai(r,!1),o=t.status(i),s=t.status(Ai(r,!0));(Rr.has(t)||o?.state!=="committed"||s?.state!=="reserved"||_(o.reservation)!==_(i)||_(s.reservation)!==_(Ai(r,!0)))&&qs(),Rr.set(t,z(_(r)));try{return await n()}finally{Rr.delete(t)}}function Tl(t,e,n){let r=kn(e),i=r.identity;return Rr.get(t)===z(_(r))&&n.storageBindingId==="control"&&n.state==="active"&&n.fence===null&&i.bindingId===n.registration.bindingId&&i.sourceId===n.registration.sourceId&&i.sourceGeneration===n.registration.sourceGeneration&&_(i.scope)===_(n.registration.scope)&&_(i.target)===_(n.target)}import{createHash as Un}from"node:crypto";import{types as zn}from"node:util";var ln="sdk2-record-journal-v1",un="sdk2-record-journal-v2",Ds="0".repeat(64),Zc=9223372036854775807n,Qc=262144,ed=1048576,wi=33554432,ki=67108864,Si=262144,Ci=class extends Error{constructor(n){super(`Archive record journal: ${n}`);this.code=n;this.name="ArchiveRecordJournalError"}code};function ee(t){throw new Ci(t)}var Nn=t=>Un("sha256").update(t).digest("hex"),Ve=t=>Buffer.from(Me(t)).toString("utf8"),ut=(t,e=0n)=>{(typeof t!="string"||!/^(0|[1-9][0-9]{0,18})$/.test(t))&&ee("invalid_input");let n=BigInt(t);return(n<e||n>Zc)&&ee("invalid_input"),n},kt=(t,e,n)=>{(!Number.isSafeInteger(t)||Object.is(t,-0)||t<e||t>n)&&ee("invalid_input")},Ri=t=>{(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(t))&&ee("invalid_input")},Hs=Object.getPrototypeOf(Uint8Array.prototype),td=Object.getOwnPropertyDescriptor(Hs,"byteLength").get,nd=Object.getOwnPropertyDescriptor(Hs,"buffer").get;function js(t,e){(!t||typeof t!="object"||zn.isProxy(t)||![Object.prototype,null].includes(Object.getPrototypeOf(t)))&&ee("invalid_input");let n=Reflect.ownKeys(t);(n.length!==e.length||n.some(i=>typeof i!="string"||!e.includes(i)))&&ee("invalid_input");let r=Object.create(null);for(let i of e){let o=Object.getOwnPropertyDescriptor(t,i);(!o?.enumerable||!Object.hasOwn(o,"value"))&&ee("invalid_input"),r[i]=o.value}return r}function rd(t){let e=js(t,["operationKey","expectedHead","recordDraft","payload","attachments"]),n=e.attachments;(!n||typeof n!="object"||zn.isProxy(n)||!Array.isArray(n))&&ee("invalid_input");let r=Object.getOwnPropertyDescriptor(n,"length").value;(r>128||Reflect.ownKeys(n).length!==r+1)&&ee("invalid_input");let i=s=>{let c=js(s,["body","mediaType"]);return(!c.body||typeof c.body!="object"||zn.isProxy(c.body)||!zn.isUint8Array(c.body)||zn.isSharedArrayBuffer(nd.call(c.body)))&&ee("invalid_input"),{body:c.body,mediaType:c.mediaType}},o=[];for(let s=0;s<r;s++){let c=Object.getOwnPropertyDescriptor(n,String(s));(!c?.enumerable||!Object.hasOwn(c,"value"))&&ee("invalid_input"),o.push(i(c.value))}return{operationKey:e.operationKey,expectedHead:Ee(Me(e.expectedHead)),recordDraft:Ee(Me(e.recordDraft)),payload:i(e.payload),attachments:o}}function kr(t){(typeof t!="string"||!/^[0-9]{16}$/.test(t))&&ee("format_mismatch");let e=Number(t);return kt(e,0,Number.MAX_SAFE_INTEGER),e}function Ms(t,e,n,r){let i=Ee(Buffer.from(t));(!i||i.format!==ln&&i.format!==un)&&ee("format_mismatch");let o=i.format===un,s=o?kr(i.publishedAtMs):null;return t!==Ve({format:i.format,kind:"record",sourceId:n,sourceGeneration:r,record:e,...o?{publishedAtMs:i.publishedAtMs}:{}})&&ee("integrity_mismatch"),s}function Gl(t,e,n,r){kt(n,1e3,864e5),kt(r,0,Number.MAX_SAFE_INTEGER);let i=t.records.filter(s=>BigInt(s.sequence)>e);if(i.length===0)return!1;let o=Number.MAX_SAFE_INTEGER;for(let s of i){let c=t.publishedAtMs.get(s.recordId);if(c==null||r<c)return!0;o=Math.min(o,c)}return r-o>=n}function id(t,e){let{sourceId:n,sourceGeneration:r,generations:i}=e,o=Ve(i),s=S=>{Ve(S)!==o&&ee("stale_generation")},c=(S,k)=>{(S.basket!=="original"||S.entryId!==k.artifactId||S.bodyBytes!==k.bytes||S.bodySha256!==k.sha256||k.sourceId!==n)&&ee("integrity_mismatch")},d=[],l=new Map,p=new Map,u=new Map,v=0;for(let S of t){if(!S.entryId.startsWith("jr-p-")&&!S.entryId.startsWith("jr-a-"))continue;v+=S.metadataBytes,v>ki&&ee("capacity_exceeded");let k=Ee(Buffer.from(S.metadata,"utf8"));if((!k||k.format!==ln&&k.format!==un)&&ee("format_mismatch"),(k.sourceId!==n||k.sourceGeneration!==r)&&ee("stale_generation"),k.kind==="record"&&S.entryId.startsWith("jr-p-")){let I=k.format===un;Object.keys(k).sort().join(",")!==(I?"format,kind,publishedAtMs,record,sourceGeneration,sourceId":"format,kind,record,sourceGeneration,sourceId")&&ee("format_mismatch");let m=sn(k.record);l.set(m.recordId,I?kr(k.publishedAtMs):null),s(m.target.generations),c(S,m.payload),d.push(m),d.length>4096&&ee("capacity_exceeded"),p.set(m.payload.artifactId,{ref:m.payload,witness:S,recordId:m.recordId,payloadDigest:m.payloadDigest})}else k.kind==="attachment"&&S.entryId.startsWith("jr-a-")?((k.format!==ln||Object.keys(k).sort().join(",")!=="artifact,format,kind,recordId,sourceGeneration,sourceId"||typeof k.recordId!="string"||!k.artifact)&&ee("format_mismatch"),c(S,k.artifact),u.set(S.entryId,{recordId:k.recordId,artifact:k.artifact,witness:S})):ee("format_mismatch")}d.sort((S,k)=>ut(S.sequence,1n)<ut(k.sequence,1n)?-1:1);let g=Ds,b=new Set;for(let[S,k]of d.entries()){(k.sequence!==String(S+1)||k.predecessorDigest!==g||b.has(k.recordId)||k.target.sessionId!==d[0].target.sessionId)&&ee("archive_gap"),b.add(k.recordId),g=k.recordDigest;for(let I of k.attachments){let m=u.get(I.artifactId);(!m||m.recordId!==k.recordId||Ve(m.artifact)!==Ve(I)||p.has(I.artifactId))&&ee("archive_gap"),p.set(I.artifactId,{ref:I,witness:m.witness,recordId:k.recordId}),u.delete(I.artifactId)}if(k.projection){let I=ut(k.projection.coverage.throughSequence,1n);(I>=ut(k.sequence,1n)||d[Number(I-1n)]?.recordDigest!==k.projection.coverage.headDigest||k.projection.sourceHeadDigest!==k.predecessorDigest)&&ee("archive_gap")}}u.size>0&&ee("archive_gap");let A=d.at(-1);return{records:d,artifacts:p,publishedAtMs:l,head:A?{sequence:A.sequence,recordDigest:A.recordDigest}:null}}function Cr(t){let{spool:e,bindingId:n,sourceId:r,sourceGeneration:i}=t;for(let g of[n,r,i])Ri(g);let o=Ee(Me(t.generations));(!o||typeof o.historyEpoch!="string"||o.historyEpoch.length<1||Array.from(o.historyEpoch).length>512||Object.keys(o).sort().join(",")!=="deletionGeneration,historyEpoch,projectionRevision")&&ee("invalid_input"),ut(o.deletionGeneration),ut(o.projectionRevision);let s=Ve(o),c=g=>{Ve(g)!==s&&ee("stale_generation")},d=g=>Je(e).readEntry({bindingId:n,entryId:g,offset:0,maxBytes:1}).witness,l=()=>{let g=Je(e).snapshot();g.usage.bindings.some(A=>A.bindingId===n)||ee("invalid_input");function*b(){for(let A of g.inventory.entries)A.bindingId===n&&(A.entryId.startsWith("jr-p-")||A.entryId.startsWith("jr-a-"))&&(yield d(A.entryId))}return id(b(),{sourceId:r,sourceGeneration:i,generations:o})},p=(g,b)=>g===null?b===null:b!==null&&g.sequence===b.sequence&&g.recordDigest===b.recordDigest,u=(g,b,A,S)=>{(g.bindingId!==n||g.operationKey!==b||g.intentDigest!==A||g.entries.length!==S.length)&&ee("operation_conflict");for(let[k,I]of S.entries()){let m=g.entries[k];(!m||m.entryId!==I.entryId||m.basket!==I.basket||m.metadata!==I.metadata||m.bodyBytes!==I.body.byteLength||m.bodySha256!==Nn(I.body))&&ee("operation_conflict")}};l();let v={head(){return l().head},append(g){g=rd(g),(typeof g.operationKey!="string"||g.operationKey.length===0||g.operationKey.includes("\0")||Buffer.byteLength(g.operationKey,"utf8")>256||Buffer.from(g.operationKey).toString("utf8")!==g.operationKey)&&ee("invalid_input"),g.expectedHead!==null&&(ut(g.expectedHead.sequence,1n),/^[a-f0-9]{64}$/.test(g.expectedHead.recordDigest)||ee("invalid_input")),(!Array.isArray(g.attachments)||g.attachments.length>128)&&ee("invalid_input");let b=0;for(let L of[g.payload,...g.attachments]){let a=td.call(L.body);(a<1||a>wi)&&ee("invalid_input"),b+=a,b>ki&&ee("capacity_exceeded")}c(g.recordDraft.target.generations);let A=Nn(Ve([n,g.operationKey])),S=Kn({...g.recordDraft,recordId:`jr-r-${A}`,sequence:g.expectedHead===null?"1":String(ut(g.expectedHead.sequence,1n)+1n),predecessorDigest:g.expectedHead?.recordDigest??Ds,payload:{...g.payload,artifactId:`jr-p-${A}`,sourceId:r},attachments:g.attachments.map((L,a)=>({...L,artifactId:`jr-a-${Nn(Ve([n,g.operationKey,a]))}`,sourceId:r}))}),k=S.record,I={bindingId:n,operationKey:g.operationKey},m=e.status(I),w=Nn(Ve({format:ln,sourceId:r,sourceGeneration:i,expectedHead:g.expectedHead,recordDigest:k.recordDigest}));m&&m.reservation.intentDigest!==w&&ee("operation_conflict");let C=[{entryId:k.payload.artifactId,basket:"original",body:S.payload,metadata:Ve({format:ln,kind:"record",sourceId:r,sourceGeneration:i,record:k})},...k.attachments.map((L,a)=>({entryId:L.artifactId,basket:"original",body:S.attachments[a],metadata:Ve({format:ln,kind:"attachment",sourceId:r,sourceGeneration:i,recordId:k.recordId,artifact:L})}))],H=C.reduce((L,a)=>L+a.body.byteLength+Buffer.byteLength(a.metadata)+64,0),j=m?.state==="reserved"&&m.reservation.originalMax.bytes===H;if(m?.state==="committed"){let L=m.receipt.entries[0]??ee("operation_conflict"),a=Ee(Buffer.from(L.metadata));a.format===un?(kr(a.publishedAtMs),C[0]={...C[0],metadata:Ve({format:un,kind:"record",sourceId:r,sourceGeneration:i,record:k,publishedAtMs:a.publishedAtMs})}):a.format!==ln&&ee("format_mismatch")}else if(!j&&(t.publicationClock!==void 0||m?.state==="reserved")){t.publicationClock||ee("reconciliation_required");let L=t.publicationClock();kt(L,0,Number.MAX_SAFE_INTEGER);let a=String(L).padStart(16,"0");kr(a),C[0]={...C[0],metadata:Ve({format:un,kind:"record",sourceId:r,sourceGeneration:i,record:k,publishedAtMs:a})}}let x=C.reduce((L,a)=>L+a.body.byteLength+Buffer.byteLength(a.metadata)+64,0);if((x>ki||C.some(L=>Buffer.byteLength(L.metadata)>Qc))&&ee("capacity_exceeded"),m?.state==="committed")return u(m.receipt,I.operationKey,w,C),k;Je(e).snapshot().inventory.reservations.some(L=>L.bindingId===n&&L.operationKey!==I.operationKey)&&ee("reconciliation_required");let F=l();if(p(F.head,g.expectedHead)||ee("head_conflict"),F.records.length>=4096&&ee("capacity_exceeded"),F.records[0]&&F.records[0].target.sessionId!==k.target.sessionId&&ee("stale_generation"),k.projection){let L=ut(k.projection.coverage.throughSequence,1n);(L>=ut(k.sequence,1n)||F.records[Number(L-1n)]?.recordDigest!==k.projection.coverage.headDigest||k.projection.sourceHeadDigest!==k.predecessorDigest)&&ee("archive_gap")}if(!m)try{e.reserve({...I,intentDigest:w,originalMax:{bytes:x,records:C.length},terminalReserve:{bytes:1,records:1}})}catch(L){if(!(L instanceof R)||L.code!=="commit_unknown"||e.status(I)?.reservation.intentDigest!==w)throw L}try{u(e.commit({...I,intentDigest:w,entries:C}),I.operationKey,w,C)}catch(L){if(!(L instanceof R)||L.code!=="commit_unknown")throw L;let a=e.status(I);if(a?.state!=="committed")throw L;u(a.receipt,I.operationKey,w,C)}return k},list(g){c(g.generations),kt(g.limit,1,128),kt(g.maxBytes,1024,ed);let b=g.afterSequence===null?0n:ut(g.afterSequence),A=l();b>BigInt(A.records.length)&&ee("archive_gap");let S=[],k=m=>({protocol:"sdk2-ext-v1",bindingId:n,generations:{...o},records:S,nextAfterSequence:S.at(-1)?.sequence??g.afterSequence,complete:m,publishedThroughSequence:A.head?.sequence??null});for(let m of A.records.slice(Number(b),Number(b)+g.limit))if(S.push(m),Buffer.byteLength(JSON.stringify(k(b+BigInt(S.length)===BigInt(A.records.length))))>g.maxBytes){S.pop(),S.length===0&&ee("capacity_exceeded");break}let I=k(b+BigInt(S.length)===BigInt(A.records.length));return Buffer.byteLength(JSON.stringify(I))>g.maxBytes&&ee("capacity_exceeded"),I},readArtifactBody(g){c(g.generations),Ri(g.artifactId),kt(g.maxBytes,1,wi);let b=l().artifacts.get(g.artifactId)??ee("artifact_unavailable");b.ref.bytes>g.maxBytes&&ee("capacity_exceeded");let A=new Uint8Array(b.ref.bytes),S=Un("sha256"),k=b.payloadDigest?Un("sha256").update("tansr.sdk2.payload.v1\0"):void 0;for(let I=0;I<b.ref.bytes;){let m=Je(e).readEntry({bindingId:n,entryId:g.artifactId,offset:I,maxBytes:Math.min(Si,b.ref.bytes-I)});(m.bodyState!=="retained"||!m.body)&&ee("artifact_unavailable"),(m.offset!==I||m.body.byteLength===0||I+m.body.byteLength>b.ref.bytes||m.witness.bodySha256!==b.ref.sha256||m.witness.bodyBytes!==b.ref.bytes)&&ee("integrity_mismatch"),A.set(m.body,I),S.update(m.body),k?.update(m.body),I+=m.body.byteLength,m.complete!==(I===b.ref.bytes)&&ee("integrity_mismatch")}return(S.digest("hex")!==b.ref.sha256||k&&k.digest("hex")!==b.payloadDigest)&&ee("integrity_mismatch"),{artifact:{...b.ref},body:A}},readArtifact(g){c(g.generations),Ri(g.artifactId),kt(g.offset,0,wi-1),kt(g.maxBytes,1,Si);let b=l().artifacts.get(g.artifactId)??ee("artifact_unavailable");g.offset>=b.ref.bytes&&ee("invalid_input");let A=Un("sha256"),S=b.payloadDigest?Un("sha256").update("tansr.sdk2.payload.v1\0"):void 0;for(let I=0;I<b.ref.bytes;){let m=Je(e).readEntry({bindingId:n,entryId:g.artifactId,offset:I,maxBytes:Si});(m.bodyState!=="retained"||!m.body)&&ee("artifact_unavailable"),m.body.byteLength===0&&ee("integrity_mismatch"),A.update(m.body),S?.update(m.body),I+=m.body.byteLength}(A.digest("hex")!==b.ref.sha256||S&&S.digest("hex")!==b.payloadDigest)&&ee("integrity_mismatch");let k=Je(e).readEntry({bindingId:n,entryId:g.artifactId,offset:g.offset,maxBytes:g.maxBytes});return(k.bodyState!=="retained"||!k.body)&&ee("artifact_unavailable"),{artifact:{...b.ref},offset:g.offset,body:k.body,chunkSha256:Nn(k.body),complete:k.complete}}};return rs(v,{spool:e,bindingId:n,read:()=>{let g=l();return{records:g.records,head:g.head}}}),v}var _r=16,Ks=128+_r,Ls=262144,Gs=new WeakMap,_i=new WeakMap,Ct=t=>{throw new R(t)};function Ns(t){if(t!==null&&typeof t=="object"){for(let e of Object.values(t))Ns(e);Object.freeze(t)}return t}function Wl(t,e){Gs.set(t,e)}function zt(t){P(t,["spool","control","slot"],["operations","includeWork","expectedHeadEventDigest"]);let{spool:e,control:n}=t,r=_i.get(e);r&&(r.reentered=!0,Ct("reentrant"));let i={reentered:!1};_i.set(e,i);try{Gt(e,n)!=="sdk2-spool-v2"&&Ct("format_mismatch"),Ge(t.slot);let o={...t.slot};t.includeWork!==void 0&&typeof t.includeWork!="boolean"&&Ct("invalid_input"),t.expectedHeadEventDigest!==void 0&&t.expectedHeadEventDigest!==null&&(typeof t.expectedHeadEventDigest!="string"||!/^[a-f0-9]{64}$/.test(t.expectedHeadEventDigest))&&Ct("invalid_input");let s=ss(t.operations??[],_r).map(u=>(P(u,["bindingId","operationKey"]),{...u}));new Set(s.map(u=>_(u))).size!==s.length&&Ct("invalid_input");let c=Gs.get(e)??Ct("identity_mismatch"),d=et(e,n,o);i.reentered&&Ct("reentrant");let l=c(o,d,s,{includeWork:t.includeWork,expectedHeadEventDigest:t.expectedHeadEventDigest}),p=et(e,n,o);return i.reentered&&Ct("reentrant"),_({scope:d.scope,target:d.target})!==_({scope:p.scope,target:p.target})&&Ct("reconciliation_required"),Ns(structuredClone(l))}finally{_i.delete(e)}}import{types as ea}from"node:util";import{closeSync as Ti,existsSync as Fn,fstatSync as ji,fsyncSync as Ws,lstatSync as $s,openSync as Di,readSync as od,realpathSync as Hi,writeFileSync as sd}from"node:fs";import{hostname as Mi}from"node:os";import{join as Wn}from"node:path";import{types as xi}from"node:util";function Ke(t){try{return fr(t)}catch(e){throw e instanceof es?new R("invalid_input"):e}}var Bi=new WeakMap,Js=new WeakMap,Us=new WeakMap,Ki=262144,$n=4096,ad=128,Br=new WeakMap;function Vs(t){let e=pn(Wn(t.physical.store.path,".sdk2-archive-owner-v2.json"),Ki).bytes,n=Ys(e),r={epoch:t.ownerEpoch,pid:process.pid,host:Mi()};(z(e)!==t.ownerRootDigest||z(_(t.physical))!==t.physicalPairDigest||!pt(n.physical,t.physical)||!pt(n.slot,t.slot)||n.registration.sessionId!==t.sessionId||n.registration.scope.applicationScopeId!==t.scope.applicationScopeId||n.registration.scope.endUserId!==t.scope.endUserId||Fn(Li(t.physical.store.path,t.ownerRootDigest,r)))&&se("identity_mismatch"),Gi({...t,spool:t.physical.spool,assertAuthorized(){}},n);let i=Br.get(t.storeIdentity);i||(i=new Map,Br.set(t.storeIdentity,i));let o=i.get(t.ownerRootDigest);o||(o=new Map,i.set(t.ownerRootDigest,o)),o.set(r.epoch,Object.freeze({sessionId:t.sessionId,scope:Object.freeze({...t.scope}),slot:Object.freeze({...t.slot}),pairDigest:t.physicalPairDigest,owner:Object.freeze(r)}))}function se(t="reconciliation_required"){throw new R(t)}var pt=(t,e)=>_(t)===_(e);function Jn(t){(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(t))&&se("invalid_input")}function zs(t){(typeof t!="string"||!/^[a-f0-9]{64}$/.test(t))&&se("invalid_input")}function cd(t){let e=Hi(t),n=$s(e,{bigint:!0});return(!n.isFile()||n.isSymbolicLink()||n.ino===0n)&&se("identity_mismatch"),Object.freeze({path:e,dev:n.dev.toString(),ino:n.ino.toString()})}function pn(t,e){let n=$s(t,{bigint:!0});(!n.isFile()||n.isSymbolicLink())&&se("identity_mismatch");let r=Di(t,"r");try{let i=ji(r,{bigint:!0});(i.dev!==n.dev||i.ino!==n.ino||i.ino===0n)&&se("identity_mismatch"),i.size>BigInt(e)&&se("capacity_exceeded");let o=Buffer.alloc(e+1),s=0;for(;s<o.length;){let l=od(r,o,s,o.length-s,null);if(l===0)break;s+=l}s>e&&se("capacity_exceeded");let c=o.subarray(0,s),d=c.toString("utf8");return Buffer.from(d).equals(c)||se(),{bytes:d,physical:Object.freeze({path:Hi(t),dev:i.dev.toString(),ino:i.ino.toString()})}}finally{Ti(r)}}function Xs(t){try{let e=P(t,["epoch","pid","host"]);return Jn(e.epoch),(!Number.isSafeInteger(e.pid)||e.pid<=0||typeof e.host!="string"||e.host.length===0)&&se(),Object.freeze(e)}catch{se()}}function dd(t){t.host!==Mi()&&se();try{process.kill(t.pid,0)}catch(e){if(e.code==="ESRCH")return}se()}function Fs(t,e=!1){let n=P(t,e?["path","dev","ino","storeId"]:["path","dev","ino"]);return(typeof n.path!="string"||n.path.length===0||n.path.includes("\0")||typeof n.dev!="string"||!/^(0|[1-9][0-9]*)$/.test(n.dev)||typeof n.ino!="string"||!/^[1-9][0-9]*$/.test(n.ino))&&se(),e&&Jn(n.storeId),Object.freeze(n)}function Ys(t){try{let e=P(JSON.parse(t),["format","physical","slot","registration","createRequest","createSemanticDigest","confirmedHistory","owner"]);e.format!=="sdk2-store-owner-v2"&&se("format_mismatch"),_(e)!==t&&se();let n=P(e.physical,["store","spool"]),r=Object.freeze({store:Fs(n.store),spool:Fs(n.spool,!0)}),i=P(e.slot,["storageBindingId","slotId"]),o=Object.freeze(i);Ge(o);let s=ze({kind:"initialize",transitionId:"owner-root-validation",registration:e.registration,epoch:{id:"owner-root-validation",issuedAtMs:0,expiresAtMs:1,active:!1}});s.kind!=="initialize"&&se();let c=s.registration,d=an({...o,scope:c.scope,operation:"binding-create",request:e.createRequest}).request;zs(e.createSemanticDigest);let l=P(e.confirmedHistory,["commitId","observation"]);Jn(l.commitId);let p=P(l.observation,["sessionId","sourceSnapshotDigest","localHistoryGeneration"]);return(p.sessionId!==c.sessionId||!Number.isSafeInteger(p.localHistoryGeneration)||p.localHistoryGeneration<0||Object.is(p.localHistoryGeneration,-0))&&se(),zs(p.sourceSnapshotDigest),Zs({format:e.format,physical:r,slot:o,registration:c,createRequest:d,createSemanticDigest:e.createSemanticDigest,confirmedHistory:{commitId:l.commitId,observation:{sessionId:c.sessionId,sourceSnapshotDigest:p.sourceSnapshotDigest,localHistoryGeneration:p.localHistoryGeneration}},owner:Xs(e.owner)})}catch(e){if(e instanceof R&&["format_mismatch","capacity_exceeded"].includes(e.code))throw e;se()}}function Zs(t){if(t&&typeof t=="object"){for(let e of Object.values(t))Zs(e);Object.freeze(t)}return t}function ld(t){let e=P(t,["storeIdentity","sessionId","scope","slot","spool","ownerEpoch","assertAuthorized"]);(!e.storeIdentity||typeof e.storeIdentity!="object"||xi.isProxy(e.storeIdentity)||typeof e.assertAuthorized!="function"||xi.isProxy(e.assertAuthorized))&&se("invalid_input"),Jn(e.ownerEpoch);let n=P(e.slot,["storageBindingId","slotId"]),r=Object.freeze(n);Ge(r);let i=an({...r,scope:e.scope,operation:"binding-create",request:{operationEpoch:e.ownerEpoch,requestId:"owner-preflight"}});(typeof e.sessionId!="string"||[...e.sessionId].length===0||[...e.sessionId].length>512||Buffer.from(e.sessionId).toString("utf8")!==e.sessionId)&&se("invalid_input");let o=P(e.spool,["path","storeId"]);return Jn(o.storeId),(typeof o.path!="string"||o.path.length===0||o.path.includes("\0"))&&se("invalid_input"),Object.freeze({storeIdentity:e.storeIdentity,sessionId:e.sessionId,scope:Object.freeze(i.scope),slot:r,spool:Object.freeze(o),ownerEpoch:e.ownerEpoch,assertAuthorized:e.assertAuthorized})}function Oi(t,e){let n=Us.get(t);n||(n={active:!1,reentered:!1},Us.set(t,n)),n.active&&(n.reentered=!0,se("reentrant")),n.active=!0,n.reentered=!1;try{let r=e(n);return n.reentered&&se("reentrant"),r}catch(r){throw r instanceof R?r:new R("storage_failure")}finally{n.active=!1}}function Pi(t,e){let n=Reflect.apply(t.assertAuthorized,void 0,[]);xi.isPromise(n)&&Ce(n),n!==void 0&&se("invalid_input"),e.reentered&&se("reentrant")}function Li(t,e,n){return Wn(t,`.sdk2-installation-owner-${z(_([e,n]))}.json`)}function Gi(t,e){let n=Nt(t.storeIdentity,t.sessionId,t.scope),r={...cd(t.spool.path),storeId:t.spool.storeId};pt(e.physical,{store:n,spool:r})||se("identity_mismatch"),Fn(Wn(n.path,".sdk2-archive-owner.json"))&&se("format_mismatch")}function Ei(t){Gi(t.options,t.root),pn(t.rootPath,Ki).bytes!==t.rootBytes&&se("identity_mismatch");for(let e of t.predecessors)e.path&&pn(e.path,$n).bytes!==e.bytes&&se();Fn(Li(t.root.physical.store.path,t.rootDigest,t.owner))&&se(),Br.get(t.options.storeIdentity)?.get(t.rootDigest)?.has(t.owner.epoch)&&se()}function qi(t,e){Pi(t.options,e),Ei(t);let n=pn(t.path,$n);(n.bytes!==t.bytes||!t.physical||!pt(n.physical,t.physical))&&se("identity_mismatch")}function ud(t,e){(t.storeIdentity!==e.storeIdentity||t.assertAuthorized!==e.assertAuthorized||t.sessionId!==e.sessionId||t.ownerEpoch!==e.ownerEpoch||!pt(t.slot,e.slot)||!pt(t.spool,e.spool)||t.scope.applicationScopeId!==e.scope.applicationScopeId||t.scope.endUserId!==e.scope.endUserId)&&se("identity_mismatch")}function pd(t){let e=pn(t.path,$n);(e.bytes!==t.bytes||!t.physical||!pt(e.physical,t.physical))&&se();let n=Di(t.path,"r+");try{let r=ji(n,{bigint:!0});(r.dev.toString()!==t.physical.dev||r.ino.toString()!==t.physical.ino)&&se("identity_mismatch"),Ws(n)}finally{Ti(n)}}function Qs(t){let e=ld(t);return Oi(t,n=>{Pi(e,n);let r=Bi.get(t);if(r)ud(e,r.options),Ei(r),r.token||pd(r);else{let i=Nt(e.storeIdentity,e.sessionId,e.scope);Fn(Wn(i.path,".sdk2-archive-owner.json"))&&se("format_mismatch");let o=Wn(i.path,".sdk2-archive-owner-v2.json"),s=pn(o,Ki).bytes,c=Ys(s);(c.registration.sessionId!==e.sessionId||!pt(c.slot,e.slot)||c.registration.scope.applicationScopeId!==e.scope.applicationScopeId||c.registration.scope.endUserId!==e.scope.endUserId)&&se("identity_mismatch"),Gi(e,c);let d=z(s),l=Object.freeze({epoch:e.ownerEpoch,pid:process.pid,host:Mi()}),p=[],u=new Set,v=c.owner,g,b,A;for(let k=0;;k++){k>=ad&&se("capacity_exceeded"),(u.has(v.epoch)||v.epoch===l.epoch)&&se(),u.add(v.epoch);let I=Br.get(e.storeIdentity)?.get(d)?.get(v.epoch);if(I&&I.sessionId===e.sessionId&&I.scope.applicationScopeId===e.scope.applicationScopeId&&I.scope.endUserId===e.scope.endUserId&&pt(I.slot,e.slot)&&I.pairDigest===z(_(c.physical))&&pt(I.owner,v)||dd(v),p.push({owner:v,...g?{path:g,bytes:b}:{}}),A=Li(i.path,d,v),!Fn(A))break;let m=pn(A,$n).bytes,w;try{w=P(JSON.parse(m),["format","rootDigest","owner"])}catch{se()}(w.format!=="sdk2-installation-owner-successor-v1"||w.rootDigest!==d||_(w)!==m)&&se(),v=Xs(w.owner),g=A,b=m}r={input:t,options:e,root:c,rootBytes:s,rootPath:o,rootDigest:d,pairDigest:z(_(c.physical)),owner:l,predecessors:Object.freeze(p.map(k=>Object.freeze(k))),path:A,bytes:_({format:"sdk2-installation-owner-successor-v1",rootDigest:d,owner:l})},Buffer.byteLength(r.bytes)>$n&&se("capacity_exceeded"),Pi(e,n),Ei(r),Bi.set(t,r);let S;try{S=Di(A,"wx",384)}catch(k){throw Bi.delete(t),k.code==="EEXIST"&&se(),k}try{let k=ji(S,{bigint:!0});r.physical=Object.freeze({path:Hi(A),dev:k.dev.toString(),ino:k.ino.toString()}),sd(S,r.bytes),Ws(S)}finally{Ti(S)}}if(qi(r,n),!r.token){let i=r,o=Object.freeze({ownerEpoch:r.owner.epoch,ownerRootDigest:r.rootDigest,physicalPairDigest:r.pairDigest,assertCurrent(){Oi(i.input,s=>{qi(i,s)})}});Js.set(o,r),r.token=o}return r.token})}function rt(t,e){let n=Js.get(t)??se("identity_mismatch"),r=P(e,["storeIdentity","sessionId","slot"]);return(r.storeIdentity!==n.options.storeIdentity||r.sessionId!==n.options.sessionId||!pt(r.slot,n.options.slot))&&se("identity_mismatch"),Oi(n.input,i=>(qi(n,i),Object.freeze({root:n.root,predecessorOwners:Object.freeze(n.predecessors.map(o=>o.owner)),currentOwner:n.owner,ownerRootDigest:n.rootDigest,physicalPairDigest:n.pairDigest})))}var ta=new WeakMap,Ni=new WeakMap,at=t=>{throw new R(t)};function pu(t,e){ta.set(t,e)}function na(t){P(t,["owner","storeIdentity","spool","sessionId","slot","readAuthority"]);let{owner:e,storeIdentity:n,spool:r,sessionId:i,readAuthority:o}=t,s=Ni.get(r);s&&(s.reentered=!0,at("reentrant"));let c={reentered:!1};Ni.set(r,c);try{Ge(t.slot);let d={...t.slot};(typeof o!="function"||ea.isProxy(o))&&at("invalid_input");let l={storeIdentity:n,sessionId:i,slot:d},p=rt(e,l),u=ta.get(r)??at("identity_mismatch"),v=()=>{let I=Reflect.apply(o,void 0,[]);ea.isPromise(I)&&(Promise.prototype.then.call(I,void 0,()=>{}),at("invalid_input"));let m=P(I,["scope","sessionId"]);m.sessionId!==i&&at("identity_mismatch");let w=an({...d,scope:m.scope,operation:"binding-create",request:p.root.createRequest}).scope;return(w.applicationScopeId!==p.root.registration.scope.applicationScopeId||w.endUserId!==p.root.registration.scope.endUserId)&&at("identity_mismatch"),{scope:w,sessionId:i}},g=v();c.reentered&&at("reentrant");let b=_e(r,n,i,g.scope);_(b.identity)!==_(p.root.physical)&&at("identity_mismatch");let A=u(d,g),S=v(),k=rt(e,l);return c.reentered&&at("reentrant"),(_(g)!==_(S)||k.ownerRootDigest!==p.ownerRootDigest||k.physicalPairDigest!==p.physicalPairDigest)&&at("reconciliation_required"),_(_e(r,n,i,S.scope).identity)!==_(p.root.physical)&&at("identity_mismatch"),A.current&&_(A.current.registration)!==_(p.root.registration)&&at("identity_mismatch"),structuredClone(A)}finally{Ni.delete(r)}}var ra=new WeakMap;function fu(t,e){ra.set(t,e)}function ia(t,e){return ra.get(t)?.(e)}import{types as zc}from"node:util";import{closeSync as To,existsSync as Eo,fstatSync as il,fsyncSync as vc,openSync as jo,readFileSync as ol,writeFileSync as sl}from"node:fs";import{hostname as al}from"node:os";import{join as qo}from"node:path";import{types as vn}from"node:util";var oa=new WeakSet,sa=new WeakMap;function bu(t){let e=P(t,["commitId","storeIdentity","observation","original"]),n=P(e.observation,["sessionId","sourceSnapshotDigest","localHistoryGeneration"]);if(typeof e.commitId!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(e.commitId)||e.storeIdentity===null||typeof e.storeIdentity!="object"||typeof n.sessionId!="string"||n.sessionId.length===0||n.sessionId.length>512||typeof n.sourceSnapshotDigest!="string"||!/^[a-f0-9]{64}$/.test(n.sourceSnapshotDigest)||typeof n.localHistoryGeneration!="number"||!Number.isSafeInteger(n.localHistoryGeneration)||n.localHistoryGeneration<0||Object.is(n.localHistoryGeneration,-0))throw new R("invalid_input");let r=e.commitId,i=e.storeIdentity,o=e.original,s=Object.freeze({sessionId:n.sessionId,sourceSnapshotDigest:n.sourceSnapshotDigest,localHistoryGeneration:n.localHistoryGeneration}),c=Ke(o),d={confirmed:!1},l=Object.freeze(c.then(()=>{d.confirmed=!0})),p=Object.freeze(l.then(()=>Object.freeze({state:"confirmed"}),()=>Object.freeze({state:"unconfirmed"}))),u=Object.freeze({commitId:r,storeIdentity:i,observation:s,original:o,completion:l,outcome:p});return oa.add(u),sa.set(u,d),u}function Ui(t,e){if(!oa.has(t)||t.storeIdentity!==e)throw new Error("Archive history commit identity mismatch")}function aa(t,e){if(Ui(t,e),!sa.get(t)?.confirmed)throw new R("reconciliation_required")}import{types as zi}from"node:util";var _t=new WeakMap,Vn=new WeakMap;function ca(t){let e=_t.get(t)??Be("identity_mismatch");return Object.freeze({phase:e.phase,hasRuntime:e.runtime!==void 0})}function Be(t="reconciliation_required"){throw new R(t)}function xr(t){let e=P(t,["storeIdentity","sessionId","operationKey","semanticDigest"]);(!e.storeIdentity||typeof e.storeIdentity!="object"||zi.isProxy(e.storeIdentity)||typeof e.sessionId!="string"||[...e.sessionId].length<1||[...e.sessionId].length>512||Buffer.from(e.sessionId).toString("utf8")!==e.sessionId||typeof e.operationKey!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,255}$/.test(e.operationKey)||typeof e.semanticDigest!="string"||!/^[a-f0-9]{64}$/.test(e.semanticDigest))&&Be("invalid_input");let n=e.storeIdentity,r=e.sessionId,i=Vn.get(n),o=i?.get(r);if(o)return(o.operationKey!==e.operationKey||o.semanticDigest!==e.semanticDigest)&&Be("operation_conflict"),o.token;let s=Object.freeze(Object.create(null)),c={token:s,operationKey:e.operationKey,semanticDigest:e.semanticDigest,phase:"prepared"};return _t.set(s,c),i||(i=new Map,Vn.set(n,i)),i.set(r,c),s}function Cn(t){let e=_t.get(t)??Be("identity_mismatch");e.phase==="prepared"&&(e.phase="accepted")}function da(t,e){let n=_t.get(t)??Be("identity_mismatch");(!e||typeof e!="object"||zi.isProxy(e))&&Be("invalid_input"),n.phase!=="accepted"&&n.phase!=="installed"&&Be(),n.runtime!==void 0&&n.runtime!==e&&Be("identity_mismatch"),n.runtime=e,n.phase="installed"}function la(t,e){let n=_t.get(t)??Be("identity_mismatch");(!e||typeof e!="object"||zi.isProxy(e))&&Be("invalid_input"),n.phase!=="accepted"&&n.phase!=="retiring"&&Be(),n.runtime!==void 0&&n.runtime!==e&&Be("identity_mismatch"),n.runtime=e,n.phase="retiring"}function ua(t){let e=_t.get(t)??Be("identity_mismatch");e.phase==="installed"&&(e.phase="accepted")}function pa(t,e,n,r){let i=_t.get(t)??Be("identity_mismatch"),o=Vn.get(e);(o?.get(n)!==i||i.runtime!==r||!["installed","retiring","accepted"].includes(i.phase))&&Be("identity_mismatch");let s=!1;return()=>{s||((o?.get(n)!==i||i.runtime!==r)&&Be("identity_mismatch"),i.phase="accepted",i.runtime=void 0,s=!0)}}function Ft(t){let e=_t.get(t)??Be("identity_mismatch");e.phase==="retired"&&Be("operation_conflict"),e.phase="retiring"}function yd(t,e){let n=t===void 0?void 0:Vn.get(t)?.get(e);n||Be("identity_mismatch"),Ft(n.token)}function Or(t){let e=_t.get(t)??Be("identity_mismatch");e.phase!=="retiring"&&Be(),e.runtime=void 0,e.phase="retired"}function ya(t,e,n){let r=t===void 0?void 0:Vn.get(t)?.get(e);return r!==void 0&&(r.phase==="retired"?n!==void 0:r.phase!=="installed"||r.runtime!==n)}function Pr(t,e,n){ya(t,e,n)&&Be()}import{types as en}from"node:util";import{types as Tt}from"node:util";import{types as _n}from"node:util";function Bt(t,e,n){return Object.freeze({sessionId:t,localHistoryGeneration:n,sourceSnapshotDigest:Lt(Buffer.from(JSON.stringify(e),"utf8"))})}function Bu(t){if(_n.isPromise(t))throw Promise.prototype.then.call(t,void 0,()=>{}),new Error("Archive binding work must be synchronous");if(!t||typeof t!="object"||_n.isProxy(t)||![null,Object.prototype].includes(Object.getPrototypeOf(t)))throw new Error("Invalid archive binding candidate");for(let e of Reflect.ownKeys(t)){let n=Object.getOwnPropertyDescriptor(t,e);if(typeof e!="string"||!["value","capture","contextMaterials","lifecycle","installation"].includes(e)||!n.enumerable||!Object.hasOwn(n,"value"))throw new Error("Invalid archive binding candidate")}if(!Object.hasOwn(t,"value"))throw new Error("Invalid archive binding candidate");if(t.installation!==void 0&&t.lifecycle===void 0)throw new Error("Archive installation requires a complete lifecycle bundle");return Object.freeze({...t})}function xu(t){if(t===void 0)return;let e=t.assertReady();if(e!==void 0)throw _n.isPromise(e)&&Promise.prototype.then.call(e,void 0,()=>{}),new Error("Archive capture readiness must be synchronous")}var fa=new WeakMap;function gd(t){if(_n.isPromise(t))throw Ce(t),new Error("Archive source observation must be synchronous");if(t===null||typeof t!="object"&&typeof t!="function")return;let e=t;for(let n=0;e!==null;n++){if(n>=8||_n.isProxy(e)||Object.getOwnPropertyDescriptor(e,"then")!==void 0)throw new Error("Archive source observation must be synchronous");e=Object.getPrototypeOf(e)}}function Ou(t,e,n,r){if(typeof r!="function"||_n.isProxy(r))throw new Error("Invalid archive source observation callback");let i=fa.get(t);if(i===void 0&&(i={active:!1,reentered:!1},fa.set(t,i)),i.active)throw i.reentered=!0,new Error("Archive source observation is reentrant");i.active=!0,i.reentered=!1;let o=i,s=!0;try{n();let c=Object.freeze({...e()}),d=Object.freeze({observation:c,assertCurrent(){if(!s||o.reentered)throw new Error("Archive source observation lease is no longer current");n();let p=e();if(p.sessionId!==c.sessionId||p.localHistoryGeneration!==c.localHistoryGeneration||p.sourceSnapshotDigest!==c.sourceSnapshotDigest)throw new Error("Archive source observation changed")}});d.assertCurrent();let l=r(d);return gd(l),d.assertCurrent(),l}finally{s=!1,i.active=!1}}var Wt=(t,e)=>_(t)===_(e);function Wi(){throw new R("identity_mismatch")}function Xn(t,e,n,r,i){let o=e.root,s=t.current;if((!s||t.writeBarrier!=="clear"||!Wt(s.registration,o.registration)||!Wt(n.request,o.createRequest)||nt(o.slot,o.registration,{kind:"binding-create",body:n}).semantic!==o.createSemanticDigest||t.ready!==null||t.retirement!==null||s.fence!==null)&&Wi(),t.plan===null){(s.state!=="unbound"||t.originalCreate!==null||t.createEventDigest!==null||!Wt(s.target,n.target)||s.revision!==n.expectedRevision||i!==void 0&&t.headEventDigest!==i)&&Wi();return}let c=t.plan;(s.state!=="active"||t.headEventDigest!==t.createEventDigest||BigInt(s.revision)!==BigInt(n.expectedRevision)+1n||!Wt(s.target,n.target)||!Wt(t.originalCreate,n)||c.ownerRootDigest!==e.ownerRootDigest||c.physicalPairDigest!==e.physicalPairDigest||c.createSemanticDigest!==o.createSemanticDigest||!Wt(c.confirmedHistory,o.confirmedHistory)||!Wt(c.createRequest,o.createRequest)||!Wt({limits:c.createResponse.limits,rejectedCapabilities:c.createResponse.rejectedCapabilities,captureBindingId:c.captureBindingId,recordBindingId:c.recordBindingId,materialBindingId:c.materialBindingId},r))&&Wi()}import{types as Id}from"node:util";import{createHash as $i}from"node:crypto";import{types as Yn}from"node:util";var Er="sdk2-inline-turn-attachments-v1",Ot="sdk2-trusted-turn-attachments-v1",xt="sdk2-trusted-media-turn-attachments-v2",qr=65536;function bt(t){return t===Ot||t===xt}function Zn(t,e){if(bt(t)){if(typeof e!="string"||!e||e.includes("\0")||Buffer.byteLength(e)>256||Buffer.from(e).toString("utf8")!==e)throw new R("invalid_input")}else if(t!==void 0&&t!==Er||e!==void 0)throw new R("invalid_input")}function ha(t,e){let n=JSON.parse(Buffer.from(t).toString("utf8"));if(n.format!==cn||!Array.isArray(n.messages))throw new R("invalid_input");let r=[],i=new Set;for(let[o,s]of n.messages.entries())for(let[c,d]of s.blocks.entries()){if(d.t!=="tool_result")continue;let l=pi(d.artifact);if(l.state!=="available")continue;let p=l.artifact;if(p.kind!=="image"&&e!==xt)continue;let u=p.kind==="image"?p.data.images:p.kind==="video"?p.data.videos:p.data.audio.b64===void 0&&p.data.audio.url?[{url:p.data.audio.url}]:[];for(let[v,g]of u.entries()){let b=e===xt?`${p.kind}:${p.kind==="speech"?p.data.audio.mime:""}:${g.url}`:g.url;if(!(g.url.startsWith("data:")||i.has(b))){if(r.length>=128)throw new R("capacity_exceeded");i.add(b),r.push({messageIndex:o,blockIndex:c,imageIndex:v,reference:g.url,kind:p.kind,...p.kind==="speech"?{mime:p.data.audio.mime}:{}})}}}return r}function ma(t,e,n){if(!t||typeof t!="object"||Yn.isProxy(t)||Object.getPrototypeOf(t)!==Object.prototype)throw new R("invalid_input");let r=Object.getOwnPropertyDescriptors(t),i=["mediaType","bytes","sha256"];if(Reflect.ownKeys(r).length!==i.length||i.some(c=>!r[c]||!("value"in r[c])))throw new R("invalid_input");let o=Object.fromEntries(i.map(c=>[c,r[c].value]));if(!["image/png","image/jpeg","image/gif","image/webp",...n===xt?["audio/wav","audio/mpeg","audio/ogg","audio/flac","audio/mp4","video/mp4","video/webm"]:[]].includes(o.mediaType)||!Number.isSafeInteger(o.bytes)||o.bytes<1||typeof o.sha256!="string"||!/^[a-f0-9]{64}$/.test(o.sha256))throw new R("invalid_input");if(o.bytes>e)throw new R("capacity_exceeded");return Object.freeze(o)}function va(t,e,n,r,i=Ot){if(i===xt&&r.media!==!0)throw new R("reconciliation_required");return ha(t,i).map(({kind:o,mime:s,...c})=>{r.signal?.throwIfAborted();let d=r.describe(Object.freeze({...n,...c}));if(Yn.isPromise(d))throw d.catch(()=>{}),new R("invalid_input");if(d===void 0)throw new R("reconciliation_required");let l=ma(d,e,i);if(!l.mediaType.startsWith(o==="speech"?"audio/":`${o}/`)||s!==void 0&&l.mediaType!==s)throw new R("operation_conflict");return Object.freeze({messageIndex:c.messageIndex,blockIndex:c.blockIndex,imageIndex:c.imageIndex,...l})})}function Tr(t,e,n=Ot){if(!Array.isArray(t)||t.length>128)throw new R("invalid_input");return t.map(r=>{if(!r||typeof r!="object"||Yn.isProxy(r))throw new R("invalid_input");let i=Object.getOwnPropertyDescriptors(r),o=["messageIndex","blockIndex","imageIndex","mediaType","bytes","sha256"];if(Reflect.ownKeys(i).length!==o.length||o.some(c=>!i[c]||!("value"in i[c])))throw new R("invalid_input");let s=Object.fromEntries(o.map(c=>[c,i[c].value]));if([s.messageIndex,s.blockIndex,s.imageIndex].some(c=>!Number.isSafeInteger(c)||c<0))throw new R("invalid_input");return Object.freeze({messageIndex:s.messageIndex,blockIndex:s.blockIndex,imageIndex:s.imageIndex,...ma({mediaType:s.mediaType,bytes:s.bytes,sha256:s.sha256},e,n)})})}function ba(t,e,n,r){if(!bt(t)){if(e!==void 0)throw new R("invalid_input");return}let i=Tr(e,r,t),o=[-1,-1,-1];for(let s of i){let c=[s.messageIndex,s.blockIndex,s.imageIndex],d=c.findIndex((l,p)=>l!==o[p]);if(d<0||c[d]<o[d])throw new R("operation_conflict");if(o=c,!n.attachments.some(l=>l.mediaType===s.mediaType&&l.sha256===s.sha256&&l.bytes===s.bytes))throw new R("operation_conflict")}if(n.attachments.reduce((s,c)=>s+c.bytes,0)>r)throw new R("capacity_exceeded")}async function Ia(t){let e=[...Ji(t.body,t.maxBytes)],n=new Map(e.map(c=>[`${c.mediaType}:${$i("sha256").update(c.body).digest("hex")}`,c])),r=e.reduce((c,d)=>c+d.body.byteLength,0),i=t.policy??Ot,o=ha(t.body,i),s=Tr(t.attachments,t.maxBytes,i);if(o.length!==s.length)throw new R("operation_conflict");for(let[c,{kind:d,mime:l,...p}]of o.entries()){let u=s[c];if(u.messageIndex!==p.messageIndex||u.blockIndex!==p.blockIndex||u.imageIndex!==p.imageIndex)throw new R("operation_conflict");if(!u.mediaType.startsWith(d==="speech"?"audio/":`${d}/`)||l!==void 0&&u.mediaType!==l)throw new R("operation_conflict");let v=`${u.mediaType}:${u.sha256}`,g=n.get(v);if(!g&&(e.length>=128||r+u.bytes>t.maxBytes))throw new R("capacity_exceeded");t.assertCurrent();let b=g?.body??t.readArchived(u);if(b===void 0){let I=t.source;if(!I||I.sourceId!==t.context.attachmentSourceId||i===xt&&I.media!==!0)throw new R("reconciliation_required");I.signal?.throwIfAborted(),b=await I.read(Object.freeze({...t.context,...p,mediaType:u.mediaType,bytes:u.bytes,sha256:u.sha256,maxBytes:u.bytes}),I.signal),I.signal?.throwIfAborted()}if(t.assertCurrent(),!(b instanceof Uint8Array)||Yn.isProxy(b)||Yn.isSharedArrayBuffer(b.buffer))throw new R("invalid_input");if(b.byteLength!==u.bytes)throw new R("operation_conflict");let A=Buffer.from(b),S=A.subarray(0,8).equals(Buffer.from(`PNG\r
|
|
5
|
-
|
|
6
|
-
`,"latin1"))?"image/png":A.subarray(0,3).equals(Buffer.from("ÿØÿ","latin1"))?"image/jpeg":/^(GIF87a|GIF89a)/.test(A.toString("latin1",0,6))?"image/gif":A.toString("latin1",0,4)==="RIFF"&&A.toString("latin1",8,12)==="WEBP"?"image/webp":void 0,k=i===xt&&(u.mediaType==="audio/wav"&&A.toString("latin1",0,4)==="RIFF"&&A.toString("latin1",8,12)==="WAVE"||u.mediaType==="audio/mpeg"&&(A.toString("latin1",0,3)==="ID3"||A.length>=2&&A[0]===255&&(A[1]&224)===224)||u.mediaType==="audio/ogg"&&A.toString("latin1",0,4)==="OggS"||u.mediaType==="audio/flac"&&A.toString("latin1",0,4)==="fLaC"||["audio/mp4","video/mp4"].includes(u.mediaType)&&A.length>=12&&A.toString("latin1",4,8)==="ftyp"||u.mediaType==="video/webm"&&A.subarray(0,4).equals(Buffer.from([26,69,223,163])));if(A.byteLength!==u.bytes||$i("sha256").update(A).digest("hex")!==u.sha256||S!==u.mediaType&&!k)throw new R("operation_conflict");if(!g){let I={mediaType:u.mediaType,body:A};n.set(v,I),r+=A.byteLength,e.push(I)}}return e}function Ji(t,e){if(!Number.isSafeInteger(e)||e<1||e>33554432||t.byteLength>e)throw new R("capacity_exceeded");let n=JSON.parse(Buffer.from(t).toString("utf8"));if(n.format!==cn||!Array.isArray(n.messages))throw new R("invalid_input");let r=[],i=new Set,o=0,s=(c,d)=>{if(d.length===0||d.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(d)||!/^(?:image|audio)\/[A-Za-z0-9.+-]+$/i.test(c))return;let l=Buffer.from(d,"base64");if(l.toString("base64")!==d)return;let p=`${c}:${$i("sha256").update(l).digest("hex")}`;if(!i.has(p)){if(r.length>=128||o+l.byteLength>e)throw new R("capacity_exceeded");i.add(p),o+=l.byteLength,r.push({mediaType:c,body:l})}};for(let c of n.messages)for(let d of c.blocks){if(d.t==="image"&&s(d.mime,d.data),d.t!=="tool_result")continue;for(let u of d.content)u.t==="image"&&s(u.mime,u.data);let l=pi(d.artifact);if(l.state!=="available")continue;let p=l.artifact;if(p.kind==="speech"&&p.data.audio.b64!==void 0)s(p.data.audio.mime,p.data.audio.b64);else if(p.kind==="image")for(let u of p.data.images){let v=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.+)$/.exec(u.url);v&&s(v[1],v[2])}}return r}function Vi(t){let{receipt:e,record:n,bindingId:r,operationKey:i,sourceId:o,sourceGeneration:s,expectedHead:c}=t,d=()=>{throw new R("inventory_unknown")},l=z(_([r,i]));(n.recordId!==`jr-r-${l}`||n.payload.artifactId!==`jr-p-${l}`||n.attachments.length>128||e.state!=="committed"||e.bindingId!==r||e.operationKey!==i||e.entries.length!==n.attachments.length+1||e.intentDigest!==z(_({format:"sdk2-record-journal-v1",sourceId:o,sourceGeneration:s,expectedHead:c,recordDigest:n.recordDigest})))&&d();let p=0;for(let[u,v]of[n.payload,...n.attachments].entries()){let g=e.entries[u];if(u===0)try{Ms(g.metadata,n,o,s)}catch{d()}let b=u===0?g.metadata:_({format:"sdk2-record-journal-v1",kind:"attachment",sourceId:o,sourceGeneration:s,recordId:n.recordId,artifact:v});(v.sourceId!==o||u>0&&v.artifactId!==`jr-a-${z(_([r,i,u-1]))}`||g.entryId!==v.artifactId||g.basket!=="original"||g.bodyBytes!==v.bytes||g.bodySha256!==v.sha256||g.metadata!==b||g.metadataBytes!==Buffer.byteLength(b)||g.logicalBytes!==g.metadataBytes+v.bytes+64)&&d(),p+=g.logicalBytes}return p>67108864&&d(),{payload:e.entries[0],logicalBytes:p}}var Aa="sdk2-rewrite-projection-v1",wa="sdk2-rewrite-projection-v2",yn=1048576,Sa=t=>`rewrite-projection-${z(_([t.slot,t.ownerEpoch,t.rewriteId]))}`;function fn(){throw new R("reconciliation_required")}function gn(t,e){let n=P(t,["policy","operationKey","expectedHead","bodySha256","bytes"]),r=P(n.expectedHead,["sequence","recordDigest"]);return(n.policy!==Aa&&n.policy!==wa||n.operationKey!==Sa(e)||typeof r.sequence!="string"||!/^[1-9][0-9]{0,18}$/.test(r.sequence)||BigInt(r.sequence)>=9223372036854775807n||typeof r.recordDigest!="string"||!/^[a-f0-9]{64}$/.test(r.recordDigest)||typeof n.bodySha256!="string"||!/^[a-f0-9]{64}$/.test(n.bodySha256)||typeof n.bytes!="number"||!Number.isSafeInteger(n.bytes)||n.bytes<1||n.bytes>yn)&&fn(),Object.freeze({policy:n.policy,operationKey:n.operationKey,expectedHead:Object.freeze({sequence:r.sequence,recordDigest:r.recordDigest}),bodySha256:n.bodySha256,bytes:n.bytes})}function bd(t,e){Lt(Buffer.from(JSON.stringify(t)))!==e.sourceSnapshotDigest&&fn();let n=JSON.parse(Buffer.from(fs(t,{maxBytes:yn})).toString("utf8")),r=n.messages.filter(s=>ys(s));(r.length!==1||r[0].blocks.length!==1||r[0].blocks[0].t!=="text")&&fn();let i=n.messages.filter(s=>s!==r[0]);i.length&&(i=JSON.parse(Buffer.from(br({messages:i,turnState:"completed",maxBytes:yn}).body).toString("utf8")).messages);let o=Buffer.from(JSON.stringify({format:cn,messages:[r[0],...i]}));return o.byteLength>yn&&fn(),o}function Ra(t){return Cr({spool:t.spool,bindingId:t.recordBindingId,sourceId:t.sourceId,sourceGeneration:t.sourceGeneration,generations:t.target.generations,...t.publicationClock===void 0?{}:{publicationClock:t.publicationClock}})}function Qn(t){t.assertCurrent();let e=Ra(t),n=t.fact===void 0?void 0:gn(t.fact,t),r=n?.expectedHead??e.head();if(r===null)return;let i=n?.policy??wa,o=bd(t.messages,t.target),s=i===Aa?o:vr(o,yn),c=gn({policy:i,operationKey:Sa(t),expectedHead:r,bodySha256:yr(s),bytes:s.byteLength},t);return n!==void 0&&_(n)!==_(c)&&fn(),t.assertCurrent(),Object.freeze({fact:c,publish(){t.assertCurrent(),e.append({operationKey:c.operationKey,expectedHead:c.expectedHead,recordDraft:{target:t.target,turnId:t.rewriteId,recordKind:"projection",turnState:"completed",projection:{coverage:{fromSequence:"1",throughSequence:c.expectedHead.sequence,headDigest:c.expectedHead.recordDigest},assemblerVersion:c.policy,sourceHeadDigest:c.expectedHead.recordDigest}},payload:{body:s,mediaType:"application/json"},attachments:[]}),t.assertCurrent(),Xi(t,c)}})}function Xi(t,e){let n=gn(e,t);t.assertCurrent();let r=Ra(t),i=r.list({generations:t.target.generations,afterSequence:n.expectedHead.sequence,limit:1,maxBytes:yn}).records[0],o=z(_([t.recordBindingId,n.operationKey]));(!i||i.recordId!==`jr-r-${o}`||i.recordKind!=="projection"||i.turnState!=="completed"||i.turnId!==t.rewriteId||_(i.target)!==_(t.target)||i.predecessorDigest!==n.expectedHead.recordDigest||i.payload.sha256!==n.bodySha256||i.payload.bytes!==n.bytes||i.projection?.assemblerVersion!==n.policy||i.projection.coverage.fromSequence!=="1"||i.projection.coverage.throughSequence!==n.expectedHead.sequence||i.projection.coverage.headDigest!==n.expectedHead.recordDigest||i.projection.sourceHeadDigest!==n.expectedHead.recordDigest)&&fn();let s=r.readArtifactBody({generations:t.target.generations,artifactId:i.payload.artifactId,maxBytes:yn}).body;(s.byteLength!==n.bytes||yr(s)!==n.bodySha256)&&fn(),t.assertCurrent()}var _a=["intent","history","facts"],Zi=["intent","capture","publication-intent","publication-result","store-intent","compensation-intent","compensation-result","facts"],no=16384,Ad=z(""),ro="sdk2-governance-material-v1",be=(t,e)=>_(t)===_(e);function Y(){throw new R("reconciliation_required")}function $t(t,e=128){(typeof t!="string"||!t||Buffer.byteLength(t)>e||t.includes("\0")||Buffer.from(t).toString()!==t)&&Y()}function Ba(t){(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/u.test(t))&&Y()}function yt(t){(!Number.isSafeInteger(t)||t<0||Object.is(t,-0))&&Y()}function At(t){(typeof t!="string"||!/^[a-f0-9]{64}$/.test(t))&&Y()}function It(t){return(typeof t!="string"||!/^(0|[1-9][0-9]{0,18})$/.test(t)||BigInt(t)>9223372036854775807n)&&Y(),BigInt(t)}function ye(t,e,n=[]){return P(t,e,n)}function Qi(t,e,n=0){return(Id.isProxy(t)||!Array.isArray(t)||t.length<n||t.length>e||Object.getPrototypeOf(t)!==Array.prototype||Reflect.ownKeys(t).length!==t.length+1)&&Y(),Array.from({length:t.length},(r,i)=>{let o=Object.getOwnPropertyDescriptor(t,String(i));return(!o||!Object.hasOwn(o,"value")||!o.enumerable)&&Y(),o.value})}function ct(t,e=!0){(typeof t!="string"||Buffer.byteLength(t)>262144||Buffer.from(t).toString()!==t)&&Y();let n=Ee(Buffer.from(t));return e&&_(n)!==t&&Y(),(n===null||typeof n!="object"||Array.isArray(n))&&Y(),n}function Jt(t){if(t&&typeof t=="object"){for(let e of Object.values(t))Jt(e);Object.freeze(t)}return t}function Dr(t){ye(t,["snapshot","work"]);let{snapshot:e,work:n}=t;ye(e,["slot","current","headEventDigest","originalCreate","plan","createEventDigest","ready","retirement","operations","writeBarrier"],["work"]),Ge(e.slot),At(e.headEventDigest),At(e.createEventDigest),(!e.current||!e.plan||!e.work||e.retirement!==null||e.current.state==="closed")&&Y();let r=as(e.current),i=Ss(e.plan);(!["active","closing","backpressured"].includes(r.state)||!be(i.slot,e.slot)||r.storageBindingId!==e.slot.storageBindingId||r.slotId!==e.slot.slotId||i.sessionId!==r.registration.sessionId||i.scope.applicationScopeId!==r.registration.scope.applicationScopeId||i.scope.endUserId!==r.registration.scope.endUserId||i.bindingId!==r.registration.bindingId||i.sourceId!==r.registration.sourceId||i.sourceGeneration!==r.registration.sourceGeneration||!r.registration.relatedBindingIds.includes(i.captureBindingId)||!r.registration.relatedBindingIds.includes(i.recordBindingId)||!["clear","unknown"].includes(e.writeBarrier))&&Y(),ye(e.work,["active","lastCompleted"]),be(e.work.active??e.work.lastCompleted,n)||Y(),ye(n,["kind","ownerEpoch","workId","turnId","captureRunKey","admission","admittedTarget","admittedEventDigest","finish"]),$t(n.ownerEpoch),$t(n.workId),At(n.admittedEventDigest);let o=v=>{let g=tt({scope:r.registration.scope,target:v,nowMs:0}).target;return g.sessionId!==i.sessionId&&Y(),g};o(n.admittedTarget);let s=ze(n.admission);if(n.kind==="run"?($t(n.turnId),$t(n.captureRunKey,256),(s.kind!=="admit-run"||s.ownerEpoch!==n.ownerEpoch||s.runKey!==n.workId||s.turnId!==n.turnId||n.workId!==`run-${z(n.captureRunKey)}`||s.transitionId!==`admit-${z(n.captureRunKey)}`)&&Y()):n.kind==="rewrite"?(n.turnId!==null||n.captureRunKey!==null||s.kind!=="prepare-rewrite"||s.candidateTarget!==null||s.ownerEpoch!==n.ownerEpoch||s.rewriteId!==n.workId||s.transitionId!==`rewrite-prepare-${z(_([n.ownerEpoch,n.workId]))}`)&&Y():Y(),n.finish===null){let v=r.fence;(!v||v.kind!==n.kind||v.id!==n.workId||v.ownerEpoch!==n.ownerEpoch||v.turnId!==n.turnId||!be(v.target,n.admittedTarget))&&Y()}else ye(n.finish,["mutation","eventDigest","resultingTarget"]),At(n.finish.eventDigest),o(n.finish.resultingTarget),(r.fence!==null||e.work.active!==null||!be(r.target,n.finish.resultingTarget))&&Y();let c=new Map,d=0,l=0;for(let v of Qi(e.operations,16)){let g=ye(v,["key","saved"]),b=ye(g.key,["bindingId","operationKey"]);$t(b.bindingId,256),$t(b.operationKey,256),r.registration.relatedBindingIds.includes(b.bindingId)||Y();let A=_(b);if(c.has(A)&&Y(),g.saved!==null){let S=ye(g.saved,["state","reservation"],["receipt"]);if(S.state==="reserved")ye(S,["state","reservation"]);else if(S.state==="committed"){ye(S,["state","reservation","receipt"]);let k=ye(S.receipt,["state","bindingId","operationKey","intentDigest","commitDigest","entries"]);for(let I of Qi(k.entries,129)){let m=ye(I,["entryId","basket","metadata","metadataBytes","bodyBytes","bodySha256","logicalBytes"]);(typeof m.metadata!="string"||Buffer.from(m.metadata).toString()!==m.metadata)&&Y(),l+=Buffer.byteLength(m.metadata),d++,(d>Ks||l>Ls)&&Y()}}else Y()}c.set(A,g.saved)}let p=v=>({bindingId:e.slot.storageBindingId,operationKey:`host-${n.kind}-${v}-${z(_([e.slot,n.ownerEpoch,n.kind==="run"?n.captureRunKey:n.workId]))}`}),u=n.kind==="run"?[{bindingId:i.recordBindingId,operationKey:`recording:${z(n.captureRunKey)}`},{bindingId:i.captureBindingId,operationKey:`${n.captureRunKey}:prepared-turn`},{bindingId:i.captureBindingId,operationKey:`${n.captureRunKey}:materials-seal`}]:[];return{s:e,w:n,state:r,plan:i,target:o,operations:c,hostKey:p,recordingKeys:u}}function tr(t){let e=Dr(t);return Jt([...(e.w.kind==="run"?_a:Zi).map(e.hostKey),...e.recordingKeys])}function xa(t,e){let n=Dr(t),r=ye(e,["version","initial","admission","captureRunKey","recording"]);(n.w.kind!=="run"||n.w.finish!==null||n.s.writeBarrier!=="clear"||n.state.state!=="active"||r.version!==1||r.captureRunKey!==n.w.captureRunKey||!be(r.admission,n.w.admission))&&Y();let i=ye(Pt(n,"intent"),["initial","store"]),o=to(n,i.initial);(i.store!=="host-owned-original-store"||o.confirmedCommitId===null||!be(o,r.initial)||!be(o.target,n.w.admittedTarget))&&Y();for(let s of["history","facts"]){let c=n.hostKey(s),d=n.operations.get(_(c)),l={...c,intentDigest:z(c.operationKey),originalMax:{bytes:no,records:1},terminalReserve:{bytes:1,records:1}};(!d||d.state!=="reserved"||!be(d.reservation,l))&&Y()}wt(n,n.recordingKeys[0]);for(let s of n.recordingKeys.slice(1))n.operations.get(_(s))?.state==="committed"&&Y();return Jt(structuredClone(r))}function wt(t,e,n,r=!1){let i=t.operations.get(_(e));(!i||i.state!=="committed")&&Y(),ye(i,["state","reservation","receipt"]);let o=gr(i.reservation);(o.bindingId!==e.bindingId||o.operationKey!==e.operationKey||n&&!be(o,n))&&Y();let s=i.receipt;ye(s,["state","bindingId","operationKey","intentDigest","commitDigest","entries"]),(s.state!=="committed"||s.bindingId!==e.bindingId||s.operationKey!==e.operationKey||s.intentDigest!==o.intentDigest)&&Y(),At(s.commitDigest);let c=Qi(s.entries,r?129:1,1).map(d=>{let l=ye(d,["entryId","basket","metadata","metadataBytes","bodyBytes","bodySha256","logicalBytes"]);return $t(l.entryId,256),yt(l.metadataBytes),yt(l.bodyBytes),yt(l.logicalBytes),At(l.bodySha256),(typeof l.metadata!="string"||Buffer.from(l.metadata).toString()!==l.metadata||l.metadataBytes!==Buffer.byteLength(l.metadata)||l.metadataBytes>262144||l.bodyBytes>33554432||l.logicalBytes!==l.metadataBytes+l.bodyBytes+64||l.basket!=="original"||l.logicalBytes>o.originalMax.bytes||o.terminalReserve.bytes!==1||o.terminalReserve.records!==1)&&Y(),l});return(o.originalMax.records!==c.length||c.reduce((d,l)=>d+l.logicalBytes,0)>o.originalMax.bytes||new Set(c.map(d=>d.entryId)).size!==c.length)&&Y(),s.commitDigest!==z(JSON.stringify(c.map(d=>[d.entryId,d.basket,d.metadata,d.bodyBytes,d.bodySha256])))&&Y(),{saved:s,reservation:o,entry:c[0],entries:c}}function eo(t){(t.bodyBytes!==0||t.bodySha256!==Ad)&&Y()}function Pt(t,e){let n=t.hostKey(e),r=wt(t,n,{...n,intentDigest:z(n.operationKey),originalMax:{bytes:no,records:1},terminalReserve:{bytes:1,records:1}});eo(r.entry),r.entry.entryId!==n.operationKey&&Y();let i=ct(r.entry.metadata);return ye(i,t.w.kind==="run"?["format","slot","ownerEpoch","turnId","captureRunKey","controlRunId","kind","value"]:["format","slot","ownerEpoch","rewriteId","kind","value"]),(i.format!==`sdk2-host-${t.w.kind}-v1`||!be(i.slot,t.s.slot)||i.ownerEpoch!==t.w.ownerEpoch||i.kind!==e||(t.w.kind==="run"?i.turnId!==t.w.turnId||i.captureRunKey!==t.w.captureRunKey||i.controlRunId!==t.w.workId:i.rewriteId!==t.w.workId))&&Y(),t.w.kind==="run"&&e==="facts"?ct(i.value):wd(i.value)}function wd(t){return _(t),(!t||typeof t!="object"||Array.isArray(t))&&Y(),t}function to(t,e){let n=ye(e,["target","localHistoryGeneration","confirmedCommitId"]);return yt(n.localHistoryGeneration),n.confirmedCommitId!==null&&Ba(n.confirmedCommitId),{target:t.target(n.target),localHistoryGeneration:n.localHistoryGeneration,confirmedCommitId:n.confirmedCommitId}}function jr(t,e){let n=ye(e,["target","localHistoryGeneration","commitId"]);return Ba(n.commitId),yt(n.localHistoryGeneration),{target:t.target(n.target),localHistoryGeneration:n.localHistoryGeneration,confirmedCommitId:n.commitId}}function Yi(t,e){(e.localHistoryGeneration<t.localHistoryGeneration||!be(e.target,t.target)&&e.localHistoryGeneration===t.localHistoryGeneration)&&Y()}function ka(t){let e=ye(t,["status","failureCount","omittedFailures"]);yt(e.failureCount),yt(e.omittedFailures),(!["completed","failed"].includes(e.status)||e.omittedFailures>e.failureCount)&&Y()}function Ca(t,e,n,r){let i=ze(e);i.kind!=="finish-run"&&i.kind!=="finish-rewrite"&&Y(),i.kind!==(t.w.kind==="run"?"finish-run":"finish-rewrite")&&Y();let o=i,s=d=>t.w.kind==="run"?`finish-${z(_([t.w.captureRunKey,d]))}`:`rewrite-finish-${z(_([t.w.ownerEpoch,t.w.workId,d]))}`,c=d=>{(d.ownerEpoch!==t.w.ownerEpoch||(d.kind==="finish-run"?d.runKey!==t.w.workId||!be(d.expectedTarget,n.target):d.rewriteId!==t.w.workId||d.outcome!==r))&&Y()};if(c(o),(o.transitionId!==s(0)||It(o.expectedRevision)<=It(t.w.admission.expectedRevision))&&Y(),t.w.finish){let d=ze(t.w.finish.mutation);d.kind!=="finish-run"&&d.kind!=="finish-rewrite"&&Y(),d.kind!==o.kind&&Y(),c(d);let l=Array.from({length:9},(p,u)=>u).find(p=>d.transitionId===s(p));(l===void 0||(l===0?!be(d,o):It(d.expectedRevision)<=It(o.expectedRevision))||It(t.state.revision)<=It(d.expectedRevision)||!be(t.w.finish.resultingTarget,n.target))&&Y()}else It(o.expectedRevision)>It(t.state.revision)&&Y(),t.w.kind==="rewrite"&&r==="published"&&!be(t.state.fence?.candidateTarget,n.target)&&Y();return o}function Bn(t,e){be(t,{unused:!0,outcome:e})||Y()}function er(t,e){return e.filter(n=>!t.operations.has(_(n)))}function Et(t){let e=Dr(t);er(e,(e.w.kind==="run"?_a:Zi).map(e.hostKey)).length&&Y();let n=Pt(e,"intent");ye(n,e.w.kind==="run"?["initial","store"]:["initial","reason"]),(e.w.kind==="run"?n.store!=="host-owned-original-store":!["compaction","restore","model-transition"].includes(n.reason))&&Y();let r=to(e,n.initial);be(r.target,e.w.admittedTarget)||Y();let i=Pt(e,"facts"),o,s,c=[];if(e.w.kind==="run"){ye(i,["commit","query","capture","recoveryFinish"]),ka(i.query);let d=Pt(e,"history");o=jr(e,d),(i.capture!=="confirmed"||!be(d,i.commit)||!be(o.target.generations,r.target.generations))&&Y(),Yi(r,o),s=Ca(e,i.recoveryFinish,o,null),c=kd(e)}else{ye(i,["outcome","history","capture","resources","recoveryFinish"],["projection"]),ka(i.resources),["published","unchanged","compensated"].includes(i.outcome)||Y(),o=to(e,i.history),o.confirmedCommitId===null&&Y();let d=Object.fromEntries(Zi.filter(l=>l!=="intent"&&l!=="facts").map(l=>[l,Pt(e,l)]));if(i.outcome==="published"){let l=jr(e,d["store-intent"]);Yi(r,l);let p=ye(d["publication-intent"],["candidate"]),u=ye(d["publication-result"],["candidate","outcome"]),v=ye(p.candidate,["target","localHistoryGeneration"]);yt(v.localHistoryGeneration),e.target(v.target),(!be(l,o)||u.outcome!=="published"||!be(p.candidate,u.candidate)||!be(p.candidate,{target:o.target,localHistoryGeneration:o.localHistoryGeneration})||i.capture!=="confirmed")&&Y(),Bn(d["compensation-intent"],"published"),Bn(d["compensation-result"],"published")}else if((!be(o.target,r.target)||o.localHistoryGeneration!==r.localHistoryGeneration)&&Y(),Bn(d["publication-intent"],i.outcome),Bn(d["publication-result"],i.outcome),i.outcome==="unchanged"){be(o,r)||Y();for(let l of["store-intent","compensation-intent","compensation-result"])Bn(d[l],"unchanged")}else{let l=jr(e,d["store-intent"]);Yi(r,l);let p=ye(d["compensation-intent"],["original","compensation"]),u=ye(d["compensation-result"],["compensation","outcome"]);(!be(p.original,d["store-intent"])||!be(p.compensation,u.compensation)||u.outcome!=="confirmed"||!be(jr(e,p.compensation),o)||o.confirmedCommitId===l.confirmedCommitId||o.confirmedCommitId===r.confirmedCommitId||i.capture!=="confirmed")&&Y()}if(s=Ca(e,i.recoveryFinish,o,i.outcome==="published"?"published":"unchanged"),i.capture==="confirmed"?c=Rd(e,d.capture):((i.capture!=="not-started"||i.outcome!=="unchanged")&&Y(),Bn(d.capture,"unchanged")),i.projection!==void 0){(n.reason!=="compaction"||i.outcome!=="published")&&Y();let l=gn(i.projection,{slot:e.s.slot,ownerEpoch:e.w.ownerEpoch,rewriteId:e.w.workId});e.w.finish!==null&&(c=[...c,...Sd(e,l,o.target)])}}return c.length?Jt({kind:"needs-operations",neededOperationKeys:c}):(o.confirmedCommitId===null&&Y(),Jt({kind:"verified",history:{commitId:o.confirmedCommitId,observation:{sessionId:o.target.sessionId,sourceSnapshotDigest:o.target.sourceSnapshotDigest,localHistoryGeneration:o.localHistoryGeneration}},target:o.target,work:structuredClone(e.w),recoveryFinish:s,controlCompleted:e.w.finish!==null,captureMetadataComplete:!0,headEventDigest:e.s.headEventDigest,writeBarrier:e.s.writeBarrier}))}function Sd(t,e,n){let r={bindingId:t.plan.recordBindingId,operationKey:e.operationKey};if(er(t,[r]).length)return[r];let i=wt(t,r,void 0,!0),o=ct(i.entry.metadata);ye(o,["format","kind","sourceId","sourceGeneration","record",...o.format==="sdk2-record-journal-v2"?["publishedAtMs"]:[]]);let s=sn(o.record);(!["sdk2-record-journal-v1","sdk2-record-journal-v2"].includes(o.format)||o.kind!=="record"||o.sourceId!==t.plan.sourceId||o.sourceGeneration!==t.plan.sourceGeneration||s.recordKind!=="projection"||s.turnState!=="completed"||s.turnId!==t.w.workId||!be(s.target,n)||s.attachments.length!==0||s.payload.sha256!==e.bodySha256||s.payload.bytes!==e.bytes||s.projection?.assemblerVersion!==e.policy||s.projection.coverage.fromSequence!=="1"||s.projection.coverage.throughSequence!==e.expectedHead.sequence||s.projection.coverage.headDigest!==e.expectedHead.recordDigest||s.projection.sourceHeadDigest!==e.expectedHead.recordDigest)&&Y();let c=Vi({receipt:i.saved,record:s,bindingId:r.bindingId,operationKey:r.operationKey,sourceId:t.plan.sourceId,sourceGeneration:t.plan.sourceGeneration,expectedHead:e.expectedHead});return i.reservation.originalMax.bytes!==c.logicalBytes&&Y(),[]}function Rd(t,e){let n=ye(e,["operationKey","bodySha256","bytes"]);$t(n.operationKey,256),At(n.bodySha256),yt(n.bytes);let r={bindingId:t.plan.captureBindingId,operationKey:n.operationKey};if(er(t,[r]).length)return[r];let i=wt(t,r),o=ct(i.entry.metadata,!1);return ye(o,["format","projectionPolicyId","kind","complete","bodySha256"]),(o.format!=="sdk2-session-capture-v1"||o.projectionPolicyId!==ro||o.kind!=="governance"||o.complete!==!0||o.bodySha256!==n.bodySha256||i.entry.bodySha256!==n.bodySha256||i.entry.bodyBytes!==n.bytes||i.reservation.intentDigest!==z(i.entry.metadata)||i.reservation.originalMax.bytes!==i.entry.logicalBytes||i.entry.entryId!==`material-${z(JSON.stringify([r.bindingId,r.operationKey]))}`)&&Y(),[]}function kd(t){let e=er(t,t.recordingKeys);if(e.length)return e;let[n,r,i]=t.recordingKeys,o=wt(t,n),s=wt(t,r),c=wt(t,i);eo(o.entry),eo(c.entry);let d=ct(o.entry.metadata),l=ct(s.entry.metadata),p=ct(c.entry.metadata);if(ye(d,["format","captureBindingId","recordBindingId","runKey","turnId","target","expectedHead","projectionPolicyId","sourceId","sourceGeneration","maxTurnBytes","ownerEpoch"],["attachmentPolicy","attachmentSourceId","textProjectionPolicy"]),d.textProjectionPolicy!==void 0&&d.textProjectionPolicy!==mt&&Y(),Zn(d.attachmentPolicy,d.attachmentSourceId),yt(d.maxTurnBytes),(d.format!=="sdk2-recording-lease-v1"||d.captureBindingId!==t.plan.captureBindingId||d.recordBindingId!==t.plan.recordBindingId||d.runKey!==t.w.captureRunKey||d.turnId!==t.w.turnId||d.ownerEpoch!==t.w.ownerEpoch||!be(d.target,t.w.admittedTarget)||d.projectionPolicyId!==ro||d.sourceId!==t.plan.sourceId||d.sourceGeneration!==t.plan.sourceGeneration||d.maxTurnBytes<1||d.maxTurnBytes>33554432||o.reservation.intentDigest!==z(o.entry.metadata)||o.reservation.originalMax.bytes!==o.entry.logicalBytes||o.entry.entryId!==`recording-${z(n.operationKey)}`)&&Y(),d.expectedHead!==null){let I=ye(d.expectedHead,["sequence","recordDigest"]);It(I.sequence)<1n&&Y(),At(I.recordDigest)}for(let[I,m,w]of[[s,r,"prepared"],[c,i,"materials-seal"]])(I.reservation.intentDigest!==z(_([`sdk2-recording-${w}-v1`,z(o.entry.metadata)]))||I.reservation.originalMax.bytes!==(w==="prepared"?d.maxTurnBytes:0)+(d.attachmentPolicy===Ot?qr:no)||I.entry.entryId!==`recording-${z(_([t.plan.captureBindingId,m.operationKey]))}`)&&Y();ye(l,["format","leaseDigest","operationKey","runKey","turnId","outcome","turnState","bodySha256","messageCount","toolCallCount","pendingToolCalls"],["trustedAttachments"]);for(let I of["messageCount","toolCallCount","pendingToolCalls"])yt(l[I]);(l.format!=="sdk2-recording-prepared-v1"||l.leaseDigest!==o.reservation.intentDigest||l.operationKey!==`${t.w.captureRunKey}:turn`||l.runKey!==t.w.captureRunKey||l.turnId!==t.w.turnId||l.bodySha256!==s.entry.bodySha256||s.entry.bodyBytes>d.maxTurnBytes||!["completed","aborted","failed","interrupted"].includes(l.outcome)||!["completed","cancelled","incomplete"].includes(l.turnState)||l.outcome==="aborted"!=(l.turnState==="cancelled")||l.turnState==="completed"&&l.outcome!=="completed")&&Y(),ye(p,["format","leaseDigest","preparedCommitDigest","operationKey","outcome","recordDigest","materialsComplete","materialsDigest"]),At(p.recordDigest),At(p.materialsDigest),(p.format!=="sdk2-recording-materials-seal-v1"||p.leaseDigest!==o.reservation.intentDigest||p.preparedCommitDigest!==s.saved.commitDigest||p.operationKey!==l.operationKey||p.outcome!==l.outcome||p.materialsComplete!==!0)&&Y();let u={bindingId:t.plan.recordBindingId,operationKey:l.operationKey};if(er(t,[u]).length)return[u];let v=wt(t,u,void 0,!0),g=ct(v.entry.metadata);ye(g,["format","kind","sourceId","sourceGeneration","record",...g.format==="sdk2-record-journal-v2"?["publishedAtMs"]:[]]);let b=sn(g.record),A=z(_([u.bindingId,u.operationKey]));ba(d.attachmentPolicy,l.trustedAttachments,b,d.maxTurnBytes);let S=d.expectedHead;(!["sdk2-record-journal-v1","sdk2-record-journal-v2"].includes(g.format)||g.kind!=="record"||g.sourceId!==t.plan.sourceId||g.sourceGeneration!==t.plan.sourceGeneration||b.recordDigest!==p.recordDigest||b.recordId!==`jr-r-${A}`||b.recordKind!=="turn"||b.turnState!==l.turnState||b.turnId!==t.w.turnId||!be(b.target,t.w.admittedTarget)||d.attachmentPolicy===void 0&&b.attachments.length!==0||b.sequence!==String(S?It(S.sequence)+1n:1n)||b.predecessorDigest!==(S?.recordDigest??"0".repeat(64))||b.payload.artifactId!==`jr-p-${A}`||v.entry.entryId!==b.payload.artifactId||b.payload.sourceId!==t.plan.sourceId||b.payload.mediaType!=="application/json"||b.payload.sha256!==s.entry.bodySha256||b.payload.bytes!==s.entry.bodyBytes||v.entry.bodySha256!==s.entry.bodySha256||v.entry.bodyBytes!==s.entry.bodyBytes||v.reservation.intentDigest!==z(_({format:"sdk2-record-journal-v1",sourceId:t.plan.sourceId,sourceGeneration:t.plan.sourceGeneration,expectedHead:d.expectedHead,recordDigest:b.recordDigest})))&&Y();let k=Vi({receipt:v.saved,record:b,bindingId:u.bindingId,operationKey:u.operationKey,sourceId:t.plan.sourceId,sourceGeneration:t.plan.sourceGeneration,expectedHead:d.expectedHead});return v.reservation.originalMax.bytes!==k.logicalBytes&&Y(),[]}function Oa(t){Et(t).kind!=="verified"&&Y();let n=Dr(t),r=(S,k=!1)=>{let I=wt(n,S,void 0,k);return{key:S,reservation:I.reservation,commitDigest:I.saved.commitDigest,entry:I.entry}};if(n.w.kind==="rewrite")return Pt(n,"facts").capture==="not-started"?Jt({kind:"rewrite",capture:"not-started"}):Jt(structuredClone({kind:"rewrite",capture:"confirmed",material:r({bindingId:n.plan.captureBindingId,operationKey:Pt(n,"capture").operationKey}),...Pt(n,"facts").projection===void 0?{}:{projection:gn(Pt(n,"facts").projection,{slot:n.s.slot,ownerEpoch:n.w.ownerEpoch,rewriteId:n.w.workId})}}));let[i,o,s]=n.recordingKeys,c=r(i),d=r(o),l=r(s),p=ct(c.entry.metadata),u=ct(d.entry.metadata),v=ct(l.entry.metadata),g={bindingId:n.plan.recordBindingId,operationKey:u.operationKey},b=r(g,!0),A={kind:"run",recording:{captureBindingId:n.plan.captureBindingId,recordBindingId:n.plan.recordBindingId,sourceId:n.plan.sourceId,sourceGeneration:n.plan.sourceGeneration,generations:n.w.admittedTarget.generations,projectionPolicyId:ro,maxTurnBytes:p.maxTurnBytes},recovery:{runKey:n.w.captureRunKey,turnId:n.w.turnId,originalOwnerEpoch:n.w.ownerEpoch,target:n.w.admittedTarget,expectedHead:p.expectedHead,sourceId:n.plan.sourceId,sourceGeneration:n.plan.sourceGeneration},outcome:u.outcome,record:sn(ct(b.entry.metadata).record),lease:c,prepared:d,seal:l,journal:b,journalAttachments:wt(n,g,void 0,!0).entries.slice(1),materialsDigest:v.materialsDigest};return Jt(structuredClone(A))}import{createHash as Od}from"node:crypto";import{types as io}from"node:util";import{createHash as Bd}from"node:crypto";import{types as xn}from"node:util";import{createHash as Cd}from"node:crypto";var hn=t=>Cd("sha256").update(t).digest("hex"),Pa=new WeakMap;function Ea(t,e){let n=Pa.get(t);if(!n)throw new R("identity_mismatch");n(e)}function qa(t){let{spool:e,bindingId:n,projectionPolicyId:r}=t;for(let A of[n,r])if(typeof A!="string"||A.length===0||Buffer.byteLength(A)>256||A.includes("\0"))throw new TypeError("Session capture: invalid identity");let i=A=>hn(JSON.stringify(["sdk2-run-capture-v1",n,r,A])),o=A=>`${A}:fence`,s=A=>({bindingId:n,operationKey:A,intentDigest:i(A),originalMax:{bytes:1,records:1},terminalReserve:{bytes:2048,records:1}}),c=A=>({bindingId:n,operationKey:o(A),intentDigest:hn(JSON.stringify(["sdk2-run-fence-v1",n,r,A])),originalMax:{bytes:1,records:1},terminalReserve:{bytes:1,records:1}}),d=(...A)=>{if(e.snapshot().inventory.reservations.some(S=>S.bindingId===n&&!A.includes(S.operationKey)))throw new R("reconciliation_required")},l=(A,S)=>{if(A.bindingId!==S.bindingId||A.operationKey!==S.operationKey||A.intentDigest!==S.intentDigest||A.originalMax.bytes!==S.originalMax.bytes||A.originalMax.records!==S.originalMax.records||A.terminalReserve.bytes!==S.terminalReserve.bytes||A.terminalReserve.records!==S.terminalReserve.records)throw new R("operation_conflict")},p=A=>{let S=e.status(A);if(!S)throw new R("operation_conflict");return l(S.reservation,A),S},u=A=>{let S=e.status(A);S&&l(S.reservation,A);try{l(e.reserve(A),A)}catch(k){if(!(k instanceof R)||k.code!=="commit_unknown")throw k;let I=e.status(A);if(!I)throw k;l(I.reservation,A)}},v=(A,S,k,I)=>{if(A.state!=="committed"||A.bindingId!==n||A.operationKey!==S||A.intentDigest!==k||A.entries.length!==I.length)throw new R("operation_conflict");for(let[m,w]of I.entries()){let C=A.entries[m];if(!C||C.entryId!==w.entryId||C.basket!==w.basket||C.metadata!==w.metadata||C.bodyBytes!==w.body.byteLength||C.bodySha256!==hn(w.body))throw new R("operation_conflict")}},g=(A,S,k)=>{try{v(e.commit({bindingId:n,operationKey:A,intentDigest:S,entries:k}),A,S,k)}catch(I){if(!(I instanceof R)||I.code!=="commit_unknown")throw I;let m=e.status({bindingId:n,operationKey:A});if(m?.state!=="committed")throw I;v(m.receipt,A,S,k)}},b={assertReady(){d()},async prepareRun({runKey:A}){e.status({bindingId:n,operationKey:A}),e.status({bindingId:n,operationKey:o(A)}),d(A,o(A)),u(c(A)),u(s(A))},async write(A){let{operationKey:S,runKey:k,kind:I,complete:m,body:w}=A;if(k===void 0)d(S);else if(p(s(k)),p(c(k)).state!=="reserved")throw new R("operation_conflict");let C=JSON.stringify({format:"sdk2-session-capture-v1",projectionPolicyId:r,kind:I,complete:m,...k===void 0?{}:{runKey:k},bodySha256:hn(w)}),H=hn(C),j={entryId:`material-${hn(JSON.stringify([n,S]))}`,basket:"original",metadata:C,body:w};e.status({bindingId:n,operationKey:S})===null&&u({bindingId:n,operationKey:S,intentDigest:H,originalMax:{bytes:Buffer.byteLength(C)+w.byteLength+64,records:1},terminalReserve:{bytes:1,records:1}}),g(S,H,[j])},async finishRun({runKey:A,outcome:S,materialsComplete:k}){if(typeof k!="boolean")throw new R("invalid_input");let I=s(A),m=c(A);p(I),p(m);let w=JSON.stringify({format:"sdk2-run-terminal-v1",projectionPolicyId:r,outcome:S});if(g(A,I.intentDigest,[{entryId:`terminal-${hn(JSON.stringify([n,A]))}`,basket:"terminal",metadata:w,body:new Uint8Array}]),!k)throw new R("reconciliation_required");g(m.operationKey,m.intentDigest,[])}};return Pa.set(b,A=>{if(p(s(A)).state!=="reserved"||p(c(A)).state!=="reserved")throw new R("reconciliation_required")}),b}import{createHash as _d}from"node:crypto";var nr=t=>Buffer.from(Me(t)).toString("utf8");function Hr(t){let{spool:e,captureBindingId:n,projectionPolicyId:r,runKey:i}=t,o=[];for(let c of e.snapshot().inventory.entries){if(c.bindingId!==n||!c.entryId.startsWith("material-"))continue;let d=e.readEntry({bindingId:n,entryId:c.entryId,offset:0,maxBytes:1}),l;try{l=JSON.parse(d.witness.metadata)}catch{throw new R("format_mismatch")}if(l.runKey===i){if(l.format!=="sdk2-session-capture-v1"||l.projectionPolicyId!==r||l.bodySha256!==d.witness.bodySha256)throw new R("identity_mismatch");o.push(d.witness)}}o.sort((c,d)=>nr(c)<nr(d)?-1:nr(c)>nr(d)?1:0);let s=_d("sha256").update(nr(o)).digest("hex");return Object.freeze({witnesses:Object.freeze(o),digest:s})}var Ta="sdk2-recording-lease-v1",ja="sdk2-recording-prepared-v1",Da="sdk2-recording-materials-seal-v1",xd=16384,qe=t=>Bd("sha256").update(t).digest("hex"),Fe=t=>Buffer.from(Me(t)).toString("utf8"),Ha=new WeakMap;function Ma(t,e){if(Ha.get(t)!==e)throw new R("identity_mismatch")}function rr(t){let{spool:e,captureBindingId:n,recordBindingId:r,projectionPolicyId:i,sourceId:o,sourceGeneration:s,acquireAuthority:c,acquireRecoveryAuthority:d}=t,l=t.textProjectionPolicy;if(l!==void 0&&l!==mt)throw new R("invalid_input");if(n===r)throw new TypeError("Recording capture requires separate registered baskets");let p=e.bindingIdentity(n),u=e.bindingIdentity(r);if(p.applicationScopeId!==u.applicationScopeId||p.endUserId!==u.endUserId)throw new R("identity_mismatch");let v=qa({spool:e,bindingId:n,projectionPolicyId:i}),g=Cr({spool:e,bindingId:r,sourceId:o,sourceGeneration:s,generations:t.generations,...t.publicationClock===void 0?{}:{publicationClock:t.publicationClock}}),b=Fe(t.generations),A=t.maxTurnBytes??1048576;if(!Number.isSafeInteger(A)||A<1||A>33554432)throw new R("invalid_input");let S=t.trustedAttachmentSource,k;if(S!==void 0){if(!S||typeof S!="object"||xn.isProxy(S))throw new R("invalid_input");let f=Object.getOwnPropertyDescriptors(S);if(Reflect.ownKeys(f).some(B=>!["sourceId","signal","describe","read","media"].includes(String(B)))||["sourceId","describe","read"].some(B=>!f[B]||!("value"in f[B]))||f.signal&&!("value"in f.signal)||f.media&&(!("value"in f.media)||f.media.value!==!0)||typeof f.describe?.value!="function"||typeof f.read?.value!="function"||xn.isProxy(f.describe?.value)||xn.isProxy(f.read?.value))throw new R("invalid_input");Zn(Ot,f.sourceId.value);let h=f.signal?.value;h!==void 0&&AbortSignal.prototype.throwIfAborted.call(h),k=Object.freeze({sourceId:f.sourceId.value,...f.media?{media:!0}:{},...h===void 0?{}:{signal:h},describe:f.describe.value.bind(S),read:f.read.value.bind(S)})}let I=()=>{for(let f of e.snapshot().inventory.entries){if(f.bindingId!==r||!f.entryId.startsWith("recording-"))continue;let h=e.readEntry({bindingId:r,entryId:f.entryId,offset:0,maxBytes:1}),B=Ee(Buffer.from(h.witness.metadata));if(B.format!==Ta||B.captureBindingId!==n||B.recordBindingId!==r||B.projectionPolicyId!==i||B.sourceId!==o||B.sourceGeneration!==s||B.textProjectionPolicy!==void 0&&B.textProjectionPolicy!==mt)throw new R("identity_mismatch")}};I();let m,w=!1,C=!1,H=!1,j=!1,x=!1,q=f=>{let h=f.assertCurrent();if(h!==void 0)throw h&&typeof h=="object"&&"then"in h&&Promise.resolve(h).catch(()=>{}),new R("invalid_input")},F=f=>{if(!m||m.runKey!==f)throw new R("operation_conflict");return m},L=f=>Fe({format:Ta,captureBindingId:n,recordBindingId:r,runKey:f.runKey,turnId:f.turnId,target:f.target,expectedHead:f.expectedHead,projectionPolicyId:i,sourceId:o,sourceGeneration:s,maxTurnBytes:A,...f.ownerEpoch===void 0?{}:{ownerEpoch:f.ownerEpoch},...f.attachmentPolicy===void 0?{}:{attachmentPolicy:f.attachmentPolicy},...f.attachmentSourceId===void 0?{}:{attachmentSourceId:f.attachmentSourceId},...f.textProjectionPolicy===void 0?{}:{textProjectionPolicy:f.textProjectionPolicy}}),a=(f,h)=>({bindingId:n,operationKey:`${f.runKey}:${h==="prepared"?"prepared-turn":"materials-seal"}`,intentDigest:qe(Fe([h==="prepared"?ja:Da,qe(L(f))])),originalMax:{bytes:(h==="prepared"?A:0)+(bt(f.attachmentPolicy)?qr:xd),records:1},terminalReserve:{bytes:1,records:1}}),T=(f,h)=>{if(Fe(f)!==Fe(h))throw new R("operation_conflict")},D=f=>{let h=e.status(f);if(h){T(h.reservation,f);return}try{T(e.reserve(f),f)}catch(B){if(!(B instanceof R)||B.code!=="commit_unknown")throw B;let O=e.status(f);if(!O)throw B;T(O.reservation,f)}},K=(f,h,B)=>({entryId:`recording-${qe(Fe([n,f.operationKey]))}`,basket:"original",metadata:h,body:B}),V=(f,h,B)=>{let O=f.entries[0];if(f.bindingId!==h.bindingId||f.operationKey!==h.operationKey||f.intentDigest!==h.intentDigest||f.entries.length!==1||O?.entryId!==B.entryId||O.basket!==B.basket||O.metadata!==B.metadata||O.bodyBytes!==B.body.byteLength||O.bodySha256!==qe(B.body))throw new R("operation_conflict")},Z=(f,h)=>{let B=e.status(f);if(!B)throw new R("reconciliation_required");if(T(B.reservation,f),B.state==="committed")return V(B.receipt,f,h),B.receipt;try{let O=e.commit({...f,entries:[h]});return V(O,f,h),O}catch(O){if(!(O instanceof R)||O.code!=="commit_unknown")throw O;let N=e.status(f);if(N?.state!=="committed")throw O;return V(N.receipt,f,h),N.receipt}},re=f=>{let h=e.status(f);if(!h)throw new R("reconciliation_required");if(T(h.reservation,f),h.state!=="committed"||h.receipt.entries.length!==1)throw new R("reconciliation_required");let B=h.receipt.entries[0];if(B.bodyBytes>A)throw new R("capacity_exceeded");let O=new Uint8Array(B.bodyBytes),N=0;do{let ie=e.readEntry({bindingId:n,entryId:B.entryId,offset:N,maxBytes:262144});if(ie.bodyState==="released")throw new R("entry_released");if(ie.bodyState!=="retained"||!ie.body||Fe(ie.witness)!==Fe(B))throw new R("reconciliation_required");if(O.set(ie.body,N),N+=ie.body.byteLength,ie.complete)break;if(ie.body.byteLength===0)throw new R("reconciliation_required")}while(N<B.bodyBytes);if(N!==B.bodyBytes)throw new R("reconciliation_required");let J=K(f,B.metadata,O);return V(h.receipt,f,J),{entry:J,receipt:h.receipt}},Re=(f,h)=>Fe({format:ja,leaseDigest:qe(L(f)),operationKey:h.operationKey,runKey:h.runKey,turnId:h.turnId,outcome:h.outcome,turnState:h.turnState,bodySha256:qe(h.body),messageCount:h.messageCount,toolCallCount:h.toolCallCount,pendingToolCalls:h.pendingToolCalls,...bt(f.attachmentPolicy)?{trustedAttachments:f.trustedAttachments}:{}}),Se=(f,h)=>Object.freeze({attachmentSourceId:f.attachmentSourceId,sourceId:o,sourceGeneration:s,target:Object.freeze({...f.target,generations:Object.freeze({...f.target.generations})}),runKey:f.runKey,turnId:f.turnId,bodySha256:qe(h.body)}),st=async(f,h)=>{let B=f.attachmentPolicy===void 0?[]:Ji(h.body,A);if(bt(f.attachmentPolicy)){let O=e.status({bindingId:r,operationKey:h.operationKey}),N=O?.state==="committed"?g.list({generations:f.target.generations,afterSequence:f.expectedHead?.sequence??null,limit:1,maxBytes:1048576}).records[0]:void 0;if(O?.state==="committed"&&(!N||N.recordId!==`jr-r-${qe(Fe([r,h.operationKey]))}`||N.payload.sha256!==qe(h.body)))throw new R("operation_conflict");B=await Ia({body:h.body,maxBytes:A,policy:f.attachmentPolicy,context:Se(f,h),attachments:f.trustedAttachments,source:k,assertCurrent:()=>q(f.authority),readArchived:J=>{if(!N)return;let ie=N.attachments.find(ge=>ge.mediaType===J.mediaType&&ge.sha256===J.sha256&&ge.bytes===J.bytes);if(!ie)throw new R("operation_conflict");return g.readArtifactBody({generations:f.target.generations,artifactId:ie.artifactId,maxBytes:J.bytes}).body}})}return bt(f.attachmentPolicy)&&q(f.authority),g.append({operationKey:h.operationKey,expectedHead:f.expectedHead,recordDraft:{target:f.target,turnId:f.turnId,recordKind:"turn",turnState:h.turnState},payload:{body:h.body,mediaType:"application/json"},attachments:B})},Ze=f=>Hr({spool:e,captureBindingId:n,projectionPolicyId:i,runKey:f}).digest,dt=(f,h,B)=>Fe({format:Da,leaseDigest:qe(L(f)),preparedCommitDigest:re(a(f,"prepared")).receipt.commitDigest,operationKey:h.operationKey,outcome:h.outcome,recordDigest:B.recordDigest,materialsComplete:!0,materialsDigest:Ze(f.runKey)}),y=f=>{let h=`recording:${qe(f.runKey)}`,B=L(f),O=qe(B),N={entryId:`recording-${qe(h)}`,basket:"original",metadata:B,body:new Uint8Array},J={bindingId:r,operationKey:h},ie={...J,intentDigest:O,originalMax:{bytes:Buffer.byteLength(B)+64,records:1},terminalReserve:{bytes:1,records:1}},ge=a(f,"prepared"),me=a(f,"seal"),ke=pe=>{let de=pe.entries[0];if(pe.bindingId!==r||pe.operationKey!==h||pe.intentDigest!==O||pe.entries.length!==1||de?.entryId!==N.entryId||de.metadata!==B||de.bodyBytes!==0||de.bodySha256!==qe(N.body))throw new R("operation_conflict")},$e=[ge,me,ie].map(pe=>e.status(pe));for(let[pe,de]of $e.entries())de&&T(de.reservation,[ge,me,ie][pe]);let we=$e[2];if(we&&we.reservation.intentDigest!==O)throw new R("operation_conflict");if(we?.state==="committed"&&$e[0]&&$e[1]){ke(we.receipt);return}try{let pe=ia(e,{prepared:ge,seal:me,lease:ie,leaseEntry:N});if(pe){ke(pe);return}}catch(pe){if(!(pe instanceof R)||pe.code!=="commit_unknown")throw pe;let de=[ge,me,ie].map(Qe=>e.status(Qe));for(let[Qe,Kt]of de.entries())Kt&&T(Kt.reservation,[ge,me,ie][Qe]);let ve=de[2];if(!de[0]||!de[1]||ve?.state!=="committed")throw pe;ke(ve.receipt);return}if(D(ge),D(me),we?.state==="committed"){ke(we.receipt);return}if(!we)try{e.reserve({...J,intentDigest:O,originalMax:{bytes:Buffer.byteLength(B)+64,records:1},terminalReserve:{bytes:1,records:1}})}catch(pe){if(!(pe instanceof R)||pe.code!=="commit_unknown"||e.status(J)?.reservation.intentDigest!==O)throw pe}try{ke(e.commit({...J,intentDigest:O,entries:[N]}))}catch(pe){if(!(pe instanceof R)||pe.code!=="commit_unknown")throw pe;let de=e.status(J);if(de?.state!=="committed")throw pe;ke(de.receipt)}},E=f=>typeof f=="string"&&f.length>0&&Buffer.byteLength(f)<=256&&!f.includes("\0")&&Buffer.from(f).toString("utf8")===f,U=(f,h)=>{if(h.operationKey!==`${f.runKey}:turn`||h.runKey!==f.runKey||h.turnId!==f.turnId||!["completed","aborted","failed","interrupted"].includes(h.outcome)||!["completed","cancelled","incomplete"].includes(h.turnState)||h.outcome==="aborted"!=(h.turnState==="cancelled")||h.turnState==="completed"&&h.outcome!=="completed"||[h.messageCount,h.toolCallCount,h.pendingToolCalls].some(J=>!Number.isSafeInteger(J)||J<0))throw new R("operation_conflict");if(h.body.byteLength>A)throw new R("capacity_exceeded");let B=Buffer.from(h.body).toString("utf8");if(!Buffer.from(B).equals(Buffer.from(h.body)))throw new R("invalid_input");let O=JSON.parse(B);if(O?.format!==cn||!Array.isArray(O.messages)||Object.keys(O).length!==2)throw new R("invalid_input");let N=br({messages:O.messages,turnState:h.turnState,maxBytes:A});if(f.textProjectionPolicy===mt&&!Buffer.from(vr(h.body,A)).equals(Buffer.from(h.body)))throw new R("operation_conflict");if(N.messageCount!==h.messageCount||N.toolCallCount!==h.toolCallCount||N.pendingToolCalls!==h.pendingToolCalls)throw new R("operation_conflict")},Q=f=>{if(!f||typeof f!="object"||xn.isProxy(f)||Object.getPrototypeOf(f)!==Object.prototype)throw new R("invalid_input");let h=Object.getOwnPropertyDescriptors(f),B=["operationKey","runKey","turnId","outcome","turnState","body","messageCount","toolCallCount","pendingToolCalls"];if(Reflect.ownKeys(h).length!==B.length||B.some(N=>!h[N]||!("value"in h[N])))throw new R("invalid_input");let O=Object.fromEntries(B.map(N=>[N,h[N].value]));if(!(O.body instanceof Uint8Array)||xn.isProxy(O.body)||xn.isSharedArrayBuffer(O.body.buffer))throw new R("invalid_input");return{...O,body:Uint8Array.from(O.body)}},ce=f=>{if(!E(f))throw new R("invalid_input");let h=`recording:${qe(f)}`,B=e.status({bindingId:r,operationKey:h});if(B?.state!=="committed"||B.receipt.entries.length!==1)throw new R("reconciliation_required");let O=B.receipt.entries[0],N=Ee(Buffer.from(O.metadata));if(!E(N.turnId)||!E(N.ownerEpoch)||N.runKey!==f||N.maxTurnBytes!==A||N.attachmentPolicy!==void 0&&N.attachmentPolicy!==Er&&!bt(N.attachmentPolicy)||N.textProjectionPolicy!==void 0&&N.textProjectionPolicy!==mt)throw new R("reconciliation_required");let J={runKey:f,turnId:N.turnId,target:N.target,expectedHead:N.expectedHead,ownerEpoch:N.ownerEpoch,...N.textProjectionPolicy===void 0?{}:{textProjectionPolicy:N.textProjectionPolicy},...N.attachmentPolicy===void 0?{}:{attachmentPolicy:N.attachmentPolicy},...N.attachmentSourceId===void 0?{}:{attachmentSourceId:N.attachmentSourceId},authority:{target:N.target,assertCurrent(){throw new R("reconciliation_required")}},basePrepared:!0};Zn(J.attachmentPolicy,J.attachmentSourceId);let ie=L(J);if(ie!==O.metadata||B.reservation.intentDigest!==qe(ie)||O.entryId!==`recording-${qe(h)}`||O.basket!=="original"||O.bodyBytes!==0||O.bodySha256!==qe(new Uint8Array)||Fe(J.target.generations)!==b)throw new R("identity_mismatch");return Kn({recordId:"validation",sequence:"1",predecessorDigest:"0".repeat(64),target:J.target,turnId:J.turnId,recordKind:"turn",turnState:"incomplete",payload:{artifactId:"validation",sourceId:o,mediaType:"application/json",body:Buffer.from("{}")},attachments:[]}),J},ne=f=>{let h=re(a(f,"prepared")),B=Ee(Buffer.from(h.entry.metadata));bt(f.attachmentPolicy)&&(f.trustedAttachments=Tr(B.trustedAttachments,A,f.attachmentPolicy));let O={operationKey:B.operationKey,runKey:B.runKey,turnId:B.turnId,outcome:B.outcome,turnState:B.turnState,body:h.entry.body,messageCount:B.messageCount,toolCallCount:B.toolCallCount,pendingToolCalls:B.pendingToolCalls};if(U(f,O),Re(f,O)!==h.entry.metadata)throw new R("operation_conflict");return O},he={assertReady(){if(I(),v.assertReady(),m||x)throw new R("reconciliation_required")},async prepareRun({runKey:f,turnId:h}){if(w||C||H||j||x)throw new R("reentrant");if(typeof h!="string"||h.length===0)throw new R("invalid_input");if(m&&(m.runKey!==f||m.turnId!==h))throw new R("operation_conflict");w=!0;try{if(I(),!m){let O=c({runKey:f,turnId:h});if(O&&typeof O=="object"&&"then"in O)throw Promise.resolve(O).catch(()=>{}),new R("invalid_input");if(!O||typeof O.assertCurrent!="function")throw new R("invalid_input");let N=Ee(Me(O.target));if(Fe(N.generations)!==b)throw new R("identity_mismatch");if(Kn({recordId:"validation",sequence:"1",predecessorDigest:"0".repeat(64),target:N,turnId:h,recordKind:"turn",turnState:"incomplete",payload:{artifactId:"validation",sourceId:o,mediaType:"application/json",body:Buffer.from("{}")},attachments:[]}),q(O),O.ownerEpoch!==void 0&&!E(O.ownerEpoch))throw new R("invalid_input");m={runKey:f,turnId:h,target:N,expectedHead:g.head(),authority:O,basePrepared:!1,...l===void 0?{}:{textProjectionPolicy:l},attachmentPolicy:k===void 0?Er:k.media===!0?xt:Ot,...k===void 0?{}:{attachmentSourceId:k.sourceId},...O.ownerEpoch===void 0?{}:{ownerEpoch:O.ownerEpoch}}}let B=F(f);q(B.authority),B.basePrepared||(await v.prepareRun({runKey:f,turnId:h}),B.basePrepared=!0),q(B.authority),y(B)}finally{w=!1}},async write(f){if(w||C||H||j||x)throw new R("reentrant");j=!0;try{d!==void 0&&f.runKey!==void 0&&q(F(f.runKey).authority),await v.write(f),d!==void 0&&f.runKey!==void 0&&q(F(f.runKey).authority)}finally{j=!1}},async writeTurn(f){if(w||C||H||j||x)throw new R("reentrant");H=!0;try{let h=Q(f),B=F(h.runKey);U(B,h),q(B.authority),bt(B.attachmentPolicy)&&B.trustedAttachments===void 0&&(e.status(a(B,"prepared"))?.state==="committed"?ne(B):B.trustedAttachments=va(h.body,A,Se(B,h),k,B.attachmentPolicy),q(B.authority));let O=Re(B,h);if(B.writeIdentity!==void 0&&B.writeIdentity!==O)throw new R("operation_conflict");B.writeIdentity=O,B.write=h,Z(a(B,"prepared"),K(a(B,"prepared"),O,h.body)),q(B.authority),B.published=await st(B,h)}finally{H=!1}},async finishRun(f){if(w||C||H||j||x)throw new R("reentrant");if(typeof f.materialsComplete!="boolean")throw new R("invalid_input");let h=F(f.runKey);d!==void 0&&q(h.authority),C=!0;try{if(h.write&&h.write.outcome!==f.outcome)throw new R("operation_conflict");let B=f.materialsComplete===!0&&h.published!==void 0&&h.write!==void 0;if(B){let O=a(h,"seal");Z(O,K(O,dt(h,h.write,h.published),new Uint8Array))}d!==void 0&&q(h.authority),await v.finishRun({...f,materialsComplete:B}),m===h&&(m=void 0)}finally{C=!1}},async recoverRun({runKey:f}){if(w||C||H||j||x)throw new R("reentrant");if(m||!d)throw new R("reconciliation_required");x=!0;try{I();let h=ce(f),B=d({runKey:f,turnId:h.turnId,originalOwnerEpoch:h.ownerEpoch,target:Ee(Me(h.target)),expectedHead:h.expectedHead===null?null:{...h.expectedHead},sourceId:o,sourceGeneration:s});if(B&&typeof B=="object"&&"then"in B)throw Promise.resolve(B).catch(()=>{}),new R("invalid_input");if(!B||typeof B.assertCurrent!="function")throw new R("invalid_input");q(B),h.authority={target:h.target,assertCurrent:()=>B.assertCurrent()};let O=ne(h),N=await st(h,O);q(B);let J=re(a(h,"seal"));if(J.entry.metadata!==dt(h,O,N)||J.entry.body.byteLength!==0)throw new R("operation_conflict");return q(B),await v.finishRun({runKey:f,outcome:O.outcome,materialsComplete:!0}),{state:"settled",runKey:f,turnId:h.turnId,outcome:O.outcome,record:N}}finally{x=!1}}};if(Ha.set(he,e),d!==void 0){let f=h=>{if(w||C||H||j||x||!h.ownerEpoch||!h.basePrepared||h.write||h.published)throw new R("reconciliation_required");Ea(v,h.runKey);let B=new Set([h.runKey,`${h.runKey}:fence`,a(h,"prepared").operationKey,a(h,"seal").operationKey]);if(e.snapshot().inventory.reservations.some(O=>O.bindingId===n&&!B.has(O.operationKey)))throw new R("reconciliation_required");for(let O of["prepared","seal"]){let N=a(h,O),J=e.status(N);if(J?.state!=="reserved")throw new R("reconciliation_required");T(J.reservation,N)}return{leaseDigest:qe(L(h)),materialsDigest:Ze(h.runKey)}};Ir(he,{read(h){let B=F(h);return q(B.authority),f(B)},restore(h,B){if(m)throw new R("reconciliation_required");I();let O=ce(h);if(Fe(f(O))!==Fe(B))throw new R("identity_mismatch");let N=d({runKey:h,turnId:O.turnId,originalOwnerEpoch:O.ownerEpoch,target:Ee(Me(O.target)),expectedHead:O.expectedHead===null?null:{...O.expectedHead},sourceId:o,sourceGeneration:s});if(!N||typeof N.assertCurrent!="function")throw new R("invalid_input");q(N),O.authority={target:O.target,assertCurrent:()=>N.assertCurrent()},m=O}})}return he}var La=new WeakMap,Mr=new WeakMap,Pd="sdk2-governance-material-v1",Ed=z(""),De=(t,e)=>_(t)===_(e);function le(t="reconciliation_required"){throw new R(t)}function oo(t){if(t&&typeof t=="object"){for(let e of Object.values(t))oo(e);Object.freeze(t)}return t}function Gr(t){return z(JSON.stringify(t))}function qd(t){return P(t,["spool","control","slot","storeIdentity","owner","assertCurrent"]),(typeof t.assertCurrent!="function"||io.isProxy(t.assertCurrent)||!t.storeIdentity||typeof t.storeIdentity!="object"||io.isProxy(t.storeIdentity))&&le("invalid_input"),Ge(t.slot),Object.freeze({...t,slot:Object.freeze({...t.slot})})}function Ga(t){let e=qd(t),n=Mr.get(e.spool);n&&(n.reentered=!0,le("reentrant"));let r={reentered:!1};return Mr.set(e.spool,r),{context:e,guard:r}}function Vt(t,e){let n=Reflect.apply(t.assertCurrent,void 0,[]);io.isPromise(n)&&Promise.prototype.then.call(n,void 0,()=>{}),n!==void 0&&le("invalid_input"),e.reentered&&le("reentrant")}function Na(t){P(t,["snapshot","facts"]),P(t.facts,["kind","history","target","work","recoveryFinish","controlCompleted","captureMetadataComplete","headEventDigest","writeBarrier"]);let e=Et({snapshot:t.snapshot,work:t.facts.work});return(e.kind!=="verified"||!De(e,t.facts))&&le(),e}function ao(t){let e=Na(t);if(e.work.kind!=="run"){let r=ir(t);return r.kind==="rewrite"&&r.capture==="confirmed"&&r.projection!==void 0?oo([{bindingId:t.snapshot.plan?.recordBindingId??le(),operationKey:r.projection.operationKey}]):Object.freeze([])}let n=t.snapshot.plan?.captureBindingId??le();return oo([{bindingId:n,operationKey:e.work.captureRunKey},{bindingId:n,operationKey:`${e.work.captureRunKey}:fence`}])}function On(t,e,n){Vt(t,e),lt(t.spool,t.control);let r=n.snapshot.plan??le(),i=n.snapshot.current??le();(!De(t.slot,n.snapshot.slot)||!De(t.slot,r.slot))&&le("identity_mismatch");let o=et(t.spool,t.control,t.slot),s=rt(t.owner,{storeIdentity:t.storeIdentity,sessionId:r.sessionId,slot:t.slot});(o.scope.applicationScopeId!==s.root.registration.scope.applicationScopeId||o.scope.endUserId!==s.root.registration.scope.endUserId||o.target.sessionId!==r.sessionId||!De(s.root.registration,i.registration)||r.ownerRootDigest!==s.ownerRootDigest||r.physicalPairDigest!==s.physicalPairDigest||!De(r.createRequest,s.root.createRequest)||r.createSemanticDigest!==s.root.createSemanticDigest||!De(r.confirmedHistory,s.root.confirmedHistory)||!De(_e(t.spool,t.storeIdentity,r.sessionId,o.scope).identity,s.root.physical)||!s.predecessorOwners.some(c=>c.epoch===n.facts.work.ownerEpoch))&&le("identity_mismatch"),Vt(t,e)}function Kr(t,e,n){Na(n),On(t,e,n);let r=zt({spool:t.spool,control:t.control,slot:t.slot,operations:n.snapshot.operations.map(s=>s.key),includeWork:!0,expectedHeadEventDigest:n.snapshot.headEventDigest}),i=Et({snapshot:r,work:n.facts.work});(i.kind!=="verified"||!De(i,n.facts))&&le();let o={snapshot:r,facts:i};return On(t,e,o),o}function Td(t,e){if(e.kind!=="run")return;let{captureBindingId:n,projectionPolicyId:r}=e.recording,{runKey:i}=e.recovery,o={bindingId:n,operationKey:i},s={bindingId:n,operationKey:`${i}:fence`},c={...o,intentDigest:z(JSON.stringify(["sdk2-run-capture-v1",n,r,i])),originalMax:{bytes:1,records:1},terminalReserve:{bytes:2048,records:1}},d={...s,intentDigest:z(JSON.stringify(["sdk2-run-fence-v1",n,r,i])),originalMax:{bytes:1,records:1},terminalReserve:{bytes:1,records:1}},l=JSON.stringify({format:"sdk2-run-terminal-v1",projectionPolicyId:r,outcome:e.outcome}),p={entryId:`terminal-${z(JSON.stringify([n,i]))}`,basket:"terminal",metadata:l,metadataBytes:Buffer.byteLength(l),bodyBytes:0,bodySha256:Ed,logicalBytes:Buffer.byteLength(l)+64},u=(v,g)=>{let b=t.snapshot.operations.find(S=>De(S.key,Ka(v)))?.saved;(!b||b.state!=="committed"||!De(gr(b.reservation),v))&&le(),P(b.receipt,["state","bindingId","operationKey","intentDigest","commitDigest","entries"]);let A={state:"committed",...Ka(v),intentDigest:v.intentDigest,commitDigest:z(JSON.stringify(g.map(S=>[S.entryId,S.basket,S.metadata,S.bodyBytes,S.bodySha256]))),entries:g};De(b.receipt,A)||le()};u(c,[p]),u(d,[])}function Ka(t){return{bindingId:t.bindingId,operationKey:t.operationKey}}function Ua(t){return Gr({history:t.history,target:t.target,recoveryFinish:t.recoveryFinish})}function za(t){let e=t.work;return Gr({kind:e.kind,ownerEpoch:e.ownerEpoch,workId:e.workId,turnId:e.turnId,captureRunKey:e.captureRunKey,admission:e.admission,admittedTarget:e.admittedTarget,admittedEventDigest:e.admittedEventDigest})}function Lr(t){let e=ir(t),n=e.kind==="rewrite"&&e.capture==="confirmed"?e.projection?.operationKey:void 0,r=t.snapshot.operations.filter(i=>n===void 0||i.key.bindingId!==t.snapshot.plan?.recordBindingId||i.key.operationKey!==n).map(i=>({key:i.key,saved:i.saved}));return r.sort((i,o)=>_(i.key).localeCompare(_(o.key),"en")),Gr(r)}function jd(t,e,n){let r=n.witness;(!Number.isSafeInteger(r.bodyBytes)||r.bodyBytes<0||r.bodyBytes>33554432)&&le();let i=0,o=Od("sha256");do{Vt(t,e);let s=t.spool.readEntry({bindingId:n.bindingId,entryId:r.entryId,offset:i,maxBytes:262144});if((s.bodyState!=="retained"||!s.body||s.offset!==i||!De(s.witness,r)||s.body.byteLength>262144||i+s.body.byteLength>r.bodyBytes)&&le(),o.update(s.body),i+=s.body.byteLength,Vt(t,e),s.complete){i!==r.bodyBytes&&le();break}(s.body.byteLength===0||i>=r.bodyBytes)&&le()}while(i<r.bodyBytes);(i!==r.bodyBytes||o.digest("hex")!==r.bodySha256)&&le()}function so(t,e,n){Vt(t,e);let r=[],i=null;if(n.kind==="run"){let o=Hr({spool:t.spool,captureBindingId:n.recording.captureBindingId,projectionPolicyId:Pd,runKey:n.recovery.runKey});o.digest!==n.materialsDigest&&le(),i=o.digest;for(let s of[n.prepared,n.journal])r.push({bindingId:s.key.bindingId,witness:s.entry});for(let s of n.journalAttachments)r.push({bindingId:n.journal.key.bindingId,witness:s});for(let s of o.witnesses)r.push({bindingId:n.recording.captureBindingId,witness:s})}else n.capture==="confirmed"&&r.push({bindingId:n.material.key.bindingId,witness:n.material.entry});for(let o of r)jd(t,e,o);return Vt(t,e),Gr({entries:r,materialsDigest:i})}function ir(t){let e=Oa({snapshot:t.snapshot,work:t.facts.work});return Td(t,e),e}function Fa(t,e,n){let r=n.snapshot.plan??le(),i=n.facts.work;return{spool:t.spool,slot:t.slot,ownerEpoch:i.ownerEpoch,rewriteId:i.workId,recordBindingId:r.recordBindingId,sourceId:r.sourceId,sourceGeneration:r.sourceGeneration,target:n.facts.target,assertCurrent(){On(t,e,n)}}}function Dd(t,e){let n=t.facts.work,r=t.facts.recoveryFinish,i=s=>n.kind==="run"?`finish-${z(_([n.captureRunKey,s]))}`:`rewrite-finish-${z(_([n.ownerEpoch,n.workId,s]))}`,o=Array.from({length:9},(s,c)=>c).find(s=>i(s)===e.transitionId);(o===void 0||(o===0?!De(e,r):BigInt(e.expectedRevision)<=BigInt(r.expectedRevision)))&&le(),(e.ownerEpoch!==n.ownerEpoch||e.kind!==(n.kind==="run"?"finish-run":"finish-rewrite")||(e.kind==="finish-run"?e.runKey!==n.workId||!De(e.expectedTarget,t.facts.target):e.rewriteId!==n.workId||r.kind!=="finish-rewrite"||e.outcome!==r.outcome))&&le(),n.finish!==null?De(n.finish.mutation,e)||le():BigInt(e.expectedRevision)>BigInt(t.snapshot.current?.revision??le())&&le()}async function Wa(t,e){let{context:n,guard:r}=Ga(t);try{let i=Kr(n,r,e);(i.facts.controlCompleted||i.snapshot.writeBarrier!=="clear"||i.snapshot.work?.active===null)&&le();let o=ir(i),s=Lr(i),c=so(n,r,o);if(o.kind==="run"){let p=()=>{On(n,r,i)},u=rr({spool:n.spool,...o.recording,publicationClock:()=>et(n.spool,n.control,n.slot).nowMs,acquireAuthority(){return le("unsupported_capability")},acquireRecoveryAuthority(g){return De(g,o.recovery)||le("identity_mismatch"),p(),{assertCurrent:p}}});p();let v=await u.recoverRun({runKey:o.recovery.runKey});p(),(v.state!=="settled"||v.runKey!==o.recovery.runKey||v.turnId!==o.recovery.turnId||v.outcome!==o.outcome||!De(v.record,o.record))&&le()}else if(o.capture==="confirmed"&&o.projection!==void 0){let p=i.snapshot.plan??le(),u=i.snapshot.current??le(),v=_e(n.spool,n.storeIdentity,p.sessionId,u.registration.scope);On(n,r,i);let g=await v.readConfirmed();On(n,r,i),g||le(),(Qn({...Fa(n,r,i),publicationClock:()=>et(n.spool,n.control,n.slot).nowMs,messages:g.messages,fact:o.projection})??le()).publish()}let d=Kr(n,r,i);(Lr(d)!==s||so(n,r,ir(d))!==c)&&le();let l=Object.freeze(Object.create(null));return La.set(l,{spool:n.spool,control:n.control,storeIdentity:n.storeIdentity,owner:n.owner,slot:n.slot,workDigest:za(d.facts),fixedFactsDigest:Ua(d.facts),operationDigest:s,captureDigest:c}),Vt(n,r),l}finally{Mr.delete(n.spool)}}function $a(t,e,n){let r=La.get(t)??le("identity_mismatch"),{context:i,guard:o}=Ga(e);try{P(n,["snapshot","facts","pendingMutation"]),(r.spool!==i.spool||r.control!==i.control||r.storeIdentity!==i.storeIdentity||r.owner!==i.owner||!De(r.slot,i.slot))&&le("identity_mismatch");let s=ze(n.pendingMutation);s.kind!=="finish-run"&&s.kind!=="finish-rewrite"&&le("invalid_input");let c=Kr(i,o,{snapshot:n.snapshot,facts:n.facts});(za(c.facts)!==r.workDigest||Ua(c.facts)!==r.fixedFactsDigest||Lr(c)!==r.operationDigest)&&le(),Dd(c,s);let d=ir(c);so(i,o,d)!==r.captureDigest&&le(),d.kind==="rewrite"&&d.capture==="confirmed"&&d.projection!==void 0&&Xi(Fa(i,o,c),d.projection);let l=Kr(i,o,c);Lr(l)!==r.operationDigest&&le(),Vt(i,o)}finally{Mr.delete(i.spool)}}function co(t){let e=()=>{throw new R("reconciliation_required")},n=P(t,["query","historyEpoch","turn","archive"],["deadline"]),r=n,i=r.query,o=P(n.archive,["version","history","messages","queryDigest","historyEpoch","turn"]),s=P(o.history,["commitId","observation"]),c=P(s.observation,["sessionId","sourceSnapshotDigest","localHistoryGeneration"]);(!i||i.version!==1||typeof i.sessionId!="string"||!Array.isArray(i.messages)||i.retryBarrier||typeof r.historyEpoch!="string"||!r.historyEpoch||!Number.isSafeInteger(r.turn)||r.turn<1||o.version!==1||o.turn!==r.turn||o.historyEpoch!==r.historyEpoch||o.queryDigest!==z(_(i))||!Array.isArray(o.messages)||typeof s.commitId!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/u.test(s.commitId)||c.sessionId!==i.sessionId||!Number.isSafeInteger(c.localHistoryGeneration)||c.localHistoryGeneration<0||Bt(i.sessionId,o.messages,0).sourceSnapshotDigest!==c.sourceSnapshotDigest)&&e();let d=P(i.capture,["version","configuration","owner","sequence","runKey","turnId","fullTurn","sink"]),l=P(d.fullTurn,["messages","staged","incomplete"]),p=P(d.sink,["version","initial","admission","captureRunKey","recording"]),u=P(p.initial,["target","localHistoryGeneration","confirmedCommitId"]),v=P(p.admission,["kind","transitionId","expectedRevision","ownerEpoch","runKey","turnId"]);return(!Array.isArray(l.messages)||!Array.isArray(l.staged)||typeof l.incomplete!="boolean"||d.version!==1||p.version!==1||d.turnId!==i.turnId||v.turnId!==i.turnId||d.runKey!==p.captureRunKey||v.kind!=="admit-run"||u.confirmedCommitId!==s.commitId||u.localHistoryGeneration!==c.localHistoryGeneration||u.target?.sourceSnapshotDigest!==c.sourceSnapshotDigest)&&e(),structuredClone(r)}var Ja=new WeakMap,Va=new WeakSet;function uo(t){Va.has(t)||lo("dependency_held")}function lo(t="identity_mismatch"){throw new R(t)}var Hd=t=>JSON.parse(_(t));function Xa(t,e){Ja.set(t,e)}function Ya(t){Va.add(t)}function po(t){let e=Ja.get(t)??lo();return e.used&&lo("operation_conflict"),e.assertCurrent(),e.used=!0,{options:Hd(e.options),marker:e.marker,assertCurrent:e.assertCurrent,retainUnclosed:e.retainUnclosed}}function yo(t){throw new R(t)}async function Za(t){return ec(t)}async function Qa(t){let e=po(t);return ec(e.options,e)}async function ec(t,e){e?.assertCurrent(),t.format!==void 0&&t.format!==xs&&t.format!==Os&&yo("invalid_input"),(typeof t.path!="string"||t.path.length===0||t.path.includes("\0"))&&yo("invalid_input"),bi(t.path),Ln(t.storeId),(t.path===":memory:"||t.mode!=="create"&&t.mode!=="recover")&&yo("invalid_input");let n=structuredClone(t);for(let i of n.bindings)Ln(i.bindingId),Ln(i.applicationScopeId),Ln(i.endUserId);for(let i of[n.maxReservations,n.maxOperations,n.maxEntries,n.maxDatabasePages])Ps(i,1);wr({...n,inventory:{status:"known",kind:"initial",reservations:[],entries:[]}});let{openValidatedSqliteArchiveSpool:r}=await import("./tansr-sqlite-spool-implementation-LHEIRSUX.mjs");return r(n,e)}import{randomUUID as Vd}from"node:crypto";import{lstatSync as ic,mkdirSync as ko,realpathSync as sc}from"node:fs";import{join as Zt}from"node:path";import{types as cr}from"node:util";import{createRequire as Xd}from"node:module";import{closeSync as Md,lstatSync as tc,openSync as Kd,realpathSync as Ld}from"node:fs";import{dirname as Gd,isAbsolute as Nd,resolve as Ud}from"node:path";import{createRequire as zd}from"node:module";import{types as Io}from"node:util";var Wr=class extends Error{constructor(n){super(`SDK2 host budget: ${n}`);this.code=n;this.name="ArchiveHostBudgetError"}code},mo="sdk2-host-budget-v1",mn=262144,Fd=16,Wd=65536,$d=65536,nc=BigInt(Number.MAX_SAFE_INTEGER),Jd=`
|
|
7
|
-
CREATE TABLE budget_meta(id INTEGER PRIMARY KEY CHECK(id=1),format TEXT NOT NULL,identity TEXT NOT NULL,config TEXT NOT NULL) STRICT;
|
|
8
|
-
CREATE TABLE budget_catalog(id INTEGER PRIMARY KEY CHECK(id=1),claims INTEGER NOT NULL CHECK(claims>=0),bytes INTEGER NOT NULL CHECK(bytes>=0),records INTEGER NOT NULL CHECK(records>=0),digest TEXT NOT NULL) STRICT;
|
|
9
|
-
CREATE TABLE budget_claim(claim_id TEXT PRIMARY KEY,subject_key TEXT NOT NULL UNIQUE,application_scope_id TEXT NOT NULL,end_user_id TEXT NOT NULL,intent TEXT NOT NULL,digest TEXT NOT NULL,bytes INTEGER NOT NULL CHECK(bytes>0),records INTEGER NOT NULL CHECK(records>0)) STRICT;
|
|
10
|
-
CREATE INDEX budget_claim_application ON budget_claim(application_scope_id);
|
|
11
|
-
CREATE INDEX budget_claim_user ON budget_claim(application_scope_id,end_user_id);
|
|
12
|
-
CREATE TABLE budget_counter(bucket TEXT PRIMARY KEY,claims INTEGER NOT NULL CHECK(claims>0),bytes INTEGER NOT NULL CHECK(bytes>0),records INTEGER NOT NULL CHECK(records>0),digest TEXT NOT NULL) STRICT;
|
|
13
|
-
CREATE TABLE budget_claim_physical(claim_id TEXT PRIMARY KEY,attempt_id TEXT NOT NULL,plan_digest TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('building','bound')),physical_json TEXT,digest TEXT NOT NULL) STRICT;
|
|
14
|
-
`,Ao=new WeakMap,wo=new WeakMap;function X(t="invalid_input"){throw new Wr(t)}function ar(t,e){try{return P(t,e)}catch{return X()}}function qt(t,e=!1){return(typeof t!="string"||[...t].length<1||[...t].length>(e?512:128)||Buffer.from(t).toString("utf8")!==t||!e&&!/^[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(t))&&X(),t}function sr(t){return(typeof t!="string"||!/^[a-f0-9]{64}$/.test(t))&&X(),t}function Xt(t,e=Number.MAX_SAFE_INTEGER){return(typeof t!="number"||!Number.isSafeInteger(t)||t<1||t>e)&&X(),t}function Nr(t){let e=ar(t,["bytes","records"]);return{bytes:Xt(e.bytes),records:Xt(e.records)}}function Ie(t){try{return _(t)}catch{return X("invalid_input")}}function Pn(t){if(t&&typeof t=="object"){for(let e of Object.values(t))Pn(e);Object.freeze(t)}return t}function Ur(t){let e=ar(t,["claimId","applicationScopeId","endUserId","sessionId","storeIdentityDigest","configurationDigest","databases"]),n=e.databases;(!Array.isArray(n)||Io.isProxy(n)||n.length<1||n.length>Fd||Reflect.ownKeys(n).length!==n.length+1)&&X();let r=new Set,i=new Set,o=0n,s=0n,c=[];for(let p=0;p<n.length;p++){let u=Object.getOwnPropertyDescriptor(n,String(p));(!u?.enumerable||!Object.hasOwn(u,"value"))&&X();let v=ar(u.value,["storeId","directoryName","bindingsDigest","limit","maxReservations","maxOperations","maxEntries","maxDatabasePages"]),g=qt(v.storeId),b=qt(v.directoryName);(!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(b)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(b)||r.has(g)||i.has(b.toLowerCase()))&&X(),r.add(g),i.add(b.toLowerCase());let A=Nr(v.limit);o+=BigInt(A.bytes),s+=BigInt(A.records),(o>nc||s>nc)&&X("capacity_exceeded"),c.push({storeId:g,directoryName:b,bindingsDigest:sr(v.bindingsDigest),limit:A,maxReservations:Xt(v.maxReservations),maxOperations:Xt(v.maxOperations),maxEntries:Xt(v.maxEntries),maxDatabasePages:Xt(v.maxDatabasePages)})}let d=Pn({claimId:qt(e.claimId),applicationScopeId:qt(e.applicationScopeId),endUserId:qt(e.endUserId,!0),sessionId:qt(e.sessionId,!0),storeIdentityDigest:sr(e.storeIdentityDigest),configurationDigest:sr(e.configurationDigest),databases:c}),l=Ie(d);return Buffer.byteLength(l)>mn&&X("capacity_exceeded"),{intent:d,json:l,digest:z(l),total:{bytes:Number(o),records:Number(s)}}}function rc(t){return Ur(t).intent}function $r(t,e){let n=tc(t,{bigint:!0}),r=Ld(t),i=tc(r,{bigint:!0});return(n.isSymbolicLink()||i.ino===0n||(e?!i.isDirectory():!i.isFile())||n.ino!==i.ino||n.dev!==i.dev)&&X("identity_mismatch"),{path:r,dev:i.dev.toString(),ino:i.ino.toString()}}function vo(t){if(t instanceof Wr)throw t;return X("storage_failure")}function fo(t){return[Ie(["host"]),Ie(["app",t.applicationScopeId]),Ie(["user",t.applicationScopeId,t.endUserId])]}function go(t){return Ie([t.storeIdentityDigest,t.sessionId])}function zr(){return{claims:0n,bytes:0n,records:0n}}function Fr(t,e){return z(Ie([t,e.claims.toString(),e.bytes.toString(),e.records.toString()]))}function ho(t,e){return{claims:t.claims+1n,bytes:t.bytes+BigInt(e.total.bytes),records:t.records+BigInt(e.total.records)}}function or(t,e){return t.claims===e.claims&&t.bytes===e.bytes&&t.records===e.records}function yy(t){let e=ar(t,["path","mode","hostId","limits","maxAllocationRecords","maxDatabasePages","assertAuthorized"]);(typeof e.path!="string"||!Nd(e.path)||e.path.includes("\0")||e.mode!=="create"&&e.mode!=="reopen"||typeof e.assertAuthorized!="function"||Io.isProxy(e.assertAuthorized))&&X();let n=ar(e.limits,["host","application","endUser"]),r=Pn({hostId:qt(e.hostId),limits:{host:Nr(n.host),application:Nr(n.application),endUser:Nr(n.endUser)},maxAllocationRecords:Xt(e.maxAllocationRecords,Wd),maxDatabasePages:Xt(e.maxDatabasePages,$d)}),i=Ud(e.path),o;try{let{DatabaseSync:s}=zd(import.meta.url)("node:sqlite"),c=$r(Gd(i),!0);if(e.mode==="create"){let p=Kd(i,"wx",384);Md(p)}let d={parent:c,database:$r(i,!1)};if(o=new s(i),e.mode==="reopen"){let p=o.prepare("SELECT * FROM budget_meta LIMIT 2").all();(p.length!==1||p[0]?.format!==mo||p[0].identity!==Ie(d)||p[0].config!==Ie(r))&&X("identity_mismatch")}if(o.exec("PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA temp_store=MEMORY; PRAGMA busy_timeout=0;"),e.mode==="create"&&o.exec("PRAGMA page_size=4096;"),(o.prepare("PRAGMA page_size").get()?.page_size!==4096||o.prepare(`PRAGMA max_page_count=${r.maxDatabasePages}`).get()?.max_page_count!==r.maxDatabasePages)&&X("capacity_exceeded"),e.mode==="create"){o.exec("BEGIN IMMEDIATE");let p=!1;try{o.exec(Jd),o.prepare("INSERT INTO budget_meta VALUES (1,?,?,?)").run(mo,Ie(d),Ie(r)),o.prepare("INSERT INTO budget_catalog VALUES (1,0,0,0,?)").run(Fr("catalog",zr())),p=!0,o.exec("COMMIT")}catch(u){try{o.isTransaction&&o.exec("ROLLBACK")}catch{}throw p&&X("commit_unknown"),u}}let l=new bo(o,d,r,e.assertAuthorized);return l.validate(),l}catch(s){try{o?.close()}catch{}return vo(s)}}var bo=class{#n;#i;#t;#p;#y=new Map;#c=!1;#s=!1;#a=!1;#o;#r=!1;#f;constructor(e,n,r,i){this.#n=e,this.#i=n,this.#t=r,this.#p=i,wo.set(this,{locate:()=>this.#h(()=>Object.freeze({root:Object.freeze({...n.parent}),budgetIdentityDigest:z(Ie(n))})),access:(o,s,c)=>this.#B(o,s,c)})}#e(e){let n=this.#n.prepare(e);return n.setReadBigInts(!0),n}#g(){(Ie($r(this.#i.parent.path,!0))!==Ie(this.#i.parent)||Ie($r(this.#i.database.path,!1))!==Ie(this.#i.database))&&X("identity_mismatch");let e=this.#e("SELECT * FROM budget_meta LIMIT 2").all();(e.length!==1||e[0]?.id!==1n||e[0].format!==mo||e[0].identity!==Ie(this.#i)||e[0].config!==Ie(this.#t))&&X("identity_mismatch"),(this.#e("PRAGMA synchronous").get()?.synchronous!==2n||this.#e("PRAGMA journal_mode").get()?.journal_mode!=="delete"||this.#e("PRAGMA page_size").get()?.page_size!==4096n||this.#e("PRAGMA max_page_count").get()?.max_page_count!==BigInt(this.#t.maxDatabasePages))&&X("identity_mismatch")}#S(e){(typeof e.intent!="string"||Buffer.byteLength(e.intent)>mn)&&X("reconciliation_required");let n;try{n=Ur(JSON.parse(e.intent))}catch{return X("reconciliation_required")}return(n.json!==e.intent||n.digest!==e.digest||n.intent.claimId!==e.claim_id||go(n.intent)!==e.subject_key||n.intent.applicationScopeId!==e.application_scope_id||n.intent.endUserId!==e.end_user_id||BigInt(n.total.bytes)!==e.bytes||BigInt(n.total.records)!==e.records)&&X("reconciliation_required"),n}#I(e,n,r,i=!1){(!e||typeof e.claims!="bigint"||typeof e.bytes!="bigint"||typeof e.records!="bigint")&&X("reconciliation_required");let o={claims:e.claims,bytes:e.bytes,records:e.records},s=i?0n:1n;return(o.claims<s||o.bytes<s||o.records<s||o.claims>BigInt(this.#t.maxAllocationRecords)||o.bytes>BigInt(r.bytes)||o.records>BigInt(r.records)||o.claims===0n!=(o.bytes===0n&&o.records===0n)||o.bytes<o.claims||o.records<o.claims||e.digest!==Fr(n,o))&&X("reconciliation_required"),o}#R(){let e=this.#e("SELECT * FROM budget_catalog LIMIT 2").all();return(e.length!==1||e[0]?.id!==1n)&&X("reconciliation_required"),this.#I(e[0],"catalog",this.#t.limits.host,!0)}#_(){let e=this.#e("SELECT COUNT(*) AS n,COALESCE(SUM(length(CAST(intent AS BLOB))),0) AS bytes,COALESCE(MAX(length(CAST(intent AS BLOB))),0) AS maximum FROM budget_claim").get();(typeof e.n!="bigint"||e.n>BigInt(this.#t.maxAllocationRecords)||typeof e.maximum!="bigint"||e.maximum>BigInt(mn)||typeof e.bytes!="bigint"||e.bytes>BigInt(this.#t.maxAllocationRecords)*BigInt(mn))&&X("capacity_exceeded");let n=new Map;for(let s of this.#e("SELECT * FROM budget_claim ORDER BY claim_id").iterate()){let c=this.#S(s),d=fo(c.intent);for(let l=0;l<d.length;l++){let p=d[l],u=ho(n.get(p)??zr(),c),v=[this.#t.limits.host,this.#t.limits.application,this.#t.limits.endUser][l];(u.bytes>BigInt(v.bytes)||u.records>BigInt(v.records))&&X("capacity_exceeded"),n.set(p,u)}}this.#e("SELECT COUNT(*) AS n FROM budget_counter").get()?.n!==BigInt(n.size)&&X("reconciliation_required");for(let s of this.#e("SELECT * FROM budget_counter").iterate()){let c=typeof s.bucket=="string"?n.get(s.bucket):void 0;(!c||!or(c,this.#I(s,s.bucket,this.#t.limits.host)))&&X("reconciliation_required")}let i=this.#R(),o=n.get(Ie(["host"]))??zr();if((i.claims!==e.n||!or(i,o))&&X("reconciliation_required"),this.#C()){let s=this.#e("SELECT COUNT(*) AS n FROM budget_claim_physical").get()?.n;(typeof s!="bigint"||s>i.claims)&&X("reconciliation_required");for(let c of this.#e("SELECT claim_id FROM budget_claim_physical").iterate())(typeof c.claim_id!="string"||!this.#e("SELECT 1 FROM budget_claim WHERE claim_id=?").get(c.claim_id))&&X("reconciliation_required"),this.#w(c.claim_id)}}#m(e){let n=this.#e(`SELECT claim_id,subject_key,application_scope_id,end_user_id,digest,bytes,records,
|
|
15
|
-
CASE WHEN length(CAST(intent AS BLOB))<=${mn} THEN intent ELSE NULL END AS intent FROM budget_claim WHERE claim_id=?`).get(e.intent.claimId),r=this.#e("SELECT claim_id FROM budget_claim WHERE subject_key=?").get(go(e.intent));if(!n){r&&X("operation_conflict");return}let i=this.#S(n);return(i.json!==e.json||r?.claim_id!==e.intent.claimId)&&X("operation_conflict"),i}#d(e,n){let r=this.#R(),i=fo(e.intent),o=[r.claims>0n,!!this.#e("SELECT 1 FROM budget_claim WHERE application_scope_id=? LIMIT 1").get(e.intent.applicationScopeId),!!this.#e("SELECT 1 FROM budget_claim WHERE application_scope_id=? AND end_user_id=? LIMIT 1").get(e.intent.applicationScopeId,e.intent.endUserId)],s=[this.#t.limits.host,this.#t.limits.application,this.#t.limits.endUser],c=i.map((d,l)=>{let p=this.#e("SELECT * FROM budget_counter WHERE bucket=?").get(d);!!p!==o[l]&&X("reconciliation_required");let u=p?this.#I(p,d,s[l]):zr();return n&&(u.claims<1n||u.bytes<BigInt(n.total.bytes)||u.records<BigInt(n.total.records))&&X("reconciliation_required"),u});or(r,c[0])||X("reconciliation_required");for(let d=1;d<c.length;d++){let l=c[d],p=c[d-1];(l.claims>p.claims||l.bytes>p.bytes||l.records>p.records)&&X("reconciliation_required")}return{catalog:r,counters:c}}#v(e,n){let r=this.#m(e);return r?.json!==n?.json&&X("reconciliation_required"),r}#b(e,n){(!or(e.catalog,n.catalog)||e.counters.some((r,i)=>!or(r,n.counters[i])))&&X("reconciliation_required")}#h(e){this.#c&&X("closed"),this.#s&&(this.#a=!0,X("reentrant")),this.#r&&X("reconciliation_required"),this.#s=!0,this.#a=!1;try{this.#g();let n=e();return this.#a&&X("reentrant"),n}catch(n){return vo(n)}finally{this.#s=!1}}#l(e,n){let r=this.#p(Object.freeze({operation:n,applicationScopeId:e.intent.applicationScopeId,endUserId:e.intent.endUserId,sessionId:e.intent.sessionId}));Io.isPromise(r)&&(Ce(r),X("invalid_input")),r!==void 0&&X("invalid_input"),this.#a&&X("reentrant"),this.#g()}#u(){try{this.#n.isTransaction&&this.#n.exec("ROLLBACK")}catch{this.#r=!0}}#A(e){let n=this.#y.get(e.intent.claimId);return n||(n=Object.freeze(Object.create(null)),this.#y.set(e.intent.claimId,n),Ao.set(n,{owner:this,prepared:e,read:()=>this.#k(e.intent)})),n}validate(){this.#h(()=>{this.#n.exec("BEGIN");try{this.#_(),this.#g()}finally{this.#u()}this.#r&&X("reconciliation_required")})}allocate(e){let n=Ur(e);return this.#h(()=>{(this.#o||this.#f)&&X("reconciliation_required"),this.#l(n,"allocate");let r=!1;try{this.#n.exec("BEGIN IMMEDIATE");let i=this.#m(n),o=this.#d(n,i);if(i)return this.#l(n,"allocate"),this.#b(this.#d(n,this.#v(n,i)),o),this.#u(),this.#r&&X("reconciliation_required"),this.#A(i);o.catalog.claims>=BigInt(this.#t.maxAllocationRecords)&&X("capacity_exceeded");let s=fo(n.intent),c=[this.#t.limits.host,this.#t.limits.application,this.#t.limits.endUser],d={catalog:ho(o.catalog,n),counters:o.counters.map(l=>ho(l,n))};for(let l=0;l<s.length;l++){let p=d.counters[l];(p.bytes>BigInt(c[l].bytes)||p.records>BigInt(c[l].records))&&X("capacity_exceeded"),this.#e("INSERT INTO budget_counter VALUES (?,?,?,?,?) ON CONFLICT(bucket) DO UPDATE SET claims=excluded.claims,bytes=excluded.bytes,records=excluded.records,digest=excluded.digest").run(s[l],p.claims,p.bytes,p.records,Fr(s[l],p))}return this.#e("INSERT INTO budget_claim VALUES (?,?,?,?,?,?,?,?)").run(n.intent.claimId,go(n.intent),n.intent.applicationScopeId,n.intent.endUserId,n.json,n.digest,BigInt(n.total.bytes),BigInt(n.total.records)),this.#e("UPDATE budget_catalog SET claims=?,bytes=?,records=?,digest=? WHERE id=1").run(d.catalog.claims,d.catalog.bytes,d.catalog.records,Fr("catalog",d.catalog)),this.#l(n,"allocate"),this.#b(this.#d(n,this.#v(n,n)),d),r=!0,this.#n.exec("COMMIT"),this.#g(),this.#A(n)}catch(i){if(this.#u(),r)return this.#o=n,X("commit_unknown");throw this.#r&&X("reconciliation_required"),i}})}query(e){return this.#k(e)}#k(e){let n=Ur(e);return this.#h(()=>{this.#o&&this.#o.json!==n.json&&X("reconciliation_required"),this.#l(n,"query");let r;try{this.#n.exec("BEGIN"),r=this.#m(n);let i=this.#d(n,r);this.#l(n,"query"),this.#b(this.#d(n,this.#v(n,r)),i)}catch(i){throw this.#u(),i}return this.#u(),this.#r&&X("reconciliation_required"),this.#o=void 0,r?this.#A(r):null})}close(){if(this.#s&&(this.#a=!0,X("reentrant")),!this.#c)try{this.#n.close(),this.#c=!0}catch(e){vo(e)}}#C(){return!!this.#e("SELECT 1 FROM sqlite_master WHERE type='table' AND name='budget_claim_physical'").get()}#w(e){this.#C()||X("reconciliation_required");let n=this.#e(`SELECT attempt_id,plan_digest,state,digest,CASE WHEN physical_json IS NULL OR length(CAST(physical_json AS BLOB))<=${mn} THEN physical_json ELSE '!' END AS physical_json FROM budget_claim_physical WHERE claim_id=?`).get(e);if(!n)return null;try{let r=qt(n.attempt_id),i=sr(n.plan_digest);n.state!=="building"&&n.state!=="bound"&&X("reconciliation_required");let o=n.physical_json===null?null:JSON.parse(n.physical_json);n.state==="building"!=(o===null)&&X("reconciliation_required");let s={attemptId:r,planDigest:i,state:n.state,physical:o};return(n.physical_json!==null&&Ie(o)!==n.physical_json||z(Ie([e,s]))!==n.digest)&&X("reconciliation_required"),Pn(s)}catch{return X("reconciliation_required")}}#B(e,n,r){sr(n),qt(r);let i=Ie([e.json,n,r]),o=(s,c)=>this.#h(()=>{(this.#o||this.#f&&(s!=="read"||this.#f!==i))&&X("reconciliation_required"),this.#l(e,s==="read"?"query":"allocate");let d=!1;try{this.#n.exec(s==="read"?"BEGIN":"BEGIN IMMEDIATE");let l=this.#m(e);l||X("reconciliation_required");let p=this.#d(e,l),u=this.#w(e.intent.claimId);u&&(u.planDigest!==n||u.state==="building"&&u.attemptId!==r)&&X("operation_conflict");let v=u,g=!1;if(s==="begin"&&!u&&(v={attemptId:r,planDigest:n,state:"building",physical:null},g=!0),s==="bind"){(!u||u.attemptId!==r||c===null||c===void 0)&&X("operation_conflict");let b=Ie(c);Buffer.byteLength(b)>mn&&X("capacity_exceeded"),u.state==="bound"&&Ie(u.physical)!==b&&X("operation_conflict"),v={attemptId:r,planDigest:n,state:"bound",physical:JSON.parse(b)},g=u.state!=="bound"}return g&&v&&this.#e("INSERT INTO budget_claim_physical VALUES (?,?,?,?,?,?) ON CONFLICT(claim_id) DO UPDATE SET state=excluded.state,physical_json=excluded.physical_json,digest=excluded.digest").run(e.intent.claimId,v.attemptId,v.planDigest,v.state,v.physical===null?null:Ie(v.physical),z(Ie([e.intent.claimId,v]))),this.#l(e,s==="read"?"query":"allocate"),this.#b(this.#d(e,this.#v(e,l)),p),Ie(this.#w(e.intent.claimId))!==Ie(v)&&X("reconciliation_required"),g?(d=!0,this.#n.exec("COMMIT"),this.#g()):(this.#u(),this.#r&&X("reconciliation_required")),s==="read"&&(this.#f=void 0),Pn(v)}catch(l){throw this.#u(),d&&(this.#f=i,X("commit_unknown")),this.#r&&X("reconciliation_required"),l}});return Object.freeze({root:Object.freeze({...this.#i.parent}),budgetIdentityDigest:z(Ie(this.#i)),read:()=>o("read"),begin:()=>o("begin")??X("reconciliation_required"),bind:s=>o("bind",s)??X("reconciliation_required")})}};function So(t,e){let n=Ao.get(t);return(!n||n.owner!==e)&&X("identity_mismatch"),n.read()!==t&&X("reconciliation_required"),Pn({intent:n.prepared.intent,total:{...n.prepared.total},intentDigest:n.prepared.digest})}function Ro(t,e,n,r){let i=Ao.get(t);return(!i||i.owner!==e||i.read()!==t)&&X("identity_mismatch"),(wo.get(e)??X("identity_mismatch")).access(i.prepared,n,r)}function Jr(t){return(wo.get(t)??X("identity_mismatch")).locate()}var Tn=new WeakMap,Xr=new Map,Co=new Map,xe=(t,e)=>_(t)===_(e);function $(t="identity_mismatch"){throw new R(t)}var ac=t=>JSON.parse(_(t));function Bo(t){return t&&typeof t=="object"&&(Object.values(t).forEach(Bo),Object.freeze(t)),t}function Ne(t,e){try{let n=ic(t,{bigint:!0}),r=sc(t),i=ic(r,{bigint:!0});return(n.isSymbolicLink()||i.ino===0n||n.ino!==i.ino||n.dev!==i.dev||(e?!i.isDirectory():!i.isFile()))&&$(),{path:r,dev:i.dev.toString(),ino:i.ino.toString()}}catch{return $()}}function cc(t){cr.isPromise(t)&&(Ce(t),$("invalid_input"));let e=P(t,["scope","sessionId"]),n=P(e.scope,["applicationScopeId","endUserId","authorizationRevision"]);return(typeof e.sessionId!="string"||[...e.sessionId].length<1||[...e.sessionId].length>512||typeof n.applicationScopeId!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(n.applicationScopeId)||typeof n.endUserId!="string"||[...n.endUserId].length<1||[...n.endUserId].length>512||typeof n.authorizationRevision!="string"||!/^(0|[1-9][0-9]{0,18})$/.test(n.authorizationRevision)||BigInt(n.authorizationRevision)>9223372036854775807n)&&$("invalid_input"),Bo(ac(t))}function En(t){return cc(t.readAuthority())}function _o(t){Xr.get(t.groupPath)===t&&Xr.delete(t.groupPath)}function Yd(t,e,n){let r=t.options.assertOpenAuthorized({operation:n,claimId:t.intent.claimId,scope:e.scope,sessionId:e.sessionId});cr.isPromise(r)&&Ce(r),r!==void 0&&$("invalid_input");let i=En(t.options);t.reentered&&$("reentrant"),(!xe(i,e)||i.sessionId!==t.authority.sessionId||i.scope.applicationScopeId!==t.authority.scope.applicationScopeId||i.scope.endUserId!==t.authority.scope.endUserId)&&$(),(!xe(Jr(t.options.budget),t.root)||!xe(Nt(t.options.storeIdentity,i.sessionId,i.scope),t.store))&&$()}function qn(t,e,n){let{role:r,directoryName:i,...o}=e;return{...o,path:Zt(t.groupPath,i,"spool.sqlite"),mode:n}}function dc(t,e){return _({format:"sdk2-budget-spool-v1",budgetIdentityDigest:t.root.budgetIdentityDigest,claimId:t.intent.claimId,intentDigest:z(_(t.intent)),planDigest:t.digest,role:e.role,optionsDigest:z(_(e)),...Yr(t)})}function Yr(t){return t.role==="remote-source"?{installationRole:"remote-source"}:{}}function Zd(t,e){return(!Array.isArray(t)||t[0]?.role!=="capture"||t[0]?.format!=="sdk2-spool-v2"||(e==="local-receiver"?t.length!==2||t[1]?.role!=="source"||t[1]?.format!=="sdk2-spool-v1":t.length!==1))&&$("invalid_input"),t}function Qd(t,e,n){let r=rt(n.owner,{storeIdentity:t.options.storeIdentity,sessionId:e.sessionId,slot:n.slot}),i=qn(t,t.databases[0],"recover");(!xe(r.root.physical.store,t.store)||r.root.physical.spool.path!==sc(i.path)||r.root.physical.spool.storeId!==i.storeId||!xe(r.root.physical.spool,{...Ne(i.path,!1),storeId:i.storeId})||r.root.registration.scope.applicationScopeId!==e.scope.applicationScopeId||r.root.registration.scope.endUserId!==e.scope.endUserId)&&$()}function Py(t){let e=P(t,["budget","storeIdentity","claimId","databases","readAuthority","assertOpenAuthorized"],["role"]);e.role!==void 0&&e.role!=="local-receiver"&&e.role!=="remote-source"&&$("invalid_input");for(let v of["readAuthority","assertOpenAuthorized"])(typeof e[v]!="function"||cr.isProxy(e[v]))&&$("invalid_input");let n={...e},r=n.role??"local-receiver",i=En(n),o=Jr(n.budget),s=Nt(n.storeIdentity,i.sessionId,i.scope),c=Zd(ac(n.databases),r);for(let v of c)P(v,["role","directoryName","format","storeId","bindings","globalLimit","maxReservations","maxOperations","maxEntries","maxDatabasePages"]),wr({...v,inventory:{status:"known",kind:"initial",reservations:[],entries:[]}}),v.bindings.some(g=>g.applicationScopeId!==i.scope.applicationScopeId||g.endUserId!==i.scope.endUserId)&&$();r==="local-receiver"&&c[1].bindings.some(v=>!c[0].bindings.some(g=>g.bindingId===v.bindingId))&&$();let d=z(_(r==="local-receiver"?c:{role:r,databases:c})),l=rc({claimId:n.claimId,applicationScopeId:i.scope.applicationScopeId,endUserId:i.scope.endUserId,sessionId:i.sessionId,storeIdentityDigest:z(_(s)),configurationDigest:d,databases:c.map(v=>({storeId:v.storeId,directoryName:v.directoryName,bindingsDigest:z(_(v.bindings)),limit:v.globalLimit,maxReservations:v.maxReservations,maxOperations:v.maxOperations,maxEntries:v.maxEntries,maxDatabasePages:v.maxDatabasePages}))}),p=Object.freeze(Object.create(null)),u={options:n,authority:i,role:r,store:s,root:o,intent:l,digest:d,groupPath:Zt(o.root.path,".sdk2-budget-bindings",z(_(l))),databases:Bo(c),attemptId:Vd(),busy:!1,reentered:!1,completed:!1};return xe(En(n),i)||$(),Tn.set(p,u),p}function lc(t){let e=Tn.get(t)??$(),n=qn(e,e.databases[0],"recover");return Object.freeze({path:n.path,storeId:n.storeId})}function Ey(t,e){return el(t,[e])[0].value}function el(t,e){let n=[...e];return(n.length<1||n.length>256||new Set(n).size!==n.length||n.some(r=>typeof r!="string"||!/^[A-Za-z0-9._~-]{1,128}$/.test(r)))&&$("invalid_input"),uc(t,r=>tl(r,n))}function tl(t,e){let n=[];for(let r of e){let i=t.prepare(`SELECT length(CAST(intent_digest AS BLOB)) AS intent_bytes,length(CAST(state AS BLOB)) AS state_bytes,
|
|
16
|
-
length(CAST(commit_digest AS BLOB)) AS commit_bytes,length(CAST(entry_ids AS BLOB)) AS ids_bytes
|
|
17
|
-
FROM capture_ops WHERE binding_id='control' AND operation_key=?`).get(r),o=t.prepare("SELECT length(CAST(metadata AS BLOB)) AS bytes FROM entries WHERE binding_id='control' AND entry_id=?").get(r),s=null;if(!i)o&&$();else{(i.intent_bytes!==64||i.state_bytes!==8&&i.state_bytes!==9||!(i.commit_bytes===null||i.commit_bytes===64)||!(i.ids_bytes===null||typeof i.ids_bytes=="number"&&i.ids_bytes<=256))&&$();let c=t.prepare("SELECT intent_digest,original_bytes,original_records,terminal_bytes,terminal_records,state,commit_digest,entry_ids FROM capture_ops WHERE binding_id='control' AND operation_key=?").get(r);if((c.original_bytes!==16384||c.original_records!==1||c.terminal_bytes!==1||c.terminal_records!==1)&&$(),c.state==="reserved")(o||c.commit_digest!==null||c.entry_ids!==null)&&$(),s={state:"reserved",metadata:null};else{(c.state!=="committed"||!o||typeof o.bytes!="number"||o.bytes>16e3)&&$();let d=t.prepare("SELECT operation_key,basket,metadata,metadata_bytes,body_sha,body_bytes,length(body) AS bytes FROM entries WHERE binding_id='control' AND entry_id=?").get(r),l=z(""),p=typeof d.metadata=="string"?z(d.metadata):"";if(/^host-record-retention-[1-9][0-9]{0,2}-complete$/.test(r)){let u=n.find(g=>g.operationKey===r.slice(0,-9))?.value;(u?.state!=="committed"||!u.metadata)&&$("reconciliation_required");let v=Ii(JSON.parse(u.metadata));_(Es(v))!==d.metadata&&$("reconciliation_required"),p=z(u.metadata)}if(r===Gn.completed){let u=n.find(g=>g.operationKey===Gn.intent)?.value;(u?.state!=="committed"||!u.metadata)&&$("reconciliation_required");let v=kn(JSON.parse(u.metadata));_(Ts(v))!==d.metadata&&$("reconciliation_required"),p=z(u.metadata)}(d.operation_key!==r||d.basket!=="original"||typeof d.metadata!="string"||Buffer.byteLength(d.metadata)!==o.bytes||d.metadata_bytes!==o.bytes||d.body_bytes!==0||d.bytes!==0||d.body_sha!==l||c.intent_digest!==p||c.entry_ids!==JSON.stringify([r])||c.commit_digest!==z(JSON.stringify([[r,"original",d.metadata,0,l]])))&&$(),s={state:"committed",metadata:d.metadata}}}n.push({operationKey:r,value:s})}return Object.freeze(n.map(r=>Object.freeze(r)))}function uc(t,e){let n=Tn.get(t)??$();n.busy&&(n.reentered=!0,$("reentrant")),n.busy=!0,n.reentered=!1;try{let r=En(n.options),i=()=>{n.reentered&&$("reentrant"),(!xe(En(n.options),r)||!xe(r,n.authority)||!xe(Jr(n.options.budget),n.root)||!xe(Nt(n.options.storeIdentity,r.sessionId,r.scope),n.store))&&$()};i();let o=n.options.budget.query(n.intent)??$("reconciliation_required"),s=So(o,n.options.budget);xe(s.intent,n.intent)||$();let c=Ro(o,n.options.budget,n.digest,n.attemptId),d=c.read();d?.state!=="bound"&&$("reconciliation_required");let l={...Yr(n),root:Ne(Zt(n.root.root.path,".sdk2-budget-bindings"),!0),group:Ne(n.groupPath,!0),store:n.store,databases:n.databases.map(A=>({role:A.role,directory:Ne(Zt(n.groupPath,A.directoryName),!0),spool:{...Ne(qn(n,A,"recover").path,!1),storeId:A.storeId},optionsDigest:z(_(A))}))};xe(d.physical,l)||$();let p=n.databases[0],u=qn(n,p,"recover"),v={format:u.format,storeId:u.storeId,hostBudget:dc(n,p),bindings:JSON.stringify(u.bindings.map(({bindingId:A,applicationScopeId:S,endUserId:k})=>[A,S,k]).sort((A,S)=>A[0]<S[0]?-1:A[0]===S[0]?0:1))},{DatabaseSync:g}=Xd(import.meta.url)("node:sqlite"),b=new g(u.path,{readOnly:!0});try{b.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=0; BEGIN");let A=b.prepare("PRAGMA page_count").get()?.page_count;(typeof A!="number"||A<1||A>u.maxDatabasePages)&&$("capacity_exceeded");for(let[k,I]of Object.entries(v)){let m=b.prepare("SELECT length(CAST(value AS BLOB)) AS bytes FROM spool_meta WHERE key=?").get(k);(!m||m.bytes!==Buffer.byteLength(I))&&$(),b.prepare("SELECT value FROM spool_meta WHERE key=?").get(k)?.value!==I&&$()}let S=e(b,u,r);b.exec("ROLLBACK"),i();for(let k of[l.root,l.group,l.store,...l.databases.flatMap(I=>[I.directory,I.spool])])xe(Ne(k.path,!("storeId"in k)),"storeId"in k?{path:k.path,dev:k.dev,ino:k.ino}:k)||$();return xe(c.read(),d)||$(),S}finally{b.close()}}finally{n.busy=!1}}function qy(t,e){let n=P(e,["digest","retentionRevision"]);return(typeof n.digest!="string"||!/^[a-f0-9]{64}$/.test(n.digest)||!Vr(n.retentionRevision))&&$("invalid_input"),uc(t,(r,i,o)=>{let s=r.prepare(`SELECT COUNT(*) AS count,COALESCE(SUM(length(CAST(operation_key AS BLOB))+
|
|
18
|
-
length(CAST(intent_digest AS BLOB))+length(CAST(state AS BLOB))+COALESCE(length(CAST(commit_digest AS BLOB)),0)+
|
|
19
|
-
COALESCE(length(CAST(entry_ids AS BLOB)),0)),0) AS bytes FROM capture_ops WHERE binding_id='control'`).get(),c=r.prepare(`SELECT COUNT(*) AS count,COALESCE(SUM(length(CAST(metadata AS BLOB))+
|
|
20
|
-
length(CAST(entry_id AS BLOB))+length(CAST(operation_key AS BLOB))+length(CAST(basket AS BLOB))+length(CAST(body_sha AS BLOB))),0) AS bytes,
|
|
21
|
-
COALESCE(MAX(length(CAST(metadata AS BLOB))),0) AS maximum FROM entries WHERE binding_id='control'`).get();(![s.count,s.bytes,c.count,c.bytes,c.maximum].every(u=>typeof u=="number"&&Number.isSafeInteger(u)&&u>=0)||Number(s.count)>Math.min(i.maxOperations,4096)||Number(c.count)>Math.min(i.maxEntries,4096)||Number(c.maximum)>262144||Number(s.bytes)+Number(c.bytes)>16777216)&&$("capacity_exceeded");let d=r.prepare(`SELECT e.entry_id,e.operation_key,e.basket,e.metadata,e.metadata_bytes,e.body_sha,e.body_bytes,length(e.body) AS body_size,
|
|
22
|
-
o.intent_digest,o.original_bytes,o.original_records,o.terminal_bytes,o.terminal_records,o.state,o.commit_digest,o.entry_ids
|
|
23
|
-
FROM entries e LEFT JOIN capture_ops o ON o.binding_id=e.binding_id AND o.operation_key=e.operation_key
|
|
24
|
-
WHERE e.binding_id='control' ORDER BY e.entry_id`).all(),l=new Map,p=[];for(let u of d){let v=u.entry_id;typeof v!="string"&&$("reconciliation_required");let g=v.startsWith("history-lineage-"),b=v.startsWith("host-run-facts-"),A=v.startsWith("host-rewrite-facts-");if(!g&&!b&&!A)continue;(u.operation_key!==v||u.state!=="committed"||u.basket!=="original"||typeof u.metadata!="string"||u.metadata_bytes!==Buffer.byteLength(u.metadata)||u.body_bytes!==0||u.body_size!==0||u.body_sha!==z("")||u.original_records!==1||u.terminal_bytes!==1||u.terminal_records!==1||u.original_bytes!==(g?Number(u.metadata_bytes)+64:16384)||Number(u.metadata_bytes)+64>Number(u.original_bytes)||u.entry_ids!==JSON.stringify([v])||u.intent_digest!==z(g?u.metadata:v)||u.commit_digest!==z(JSON.stringify([[v,"original",u.metadata,0,z("")]])))&&$("reconciliation_required");let S=oc(u.metadata);if(g){P(S,["format","storeCommitId","sourceSnapshotDigest","workId","baselineSequence","retentionRevision","origins"]),(S.format!=="serve-archive-lineage-v1"||!Yt(S.storeCommitId)||!Yt(S.workId,256)||typeof S.sourceSnapshotDigest!="string"||!/^[a-f0-9]{64}$/.test(S.sourceSnapshotDigest)||!Vr(S.baselineSequence)||!Vr(S.retentionRevision)||!Array.isArray(S.origins)||S.origins.length>4096||v!=="history-lineage-"+z(S.storeCommitId))&&$("reconciliation_required");for(let q of S.origins){let F=P(q,["recordIds","throughSequence"]);(!Array.isArray(F.recordIds)||F.recordIds.length>128||new Set(F.recordIds).size!==F.recordIds.length||F.recordIds.some(L=>!Yt(L))||F.throughSequence!==null&&(!Vr(F.throughSequence)||F.throughSequence==="0"))&&$("reconciliation_required")}S.sourceSnapshotDigest===n.digest&&S.retentionRevision===n.retentionRevision&&p.push({commitId:S.storeCommitId,digest:S.sourceSnapshotDigest});continue}P(S,b?["format","slot","ownerEpoch","turnId","captureRunKey","controlRunId","kind","value"]:["format","slot","ownerEpoch","rewriteId","kind","value"]);let k=P(S.slot,["storageBindingId","slotId"]);(S.format!==(b?"sdk2-host-run-v1":"sdk2-host-rewrite-v1")||S.kind!=="facts"||k.storageBindingId!=="control"||!Yt(k.slotId)||!Yt(S.ownerEpoch))&&$("reconciliation_required");let I=b?S.captureRunKey:S.rewriteId;(!Yt(I,256)||b&&(!Yt(S.turnId)||S.controlRunId!=="run-"+z(I))||v!==`host-${b?"run":"rewrite"}-facts-${z(_([k,S.ownerEpoch,I]))}`)&&$("reconciliation_required");let m=b?oc(S.value):P(S.value,["outcome","history","capture","resources"],["recoveryFinish","projection"]);b?P(m,["commit","query","capture"],["recoveryFinish"]):["published","unchanged","compensated"].includes(m.outcome)||$("reconciliation_required"),m.capture!=="confirmed"&&!(A&&m.outcome==="unchanged"&&m.capture==="not-started")&&$("reconciliation_required");let w=P(b?m.query:m.resources,["status","failureCount","omittedFailures"]);(!["completed","failed"].includes(w.status)||![w.failureCount,w.omittedFailures].every(q=>typeof q=="number"&&Number.isSafeInteger(q)&&q>=0))&&$("reconciliation_required");let C=P(b?m.commit:m.history,b?["commitId","target","localHistoryGeneration"]:["confirmedCommitId","target","localHistoryGeneration"]),H=b?C.commitId:C.confirmedCommitId,j=tt({scope:o.scope,target:C.target,nowMs:0}).target;(!Yt(H)||j.sessionId!==o.sessionId||typeof C.localHistoryGeneration!="number"||!Number.isSafeInteger(C.localHistoryGeneration)||C.localHistoryGeneration<0)&&$("reconciliation_required");let x=l.get(H);x!==void 0&&x!==j.sourceSnapshotDigest&&$("reconciliation_required"),l.set(H,j.sourceSnapshotDigest)}return p.some(u=>l.get(u.commitId)===u.digest)})}function Yt(t,e=128){return typeof t=="string"&&t.length>0&&Buffer.byteLength(t)<=e&&!t.includes("\0")&&Buffer.from(t).toString("utf8")===t}function Vr(t){return typeof t=="string"&&/^(0|[1-9][0-9]{0,18})$/.test(t)&&BigInt(t)<=9223372036854775807n}function oc(t){typeof t!="string"&&$("reconciliation_required");let e;try{e=JSON.parse(t)}catch{$("reconciliation_required")}return(!e||typeof e!="object"||Array.isArray(e)||_(e)!==t)&&$("reconciliation_required"),e}function pc(t){return(Tn.get(t)??$()).role}function yc(t,e){let n=Tn.get(t)??$();n.busy&&(n.reentered=!0,$("reentrant"));let r=n.failedOpen;r||$("operation_not_found"),n.busy=!0,n.reentered=!1;try{let i=P(e,["readAuthority"]).readAuthority;(typeof i!="function"||cr.isProxy(i))&&$("invalid_input");let o=()=>{P(e,["readAuthority"]).readAuthority!==i&&$();let l=cc(Reflect.apply(i,void 0,[]));return n.reentered&&$("reentrant"),(P(e,["readAuthority"]).readAuthority!==i||l.sessionId!==n.authority.sessionId||l.scope.applicationScopeId!==n.authority.scope.applicationScopeId||l.scope.endUserId!==n.authority.scope.endUserId)&&$(),l},s=o(),c=()=>{let l=o();(!xe(l,s)||!xe(Ne(n.root.root.path,!0),n.root.root)||!xe(Nt(n.options.storeIdentity,l.sessionId,l.scope),n.store))&&$(),n.reentered&&$("reentrant")};if(c(),r.closed)return;let d=[];for(let l of r.closers)if(!l.closed){c();try{let p=(l.close??$())();cr.isPromise(p)&&Ce(p),p!==void 0&&$("invalid_input"),l.closed=!0,l.close=null}catch(p){d.push(p)}c()}if(d.length)throw new AggregateError(d,"Budget retained spool close failed");c(),r.closed=!0,n.completed=!0,Co.get(n.groupPath)===r&&Co.delete(n.groupPath),_o(n)}finally{n.busy=!1}}async function fc(t,e,n){let r=Tn.get(t)??$();r.busy&&(r.reentered=!0,$("reentrant")),e!=="create"&&e!=="recover"&&$("invalid_input"),(r.completed||Xr.has(r.groupPath))&&$("dependency_held"),r.busy=!0,r.reentered=!1,Xr.set(r.groupPath,r);let i=[],o=[],s=!1,c=!0;try{let d=En(r.options),l=()=>{Yd(r,d,e),e==="recover"&&(n||$("identity_mismatch"),Qd(r,d,n))};if(l(),!r.access){let j;try{j=e==="create"?r.options.budget.allocate(r.intent):r.options.budget.query(r.intent)}catch(q){if(q?.code!=="commit_unknown")throw q;l(),j=r.options.budget.query(r.intent)}l(),j||$("reconciliation_required");let x=So(j,r.options.budget);l(),xe(x.intent,r.intent)||$(),r.access=Ro(j,r.options.budget,r.digest,r.attemptId),l()}let p=r.access,u=p.read();l();let v=Zt(r.root.root.path,".sdk2-budget-bindings"),g;if(e==="create"){u?.state==="bound"&&$("operation_conflict");try{u=p.begin()}catch(j){if(j?.code!=="commit_unknown")throw j;l(),u=p.read()}l(),(u?.state!=="building"||u.attemptId!==r.attemptId)&&$("reconciliation_required");try{ko(v)}catch(j){if(j.code!=="EEXIST")throw j}Ne(v,!0),l();try{ko(r.groupPath)}catch{$("reconciliation_required")}for(let j of r.databases)l(),ko(Zt(r.groupPath,j.directoryName))}else{u?.state!=="bound"&&$("reconciliation_required"),g=u.physical;let j={...Yr(r),root:Ne(v,!0),group:Ne(r.groupPath,!0),store:r.store,databases:r.databases.map(x=>({role:x.role,directory:Ne(Zt(r.groupPath,x.directoryName),!0),spool:{...Ne(qn(r,x,e).path,!1),storeId:x.storeId},optionsDigest:z(_(x))}))};xe(j,g)||$()}let b=[Ne(v,!0),Ne(r.groupPath,!0),...r.databases.map(j=>Ne(Zt(r.groupPath,j.directoryName),!0))],A=()=>{b.forEach(j=>{xe(Ne(j.path,!0),j)||$()})};for(let j of r.databases){l(),A();let x=Object.freeze(Object.create(null));Xa(x,{options:qn(r,j,e),marker:dc(r,j),used:!1,assertCurrent(){c||$(),l(),A()},retainUnclosed(F){o.push(F)}});let q=await Qa(x);i.push(q),l(),A()}let S={...Yr(r),root:b[0],group:b[1],store:r.store,databases:r.databases.map((j,x)=>({role:j.role,directory:b[x+2],spool:_e(i[x],r.options.storeIdentity,d.sessionId,d.scope).identity.spool,optionsDigest:z(_(j))}))},[k,I]=S.databases;if(r.role==="local-receiver"&&k.spool.dev===I.spool.dev&&k.spool.ino===I.spool.ino&&$(),l(),A(),e==="create"){try{u=p.bind(S)}catch(j){if(j?.code!=="commit_unknown")throw j;l(),u=p.read()}l(),(u?.state!=="bound"||!xe(u.physical,S))&&$("reconciliation_required")}else xe(S,g)||$();A(),l();let m=i.map(j=>({close:j.close.bind(j),closed:!1})),w=!1,C=()=>{if(w)return;let j=[];for(let x of m)if(!x.closed)try{x.close(),x.closed=!0}catch(q){j.push(q)}if(j.length)throw new AggregateError(j,"Budget spool group close failed");w=!0;for(let x of i)Ya(x);_o(r)},H=r.role==="local-receiver"?Object.freeze({role:"local-receiver",capture:i[0],source:i[1],close:C}):Object.freeze({role:"remote-source",capture:i[0],close:C});return r.failedOpen=void 0,r.completed=!0,s=!0,H}finally{c=!1;try{if(!s){let d=[];for(let p of i)try{p.close()}catch(u){d.push(u),o.push(p.close.bind(p))}let l={closers:o.map(p=>({close:p,closed:!1})),closed:!1};if(r.failedOpen=l,o.length?Co.set(r.groupPath,l):_o(r),d.length)throw new AggregateError(d,"Budget spool group retained after close failure")}}finally{r.busy=!1}}}var gc=new WeakMap;function ef(t,e){return P(e,["storeIdentity","sessionId","slot","spool","ownerEpoch"]),Ge(e.slot),(gc.get(t)??M("identity_mismatch"))(e)}var Oo=new WeakMap,hc=new WeakMap;function Fi(t,e){let n=hc.get(t)??M("identity_mismatch");return P(e,["storeIdentity","sessionId"]),(n.storeIdentity!==e.storeIdentity||n.sessionId!==e.sessionId)&&M("identity_mismatch"),n.assertCurrent(),n}var Oe=(t,e)=>_(t)===_(e),Qt=(t,e)=>t.sessionId===e.sessionId&&Oe(t.scope,e.scope);function M(t="reconciliation_required"){throw new R(t)}function ft(t){if(t!==null&&typeof t=="object"){for(let e of Object.values(t))ft(e);Object.freeze(t)}return t}function Xe(t,e){return Bt(t,e,0).sourceSnapshotDigest}async function tf(t,e){let n=Oo.get(t)??M("identity_mismatch");return P(e,["storeIdentity","sessionId"]),(n.storeIdentity!==e.storeIdentity||n.sessionId!==e.sessionId)&&M("identity_mismatch"),n.read()}async function hd(t,e,n){let r=Oo.get(t)??M("identity_mismatch");return P(e,["storeIdentity","sessionId"]),(r.storeIdentity!==e.storeIdentity||r.sessionId!==e.sessionId)&&M("identity_mismatch"),(typeof n!="function"||Tt.isProxy(n))&&M("invalid_input"),r.use(n)}function xo(t){if(Tt.isPromise(t)&&(Ce(t),M("invalid_input")),t===null||typeof t!="object"&&typeof t!="function")return;let e=t;for(let n=0;e!==null;n++)(n>=8||Tt.isProxy(e)||Object.getOwnPropertyDescriptor(e,"then")!==void 0)&&M("invalid_input"),e=Object.getPrototypeOf(e)}function nf(t){P(t,["storeIdentity","sessionId","slot","budget","ownerEpoch","readAuthority"],["assertCompletionAuthorized","assertContinuationAuthorized","readCloseAuthority"]),nl(t),t.readCloseAuthority!==void 0&&(typeof t.readCloseAuthority!="function"||Tt.isProxy(t.readCloseAuthority))&&M("invalid_input");let e=pc(t.budget),n=rl(t,{kind:"budget",plan:t.budget,...t.readCloseAuthority?{readCloseAuthority:t.readCloseAuthority}:{}});return Object.freeze(e==="local-receiver"?{role:e,recovery:n.recovery,capture:n.capture,source:n.source}:{role:e,recovery:n.recovery,capture:n.capture})}function nl(t){(!t.storeIdentity||typeof t.storeIdentity!="object"||Tt.isProxy(t.storeIdentity)||typeof t.readAuthority!="function"||Tt.isProxy(t.readAuthority)||t.assertCompletionAuthorized!==void 0&&(typeof t.assertCompletionAuthorized!="function"||Tt.isProxy(t.assertCompletionAuthorized))||t.assertContinuationAuthorized!==void 0&&(typeof t.assertContinuationAuthorized!="function"||Tt.isProxy(t.assertContinuationAuthorized)))&&M("invalid_input"),Ge(t.slot)}function rl(t,e){let{storeIdentity:n,sessionId:r,ownerEpoch:i,readAuthority:o,assertCompletionAuthorized:s,assertContinuationAuthorized:c}=t,d=Object.freeze({...t.slot}),l=e.kind==="bare"?e.options:lc(e.plan),p=!1,u=!1,v=!1,g=0,b,A,S,k,I=!1,m,w,C,H,j=!1,x,q,F,L,a={storeIdentity:n,sessionId:r,slot:d},T=()=>{let f=Reflect.apply(o,void 0,[]);Tt.isPromise(f)&&(Ce(f),M("invalid_input"));let h=P(f,["scope","sessionId","nowMs"]);h.sessionId!==r&&M("identity_mismatch"),(!Number.isSafeInteger(h.nowMs)||h.nowMs<0||Object.is(h.nowMs,-0))&&M("invalid_input");let B=an({...d,scope:h.scope,operation:"binding-create",request:{operationEpoch:"cold-read",requestId:"cold-read"}}).scope;return w&&(B.applicationScopeId!==w.root.registration.scope.applicationScopeId||B.endUserId!==w.root.registration.scope.endUserId)&&M("identity_mismatch"),(u||v)&&M(u?"reentrant":"closed"),{scope:B,sessionId:r,nowMs:h.nowMs}},D=()=>{v&&M("closed");let f=rt(m??M(),a);(!w||f.ownerRootDigest!==w.ownerRootDigest||f.physicalPairDigest!==w.physicalPairDigest)&&M("identity_mismatch"),b&&!Oe(_e(b,n,r,T().scope).identity,w.root.physical)&&M("identity_mismatch"),u&&M("reentrant")},K=f=>{c||M("unsupported_capability"),Qt(T(),f)||M();let h=Reflect.apply(c,void 0,[ft({scope:structuredClone(f.scope),sessionId:r})]);xo(h),h!==void 0&&M("invalid_input"),Qt(T(),f)||M()},V=(f,h)=>{s||M("unsupported_capability"),D(),Qt(T(),h)||M();let B=(w??M()).predecessorOwners.find(N=>N.epoch===f.ownerEpoch);(!B||B.epoch===i||f.finish?.mutation.ownerEpoch!==void 0&&f.finish.mutation.ownerEpoch!==B.epoch)&&M("identity_mismatch");let O=Reflect.apply(s,void 0,[ft({operation:f.kind==="run"?"finish-run":"finish-rewrite",scope:structuredClone(h.scope),sessionId:r,originalOwnerEpoch:B.epoch,workId:f.workId})]);xo(O),O!==void 0&&M("invalid_input"),Qt(T(),h)||M(),D()},Z=f=>p?(u=!0,Promise.reject(new R("reentrant"))):v?Promise.reject(new R("closed")):(p=!0,u=!1,f().then(h=>(u&&M("reentrant"),h)).finally(()=>{p=!1})),re=(f,h,B=!1)=>{D();let O=zt({spool:b??M(),control:A??M(),slot:d,includeWork:B,...f===void 0?{}:{expectedHeadEventDigest:f},...h?{operations:h}:{}});return D(),O},Re=f=>{let h=w?.root??M(),B=f.plan??M();(!f.originalCreate||!f.current||!f.createEventDigest||!Oe(f.current.registration,h.registration)||!Oe(B.slot,d)||B.sessionId!==r||B.ownerRootDigest!==w.ownerRootDigest||B.physicalPairDigest!==w.physicalPairDigest||!Oe(B.createRequest,h.createRequest)||B.createSemanticDigest!==h.createSemanticDigest||!Oe(B.confirmedHistory,h.confirmedHistory))&&M("identity_mismatch"),(nt(d,h.registration,{kind:"binding-create",body:f.originalCreate}).semantic!==h.createSemanticDigest||!Oe(f.originalCreate.request,h.createRequest))&&M("identity_mismatch")},Se=(f,h,B=!1)=>{D(),Qt(T(),h)||M();let O=re(f.headEventDigest);Re(O),(!B&&O.writeBarrier!=="clear"||O.writeBarrier!==f.writeBarrier||!Oe(O.current,f.current)||!Oe(O.plan,f.plan)||f.ready!==null&&!Oe(O.ready,f.ready)||!Oe(O.retirement,f.retirement))&&M()},st=async(f,h,B=!1)=>{Se(f,h,B);let O=await _e(b??M(),n,r,h.scope).read();Se(f,h,B),(!O||!Array.isArray(O.messages))&&M();let N=structuredClone(O.messages);return Xe(r,N)!==Xe(r,O.messages)&&M(),ft(N)},Ze=(f,h,B,O,N,J)=>{let ie=g,ge=ft(structuredClone(B)),me=B.observation.sourceSnapshotDigest,ke=Object.freeze(Object.create(null)),$e=!1,we=!1,pe=()=>{if(($e||ie!==g)&&M("stale_generation"),!N){Se(f,h);return}K(h),D();let ve=re();Xn(ve,w,N.body,N.policy,f.headEventDigest),ve.plan===null&&(!ve.current.epoch.active||h.nowMs>=ve.current.epoch.expiresAtMs)&&M("epoch_expired"),K(h)},de=async()=>{pe();let ve=await _e(b,n,r,h.scope).read();if(pe(),(!ve||!Array.isArray(ve.messages))&&M("stale_generation"),J){let Kt=co(await _e(b,n,r,h.scope).readRuntimeCheckpoint());pe(),(!Oe(Kt,J)||Xe(r,ve.messages)!==Xe(r,J.query.messages))&&M("stale_generation")}else Xe(r,ve.messages)!==me&&M("stale_generation");let Qe=ft(structuredClone(J?.archive.messages??ve.messages));return Xe(r,Qe)!==me&&M("stale_generation"),Object.freeze({history:ge,messages:Qe,source:O,snapshot:f,...J?{runtime:J}:{}})};return Oo.set(ke,{storeIdentity:n,sessionId:r,read:()=>Z(de).catch(ve=>{throw $e=!0,ve}),use:ve=>Z(async()=>{we&&M("stale_generation");let Qe=await de(),Kt=!0,Yo=Object.freeze(Object.create(null)),ui=()=>{Kt||M("stale_generation"),pe()};hc.set(Yo,{storeIdentity:n,sessionId:r,details:Qe,spool:b,owner:m,proof:w,guard:H,...N?{continuation:N,assertContinuationCurrent(){(!Kt||$e||ie!==g)&&M("stale_generation"),K(h),D(),K(h)}}:{},assertCurrent:ui});try{ui(),we=!0;let Zo=ve(Qe,Yo);return xo(Zo),ui(),Zo}finally{Kt=!1}}).catch(Qe=>{throw $e=!0,ua(H??M()),Qe})}),ke},dt=async(f,h=!1)=>{if(m||(C??={storeIdentity:n,sessionId:r,slot:d,scope:f.scope,spool:{path:l.path,storeId:l.storeId},ownerEpoch:i,assertAuthorized(){T(),q&&K(q)}},m=Qs(C),w=rt(m,a),H=xr({storeIdentity:n,sessionId:r,operationKey:cs(w.root.registration,"binding-create",w.root.createRequest),semanticDigest:w.root.createSemanticDigest})),D(),!b){if(e.kind==="bare")b=await Za(e.options);else try{S=await fc(e.plan,"recover",{owner:m,slot:d}),b=S.capture,k=void 0}catch(N){throw k={error:N},N}D(),q&&K(q)}let B=na({owner:m,storeIdentity:n,spool:b,sessionId:r,slot:d,readAuthority(){let N=T();return{scope:N.scope,sessionId:N.sessionId}}});if(Qt(T(),f)||M(),!h&&B.writeBarrier!=="clear"&&M(),!B.current)return null;x=structuredClone(B.current.target),A??=hr({...d,spool:b,readAuthority(N){let J=T();if(N!=="read"){if(N==="query"&&q)return K(q),{scope:J.scope,target:x??M(),nowMs:J.nowMs};let ie=F??M("unsupported_capability");return N!==(ie.work.kind==="run"?"finish-run":"finish-rewrite")&&M("unsupported_capability"),V(ie.work,ie.authority),{scope:J.scope,target:ie.target,nowMs:J.nowMs}}return{scope:J.scope,target:x??M(),nowMs:J.nowMs}}});let O=re(B.headEventDigest);return!h&&O.writeBarrier!=="clear"&&M(),O},y=(f,h)=>{let B=f.work?.active??f.work?.lastCompleted??M(),O=new Map;for(let ie of tr({snapshot:f,work:B}))O.set(_(ie),ie);let N=f,J;for(let ie=0;ie<3&&(N=re(f.headEventDigest,[...O.values()],!0),Oe(N.work,f.work)||M(),J=Et({snapshot:N,work:B}),J.kind!=="verified");ie++){let ge=O.size;for(let me of J.neededOperationKeys)O.set(_(me),me);(O.size===ge||O.size>16)&&M()}if((J?.kind!=="verified"||!J.captureMetadataComplete)&&M(),h){for(let ie of ao({snapshot:N,facts:J}))O.set(_(ie),ie);O.size>16&&M(),N=re(f.headEventDigest,[...O.values()],!0),Oe(N.work,f.work)||M(),J=Et({snapshot:N,work:B}),J.kind!=="verified"&&M()}return{snapshot:N,facts:J}},E=async f=>{let h=await dt(f);if(h===null)return Object.freeze({kind:"prepared-orphan",headEventDigest:null});if(h.plan===null)return(h.current?.state!=="unbound"||h.ready!==null||h.retirement!==null)&&M(),Object.freeze({kind:"prepared-orphan",headEventDigest:h.headEventDigest});if(Re(h),j||Cn(H??M()),h.current?.state==="closed"){h.retirement||M();let ge=await st(h,f),me=await st(h,f);return Xe(r,ge)!==Xe(r,me)&&M(),Se(h,f),j||(ca(H??M()).phase!=="retired"&&(Ft(H??M()),Or(H??M())),j=!0),Object.freeze({kind:"retired",messages:me,snapshot:h})}if((j||h.retirement)&&M(),h=re(h.headEventDigest,void 0,!0),h.work||M(),h.current?.fence!==null||h.work.active!==null){Se(h,f);let ge=h.work.active,me=ge?.kind==="run"?await _e(b,n,r,f.scope).readRuntimeCheckpoint():null;if(Se(h,f),me!==null){let ke=ft(co(me));(!ge||ge.kind!=="run"||!h.ready||h.current?.state!=="active"||!w.predecessorOwners.some(ve=>ve.epoch===ge.ownerEpoch&&ve.epoch!==i))&&M("identity_mismatch");let $e=tr({snapshot:h,work:ge});h=re(h.headEventDigest,$e,!0);let we=ke.query.capture,pe=xa({snapshot:h,work:ge},we.sink);(pe.initial.confirmedCommitId!==ke.archive.history.commitId||pe.initial.target.sourceSnapshotDigest!==ke.archive.history.observation.sourceSnapshotDigest||!Oe(pe.initial.target,h.current.target))&&M("stale_generation");let de=await st(h,f);return Xe(r,de)!==Xe(r,ke.query.messages)&&M("stale_generation"),Se(h,f),Object.freeze({kind:"confirmed",confirmation:Ze(h,f,ke.archive.history,"run",void 0,ke)})}return Object.freeze({kind:"pending-work",snapshot:h})}let B=h.work.lastCompleted,O;if(B){let ge=y(h,!1),me=ge.facts;h=ge.snapshot,(!me.controlCompleted||!Oe(me.target,h.current?.target))&&M(),O=me.history}else O=w.root.confirmedHistory,Oe(h.current?.target,h.plan?.initialTarget)||M();let N=await st(h,f),J=await st(h,f),ie=Xe(r,N);return(O.observation.sessionId!==r||O.observation.sourceSnapshotDigest!==ie||Xe(r,J)!==ie)&&M("stale_generation"),Se(h,f),Object.freeze({kind:"confirmed",confirmation:Ze(h,f,O,B?.kind??"installation")})},ne=Object.freeze({read:()=>Z(async()=>(g++,E(T()))),finishPending:()=>p?(u=!0,Promise.reject(new R("reentrant"))):s?Z(async()=>{g++;let f=T();for(;;){let h=await dt(f,!0);if(!h)return Object.freeze({kind:"prepared-orphan",headEventDigest:null});if(!h.plan||(Re(h),j||Cn(H??M()),h.current?.state==="closed"||j||h.retirement))return L&&M(),E(f);let B=re(h.headEventDigest,void 0,!0);if(B.work||M(),!L&&!B.work.active)return E(f);let O=B.work.active??B.work.lastCompleted??M();V(O,f);let N=y(B,!0),{snapshot:J,facts:ie}=N,ge;if(!L&&(ie.controlCompleted&&M(),J.writeBarrier!=="clear")){(O.kind!=="rewrite"||!B.work.active)&&M();let de=ao(N);de.length!==1&&M(),ge=de[0]}let me=L!==void 0||ge!==void 0,ke={spool:b,control:A,slot:d,storeIdentity:n,owner:m,assertCurrent(){V(O,f),Se(J,f,me)}},$e=async de=>{for(let ve=0;ve<de;ve++){V(O,f);let Qe=await st(J,f,me);V(O,f),(ie.history.observation.sessionId!==r||Xe(r,Qe)!==ie.history.observation.sourceSnapshotDigest)&&M("stale_generation")}};if(await $e(2),ge){V(O,f),Se(J,f,!0),b.status(ge),V(O,f);let de=re(J.headEventDigest,J.operations.map(ve=>ve.key),!0);(de.writeBarrier!=="clear"||!Oe({...de,writeBarrier:J.writeBarrier},J))&&M(),Se(de,f);continue}if(!L){let de=await Wa(ke,N);V(O,f),Se(J,f),L={evidence:de,facts:ie,mutation:ft(structuredClone(ie.recoveryFinish)),attempt:0,rebase:!1},await $e(1)}let we=L;if($a(we.evidence,ke,{...N,pendingMutation:we.mutation}),we.rebase){(J.writeBarrier!=="clear"||ie.controlCompleted||we.attempt>8)&&M();let de=O.kind==="run"?`finish-${z(_([O.captureRunKey,we.attempt]))}`:`rewrite-finish-${z(_([O.ownerEpoch,O.workId,we.attempt]))}`;we.mutation=ft({...we.facts.recoveryFinish,transitionId:de,expectedRevision:J.current.revision}),we.rebase=!1}V(O,f),Se(J,f,!0),F={work:O,authority:f,target:ie.target};try{let de=A.mutate(we.mutation);(de.control.fence!==null||!Oe(de.control.target,ie.target))&&M()}catch(de){if(de instanceof R&&de.code==="revision_conflict"&&we.attempt<8){V(O,f);let ve=re();if(Re(ve),ve.writeBarrier!=="clear"||ve.current?.fence===null||BigInt(ve.current?.revision??M())<=BigInt(we.mutation.expectedRevision))throw de;we.attempt++,we.rebase=!0;continue}throw de}finally{F=void 0}V(O,f);let pe=await E(f);return L=void 0,pe}}):Promise.reject(new R("unsupported_capability")),continuePrepared:f=>p?(u=!0,Promise.reject(new R("reentrant"))):c?Z(async()=>{g++;let h=T();K(h),P(f,["body","policy"]);let B=ze({kind:"binding-create",body:f.body});B.kind!=="binding-create"&&M("invalid_input");let O=ft(B.body),N=ft(Sn(f.policy));q=h;try{let J=await dt(h,!0);K(h),D(),(!J||!J.current)&&M();let ie=w.root;if((!Oe(O.request,ie.createRequest)||nt(d,ie.registration,B).semantic!==ie.createSemanticDigest)&&M("operation_conflict"),A.query("binding-create",O.request),J=re(),J.writeBarrier!=="clear"&&M(),J.plan){Re(J),Oe(J.originalCreate,O)||M("operation_conflict");let me=await E(h);return me.kind!=="confirmed"&&M("dependency_held"),me.confirmation}Xn(J,w,O,N),(!J.current.epoch.active||h.nowMs>=J.current.epoch.expiresAtMs)&&M("epoch_expired");let ge=ie.confirmedHistory;for(let me=0;me<2;me++){K(h),D(),Xn(re(J.headEventDigest),w,O,N);let ke=await _e(b,n,r,h.scope).read();K(h),D(),Xn(re(J.headEventDigest),w,O,N),(!ke||!Array.isArray(ke.messages)||ge.observation.sessionId!==r||Xe(r,ke.messages)!==ge.observation.sourceSnapshotDigest)&&M("stale_generation")}return Ze(J,h,ge,"installation",Object.freeze({body:O,policy:N}))}finally{q=void 0}}):Promise.reject(new R("unsupported_capability")),close(){if(p&&(u=!0,M("reentrant")),e.kind==="bare"){if(v)return;v=!0,g++,b?.close();return}if(!I){v||(v=!0,g++),p=!0,u=!1;try{if(S)S.close();else if(k){let f=e.readCloseAuthority??M("unsupported_capability");yc(e.plan,{readAuthority(){u&&M("reentrant");let h=f();return u&&M("reentrant"),h}})}u&&M("reentrant"),I=!0}finally{p=!1}}}});gc.set(ne,f=>{p&&(u=!0,M("reentrant")),v&&M("closed"),p=!0,u=!1;try{(!j||f.spool!==b||f.storeIdentity!==n||f.sessionId!==r||f.ownerEpoch!==i||!Oe(f.slot,d))&&M("identity_mismatch");let h=T();D();let B=re();return Re(B),(B.writeBarrier!=="clear"||B.current?.state!=="closed"||!B.retirement||B.ready===null&&B.retirement.record.installedRecordDigest!==null)&&M(),Qt(T(),h)||M(),D(),u&&M("reentrant"),Object.freeze({guard:H??M(),ownerRootDigest:w.ownerRootDigest,physicalPairDigest:w.physicalPairDigest})}finally{p=!1}});let he=f=>{p&&(u=!0,M("reentrant")),v&&M("closed"),p=!0,u=!1;try{let h=T();return D(),Qt(T(),h)||M(),(!S||S.capture!==b)&&M("unsupported_capability"),f==="source"&&S.role!=="local-receiver"&&M("unsupported_capability"),u&&M("reentrant"),f==="capture"?S.capture:S.source}finally{p=!1}};return{recovery:ne,capture:()=>he("capture"),source:()=>he("source")}}var Po=new WeakMap,Zr=(t,e)=>_(t)===_(e);function Ue(t="identity_mismatch"){throw new R(t)}function Qr(t){if(en.isPromise(t)&&(Promise.prototype.then.call(t,void 0,()=>{}),Ue("invalid_input")),t===null||typeof t!="object"&&typeof t!="function")return;let e=t;for(let n=0;e!==null;n++)(n>=8||en.isProxy(e)||Object.getOwnPropertyDescriptor(e,"then")!==void 0)&&Ue("invalid_input"),e=Object.getPrototypeOf(e)}function mc(t){Qr(t),t!==void 0&&Ue("invalid_input")}function jt(t){let e=Po.get(t)??Ue();return e.value.assertCurrent(),e.value}function md(t,e,n){(typeof n!="function"||en.isProxy(n))&&Ue("invalid_input");let r=Po.get(e);r&&(r.reentered=!0,Ue("reentrant"));let i=P(e,["observation","signal","assertCurrent","historyPort"]),o=P(i.observation,["sessionId","sourceSnapshotDigest","localHistoryGeneration"]);(typeof o.sessionId!="string"||!Number.isSafeInteger(o.localHistoryGeneration)||o.localHistoryGeneration<0||!(i.signal instanceof AbortSignal)||en.isProxy(i.signal)||typeof i.assertCurrent!="function"||en.isProxy(i.assertCurrent))&&Ue("invalid_input");let s=i.historyPort,c=P(s,["storeIdentity","read","latestCommit"]);(!c.storeIdentity||typeof c.storeIdentity!="object"||en.isProxy(c.storeIdentity)||typeof c.read!="function"||en.isProxy(c.read)||typeof c.latestCommit!="function"||en.isProxy(c.latestCommit))&&Ue("invalid_input");let d=Fi(t,{storeIdentity:c.storeIdentity,sessionId:o.sessionId}),l=d.details.history,p=Object.freeze({...l.observation,localHistoryGeneration:d.details.runtime===void 0?0:l.observation.localHistoryGeneration}),u=Object.freeze({commitId:l.commitId,observation:p});Zr(o,p)||Ue("stale_generation");let v=()=>{(!b.active||b.reentered)&&Ue("stale_generation"),b.checking&&(b.reentered=!0,Ue("reentrant")),b.checking=!0;try{d.assertCurrent();let A=P(e,["observation","signal","assertCurrent","historyPort"]);(A.signal!==i.signal||A.assertCurrent!==i.assertCurrent||A.historyPort!==s||!Zr(A.observation,p))&&Ue(),AbortSignal.prototype.throwIfAborted.call(i.signal),mc(Reflect.apply(i.assertCurrent,e,[]));let S=P(s,["storeIdentity","read","latestCommit"]);(S.storeIdentity!==d.storeIdentity||S.read!==c.read||S.latestCommit!==c.latestCommit)&&Ue();let k=Reflect.apply(c.latestCommit,s,[]);Qr(k),k!==null&&Ue("stale_generation");let I=Reflect.apply(c.read,s,[]);Qr(I);let m=P(I,["observation","confirmedCommit"]);(!Zr(m.observation,p)||!Zr(m.confirmedCommit,u))&&Ue("stale_generation"),mc(Reflect.apply(i.assertCurrent,e,[])),AbortSignal.prototype.throwIfAborted.call(i.signal),d.assertCurrent(),b.reentered&&Ue("reentrant")}finally{b.checking=!1}},b={value:Object.freeze({...d,history:u,assertCurrent:v}),active:!0,checking:!1,reentered:!1};Po.set(e,b);try{v();let A=n();return Qr(A),v(),A}finally{b.active=!1}}var tn=new WeakMap,ei=new WeakSet,He=(t,e)=>_(t)===_(e);function Dt(t){let e=t.control.read()??ae("operation_not_found"),n=tn.get(t.storeIdentity)?.get(e.registration.sessionId);return(!n||n.options.spool!==t.spool||n.options.control!==t.control||n.options.ownerEpoch!==t.ownerEpoch||!He(n.options.slot,t.slot))&&ae("identity_mismatch"),n.owner.assertCurrent(),n.owner}function ae(t="reconciliation_required"){throw new R(t)}function Ic(t,e){let n=Dt(t),r=t.control.read()??ae(),i=r.registration.sessionId,o=tn.get(t.storeIdentity),s=o?.get(i)??ae(),c=_e(t.spool,t.storeIdentity,i,r.registration.scope).identity,d=pa(n.guard,t.storeIdentity,i,e),l=!1;return()=>{l||(uo(t.spool),(o?.get(i)!==s||ei.has(n))&&ae("identity_mismatch"),d(),Vs({storeIdentity:t.storeIdentity,sessionId:i,scope:r.registration.scope,slot:t.slot,physical:c,ownerEpoch:t.ownerEpoch,ownerRootDigest:n.ownerRootDigest,physicalPairDigest:n.physicalPairDigest}),ei.add(n),o.delete(i),l=!0)}}function bc(t){let e=jo(t,"r");try{return il(e).size>262144&&ae("capacity_exceeded"),ol(e,"utf8")}finally{To(e)}}function gt(t,e){let n=P(t,["observation","signal","assertCurrent","historyPort"]);(vn.isProxy(n.signal)||!(n.signal instanceof AbortSignal)||typeof n.assertCurrent!="function"||vn.isProxy(n.assertCurrent))&&ae("invalid_input");let r=()=>{AbortSignal.prototype.throwIfAborted.call(n.signal);let d=Reflect.apply(n.assertCurrent,t,[]);vn.isPromise(d)&&Promise.prototype.then.call(d,void 0,()=>{}),d!==void 0&&ae("invalid_input"),AbortSignal.prototype.throwIfAborted.call(n.signal)};r();let i=t.historyPort??ae("identity_mismatch"),o=P(i,["storeIdentity","read","latestCommit"]);(o.storeIdentity!==e||typeof o.read!="function"||typeof o.latestCommit!="function"||vn.isProxy(o.read)||vn.isProxy(o.latestCommit))&&ae("identity_mismatch");let s=Reflect.apply(o.latestCommit,i,[]);if(s===null){let d=tn.get(e)?.get(t.observation.sessionId);(!d||d.coldPort!==i||d.coldRead!==o.read||d.coldLatest!==o.latestCommit)&&ae("identity_mismatch");let l=()=>{let u=P(i,["storeIdentity","read","latestCommit"]);(u.storeIdentity!==e||u.read!==d.coldRead||u.latestCommit!==d.coldLatest)&&ae("identity_mismatch")};l(),d.owner.assertCurrent(),l();let p=Reflect.apply(d.coldRead,i,[]);return l(),vn.isPromise(p)&&(Promise.prototype.then.call(p,void 0,()=>{}),ae("invalid_input")),P(p,["observation","confirmedCommit"]),(!He(p.confirmedCommit,d.owner.confirmedHistory)||!He(p.observation,d.owner.confirmedHistory.observation)||t.observation.sessionId!==p.observation.sessionId||t.observation.sourceSnapshotDigest!==p.observation.sourceSnapshotDigest)&&ae("stale_generation"),r(),l(),d.owner.assertCurrent(),l(),r(),l(),structuredClone(d.owner.confirmedHistory)}s===void 0&&ae(),aa(s,e);let c=i.read();return vn.isPromise(c)&&(Promise.prototype.then.call(c,void 0,()=>{}),ae("invalid_input")),P(c,["observation","confirmedCommit"]),(c.confirmedCommit===null||c.confirmedCommit.commitId!==s.commitId||!He(c.confirmedCommit.observation,s.observation)||!He(c.observation,s.observation)||t.observation.sessionId!==c.observation.sessionId||t.observation.sourceSnapshotDigest!==c.observation.sourceSnapshotDigest)&&ae("stale_generation"),r(),structuredClone(c.confirmedCommit)}function Ac(t,e,n){let{spool:r,control:i,storeIdentity:o,ownerEpoch:s}=t,c={...t.slot};lt(r,i),/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(s)||ae("invalid_input");let d=ze({kind:"binding-create",body:e});d.kind!=="binding-create"&&ae("invalid_input");let l=d.body,p=i.read()??ae("operation_not_found");He(p,r.readBindingControl(c))||ae("identity_mismatch");let u=nt(c,p.registration,d),v=tn.get(o),g=v?.get(p.registration.sessionId);if(g){g.coldPort!==void 0&&ae("identity_mismatch"),(g.options.spool!==r||g.options.control!==i||g.options.ownerEpoch!==s||!He(g.options.slot,c)||g.key!==u.key||g.semantic!==u.semantic)&&ae("operation_conflict"),g.owner.assertCurrent();let q=gt(n,o);return He(q,g.owner.confirmedHistory)||ae("stale_generation"),g.owner}(p.state!=="unbound"||p.fence!==null)&&ae("dependency_held"),(!He(l.target,p.target)||l.expectedRevision!==p.revision||l.archive.sourceId!==p.registration.sourceId)&&ae("stale_generation");let b=gt(n,o),A=Object.freeze({...b,observation:Object.freeze({...b.observation})});(A.observation.sessionId!==p.registration.sessionId||A.observation.sourceSnapshotDigest!==l.target.sourceSnapshotDigest)&&ae("stale_generation");let S=_e(r,o,p.registration.sessionId,p.registration.scope).identity,k=z(_(S));Eo(qo(S.store.path,".sdk2-archive-owner.json"))&&ae("format_mismatch");let I={format:"sdk2-store-owner-v2",physical:S,slot:c,registration:p.registration,createRequest:l.request,createSemanticDigest:u.semantic,confirmedHistory:A,owner:{epoch:s,pid:process.pid,host:al()}},m=_(I),w=z(m),C=qo(S.store.path,".sdk2-archive-owner-v2.json"),H=xr({storeIdentity:o,sessionId:p.registration.sessionId,operationKey:u.key,semanticDigest:u.semantic});if(Eo(C)){bc(C)!==m&&ae("identity_mismatch");let q=jo(C,"r+");try{vc(q)}finally{To(q)}}else{let q=jo(C,"wx",384);try{sl(q,m),vc(q)}finally{To(q)}}let j={...t,slot:c},x=Object.freeze({physicalPairDigest:k,ownerRootDigest:w,confirmedHistory:A,guard:H,assertCurrent(){(ei.has(x)||Eo(qo(S.store.path,`.sdk2-installation-owner-${z(_([w,I.owner]))}.json`)))&&ae("identity_mismatch"),lt(r,i);let q=_e(r,o,p.registration.sessionId,p.registration.scope).identity;(!He(q,S)||bc(C)!==m)&&ae("identity_mismatch")}});return v||(v=new Map,tn.set(o,v)),v.set(p.registration.sessionId,{options:j,semantic:u.semantic,key:u.key,owner:x}),x.assertCurrent(),x}function wc(t,e){return Do(t,e,"installation")}function Sc(t,e){return Do(t,e,"continuation")}function Rc(t,e){return Do(t,e,"retirement")}function Do(t,e,n){let r=jt(e),{spool:i,control:o,storeIdentity:s,ownerEpoch:c}=t,d=Object.freeze({...P(t.slot,["storageBindingId","slotId"])});(r.spool!==i||r.storeIdentity!==s||r.owner.ownerEpoch!==c||!He(d,r.proof.root.slot))&&ae("identity_mismatch"),lt(i,o);let l=o.read()??ae("operation_not_found"),p=r.details.snapshot,u=n==="continuation",v=n==="retirement",g=n==="installation"?r.details.runtime:void 0,b=g?g.query.capture.sink:void 0,A=u?r.continuation?.body??ae():p.originalCreate??ae(),S=p.plan,k=l.state==="closing",I=k&&!v;(p.writeBarrier!=="clear"||l.fence!==null&&!b||(u?S!==null||l.state!=="unbound"||p.ready!==null||p.retirement!==null:r.continuation!==void 0||!S||(v?!k||p.ready!==null:l.state!=="active"&&!k||k&&p.ready===null))||!He(l,i.readBindingControl(d))||!He(l,p.current)||!He(l.registration,r.proof.root.registration)||l.registration.sessionId!==r.sessionId||l.target.sourceSnapshotDigest!==r.history.observation.sourceSnapshotDigest||S!==null&&(S.ownerRootDigest!==r.proof.ownerRootDigest||S.physicalPairDigest!==r.proof.physicalPairDigest))&&ae("identity_mismatch");let m=nt(d,l.registration,{kind:"binding-create",body:A});(m.semantic!==r.proof.root.createSemanticDigest||S!==null&&m.semantic!==S.createSemanticDigest)&&ae("identity_mismatch");let w=tn.get(s),C=w?.get(r.sessionId);if(C){let D=C.coldPurpose==="continuation"&&n==="installation"&&l.state==="active";return(C.coldPort!==e.historyPort||!D&&(C.coldClosing!==I||C.coldPurpose!==n)||C.options.control!==o||C.options.spool!==i||C.options.ownerEpoch!==c||!He(C.options.slot,d)||C.semantic!==m.semantic||C.key!==m.key)&&ae("operation_conflict"),He(C.owner.confirmedHistory,r.history)||ae("stale_generation"),C.owner.assertCurrent(),r.assertCurrent(),D&&(C.coldPurpose=n,C.coldClosing=I),C.owner}let H=r.proof.root.physical,j=r.proof.ownerRootDigest,x=r.proof.physicalPairDigest,q={storeIdentity:s,sessionId:r.sessionId,slot:d},F=r.owner,L=l.registration.scope,a=Object.freeze({physicalPairDigest:x,ownerRootDigest:j,confirmedHistory:r.history,guard:r.guard,...b?{resumedRun:b}:{},assertCurrent(){ei.has(a)&&ae("identity_mismatch");let D=rt(F,q);(D.currentOwner.epoch!==c||D.ownerRootDigest!==j||D.physicalPairDigest!==x)&&ae("identity_mismatch"),lt(i,o),He(_e(i,s,q.sessionId,L).identity,H)||ae("identity_mismatch"),rt(F,q)}});a.assertCurrent(),r.assertCurrent(),w||(w=new Map,tn.set(s,w));let T=e.historyPort;return w.set(r.sessionId,{options:{...t,slot:d},semantic:m.semantic,key:m.key,owner:a,coldPort:T,coldClosing:I,coldPurpose:n,coldRead:T.read,coldLatest:T.latestCommit}),a}function ti(t,e){let n=t.control.read()??ae("operation_not_found"),r=tn.get(t.storeIdentity)?.get(n.registration.sessionId);(!r||!r.coldClosing||r.coldPort!==e||r.coldRead!==e.read||r.coldLatest!==e.latestCommit||r.options.spool!==t.spool||r.options.control!==t.control||r.options.ownerEpoch!==t.ownerEpoch||!He(r.options.slot,t.slot)||n.state!=="closing"||n.fence!==null)&&ae("identity_mismatch"),r.owner.assertCurrent()}import{types as gl}from"node:util";import{types as nn}from"node:util";var kc=new WeakMap,cl=new WeakMap,dl=(t,e)=>_(t)===_(e);function jn(){throw new R("reconciliation_required")}function jf(t,e,n,r=!1){let i=t===void 0?void 0:cl.get(t)?.get(e);i&&((!i.ready||!r&&(i.installed===void 0||i.installed!==n))&&jn(),i.assertCurrent())}function Cc(t,e){let n=kc.get(t)??jn();(!n.ready||n.installed)&&jn(),n.installed=e}function ni(t,e){let n=kc.get(t)??jn();return(n.options.spool!==e.spool||n.options.storeIdentity!==e.storeIdentity||n.options.ownerEpoch!==e.ownerEpoch||!dl(n.options.slot,e.slot)||!n.ready)&&jn(),(e.captureBindingId!==void 0&&e.captureBindingId!==n.options.captureBindingId||e.recordBindingId!==void 0&&e.recordBindingId!==n.options.recordBindingId||e.captureBindingId!==void 0&&(e.maxTurnBytes??1048576)!==(n.options.maxTurnBytes??1048576))&&jn(),n.assertCurrent(),n}import{types as dr}from"node:util";function Le(){throw new R("reconciliation_required")}function _c(t,e){let n=t;for(;n!==null;){dr.isProxy(n)&&Le();let r=Object.getOwnPropertyDescriptor(n,e);if(r!==void 0)return Object.hasOwn(r,"value")||Le(),r.value;n=Object.getPrototypeOf(n)}Le()}function bn(t,e){let n=_c(t,e);return(typeof n!="function"||dr.isProxy(n))&&Le(),(...r)=>Reflect.apply(n,t,r)}function ri(t){let e=new Set,n=r=>{if(!(r==null||typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))){(typeof r!="object"||dr.isProxy(r)||e.has(r)||![null,Object.prototype,Array.prototype].includes(Object.getPrototypeOf(r)))&&Le(),e.add(r);for(let i of Reflect.ownKeys(r)){let o=Object.getOwnPropertyDescriptor(r,i);(typeof i!="string"||!Object.hasOwn(o,"value"))&&Le(),n(o.value)}e.delete(r)}};return n(t),JSON.stringify(t)}function Bc(t){if(t!==null&&typeof t=="object"){for(let e of Object.values(t))Bc(e);Object.freeze(t)}return t}var ll=t=>Lt(Buffer.from(t,"utf8"));function xc(t){let e=P(t,["handle","turnId","sessionId","prefixDigest","inputStart"]),n=e.handle;(!n||typeof n!="object"||dr.isProxy(n))&&Le();let r=bn(n,"messages"),i=bn(n,"counters"),o=bn(n,"inputReceipts"),s=bn(n,"inputTarget"),c=_c(n,"events");(c===null||typeof c!="object"||dr.isProxy(c))&&Le();let d=bn(c,"next"),l=bn(c,"return"),p=bn(c,"throw"),u=ri(r()),v=Bc(JSON.parse(u));(!Array.isArray(v)||typeof e.inputStart!="number"||!Number.isSafeInteger(e.inputStart)||e.inputStart<0||e.inputStart>=v.length||ll(ri(v.slice(0,e.inputStart)))!==e.prefixDigest)&&Le();let g=Object.freeze(v.slice(e.inputStart));g.every(x=>x.role==="user")||Le();let b=P(s(),["turnId","open"]);(b.turnId!==e.turnId||b.open!==!0)&&Le();let A=!1,S=!1,k=!1,I=0,m,w=x=>{try{let q=Qo.parse(x);if(q.sessionId!==e.sessionId||q.turnId!==e.turnId||q.source!=="kernel"||q.seq!==I){S=!0;return}I===0&&q.type==="turn.started"?I++:I===1&&q.type==="turn.aborted"&&q.reason!=="internal_error"?(m=Object.freeze({type:"turn.aborted",reason:q.reason}),I++):S=!0}catch{S=!0}},C=async(x,q,F)=>{let L;try{L=(await fr(x(...q))).value;let T=P(L,["value","done"]);return typeof T.done!="boolean"&&Le(),T.done?A=!0:F&&w(T.value),L}catch(a){throw S=!0,a}};return Object.freeze({events:Object.freeze({async next(...x){k&&(S=!0),k=!0;try{return await C(d,x,!0)}finally{k=!1}},async return(x){return A||(S=!0),C(l,[x],!1)},async throw(x){return A||(S=!0),C(p,[x],!1)},[Symbol.asyncIterator](){return this},async[Symbol.asyncDispose](){await this.return()}}),read(){(!A||S||I!==2||m===void 0||k)&&Le(),ri(r())!==u&&Le();let x=P(i(),["modelTurns","toolRounds","consecutiveErrors","queueInjections"],["apiRounds","outputCapEscalations","recoveryAttempts"]);for(let L of["apiRounds","modelTurns","toolRounds","queueInjections"])(!Object.hasOwn(x,L)||x[L]!==0||!Number.isSafeInteger(x[L])||Object.is(x[L],-0))&&Le();let q=P(s(),["turnId","open"]);(q.turnId!==e.turnId||q.open!==!1)&&Le();let F=o();return ri(F),(!Array.isArray(F)||F.some(L=>L.turnId!==e.turnId||!["closed","cancelled"].includes(L.state)))&&Le(),Object.freeze({messages:v,inputMessages:g,terminal:m})}})}import{types as ii}from"node:util";var Ec=new WeakMap;function qc(t,e){let n=Ec.get(t)??G("identity_mismatch");return fi(e,t.sink),n.claimed&&G("operation_conflict"),n.claimed=!0,n.port}var ul="sdk2-host-run-v1",pl=16384,fe=(t,e)=>_(t)===_(e);function G(t){throw new R(t)}function lr(t){(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/u.test(t))&&G("invalid_input")}function Oc(t){(typeof t!="number"||!Number.isSafeInteger(t)||t<0)&&G("invalid_input")}function Pc(t){return ii.isPromise(t)&&(Ce(t),G("invalid_input")),t}function Ho(t){try{return Is(t)}catch{return G("invalid_input")}}function Tc(t){let{spool:e,control:n,gate:r,recording:i,storeIdentity:o,readCurrent:s,ownerEpoch:c}=t,d=Gt(e,n);d==="sdk2-spool-v2"&&t.recoveryOwner!==void 0&&G("format_mismatch");let l=t.recoveryOwner===void 0?void 0:ni(t.recoveryOwner,t),p=d==="sdk2-spool-v2"?Dt(t):void 0,u=l!==void 0||p!==void 0,v=()=>{l?.assertCurrent(),p?.assertCurrent()};lr(c),Ma(i,e),(!o||typeof o!="object"||ii.isProxy(o))&&G("invalid_input");let g={...t.slot};Ge(g);let b=n.read()??G("operation_not_found");fe(e.readBindingControl(g),b)||G("identity_mismatch"),(b.storageBindingId!==g.storageBindingId||b.slotId!==g.slotId)&&G("identity_mismatch"),b.acceptedCapabilities.includes("archive-transfer-v1")||G("unsupported_capability");let A={...b.registration.scope},S=e.bindingIdentity(g.storageBindingId);(A.applicationScopeId!==S.applicationScopeId||A.endUserId!==S.endUserId)&&G("identity_mismatch");let k,I=!1,m=!1,w,C=new Set,H=y=>{m&&(w?.hooks.reentered(),G("reentrant")),m=!0;try{return y()}finally{m=!1}},j=()=>{let y=P(Pc(s()),["target","localHistoryGeneration","confirmedCommitId"]);return Oc(y.localHistoryGeneration),y.confirmedCommitId!==null&&lr(y.confirmedCommitId),{target:tt({scope:A,target:y.target,nowMs:0}).target,localHistoryGeneration:y.localHistoryGeneration,confirmedCommitId:y.confirmedCommitId}},x=y=>({...y.status,querySettlement:y.status.querySettlement===null?null:Ho(y.status.querySettlement)}),q=y=>{y.status={...y.status,stage:"reconciliation-required",failureCount:y.status.failureCount+1}},F=y=>{let E=Ke(y);return C.add(E),E.then(()=>{C.delete(E)},()=>{C.delete(E)}),E.then(({value:U})=>U)},L=(y,E)=>{let U=`host-run-${E}-${z(_([g,y.status.ownerEpoch,y.status.captureRunKey]))}`;return{bindingId:g.storageBindingId,operationKey:U,intentDigest:z(U),originalMax:{bytes:pl,records:1},terminalReserve:{bytes:1,records:1}}},a=(y,E,U)=>{let Q=L(y,E),ce=e.status(Q)??G("reconciliation_required");fe(ce.reservation,Q)||G("operation_conflict");let ne={entryId:Q.operationKey,basket:"original",metadata:_({format:ul,slot:g,ownerEpoch:y.status.ownerEpoch,turnId:y.status.turnId,captureRunKey:y.status.captureRunKey,controlRunId:y.status.controlRunId,kind:E,value:U}),body:new Uint8Array};e.commit({...Q,entries:[ne]})},T=y=>{k!==y&&G("operation_conflict"),v();let E=n.read()??G("operation_not_found");fe(e.readBindingControl(g),E)||G("identity_mismatch"),fe(E.registration,b.registration)||G("identity_mismatch"),(E.fence?.kind!=="run"||E.fence.id!==y.status.controlRunId||E.fence.ownerEpoch!==y.status.ownerEpoch||E.fence.turnId!==y.status.turnId)&&G("operation_conflict")},D=y=>{if(!(y.finalizing||y.status.stage==="settled")&&!y.callbackUnresolved&&!(y.status.capture!=="confirmed"||y.status.query!=="confirmed"||y.status.legacyStore!=="confirmed")){y.finalizing=!0;try{if(v(),!y.finish){T(y);let U=j(),Q=y.commit??G("reconciliation_required");(U.confirmedCommitId!==Q.commitId||U.localHistoryGeneration!==Q.localHistoryGeneration||!fe(U.target,Q.target))&&G("reconciliation_required");let ce=n.read()??G("operation_not_found"),ne={kind:"finish-run",transitionId:`finish-${z(_([y.status.captureRunKey,y.finishAttempt]))}`,expectedRevision:ce.revision,ownerEpoch:y.status.ownerEpoch,runKey:y.status.controlRunId,expectedTarget:Q.target};u&&(y.recoveryFinish??=ne);let he=_({commit:Q,query:{status:y.status.querySettlement.status,failureCount:y.status.querySettlement.failureCount,omittedFailures:y.status.querySettlement.omittedFailures},capture:"confirmed",...y.recoveryFinish===void 0?{}:{recoveryFinish:y.recoveryFinish}});y.finalFacts!==void 0&&y.finalFacts!==he&&G("operation_conflict"),y.finalFacts=he,a(y,"facts",he),y.finish=ne}y.status={...y.status,stage:"finishing"};let E=n.mutate(y.finish);(E.control.fence!==null||!fe(E.control.target,y.commit.target))&&G("reconciliation_required"),y.status={...y.status,stage:"settled"},y.work?.release(),y.work=void 0}catch(E){try{if(E instanceof R&&E.code==="revision_conflict"&&y.finishAttempt<8&&y.finish){let U=n.read();U?.fence?.kind==="run"&&U.fence.id===y.finish.runKey&&U.fence.ownerEpoch===y.status.ownerEpoch&&fe(e.readBindingControl(g),U)&&BigInt(U.revision)>BigInt(y.finish.expectedRevision)&&(y.finish=void 0,y.finishAttempt++)}}finally{q(y)}throw E}finally{y.finalizing=!1}}},K=y=>{let E=Promise.resolve().then(()=>H(()=>D(y)));F(E).catch(()=>{})},V=()=>{let y=n.read(),E=k?x(k):null;return{status:E?.stage==="reconciliation-required"||w!==void 0||(!E||E.stage==="settled")&&y?.fence!=null?"reconciliation-required":C.size>0||E&&E.stage!=="settled"?"pending":"completed",pendingWork:C.size,admissionStopped:I||y?.state!=="active",run:E}},Z=(y,E)=>{let U,Q=(async()=>{let ce=H(()=>{w!==void 0&&G("reconciliation_required");let ne=k??G("reconciliation_required");if(v(),(y.turnId!==ne.status.turnId||typeof y.runKey!="string"||!y.runKey||y.runKey.length>256)&&G("operation_conflict"),ne.status.captureRunKey!==null&&ne.status.captureRunKey!==y.runKey&&G("operation_conflict"),ne.cancelledUnadmitted&&G("operation_conflict"),ne.admitted||yi(e,n,n.read()??G("operation_not_found")),U=ne,ne.prepareEntered=!0,ne.status={...ne.status,captureRunKey:y.runKey,controlRunId:`run-${z(y.runKey)}`,capture:"inflight"},!ne.admit){I&&(E===void 0||ne.inputFinalizer!==E||E.key!==y.runKey)&&G("binding_closed");let he=n.read()??G("operation_not_found");(!fe(j(),ne.initial)||!fe(he.target,ne.initial.target))&&G("stale_generation"),ne.admit={kind:"admit-run",transitionId:`admit-${z(y.runKey)}`,expectedRevision:he.revision,ownerEpoch:c,runKey:ne.status.controlRunId,turnId:ne.status.turnId}}if(!ne.admitted){let he=r.acquireIdle(g,ne.admit.expectedRevision);try{n.mutate(ne.admit,{idleLease:he}),ne.admitted=!0}finally{he.release()}ne.work=r.enterWork()}T(ne),ne.status={...ne.status,stage:"admitted"};for(let he of["intent","history","facts"]){let f=L(ne,he),h=e.status(f);h?fe(h.reservation,f)||G("operation_conflict"):e.reserve(f)}return a(ne,"intent",{initial:ne.initial,store:"host-owned-original-store"}),ne});ce.prepared||(await Ke(i.prepareRun(y)),ce.prepared=!0),H(()=>{if(T(ce),ce.callbackUnresolved&&G("reconciliation_required"),!ce.notified){if(ce.notified=!0,ce.queryEnded||ce.queryHandle?.inputTarget?.().open===!1)return;try{Pc(ce.onAdmitted?.())!==void 0&&G("invalid_input"),fe(j(),ce.initial)||G("stale_generation")}catch(ne){throw ce.callbackUnresolved=!0,ne}}})})();return Q.catch(()=>{U&&(U.status={...U.status,capture:"unresolved"},q(U))}),F(Q)},re={assertReady(){H(()=>{let y=n.read()??G("operation_not_found");if(w?.capturing){dt(w.id),i.assertReady();return}(I||y.state!=="active")&&G("binding_closed"),(y.fence!==null||k&&!["planned","settled"].includes(k.status.stage))&&G("reconciliation_required"),i.assertReady()})},prepareRun(y){return Z(y)},write(y){return w!==void 0?H(()=>{(!w?.capturing||y.kind!=="governance"||y.runKey!==void 0)&&G("operation_conflict"),dt(w.id),w.hooks.beforeWrite(y)}):y.runKey!==void 0&&H(()=>{let E=k??G("operation_conflict");y.runKey!==E.status.captureRunKey&&G("identity_mismatch"),T(E)}),F(i.write(y))},writeTurn(y){let E=k;if(!E||y.runKey!==E.status.captureRunKey||!i.writeTurn)return Promise.reject(new R("operation_conflict"));T(E);let U=Ke(i.writeTurn(y)).then(()=>{E.fullTurn=!0});return F(U)},finishRun(y){let E=k;if(!E||y.runKey!==E.status.captureRunKey)return Promise.reject(new R("operation_conflict"));T(E);let U=Ke(i.finishRun(y)).then(()=>{if(!E.fullTurn||!y.materialsComplete){E.status={...E.status,capture:"unresolved"},q(E);return}E.status={...E.status,capture:"confirmed"},K(E)},Q=>{throw E.status={...E.status,capture:"unresolved"},q(E),Q});return F(U)}},Re=gs(re),Se=y=>(T(y),(!y.prepared||!y.admitted||!y.notified||!y.queryBound||y.queryEnded||y.fullTurn||y.callbackUnresolved||y.commit!==void 0||y.commitRegistered||y.finalizing||y.finish!==void 0||y.status.stage!=="admitted"||y.status.capture!=="inflight"||y.status.query!=="inflight")&&G("reconciliation_required"),{version:1,initial:y.recoveryInitial??y.initial,admission:y.admit,captureRunKey:y.status.captureRunKey});p!==void 0&&Ir(re,{read(y){return H(()=>{let E=k??G("reconciliation_required");return E.status.captureRunKey!==y&&G("identity_mismatch"),{...Se(E),recording:hs(i,y)}})},restore(y,E){H(()=>{let U=k??G("reconciliation_required"),Q=E;(!Q||Q.captureRunKey!==y||!fe(Q,p.resumedRun)||!fe(Se(U),{version:Q.version,initial:Q.initial,admission:Q.admission,captureRunKey:Q.captureRunKey}))&&G("identity_mismatch"),ms(i,y,Q.recording),T(U)})}});let st=y=>Object.freeze({turnId:y.status.turnId,status:()=>x(y),armUnadmittedInput(E){return H(()=>{let U=P(E,["capture","inputStart"]);(k!==y||I||y.inputFinalizer!==void 0||!y.queryBound||y.queryReceipt===void 0||y.queryEnded||y.prepareEntered||y.admit!==void 0||y.status.stage!=="planned"||y.commitRegistered)&&G("reconciliation_required");let Q=U.capture;fi(Q,re);let ce=xc({handle:y.queryHandle,turnId:y.status.turnId,sessionId:y.initial.target.sessionId,prefixDigest:y.initial.target.sourceSnapshotDigest,inputStart:U.inputStart});return y.inputFinalizer={capture:Q,proof:ce},ce.events})},finalizeUnadmittedInput(){return H(()=>{k!==y&&G("operation_conflict");let E=y.inputFinalizer??G("reconciliation_required");if(E.work!==void 0)return E.work;(w!==void 0||C.size>0||!y.queryBound||y.queryReceipt===void 0||!y.queryEnded||y.status.query!=="confirmed"||y.status.stage!=="planned"||y.prepareEntered||y.admit!==void 0||y.admitted||y.prepared||y.notified||y.commit!==void 0||y.commitRegistered||y.work!==void 0||y.status.capture!=="not-started"||y.status.captureRunKey!==null||y.status.controlRunId!==null||y.status.legacyStore!=="not-started"||y.callbackUnresolved||y.cancelledUnadmitted)&&G("reconciliation_required");let U=n.read()??G("operation_not_found");(!fe(U,e.readBindingControl(g))||!fe(U.registration,b.registration))&&G("identity_mismatch"),(U.state!=="active"||U.fence!==null||r.busy)&&G("reconciliation_required"),(!fe(j(),y.initial)||!fe(U.target,y.initial.target))&&G("stale_generation"),i.assertReady();let Q=E.proof.read();E.facts=Q;let ce=f=>H(()=>{(k!==y||y.inputFinalizer!==E||E.key!==f||w!==void 0||y.commitRegistered||y.cancelledUnadmitted||y.status.query!=="confirmed"||!y.queryEnded)&&G("reconciliation_required");let h=n.read()??G("operation_not_found");(!fe(h,e.readBindingControl(g))||!fe(h.registration,b.registration))&&G("identity_mismatch"),(!fe(j(),y.initial)||!fe(h.target,y.initial.target)||!fe(E.proof.read(),Q))&&G("stale_generation"),h.fence===null?(h.state!=="active"||y.admitted||r.busy)&&G("binding_closed"):((!y.admit||!["active","closing"].includes(h.state))&&G("binding_closed"),T(y))}),ne=Re(E.capture,Object.freeze({turnId:y.status.turnId,facts:Q,validate:ce,prepare(f){return E.key!==void 0&&E.key!==f&&G("operation_conflict"),E.key=f,ce(f),Z({runKey:f,turnId:y.status.turnId},E)}})),he=vs(E.capture,re,ne);return E.operation=he,E.work=F(he.outcome.then(()=>(ce(E.key),y.status.capture!=="confirmed"&&G("reconciliation_required"),E.completed=!0,Q),f=>{throw y.status.capture!=="confirmed"&&(y.status={...y.status,capture:"unresolved"},y.status.stage!=="reconciliation-required"&&q(y)),f})),E.work.then(()=>{E.ended=!0},()=>{E.ended=!0}),E.work})},retryUnadmittedInput(){return H(()=>{k!==y&&G("operation_conflict");let E=y.inputFinalizer??G("reconciliation_required");if((!E.work||!E.operation||!E.facts)&&G("reconciliation_required"),!E.ended||E.completed)return E.work;if(E.retry!==void 0)return E.retry;let U=F(E.operation.retryOriginal().then(()=>(y.status.capture!=="confirmed"&&G("reconciliation_required"),E.facts)));return E.retry=U,U.catch(()=>{E.retry===U&&(E.retry=void 0)}),U})},cancelUnadmitted(){H(()=>{if(k!==y&&G("operation_conflict"),y.inputFinalizer!==void 0&&G("reconciliation_required"),y.cancelledUnadmitted)return;(w!==void 0||C.size>0||!y.queryBound||!y.queryEnded||y.status.query!=="confirmed"||y.status.stage!=="planned"||y.prepareEntered||y.admit!==void 0||y.admitted||y.prepared||y.notified||y.commit!==void 0||y.commitRegistered||y.work!==void 0||y.status.capture!=="not-started"||y.status.captureRunKey!==null||y.status.controlRunId!==null||y.status.legacyStore!=="not-started"||y.callbackUnresolved)&&G("reconciliation_required");let E=n.read()??G("operation_not_found");(!fe(E,e.readBindingControl(g))||!fe(E.registration,b.registration))&&G("identity_mismatch"),(E.fence!==null||r.busy)&&G("reconciliation_required"),(!fe(j(),y.initial)||!fe(E.target,y.initial.target))&&G("stale_generation"),i.assertReady(),y.cancelledUnadmitted=!0,y.status={...y.status,stage:"settled"}})},bindQuery(E){H(()=>{(k!==y||y.queryBound)&&G("operation_conflict");let U=P(E,["handle"],["eventsEnded","settle","receipt"]),Q=Object.hasOwn(U,"receipt");(Q?Object.keys(U).length!==2:!Object.hasOwn(U,"eventsEnded")||!Object.hasOwn(U,"settle"))&&G("invalid_input"),Q||Ce(U.eventsEnded);let ce=U.handle;ce.inputTarget?.().turnId!==y.status.turnId&&G("invalid_input");let ne=Q?As(U.receipt,ce):void 0;ne===void 0&&(typeof U.settle!="function"||!ii.isPromise(U.eventsEnded))&&G("invalid_input"),y.queryReceipt=Q?U.receipt:void 0,y.queryBound=!0,y.queryHandle=ce,y.status={...y.status,query:"inflight"};let he=U.settle;try{let f=Ke(ne?.eventsEnded??U.eventsEnded).then(()=>(y.queryEnded=!0,ne===void 0?Ke(he()):Ke(ne.outcome).then(({value:h})=>(h.state!=="fulfilled"&&G("reconciliation_required"),h.result)))).then(({value:h})=>{let B=Ho(h);if(y.status={...y.status,querySettlement:B},!["completed","failed"].includes(B.status)||Object.values(B.pending).some(O=>O!==0)){y.status={...y.status,query:"unresolved"},q(y);return}y.status={...y.status,query:"confirmed"},K(y)}).catch(()=>{y.status={...y.status,query:"unresolved"},q(y)});F(f)}catch(f){throw y.status={...y.status,query:"unresolved"},q(y),f}})},commitHistory(E){H(()=>{(k!==y||!y.admitted||y.status.stage==="settled")&&G("operation_conflict");let U=P(E,["commitId","storeIdentity","target","localHistoryGeneration","outcome"]);Ce(U.outcome),lr(U.commitId),Oc(U.localHistoryGeneration),(U.storeIdentity!==o||!ii.isPromise(U.outcome))&&G("identity_mismatch");let Q=tt({scope:A,target:U.target,nowMs:0}).target;(Q.sessionId!==y.initial.target.sessionId||!fe(Q.generations,y.initial.target.generations))&&G("stale_generation"),(U.localHistoryGeneration<y.initial.localHistoryGeneration||!fe(Q,y.initial.target)&&U.localHistoryGeneration===y.initial.localHistoryGeneration)&&G("stale_generation");let ce={commitId:U.commitId,target:Q,localHistoryGeneration:U.localHistoryGeneration};if(y.commit&&(!fe(y.commit,ce)||y.commitOutcome!==U.outcome)&&G("operation_conflict"),y.commitRegistered)return;let ne=()=>{y.commitRegistered&&(y.status={...y.status,legacyStore:y.commitOutcomeState},y.commitOutcomeState==="confirmed"?K(y):y.commitOutcomeState==="unresolved"&&q(y))};if(!y.commit){y.commit=ce,y.commitOutcome=U.outcome,y.commitOutcomeState="inflight";try{let he=Ke(y.commitOutcome).then(({value:f})=>{let h=P(f,["state"]);y.commitOutcomeState=h.state==="confirmed"?"confirmed":"unresolved",ne()}).catch(()=>{y.commitOutcomeState="unresolved",ne()});F(he)}catch(he){throw y.commitOutcomeState="unresolved",y.status={...y.status,legacyStore:"unresolved"},q(y),he}}try{a(y,"history",ce)}catch(he){throw y.status={...y.status,legacyStore:"unresolved"},q(y),he}y.commitRegistered=!0,ne()})}}),Ze={sink:re,resumeRun(y){return H(()=>{(!p?.resumedRun||k||w||I)&&G("reconciliation_required");let E=y,U=p.resumedRun;(!E||E.turnId!==U.admission.turnId||E.runKey!==U.captureRunKey||!fe(E.sink,U))&&G("identity_mismatch"),v();let Q={initial:j(),recoveryInitial:U.initial,notified:!0,admitted:!0,prepared:!0,fullTurn:!1,callbackUnresolved:!1,prepareEntered:!0,cancelledUnadmitted:!1,queryBound:!1,queryEnded:!1,finalizing:!1,finishAttempt:0,commitRegistered:!1,admit:U.admission,status:{stage:"admitted",turnId:U.admission.turnId,ownerEpoch:U.admission.ownerEpoch,captureRunKey:U.captureRunKey,controlRunId:U.admission.runKey,capture:"inflight",query:"not-started",legacyStore:"not-started",querySettlement:null,failureCount:0}};return(!fe(Q.initial.target,U.initial.target)||Q.initial.confirmedCommitId!==U.initial.confirmedCommitId)&&G("stale_generation"),k=Q,T(Q),Q.work=r.enterWork(),st(Q)})},planRun(y){return H(()=>{let E=P(y,["turnId"],["onAdmitted"]);lr(E.turnId),E.onAdmitted!==void 0&&typeof E.onAdmitted!="function"&&G("invalid_input"),I&&G("binding_closed"),w!==void 0&&G("reconciliation_required");let U=n.read()??G("operation_not_found");U.state!=="active"&&G("binding_closed"),(U.fence!==null||k&&k.status.stage!=="settled")&&G("reconciliation_required"),yi(e,n,U),i.assertReady();let Q=j();Q.confirmedCommitId===null&&G("reconciliation_required"),fe(Q.target,U.target)||G("stale_generation");let ce={initial:Q,onAdmitted:E.onAdmitted,notified:!1,admitted:!1,prepared:!1,fullTurn:!1,callbackUnresolved:!1,prepareEntered:!1,cancelledUnadmitted:!1,queryBound:!1,queryEnded:!1,finalizing:!1,finishAttempt:0,commitRegistered:!1,status:{stage:"planned",turnId:E.turnId,ownerEpoch:c,captureRunKey:null,controlRunId:null,capture:"not-started",query:"not-started",legacyStore:"not-started",querySettlement:null,failureCount:0}};return k=ce,st(ce)})},status(){return H(V)},async settle(y={}){let E=y.timeoutMs??3e4;(typeof E!="number"||E<0||Number.isNaN(E))&&G("invalid_input");let U=performance.now()+E,Q;for(;C.size>0;){if(y.signal?.aborted){Q="cancelled";break}let ne=U-performance.now();if(ne<=0){Q="timeout";break}let he,f,h=new Promise(B=>{ne!==1/0&&(he=setTimeout(()=>B("timeout"),ne)),y.signal&&(f=()=>B("cancelled"),y.signal.addEventListener("abort",f,{once:!0}))});try{let B=await Promise.race([Promise.allSettled([...C]).then(()=>{}),h]);if(B){Q=B;break}}finally{he&&clearTimeout(he),f&&y.signal?.removeEventListener("abort",f)}}let ce=Ze.status();return Q?{...ce,status:Q}:ce},async retryOriginal(){return k&&K(k),Ze.settle()},stopAdmission(){I=!0}},dt=y=>{v(),w?.id!==y&&G("identity_mismatch");let E=n.read()??G("operation_not_found");(!fe(E,e.readBindingControl(g))||!fe(E.registration,b.registration))&&G("identity_mismatch"),(E.fence?.kind!=="rewrite"||E.fence.id!==y||E.fence.ownerEpoch!==c)&&G("operation_conflict")};return Ec.set(Ze,{claimed:!1,port:Object.freeze({spool:e,control:n,gate:r,slot:Object.freeze({...g}),scope:Object.freeze({...A}),ownerEpoch:c,storeIdentity:o,durableCompletion:u,assertCompletionOwner:v,...t.recoveryOwner===void 0?{}:{recoveryOwner:t.recoveryOwner},exclusive:H,track:F,observeResources:Ho,readCurrent:j,claim(y,E){v(),lr(y),I&&G("binding_closed"),(w!==void 0||C.size>0||k&&k.status.stage!=="settled")&&G("reconciliation_required");let U=n.read()??G("operation_not_found");(U.state!=="active"||U.fence!==null)&&G("reconciliation_required"),fe(U,e.readBindingControl(g))||G("identity_mismatch");let Q=j();Q.confirmedCommitId===null&&G("reconciliation_required"),fe(Q.target,U.target)||G("stale_generation"),i.assertReady(),w={id:y,hooks:E,capturing:!1}},assertOwned:dt,release(y){(w?.id!==y||w.capturing||n.read()?.fence!==null)&&G("operation_conflict"),w=void 0},capture(y,E){let U=w;if(!U||U.id!==y||U.capturing)return Promise.reject(new R("operation_conflict"));dt(y),U.capturing=!0;let Q=Promise.resolve().then(()=>Ke(E())).then(({value:ce})=>ce).finally(()=>{U.capturing=!1});return F(Q)},settle:y=>Ze.settle(y),stopAdmission:()=>Ze.stopAdmission()})}),Ze}import{types as oi}from"node:util";var yl="sdk2-host-rewrite-v1",fl=16384,jc=["intent","capture","publication-intent","publication-result","store-intent","compensation-intent","compensation-result","facts"],Te=(t,e)=>_(t)===_(e);function oe(t){throw new R(t)}function Mo(t){(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/u.test(t))&&oe("invalid_input")}function Ko(t){(!Number.isSafeInteger(t)||t<0)&&oe("invalid_input")}function Dc(t){let e=qc(t.run,t.capture),{spool:n,control:r,slot:i,ownerEpoch:o,storeIdentity:s}=e,c=t.capture,d,l=!1,p=a=>e.track(a),u=a=>{a.status={...a.status,stage:"reconciliation-required",failureCount:a.status.failureCount+1}},v=a=>{let T=a();oi.isPromise(T)&&p(T).catch(()=>{}),T!==void 0&&oe("invalid_input")},g=a=>{a.source.signal.throwIfAborted(),v(a.source.assertCurrent);let T=e.readCurrent();(!Te(T.target,a.initial.target)||T.localHistoryGeneration!==a.initial.localHistoryGeneration)&&oe("stale_generation")},b=a=>{(d!==a||a.status.stage==="settled")&&oe("operation_conflict"),e.assertOwned(a.id)},A=(a,T)=>{let D=`host-rewrite-${T}-${z(_([i,o,a.id]))}`;return{bindingId:i.storageBindingId,operationKey:D,intentDigest:z(D),originalMax:{bytes:fl,records:1},terminalReserve:{bytes:1,records:1}}},S=a=>{for(let T of jc){let D=A(a,T),K=n.status(D);K?Te(K.reservation,D)||oe("operation_conflict"):n.reserve(D)}},k=(a,T,D)=>{let K=_({format:yl,slot:i,ownerEpoch:o,rewriteId:a.id,kind:T,value:D});a.slots[T]!==void 0&&a.slots[T]!==K&&oe("operation_conflict"),a.slots[T]=K,a.pendingSlot!==void 0&&a.pendingSlot!==T&&oe("reconciliation_required"),a.pendingSlot=T;let V=A(a,T),Z=n.status(V)??oe("reconciliation_required");Te(Z.reservation,V)||oe("operation_conflict"),n.commit({...V,entries:[{entryId:V.operationKey,basket:"original",metadata:K,body:new Uint8Array}]}),a.pendingSlot=void 0},I=(a,T)=>{let D=a.slots[T]??oe("operation_conflict");a.pendingSlot!==void 0&&a.pendingSlot!==T&&oe("reconciliation_required"),a.pendingSlot=T;let K=A(a,T),V=n.status(K)??oe("reconciliation_required");Te(V.reservation,K)||oe("operation_conflict"),n.commit({...K,entries:[{entryId:K.operationKey,basket:"original",metadata:D,body:new Uint8Array}]}),a.pendingSlot=void 0},m=a=>{if(!a.prepared){let T=e.gate.acquireIdle(i,a.preparing.expectedRevision);try{r.mutate(a.preparing,{idleLease:T}),a.prepared=!0}finally{T.release()}a.work=e.gate.enterWork()}b(a),S(a),k(a,"intent",{reason:a.reason,initial:a.initial}),(a.status.stage==="preparing"||a.status.stage==="reconciliation-required")&&(a.status={...a.status,stage:"prepared"})},w=a=>{if(a.staged)return;b(a);let T=a.candidate??oe("operation_conflict");a.staging??={kind:"stage-rewrite-candidate",transitionId:`rewrite-stage-${z(_([o,a.id]))}`,expectedRevision:r.read().revision,ownerEpoch:o,rewriteId:a.id,candidateTarget:T.target},r.mutate(a.staging),a.staged=!0,a.status={...a.status,stage:"staged"}},C=a=>({...a.status,resourceSettlement:a.status.resourceSettlement===null?null:e.observeResources(a.status.resourceSettlement)}),H=a=>{if(!(a.status.stage==="settled"||!a.outcome||a.publisherUnknown||a.storeUnknown||a.compensationUnknown)&&!(a.status.resources!=="confirmed"||a.captureRequested&&a.status.capture!=="confirmed")&&!(a.outcome==="published"&&(a.status.publication!=="confirmed"||a.status.legacyStore!=="confirmed"))&&!(a.outcome==="compensated"&&a.status.compensation!=="confirmed")){if(!a.finishing){b(a);let T=e.readCurrent();a.outcome==="published"?(!a.commit||T.confirmedCommitId!==a.commit.commitId||!Te(T.target,a.commit.target)||T.localHistoryGeneration!==a.commit.localHistoryGeneration)&&oe("reconciliation_required"):a.outcome==="compensated"?(!a.compensation||T.confirmedCommitId!==a.compensation.commitId||!Te(T.target,a.initial.target)||T.localHistoryGeneration!==a.initial.localHistoryGeneration)&&oe("reconciliation_required"):(a.storeStarted||!Te(T,a.initial))&&oe("reconciliation_required");for(let K of jc)K!=="facts"&&(a.slots[K]===void 0?k(a,K,{unused:!0,outcome:a.outcome}):I(a,K));let D={kind:"finish-rewrite",transitionId:`rewrite-finish-${z(_([o,a.id,a.finishAttempt]))}`,expectedRevision:r.read().revision,ownerEpoch:o,rewriteId:a.id,outcome:a.outcome==="compensated"?"unchanged":a.outcome};e.durableCompletion&&(a.recoveryFinish??=D),a.projectionPrepared||(a.outcome==="published"&&a.reason==="compaction"&&(a.projection=t.prepareProjection?.({rewriteId:a.id,history:T})),a.projectionPrepared=!0),k(a,"facts",{outcome:a.outcome,history:T,capture:a.status.capture,resources:{status:a.status.resourceSettlement.status,failureCount:a.status.resourceSettlement.failureCount,omittedFailures:a.status.resourceSettlement.omittedFailures},...a.recoveryFinish===void 0?{}:{recoveryFinish:a.recoveryFinish},...a.projection===void 0?{}:{projection:a.projection.fact}}),a.finishing=D}try{e.assertCompletionOwner(),a.projection?.publish();let T=r.mutate(a.finishing),D=a.outcome==="published"?a.candidate.target:a.initial.target;(T.control.fence!==null||!Te(T.control.target,D))&&oe("reconciliation_required"),a.status={...a.status,stage:"settled"},e.release(a.id),a.work?.release(),a.work=void 0}catch(T){if(T instanceof R&&T.code==="revision_conflict"&&a.finishAttempt<8&&a.finishing){let D=r.read();D?.fence?.kind==="rewrite"&&D.fence.id===a.id&&D.fence.ownerEpoch===o&&Te(n.readBindingControl(i),D)&&BigInt(D.revision)>BigInt(a.finishing.expectedRevision)&&(a.finishing=void 0,a.finishAttempt++)}throw T}}},j=a=>{p(Promise.resolve().then(()=>e.exclusive(()=>H(a))).catch(()=>{u(a)}))},x=(a,T)=>{let D;try{D=e.exclusive(()=>{b(a),(!a.prepared||a.candidate||a.outcome)&&oe("operation_conflict"),g(a);let K=Lt(Buffer.from(JSON.stringify(T.messages)));if((K!==a.initial.target.sourceSnapshotDigest||a.captureDigest!==void 0&&a.captureDigest!==K)&&oe("stale_generation"),a.status.capture==="confirmed")return Promise.resolve();if(a.captureWork)return a.captureWork;let V=!a.captureRequested;a.captureRequested=!0,a.captureDigest=K,V&&(a.captureMessages=structuredClone(T.messages)),a.status={...a.status,capture:"inflight"};let Z=e.capture(a.id,()=>V?c.captureGovernance({messages:a.captureMessages}):c.awaitReady());return a.captureWork=Z.then(()=>{a.status={...a.status,capture:"confirmed"},j(a)},re=>{throw a.status={...a.status,capture:"unresolved"},u(a),re}).finally(()=>{a.captureWork=void 0}),a.captureWork.catch(()=>{}),p(a.captureWork)})}catch(K){return Promise.reject(K)}return T.signal?new Promise((K,V)=>{let Z=T.signal,re=()=>V(Z.reason??new Error("Capture observer cancelled"));D.then(()=>{Z.removeEventListener("abort",re),K()},Re=>{Z.removeEventListener("abort",re),V(Re)}),Z.aborted?re():Z.addEventListener("abort",re,{once:!0})}):D},q=a=>Object.freeze({rewriteId:a.id,governanceCapture:Object.freeze({captureGovernance:T=>x(a,T)}),status:()=>C(a),bindWork(T){e.exclusive(()=>{b(a);let D=P(T,["ended","settle"]);Ce(D.ended),(!oi.isPromise(D.ended)||typeof D.settle!="function"||a.workBound)&&oe("invalid_input"),a.workBound=!0,a.ended=D.ended,a.settleWork=D.settle,a.status={...a.status,resources:"inflight"};try{p(Ke(a.ended).then(()=>Ke(a.settleWork())).then(({value:K})=>{let V=e.observeResources(K);if(a.status={...a.status,resourceSettlement:V},!["completed","failed"].includes(V.status)||Object.values(V.pending).some(Z=>Z!==0)){a.status={...a.status,resources:"unresolved"},u(a);return}a.status={...a.status,resources:"confirmed"},j(a)}).catch(()=>{a.status={...a.status,resources:"unresolved"},u(a)}))}catch(K){throw a.status={...a.status,resources:"unresolved"},u(a),K}})},stage(T){e.exclusive(()=>{b(a),g(a),(a.status.capture!=="confirmed"||a.publisherAttempted||a.outcome||a.compensation)&&oe("operation_conflict");let D=P(T,["target","localHistoryGeneration"]);Ko(D.localHistoryGeneration);let K=tt({scope:e.scope,target:D.target,nowMs:0}).target;(K.sessionId!==a.initial.target.sessionId||D.localHistoryGeneration<a.initial.localHistoryGeneration||!Te(K,a.initial.target)&&D.localHistoryGeneration===a.initial.localHistoryGeneration)&&oe("stale_generation");let V={target:K,localHistoryGeneration:D.localHistoryGeneration};a.candidate&&!Te(a.candidate,V)&&oe("operation_conflict"),a.candidate=V;try{w(a)}catch(Z){throw u(a),Z}})},publish(T){e.exclusive(()=>{b(a),g(a),(!a.staged||a.publisherUnknown||a.outcome==="unchanged"||a.compensation)&&oe("operation_conflict");let D=P(T,["apply","assertPublished"]);if((typeof D.apply!="function"||typeof D.assertPublished!="function")&&oe("invalid_input"),a.publisher&&(a.publisher.apply!==D.apply||a.publisher.assertPublished!==D.assertPublished)&&oe("operation_conflict"),a.publisher??={apply:D.apply,assertPublished:D.assertPublished},a.publisherAttempted){if(a.status.publication==="confirmed"){I(a,"publication-result");return}oe("reconciliation_required")}try{k(a,"publication-intent",{candidate:a.candidate})}catch(K){throw u(a),K}a.publisherAttempted=!0,a.status={...a.status,stage:"publishing"};try{v(a.publisher.apply),a.publisherUnknown&&oe("reentrant"),v(a.publisher.assertPublished);let K=e.readCurrent();(!Te(K.target,a.candidate.target)||K.localHistoryGeneration!==a.candidate.localHistoryGeneration)&&oe("stale_generation"),a.status={...a.status,publication:"confirmed",stage:"published"},a.outcome="published"}catch(K){a.publisherUnknown=!0,a.status={...a.status,publication:"unknown"},u(a);try{k(a,"publication-result",{outcome:"unknown"})}catch{}throw K}try{k(a,"publication-result",{outcome:"published",candidate:a.candidate})}catch(K){throw u(a),K}j(a)})},commitHistory(T){e.exclusive(()=>{b(a),(!a.staged||a.outcome==="unchanged"||a.publisherUnknown||a.compensation)&&oe("operation_conflict");let D=P(T,["commitId","storeIdentity","target","localHistoryGeneration","start"]);Mo(D.commitId),Ko(D.localHistoryGeneration),(D.storeIdentity!==s||typeof D.start!="function")&&oe("identity_mismatch");let K=tt({scope:e.scope,target:D.target,nowMs:0}).target,V={commitId:D.commitId,target:K,localHistoryGeneration:D.localHistoryGeneration};if(Te({target:K,localHistoryGeneration:V.localHistoryGeneration},a.candidate)||oe("stale_generation"),a.commit&&(!Te(a.commit,V)||a.start!==D.start)&&oe("operation_conflict"),a.commit??=V,a.start??=D.start,a.storeStarted){a.storeUnknown&&oe("reconciliation_required");return}try{k(a,"store-intent",V)}catch(Z){throw u(a),Z}a.storeStarted=!0,a.status={...a.status,legacyStore:"inflight"};try{let Z=a.start();oi.isPromise(Z)||oe("invalid_input"),a.storePromise=Z,p(Ke(a.storePromise).then(({value:re})=>{if(a.storeCompleted=!0,P(re,["state"]).state!=="confirmed"){a.status={...a.status,legacyStore:"unresolved"},u(a);return}a.status={...a.status,legacyStore:"confirmed"},j(a)}).catch(()=>{a.storeCompleted=!0,a.status={...a.status,legacyStore:"unresolved"},u(a)}))}catch(Z){throw a.storeUnknown=!0,a.status={...a.status,legacyStore:"unresolved"},u(a),Z}})},compensateHistory(T){e.exclusive(()=>{b(a),(!a.storeStarted||!a.storeCompleted||a.storeUnknown||a.publisherAttempted||a.publisherUnknown||a.outcome&&a.outcome!=="compensated")&&oe("reconciliation_required");let D=e.readCurrent();(!Te(D.target,a.initial.target)||D.localHistoryGeneration!==a.initial.localHistoryGeneration)&&oe("stale_generation");let K=P(T,["commitId","storeIdentity","target","localHistoryGeneration","start"]);Mo(K.commitId),Ko(K.localHistoryGeneration),(K.storeIdentity!==s||typeof K.start!="function")&&oe("identity_mismatch");let V=tt({scope:e.scope,target:K.target,nowMs:0}).target,Z={commitId:K.commitId,target:V,localHistoryGeneration:K.localHistoryGeneration};if((!Te(V,a.initial.target)||Z.localHistoryGeneration!==a.initial.localHistoryGeneration||Z.commitId===a.commit.commitId||Z.commitId===a.initial.confirmedCommitId)&&oe("stale_generation"),a.compensation&&(!Te(a.compensation,Z)||a.compensateStart!==K.start)&&oe("operation_conflict"),a.compensation??=Z,a.compensateStart??=K.start,a.compensationStarted){a.compensationUnknown&&oe("reconciliation_required");return}try{k(a,"compensation-intent",{original:a.commit,compensation:Z})}catch(re){throw u(a),re}a.compensationStarted=!0,a.status={...a.status,compensation:"inflight"};try{let re=a.compensateStart();oi.isPromise(re)||oe("invalid_input"),p(Ke(re).then(({value:Re})=>{if(P(Re,["state"]).state!=="confirmed"){a.status={...a.status,compensation:"unresolved"},u(a);return}a.status={...a.status,compensation:"confirmed",stage:"unchanged"},a.outcome="compensated";try{k(a,"compensation-result",{compensation:Z,outcome:"confirmed"})}catch{u(a);return}j(a)}).catch(()=>{a.status={...a.status,compensation:"unresolved"},u(a)}))}catch(re){throw a.compensationUnknown=!0,a.status={...a.status,compensation:"unresolved"},u(a),re}})},concludeUnchanged(){e.exclusive(()=>{b(a),(a.publisherAttempted||a.publisherUnknown||a.storeStarted||a.commit)&&oe("reconciliation_required"),Te(e.readCurrent(),a.initial)||oe("stale_generation"),a.outcome="unchanged",a.status={...a.status,stage:"unchanged"},j(a)})}}),F=a=>{let T=d?C(d):null;return T===null||T.stage==="settled"?{...a,rewrite:T,status:a.status==="completed"?"completed":a.status==="reconciliation-required"?"reconciliation-required":"pending"}:{...a,rewrite:T,status:T?.stage==="reconciliation-required"?"reconciliation-required":"pending"}},L={prepare(a){return e.exclusive(()=>{let T=P(a,["rewriteId","reason","sourceLease"]);Mo(T.rewriteId),["compaction","restore","model-transition"].includes(T.reason)||oe("invalid_input");let D=P(T.sourceLease,["signal","assertCurrent"]);if((!(D.signal instanceof AbortSignal)||typeof D.assertCurrent!="function")&&oe("invalid_input"),d&&d.status.stage!=="settled"){(d.id!==T.rewriteId||d.reason!==T.reason||d.sourceObject!==T.sourceLease)&&oe("operation_conflict");try{m(d)}catch(re){throw u(d),re}return d.ticket}l&&oe("binding_closed");let K={signal:D.signal,assertCurrent:D.assertCurrent};K.signal.throwIfAborted(),v(K.assertCurrent);let V=e.readCurrent(),Z={id:T.rewriteId,reason:T.reason,source:K,sourceObject:T.sourceLease,initial:V,prepared:!1,staged:!1,captureRequested:!1,workBound:!1,publisherAttempted:!1,publisherUnknown:!1,storeStarted:!1,storeUnknown:!1,storeCompleted:!1,compensationStarted:!1,compensationUnknown:!1,slots:{},finishAttempt:0,preparing:{kind:"prepare-rewrite",transitionId:`rewrite-prepare-${z(_([o,T.rewriteId]))}`,expectedRevision:r.read().revision,ownerEpoch:o,rewriteId:T.rewriteId,candidateTarget:null},status:{rewriteId:T.rewriteId,stage:"preparing",capture:"not-started",resources:"not-started",legacyStore:"not-started",compensation:"not-started",publication:"not-started",resourceSettlement:null,failureCount:0}};Z.ticket=q(Z),e.claim(Z.id,{reentered(){Z.status.stage==="publishing"&&(Z.publisherUnknown=!0)},beforeWrite(re){b(Z),(!Z.captureRequested||!re.complete)&&oe("operation_conflict");let Re={operationKey:re.operationKey,bodySha256:z(Buffer.from(re.body).toString("utf8")),bytes:re.body.byteLength};Z.raw&&!Te(Z.raw,Re)&&oe("operation_conflict"),Z.raw=Re,k(Z,"capture",Re)}}),d=Z;try{g(Z),m(Z)}catch(re){throw u(Z),re}return Z.ticket})},status(){let a=t.run.status();return F(a)},async settle(a){let T=await e.settle(a),D=F(T);return T.status==="timeout"||T.status==="cancelled"?{...D,status:T.status}:D},async retryOriginal(){if(d&&d.status.stage!=="settled"){let a=d;try{e.exclusive(()=>{a.pendingSlot!==void 0&&(b(a),I(a,a.pendingSlot)),a.prepared||m(a),a.staging&&!a.staged&&w(a),H(a)})}catch{u(a)}}return L.settle()},stopAdmission(){l=!0,e.stopAdmission()}};return L}var In=(t,e)=>_(t)===_(e);function Ye(){throw new R("reconciliation_required")}function Hc(t){if(t!==null&&typeof t=="object"){for(let e of Object.values(t))Hc(e);Object.freeze(t)}return t}async function Mc(t){let{spool:e,control:n,slot:r,owner:i,storeIdentity:o}=t,s,c=()=>{t.assertCurrent(),i.assertCurrent(),t.assertCurrent();let w=et(e,n,r);s!==void 0&&_({scope:w.scope,target:w.target})!==s&&Ye()};c();let d=et(e,n,r);s=_({scope:d.scope,target:d.target});let l=zt({spool:e,control:n,slot:r,includeWork:!0}),p=l.current,u=l.plan;(!p||p.state!=="active"||p.fence!==null||l.writeBarrier!=="clear"||!u||!l.ready||l.retirement!==null||!l.work||l.work.active!==null||!l.headEventDigest||!l.createEventDigest||u.ownerRootDigest!==i.ownerRootDigest||u.physicalPairDigest!==i.physicalPairDigest||u.scope.applicationScopeId!==d.scope.applicationScopeId||u.scope.endUserId!==d.scope.endUserId||!In(p.target,d.target))&&Ye();let v=Rs(l.ready,u);v.createEventDigest!==l.createEventDigest&&Ye();let g=l.work.lastCompleted,b=u.confirmedHistory;if(g){g.finish||Ye();let w=new Map;for(let H of tr({snapshot:l,work:g}))w.set(_(H),H);let C=!1;for(let H=0;H<3;H++){w.size>_r&&Ye(),c();let j=zt({spool:e,control:n,slot:r,includeWork:!0,expectedHeadEventDigest:l.headEventDigest,operations:[...w.values()]});(j.writeBarrier!=="clear"||!In(j.work,l.work))&&Ye();let x=Et({snapshot:j,work:g});if(x.kind==="verified"){(!x.controlCompleted||!In(x.target,p.target))&&Ye(),b=x.history,C=!0;break}let q=w.size;for(let F of x.neededOperationKeys)w.set(_(F),F);q===w.size&&Ye()}C||Ye()}else In(p.target,u.initialTarget)||Ye();(b.commitId!==t.history.commitId||b.observation.sessionId!==p.target.sessionId||b.observation.sourceSnapshotDigest!==p.target.sourceSnapshotDigest||t.history.observation.sessionId!==b.observation.sessionId||t.history.observation.sourceSnapshotDigest!==b.observation.sourceSnapshotDigest)&&Ye(),c();let A=await _e(e,o,p.target.sessionId,d.scope).readConfirmed();c(),(!A||Bt(p.target.sessionId,A.messages,0).sourceSnapshotDigest!==p.target.sourceSnapshotDigest)&&Ye();let S=zt({spool:e,control:n,slot:r,expectedHeadEventDigest:l.headEventDigest});(S.writeBarrier!=="clear"||!In(S.current,p)||!In(S.plan,u)||!In(S.ready,v)||S.retirement!==null)&&Ye();let k=et(e,n,r);_({scope:k.scope,target:k.target})!==s&&Ye(),c();let I={format:"sdk2-effective-context-v1",scope:d.scope,bindingId:u.bindingId,sourceId:u.sourceId,sourceGeneration:u.sourceGeneration,target:p.target,storeCommitId:b.commitId,completion:{kind:g?.kind??"installation",eventDigest:g?.finish?.eventDigest??l.createEventDigest,workId:g?.workId??null}},m={...I,referenceDigest:z(`tansr.sdk2.effective-context.v1\0${_(I)}`)};return Me(m,{maxBytes:16384}),Hc(structuredClone(m))}var Dn=new WeakMap,rn=new WeakMap,ur=new WeakMap,Lo=AbortSignal.prototype.throwIfAborted,je=(t,e)=>_(t)===_(e);function te(t){throw new R(t)}function Kc(t){t!==void 0&&(nn.isPromise(t)&&Ce(t),te("invalid_input"))}function si(t){let e=P(t,["sessionId","sourceSnapshotDigest","localHistoryGeneration"]);return(typeof e.sessionId!="string"||e.sessionId.length===0||e.sessionId.length>512||typeof e.sourceSnapshotDigest!="string"||!/^[a-f0-9]{64}$/.test(e.sourceSnapshotDigest)||typeof e.localHistoryGeneration!="number"||!Number.isSafeInteger(e.localHistoryGeneration)||e.localHistoryGeneration<0||Object.is(e.localHistoryGeneration,-0))&&te("invalid_input"),Object.freeze(e)}function Hg(t){let e=P(t,["spool","control","slot","gate","ownerEpoch","storeIdentity","historyPort","captureBindingId","recordBindingId","maxMaterialBytes"],["maxTurnBytes","recoveryOwner","trustedAttachmentSource"]),n=Object.freeze({...e,slot:Object.freeze({...P(e.slot,["storageBindingId","slotId"])})}),{spool:r,control:i,gate:o,slot:s,ownerEpoch:c,storeIdentity:d,historyPort:l}=n,p=Gt(r,i)==="sdk2-spool-v2"?()=>et(r,i,s).nowMs:void 0;n.recoveryOwner!==void 0&&ni(n.recoveryOwner,n);let u=P(l,["storeIdentity","read"],["latestCommit"]);(u.storeIdentity!==d||typeof u.read!="function")&&te("identity_mismatch"),(nn.isProxy(u.read)||u.latestCommit!==void 0&&(typeof u.latestCommit!="function"||nn.isProxy(u.latestCommit)))&&te("invalid_input");let v=u.read,g=i.read()??te("operation_not_found");g.registration.bindingId!==n.recordBindingId&&te("identity_mismatch");let b=_(g.registration),A=Object.freeze({...g.target.generations}),S=()=>{let D=i.read()??te("operation_not_found");return(!je(D,r.readBindingControl(s))||_(D.registration)!==b||D.storageBindingId!==s.storageBindingId||D.slotId!==s.slotId)&&te("identity_mismatch"),je(D.target.generations,A)||te("stale_generation"),D},k=()=>{let D=P(l,["storeIdentity","read"],["latestCommit"]);(D.storeIdentity!==d||D.read!==v||D.latestCommit!==u.latestCommit)&&te("identity_mismatch");let K=Reflect.apply(v,l,[]);nn.isPromise(K)&&(Ce(K),te("invalid_input"));let V=P(K,["observation","confirmedCommit"]),Z=si(V.observation),re=tt({scope:S().registration.scope,nowMs:0,target:{sessionId:Z.sessionId,sourceSnapshotDigest:Z.sourceSnapshotDigest,generations:A}}).target;re.sessionId!==g.registration.sessionId&&te("identity_mismatch");let Re=null;if(V.confirmedCommit!==null){let Se=P(V.confirmedCommit,["commitId","observation"]);(typeof Se.commitId!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(Se.commitId))&&te("invalid_input"),je(si(Se.observation),Z)||te("stale_generation"),Re=Se.commitId}return{target:re,localHistoryGeneration:Z.localHistoryGeneration,confirmedCommitId:Re}},I=k(),m=S(),w=Gt(r,i)==="sdk2-spool-v2"?Dt(n):void 0,C=w?.resumedRun,H=m.state==="closing";H&&ti(n,l),(m.state!=="active"&&!H||m.fence!==null&&!C||o.busy||I.confirmedCommitId===null)&&te("reconciliation_required"),je(I.target,m.target)||te("stale_generation"),m.acceptedCapabilities.includes("archive-transfer-v1")||te("unsupported_capability"),(!g.registration.relatedBindingIds.includes(n.captureBindingId)||!g.registration.relatedBindingIds.includes(n.recordBindingId))&&te("identity_mismatch");let j=rr({spool:r,captureBindingId:n.captureBindingId,publicationClock:p,recordBindingId:n.recordBindingId,sourceId:g.registration.sourceId,sourceGeneration:g.registration.sourceGeneration,generations:A,projectionPolicyId:"sdk2-governance-material-v1",textProjectionPolicy:mt,...n.maxTurnBytes===void 0?{}:{maxTurnBytes:n.maxTurnBytes},...n.trustedAttachmentSource===void 0?{}:{trustedAttachmentSource:n.trustedAttachmentSource},acquireAuthority:D=>{w?.assertCurrent();let K=S().fence;return(K?.kind!=="run"||K.ownerEpoch!==c||K.turnId!==D.turnId)&&te("identity_mismatch"),{target:K.target,ownerEpoch:c,assertCurrent(){w?.assertCurrent();let V=S().fence;(V===null||!je(V,K))&&te("identity_mismatch")}}},...w===void 0?{}:{acquireRecoveryAuthority:D=>{let K=()=>{w.assertCurrent(),(!C||D.runKey!==C.captureRunKey||D.turnId!==C.admission.turnId||D.originalOwnerEpoch!==C.admission.ownerEpoch||!je(D.target,C.initial.target)||D.sourceId!==g.registration.sourceId||D.sourceGeneration!==g.registration.sourceGeneration)&&te("identity_mismatch");let V=S().fence;(V?.kind!=="run"||V.ownerEpoch!==C.admission.ownerEpoch||V.id!==C.admission.runKey||V.turnId!==D.turnId||!je(V.target,D.target))&&te("identity_mismatch"),w.assertCurrent()};return K(),{assertCurrent:K}}}}),x=Tc({spool:r,control:i,gate:o,slot:s,ownerEpoch:c,storeIdentity:d,recording:j,readCurrent:k,...n.recoveryOwner===void 0?{}:{recoveryOwner:n.recoveryOwner}}),q=bs({sink:x.sink,maxMaterialBytes:n.maxMaterialBytes,textProjectionPolicy:mt}),F,L=Dc({run:x,capture:q,prepareProjection({rewriteId:D,history:K}){let V=F;return(!V||!je(V.target,K.target)||K.confirmedCommitId===null)&&te("reconciliation_required"),Qn({spool:r,slot:s,ownerEpoch:c,rewriteId:D,publicationClock:p,recordBindingId:n.recordBindingId,sourceId:g.registration.sourceId,sourceGeneration:g.registration.sourceGeneration,target:K.target,messages:V.messages,assertCurrent(){let Z=S(),re=k();(!je(re,K)||Z.fence!==null&&(Z.fence.kind!=="rewrite"||Z.fence.id!==D||Z.fence.ownerEpoch!==c))&&te("reconciliation_required")}})}});H&&L.stopAdmission(),Object.freeze(x.sink),Object.freeze(x),Object.freeze(q),Object.freeze(L);let a=Object.freeze({run:x,capture:q,rewrite:L,targetFor(D,K){k();let V=Bt(g.registration.sessionId,D,0);K!==void 0&&(Ui(K,d),(K.observation.sessionId!==V.sessionId||K.observation.sourceSnapshotDigest!==V.sourceSnapshotDigest)&&te("identity_mismatch"));let Z=Object.freeze({sessionId:V.sessionId,sourceSnapshotDigest:V.sourceSnapshotDigest,generations:A});return S().fence?.kind==="rewrite"&&(F={target:Z,messages:structuredClone(D)}),Z},stopAdmission(){L.stopAdmission()}}),T=Object.freeze(Object.create(null));return Dn.set(T,{options:n,runtime:a,initial:I,state:S,readCurrent:k,closingRecovery:H,resumingRun:C!==void 0,claiming:!1,reentered:!1,claimed:!1,installed:!1}),T}function ai(t,e,n=!1){let r=Dn.get(t)??te("identity_mismatch"),i=P(e,["lease","storeIdentity"],["spool","slot","ownerEpoch","captureBindingId","recordBindingId"]),o=P(i.lease,["observation","signal","assertCurrent","historyPort"]);(!r.claimed||r.claiming||r.retired||rn.get(r.options.historyPort)!==t||i.storeIdentity!==r.options.storeIdentity||o.historyPort!==r.options.historyPort)&&te("identity_mismatch");for(let g of["spool","ownerEpoch","captureBindingId","recordBindingId"])i[g]!==void 0&&i[g]!==r.options[g]&&te("identity_mismatch");i.slot!==void 0&&!je(i.slot,r.options.slot)&&te("identity_mismatch"),(typeof o.assertCurrent!="function"||nn.isProxy(o.assertCurrent)||!(o.signal instanceof AbortSignal)||nn.isProxy(o.signal))&&te("invalid_input");let s=()=>{Reflect.apply(Lo,o.signal,[]),Kc(Reflect.apply(o.assertCurrent,i.lease,[])),Reflect.apply(Lo,o.signal,[])};s();let c=r.state(),d=r.readCurrent(),l=si(o.observation),p=r.resumingRun&&r.runtime.run.status().run===null;p&&Lc(r),(c.state!==(r.closingRecovery?"closing":"active")||c.fence!==null&&!p||d.confirmedCommitId===null||!je(c.target,d.target)||l.sessionId!==d.target.sessionId||l.sourceSnapshotDigest!==d.target.sourceSnapshotDigest)&&te("reconciliation_required");let u=r.runtime.run.status(),v=r.runtime.rewrite.status();return(!p&&u.status!=="completed"||u.run!==null&&(!n||u.run.stage!=="settled")||u.admissionStopped!==r.closingRecovery||!p&&v.status!=="completed"||v.rewrite!==null&&(!n||v.rewrite.stage!=="settled")||v.admissionStopped!==r.closingRecovery)&&te("reconciliation_required"),r.closingRecovery?(ti(r.options,r.options.historyPort),Ut(r.runtime.capture)):p||r.runtime.capture.assertReady(),s(),r}function Lc(t){let e=Dt(t.options),n=e.resumedRun,r=t.state(),i=r.fence;(!t.resumingRun||!n||i?.kind!=="run"||r.state!=="active"||i.ownerEpoch!==n.admission.ownerEpoch||i.id!==n.admission.runKey||i.turnId!==n.admission.turnId||!je(i.target,n.initial.target)||t.runtime.run.status().run!==null||t.runtime.rewrite.status().rewrite!==null)&&te("reconciliation_required"),e.assertCurrent(),Ut(t.runtime.capture)}function Mg(t,e){let n=P(e,["lease","storeIdentity","runtime"]),r=ai(t,{lease:n.lease,storeIdentity:n.storeIdentity});r.runtime!==n.runtime&&te("identity_mismatch"),r.installed=!0}function Go(t,e){let n=ai(t,e);return n.installed||te("reconciliation_required"),n.runtime}async function Kg(t,e){P(e,["lease","storeIdentity"]);let n=ai(t,e,!0);(!n.installed||n.closingRecovery||n.options.gate.busy)&&te("reconciliation_required");let r=Dt(n.options),i=gt(e.lease,e.storeIdentity),o=await Mc({...n.options,owner:r,history:i,assertCurrent(){Pr(e.storeIdentity,i.observation.sessionId,n.runtime),(ai(t,e,!0)!==n||!n.installed||n.options.gate.busy)&&te("reconciliation_required"),je(gt(e.lease,e.storeIdentity),i)||te("stale_generation")}});return Pr(e.storeIdentity,i.observation.sessionId,n.runtime),e.lease.assertCurrent(),o}function Gc(t){t.lease.assertCurrent();let e=t.lease.historyPort??te("identity_mismatch");(e.storeIdentity!==t.storeIdentity||ur.has(e))&&te("identity_mismatch");let n=rn.get(e);if(t.runtime===null){n!==void 0&&te("identity_mismatch");return}let r=n===void 0?void 0:Dn.get(n);(!r||r.runtime!==t.runtime||!r.claimed||r.retired||r.claiming||r.options.spool!==t.spool||r.options.storeIdentity!==t.storeIdentity||!je(r.options.slot,t.slot)||r.options.ownerEpoch!==t.ownerEpoch||r.options.captureBindingId!==t.captureBindingId||r.options.recordBindingId!==t.recordBindingId||r.options.gate.busy)&&te("identity_mismatch");let i=r.state(),o=r.readCurrent();(!["closing","closed"].includes(i.state)||i.fence!==null||o.confirmedCommitId===null||!je(i.target,o.target))&&te("reconciliation_required");let s=r.runtime.run.status(),c=r.runtime.rewrite.status();(s.status!=="completed"||s.run!==null&&s.run.stage!=="settled"||c.status!=="completed"||c.rewrite!==null&&c.rewrite.stage!=="settled")&&te("reconciliation_required"),Ut(r.runtime.capture),t.lease.assertCurrent()}function No(t,e){let n=rn.get(t);if(e===null){n!==void 0&&te("identity_mismatch");return}let r=n===void 0?void 0:Dn.get(n);(!r||r.runtime!==e||!r.claimed||r.retired)&&te("identity_mismatch"),r.runtime.stopAdmission(),r.retired=!0,rn.delete(t)}function Lg(t){let e=Dn.get(t)??te("identity_mismatch");(!e.claimed||!e.installed||e.claiming||e.retired||rn.get(e.options.historyPort)!==t||e.options.gate.busy)&&te("identity_mismatch");let n=e.state(),r=e.readCurrent(),i=e.runtime.run.status(),o=e.runtime.rewrite.status();(!["active","closing"].includes(n.state)||n.fence!==null||r.confirmedCommitId===null||!je(n.target,r.target)||!i.admissionStopped||!o.admissionStopped||i.status!=="completed"||i.run!==null&&i.run.stage!=="settled"||o.status!=="completed"||o.rewrite!==null&&o.rewrite.stage!=="settled")&&te("reconciliation_required"),Ut(e.runtime.capture);let s=Ic(e.options,e.runtime),c=!1;return()=>{c||(s(),No(e.options.historyPort,e.runtime),c=!0)}}function Gg(t,e){let n=Dn.get(t)??te("identity_mismatch");n.claiming&&(n.reentered=!0,te("reentrant"));let r=ur.get(n.options.historyPort);r!==void 0&&(r.reentered=!0,n.reentered=!0,te("reentrant")),(n.claimed||rn.has(n.options.historyPort))&&te("operation_conflict"),n.claiming=!0,ur.set(n.options.historyPort,n);try{let i=P(e,["lease","storeIdentity"]),o=P(i.lease,["observation","signal","assertCurrent","historyPort"]);(i.storeIdentity!==n.options.storeIdentity||o.historyPort!==n.options.historyPort)&&te("identity_mismatch"),(typeof o.assertCurrent!="function"||nn.isProxy(o.assertCurrent)||!(o.signal instanceof AbortSignal)||nn.isProxy(o.signal))&&te("invalid_input");let s=o.signal,c=()=>{Reflect.apply(Lo,s,[])},d=()=>{c(),Kc(Reflect.apply(o.assertCurrent,i.lease,[])),c()};d(),n.closingRecovery?(ti(n.options,n.options.historyPort),Ut(n.runtime.capture)):n.resumingRun?Lc(n):n.runtime.capture.assertReady();let l=n.state(),p=n.runtime.run.status(),u=n.runtime.rewrite.status();(l.state!==(n.closingRecovery?"closing":"active")||l.fence!==null&&!n.resumingRun||n.options.gate.busy||!n.resumingRun&&p.status!=="completed"||p.run!==null||!n.resumingRun&&u.status!=="completed"||u.rewrite!==null||p.admissionStopped!==n.closingRecovery||u.admissionStopped!==n.closingRecovery)&&te("reconciliation_required"),d();let v=n.readCurrent(),g=si(o.observation);return(v.confirmedCommitId===null||!je(v,n.initial)||!je(v.target,l.target)||g.sessionId!==v.target.sessionId||g.sourceSnapshotDigest!==v.target.sourceSnapshotDigest)&&te("stale_generation"),je(n.state(),l)||te("stale_generation"),d(),c(),n.reentered&&te("reentrant"),rn.has(n.options.historyPort)&&te("operation_conflict"),n.options.recoveryOwner!==void 0&&Cc(n.options.recoveryOwner,n.runtime),n.claimed=!0,rn.set(n.options.historyPort,t),n.runtime}finally{n.claiming=!1,ur.get(n.options.historyPort)===n&&ur.delete(n.options.historyPort)}}var An=new WeakMap,on=new WeakMap,Nc=new WeakMap;function Qg(t,e){P(e,["body","policy","lease"]);let n=ze({kind:"binding-create",body:e.body});if(n.kind!=="binding-create")throw new R("invalid_input");lt(t.spool,t.control);let r=t.control.read();if(!r)throw new R("operation_not_found");let i=on.get(t.spool)?.(t.slot),o;if(i){let g=nt(t.slot,r.registration,n);if(_(i.plan.createRequest)!==_(n.body.request)||i.plan.createSemanticDigest!==g.semantic)throw new R("operation_conflict");o=Sn({limits:i.plan.createResponse.limits,rejectedCapabilities:i.plan.createResponse.rejectedCapabilities,captureBindingId:i.plan.captureBindingId,recordBindingId:i.plan.recordBindingId,materialBindingId:i.plan.materialBindingId})}else if(o=Sn(e.policy),![...n.body.requiredCapabilities,...n.body.optionalCapabilities.filter(b=>r.registration.capabilities.includes(b))].includes("archive-transfer-v1"))throw new R("unsupported_capability");let s=P(e.lease,["observation","signal","assertCurrent","historyPort"]),c=_(s.observation),d=e.lease,l=()=>{let g=P(d,["observation","signal","assertCurrent","historyPort"]);if(g.signal!==s.signal||g.assertCurrent!==s.assertCurrent||g.historyPort!==s.historyPort||_(g.observation)!==c)throw new R("identity_mismatch");let b=Reflect.apply(s.assertCurrent,d,[]);if(gl.isPromise(b)&&Promise.prototype.then.call(b,void 0,()=>{}),b!==void 0)throw new R("invalid_input")},p={...t,slot:{...t.slot}},u=Ac(p,n.body,e.lease),v=Object.freeze(Object.create(null));return An.set(v,{options:p,body:n.body,policy:o,owner:u,assertLease:l}),v}function eh(t,e){P(e,["lease"]);let n=jt(e.lease),{spool:r,control:i,storeIdentity:o}=t,s=Object.freeze({...P(t.slot,["storageBindingId","slotId"])});if(n.spool!==r||n.storeIdentity!==o||t.ownerEpoch!==n.owner.ownerEpoch||_(s)!==_(n.proof.root.slot))throw new R("identity_mismatch");lt(r,i);let c=on.get(r)?.(s),d=n.details.snapshot.originalCreate;if(!c||!d||_(c.plan)!==_(n.details.snapshot.plan))throw new R("identity_mismatch");let l=n.details.snapshot.current?.state==="closing";if(l&&(c.ready===null||_(c.ready)!==_(n.details.snapshot.ready)))throw new R("reconciliation_required");let p=Sn({limits:c.plan.createResponse.limits,rejectedCapabilities:c.plan.createResponse.rejectedCapabilities,captureBindingId:c.plan.captureBindingId,recordBindingId:c.plan.recordBindingId,materialBindingId:c.plan.materialBindingId}),u=Object.freeze({...t,slot:s}),v=wc(u,e.lease);l&&Ft(v.guard);let g=e.lease,b=Object.freeze(Object.create(null));return An.set(b,{options:u,body:d,policy:p,owner:v,coldPort:g.historyPort,...l?{closingReady:_(c.ready)}:{},assertLease(){jt(g)}}),n.assertCurrent(),b}function th(t,e){P(e,["lease"]);let n=jt(e.lease);if(!n.continuation||typeof n.assertContinuationCurrent!="function"||n.details.snapshot.plan!==null)throw new R("identity_mismatch");let r=n.assertContinuationCurrent,i=Sc(t,e.lease),o=Object.freeze(Object.create(null));return An.set(o,{options:Object.freeze({...t,slot:Object.freeze({...t.slot})}),body:n.continuation.body,policy:n.continuation.policy,owner:i,coldPort:e.lease.historyPort,continuationHistory:n.details.history,assertLease(){r();let s=gt(e.lease,t.storeIdentity);if(_(s)!==_(n.history))throw new R("stale_generation");r()}}),n.assertCurrent(),o}function nh(t,e){P(e,["lease"]);let n=jt(e.lease),r=on.get(t.spool)?.(t.slot);if(!r||r.ready!==null||n.details.snapshot.current?.state!=="closing"||n.continuation!==void 0||_(r.plan)!==_(n.details.snapshot.plan))throw new R("identity_mismatch");let i=Rc(t,e.lease);Ft(i.guard),n.assertCurrent()}function rh(t,e,n,r,i){let o=An.get(t);if(!o||o.coldPort!==void 0&&o.continuationHistory===void 0||o.options.spool!==e||_(o.options.slot)!==_(n)||_(o.body)!==_(r))throw new R("identity_mismatch");return o.owner.assertCurrent(),o.assertLease(),ws({control:i,body:r,policy:o.policy,physicalPairDigest:o.owner.physicalPairDigest,ownerRootDigest:o.owner.ownerRootDigest,confirmedHistory:o.continuationHistory??o.owner.confirmedHistory})}function ih(t,e){on.set(t,e)}function Uc(t,e){let n=on.get(t);if(!n)throw new R("identity_mismatch");return n(e)}function oh(t,e){Nc.set(t,e)}function sh(t,e){let n=An.get(t);if(!n||n.options.spool!==e)throw new R("identity_mismatch");Cn(n.owner.guard)}function ga(t,e){let n=An.get(t);if(!n||n.continuationHistory!==void 0||e.storeIdentity!==n.options.storeIdentity)throw new R("identity_mismatch");if(n.owner.assertCurrent(),n.coldPort!==void 0&&n.coldPort!==e.lease.historyPort)throw new R("identity_mismatch");let r=n.coldPort===void 0?void 0:jt(e.lease),i=r===void 0?gt(e.lease,e.storeIdentity):r.history,o=n.options.control.read(),s=on.get(n.options.spool)?.(n.options.slot);if(!s||!o||o.state!==(n.closingReady===void 0?"active":"closing")||o.fence!==null&&!n.owner.resumedRun||n.closingReady!==void 0&&(s.ready===null||_(s.ready)!==n.closingReady)||_(i)!==_(n.owner.confirmedHistory)||s.plan.physicalPairDigest!==n.owner.physicalPairDigest||s.plan.ownerRootDigest!==n.owner.ownerRootDigest||s.plan.createSemanticDigest!==nt(n.options.slot,o.registration,{kind:"binding-create",body:n.body}).semantic)throw new R("identity_mismatch");let c={limits:s.plan.createResponse.limits,rejectedCapabilities:s.plan.createResponse.rejectedCapabilities,captureBindingId:s.plan.captureBindingId,recordBindingId:s.plan.recordBindingId,materialBindingId:s.plan.materialBindingId};if(_(n.policy)!==_(c))throw new R("identity_mismatch");if(r!==void 0&&_(o)!==_(r.details.snapshot.current))throw new R("identity_mismatch");n.closingReady!==void 0?mr(e.contextMaterials,n.options.spool,s.plan,o,!1):r!==void 0?us(e.contextMaterials,n.options.spool,s.plan,o):ls(e.contextMaterials,n.options.spool,s.plan),r?.assertCurrent()}function vd(t,e,n,r){let i=An.get(t);if(!i)throw new R("identity_mismatch");let{spool:o,control:s,storeIdentity:c,slot:d}=i.options;ga(t,{lease:n,storeIdentity:c,contextMaterials:r});let l={spool:o,storeIdentity:c,slot:d,ownerEpoch:i.options.ownerEpoch,lease:n,captureBindingId:i.policy.captureBindingId,recordBindingId:i.policy.recordBindingId},p=Go(e,l),u=s.read(),v=on.get(o)?.(d);if(!v||!u||u.state!==(i.closingReady===void 0?"active":"closing")||u.fence!==null&&!i.owner.resumedRun||i.closingReady!==void 0&&(v.ready===null||_(v.ready)!==i.closingReady)||v.plan.physicalPairDigest!==i.owner.physicalPairDigest||v.plan.ownerRootDigest!==i.owner.ownerRootDigest||v.plan.createSemanticDigest!==nt(d,u.registration,{kind:"binding-create",body:i.body}).semantic)throw new R("identity_mismatch");if(Cn(i.owner.guard),i.closingReady===void 0){let g=Nc.get(o);if(!g)throw new R("identity_mismatch");g(d,v.plan)}if(Go(e,l)!==p)throw new R("identity_mismatch");i.owner.assertCurrent(),i.coldPort!==void 0&&jt(n),i.closingReady===void 0?da(i.owner.guard,p):la(i.owner.guard,p)}function ah(t,e){lt(t.spool,t.control);let n=ze({kind:"binding-create",body:e});if(n.kind!=="binding-create")throw new R("invalid_input");let r=t.control.read(),i=on.get(t.spool)?.(t.slot);if(!r||!i)throw new R("operation_not_found");if(_(r)!==_(t.spool.readBindingControl(t.slot)))throw new R("identity_mismatch");let o=nt(t.slot,r.registration,n);if(_(i.plan.createRequest)!==_(n.body.request)||i.plan.createSemanticDigest!==o.semantic)throw new R("operation_conflict");if(!i.ready&&r.state!=="closing"&&r.state!=="closed")throw new R("reconciliation_required");return structuredClone(i.plan.createResponse)}var wn=new WeakMap,Fc=new WeakMap,Wc=new WeakMap,zo=new WeakMap,Ht=(t,e)=>_(t)===_(e);function We(t="reconciliation_required"){throw new R(t)}function Uo(t){t!==void 0&&(zc.isPromise(t)&&Promise.prototype.then.call(t,void 0,()=>{}),We("invalid_input"))}function bh(t,e){zo.set(t,e)}function Fo(t,e,n){let r=wn.get(e);(!r||r.runtime!==n)&&We("identity_mismatch");let i=Dt(t),o=Uc(t.spool,t.slot)??We("operation_not_found"),s=t.control.read()??We("operation_not_found");(!Ht(s,t.spool.readBindingControl(t.slot))||!["closing","closed"].includes(s.state)||s.fence!==null||i.ownerRootDigest!==o.plan.ownerRootDigest||i.physicalPairDigest!==o.plan.physicalPairDigest||n===null&&o.ready!==null)&&We("identity_mismatch"),Ft(i.guard);let c=gt(e,t.storeIdentity);return Gc({...t,lease:e,runtime:n,captureBindingId:o.plan.captureBindingId,recordBindingId:o.plan.recordBindingId}),mr(r.contextMaterials,t.spool,o.plan,s,n===null),e.assertCurrent(),{options:{...t,slot:{...t.slot}},lease:e,surface:r,owner:i,plan:o.plan,ready:o.ready,history:c}}function Ih(t,e){let n=Fo(t,e.lease,e.runtime===void 0?wn.get(e.lease)?.runtime??null:e.runtime),r=Object.freeze(Object.create(null));return Fc.set(r,n),r}function Ah(t,e,n,r){let i=Fc.get(t);(!i||i.options.spool!==e||!Ht(i.options.slot,n)||wn.get(i.lease)!==i.surface||!Ht(i.plan,r.plan)||!Ht(i.ready,r.ready))&&We("identity_mismatch"),i.owner.assertCurrent(),i.lease.assertCurrent();let o=gt(i.lease,i.options.storeIdentity);Ht(o,i.history)||We("stale_generation"),i.surface.runtime!==null&&Ut(i.surface.runtime.capture),i.surface.contextMaterials!==void 0&&ps(i.surface.contextMaterials);let s=ks({plan:r.plan,control:r.control,closingEventDigest:r.closingEventDigest,installedRecord:r.ready,confirmedHistory:o});return i.lease.assertCurrent(),s}function wh(t,e){let n=Fo(t,e.lease,e.runtime===void 0?wn.get(e.lease)?.runtime??null:e.runtime),r=zo.get(t.spool)?.(t.slot)??We(),i=t.control.read()??We();(i.state!=="closed"||!Ht(r.record.finalTarget,i.target)||!Ht(r.record.confirmedHistory,n.history)||r.record.installationId!==n.plan.installationId||r.record.ownerRootDigest!==n.owner.ownerRootDigest||r.record.physicalPairDigest!==n.owner.physicalPairDigest)&&We("identity_mismatch");let o=Object.freeze(Object.create(null));return Wc.set(o,{...n,saved:r}),o}function fd(t,e,n){wn.has(t)&&We("reentrant");let r={...e};wn.set(t,r);try{t.assertCurrent();let i=n(t);zc.isPromise(i)&&(Promise.prototype.then.call(i,void 0,()=>{}),We("invalid_input"));let o=P(i,["permit","value"]),s=Wc.get(o.permit);(!s||s.lease!==t||s.surface!==r)&&We("identity_mismatch"),t.assertCurrent();let c=Fo(s.options,t,r.runtime),d=zo.get(s.options.spool)?.(s.options.slot)??We();return(!Ht(d,s.saved)||!Ht(c.history,s.history))&&We("identity_mismatch"),Uo(r.prepareDetach()),t.assertCurrent(),No(t.historyPort,r.runtime),Uo(r.detachOwnedState()),Uo(r.assertDetached()),Or(s.owner.guard),o.value}finally{wn.delete(t)}}import{createHash as hl}from"node:crypto";import{types as Xo}from"node:util";var ci=class extends Error{constructor(n){super(`Archive source transfer: ${n}`);this.code=n;this.name="ArchiveSourceTransferError"}code};var Mn="sdk2-source-transfer-v1",ml=262144,vl=33554432,di=67108864,Wo="0".repeat(64),Jo=9223372036854775807n,$o=new WeakSet,bl=new WeakMap;function W(t){throw new ci(t)}var li=t=>hl("sha256").update(t).digest("hex"),Mt=t=>Buffer.from(Me(t)).toString("utf8"),it=t=>Ee(Me(t)),Ae=(t,e)=>Mt(t)===Mt(e);function ot(t){(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(t))&&W("invalid_input")}function ue(t,e=0n){(typeof t!="string"||!/^(0|[1-9][0-9]{0,18})$/.test(t))&&W("invalid_input");let n=BigInt(t);return(n<e||n>Jo)&&W("invalid_input"),n}function pr(t,e,n){(!Number.isSafeInteger(t)||Object.is(t,-0)||t<e||t>n)&&W("invalid_input")}function $c(t){(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))&&W("invalid_input")}function ht(t,e){(!t||typeof t!="object"||Xo.isProxy(t)||![Object.prototype,null].includes(Object.getPrototypeOf(t)))&&W("invalid_input");let n=Reflect.ownKeys(t);(n.length!==e.length||n.some(i=>typeof i!="string"||!e.includes(i)))&&W("invalid_input");let r=Object.create(null);for(let i of e){let o=Object.getOwnPropertyDescriptor(t,i);(!o?.enumerable||!Object.hasOwn(o,"value"))&&W("invalid_input"),r[i]=o.value}return r}function Il(t,e){(!t||typeof t!="object"||Xo.isProxy(t)||!Array.isArray(t))&&W("invalid_input");let n=Object.getOwnPropertyDescriptor(t,"length").value;(n>e||Reflect.ownKeys(t).length!==n+1)&&W("capacity_exceeded");let r=[];for(let i=0;i<n;i++){let o=Object.getOwnPropertyDescriptor(t,String(i));(!o?.enumerable||!Object.hasOwn(o,"value"))&&W("invalid_input"),r.push(o.value)}return r}function Vo(t){let e=ht(t,["requestId","operationEpoch"]);return ot(e.requestId),ot(e.operationEpoch),{requestId:e.requestId,operationEpoch:e.operationEpoch}}function St(t,e){let n=it(t);ht(n,["protocol","ackFormat","request","bindingId","expectedRevision","generations","sourceId","sourceGeneration","coverage","payloads","attachments"]),(n.protocol!=="sdk2-ext-v1"||n.ackFormat!=="split-receipts-v1")&&W("invalid_input"),Vo(n.request),ot(n.bindingId),ot(n.sourceId),ot(n.sourceGeneration),ue(n.expectedRevision),ht(n.generations,["historyEpoch","deletionGeneration","projectionRevision"]),(typeof n.generations.historyEpoch!="string"||Array.from(n.generations.historyEpoch).length<1||Array.from(n.generations.historyEpoch).length>512)&&W("invalid_input"),ue(n.generations.deletionGeneration),ue(n.generations.projectionRevision),ht(n.coverage,["fromSequence","throughSequence","headDigest"]);let r=ue(n.coverage.fromSequence,1n);ue(n.coverage.throughSequence,r)-r>=128n&&W("capacity_exceeded"),$c(n.coverage.headDigest);for(let[s,c]of[["payloads",n.payloads],["attachments",n.attachments]]){let d=Il(c,128);s==="payloads"&&d.length===0&&W("invalid_input");let l=new Set;for(let p of d){let u=ht(p,["artifactId","sha256","state"]);ot(u.artifactId),$c(u.sha256),(u.state!=="durably-stored"||l.has(u.artifactId))&&W("invalid_input"),l.add(u.artifactId)}}let o=new Map;for(let s of[...n.payloads,...n.attachments]){let c=o.get(s.artifactId);c&&c!==s.sha256&&W("integrity_mismatch"),o.set(s.artifactId,s.sha256)}return Buffer.byteLength(Mt(n))>e&&W("capacity_exceeded"),n}function Jc(t){let e=new Map,n=0;for(let r of t)for(let i of[r.payload,...r.attachments]){let o=e.get(i.artifactId);if(o){Ae(o,i)||W("integrity_mismatch");continue}e.set(i.artifactId,i),n+=i.bytes,(n>di||e.size>256)&&W("capacity_exceeded")}return e}function Hn(t,e,n,r){(!r.length||r.length>128)&&W("invalid_input"),Jc(r);let i=o=>{let s=new Set;return o.filter(c=>s.has(c.artifactId)?!1:(s.add(c.artifactId),!0)).map(c=>({artifactId:c.artifactId,sha256:c.sha256,state:"durably-stored"}))};return St({protocol:"sdk2-ext-v1",ackFormat:"split-receipts-v1",request:e,bindingId:t.bindingId,expectedRevision:n,generations:t.generations,sourceId:t.sourceId,sourceGeneration:t.sourceGeneration,coverage:{fromSequence:r[0].sequence,throughSequence:r.at(-1).sequence,headDigest:r.at(-1).recordDigest},payloads:i(r.map(o=>o.payload)),attachments:i(r.flatMap(o=>o.attachments))},t.controlBytes)}function Al(t){let{spool:e,readAuthority:n}=t,r=it({bindingId:t.bindingId,sourceId:t.sourceId,sourceGeneration:t.sourceGeneration,generations:t.generations,controlBytes:t.controlBytes});ot(r.bindingId),ot(r.sourceId),ot(r.sourceGeneration),pr(r.controlBytes,1,ml);let i="x".repeat(128),o=String(Jo),s={protocol:"sdk2-ext-v1",ackFormat:"split-receipts-v1",request:{requestId:i,operationEpoch:i},bindingId:i,expectedRevision:o,generations:{historyEpoch:"\0".repeat(512),deletionGeneration:o,projectionRevision:o},sourceId:i,sourceGeneration:i,coverage:{fromSequence:o,throughSequence:o,headDigest:Wo},payloads:[{artifactId:i,sha256:Wo,state:"durably-stored"}],attachments:Array.from({length:128},(C,H)=>({artifactId:String(H).padEnd(128,"a"),sha256:Wo,state:"durably-stored"}))};Buffer.byteLength(Mt(s))>r.controlBytes&&W("capacity_exceeded");let c=Je(e).bindingIdentity(r.bindingId),d=C=>{let{request:H,...j}=C;return li(`tansr.sdk2.operation.v1\0${Mt({scope:[c.applicationScopeId,c.endUserId],operation:"archive-ack",semantic:j})}`)},l=C=>li(Mt({scope:[c.applicationScopeId,c.endUserId],bindingId:C.bindingId,operation:"archive-ack",request:C.request})),p=C=>{let H=ue(C.expectedRevision)+1n;return H>Jo&&W("capacity_exceeded"),{protocol:"sdk2-ext-v1",request:C.request,bindingId:C.bindingId,operation:"archive-ack",semanticDigest:d(C),state:"completed",revision:String(H),outcomeRef:`ack-${l(C)}`}},u=(C,H,j)=>{let x=n({operation:C,durableAckRevisionFloor:H,acknowledgedCoverage:it(j)});Xo.isPromise(x)&&(Promise.prototype.then.call(x,void 0,()=>{}),W("invalid_input"));let q=it(x);return ht(q,["bindingId","sourceId","sourceGeneration","generations","revision","state","operationEpoch","nowMs","releaseReady"]),(q.bindingId!==r.bindingId||typeof q.releaseReady!="boolean"||!["active","backpressured","closing","closed"].includes(q.state))&&W("invalid_input"),ue(q.revision),ht(q.operationEpoch,["id","expiresAtMs","active"]),ot(q.operationEpoch.id),pr(q.nowMs,0,Number.MAX_SAFE_INTEGER),pr(q.operationEpoch.expiresAtMs,0,Number.MAX_SAFE_INTEGER),typeof q.operationEpoch.active!="boolean"&&W("invalid_input"),q},v=(C,H=!1)=>{(C.sourceId!==r.sourceId||C.sourceGeneration!==r.sourceGeneration||!Ae(C.generations,r.generations))&&W("stale_generation"),(C.state==="closed"||!H&&C.state==="closing")&&W("binding_closed")},g=(C,H,j)=>{v(C,!0),(H.bindingId!==r.bindingId||H.sourceId!==r.sourceId||H.sourceGeneration!==r.sourceGeneration||!Ae(H.generations,r.generations))&&W("stale_generation"),(!C.operationEpoch.active||H.request.operationEpoch!==C.operationEpoch.id||C.nowMs>=C.operationEpoch.expiresAtMs)&&W("epoch_expired"),ue(C.revision)<ue(j)&&W("reconciliation_required"),H.expectedRevision!==C.revision&&W("revision_conflict")},b=C=>{$o.has(e)&&(ts(e),W("reentrant")),$o.add(e);try{return C()}finally{$o.delete(e)}},A=C=>{let H=[],j=0;for(let x of Je(e).snapshot().inventory.entries){if(x.bindingId!==r.bindingId||!x.entryId.startsWith(C))continue;let{witness:q}=Je(e).readEntry({bindingId:r.bindingId,entryId:x.entryId,offset:0,maxBytes:1});j+=q.metadataBytes,(j>di||H.length>=8192)&&W("capacity_exceeded");let F=Ee(Buffer.from(q.metadata));(!F||F.format!==Mn)&&W("integrity_mismatch"),H.push({entryId:x.entryId,metadataBytes:q.metadataBytes,value:F})}return H},S=(C,H,j)=>{Je(e).snapshot().inventory.reservations.some(x=>x.bindingId===r.bindingId&&x.operationKey!==C&&x.operationKey!==H?.operationKey&&x.operationKey!==j?.operationKey)&&W("reconciliation_required");for(let x of[H,j])if(x){let q=e.status(x);q&&(q.state!=="reserved"||!Ae(q.reservation,x))&&W("operation_conflict")}},k=(C,H,j=new Uint8Array(0))=>({entryId:C,basket:"original",metadata:Mt(H),body:j}),I=(C,H,j)=>{let x=e.status({bindingId:r.bindingId,operationKey:C});x&&x.reservation.intentDigest!==H&&W("operation_conflict"),j&&(x?.state!=="committed"||!x.receipt.entries.some(q=>q.entryId===j))&&W("integrity_mismatch")},m=(C,H,j,x,q)=>{I(C,H),x&&I(x.reservation.operationKey,x.reservation.intentDigest),S(C,x?.reservation,q);let F=C.startsWith("sx-")?"sx-":C.startsWith("sr-")?"sr-":"sa-",L=A(F),a=new Set(L.map(K=>K.entryId)),T=[...j,...x?[x.entry]:[]].filter(K=>!a.has(K.entryId));(L.length+T.length>8192||L.reduce((K,V)=>K+V.metadataBytes,0)+T.reduce((K,V)=>K+Buffer.byteLength(V.metadata),0)>di)&&W("capacity_exceeded");let D=j.reduce((K,V)=>K+Buffer.byteLength(V.metadata)+V.body.byteLength+64,0);return{bindingId:r.bindingId,operationKey:C,intentDigest:H,originalMax:{bytes:D,records:j.length},terminalReserve:{bytes:1,records:1}}},w=(C,H,j,x,q)=>{let F=m(C,H,j,x,q);x&&e.reserve(x.reservation),e.reserve(F),e.commit({bindingId:r.bindingId,operationKey:C,intentDigest:H,entries:j})};return{config:{...r,spool:e,readAuthority:n},spool:e,semantic:d,key:l,receipt:p,auth:u,admit:g,current:v,guard:b,rows:A,pending:S,entry:k,reconcile:I,prepareCommit:m,commit:w}}function wl(t){let e=new Map;for(let n of t)for(let r of[n.payload,...n.attachments]){let i=e.get(r.artifactId);i&&!Ae(i,r)&&W("integrity_mismatch"),e.set(r.artifactId,r)}return e}function Eh(t){let e=Al(t),{config:n,spool:r}=e,{journal:i}=t,o=t.requiredReplica===void 0?void 0:it(t.requiredReplica);o&&(ht(o,["policyId","policyGeneration","replicaId"]),ot(o.policyId),ot(o.policyGeneration),ot(o.replicaId));let s=()=>{let I=e.rows("sr-policy");if(I.length){(!o||I.length!==1||I[0].entryId!=="sr-policy"||!Ae(I[0].value.policy,o))&&W("operation_conflict");return}if(o){let m={format:Mn,kind:"replica-policy",policy:o};e.commit("sr-policy",li(Mt(m)),[e.entry("sr-policy",m)])}},c=I=>{if(s(),!o)return;let m=e.rows(`sr-proof-${e.key(I)}`);(m.length!==1||m[0].value.kind!=="replica-proof"||!Ae(m[0].value.policy,o)||!Ae(m[0].value.ack,I))&&W("dependency_held")};e.guard(s);let d=t.bindingControl===void 0?void 0:hr({...t.bindingControl,spool:r}),l=()=>{if(!d)return;let I=d.read();I||W("reconciliation_required");let m=Je(r).bindingIdentity(n.bindingId),w=I.registration;return(w.bindingId!==n.bindingId||w.sourceId!==n.sourceId||w.sourceGeneration!==n.sourceGeneration||!w.relatedBindingIds.includes(n.bindingId)||w.scope.applicationScopeId!==m.applicationScopeId||w.scope.endUserId!==m.endUserId)&&W("integrity_mismatch"),I},p=(I,m)=>m?(m.state==="unbound"&&W("binding_closed"),{...I,revision:m.revision,state:m.state,generations:m.target.generations,sourceId:m.registration.sourceId,sourceGeneration:m.registration.sourceGeneration,operationEpoch:{id:m.epoch.id,active:m.epoch.active,expiresAtMs:m.epoch.expiresAtMs},releaseReady:I.releaseReady&&m.fence===null}):I,u=()=>{let I=e.rows("sa-").map(x=>{let q=St(x.value.ack,n.controlBytes),F=x.value.receipt;(x.value.kind!=="ack"||x.entryId!==`sa-${e.key(q)}`||!Ae(F,e.receipt(q)))&&W("integrity_mismatch");let L=x.value.previous===void 0?void 0:St(x.value.previous,n.controlBytes);return L&&(Ae(L.request,q.request)||ue(q.expectedRevision)<=ue(L.expectedRevision)||!Ae({...q,request:L.request,expectedRevision:L.expectedRevision},L))&&W("integrity_mismatch"),{ack:q,receipt:F,...L?{previous:L}:{}}}).sort((x,q)=>ue(x.receipt.revision)<ue(q.receipt.revision)?-1:1),m=new Set(I.map(x=>e.key(x.ack))),w=new Set;for(let x of I)if(x.previous){let q=e.key(x.previous);(m.has(q)||w.has(q))&&W("integrity_mismatch"),w.add(q)}let C=null,H="0",j=null;for(let x of I)(ue(x.ack.coverage.fromSequence)>(C?ue(C.sequence):0n)+1n||ue(x.ack.coverage.throughSequence)<(C?ue(C.sequence):0n)||ue(x.receipt.revision)<=ue(H))&&W("integrity_mismatch"),C={sequence:x.ack.coverage.throughSequence,recordDigest:x.ack.coverage.headDigest},H=x.receipt.revision,j=x.ack.coverage;return{rows:I,head:C,floor:H,coverage:j}},v=I=>{let m=ue(I.throughSequence)-ue(I.fromSequence)+1n,w=[],C=ue(I.fromSequence)===1n?null:String(ue(I.fromSequence)-1n);for(;w.length<Number(m);){let H=i.list({generations:n.generations,afterSequence:C,limit:Number(m)-w.length,maxBytes:1048576});H.records.length||W("head_conflict"),w.push(...H.records),C=w.at(-1).sequence}return w.at(-1).recordDigest!==I.headDigest&&W("integrity_mismatch"),w},g=(I,m)=>{m.bindingId!==n.bindingId&&W("invalid_input");let w=I.rows.find(C=>e.key(C.ack)===e.key(m));return w&&!Ae(w.ack,m)&&W("operation_conflict"),w},b=(I,m)=>{if(d){let w=d.query("archive-ack",I.request);w?.receipt?.semanticDigest!==void 0&&w.receipt.semanticDigest!==e.semantic(I)&&W("operation_conflict"),(m?!w?.receipt||!Ae(w.receipt,m.receipt):w!==null)&&W("integrity_mismatch")}e.reconcile(`sa-ack-${e.key(I)}`,e.semantic(I),m?`sa-${e.key(I)}`:void 0)},A=I=>{let m=ht(I,["protocol","bindingId","previous","request"]),w=St(m.previous,n.controlBytes),C=Vo(m.request);return(m.protocol!=="sdk2-ext-v1"||m.bindingId!==n.bindingId||w.bindingId!==n.bindingId)&&W("invalid_input"),Ae(w.request,C)&&W("operation_conflict"),w.request.operationEpoch!==C.operationEpoch&&W("epoch_expired"),{protocol:"sdk2-ext-v1",bindingId:n.bindingId,previous:w,request:C}},S=(I,m)=>{let w=m.rows.find(C=>e.key(C.ack)===e.key({bindingId:n.bindingId,request:I.request}));return w?((!w.previous||!Ae(w.previous,I.previous))&&W("operation_conflict"),b(w.ack,w),it({...I,next:w.ack,receipt:w.receipt})):null},k={controlBytes:n.controlBytes,acknowledge(I){return e.guard(()=>{let m=St(I,n.controlBytes),w=u(),C=e.auth("acknowledge",w.floor,w.coverage),H=l(),j=g(w,m);if(j)return b(m,j),it(j.receipt);d&&b(m,void 0);let x=p(C,H);e.admit(x,m,w.floor),c(m);let q=w.head?ue(w.head.sequence):0n;(ue(m.coverage.fromSequence)>q+1n||ue(m.coverage.throughSequence)<q)&&W("head_conflict");let F=v(m.coverage);Ae(Hn(n,m.request,m.expectedRevision,F),m)||W("integrity_mismatch");let L=e.receipt(m),a=[e.entry(`sa-${e.key(m)}`,{format:Mn,kind:"ack",ack:m,receipt:L})];if(d){let T=e.prepareCommit(`sa-ack-${e.key(m)}`,e.semantic(m),a),D=d.mutate({kind:"archive-ack",body:m},{companion:{reservation:T,entries:a}});Ae(D.receipt,L)||W("integrity_mismatch")}else e.commit(`sa-ack-${e.key(m)}`,e.semantic(m),a);return it(L)})},recordRequiredReplica(I){return e.guard(()=>{o||W("invalid_input");let m=St(I,n.controlBytes),w=u(),C=p(e.auth("acknowledge",w.floor,w.coverage),l());e.current(C,!0),s();let H=`sr-proof-${e.key(m)}`,j={format:Mn,kind:"replica-proof",policy:o,ack:m},x=e.rows(H);if(x.length){(x.length!==1||!Ae(x[0].value,j))&&W("operation_conflict");return}e.admit(C,m,w.floor),Ae(Hn(n,m.request,m.expectedRevision,v(m.coverage)),m)||W("integrity_mismatch"),e.commit(H,li(Mt(j)),[e.entry(H,j)])})},queryAck(I){return e.guard(()=>{let m=St(I,n.controlBytes),w=u();e.auth("query",w.floor,w.coverage),l();let C=g(w,m);return b(m,C),it(C?.receipt??null)})},queryAckRebase(I){return e.guard(()=>{let m=A(I),w=u();return e.auth("query",w.floor,w.coverage),l(),S(m,w)})},acknowledgeRebased(I,m){return e.guard(()=>{(!d||!t.bindingControl)&&W("invalid_input");let w=A(I),C=u(),H=e.auth("acknowledge",C.floor,C.coverage),j=l(),x=S(w,C);if(x)return x;C.rows.some(Z=>Z.previous&&(e.key(Z.previous)===e.key(w.previous)||e.key(Z.previous)===e.key({bindingId:n.bindingId,request:w.request})))&&W("operation_conflict");let q=g(C,w.previous);b(w.previous,q),q&&W("operation_conflict");let F=p(H,j);(!j||j.fence!==null)&&W("dependency_held"),ds(m,{storageBindingId:t.bindingControl.storageBindingId,slotId:t.bindingControl.slotId},F.revision),ue(F.revision)<=ue(w.previous.expectedRevision)&&W("revision_conflict");let L=St({...w.previous,request:w.request,expectedRevision:F.revision},n.controlBytes);e.admit(F,L,C.floor),Ae(Hn(n,w.previous.request,w.previous.expectedRevision,v(w.previous.coverage)),w.previous)||W("integrity_mismatch");let a=C.head?ue(C.head.sequence):0n;(ue(L.coverage.fromSequence)>a+1n||ue(L.coverage.throughSequence)<a)&&W("head_conflict"),c(w.previous);let T=e.receipt(L),D=[e.entry(`sa-${e.key(L)}`,{format:Mn,kind:"ack",ack:L,receipt:T,previous:w.previous})];o&&D.push(e.entry(`sr-proof-${e.key(L)}`,{format:Mn,kind:"replica-proof",policy:o,ack:L}));let K=e.prepareCommit(`sa-ack-${e.key(L)}`,e.semantic(L),D),V=d.mutate({kind:"archive-ack",body:L},{idleLease:m,companion:{reservation:K,entries:D}});return Ae(V.receipt,T)||W("integrity_mismatch"),it({...w,next:L,receipt:T})})},preflightAckRebase(I){return e.guard(()=>{d||W("invalid_input");let m=ht(I,["ack","request"]),w=St(m.ack,n.controlBytes),C=Vo(m.request);Ae(C,w.request)&&W("operation_conflict");let H=q=>{let F=u(),L=e.auth("query",F.floor,F.coverage),a=l(),T=g(F,w);b(w,T),T&&W("operation_conflict");let D=p(L,a);ue(D.revision)<=ue(w.expectedRevision)&&W("revision_conflict");let K=q??St({...w,request:C,expectedRevision:D.revision},n.controlBytes);e.admit(D,K,F.floor);let V=v(w.coverage);return Ae(Hn(n,w.request,w.expectedRevision,V),w)||W("integrity_mismatch"),K},j=H(),x=Object.freeze({kind:"sdk2-ack-rebase-proof"});return bl.set(x,{previous:w,next:j,scope:Je(r).bindingIdentity(n.bindingId),validate(){e.guard(()=>{H(j)})}}),x})},status(){return e.guard(()=>{let I=u();return e.auth("query",I.floor,I.coverage),l(),it({head:I.head,revisionFloor:I.floor})})},readPage(I){return e.guard(()=>{let m=it(I);ht(m,["afterSequence","limit"]),pr(m.limit,1,128);let w=u();return e.current(p(e.auth("read",w.floor,w.coverage),l()),!0),i.list({generations:n.generations,...m,maxBytes:1048576})})},readArtifactBody(I){return e.guard(()=>{let m=it(I),w=u();e.current(p(e.auth("read",w.floor,w.coverage),l()),!0),pr(m.bytes,1,vl);let C=i.readArtifactBody({generations:n.generations,artifactId:m.artifactId,maxBytes:m.bytes});return Ae(C.artifact,m)||W("integrity_mismatch"),C})},releaseAcknowledged(){return e.guard(()=>{let I=u(),m=p(e.auth("release",I.floor,I.coverage),l());if(e.current(m,!0),ue(m.revision)<ue(I.floor)&&W("reconciliation_required"),m.releaseReady||W("dependency_held"),e.pending(),!I.head)return{releasedBytes:0,artifactIds:[]};let w=new Map;for(let x of I.rows){c(x.ack);let q=v(x.ack.coverage);Ae(Hn(n,x.ack.request,x.ack.expectedRevision,q),x.ack)||W("integrity_mismatch");for(let[F,L]of Jc(q)){let a=w.get(F);a&&!Ae(a,L)&&W("integrity_mismatch"),w.set(F,L)}}let C=I.head.sequence;for(;;){let x=i.list({generations:n.generations,afterSequence:C,limit:128,maxBytes:1048576});for(let q of x.records)for(let F of[q.payload,...q.attachments])w.delete(F.artifactId);if(x.complete)break;x.records.length||W("integrity_mismatch"),C=x.records.at(-1).sequence}let H=[...w.keys()];return H.length?{releasedBytes:r.ackAndRelease({bindingId:n.bindingId,entryIds:H},x=>{for(let q of x){let F=w.get(q.entryId);(!F||q.basket!=="original"||q.bodySha256!==F.sha256||q.bodyBytes!==F.bytes)&&W("integrity_mismatch")}return!0}).releasedBytes,artifactIds:H}:{releasedBytes:0,artifactIds:H}})}};return os(k,{spool:r,bindingId:n.bindingId,read:()=>e.guard(()=>{let I=u(),m=p(e.auth("query",I.floor,I.coverage),l());(m.sourceId!==n.sourceId||m.sourceGeneration!==n.sourceGeneration||!Ae(m.generations,n.generations))&&W("stale_generation"),ue(m.revision)<ue(I.floor)&&W("reconciliation_required");let w=is(i,r,n.bindingId);for(let F of I.rows){let L=Number(ue(F.ack.coverage.fromSequence,1n)),a=Number(ue(F.ack.coverage.throughSequence,1n));(a>w.records.length||L>a||!Ae(Hn(n,F.ack.request,F.ack.expectedRevision,w.records.slice(L-1,a)),F.ack))&&W("integrity_mismatch")}let C=I.head===null?0n:ue(I.head.sequence,1n),H=w.records.filter(F=>ue(F.sequence,1n)>C),j=wl(H),x=0;for(let F of j.values())x+=F.bytes,(!Number.isSafeInteger(x)||x>di)&&W("capacity_exceeded");H.length>4096&&W("capacity_exceeded");let q=m.releaseReady&&ns(r,n.bindingId);return{protocol:"sdk2-ext-v1",bindingId:n.bindingId,revision:m.revision,generations:n.generations,sourceId:n.sourceId,sourceGeneration:n.sourceGeneration,publishedThroughSequence:w.head?.sequence??null,acknowledgedCoverage:I.head===null?null:{fromSequence:"1",throughSequence:I.head.sequence,headDigest:I.head.recordDigest},releasableThroughSequence:q?I.head?.sequence??null:null,pendingBytes:x,pendingRecords:H.length,sessionPersistence:"unchanged",state:m.state}})}),k}export{gi as a,wr as b,xs as c,Os as d,Ln as e,Ps as f,bi as g,Xc as h,Yc as i,Ii as j,Es as k,Bl as l,xl as m,Gn as n,kn as o,Ai as p,Ts as q,ql as r,Tl as s,Zn as t,ba as u,Ci as v,Gl as w,id as x,Cr as y,Vi as z,Ks as A,Ls as B,Wl as C,zt as D,pu as E,bu as F,ca as G,Ft as H,yd as I,ya as J,Pr as K,fu as L,jf as M,Hg as N,Mg as O,Go as P,Kg as Q,Lg as R,Gg as S,bh as T,Ih as U,Ah as V,wh as W,fd as X,Bt as Y,Bu as Z,xu as _,Ou as $,co as aa,yy as ba,Py as ca,Ey as da,el as ea,qy as fa,yc as ga,fc as ha,ef as ia,Fi as ja,tf as ka,hd as la,nf as ma,jt as na,md as oa,Dt as pa,Qg as qa,eh as ra,th as sa,nh as ta,rh as ua,ih as va,Uc as wa,oh as xa,sh as ya,ga as za,vd as Aa,ah as Ba,ci as Ca,Hn as Da,Eh as Ea,Za as Fa};
|
|
25
|
-
//# sourceMappingURL=tansr-chunk-BX7CF5RQ.mjs.map
|