@tansr/cli 0.9.0 → 0.10.1

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.
Files changed (87) hide show
  1. package/NOTICE +1 -1
  2. package/package.json +1 -1
  3. package/tansr-artifacts.json +1309 -0
  4. package/tansr-bg-OUP4JX3I.mjs +5 -0
  5. package/tansr-chunk-2AJTBN37.mjs +29 -0
  6. package/tansr-chunk-2C6JKHKM.mjs +25 -0
  7. package/tansr-chunk-2QKLANZQ.mjs +7 -0
  8. package/tansr-chunk-3GJD3L4B.mjs +22 -0
  9. package/tansr-chunk-4R5ZK4RG.mjs +21 -0
  10. package/tansr-chunk-54YMMSEF.mjs +35 -0
  11. package/tansr-chunk-5T7X32UX.mjs +6 -0
  12. package/tansr-chunk-5VWLEU5D.mjs +4 -0
  13. package/tansr-chunk-726Y5F3M.mjs +5 -0
  14. package/tansr-chunk-AEIS2NWD.mjs +37 -0
  15. package/tansr-chunk-AMMPDY4V.mjs +5 -0
  16. package/tansr-chunk-BCOFZJWA.mjs +279 -0
  17. package/tansr-chunk-BX7CF5RQ.mjs +25 -0
  18. package/tansr-chunk-C6COFFZK.mjs +12 -0
  19. package/tansr-chunk-C7GGA5ID.mjs +5 -0
  20. package/tansr-chunk-DIT3PBNB.mjs +5 -0
  21. package/tansr-chunk-F5STVU7J.mjs +5 -0
  22. package/tansr-chunk-F7C6ITED.mjs +5 -0
  23. package/tansr-chunk-HQY7FXGU.mjs +67 -0
  24. package/tansr-chunk-HRKJLVKC.mjs +7 -0
  25. package/tansr-chunk-I3TOVAA6.mjs +5 -0
  26. package/tansr-chunk-J2ED6CI4.mjs +5 -0
  27. package/tansr-chunk-LLW6GX7K.mjs +38 -0
  28. package/tansr-chunk-LSGFLGLS.mjs +7 -0
  29. package/tansr-chunk-M63EZH2M.mjs +8 -0
  30. package/tansr-chunk-M774GK3P.mjs +6 -0
  31. package/tansr-chunk-MWHLITGY.mjs +11 -0
  32. package/tansr-chunk-MXYVQZY3.mjs +5 -0
  33. package/tansr-chunk-NA22YT73.mjs +5 -0
  34. package/tansr-chunk-NCIMR6LB.mjs +5 -0
  35. package/tansr-chunk-NROI7AG5.mjs +5 -0
  36. package/tansr-chunk-OKAA4BJC.mjs +5 -0
  37. package/tansr-chunk-OSK64SU3.mjs +5 -0
  38. package/tansr-chunk-PIET7WB3.mjs +5 -0
  39. package/tansr-chunk-Q6MUMULP.mjs +5 -0
  40. package/tansr-chunk-QEKVLX7W.mjs +5 -0
  41. package/tansr-chunk-QHEQQ2JB.mjs +9 -0
  42. package/tansr-chunk-QNHXB55W.mjs +11 -0
  43. package/tansr-chunk-QWGSXFEJ.mjs +7 -0
  44. package/tansr-chunk-R4W5HKDF.mjs +12 -0
  45. package/tansr-chunk-RRAMVVYF.mjs +5 -0
  46. package/tansr-chunk-RVSBSUXE.mjs +5 -0
  47. package/tansr-chunk-S3KHAGOR.mjs +5 -0
  48. package/tansr-chunk-S77B4PI7.mjs +6 -0
  49. package/tansr-chunk-SJFDQLLC.mjs +5 -0
  50. package/tansr-chunk-TYJWMSVW.mjs +5 -0
  51. package/tansr-chunk-UAEARRRH.mjs +8 -0
  52. package/tansr-chunk-WW5ZPL6Q.mjs +5 -0
  53. package/tansr-chunk-XAQNKJIC.mjs +4 -0
  54. package/tansr-chunk-XIOD3RQD.mjs +23 -0
  55. package/tansr-chunk-XXBNISJJ.mjs +7 -0
  56. package/tansr-chunk-YAYVXUHY.mjs +6 -0
  57. package/tansr-chunk-ZQ3ZK7IL.mjs +37 -0
  58. package/tansr-ink-devtools-stub-GTR5M7WR.mjs +4 -0
  59. package/tansr-main-O6RSYTGN.mjs +7 -0
  60. package/tansr-marked.esm-R6UL3675.mjs +68 -0
  61. package/tansr-portal-FWLKNJM2.mjs +5 -0
  62. package/tansr-render-PUEISX75.mjs +6 -0
  63. package/tansr-run-acp-entry-XJMGBZ7Q.mjs +63 -0
  64. package/tansr-run-approvals-entry-I6FX6AYX.mjs +12 -0
  65. package/tansr-run-auth-entry-LJC3UJWR.mjs +36 -0
  66. package/tansr-run-doctor-RFMVNKS5.mjs +10 -0
  67. package/tansr-run-headless-entry-G2G44HY3.mjs +78 -0
  68. package/tansr-run-init-entry-JVJEH4PI.mjs +5 -0
  69. package/tansr-run-logout-entry-DI42PBLR.mjs +5 -0
  70. package/tansr-run-mcp-serve-entry-ZPOSEKDA.mjs +14 -0
  71. package/tansr-run-orchestrate-entry-43QIZUZA.mjs +11 -0
  72. package/tansr-run-org-entry-D2FTJY7E.mjs +17 -0
  73. package/tansr-run-policy-entry-SLI4BZ2I.mjs +16 -0
  74. package/tansr-run-profile-entry-643TLJUU.mjs +14 -0
  75. package/tansr-run-serve-entry-CX6EBQAV.mjs +99 -0
  76. package/tansr-run-sessions-entry-MROXZKQS.mjs +23 -0
  77. package/tansr-run-update-entry-BOZIZIWN.mjs +5 -0
  78. package/tansr-sqlite-event-store-UQLSSZKP.mjs +26 -0
  79. package/tansr-sqlite-spool-implementation-LHEIRSUX.mjs +29 -0
  80. package/tansr-src-5BMLUX6E.mjs +143 -0
  81. package/tansr-src-KOEPYVXX.mjs +5 -0
  82. package/tansr-startup-account-YMNFBBH2.mjs +7 -0
  83. package/tansr-startup-model-LYYMNZ32.mjs +6 -0
  84. package/tansr-tui-4EYUVRFQ.mjs +75 -0
  85. package/tansr-undici.cjs +49 -0
  86. package/tansr.mjs +1 -1180
  87. package/tansrd.mjs +772 -0
@@ -0,0 +1,23 @@
1
+ import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
2
+ import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
3
+ const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
4
+ import{a as r,j as S,k as w,l as A,n as E,o as x}from"./tansr-chunk-UAEARRRH.mjs";import"./tansr-chunk-NCIMR6LB.mjs";import{a as g}from"./tansr-chunk-Q6MUMULP.mjs";import{x as b}from"./tansr-chunk-M63EZH2M.mjs";import"./tansr-chunk-XXBNISJJ.mjs";import"./tansr-chunk-3GJD3L4B.mjs";import"./tansr-chunk-HRKJLVKC.mjs";import{ef as f}from"./tansr-chunk-BCOFZJWA.mjs";import"./tansr-chunk-C7GGA5ID.mjs";import"./tansr-chunk-2C6JKHKM.mjs";import"./tansr-chunk-OKAA4BJC.mjs";import"./tansr-chunk-OSK64SU3.mjs";import"./tansr-chunk-ZQ3ZK7IL.mjs";import"./tansr-chunk-I3TOVAA6.mjs";import"./tansr-chunk-F7C6ITED.mjs";import"./tansr-chunk-DIT3PBNB.mjs";import{k as y,m as i,o as k}from"./tansr-chunk-NA22YT73.mjs";import"./tansr-chunk-QWGSXFEJ.mjs";import"./tansr-chunk-RRAMVVYF.mjs";import{writeFile as h}from"node:fs/promises";import O from"node:path";function L(a){let s=r.exportUsage,o,l,t=[];for(let d=0;d<a.length;d++){let p=a[d];if(p==="--format"||p==="--out"){let c=a[d+1];if(c===void 0||c.startsWith("-"))return{ok:!1,key:f.missingValue,params:{flag:p},usageKey:s};p==="--format"?o=c:l=c,d+=1;continue}if(p.startsWith("-"))return{ok:!1,key:f.unknownFlag,params:{flag:p},usageKey:s};t.push(p)}let[u,n]=t;if(u===void 0)return{ok:!1,key:r.exportUsage,usageKey:s};if(n!==void 0)return{ok:!1,key:f.unexpectedArg,params:{arg:n},usageKey:s};let e=o??"md";return e!=="md"&&e!=="json"?{ok:!1,key:r.exportUnknownFormat,params:{format:e},usageKey:s}:{ok:!0,action:"export",id:u,format:e,...l!==void 0?{out:l}:{}}}function P(a){let s=r.pruneUsage,o=!1,l=!1,t=w,u=A;for(let n=0;n<a.length;n++){let e=a[n];if(e==="--apply"){o=!0;continue}if(e==="--include-broken"){l=!0;continue}if(e==="--keep-days"||e==="--keep-last"){let d=a[n+1];if(d===void 0||d.startsWith("-"))return{ok:!1,key:f.missingValue,params:{flag:e},usageKey:s};if(!/^\d+$/.test(d))return{ok:!1,key:r.pruneInvalidNumber,params:{flag:e,value:d},usageKey:s};e==="--keep-days"?t=Number(d):u=Number(d),n+=1;continue}return e.startsWith("-")?{ok:!1,key:f.unknownFlag,params:{flag:e},usageKey:s}:{ok:!1,key:f.unexpectedArg,params:{arg:e},usageKey:s}}return{ok:!0,action:"prune",apply:o,keepDays:t,keepLast:u,includeBroken:l}}function D(a){let[s,...o]=a;return s===void 0?{ok:!1,key:r.usage,usageKey:r.usage}:s==="export"?L(o):s==="prune"?P(o):s.startsWith("-")?{ok:!1,key:f.unknownFlag,params:{flag:s},usageKey:r.usage}:{ok:!1,key:f.unexpectedArg,params:{arg:s},usageKey:r.usage}}function m(a){return new Date(a).toISOString()}async function F(a,s,o,l){let t=await E(s,{keepDays:a.keepDays,keepLast:a.keepLast});for(let n of t.candidates)o.write(i(r.pruneCandidate,{sessionId:n.sessionId,updatedAt:m(n.updatedAt),bytes:n.bytes})+`
5
+ `);for(let n of t.sidecarOnly)o.write(i(r.pruneSidecarOnlyEntry,{name:n.name,updatedAt:m(n.mtimeMs),bytes:n.bytes})+`
6
+ `);for(let n of t.broken)o.write(i(r.pruneBrokenEntry,{name:n.name,bytes:n.bytes})+`
7
+ `);if(t.broken.length>0&&!(a.apply&&a.includeBroken)&&o.write(i(r.pruneBrokenHint,{count:t.broken.length})+`
8
+ `),t.candidates.length>0){let n=t.candidates.reduce((e,d)=>e+d.bytes,0);o.write(i(r.pruneSummary,{count:t.candidates.length,bytes:n,oldest:m(t.candidates[0].updatedAt),newest:m(t.candidates[t.candidates.length-1].updatedAt)})+`
9
+ `)}else t.sidecarOnly.length===0&&o.write(i(r.pruneNothing)+`
10
+ `);if(t.totalSidecarOnly>0&&o.write(i(r.pruneSidecarOnlySummary,{count:t.sidecarOnly.length,bytes:t.sidecarOnly.reduce((n,e)=>n+e.bytes,0),kept:t.sidecarOnlyKeptCount})+`
11
+ `),o.write(i(r.pruneKept,{count:t.keptCount,days:a.keepDays,last:a.keepLast,inUse:t.inUseCount})+`
12
+ `),!a.apply)return o.write(i(r.pruneDryRunHint)+`
13
+ `),0;let u=await x(t,{includeBroken:a.includeBroken,onDeleted:n=>{o.write(i(r.pruneDeleted,{sessionId:n.name,bytes:n.bytes})+`
14
+ `)}});for(let n of u.skippedLocked)o.write(i(r.pruneSkippedLocked,{sessionId:n})+`
15
+ `);for(let n of u.skippedFresh)o.write(i(r.pruneSkippedFresh,{sessionId:n})+`
16
+ `);return u.aborted!==void 0?(l.write(i(r.pruneAborted,{name:u.aborted.name,message:u.aborted.message,deleted:u.deleted.length})+`
17
+ `),1):(o.write(i(r.pruneApplied,{count:u.deleted.length,bytes:u.deleted.reduce((n,e)=>n+e.bytes,0)})+`
18
+ `),0)}async function R(a,s={}){let o=s.stdout??process.stdout,l=s.stderr??process.stderr,t=s.env??process.env,u=s.cwd??process.cwd(),n=await b({cwd:u,env:t,...s.loadOptions!==void 0?{loadOptions:s.loadOptions}:{}});y(k({configLocale:n.loaded.locale,env:t}));let e=D(a);if(!e.ok)return l.write(i(e.key,e.params)+`
19
+ `),e.key!==e.usageKey&&l.write(i(e.usageKey)+`
20
+ `),1;let d=g(t);if(e.action==="prune")return F(e,d,o,l);let p=await S(d,e.id,e.format);if(!p.ok)return l.write((p.reason==="not_found"?i(r.exportNotFound,{sessionId:e.id}):i(r.exportFailed,{sessionId:e.id,detail:`${p.reason}: ${p.detail}`}))+`
21
+ `),1;if(e.out!==void 0){let c=O.resolve(u,e.out);return await h(c,p.text,"utf8"),o.write(i(r.exportWritten,{path:c})+`
22
+ `),0}return o.write(p.text),0}export{D as parseSessionsArgs,R as runSessionsEntry};
23
+ //# sourceMappingURL=tansr-run-sessions-entry-MROXZKQS.mjs.map
@@ -0,0 +1,5 @@
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{i as a,j as b,k as c}from"./tansr-chunk-4R5ZK4RG.mjs";import"./tansr-chunk-M774GK3P.mjs";import"./tansr-chunk-HQY7FXGU.mjs";import"./tansr-chunk-PIET7WB3.mjs";import"./tansr-chunk-S77B4PI7.mjs";import"./tansr-chunk-NCIMR6LB.mjs";import"./tansr-chunk-Q6MUMULP.mjs";import"./tansr-chunk-QEKVLX7W.mjs";import"./tansr-chunk-726Y5F3M.mjs";import"./tansr-chunk-M63EZH2M.mjs";import"./tansr-chunk-XXBNISJJ.mjs";import"./tansr-chunk-F5STVU7J.mjs";import"./tansr-chunk-2QKLANZQ.mjs";import"./tansr-chunk-J2ED6CI4.mjs";import"./tansr-chunk-3GJD3L4B.mjs";import"./tansr-chunk-HRKJLVKC.mjs";import"./tansr-chunk-BCOFZJWA.mjs";import"./tansr-chunk-C7GGA5ID.mjs";import"./tansr-chunk-2C6JKHKM.mjs";import"./tansr-chunk-OKAA4BJC.mjs";import"./tansr-chunk-OSK64SU3.mjs";import"./tansr-chunk-ZQ3ZK7IL.mjs";import"./tansr-chunk-I3TOVAA6.mjs";import"./tansr-chunk-F7C6ITED.mjs";import"./tansr-chunk-DIT3PBNB.mjs";import"./tansr-chunk-NA22YT73.mjs";import"./tansr-chunk-QWGSXFEJ.mjs";import"./tansr-chunk-RRAMVVYF.mjs";export{a as ALLOW_UNSIGNED_CONFIRM_TOKEN,b as parseUpdateArgs,c as runUpdateEntry};
5
+ //# sourceMappingURL=tansr-run-update-entry-BOZIZIWN.mjs.map
@@ -0,0 +1,26 @@
1
+ import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
2
+ import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
3
+ const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
4
+ import{a as W,b as N,c as i,d as P,e as R,f as v,g as C,h as T,i as k,j as L,k as O,l as q,m as I,n as M,o as B,p as U,q as x,r as D,s as j,t as Y,u as z}from"./tansr-chunk-QHEQQ2JB.mjs";import"./tansr-chunk-SJFDQLLC.mjs";import"./tansr-chunk-I3TOVAA6.mjs";import"./tansr-chunk-F7C6ITED.mjs";import"./tansr-chunk-RRAMVVYF.mjs";import{randomBytes as J,timingSafeEqual as $}from"node:crypto";import{closeSync as Z,lstatSync as ee,openSync as te}from"node:fs";import{isAbsolute as se}from"node:path";import{DatabaseSync as ne}from"node:sqlite";import{types as Q}from"node:util";var X="sdk2-events-v1",F=32768,H=1048576,re=`
5
+ CREATE TABLE event_meta (
6
+ id INTEGER PRIMARY KEY NOT NULL CHECK(id=1), format TEXT NOT NULL, store_id TEXT NOT NULL,
7
+ event_db_id BLOB NOT NULL CHECK(length(event_db_id)=32), key_check BLOB NOT NULL CHECK(length(key_check)=32)
8
+ ) STRICT;
9
+ CREATE TABLE event_stream (
10
+ scope_key BLOB PRIMARY KEY NOT NULL CHECK(length(scope_key)=32), scope_json BLOB NOT NULL CHECK(length(scope_json)<=4096),
11
+ installation_id TEXT NOT NULL CHECK(length(installation_id) BETWEEN 1 AND 128), life BLOB NOT NULL CHECK(length(life)=32),
12
+ gen INTEGER NOT NULL CHECK(gen>=1), floor INTEGER NOT NULL CHECK(floor>=0), head INTEGER NOT NULL CHECK(head>=floor),
13
+ state TEXT NOT NULL CHECK(state IN('rebuilding','ready')), limits_json BLOB NOT NULL CHECK(length(limits_json)<=1024),
14
+ stored_bytes INTEGER NOT NULL CHECK(stored_bytes>=0), wire_bytes INTEGER NOT NULL CHECK(wire_bytes>=0), rows INTEGER NOT NULL CHECK(rows BETWEEN 0 AND 4096)
15
+ ) STRICT, WITHOUT ROWID;
16
+ CREATE TABLE event_row (
17
+ scope_key BLOB NOT NULL CHECK(length(scope_key)=32), gen INTEGER NOT NULL CHECK(gen>=1), seq INTEGER NOT NULL CHECK(seq>=1),
18
+ first_seq INTEGER NOT NULL CHECK(first_seq>=1), last_seq INTEGER NOT NULL CHECK(last_seq>=first_seq AND seq BETWEEN first_seq AND last_seq AND last_seq-first_seq<8),
19
+ batch_digest BLOB NOT NULL CHECK(length(batch_digest)=32), created_ms INTEGER NOT NULL CHECK(created_ms BETWEEN 0 AND 9007199254740991),
20
+ draft_json BLOB NOT NULL CHECK(length(draft_json)<=262144), fact_digest BLOB NOT NULL CHECK(length(fact_digest)=32),
21
+ wire_bytes INTEGER NOT NULL CHECK(wire_bytes BETWEEN 1 AND 262317), stored_bytes INTEGER NOT NULL CHECK(stored_bytes=length(draft_json)+512),
22
+ PRIMARY KEY(scope_key,gen,seq), FOREIGN KEY(scope_key) REFERENCES event_stream(scope_key)
23
+ ) STRICT, WITHOUT ROWID;
24
+ CREATE INDEX event_batch ON event_row(scope_key,gen,first_seq);
25
+ `,h=E=>Buffer.from(E,"hex");function b(E){return(typeof E!="bigint"||E<0n||E>BigInt(Number.MAX_SAFE_INTEGER))&&i("stream_gap"),Number(E)}function y(E,t=32){return(!Q.isUint8Array(E)||E.byteLength!==t)&&i("stream_gap"),Buffer.from(E).toString("hex")}function V(E){if(E instanceof W)throw E;let t=E&&typeof E=="object"&&"errcode"in E?E.errcode:void 0;(t===5||t===6)&&i("owner_busy"),t===13&&i("capacity_exceeded"),i("unavailable")}function le(E){let t=R(E,["path","storeId","key","mode"],["clock"]);(typeof t.path!="string"||!se(t.path)||t.path.includes("\0"))&&i();let e=C(t.storeId);t.mode!=="create"&&t.mode!=="reopen"&&i();let s=t.clock===void 0?{wallMs:()=>Date.now(),monotonicMs:()=>performance.now()}:R(t.clock,["wallMs","monotonicMs"]);(typeof s.wallMs!="function"||typeof s.monotonicMs!="function")&&i();let n=s,r=t.path,o=P(t.key),a;try{if(t.mode==="create"){let d=te(r,"wx",384);Z(d)}else{let d=ee(r);(!d.isFile()||d.isSymbolicLink()||d.size===0)&&i("unavailable")}a=new ne(r),a.exec("PRAGMA busy_timeout=0; PRAGMA locking_mode=EXCLUSIVE;"),a.exec("BEGIN EXCLUSIVE"),a.exec("COMMIT");let c;if(t.mode==="reopen"){let d=a.prepare("SELECT * FROM event_meta LIMIT 2").all(),u=d[0];(d.length!==1||!u||u.id!==1||u.format!==X||u.store_id!==e)&&i("identity_mismatch"),c=y(u.event_db_id),(u.key_check.byteLength!==32||!$(u.key_check,D(o,e,c)))&&i("identity_mismatch")}else c=J(32).toString("hex");if(a.exec("PRAGMA foreign_keys=ON; PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA temp_store=MEMORY; PRAGMA cache_size=-4096;"),t.mode==="create"&&a.exec("PRAGMA page_size=4096;"),(a.prepare(`PRAGMA max_page_count=${F}`).get()?.max_page_count!==F||a.prepare("PRAGMA page_size").get()?.page_size!==4096)&&i("capacity_exceeded"),t.mode==="create"){a.exec("BEGIN IMMEDIATE");try{a.exec(re),a.prepare("INSERT INTO event_meta VALUES (1,?,?,?,?)").run(X,e,h(c),D(o,e,c)),a.exec("COMMIT")}catch(d){if(a.isTransaction)try{a.exec("ROLLBACK")}catch{}throw d}}let m=new K(a,o,c,n);return m.validateOpen(t.mode==="reopen"),m}catch(c){try{a?.close()}finally{o.fill(0)}return V(c)}}var K=class{#n;#f;#l;#y;#w=!1;#h=!1;#t;#b=new Map;#N=new WeakMap;#S=new Map;#L=new WeakMap;#v;#d;#R;#_;constructor(t,e,s,n){this.#n=t,this.#f=e,this.#l=s,this.#y=n,this.#v=v(n.wallMs()),this.#d=n.monotonicMs(),(!Number.isFinite(this.#d)||this.#d<0)&&i("unavailable"),this.#_=this.#v,this.#R=this.#d}#s(t,e="normal"){this.#w&&i("unavailable"),this.#h&&i("invalid_input"),this.#t&&!(e==="resolution"&&this.#t.kind!=="reopen"||e==="append"&&this.#t.kind==="retry")&&i("reconciliation_required"),this.#h=!0;try{return t()}catch(s){return V(s)}finally{this.#h=!1}}#o(){try{let t=v(this.#y.wallMs()),e=this.#y.monotonicMs();(!Number.isFinite(e)||e<this.#R)&&i("unavailable");let s=v(Math.floor(e-this.#d)),n=v(this.#v+s);return this.#R=e,this.#_=Math.max(this.#_,t,n),this.#_}catch{return this.#t={kind:"reopen"},i("unavailable")}}#e(t){let e=this.#b.get(t);return e||(e=this.#n.prepare(t),e.setReadBigInts(!0),this.#b.set(t,e)),e}#T(){let t=this.#e("PRAGMA page_size").get()?.page_size,e=this.#e("PRAGMA max_page_count").get()?.max_page_count,s=this.#e("PRAGMA page_count").get()?.page_count;return(t!==4096n||e!==BigInt(F)||typeof s!="bigint"||s>e)&&i("capacity_exceeded"),b(s)*4096}#r(t,e){let s=!1;this.#n.exec("BEGIN IMMEDIATE");try{this.#T();let n=t();return this.#m(),this.#T(),s=!0,this.#n.exec("COMMIT"),n}catch(n){let r=!1;if(this.#n.isTransaction)try{this.#n.exec("ROLLBACK")}catch{r=!0}throw r||this.#n.isTransaction?this.#t={kind:"reopen"}:s&&(this.#t=e??{kind:"reopen"}),this.#t&&i("reconciliation_required"),n}}#i(t){let e=this.#e("SELECT * FROM event_stream WHERE scope_key=?").get(h(t));e||i("stream_cursor_unknown");let s=I(L(e.scope_json)),n=M(L(e.limits_json)),r=y(e.life);return(U(s)!==t||y(e.scope_key)!==t||r!==x(this.#l,s,e.installation_id)||e.gen<1n||e.gen>N||e.floor<0n||e.floor>e.head||e.head>N||!["rebuilding","ready"].includes(e.state)||e.state==="rebuilding"&&(e.head!==0n||e.floor!==0n||e.rows!==0n))&&i("stream_gap"),{row:e,scope:s,limits:n,key:t,life:r}}#a(t){let e=this.#N.get(t);return e||i(),this.#i(e)}#E(t){let e=t.row;return q("tansr.sdk2.event-before.v1",{key:t.key,life:t.life,generation:String(e.gen),floor:String(e.floor),head:String(e.head),state:e.state,rows:b(e.rows),storedBytes:b(e.stored_bytes),wireBytes:b(e.wire_bytes)})}#q(t,e){return q("tansr.sdk2.event-fact.v1",{eventDbId:this.#l,scopeKey:t.key,life:t.life,generation:String(e.gen),sequence:String(e.seq),first:String(e.first_seq),last:String(e.last_seq),batchDigest:y(e.batch_digest),createdAtMs:b(e.created_ms),draftDigest:O(e.draft_json)})}#g(t,e){(y(e.scope_key)!==t.key||e.gen!==t.row.gen||e.seq<=t.row.floor||e.seq>t.row.head||e.first_seq<1n||e.first_seq>e.seq||e.last_seq<e.seq||e.last_seq-e.first_seq>=8n||this.#q(t,e)!==y(e.fact_digest)||e.stored_bytes!==BigInt(e.draft_json.byteLength+512))&&i("stream_gap");let s;try{s=B(L(e.draft_json),t.scope),Buffer.from(k(s)).equals(Buffer.from(e.draft_json))||i("stream_gap");let n=this.#p(t,e.seq,s,0,!0);e.wire_bytes!==BigInt(n.sse.byteLength)&&i("stream_gap")}catch{i("stream_gap")}return s}#p(t,e,s,n,r=!1){return z({key:this.#f,scope:t.scope,life:t.life,generation:t.row.gen,sequence:e,draft:s,nowMs:n,maximumTtl:r})}#k(t){let e=t.row.floor+1n,s;for(let n of this.#e("SELECT * FROM event_row WHERE scope_key=? ORDER BY gen,seq").iterate(h(t.key))){let r=n;r.seq!==e++&&i("stream_gap"),this.#g(t,r),s&&r.seq<=s.last_seq&&(r.first_seq!==s.first_seq||r.last_seq!==s.last_seq||y(r.batch_digest)!==y(s.batch_digest))&&i("stream_gap"),s&&r.seq>s.last_seq&&r.first_seq!==r.seq&&i("stream_gap"),s=r}(e!==t.row.head+1n||s&&s.last_seq!==t.row.head)&&i("stream_gap")}#m(){let t=this.#e("SELECT scope_key FROM event_stream LIMIT 257").all();t.length>256&&i("capacity_exceeded");let e={rows:0,wire:0,stored:65536},s=new Map,n=new Map;for(let o of t){let a=this.#i(y(o.scope_key)),c=a.row,g=this.#e("SELECT COUNT(*) AS rows,COALESCE(SUM(wire_bytes),0) AS wire,COALESCE(SUM(length(draft_json)+512),0) AS stored,COALESCE(SUM(CASE WHEN stored_bytes<>length(draft_json)+512 THEN 1 ELSE 0 END),0) AS bad FROM event_row WHERE scope_key=?").get(c.scope_key);(g.bad||g.rows!==c.rows||g.wire!==c.wire_bytes||g.stored!==c.stored_bytes||g.rows!==c.head-c.floor)&&i("stream_gap"),(g.rows>BigInt(a.limits.eventRetentionFrames)||g.wire>BigInt(a.limits.eventRetentionBytes))&&i("capacity_exceeded");let m={rows:b(g.rows),wire:b(g.wire),stored:b(g.stored)+8192},d=_=>{_.rows+=m.rows,_.wire+=m.wire,_.stored+=m.stored},u=a.scope.applicationScopeId,f=JSON.stringify([u,a.scope.endUserId]);s.has(u)||s.set(u,{rows:0,wire:0,stored:0}),n.has(f)||n.set(f,{rows:0,wire:0,stored:0}),d(e),d(s.get(u)),d(n.get(f))}let r=(o,a)=>{(o.rows>8192*a||o.wire>16*H*a||o.stored>24*H*a)&&i("capacity_exceeded")};r(e,2);for(let o of s.values())r(o,2);for(let o of n.values())r(o,1);return this.#e("SELECT COUNT(*) AS rows FROM event_row").get()?.rows!==BigInt(e.rows)&&i("stream_gap"),{rows:e.rows,wireBytes:e.wire,storedBytes:e.stored,streams:t.length,databaseBytes:this.#T()}}validateOpen(t){this.#s(()=>{this.#e("PRAGMA foreign_key_check").get()&&i("stream_gap"),this.#m();let e=this.#e("SELECT scope_key FROM event_stream").all();for(let s of e)this.#k(this.#i(y(s.scope_key)));t&&this.#r(()=>{for(let s of e)this.#c(this.#i(y(s.scope_key)))})})}ensureStream(t){return this.#s(()=>{let e=R(t,["scope","installationId","limits"]),s=I(e.scope),n=C(e.installationId),r=M(e.limits),o=U(s);if(this.#e("SELECT scope_key FROM event_stream WHERE scope_key=?").get(h(o))){let g=this.#i(o);(g.row.installation_id!==n||!Buffer.from(k(r)).equals(Buffer.from(g.row.limits_json)))&&i("identity_mismatch")}else this.#r(()=>{this.#e("INSERT INTO event_stream VALUES (?,?,?,?,1,0,0,?,?,0,0,0)").run(h(o),k(s),n,h(x(this.#l,s,n)),"rebuilding",k(r))});let c=this.#S.get(o);return c||(c=Object.freeze({}),this.#S.set(o,c),this.#N.set(c,o)),c})}#C(t){this.#e("UPDATE event_stream SET rows=(SELECT COUNT(*) FROM event_row WHERE scope_key=?),wire_bytes=(SELECT COALESCE(SUM(wire_bytes),0) FROM event_row WHERE scope_key=?),stored_bytes=(SELECT COALESCE(SUM(stored_bytes),0) FROM event_row WHERE scope_key=?) WHERE scope_key=?").run(h(t),h(t),h(t),h(t))}#O(t,e){e<=t.row.floor||(this.#e("DELETE FROM event_row WHERE scope_key=? AND gen=? AND seq<=?").run(h(t.key),t.row.gen,e),this.#e("UPDATE event_stream SET floor=? WHERE scope_key=?").run(e,h(t.key)),this.#C(t.key))}#I(t,e){let s=e-t.limits.eventRetentionMs;if(s<0)return t.row.floor;let n=this.#e("SELECT MAX(seq) AS seq FROM event_row WHERE scope_key=? AND gen=? AND created_ms<=?").get(h(t.key),t.row.gen,BigInt(s));return typeof n?.seq=="bigint"?n.seq:t.row.floor}#u(t,e){let s=this.#I(t,e);return s>t.row.floor&&this.#r(()=>this.#O(t,s)),this.#i(t.key)}head(t){return this.#s(()=>{let e=this.#u(this.#a(t),this.#o()),s=e.row;return{generation:String(s.gen),floor:String(s.floor),head:String(s.head),state:s.state,cursor:s.state==="ready"?j(this.#f,e.scope,e.life,s.gen,s.head):null}})}#M(t,e){let s=R(e,["generation","after","drafts"]);(!Array.isArray(s.drafts)||Q.isProxy(s.drafts)||s.drafts.length<1||s.drafts.length>8||Reflect.ownKeys(s.drafts).length!==s.drafts.length+1)&&i();let n=[];for(let g=0;g<s.drafts.length;g++){let m=Object.getOwnPropertyDescriptor(s.drafts,String(g));(!m||!("value"in m)||!m.enumerable)&&i(),n.push(B(m.value,t.scope))}let r=T(s.generation),o=T(s.after),a=n.map(k),c=q("tansr.sdk2.event-batch.v1",{scopeKey:t.key,life:t.life,generation:String(r),after:String(o),drafts:a.map(O)});return{generation:r,after:o,drafts:n,bodies:a,digest:c}}#B(t,e){if(e.generation<t.row.gen)return{state:"expired"};(e.generation>t.row.gen||e.after>t.row.head)&&i();let s=this.#e("SELECT * FROM event_row WHERE scope_key=? AND gen=? AND first_seq=? ORDER BY seq").all(h(t.key),e.generation,e.after+1n);if(s.length){let n=s[0],r=e.after+BigInt(e.drafts.length);(y(n.batch_digest)!==e.digest||n.last_seq!==r)&&i("operation_conflict");let o=e.after+1n>t.row.floor?e.after+1n:t.row.floor+1n;for(let a of s)this.#g(t,a),(a.seq!==o++||a.last_seq!==r||y(a.batch_digest)!==e.digest||!Buffer.from(a.draft_json).equals(Buffer.from(e.bodies[Number(a.seq-e.after-1n)])))&&i("stream_gap");return o!==r+1n&&i("stream_gap"),{state:"committed",receipt:{generation:String(e.generation),first:String(e.after+1n),last:String(r),digest:e.digest}}}return e.after+1n<=t.row.floor?{state:"expired"}:t.row.head===e.after?{state:"not-committed"}:i("stream_gap")}resolveAppend(t,e){return this.#s(()=>{let s=this.#a(t),n=this.#M(s,e),r=this.#t;r&&(r.kind==="reopen"||r.key!==s.key||r.life!==s.life||r.input.generation!==n.generation||r.input.after!==n.after||r.input.digest!==n.digest)&&i("reconciliation_required"),this.#n.isTransaction&&i("reconciliation_required"),this.#k(s),this.#m();let o=this.#B(s,n);return r&&((o.state==="expired"||o.state==="not-committed"&&this.#E(s)!==r.before)&&i("reconciliation_required"),this.#t=o.state==="not-committed"?{...r,kind:"retry"}:void 0),o},"resolution")}#U(t,e,s){let n=this.#a(t),r=this.#M(n,e),o=this.#t;o&&(o.kind!=="retry"||o.key!==n.key||o.life!==n.life||o.input.generation!==r.generation||o.input.after!==r.after||o.input.digest!==r.digest)&&i("reconciliation_required");let a=this.#B(n,r);if(a.state==="committed")return this.#t=void 0,a.receipt;if(a.state==="expired"&&i("stream_cursor_expired"),(n.row.state!==(s?"rebuilding":"ready")||s&&r.after!==0n)&&i("unavailable"),s){let f=r.drafts.map(p=>p.eventType);(f.filter(p=>p==="archive.status").length!==1||f.filter(p=>p==="binding.status").length!==1||f.some(p=>!["archive.status","binding.status","material.request"].includes(p))||f.filter(p=>p==="material.request").length>2)&&i();let _=r.drafts.flatMap(p=>p.eventType==="material.request"?[p.payload.materialRequestId]:[]);new Set(_).size!==_.length&&i()}if(r.after+BigInt(r.drafts.length)>N)return this.#r(()=>this.#c(n)),i("capacity_exceeded");let c=this.#o(),g=r.drafts.map((f,_)=>(this.#p(n,r.after+BigInt(_)+1n,f,c),this.#p(n,r.after+BigInt(_)+1n,f,c,!0).sse.byteLength)),m=g.reduce((f,_)=>f+_,0);(r.drafts.length>n.limits.eventRetentionFrames||m>n.limits.eventRetentionBytes)&&i("capacity_exceeded");let d={generation:String(r.generation),first:String(r.after+1n),last:String(r.after+BigInt(r.drafts.length)),digest:r.digest},u=this.#r(()=>{let f=this.#i(n.key);(f.row.gen!==r.generation||f.row.head!==r.after||this.#E(f)!==this.#E(n))&&i("operation_conflict");let _=this.#I(f,c),p=b(f.row.wire_bytes),S=f.row.head+BigInt(r.drafts.length)-BigInt(f.limits.eventRetentionFrames);S>_&&(_=S);for(let A of this.#e("SELECT seq,wire_bytes FROM event_row WHERE scope_key=? AND gen=? ORDER BY seq").iterate(h(n.key),f.row.gen)){let w=A;if(w.seq<=_||p+m>f.limits.eventRetentionBytes)p-=b(w.wire_bytes),w.seq>_&&(_=w.seq);else break}this.#O(f,_);for(let[A,w]of r.bodies.entries()){let l={scope_key:h(n.key),gen:r.generation,seq:r.after+BigInt(A)+1n,first_seq:r.after+1n,last_seq:BigInt(d.last),batch_digest:h(r.digest),created_ms:BigInt(c),draft_json:w,fact_digest:new Uint8Array(32),wire_bytes:BigInt(g[A]),stored_bytes:BigInt(w.byteLength+512)};l.fact_digest=h(this.#q(n,l)),this.#e("INSERT INTO event_row VALUES (?,?,?,?,?,?,?,?,?,?,?)").run(l.scope_key,l.gen,l.seq,l.first_seq,l.last_seq,l.batch_digest,l.created_ms,l.draft_json,l.fact_digest,l.wire_bytes,l.stored_bytes)}return this.#e("UPDATE event_stream SET head=?,state=? WHERE scope_key=?").run(BigInt(d.last),"ready",h(n.key)),this.#C(n.key),d},s?void 0:{kind:"append",key:n.key,life:n.life,input:r,before:this.#E(n)});return this.#t=void 0,u}activate(t,e){return this.#s(()=>this.#U(t,e,!0))}append(t,e){return this.#s(()=>this.#U(t,e,!1),"append")}#c(t){t.row.gen===N&&i("capacity_exceeded"),this.#e("DELETE FROM event_row WHERE scope_key=?").run(h(t.key)),this.#e("UPDATE event_stream SET gen=?,floor=0,head=0,state='rebuilding',rows=0,stored_bytes=0,wire_bytes=0 WHERE scope_key=?").run(t.row.gen+1n,h(t.key))}retire(t,e){this.#s(()=>{["uncertain-business","notification-failure","expired-material","closed"].includes(e)||i();let s=this.#a(t);this.#r(()=>this.#c(s))})}#A(t,e,s){e<t.row.gen&&i("stream_cursor_expired"),e>t.row.gen&&i("stream_cursor_unknown"),s<t.row.floor&&i("stream_cursor_expired"),s>t.row.head&&i("stream_cursor_unknown"),t.row.state!=="ready"&&i("unavailable")}inspectCursor(t,e){return this.#s(()=>{let s=this.#a(t),n=Y(this.#f,s.scope,e);return(n.life!==s.life||n.generation<s.row.gen)&&i("stream_cursor_expired"),s=this.#u(s,this.#o()),this.#A(s,n.generation,n.sequence),this.#k(s),this.#x(s,n.sequence,s.row.head,this.#o()),{generation:String(n.generation),after:String(n.sequence),through:String(s.row.head)}})}#x(t,e,s,n){for(let r of this.#e("SELECT * FROM event_row WHERE scope_key=? AND gen=? AND seq>? AND seq<=? ORDER BY seq").iterate(h(t.key),t.row.gen,e,s)){let o=r,a=this.#g(t,o);a.eventType==="material.request"&&n>=a.deadlineMs&&(this.#r(()=>this.#c(t)),i("stream_cursor_expired"))}}readPage(t,e){return this.#s(()=>{let s=R(e,["generation","after","through","maxFrames","maxBytes"]),n=T(s.generation),r=T(s.after),o=T(s.through),a=v(s.maxFrames,1,64),c=v(s.maxBytes,1,H),g=this.#a(t);n<g.row.gen&&i("stream_cursor_expired"),n>g.row.gen&&i("stream_cursor_unknown");let m=this.#o(),d=this.#u(g,m);(r>o||o>d.row.head)&&i(),this.#A(d,n,r);let u=this.#e("SELECT * FROM event_row WHERE scope_key=? AND gen=? AND seq>? AND seq<=? ORDER BY seq LIMIT ?").iterate(h(d.key),n,r,o,BigInt(a)),f=r,_=0,p=0,S=[];for(let w of u){let l=w;p++,l.seq!==f+1n&&i("stream_gap");let G=this.#g(d,l);if(G.eventType==="material.request"&&m>=G.deadlineMs&&(this.#r(()=>this.#c(d)),i("stream_cursor_expired")),_+b(l.wire_bytes)>c){S.length||i("capacity_exceeded");break}_+=b(l.wire_bytes),S.push({seq:l.seq,fact_digest:l.fact_digest}),f=l.seq}return r<o&&!S.length&&i("stream_gap"),p<a&&f<o&&S.length===p&&i("stream_gap"),{refs:S.map(w=>{let l=Object.freeze({});return this.#L.set(l,{key:d.key,life:d.life,generation:n,sequence:w.seq,digest:y(w.fact_digest)}),l}),after:String(f),complete:f===o}})}encodeForSend(t){return this.#s(()=>{let e=this.#L.get(t);e||i();let s=this.#o(),n=this.#u(this.#i(e.key),s);(e.life!==n.life||e.generation!==n.row.gen||e.sequence<=n.row.floor)&&i("stream_cursor_expired"),this.#A(n,e.generation,e.sequence);let r=this.#e("SELECT * FROM event_row WHERE scope_key=? AND gen=? AND seq=?").get(h(e.key),e.generation,e.sequence);(!r||y(r.fact_digest)!==e.digest)&&i("stream_gap");let o=this.#g(n,r);return o.eventType==="material.request"&&s>=o.deadlineMs&&(this.#r(()=>this.#c(n)),i("stream_cursor_expired")),this.#p(n,e.sequence,o,s)})}usage(){return this.#s(()=>this.#m())}close(){this.#h&&i(),!this.#w&&(this.#n.close(),this.#w=!0,this.#f.fill(0),this.#b.clear(),this.#S.clear())}};export{le as openSqliteEventStore};
26
+ //# sourceMappingURL=tansr-sqlite-event-store-UQLSSZKP.mjs.map
@@ -0,0 +1,29 @@
1
+ import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
2
+ import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
3
+ const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
4
+ import{A as dt,B as xe,C as ct,Da as Et,E as lt,L as ht,T as mt,V as ft,a as ie,b as Qe,c as Re,d as H,e as U,f as Y,g as ee,j as Ze,l as Ke,m as et,n as Se,o as tt,p as Me,s as nt,t as it,u as rt,ua as bt,va as vt,w as ot,x as st,xa as _t,ya as It,z as at}from"./tansr-chunk-BX7CF5RQ.mjs";import{d as yt,e as Pe,f as gt,g as pt,h as Ue,i as ut}from"./tansr-chunk-SJFDQLLC.mjs";import{Aa as Ve,ka as Xe,pa as $e,qa as Je,za as ze}from"./tansr-chunk-ZQ3ZK7IL.mjs";import{D as Fe,K as Ce,L as ce,M as le,N as f,O as D,P as w,R as Le,S as Ge,T as Z,U as Ne,V as Ee,W as X,Y as De,Z as ye,_ as Ye,aa as je,c as Q,l as F,m as We,t as Ie}from"./tansr-chunk-I3TOVAA6.mjs";import"./tansr-chunk-F7C6ITED.mjs";import"./tansr-chunk-QWGSXFEJ.mjs";import"./tansr-chunk-RRAMVVYF.mjs";function L(u){throw new F(u)}var G=(u,e)=>f(u)===f(e),Ae=u=>Q(Buffer.from(u.metadata)),Tt=D("");function ke(u){(typeof u!="string"||!u||u.includes("\0")||Buffer.byteLength(u)>256)&&L("invalid_input")}function ge(u){(typeof u!="number"||!Number.isSafeInteger(u)||u<0)&&L("inventory_unknown")}function Rt(u){let e=w(u,["slot","authority","captureBindingId","recordBindingId","ownerEpoch","runKey","recordDigest"]),n=w(e.slot,["storageBindingId","slotId"]);X(n);for(let o of["captureBindingId","recordBindingId","ownerEpoch","runKey"])ke(e[o]);return(typeof e.recordDigest!="string"||!/^[a-f0-9]{64}$/u.test(e.recordDigest))&&L("invalid_input"),{slot:{...n},authority:Z(e.authority),captureBindingId:e.captureBindingId,recordBindingId:e.recordBindingId,ownerEpoch:e.ownerEpoch,runKey:e.runKey,recordDigest:e.recordDigest}}function St(u,e){let{slot:n,authority:o,captureBindingId:r,recordBindingId:s,ownerEpoch:d,runKey:i}=u,{state:g,events:c}=e,a=g.registration;(!G(o.scope,a.scope)||!G(o.target,g.target)||g.storageBindingId!==n.storageBindingId||g.slotId!==n.slotId||s!==a.bindingId||r===s||r===n.storageBindingId||!a.relatedBindingIds.includes(r)||!a.relatedBindingIds.includes(s))&&L("identity_mismatch");for(let B of[n.storageBindingId,r,s]){let P=e.identity(B);(P.applicationScopeId!==a.scope.applicationScopeId||P.endUserId!==a.scope.endUserId)&&L("identity_mismatch")}g.fence!==null&&L("reconciliation_required");let p=(B,P,j)=>{let q=e.receipt(B,P);return(q.bindingId!==B||q.operationKey!==P||q.entries.length!==1||j!==void 0&&q.intentDigest!==j)&&L("inventory_unknown"),{receipt:q,entry:q.entries[0]}},y=(B,P,j="original")=>{(B.entryId!==P||B.basket!==j||B.bodyBytes!==0||B.bodySha256!==Tt)&&L("inventory_unknown")},R=`recording:${D(i)}`,k=p(s,R);y(k.entry,`recording-${D(R)}`);let S=Ae(k.entry);w(S,["format","captureBindingId","recordBindingId","runKey","turnId","target","expectedHead","projectionPolicyId","sourceId","sourceGeneration","maxTurnBytes","ownerEpoch"],["attachmentPolicy","attachmentSourceId","textProjectionPolicy"]),S.textProjectionPolicy!==void 0&&S.textProjectionPolicy!==Xe&&L("inventory_unknown"),it(S.attachmentPolicy,S.attachmentSourceId);let _=Z({...o,target:S.target}).target;(S.format!=="sdk2-recording-lease-v1"||S.captureBindingId!==r||S.recordBindingId!==s||S.runKey!==i||S.ownerEpoch!==d||S.sourceId!==a.sourceId||S.sourceGeneration!==a.sourceGeneration||_.sessionId!==a.sessionId||!G(_.generations,g.target.generations)||k.receipt.intentDigest!==D(k.entry.metadata))&&L("identity_mismatch"),ke(S.turnId),ke(S.projectionPolicyId),ge(S.maxTurnBytes);let m=S.turnId,l=S.projectionPolicyId,b=D(k.entry.metadata),h=`${i}:prepared-turn`,I=p(r,h,D(f(["sdk2-recording-prepared-v1",b]))),v=Ae(I.entry);w(v,["format","leaseDigest","operationKey","runKey","turnId","outcome","turnState","bodySha256","messageCount","toolCallCount","pendingToolCalls"],["trustedAttachments"]);let O=`${i}:turn`;(I.entry.entryId!==`recording-${D(f([r,h]))}`||I.entry.basket!=="original"||I.entry.bodyBytes>S.maxTurnBytes||v.format!=="sdk2-recording-prepared-v1"||v.leaseDigest!==b||v.operationKey!==O||v.runKey!==i||v.turnId!==m||v.bodySha256!==I.entry.bodySha256)&&L("inventory_unknown");for(let B of["messageCount","toolCallCount","pendingToolCalls"])ge(v[B]);["completed","aborted","failed","interrupted"].includes(v.outcome)||L("inventory_unknown");let A=e.records.find(B=>B.recordDigest===u.recordDigest)??L("reconciliation_required");rt(S.attachmentPolicy,v.trustedAttachments,A,S.maxTurnBytes);let C=D(f([s,O])),N=at({receipt:e.receipt(s,O),record:A,bindingId:s,operationKey:O,sourceId:a.sourceId,sourceGeneration:a.sourceGeneration,expectedHead:S.expectedHead});(A.recordId!==`jr-r-${C}`||A.payload.artifactId!==`jr-p-${C}`||A.recordKind!=="turn"||A.turnId!==m||A.turnState!==v.turnState||!G(A.target,_)||S.attachmentPolicy===void 0&&A.attachments.length!==0||A.payload.sha256!==I.entry.bodySha256||A.payload.bytes!==I.entry.bodyBytes||N.payload.entryId!==A.payload.artifactId||N.payload.bodySha256!==I.entry.bodySha256||N.payload.bodyBytes!==I.entry.bodyBytes||BigInt(A.sequence)>e.acknowledgedThrough)&&L("reconciliation_required");let K=S.expectedHead;(A.sequence!==(K===null?"1":String(BigInt(K.sequence)+1n))||A.predecessorDigest!==(K?.recordDigest??"0".repeat(64)))&&L("inventory_unknown");let M=[];for(let B of e.materials(r)){let P=Ae(B.witness);if(P.runKey!==i)continue;(P.format!=="sdk2-session-capture-v1"||P.projectionPolicyId!==l||P.bodySha256!==B.witness.bodySha256)&&L("inventory_unknown");let j=p(r,B.operationKey,D(B.witness.metadata));G(j.entry,B.witness)||L("inventory_unknown"),M.push(B.witness)}M.sort((B,P)=>f(B)<f(P)?-1:f(B)>f(P)?1:0);let ae=`${i}:materials-seal`,pe=p(r,ae,D(f(["sdk2-recording-materials-seal-v1",b])));y(pe.entry,`recording-${D(f([r,ae]))}`),pe.entry.metadata!==f({format:"sdk2-recording-materials-seal-v1",leaseDigest:b,preparedCommitDigest:I.receipt.commitDigest,operationKey:O,outcome:v.outcome,recordDigest:A.recordDigest,materialsComplete:!0,materialsDigest:D(f(M))})&&L("reconciliation_required");let z=p(r,i,D(JSON.stringify(["sdk2-run-capture-v1",r,l,i])));y(z.entry,`terminal-${D(JSON.stringify([r,i]))}`,"terminal"),z.entry.metadata!==JSON.stringify({format:"sdk2-run-terminal-v1",projectionPolicyId:l,outcome:v.outcome})&&L("inventory_unknown");let be=e.receipt(r,`${i}:fence`);(be.intentDigest!==D(JSON.stringify(["sdk2-run-fence-v1",r,l,i]))||be.entries.length!==0)&&L("reconciliation_required");let ne=`run-${D(i)}`,de=B=>{let P=`host-run-${B}-${D(f([n,d,i]))}`,{entry:j}=p(n.storageBindingId,P,D(P));y(j,P);let q=Ae(j);return w(q,["format","slot","ownerEpoch","turnId","captureRunKey","controlRunId","kind","value"]),(q.format!=="sdk2-host-run-v1"||!G(q.slot,n)||q.ownerEpoch!==d||q.turnId!==m||q.captureRunKey!==i||q.controlRunId!==ne||q.kind!==B)&&L("identity_mismatch"),q.value},ue=w(de("intent"),["initial","store"]),E=w(ue.initial,["target","localHistoryGeneration","confirmedCommitId"]);(ue.store!=="host-owned-original-store"||!G(E.target,_))&&L("inventory_unknown"),ge(E.localHistoryGeneration);let T=w(de("history"),["commitId","target","localHistoryGeneration"]);ke(T.commitId),ge(T.localHistoryGeneration);let W=Z({...o,target:T.target}).target;(W.sessionId!==_.sessionId||!G(W.generations,_.generations))&&L("identity_mismatch");let V=de("facts");typeof V!="string"&&L("inventory_unknown");let he=w(Q(Buffer.from(V)),["commit","query","capture"]),we=w(he.query,["status","failureCount","omittedFailures"]);(!G(he.commit,T)||he.capture!=="confirmed"||!["completed","failed"].includes(we.status))&&L("reconciliation_required"),ge(we.failureCount),ge(we.omittedFailures);let Oe=c.findIndex(({event:B})=>B.mutation.kind==="admit-run"&&B.mutation.ownerEpoch===d&&B.mutation.runKey===ne),Te=c.findIndex(({event:B})=>B.mutation.kind==="finish-run"&&B.mutation.ownerEpoch===d&&B.mutation.runKey===ne);(Oe<0||Te<=Oe)&&L("reconciliation_required");let me=c[Oe].event.result.control.fence,ve=c[Te].event,_e=c[Te-1].event.result.control.fence;return(me?.kind!=="run"||me.id!==ne||me.ownerEpoch!==d||me.turnId!==m||!G(me.target,_)||_e?.kind!=="run"||_e.id!==ne||_e.ownerEpoch!==d||_e.turnId!==m||ve.mutation.kind!=="finish-run"||!G(ve.mutation.expectedTarget,W)||ve.result.control.fence!==null||!G(ve.result.control.target,W))&&L("reconciliation_required"),{state:"settled",runKey:i,turnId:m,outcome:v.outcome,record:A,entry:I.entry}}import{createHash as Ct}from"node:crypto";import{types as Be}from"node:util";var oe=64,fe=262144,He=33554432,At=262144,Lt=32,kt=262144,Nt=8,Bt=131072,Dt=`
5
+ CREATE TABLE spool_meta (key TEXT PRIMARY KEY COLLATE BINARY, value TEXT NOT NULL) STRICT;
6
+ CREATE TABLE capture_ops (
7
+ binding_id TEXT NOT NULL COLLATE BINARY, operation_key TEXT NOT NULL COLLATE BINARY,
8
+ intent_digest TEXT NOT NULL, original_bytes INTEGER NOT NULL, original_records INTEGER NOT NULL,
9
+ terminal_bytes INTEGER NOT NULL, terminal_records INTEGER NOT NULL,
10
+ state TEXT NOT NULL CHECK(state IN ('reserved','committed')), commit_digest TEXT, entry_ids TEXT,
11
+ PRIMARY KEY(binding_id, operation_key)
12
+ ) STRICT;
13
+ CREATE TABLE entries (
14
+ binding_id TEXT NOT NULL COLLATE BINARY, entry_id TEXT NOT NULL COLLATE BINARY,
15
+ operation_key TEXT NOT NULL COLLATE BINARY, basket TEXT NOT NULL CHECK(basket IN ('original','terminal')),
16
+ metadata TEXT NOT NULL, metadata_bytes INTEGER NOT NULL, body_sha TEXT NOT NULL,
17
+ body_bytes INTEGER NOT NULL, body BLOB,
18
+ PRIMARY KEY(binding_id,entry_id),
19
+ FOREIGN KEY(binding_id,operation_key) REFERENCES capture_ops(binding_id,operation_key),
20
+ CHECK(body IS NULL OR length(body)=body_bytes)
21
+ ) STRICT;
22
+ CREATE TABLE holds (
23
+ binding_id TEXT NOT NULL COLLATE BINARY, token TEXT NOT NULL COLLATE BINARY,
24
+ entry_id TEXT NOT NULL COLLATE BINARY, state TEXT NOT NULL CHECK(state IN ('held','released')),
25
+ PRIMARY KEY(binding_id,token),
26
+ FOREIGN KEY(binding_id,entry_id) REFERENCES entries(binding_id,entry_id)
27
+ ) STRICT;
28
+ `,te="binding_id,entry_id,basket,metadata,metadata_bytes,body_sha,body_bytes,(body IS NOT NULL) AS retained,length(body) AS stored_bytes";function t(u){throw new F(u)}function J(u){(typeof u!="string"||!/^[a-f0-9]{64}$/.test(u))&&t("invalid_input")}function se(u){return Ct("sha256").update(u).digest("hex")}function Kt(u,e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.setPrototypeOf(e,null),e}function wt(u){return JSON.stringify(u.bindings.map(({bindingId:e,applicationScopeId:n,endUserId:o})=>[e,n,o]).sort((e,n)=>e[0]<n[0]?-1:e[0]===n[0]?0:1))}function x(u){return{bindingId:u.binding_id,operationKey:u.operation_key,intentDigest:u.intent_digest,originalMax:{bytes:u.original_bytes,records:u.original_records},terminalReserve:{bytes:u.terminal_bytes,records:u.terminal_records}}}function $(u){let e=ee(u.metadata);return Y(u.metadata_bytes),Y(u.body_bytes),J(u.body_sha),(e!==u.metadata_bytes||e>fe||u.body_bytes>He||u.retained!==0&&u.retained!==1||u.retained===1&&u.stored_bytes!==u.body_bytes||u.basket!=="original"&&u.basket!=="terminal")&&t("inventory_unknown"),{entryId:u.entry_id,basket:u.basket,metadata:u.metadata,metadataBytes:e,bodyBytes:u.body_bytes,bodySha256:u.body_sha,logicalBytes:e+u.body_bytes+oe}}function re(u){return se(JSON.stringify(u.map(e=>[e.entryId,e.basket,e.metadata,e.bodyBytes,e.bodySha256])))}function Ot(u){return{bindingId:u.binding_id,entryId:u.entry_id,token:u.token,state:u.state}}async function yn(u,e){let n=await import("node:fs"),{resolve:o}=await import("node:path"),{DatabaseSync:r}=await import("node:sqlite");e?.assertCurrent();let s=o(u.path);if(u.mode==="create"){let i=n.openSync(s,"wx",384);n.closeSync(i)}else{let i;try{i=n.lstatSync(s)}catch{t("inventory_unknown")}(!i.isFile()||i.isSymbolicLink()||i.size===0)&&t("inventory_unknown")}let d=new r(s);try{if(u.mode==="recover"){let c;try{c=Object.fromEntries(d.prepare("SELECT key,value FROM spool_meta").all().map(a=>[a.key,a.value]))}catch{t("format_mismatch")}c.format!==(u.format??Re)&&t("format_mismatch"),(c.storeId!==u.storeId||c.bindings!==wt(u))&&t("identity_mismatch"),c.hostBudget!==e?.marker&&t("identity_mismatch")}if(e?.assertCurrent(),d.exec("PRAGMA foreign_keys=ON; PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA temp_store=MEMORY; PRAGMA busy_timeout=0;"),d.prepare(`PRAGMA max_page_count=${u.maxDatabasePages}`).get().max_page_count!==u.maxDatabasePages&&t("capacity_exceeded"),u.mode==="create"){d.exec("BEGIN IMMEDIATE");try{d.exec(Dt);let c=d.prepare("INSERT INTO spool_meta(key,value) VALUES (?,?)");c.run("format",u.format??Re),c.run("storeId",u.storeId),c.run("bindings",wt(u)),e&&c.run("hostBudget",e.marker),d.exec("COMMIT")}catch(c){try{d.exec("ROLLBACK")}catch{}throw c}}let g=new qe(d,u);return g.validateRecovery(),e?.assertCurrent(),Fe(g,s,u.storeId,(c,a)=>g.assertRecoveryReady(c,a),u.format??Re,(c,a)=>g.assertRecoveryReady(c,a,!0)),u.format===H&&vt(g,c=>g.readInstallationPlan(c)),u.format===H&&_t(g,(c,a)=>g.commitInstallationReady(c,a)),u.format===H&&mt(g,c=>g.readInstallationRetirement(c)),u.format===H&&ct(g,(c,a,p,y)=>g.readInstallationRecoverySnapshot(c,a,p,y)),u.format===H&&lt(g,(c,a)=>g.readInstallationRecoveryBootstrap(c,a)),We(g,{assertReadable:g.assertObservationReadable.bind(g),releaseReady:g.observationReleaseReady.bind(g),committed:g.readObservationCommitted.bind(g),operationFacts:g.readObservationOperationFacts.bind(g)}),g}catch(i){if(!e)throw d.close(),i;try{d.close()}catch(g){throw e.retainUnclosed(()=>d.close()),new AggregateError([i,g],"Archive spool open failed with an unclosed database")}throw i}}var qe=class{#S=!1;#d=!1;#p=!1;#r=null;#y=[];#n;#t;#f=new Map;#c=new Map;#I=0;#u=new Map;#E=0;constructor(e,n){this.#n=e,this.#t=n,ht(this,o=>this.#x(o))}#e(e){let n=this.#f.get(e);if(n)return n;let o=this.#n.prepare(e);return this.#f.size===32&&this.#f.delete(this.#f.keys().next().value),this.#f.set(e,o),o}#N(e,n){if(n.retainedBytes>kt)return;let o=this.#c.get(e);if(o){this.#c.delete(e),this.#c.set(e,o);return}for(;this.#c.size>=Lt||this.#I+n.retainedBytes>kt;){let r=this.#c.keys().next().value;this.#I-=this.#c.get(r).retainedBytes,this.#c.delete(r)}this.#c.set(e,n),this.#I+=n.retainedBytes}#o(e=!1){this.#S&&t("closed"),this.#d&&t("reentrant"),this.#p&&t("reconciliation_required"),e&&(this.#r!==null||this.#y.length>0)&&t("reconciliation_required")}#a(e){U(e.bindingId),U(e.operationKey),this.#t.bindings.some(n=>n.bindingId===e.bindingId)||t("identity_mismatch")}#i(e){return this.#e("SELECT * FROM capture_ops WHERE binding_id=? AND operation_key=?").get(e.bindingId,e.operationKey)}#h(e,n){return U(e),U(n),this.#e(`SELECT ${te} FROM entries WHERE binding_id=? AND entry_id=?`).get(e,n)??t("entry_not_found")}#s(e,n){(e.state!=="committed"||e.commit_digest===null||e.entry_ids===null)&&t("inventory_unknown");let o=JSON.parse(e.entry_ids);(!Array.isArray(o)||o.some(s=>typeof s!="string")||new Set(o).size!==o.length)&&t("inventory_unknown");let r=o.map(s=>$(n?n(e.binding_id,s):this.#h(e.binding_id,s)));return re(r)!==e.commit_digest&&t("inventory_unknown"),{state:"committed",bindingId:e.binding_id,operationKey:e.operation_key,intentDigest:e.intent_digest,commitDigest:e.commit_digest,entries:r}}#b(){let e=this.#e("SELECT * FROM capture_ops").all(),n=this.#e(`SELECT ${te} FROM entries`).all(),o=n.map(d=>{let i=$(d);return{bindingId:d.binding_id,entryId:d.entry_id,basket:d.basket,records:1,bytes:i.metadataBytes+oe+(d.retained===1?i.bodyBytes:0)}}),r=e.filter(d=>d.state==="reserved").map(d=>({...x(d),state:"reserved"})),s=this.#e("SELECT count(*) AS total FROM holds").get();return(e.length+s.total>this.#t.maxOperations||n.length+r.reduce((d,i)=>d+i.originalMax.records+i.terminalReserve.records,0)>this.#t.maxEntries)&&t("capacity_exceeded"),Qe({...this.#t,inventory:{status:"known",kind:"restored",reservations:r,entries:o}})}#l(e,n){this.#o(!0),this.#d=!0;let o=!1;try{this.#n.exec("BEGIN IMMEDIATE"),this.#t.format===H&&this.#e("SELECT value FROM spool_meta WHERE key=?").get("format")?.value!==H&&t("format_mismatch");let r=n(this.#b());return this.#b(),o=!0,this.#n.exec("COMMIT"),Ie(this,"committed",e,()=>e===null?"none":this.#i(e)?.state??"none"),r}catch(r){try{this.#n.exec("ROLLBACK")}catch{try{this.#n.exec("BEGIN"),this.#n.exec("ROLLBACK")}catch{this.#p=!0}}if(o&&(this.#r=e?{bindingId:e.bindingId,operationKey:e.operationKey}:{bindingId:"",operationKey:""},Ie(this,"uncertain-business"),t("commit_unknown")),r instanceof F||r instanceof ie)throw r;t("storage_failure")}finally{this.#d=!1}}validateRecovery(){this.#o(),this.#b();let e=this.#e("PRAGMA quick_check").all();(e.length!==1||e[0].quick_check!=="ok"||this.#e("PRAGMA foreign_key_check").all().length>0)&&t("inventory_unknown");let n=this.#e("SELECT body,body_sha FROM entries WHERE body IS NOT NULL").iterate();for(let o of n)se(o.body)!==o.body_sha&&t("inventory_unknown");for(let o of this.#e("SELECT * FROM capture_ops WHERE state='committed'").all())this.#s(o)}assertRecoveryReady(e,n,o=!1){this.#o(!0);let r=Z(n);this.#d=!0;try{this.#n.exec("BEGIN");let s=this.#R({storageBindingId:e.storageBindingId,slotId:e.slotId}),d=s.at(-1)?.event.result.control;if((!d||f(d)!==f(e))&&t("reconciliation_required"),o){let i=d.registration.scope;(i.applicationScopeId!==r.scope.applicationScopeId||i.endUserId!==r.scope.endUserId||d.registration.sessionId!==r.target.sessionId)&&t("identity_mismatch"),this.#C(d,s,r.nowMs)}else f(d.registration.scope)!==f(r.scope)&&t("reconciliation_required"),this.#B(d,{target:r.target,nowMs:r.nowMs,operationEpochIds:[...new Set(s.map(i=>i.event.result.control.epoch.id))]});this.#n.exec("ROLLBACK")}catch(s){try{this.#n.exec("ROLLBACK")}catch{try{this.#n.exec("BEGIN"),this.#n.exec("ROLLBACK")}catch{this.#p=!0}}if(s instanceof F||s instanceof ie)throw s;t("storage_failure")}finally{this.#d=!1}}#g(e){if(this.#d)return this.#R(e);this.#d=!0;try{this.#n.exec("BEGIN");let n=this.#R(e);return this.#n.exec("ROLLBACK"),n}catch(n){try{this.#n.exec("ROLLBACK")}catch{try{this.#n.exec("BEGIN"),this.#n.exec("ROLLBACK")}catch{this.#p=!0}}if(n instanceof F||n instanceof ie)throw n;t("storage_failure")}finally{this.#d=!1}}#R(e){let n="bc-state-"+X(e)+"-",o=this.#e("SELECT entry_id,metadata,operation_key FROM entries WHERE binding_id=? AND entry_id LIKE ?").all(e.storageBindingId,n+"%");(o.length>ce||o.reduce((l,b)=>l+ee(b.metadata),0)>le)&&t("capacity_exceeded");let r=new Map,s=[...new Set(o.map(l=>l.operation_key))];for(let l=0;l<s.length;l+=400){let b=s.slice(l,l+400),h=this.#e("SELECT * FROM capture_ops WHERE binding_id=? AND operation_key IN ("+b.map(()=>"?").join(",")+")").all(e.storageBindingId,...b);for(let I of h)r.set(I.operation_key,I)}let d=new Set;for(let l of r.values()){(l.state!=="committed"||l.commit_digest===null||l.entry_ids===null)&&t("inventory_unknown");let b=JSON.parse(l.entry_ids);(!Array.isArray(b)||b.some(h=>typeof h!="string")||new Set(b).size!==b.length)&&t("inventory_unknown");for(let h of b)U(h),d.add(h)}let i=new Map,g=[...d];for(let l=0;l<g.length;l+=400){let b=g.slice(l,l+400),h=this.#e("SELECT "+te+" FROM entries WHERE binding_id=? AND entry_id IN ("+b.map(()=>"?").join(",")+")").all(e.storageBindingId,...b);for(let I of h)i.set(I.entry_id,I)}let c=new Map,a=(l,b)=>(U(l),U(b),l!==e.storageBindingId&&t("identity_mismatch"),i.get(b)??t("entry_not_found")),p=l=>{let b=c.get(l.operation_key);if(b)return b;let h=this.#s(l,a);return c.set(l.operation_key,h),h},y=[],R=o.map(l=>{let b=this.#c.get(l.metadata),h=b?JSON.parse(l.metadata,Kt):Q(Buffer.from(l.metadata));if(!b){if(w(h,["format","operationKey","semanticDigest","previousDigest","mutation","result"],["companion","installationPlan","retirement"]),h.retirement!==void 0&&(h.format!=="sdk2-binding-event-v2"||h.mutation.kind!=="close-drained")&&t("inventory_unknown"),h.installationPlan!==void 0){(h.format!=="sdk2-binding-event-v2"||h.mutation.kind!=="binding-create")&&t("inventory_unknown");let M=Pe(h.installationPlan);(f(M.slot)!==f(e)||M.createSemanticDigest!==h.semanticDigest||f(M.createRequest)!==f(h.mutation.body.request)||M.createResponse.revision!==h.result.control.revision||M.bindingId!==h.result.control.registration.bindingId)&&t("inventory_unknown");let ae=yt({control:h.result,body:h.mutation.body,policy:{limits:M.createResponse.limits,rejectedCapabilities:M.createResponse.rejectedCapabilities,captureBindingId:M.captureBindingId,recordBindingId:M.recordBindingId,materialBindingId:M.materialBindingId},physicalPairDigest:M.physicalPairDigest,ownerRootDigest:M.ownerRootDigest,confirmedHistory:M.confirmedHistory});f(ae)!==f(M)&&t("inventory_unknown")}h.companion!==void 0&&h.mutation.kind!=="archive-ack"&&t("inventory_unknown"),w(h.result,["control","receipt"]);let A=Ee(h.result.control),C=Ne(h.mutation),N=De(e,A.registration,C);(N.key!==h.operationKey||N.semantic!==h.semanticDigest)&&t("inventory_unknown");let K=h.result.receipt;"body"in C?(!K||K.operation!==C.kind||K.bindingId!==A.registration.bindingId||K.revision!==A.revision||f(K.request)!==f(C.body.request)||K.semanticDigest!==N.semantic||K.state!=="completed"||K.protocol!=="sdk2-ext-v1")&&t("inventory_unknown"):K!==null&&t("inventory_unknown")}h.format!==(this.#t.format===H?"sdk2-binding-event-v2":"sdk2-binding-event-v1")&&t("inventory_unknown");let I=h.result.control;(I.storageBindingId!==e.storageBindingId||I.slotId!==e.slotId||l.entry_id!==n+I.revision)&&t("inventory_unknown"),h.companion!==void 0&&this.#T(h.companion);let v=r.get(l.operation_key);(!v||v.state!=="committed"||!p(v).entries.some(A=>A.entryId===l.entry_id))&&t("inventory_unknown");let O=b??(()=>{let A=D(l.metadata),C=f(I.registration);return{digest:A,registrationCanonical:C,retainedBytes:2*(l.metadata.length+A.length+C.length)}})();return y.push({metadata:l.metadata,validated:O}),{event:h,digest:O.digest,registrationCanonical:O.registrationCanonical,metadataBytes:ee(l.metadata),storageOperationKey:l.operation_key,installationReady:null}}).sort((l,b)=>BigInt(l.event.result.control.revision)<BigInt(b.event.result.control.revision)?-1:1),k;for(let l of R){let b=l.event.result.control;(l.event.previousDigest!==(k?.digest??null)||BigInt(b.revision)!==(k?BigInt(k.event.result.control.revision)+1n:0n))&&t("inventory_unknown"),k&&l.registrationCanonical!==k.registrationCanonical&&t("inventory_unknown"),k=l}let S=R.filter(l=>l.event.installationPlan!==void 0);S.length>1&&t("inventory_unknown");let _=S[0],m=R.filter(l=>l.event.retirement!==void 0);if((m.length>1||m.length>0&&!_)&&t("inventory_unknown"),_){let l=_.event.installationPlan,b=m[0];R.some(v=>v.event.result.control.state==="closed")!==!!b&&t("inventory_unknown");let h=b?ut(b.event.retirement,l):null,I=this.#w(l,_.digest,h?.installedRecordDigest===null);if(b&&h){let v=b.event.result.control,O=R.find(C=>C.event.mutation.kind==="binding-close"&&f(C.event.mutation.body.request)===f(v.closeIntent));(!O||BigInt(O.event.result.control.revision)>=BigInt(v.revision))&&t("inventory_unknown");let A=Ue({plan:l,installedRecord:I,control:v,confirmedHistory:h.confirmedHistory,closingEventDigest:O.digest});f(A)!==f(h)&&t("inventory_unknown")}_.installationReady=I,I&&(R.length+1>ce||R.reduce((v,O)=>v+O.metadataBytes,0)+ee(f(I))>le)&&t("capacity_exceeded")}for(let l of y)this.#N(l.metadata,l.validated);return R}#w(e,n,o=!1){let r=this.#i(e.installReadyReserve);if((!r||f(x(r))!==f(e.installReadyReserve))&&t("inventory_unknown"),r.state==="reserved")return o&&t("inventory_unknown"),null;let s=this.#s(r),d=s.entries[0];if(o)return s.entries.length!==0&&t("inventory_unknown"),null;(s.entries.length!==1||!d||d.entryId!==e.installReadyReserve.operationKey||d.bodyBytes!==0||d.basket!=="original")&&t("inventory_unknown");let i=n+"\0"+d.metadata,g=this.#u.get(i),c=g?structuredClone(g.ready):pt(Q(Buffer.from(d.metadata)),e);return c.createEventDigest!==n&&t("inventory_unknown"),g||this.#D(i,c),c}#D(e,n){let o=2*(e.length+f(n).length);if(!(o>Bt)){for(;this.#u.size>=Nt||this.#E+o>Bt;){let r=this.#u.keys().next().value;this.#E-=this.#u.get(r).retainedBytes,this.#u.delete(r)}this.#u.set(e,{ready:structuredClone(n),retainedBytes:o}),this.#E+=o}}readBindingControl(e){return this.#o(),this.#a({bindingId:e.storageBindingId,operationKey:"control-read"}),structuredClone(this.#g(e).at(-1)?.event.result.control??null)}readInstallationPlan(e){this.#o(),this.#t.format!==H&&t("format_mismatch");let n=this.#g(e).filter(r=>r.event.installationPlan!==void 0);n.length>1&&t("inventory_unknown");let o=n[0];return o?{plan:structuredClone(o.event.installationPlan),createEventDigest:o.digest,ready:o.installationReady??null}:null}readInstallationRetirement(e){this.#o(),this.#t.format!==H&&t("format_mismatch");let n=this.#g(e).find(o=>o.event.retirement!==void 0);return n?(n.event.mutation.kind!=="close-drained"&&t("inventory_unknown"),{record:structuredClone(n.event.retirement),closedEventDigest:n.digest,transitionId:n.event.mutation.transitionId}):null}#O(e){this.#e("SELECT value FROM spool_meta WHERE key=?").get("format")?.value!==H&&t("format_mismatch");let n=this.#e("SELECT COUNT(*) AS records, COALESCE(SUM(length(CAST(metadata AS BLOB))),0) AS bytes FROM entries WHERE binding_id=? AND entry_id LIKE ?").get(e.storageBindingId,`bc-state-${X(e)}-%`);return(n.records>ce||n.bytes>le)&&t("capacity_exceeded"),this.#R(e)}readInstallationRecoveryBootstrap(e,n){this.#o(),this.#t.format!==H&&t("format_mismatch"),this.#a({bindingId:e.storageBindingId,operationKey:"recovery-bootstrap"});let o=this.#k(e.storageBindingId);(o.applicationScopeId!==n.scope.applicationScopeId||o.endUserId!==n.scope.endUserId)&&t("identity_mismatch"),this.#d=!0;try{this.#n.exec("BEGIN");let r=this.#O(e),s=r.at(-1),d=s?.event.result.control??null;d&&(d.registration.scope.applicationScopeId!==n.scope.applicationScopeId||d.registration.scope.endUserId!==n.scope.endUserId||d.registration.sessionId!==n.sessionId)&&t("identity_mismatch");let i={current:d,headEventDigest:s?.digest??null,writeBarrier:this.#r!==null||this.#y.length>0?"unknown":"clear"};return this.#n.exec("ROLLBACK"),i}catch(r){try{this.#n.exec("ROLLBACK")}catch{try{this.#n.exec("BEGIN"),this.#n.exec("ROLLBACK")}catch{this.#p=!0}}if(r instanceof F||r instanceof ie)throw r;t("storage_failure")}finally{this.#d=!1}}#K(e,n,o){let r=null,s=null,d=null,i=(c,a)=>f(c)===f(a);for(let c of o){let a=c.event.mutation,p=c.event.result.control,y=p.fence;if(a.kind==="admit-run"||a.kind==="prepare-rewrite"){(r!==null||y===null||!d||!i(y.target,d.target)||!i(p.target,d.target))&&t("inventory_unknown");let R=a.kind==="admit-run";r={kind:R?"run":"rewrite",ownerEpoch:a.ownerEpoch,workId:R?a.runKey:a.rewriteId,turnId:R?a.turnId:null,captureRunKey:null,admission:a,admittedTarget:y.target,admittedEventDigest:c.digest,finish:null}}else(a.kind==="finish-run"||a.kind==="finish-rewrite")&&((!r||y!==null||r.kind!==(a.kind==="finish-run"?"run":"rewrite")||r.ownerEpoch!==a.ownerEpoch||r.workId!==(a.kind==="finish-run"?a.runKey:a.rewriteId))&&t("inventory_unknown"),a.kind==="finish-run"&&a.expectedTarget!==void 0&&!i(a.expectedTarget,p.target)&&t("inventory_unknown"),a.kind==="finish-rewrite"&&!i(p.target,a.outcome==="published"?d?.fence?.candidateTarget:r.admittedTarget)&&t("inventory_unknown"),s={...r,finish:{mutation:a,eventDigest:c.digest,resultingTarget:p.target}},r=null);(r===null?y!==null:y===null||y.kind!==r.kind||y.ownerEpoch!==r.ownerEpoch||y.id!==r.workId||y.turnId!==r.turnId||!i(y.target,r.admittedTarget)||!i(p.target,r.admittedTarget))&&t("inventory_unknown"),d=p}let g=[r,s].filter(c=>c?.kind==="run");if(g.length>0){let c="host-run-intent-",a="host-run-intent.",p=this.#e("SELECT COUNT(*) AS records, COALESCE(SUM(length(CAST(metadata AS BLOB))),0) AS bytes FROM entries WHERE binding_id=? AND entry_id>=? AND entry_id<?").get(e.storageBindingId,c,a);(p.records>this.#t.maxEntries||p.bytes>this.#t.globalLimit.bytes)&&t("capacity_exceeded");let y=new Map,R=this.#e("SELECT entry_id,operation_key,length(CAST(metadata AS BLOB)) AS actual_bytes FROM entries WHERE binding_id=? AND entry_id>=? AND entry_id<? ORDER BY entry_id").iterate(e.storageBindingId,c,a);for(let k of R){let S=k;S.actual_bytes+oe>16384&&t("capacity_exceeded");let _=this.#h(e.storageBindingId,S.entry_id),m=$(_),l=_.entry_id;(m.bodyBytes!==0||m.bodySha256!==se(new Uint8Array)||m.basket!=="original"||S.operation_key!==l)&&t("inventory_unknown");let b={bindingId:e.storageBindingId,operationKey:l,intentDigest:D(l),originalMax:{bytes:16384,records:1},terminalReserve:{bytes:1,records:1}},h=this.#e("SELECT length(CAST(entry_ids AS BLOB)) AS bytes FROM capture_ops WHERE binding_id=? AND operation_key=?").get(e.storageBindingId,l);(h?.bytes==null||h.bytes>1024)&&t("inventory_unknown");let I=this.#i(b);(!I||I.state!=="committed"||I.entry_ids!==JSON.stringify([l])||!i(x(I),b))&&t("inventory_unknown"),this.#s(I,(N,K)=>((N!==e.storageBindingId||K!==l)&&t("inventory_unknown"),_));let v=w(Q(Buffer.from(m.metadata)),["format","slot","ownerEpoch","turnId","captureRunKey","controlRunId","kind","value"]);X(v.slot);for(let N of["ownerEpoch","turnId","captureRunKey","controlRunId"])U(v[N]);(v.format!=="sdk2-host-run-v1"||v.kind!=="intent"||v.controlRunId!==`run-${D(v.captureRunKey)}`||l!==`host-run-intent-${D(f([v.slot,v.ownerEpoch,v.captureRunKey]))}`)&&t("inventory_unknown");let O=w(v.value,["initial","store"]),A=w(O.initial,["target","localHistoryGeneration","confirmedCommitId"]);Y(A.localHistoryGeneration),A.confirmedCommitId!==null&&U(A.confirmedCommitId);let C=Z({scope:n.scope,target:A.target,nowMs:n.nowMs}).target;O.store!=="host-owned-original-store"&&t("inventory_unknown");for(let N of g)i(v.slot,e)&&v.ownerEpoch===N.ownerEpoch&&v.turnId===N.turnId&&v.controlRunId===N.workId&&((!i(C,N.admittedTarget)||y.has(N))&&t("reconciliation_required"),y.set(N,v.captureRunKey))}r?.kind==="run"&&(r={...r,captureRunKey:y.get(r)??null}),s?.kind==="run"&&(s={...s,captureRunKey:y.get(s)??null})}return{active:r,lastCompleted:s}}readInstallationRecoverySnapshot(e,n,o,r){this.#o(),this.#t.format!==H&&t("format_mismatch"),this.#a({bindingId:e.storageBindingId,operationKey:"recovery-read"}),X(e);let s=d=>{let i=this.#k(d);(i.applicationScopeId!==n.scope.applicationScopeId||i.endUserId!==n.scope.endUserId)&&t("identity_mismatch")};s(e.storageBindingId),this.#d=!0;try{this.#n.exec("BEGIN");let d=this.#O(e),i=d.at(-1),g=i?.event.result.control??null;r.expectedHeadEventDigest!==void 0&&r.expectedHeadEventDigest!==(i?.digest??null)&&t("reconciliation_required"),g&&(g.registration.scope.applicationScopeId!==n.scope.applicationScopeId||g.registration.scope.endUserId!==n.scope.endUserId||g.registration.sessionId!==n.target.sessionId)&&t("identity_mismatch");let c=d.find(_=>_.event.installationPlan!==void 0),a=d.find(_=>_.event.retirement!==void 0);c&&c.event.mutation.kind!=="binding-create"&&t("inventory_unknown"),a&&a.event.mutation.kind!=="close-drained"&&t("inventory_unknown");let p=new Set([e.storageBindingId,...g?.registration.relatedBindingIds??[]]),y=0,R=0,k=o.map(_=>{this.#a(_),p.has(_.bindingId)||t("identity_mismatch"),s(_.bindingId);let m=this.#e("SELECT length(CAST(entry_ids AS BLOB)) AS bytes FROM capture_ops WHERE binding_id=? AND operation_key=?").get(_.bindingId,_.operationKey);m?.bytes!=null&&m.bytes>xe&&t("capacity_exceeded");let l=this.#i(_);if(!l)return{key:_,saved:null};let b=Le(x(l));if(l.state==="reserved")return{key:_,saved:{state:"reserved",reservation:b}};(l.state!=="committed"||l.entry_ids===null)&&t("inventory_unknown");let h=JSON.parse(l.entry_ids);Array.isArray(h)||t("inventory_unknown"),y+=h.length,y>dt&&t("capacity_exceeded"),(h.some(O=>typeof O!="string")||new Set(h).size!==h.length)&&t("inventory_unknown");let I=new Map;for(let O of h){U(O);let A=this.#e("SELECT length(CAST(metadata AS BLOB)) AS bytes FROM entries WHERE binding_id=? AND entry_id=?").get(_.bindingId,O);A||t("entry_not_found"),R+=A.bytes,(A.bytes>fe||R>xe)&&t("capacity_exceeded");let C=this.#e(`SELECT ${te},operation_key FROM entries WHERE binding_id=? AND entry_id=?`).get(_.bindingId,O);(!C||C.operation_key!==_.operationKey)&&t("inventory_unknown"),I.set(O,C)}let v=this.#s(l,(O,A)=>(O!==_.bindingId&&t("identity_mismatch"),I.get(A)??t("entry_not_found")));return{key:_,saved:{state:"committed",reservation:b,receipt:v}}}),S={slot:e,current:g,headEventDigest:i?.digest??null,originalCreate:c?.event.mutation.kind==="binding-create"?c.event.mutation.body:null,plan:c?.event.installationPlan??null,createEventDigest:c?.digest??null,ready:c?.installationReady??null,retirement:a?.event.mutation.kind==="close-drained"?{record:a.event.retirement,closedEventDigest:a.digest,transitionId:a.event.mutation.transitionId}:null,operations:k,writeBarrier:this.#r!==null||this.#y.length>0?"unknown":"clear",...r.includeWork?{work:this.#K(e,n,d)}:{}};return this.#n.exec("ROLLBACK"),S}catch(d){try{this.#n.exec("ROLLBACK")}catch{try{this.#n.exec("BEGIN"),this.#n.exec("ROLLBACK")}catch{this.#p=!0}}if(d instanceof F||d instanceof ie)throw d;t("storage_failure")}finally{this.#d=!1}}commitInstallationReady(e,n){this.#o(),this.#t.format!==H&&t("format_mismatch");let o=Pe(n);return f(e)!==f(o.slot)&&t("identity_mismatch"),this.#r!==null&&((this.#r.bindingId!==o.installReadyReserve.bindingId||this.#r.operationKey!==o.installReadyReserve.operationKey)&&t("reconciliation_required"),this.status(o.installReadyReserve)),this.#l(o.installReadyReserve,r=>{let s=this.#g(e),d=s.find(y=>y.event.installationPlan);(!d||f(d.event.installationPlan)!==f(o))&&t("identity_mismatch");let i=this.#w(o,d.digest);if(i)return i;let g=s.at(-1).event.result.control;(g.state!=="active"||g.fence!==null)&&t("dependency_held");let c=gt({plan:o,createEventDigest:d.digest}),a=this.#v([{entryId:o.installReadyReserve.operationKey,basket:"original",metadata:f(c),body:new Uint8Array}]),p=[g.closingReserve,g.closedReserve].filter(y=>y!==null&&this.#i(y)?.state!=="committed");return(s.length+1+p.length>ce||s.reduce((y,R)=>y+R.metadataBytes,0)+a[0].witness.metadataBytes+p.length*Ce>le)&&t("capacity_exceeded"),this.#m(o.installReadyReserve,a,r),c})}queryBindingOperation(e){this.#o();let n=Ge(e),o=w(n,["storageBindingId","slotId","scope","operation","request"]),r={storageBindingId:n.storageBindingId,slotId:n.slotId};this.#a({bindingId:r.storageBindingId,operationKey:"control-query"}),X(r);let s=this.#t.bindings.find(y=>y.bindingId===r.storageBindingId),d=w(o.scope,["applicationScopeId","endUserId","authorizationRevision"]);(d.applicationScopeId!==s.applicationScopeId||d.endUserId!==s.endUserId)&&t("identity_mismatch");let i=w(o.request,["operationEpoch","requestId"]);(typeof i.operationEpoch!="string"||typeof i.requestId!="string"||!["binding-create","archive-ack","binding-close"].includes(n.operation))&&t("invalid_input");let g=this.#g(r),c=g.at(-1)?.event.result.control;if(!c)return null;let a="bc-op-"+D(f({scope:[s.applicationScopeId,s.endUserId],resource:n.operation==="binding-create"?{sessionId:c.registration.sessionId}:{bindingId:c.registration.bindingId},operation:n.operation,request:n.request})),p=g.find(y=>y.event.operationKey===a);return p?(this.status({bindingId:r.storageBindingId,operationKey:p.storageOperationKey}),structuredClone(p.event.result)):(this.#r?.bindingId===r.storageBindingId&&(this.#r.operationKey===a||n.operation==="binding-close"&&this.#r.operationKey===c.closingReserve?.operationKey)&&this.status(this.#r),null)}#v(e){(Be.isProxy(e)||!Array.isArray(e)||e.length>this.#t.maxEntries)&&t("invalid_input"),Reflect.ownKeys(e).length!==e.length+1&&t("invalid_input");let o=Object.getPrototypeOf(Uint8Array.prototype),r=Object.getOwnPropertyDescriptor(o,"buffer").get,s=Object.getOwnPropertyDescriptor(o,"byteLength").get,d=0,i=new Set;return Array.from({length:e.length},(c,a)=>{let p=Object.getOwnPropertyDescriptor(e,String(a));(!p||!Object.hasOwn(p,"value")||!p.enumerable)&&t("invalid_input");let y=w(p.value,["entryId","basket","metadata","body"]);U(y.entryId),i.has(y.entryId)&&t("entry_conflict"),i.add(y.entryId),y.basket!=="original"&&y.basket!=="terminal"&&t("invalid_input"),(Be.isProxy(y.body)||!Be.isUint8Array(y.body)||Be.isSharedArrayBuffer(r.call(y.body)))&&t("invalid_input");let R=s.call(y.body),k=ee(y.metadata);return(R>He||k>fe)&&t("capacity_exceeded"),d+=k+R+oe,d>this.#t.globalLimit.bytes&&t("capacity_exceeded"),{item:y,bodyBytes:R,metadataBytes:k}}).map(({item:c,bodyBytes:a,metadataBytes:p})=>{let y=new Uint8Array(c.body);return{body:y,witness:{entryId:c.entryId,basket:c.basket,metadata:c.metadata,metadataBytes:p,bodyBytes:a,bodySha256:se(y),logicalBytes:p+a+oe}}})}#_(e,n){this.#a(e),J(e.intentDigest);let o=this.#i(e);if(o){f(x(o))!==f(e)&&t("operation_conflict");return}n.reserve(e).status==="rejected"&&t("capacity_exceeded"),this.#e("INSERT INTO capture_ops(binding_id,operation_key,intent_digest,original_bytes,original_records,terminal_bytes,terminal_records,state) VALUES (?,?,?,?,?,?,?,?)").run(e.bindingId,e.operationKey,e.intentDigest,e.originalMax.bytes,e.originalMax.records,e.terminalReserve.bytes,e.terminalReserve.records,"reserved")}#m(e,n,o){let r=re(n.map(i=>i.witness)),s=this.#i(e)??t("operation_not_found");if(s.state==="committed"){s.commit_digest!==r&&t("operation_conflict");return}o.settle(e,{status:"known",originalEntries:n.filter(i=>i.witness.basket==="original").map(i=>({entryId:i.witness.entryId,bytes:i.witness.logicalBytes,records:1})),terminalEntries:n.filter(i=>i.witness.basket==="terminal").map(i=>({entryId:i.witness.entryId,bytes:i.witness.logicalBytes,records:1}))});let d=this.#e("INSERT INTO entries(binding_id,entry_id,operation_key,basket,metadata,metadata_bytes,body_sha,body_bytes,body) VALUES (?,?,?,?,?,?,?,?,?)");for(let i of n)d.run(e.bindingId,i.witness.entryId,e.operationKey,i.witness.basket,i.witness.metadata,i.witness.metadataBytes,i.witness.bodySha256,i.witness.bodyBytes,i.body);this.#e("UPDATE capture_ops SET state='committed',commit_digest=?,entry_ids=? WHERE binding_id=? AND operation_key=?").run(r,JSON.stringify(n.map(i=>i.witness.entryId)),e.bindingId,e.operationKey)}#T(e){w(e,["bindingId","operationKey","intentDigest","commitDigest","entryIds"]),this.#a(e),J(e.intentDigest),J(e.commitDigest),(!Array.isArray(e.entryIds)||e.entryIds.length>this.#t.maxEntries)&&t("inventory_unknown");let n=this.#i(e);(!n||n.state!=="committed"||n.intent_digest!==e.intentDigest||n.commit_digest!==e.commitDigest)&&t("inventory_unknown");let o=this.#s(n);return f(o.entries.map(r=>r.entryId))!==f(e.entryIds)&&t("inventory_unknown"),o}#A(e,n){let o=e.registration,r=[];for(let a of o.relatedBindingIds){let p=this.#e(`SELECT ${te} FROM entries WHERE binding_id=? AND (entry_id LIKE 'jr-p-%' OR entry_id LIKE 'jr-a-%')`).all(a);p.length&&a!==o.bindingId&&t("reconciliation_required"),r.push(...p)}let s=st(r.map($),{sourceId:o.sourceId,sourceGeneration:o.sourceGeneration,generations:e.target.generations});s.records.some(a=>a.target.sessionId!==o.sessionId)&&t("identity_mismatch");let d=new Map;for(let a of r){let p=this.#e("SELECT operation_key FROM entries WHERE binding_id=? AND entry_id=?").get(a.binding_id,a.entry_id),y=d.get(p.operation_key)??this.#s(this.#i({bindingId:a.binding_id,operationKey:p.operation_key})??t("inventory_unknown"));y.entries.some(R=>R.entryId===a.entry_id)||t("inventory_unknown"),d.set(p.operation_key,y)}let i=0n,g=null,c=null;for(let{event:a}of n){if(a.mutation.kind!=="archive-ack")continue;let p=a.mutation.body,y=BigInt(p.coverage.fromSequence),R=BigInt(p.coverage.throughSequence);(y>i+1n||R<i||R>BigInt(s.records.length)||R-y>=128n)&&t("reconciliation_required");let k=s.records.slice(Number(y-1n),Number(R)),S=Et({bindingId:o.bindingId,sourceId:o.sourceId,sourceGeneration:o.sourceGeneration,generations:e.target.generations,controlBytes:fe},p.request,p.expectedRevision,k);f(S)!==f(p)&&t("reconciliation_required");let _=D(f({scope:[o.scope.applicationScopeId,o.scope.endUserId],bindingId:o.bindingId,operation:"archive-ack",request:p.request})),m=a.result.receipt;(!m||m.outcomeRef!=="ack-"+_||m.revision!==String(BigInt(p.expectedRevision)+1n))&&t("inventory_unknown");let l=a.companion;(!l||l.bindingId!==o.bindingId||l.operationKey!=="sa-ack-"+_||l.intentDigest!==m.semanticDigest)&&t("reconciliation_required");let b=this.#T(l),h=b.entries[0],I=f({format:"sdk2-source-transfer-v1",kind:"ack",ack:p,receipt:m});(b.entries.length!==1||!h||h.entryId!=="sa-"+_||h.basket!=="original"||h.bodyBytes!==0||h.bodySha256!==se(new Uint8Array(0))||h.metadata!==I)&&t("reconciliation_required"),i=R,g=p.coverage.headDigest,c=p.coverage}return f(e.acknowledged)!==f(c)&&t("reconciliation_required"),{index:s,through:i,headDigest:g}}#M(e,n){let{index:o,through:r,headDigest:s}=this.#A(e,n);o.head===null?r!==0n&&t("reconciliation_required"):(r!==BigInt(o.head.sequence)||s!==o.head.recordDigest)&&t("reconciliation_required")}#C(e,n,o){let r=n.find(i=>i.event.installationPlan)?.event.installationPlan;if(!r)return;let{index:s,through:d}=this.#A(e,n);ot(s,d,r.createResponse.limits.offlineMs,o)&&t("capacity_exceeded")}releasePreparedBody(e){let n=Rt(e);return this.#l(null,()=>{let o=this.#g(n.slot),r=o.at(-1)?.event.result.control??t("operation_not_found"),{index:s,through:d}=this.#A(r,o);r.fence!==null&&t("reconciliation_required"),this.#B(r);let i=St(n,{state:r,events:o,records:s.records,acknowledgedThrough:d,identity:c=>this.#k(c),receipt:(c,a)=>this.#s(this.#i({bindingId:c,operationKey:a})??t("reconciliation_required")),materials:c=>this.#e("SELECT "+te+",operation_key FROM entries WHERE binding_id=? AND entry_id LIKE ?").all(c,"material-%").map(a=>({operationKey:a.operation_key,witness:$(a)}))}),g=this.#h(n.captureBindingId,i.entry.entryId);return this.#e("UPDATE entries SET body=NULL WHERE binding_id=? AND entry_id=?").run(n.captureBindingId,g.entry_id),{...i,releasedBytes:g.retained===1?g.body_bytes:0}})}#k(e){let n=this.#t.bindings.find(o=>o.bindingId===e)??t("identity_mismatch");return{applicationScopeId:n.applicationScopeId,endUserId:n.endUserId}}#L(e,n,o,r=e){let s=this.#e("SELECT COUNT(*) AS records, COALESCE(SUM(metadata_bytes), 0) AS bytes FROM entries WHERE binding_id=?").get(e);if(s.records>$e||s.bytes>Je)return!1;let d=this.#e("SELECT "+te+",operation_key FROM entries WHERE binding_id=?").all(e).map(p=>({operationKey:p.operation_key,witness:$(p),bodyState:p.retained===1?"retained":"released"})),i=this.#e("SELECT * FROM capture_ops WHERE binding_id=?").all(e).map(p=>p.state==="reserved"?{state:"reserved",reservation:x(p)}:{state:"committed",reservation:x(p),receipt:this.#s(p)}),g=this.#e("SELECT * FROM holds WHERE binding_id=?").all(e).map(Ot),c={bindingId:e,protocolBindingId:r,entries:d,operations:i,holds:g},a=o?Ve(c,n,o):ze(c,n);return a.kind==="recognized-close-standby"&&f(a.reservation)===f(n)}#B(e,n,o,r=!1){let s=[e.closingReserve,e.closedReserve,e.fence?.completion,ye(e)].filter(d=>d!=null);o&&((e.state!=="closing"||e.fence!==null||o.bindingId!==e.storageBindingId)&&t("identity_mismatch"),s.push(o));for(let d of e.registration.relatedBindingIds){this.#e("SELECT 1 FROM holds WHERE binding_id=? AND state='held' LIMIT 1").get(d)&&t("dependency_held");let g=this.#e("SELECT * FROM capture_ops WHERE binding_id=? AND state='reserved'").all(d).filter(a=>{if(s.some(_=>f(_)===f(x(a))))return!1;if(r&&d===e.storageBindingId&&a.operation_key===Se.completed){let _=this.#i({bindingId:d,operationKey:Se.intent});if(!_||_.state!=="committed")return!0;let m=this.#s(_),l=m.entries[0];if(m.entries.length!==1||!l||l.entryId!==Se.intent||l.bodyBytes!==0||l.metadataBytes>16e3||l.basket!=="original")return!0;let b=tt(JSON.parse(l.metadata));return!nt(this,b,e)||f(x(_))!==f(Me(b,!1))||f(x(a))!==f(Me(b,!0))}if(!r||d!==e.storageBindingId||!/^host-record-retention-([1-9][0-9]{0,2})-complete$/.test(a.operation_key))return!0;let p=a.operation_key.slice(0,-9),y=this.#i({bindingId:d,operationKey:p});if(!y||y.state!=="committed")return!0;let R=this.#s(y);if(R.entries.length!==1)return!0;let k=R.entries[0];if(k.entryId!==p||k.bodyBytes!==0||k.metadataBytes>16e3||k.basket!=="original")return!0;let S=Ze(JSON.parse(k.metadata));return!et(S,e)||f(x(y))!==f(Ke(S,!1))||f(x(a))!==f(Ke(S,!0))});if(g.length===0)continue;let c=g.find(a=>a.operation_key==="material-close");c&&n&&e.state==="active"&&e.acceptedCapabilities.includes("context-materials-v1")&&this.#L(d,x(c),{bindingId:d,...n,sourceId:e.registration.sourceId,sourceGeneration:e.registration.sourceGeneration,state:e.state,operationEpoch:e.epoch},e.registration.bindingId)||g.length===1&&c&&this.#L(d,x(c),void 0,e.registration.bindingId)||t("reconciliation_required")}}commitBindingMutation(e){this.#o(),w(e,["storageBindingId","slotId","authority","mutation","entries"],["idleLease","companion","installation"]);let n={storageBindingId:e.storageBindingId,slotId:e.slotId},o=X(n);this.#a({bindingId:n.storageBindingId,operationKey:"control-mutate"});let r=Z(e.authority),s=Ne(e.mutation);if(e.installation!==void 0){let m=w(e.installation,["kind"],["prepared","candidate"]);m.kind==="create"?(w(e.installation,["kind","prepared"]),s.kind!=="binding-create"&&t("invalid_input")):m.kind==="retire"?(w(e.installation,["kind","candidate"]),s.kind!=="close-drained"&&t("invalid_input")):t("invalid_input"),this.#t.format!==H&&t("format_mismatch")}let d=this.#v(e.entries);s.kind!=="archive-ack"&&(d.length>0||e.companion!==void 0)&&t("invalid_input");let i;if(e.companion!==void 0){let m=w(e.companion,["reservation","entries"]);i={reservation:Le(m.reservation),entries:this.#v(m.entries)},this.#a(i.reservation)}let g=this.#g(n),c=g.at(-1)?.event.result.control,a=c?.registration??(s.kind==="initialize"?s.registration:t("operation_not_found")),p=this.#t.bindings.find(m=>m.bindingId===n.storageBindingId);(r.scope.applicationScopeId!==p.applicationScopeId||r.scope.endUserId!==p.endUserId||a.scope.applicationScopeId!==p.applicationScopeId||a.scope.endUserId!==p.endUserId||a.sessionId!==r.target.sessionId)&&t("identity_mismatch");for(let m of a.relatedBindingIds){let l=this.#t.bindings.find(b=>b.bindingId===m);(!l||l.applicationScopeId!==p.applicationScopeId||l.endUserId!==p.endUserId)&&t("identity_mismatch")}i&&(i.reservation.bindingId===n.storageBindingId||!a.relatedBindingIds.includes(i.reservation.bindingId))&&t("identity_mismatch");let y=De(n,a,s),R=s.kind==="binding-close"?c?.closingReserve:s.kind==="close-drained"?c?.closedReserve:s.kind==="finish-run"||s.kind==="finish-rewrite"?c?.fence?.completion:s.kind==="stage-rewrite-candidate"?ye(c):null,k=g.find(m=>m.event.operationKey===y.key)?.storageOperationKey??R?.operationKey??y.key;if(this.#r!==null){let l=g.find(b=>b.event.operationKey===y.key)?.storageOperationKey??k;(this.#r.bindingId!==n.storageBindingId||this.#r.operationKey!==l)&&t("reconciliation_required"),this.status(this.#r)}let S={...n,authority:r,mutation:s,entries:e.entries,...e.idleLease?{idleLease:e.idleLease}:{}},_=this.#l({bindingId:n.storageBindingId,operationKey:k},m=>{let l=this.#g(n),b=l.at(-1),h=b?.event.result.control??null,I=l.find(E=>E.event.operationKey===y.key);if(I){I.event.semanticDigest!==y.semantic&&t("operation_conflict");let E=this.#i({bindingId:n.storageBindingId,operationKey:I.storageOperationKey})??t("inventory_unknown");if(re(this.#s(E).entries.slice(1))!==re(d.map(T=>T.witness))&&t("operation_conflict"),i){let T=this.#i(i.reservation);(!T||T.state!=="committed"||T.intent_digest!==i.reservation.intentDigest||T.commit_digest!==re(i.entries.map(W=>W.witness)))&&t("operation_conflict"),I.event.companion&&(I.event.companion.bindingId!==i.reservation.bindingId||I.event.companion.operationKey!==i.reservation.operationKey||I.event.companion.commitDigest!==T.commit_digest)&&t("operation_conflict")}return structuredClone(I.event.result)}if(i&&this.#i(i.reservation)?.state==="committed"&&t("operation_conflict"),s.kind==="initialize"){let E=this.#e("SELECT metadata FROM entries WHERE entry_id LIKE 'bc-state-%-0'").all();for(let T of E){let W=Q(Buffer.from(T.metadata)).result.control;Ee(W);let V=W.registration;(V.scope.applicationScopeId===a.scope.applicationScopeId&&V.scope.endUserId===a.scope.endUserId&&(V.sessionId===a.sessionId||V.bindingId===a.bindingId)||V.relatedBindingIds.some(he=>a.relatedBindingIds.includes(he)))&&t("identity_mismatch")}}s.kind==="rotate-epoch"&&l.some(E=>E.event.result.control.epoch.id===s.epoch.id)&&t("epoch_expired"),(s.kind==="admit-run"||s.kind==="prepare-rewrite")&&l.some(E=>{let T=E.event.mutation;return T.kind===s.kind&&T.ownerEpoch===s.ownerEpoch&&(T.kind==="admit-run"?T.runKey===s.runKey:T.rewriteId===s.rewriteId)})&&t("operation_conflict");let v=je(S,h);Ee(v.control);let O=e.installation?.kind==="create"&&s.kind==="binding-create"?bt(e.installation.prepared,this,n,s.body,v):void 0,A=l.find(E=>E.event.installationPlan),C=O??A?.event.installationPlan,N=A?.installationReady,K;if(s.kind==="close-drained"&&C){e.installation?.kind!=="retire"&&t("identity_mismatch");let E=l.find(W=>W.event.mutation.kind==="binding-close"&&f(W.event.mutation.body.request)===f(v.control.closeIntent));E||t("inventory_unknown");let T=ft(e.installation.candidate,this,n,{plan:C,ready:N??null,control:v.control,closingEventDigest:E.digest});K=Ue({plan:C,installedRecord:N??null,control:v.control,confirmedHistory:T.confirmedHistory,closingEventDigest:E.digest}),f(K)!==f(T)&&t("identity_mismatch")}else e.installation?.kind==="retire"&&t("identity_mismatch");h&&["binding-create","admit-run","prepare-rewrite","close-drained"].includes(s.kind)&&this.#B(h,s.kind==="admit-run"?{target:r.target,nowMs:r.nowMs,operationEpochIds:[...new Set(l.map(E=>E.event.result.control.epoch.id))]}:void 0,K&&!N?C.installReadyReserve:void 0,s.kind==="prepare-rewrite"),h&&s.kind==="close-drained"&&this.#M(h,l),h&&s.kind==="admit-run"&&this.#C(h,l,r.nowMs),(s.kind==="binding-create"||s.kind==="admit-run"||s.kind==="prepare-rewrite"||s.kind==="close-drained")&&Ye(e.idleLease,n,h?.revision??"0");let M=i?{bindingId:i.reservation.bindingId,operationKey:i.reservation.operationKey,intentDigest:i.reservation.intentDigest,commitDigest:re(i.entries.map(E=>E.witness)),entryIds:i.entries.map(E=>E.witness.entryId)}:void 0,ae={format:this.#t.format===H?"sdk2-binding-event-v2":"sdk2-binding-event-v1",operationKey:y.key,semanticDigest:y.semantic,previousDigest:b?.digest??null,mutation:s,result:v,...M?{companion:M}:{},...O?{installationPlan:O}:{},...K?{retirement:K}:{}},pe=this.#v([{entryId:"bc-state-"+o+"-"+v.control.revision,basket:"original",metadata:f(ae),body:new Uint8Array(0)}]),z=[...pe,...d],be=N?1:0,ne=N?ee(f(N)):0,de=[v.control.closingReserve,v.control.closedReserve,v.control.fence?.completion,ye(v.control),C?.installReadyReserve].filter(E=>E!=null&&E.operationKey!==k&&!(K&&E.operationKey===C?.installReadyReserve.operationKey)&&this.#i(E)?.state!=="committed");(l.length+1+be+de.length>ce||l.reduce((E,T)=>E+T.metadataBytes,0)+ne+pe[0].witness.metadataBytes+de.length*Ce>le)&&t("capacity_exceeded");for(let E of[v.control.closingReserve,v.control.closedReserve,v.control.fence?.completion,ye(v.control)])E&&this.#_(E,m);O&&this.#_(O.installReadyReserve,m);let ue=R??{bindingId:n.storageBindingId,operationKey:y.key,intentDigest:y.semantic,originalMax:{bytes:z.filter(E=>E.witness.basket==="original").reduce((E,T)=>E+T.witness.logicalBytes,0),records:z.filter(E=>E.witness.basket==="original").length},terminalReserve:{bytes:Math.max(1,z.filter(E=>E.witness.basket==="terminal").reduce((E,T)=>E+T.witness.logicalBytes,0)),records:Math.max(1,z.filter(E=>E.witness.basket==="terminal").length)}};if(this.#_(ue,m),i&&(this.#_(i.reservation,m),this.#m(i.reservation,i.entries,m)),s.kind==="finish-rewrite"&&s.outcome==="unchanged"){let E=ye(h);E&&this.#m(E,[],m)}return K&&!N&&this.#m(C.installReadyReserve,[],m),this.#m(ue,z,m),structuredClone(v)});return e.installation?.kind==="create"&&It(e.installation.prepared,this),_}#x(e){this.#o(!0);let n=w(e,["prepared","seal","lease","leaseEntry"]),o=["prepared","seal","lease"].map(d=>{let i=w(n[d],["bindingId","operationKey","intentDigest","originalMax","terminalReserve"]),g={bindingId:i.bindingId,operationKey:i.operationKey};this.#a(g),J(i.intentDigest);let c=a=>{let p=w(i[a],["bytes","records"]);return Y(p.bytes,1),Y(p.records,1),{bytes:p.bytes,records:p.records}};return{...g,intentDigest:i.intentDigest,originalMax:c("originalMax"),terminalReserve:c("terminalReserve")}});new Set(o.map(d=>JSON.stringify([d.bindingId,d.operationKey]))).size!==3&&t("operation_conflict");let r=o[2],s=this.#v([n.leaseEntry]);(s[0].witness.basket!=="original"||s[0].witness.bodyBytes!==0)&&t("invalid_input");try{return this.#l(r,d=>{for(let i of o)this.#_(i,d);return this.#b(),this.#m(r,s,d),this.#s(this.#i(r))})}catch(d){throw d instanceof F&&d.code==="commit_unknown"&&(this.#r=null,this.#y=o.map(({bindingId:i,operationKey:g})=>({bindingId:i,operationKey:g}))),d}}prepareOperation(e){this.#o(!0);let n=w(e,["pending","request","entry"]),o=["pending","request"].map(i=>{let g=w(n[i],["bindingId","operationKey","intentDigest","originalMax","terminalReserve"]),c={bindingId:g.bindingId,operationKey:g.operationKey};this.#a(c),J(g.intentDigest);let a=p=>{let y=w(g[p],["bytes","records"]);return Y(y.bytes,1),Y(y.records,1),{bytes:y.bytes,records:y.records}};return{...c,intentDigest:g.intentDigest,originalMax:a("originalMax"),terminalReserve:a("terminalReserve")}}),[r,s]=o;(r.bindingId!==s.bindingId||r.intentDigest!==s.intentDigest||r.operationKey===s.operationKey)&&t("operation_conflict");let d=this.#v([n.entry]);d[0].witness.basket!=="original"&&t("invalid_input");try{return this.#l(s,i=>{for(let g of o)this.#_(g,i);return this.#b(),this.#m(s,d,i),this.#s(this.#i(s))})}catch(i){throw i instanceof F&&i.code==="commit_unknown"&&(this.#r=null,this.#y=o.map(({bindingId:g,operationKey:c})=>({bindingId:g,operationKey:c}))),i}}reserve(e){return this.#o(!0),this.#a(e),J(e.intentDigest),this.#l(e,n=>{let o=this.#i(e);if(o){let s=x(o);return JSON.stringify(s)!==JSON.stringify({bindingId:e.bindingId,operationKey:e.operationKey,intentDigest:e.intentDigest,originalMax:{bytes:e.originalMax.bytes,records:e.originalMax.records},terminalReserve:{bytes:e.terminalReserve.bytes,records:e.terminalReserve.records}})&&t("operation_conflict"),s}return n.reserve(e).status==="rejected"&&t("capacity_exceeded"),this.#e("INSERT INTO capture_ops(binding_id,operation_key,intent_digest,original_bytes,original_records,terminal_bytes,terminal_records,state) VALUES (?,?,?,?,?,?,?,?)").run(e.bindingId,e.operationKey,e.intentDigest,e.originalMax.bytes,e.originalMax.records,e.terminalReserve.bytes,e.terminalReserve.records,"reserved"),{...x(this.#i(e))}})}commit(e){this.#o(!0),this.#a(e),J(e.intentDigest),(!Array.isArray(e.entries)||e.entries.length>this.#t.maxEntries)&&t("invalid_input");let n=this.#i(e)??t("operation_not_found");n.intent_digest!==e.intentDigest&&t("operation_conflict");let o={bytes:0,records:0},r={bytes:0,records:0},s=new Set,i=e.entries.map(c=>{U(c.entryId),s.has(c.entryId)&&t("entry_conflict"),s.add(c.entryId),(c.basket!=="original"&&c.basket!=="terminal"||!(c.body instanceof Uint8Array))&&t("invalid_input"),c.body.buffer instanceof SharedArrayBuffer&&t("invalid_input");let a=ee(c.metadata);(a>fe||c.body.byteLength>He)&&t("capacity_exceeded");let p=c.basket==="original"?o:r;return p.bytes+=a+oe+c.body.byteLength,p.records++,(p.bytes>(c.basket==="original"?n.original_bytes:n.terminal_bytes)||p.records>(c.basket==="original"?n.original_records:n.terminal_records)||o.bytes+r.bytes>this.#t.globalLimit.bytes||o.records+r.records>this.#t.globalLimit.records)&&t("capacity_exceeded"),{entryId:c.entryId,basket:c.basket,metadata:c.metadata,body:c.body,metadataBytes:a,bodyBytes:c.body.byteLength}}).map(c=>{let a=new Uint8Array(c.body);return a.byteLength!==c.bodyBytes&&t("invalid_input"),{witness:{entryId:c.entryId,basket:c.basket,metadata:c.metadata,metadataBytes:c.metadataBytes,bodyBytes:a.byteLength,bodySha256:se(a),logicalBytes:c.metadataBytes+oe+a.byteLength},body:a}}),g=re(i.map(c=>c.witness));return this.#l(e,c=>{let a=this.#i(e)??t("operation_not_found");if(a.intent_digest!==e.intentDigest&&t("operation_conflict"),a.state==="committed")return a.commit_digest!==g&&t("operation_conflict"),this.#s(a);c.settle(e,{status:"known",originalEntries:i.filter(y=>y.witness.basket==="original").map(y=>({entryId:y.witness.entryId,bytes:y.witness.logicalBytes,records:1})),terminalEntries:i.filter(y=>y.witness.basket==="terminal").map(y=>({entryId:y.witness.entryId,bytes:y.witness.logicalBytes,records:1}))});let p=this.#e("INSERT INTO entries(binding_id,entry_id,operation_key,basket,metadata,metadata_bytes,body_sha,body_bytes,body) VALUES (?,?,?,?,?,?,?,?,?)");for(let y of i)p.run(e.bindingId,y.witness.entryId,e.operationKey,y.witness.basket,y.witness.metadata,y.witness.metadataBytes,y.witness.bodySha256,y.witness.bodyBytes,y.body);return this.#e("UPDATE capture_ops SET state='committed',commit_digest=?,entry_ids=? WHERE binding_id=? AND operation_key=?").run(g,JSON.stringify(i.map(y=>y.witness.entryId)),e.bindingId,e.operationKey),this.#s(this.#i(e))})}status(e){this.#o(),this.#a(e);let n=this.#i(e),o=n?n.state==="reserved"?{state:"reserved",reservation:x(n)}:{state:"committed",reservation:x(n),receipt:this.#s(n)}:null;return this.#r?.bindingId===e.bindingId&&this.#r.operationKey===e.operationKey&&(this.#r=null),this.#y=this.#y.filter(r=>r.bindingId!==e.bindingId||r.operationKey!==e.operationKey),o}readEntry(e){this.#o(),Y(e.offset),Y(e.maxBytes,1),e.maxBytes>At&&t("invalid_input");let n=this.#h(e.bindingId,e.entryId),o=$(n);if(e.offset>o.bodyBytes&&t("invalid_input"),n.retained===0)return{witness:o,bodyState:"released",offset:e.offset,body:null,complete:!1};if(e.offset===o.bodyBytes)return{witness:o,bodyState:"retained",offset:e.offset,body:new Uint8Array,complete:!0};let r=this.#e("SELECT substr(body,?,?) AS part FROM entries WHERE binding_id=? AND entry_id=?").get(e.offset+1,e.maxBytes,e.bindingId,e.entryId);return(!(r.part instanceof Uint8Array)||r.part.byteLength!==Math.min(e.maxBytes,o.bodyBytes-e.offset))&&t("inventory_unknown"),{witness:o,bodyState:"retained",offset:e.offset,body:Uint8Array.from(r.part),complete:e.offset+r.part.length===o.bodyBytes}}acquireHold(e){return U(e.token),this.#l(null,()=>{let n=this.#e("SELECT * FROM holds WHERE binding_id=? AND token=?").get(e.bindingId,e.token);return n?(n.entry_id!==e.entryId&&t("hold_conflict"),Ot(n)):(this.#h(e.bindingId,e.entryId).retained===0&&t("entry_released"),this.#e("INSERT INTO holds(binding_id,token,entry_id,state) VALUES (?,?,?,'held')").run(e.bindingId,e.token,e.entryId),{...e,state:"held"})})}releaseHold(e){return U(e.token),this.#l(null,()=>((this.#e("SELECT * FROM holds WHERE binding_id=? AND token=?").get(e.bindingId,e.token)??t("hold_not_found")).entry_id!==e.entryId&&t("hold_conflict"),this.#e("UPDATE holds SET state='released' WHERE binding_id=? AND token=?").run(e.bindingId,e.token),{...e,state:"released"}))}ackAndRelease(e,n){return U(e.bindingId),(!Array.isArray(e.entryIds)||e.entryIds.length===0||e.entryIds.length>this.#t.maxEntries||new Set(e.entryIds).size!==e.entryIds.length)&&t("invalid_input"),this.#l(null,()=>{let o=e.entryIds.map(i=>this.#h(e.bindingId,i));for(let i of o)this.#e("SELECT 1 AS present FROM holds WHERE binding_id=? AND entry_id=? AND state='held' LIMIT 1").get(i.binding_id,i.entry_id)&&t("held");let r=o.map($),s=n(structuredClone(r));s!==!0&&(s!==null&&(typeof s=="object"||typeof s=="function")&&"then"in s&&typeof s.then=="function"&&Promise.resolve(s).catch(()=>{}),t("confirmation_rejected"));let d=this.#e("UPDATE entries SET body=NULL WHERE binding_id=? AND entry_id=?");for(let i of o)d.run(i.binding_id,i.entry_id);return{releasedBytes:o.reduce((i,g)=>i+(g.retained===1?g.body_bytes:0),0),entries:r}})}bindingIdentity(e){this.#o(),U(e);let n=this.#t.bindings.find(o=>o.bindingId===e);return n||t("identity_mismatch"),{applicationScopeId:n.applicationScopeId,endUserId:n.endUserId}}assertObservationReadable(){this.#o(),(this.#r!==null||this.#y.length>0)&&t("reconciliation_required")}readObservationCommitted(e){this.assertObservationReadable(),this.#a(e);let n=this.#i(e);if(!n||n.state!=="committed")return null;n.entry_ids===null&&t("inventory_unknown");let o=JSON.parse(n.entry_ids);(!Array.isArray(o)||o.length>this.#t.maxEntries||o.length>16384)&&t("capacity_exceeded");let r=0;return this.#s(n,(s,d)=>{let i=this.#h(s,d);return r+=i.metadata_bytes,(!Number.isSafeInteger(r)||r>67108864)&&t("capacity_exceeded"),i})}readObservationOperationFacts(e){this.assertObservationReadable();let n=w(e,["bindingId","operationKeyPrefix","maxBodyBytes"]),o=n.bindingId,r=n.operationKeyPrefix,s=n.maxBodyBytes;this.#a({bindingId:o,operationKey:r}),Y(s,1),(!/^[A-Za-z0-9_-]+$/.test(r)||s>At)&&t("invalid_input");let d=r.slice(0,-1)+String.fromCharCode(r.charCodeAt(r.length-1)+1);this.#d=!0;try{this.#n.exec("BEGIN");let i=this.#e("SELECT count(*) AS records, COALESCE(SUM(length(CAST(entry_ids AS BLOB))),0) AS bytes FROM capture_ops WHERE binding_id=? AND operation_key>=? AND operation_key<?").get(o,r,d);(i.records>this.#t.maxOperations||i.bytes>this.#t.maxEntries*2048+this.#t.maxOperations*2)&&t("capacity_exceeded");let g=this.#e("SELECT * FROM capture_ops WHERE binding_id=? AND operation_key>=? AND operation_key<? ORDER BY operation_key").all(o,r,d);this.#e("SELECT count(*) AS records FROM entries WHERE binding_id=? AND entry_id>=? AND entry_id<?").get(o,r,d).records>this.#t.maxEntries&&t("capacity_exceeded");let a=new Set(this.#e("SELECT entry_id FROM entries WHERE binding_id=? AND entry_id>=? AND entry_id<? ORDER BY entry_id").all(o,r,d).map(m=>m.entry_id));for(let m of a)U(m);for(let m of g){if(this.#a({bindingId:m.binding_id,operationKey:m.operation_key}),J(m.intent_digest),m.state==="reserved")continue;(m.state!=="committed"||m.entry_ids===null)&&t("inventory_unknown");let l=JSON.parse(m.entry_ids);(!Array.isArray(l)||l.length>this.#t.maxEntries||l.some(b=>typeof b!="string")||new Set(l).size!==l.length)&&t("inventory_unknown");for(let b of l)U(b),a.add(b)}a.size>this.#t.maxEntries&&t("capacity_exceeded");let p=[...a],y=new Map,R=0;for(let m=0;m<p.length;m+=400){let l=p.slice(m,m+400),b=l.map(()=>"?").join(","),h=this.#e("SELECT COALESCE(SUM(length(CAST(metadata AS BLOB)) + MIN(COALESCE(length(body),0),?)),0) AS bytes FROM entries WHERE binding_id=? AND entry_id IN ("+b+")").get(s,o,...l);R+=h.bytes,(!Number.isSafeInteger(R)||R>this.#t.globalLimit.bytes)&&t("capacity_exceeded");let I=this.#e("SELECT "+te+",substr(body,1,?) AS body FROM entries WHERE binding_id=? AND entry_id IN ("+b+")").all(s,o,...l);for(let v of I)y.set(v.entry_id,v)}let k=(m,l)=>(m!==o&&t("identity_mismatch"),y.get(l)??t("entry_not_found")),S=g.map(m=>m.state==="reserved"?{state:"reserved",reservation:x(m)}:{state:"committed",reservation:x(m),receipt:this.#s(m,k)}),_=p.map(m=>{let l=y.get(m)??t("entry_not_found"),b=$(l);if(l.retained===0)return{entryId:m,witness:b,bodyState:"released",offset:0,body:null,complete:!1};(!(l.body instanceof Uint8Array)||l.body.byteLength!==Math.min(s,b.bodyBytes))&&t("inventory_unknown");let h=l.body.byteLength===b.bodyBytes;return h&&se(l.body)!==b.bodySha256&&t("inventory_unknown"),{entryId:m,witness:b,bodyState:"retained",offset:0,body:l.body,complete:h}});return this.#n.exec("ROLLBACK"),{operations:S,entries:_}}catch(i){try{this.#n.exec("ROLLBACK")}catch{try{this.#n.exec("BEGIN"),this.#n.exec("ROLLBACK")}catch{this.#p=!0}}if(i instanceof F||i instanceof ie)throw i;t("storage_failure")}finally{this.#d=!1}}observationReleaseReady(e){return this.assertObservationReadable(),this.#a({bindingId:e,operationKey:"observation"}),!this.#e("SELECT 1 FROM holds WHERE binding_id=? AND state='held' LIMIT 1").get(e)&&!this.#e("SELECT 1 FROM capture_ops WHERE binding_id=? AND state='reserved' LIMIT 1").get(e)}snapshot(){return this.#o(),this.#b().snapshot()}close(){this.#S&&t("closed"),this.#d&&t("reentrant"),this.#n.close(),this.#S=!0,this.#f.clear(),this.#c.clear(),this.#I=0,this.#u.clear(),this.#E=0,Ie(this,"closed")}};export{yn as openValidatedSqliteArchiveSpool};
29
+ //# sourceMappingURL=tansr-sqlite-spool-implementation-LHEIRSUX.mjs.map