@robota-sdk/agent-session 3.2.3 → 3.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.cjs CHANGED
@@ -1,13 +1,13 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./session-claims-CVHnnUhA.cjs");let t=require("@robota-sdk/agent-core"),n=require("@robota-sdk/agent-node-lock"),r=require("fs"),i=require("path"),a=require("@robota-sdk/agent-core/node"),o=require("node:buffer"),s=require("node:crypto"),c=require("node:fs"),l=require("node:path"),u=require("@robota-sdk/agent-file-authority");const d=`the sealed session file does not open for this session: it is damaged or sealed with other keys`,f=/^[0-9a-f]{64}$/;function p(e){return typeof e==`string`&&f.test(e)}function m(e){return(0,s.createHash)(`sha256`).update(e).digest(`hex`)}function h(e,t){return o.Buffer.from(e.buffer,e.byteOffset,e.byteLength).equals(t)}function g(e){return{kind:`session-record`,id:e}}function _(e){return o.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`)}function v(e){return JSON.stringify({schemaVersion:2,record:e},null,2)}function ee(e,t){let n=v(e),r=o.Buffer.from(n,`utf8`);return{stored:t===void 0?r:t.sealBytes(r,g(e.id)),text:n}}function te(e,n,r){if(!(0,t.isSealedArtifactBytes)(n))return`plain`;if(!(0,t.isCurrentSealedArtifactBytes)(n))return`newer-format`;let i;try{i=r.openBytes(n,g(e))}catch(e){if((0,t.isArtifactLockedError)(e))throw e;return`does-not-open`}return i.fill(0),`sealed`}function ne(e,t,n){return n.sealBytes(t,g(e))}function re(t){let n;try{n=JSON.parse(t)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let r=e.b(n);return r.status===`valid`?{status:`valid`,record:r.record}:r.status===`unsupported`?{status:`unsupported`,schemaVersion:r.schemaVersion,...r.cwd===void 0?{}:{cwd:r.cwd}}:{status:`corrupt`,issues:r.issues,...r.cwd===void 0?{}:{cwd:r.cwd}}}function y(e,t){let n=re(t);return n.status!==`valid`||n.record.id===e?n:{status:`corrupt`,issues:[{path:`id`,message:`the record belongs to another session id`}]}}function ie(e,t){return y(e,_(t)).status===`valid`}function ae(e){return e===void 0?{kind:`absent`}:(0,t.isSealedArtifactBytes)(e)?{kind:`sealed`,bytes:e}:{kind:`plain`,bytes:e}}function b(e){return e.kind===`sealed`||e.kind===`plain`?e.bytes:void 0}var oe=class{#e=new Map;#t=new Set;#n=new Set;#r;constructor(e=()=>!1){this.#r=e}get size(){return this.#t.size}state(e){return this.#e.get(e)}hold(e,t){this.#i(e).held=t,this.#t.delete(e),this.#t.add(e);for(let e of this.#t){if(this.#t.size<=32)break;this.#e.get(e)?.held?.kind===`pinned`||this.#r(e)||this.dropHeld(e)}}holdHandoff(e,t){this.#i(e).handoff=t,this.#n.delete(e),this.#n.add(e);for(let e of this.#n){if(this.#n.size<=8)break;this.dropHandoff(e)}}dropHeld(e){this.#t.delete(e),this.#a(e,e=>delete e.held)}dropHandoff(e){this.#n.delete(e),this.#a(e,e=>delete e.handoff)}taint(e){this.#i(e).tainted=!0}untaint(e){this.#a(e,e=>e.tainted=!1)}setPending(e,t){this.#i(e).pendingDigest=t}clearPending(e){this.#a(e,e=>delete e.pendingDigest)}pending(){let e=[];for(let[t,n]of this.#e)n.pendingDigest!==void 0&&e.push([t,n.pendingDigest]);return e}forget(e){this.#t.delete(e),this.#n.delete(e),this.#a(e,e=>{delete e.held,delete e.handoff,delete e.pendingDigest})}#i(e){let t=this.#e.get(e);return t===void 0&&(t={tainted:!1},this.#e.set(e,t)),t}#a(e,t){let n=this.#e.get(e);n!==void 0&&(t(n),n.held===void 0&&n.handoff===void 0&&n.pendingDigest===void 0&&!n.tainted&&this.#e.delete(e))}};const se=`rsh2.`,ce={owner:!0,unverified:!1},le=/^[A-Za-z0-9_-]+$/,ue=new TextDecoder(`utf-8`,{fatal:!0});function de(e,t,n){return`${se}${n?`owner`:`unverified`}.${e}.${o.Buffer.from(t,`utf8`).toString(`base64url`)}`}function fe(e){if(typeof e!=`string`||!e.startsWith(se))return;let[t,n,r,...i]=e.slice(5).split(`.`);if(t!==`owner`&&t!==`unverified`||i.length>0||n===void 0||r===void 0||!p(n)||!le.test(r))return;let a=o.Buffer.from(r,`base64url`);if(a.toString(`base64url`)===r)try{return{digest:n,text:ue.decode(a),owner:ce[t]}}catch{return}}const pe=`robota-authorship/v1 `,x=o.Buffer.from(pe,`ascii`),me=/^[A-Za-z0-9_-]+$/;function he(e,t){let n=o.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64url`);return o.Buffer.concat([o.Buffer.from(`${pe}${n}\n`,`ascii`),t])}function ge(e){let t=o.Buffer.from(e.buffer,e.byteOffset,e.byteLength);if(t.length<x.length||!t.subarray(0,x.length).equals(x))return{envelope:e,tag:void 0};let n=t.indexOf(10,x.length);if(n<0)return{envelope:e,tag:`malformed`};let r=t.subarray(x.length,n).toString(`latin1`),i=e.subarray(n+1);if(!me.test(r))return{envelope:i,tag:`malformed`};let a=o.Buffer.from(r,`base64url`);return a.length!==32||a.toString(`base64url`)!==r?{envelope:i,tag:`malformed`}:{envelope:i,tag:a}}const S={probe:{writer:!1,takes:!1,holds:!1,taints:!0},hold:{writer:!0,takes:!0,holds:!0,taints:!0},list:{writer:!1,takes:!1,holds:!1,taints:!1},held:{writer:!0,takes:!0,holds:!1,taints:!0},export:{writer:!0,takes:!1,holds:!1,taints:!0},claim:{writer:!0,takes:!0,holds:!0,taints:!0},save:{writer:!0,takes:!1,holds:!1,taints:!1}},C=Object.freeze({status:`locked`,reason:`no-keys`}),w=Object.freeze({status:`locked`,reason:`changed`}),T=Object.freeze({status:`locked`}),_e=Object.freeze({status:`missing`});function E(e,t,n,r){return{status:`valid`,record:e.record,authorship:t?`verified`:`unverified`,...n===void 0?{}:{digest:n},...r?{diverged:!0}:{}}}function D(e,n,r){let i;try{i=e.openBytes(r,g(n))}catch(e){return(0,t.isArtifactLockedError)(e)?e.reason===`no-keys`?{kind:`no-keys`}:{kind:`locked`}:{kind:`does-not-open`}}try{let{envelope:t,tag:r}=ge(i),a=!1;if(r instanceof Uint8Array&&e.verifyAuthorship!==void 0)try{a=e.verifyAuthorship(t,r,g(n))===!0}catch{a=!1}return{kind:`text`,text:_(t),verified:a}}finally{i.fill(0)}}function ve(e,n,r){let i,a=!1;if(!(0,t.isSealedArtifactBytes)(n))i=_(n);else{if(!(0,t.isCurrentSealedArtifactBytes)(n))return{status:`unsupported`,schemaVersion:void 0};let o=D(r,e,n);if(o.kind===`locked`)return T;if(o.kind===`no-keys`)return C;if(o.kind===`does-not-open`)return{status:`corrupt`,issues:[{path:``,message:d}]};i=o.text,a=o.verified}let o=y(e,i);return o.status===`valid`?E(o,a,m(n),!1):o}var ye=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n,r,i){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,e.tagAuthorship!==void 0&&e.onUnlock!==void 0&&(this.#a=()=>this.#g(),e.onUnlock(this.#a))}read(e,t,n,r,i){let a=this.guarded(e,t,i);if(a!==void 0)return a;if(t.kind===`absent`){let t=r();return t.status===`valid`?this.#l(e,t,`unverified`,void 0,i,!1):t}let o=b(t);return o===void 0?n:this.decode(e,o,i)}decode(e,n,r){let i,a=!1;if(!(0,t.isSealedArtifactBytes)(n))i=_(n);else{if(!(0,t.isCurrentSealedArtifactBytes)(n))return{status:`unsupported`,schemaVersion:void 0};let r=D(this.#e,e,n);if(r.kind===`locked`)return T;if(r.kind===`no-keys`)return C;if(r.kind===`does-not-open`)return{status:`corrupt`,issues:[{path:``,message:d}]};i=r.text,a=r.verified}let o=y(e,i);if(o.status!==`valid`)return o;let s=m(n),c=this.#n.state(e),l=a||this.#s(c,c?.held,s)?`owner`:`unverified`;return S[r].holds&&this.#n.hold(e,{digest:s,text:i,kind:l}),this.#l(e,o,l,s,r,!1)}claimRead(e,t,n,r,i){let a=this.#n.state(e)?.held,o=b(n);return!t&&a!==void 0&&o!==void 0&&m(o)===a.digest?this.#c(e,a,`claim`,!1):this.read(e,n,r,i,`claim`)}beforeClaim(e,t,n){if(this.#n.state(e)?.held?.kind===`pinned`&&!n)throw this.#r.refusal(e,`has_writer`);t&&(this.#n.dropHeld(e),this.#n.dropHandoff(e))}guarded(e,n,r){let i=this.#n.state(e),a=this.#o(e,i),o=a?void 0:i?.handoff;if(!a&&o===void 0)return;let s=S[r],c=b(n),l=c===void 0?void 0:m(c);if(o!==void 0)return s.takes&&this.#n.dropHandoff(e),c===void 0||l!==o.digest?w:(s.takes&&this.#n.hold(e,o),this.#c(e,o,r,!1));let u=i?.held;if(u!==void 0&&l===u.digest)return this.#c(e,u,r,!1);let d=!1;if(u?.kind!==`pinned`&&n.kind===`sealed`&&(0,t.isCurrentSealedArtifactBytes)(n.bytes)){let t=D(this.#e,e,n.bytes);if(t.kind===`text`&&t.verified&&l!==void 0){let n=y(e,t.text);if(n.status===`valid`)return r!==`save`&&this.#n.hold(e,{digest:l,text:t.text,kind:`owner`}),E(n,!0,l,!1)}d=t.kind===`locked`}return n.kind===`absent`?u===void 0?_e:this.#c(e,u,r,!0):s.writer||u===void 0?d?T:w:this.#c(e,u,r,!0)}assertReplaceable(n,r){let i=this.guarded(n,r,`save`);if(i!==void 0){if(i.status!==`locked`)return;throw new e.a(n,i.reason===`changed`?`changed`:`locked`)}switch(r.kind){case`absent`:case`plain`:return;case`unreadable`:case`oversized`:throw new e.a(n,`unreadable`);case`sealed`:break}let a=r.bytes;if(!(0,t.isCurrentSealedArtifactBytes)(a))throw new e.a(n,`newer-format`);let o=this.#n.state(n)?.held;if(o!==void 0&&o.digest===m(a))return;let s=D(this.#e,n,a);if(s.kind!==`text`)throw new e.a(n,o===void 0?s.kind===`locked`||s.kind===`no-keys`?s.kind:`does-not-open`:`changed`)}prepare(e,t,n){let r=o.Buffer.from(t,`utf8`),i=this.#d(e,n),a=r,s=!1;if(i===`owner`){let t=this.#f(e,r);t===`locked`?s=n.handoff!==!0:t!==void 0&&(a=he(t,r))}try{return{stored:this.#e.sealBytes(a,g(e)),text:t,heldAs:i,tagPending:s}}finally{a!==r&&a.fill(0)}}wrote(e,t,n){let r=this.#n.state(e)?.held,i=t.heldAs===`pinned`&&r?.kind===`pinned`&&r.vouched,a={digest:m(t.stored),text:t.text,kind:t.heldAs,...i===!0?{vouched:i}:{}};n&&!this.#r.has(e)&&t.heldAs!==`pinned`?(this.#n.dropHeld(e),this.#n.holdHandoff(e,a)):(this.#n.dropHandoff(e),this.#n.hold(e,a)),t.tagPending?this.#n.setPending(e,a.digest):this.#n.clearPending(e)}wroteIfPresent(e,t,n,r){n.kind===`sealed`&&h(n.bytes,t.stored)&&this.wrote(e,t,r)}held(e,t){let n=this.guarded(e,t,`held`);if(n!==void 0)return n;let r=this.#n.state(e)?.held;if(r===void 0)return;let i=b(t);return i===void 0||m(i)!==r.digest?w:this.#c(e,r,`held`,!1)}exportHeld(e,n,r){if(n.kind!==`sealed`||!(0,t.isCurrentSealedArtifactBytes)(n.bytes))return;let i=m(n.bytes),a=(e,t)=>de(i,e,t===`owner`),o=this.#n.state(e);if(this.#o(e,o)){if(r.handoffOnly===!0)return;let t=this.guarded(e,n,`export`),o=this.#n.state(e)?.held;return t?.status!==`valid`||t.diverged===!0||o?.digest!==i?void 0:a(o.text,t.authorship===`verified`?`owner`:`unverified`)}let s=o?.handoff;if(s!==void 0)return r.keep!==!0&&this.#n.dropHandoff(e),s.digest===i?(this.#u(e,s.kind,`export`),a(s.text,s.kind)):void 0;if(r.handoffOnly===!0)return;let c=D(this.#e,e,n.bytes);if(c.kind!==`text`||y(e,c.text).status!==`valid`)return;let l=c.verified||this.#s(o,o?.held,i)?`owner`:`unverified`;return this.#u(e,l,`export`),a(c.text,l)}importHeld(e,t){let n=fe(t);if(n===void 0)throw TypeError(`The held record is not a token this build issues.`);if(y(e,n.text).status!==`valid`)throw TypeError(`The held record is not a valid record of this session.`);this.#r.assertUnclaimed(e),this.#n.dropHandoff(e),this.#n.hold(e,{digest:n.digest,text:n.text,kind:`pinned`,...n.owner?{vouched:!0}:{}})}adopt(e,t){if(!p(t))return`changed`;let n=this.#n.state(e),r=this.#t.current(e),i=b(r),a=i===void 0?void 0:m(i),o=n?.held;if(o!==void 0&&o.digest===t&&o.kind!==`pinned`)return this.#n.hold(e,{...o,kind:`owner`}),this.#n.untaint(e),a===t&&this.#m(e,t,o.text,!0)===`pending`?`pending`:`adopted`;if(i===void 0||a!==t||this.#e.tagAuthorship===void 0)return`changed`;let s=this.#p(e,r,i);if(s===`locked`)return this.#n.untaint(e),this.#n.setPending(e,t),`pending`;if(s===void 0||y(e,s).status!==`valid`)return`changed`;let c=this.#m(e,t,s,!1);return c!==`changed`&&this.#n.untaint(e),c}heldDigest(e){return this.#n.state(e)?.held?.digest}forget(e){this.#n.forget(e)}discardHeld(e){this.#n.dropHeld(e)}onUnlock(e){return this.#e.onUnlock?.(e)??(()=>void 0)}#o(e,t){return this.#r.has(e)||t?.held?.kind===`pinned`}#s(e,t,n){return e?.pendingDigest===n||t?.kind===`owner`&&t.digest===n}#c(e,t,n,r){let i=y(e,t.text);if(i.status!==`valid`)return i;if(t.kind===`pinned`)return E(i,t.vouched===!0,t.digest,r);let a=this.#s(this.#n.state(e),t,t.digest)?`owner`:`unverified`;return this.#l(e,i,a,t.digest,n,r)}#l(e,t,n,r,i,a){return this.#u(e,n,i),E(t,n===`owner`,r,a)}#u(e,t,n){t!==`owner`&&S[n].taints&&!this.#o(e,this.#n.state(e))&&this.#n.taint(e)}#d(e,t){let n=this.#n.state(e),r=n?.held??n?.handoff;return r?.kind===`pinned`?`pinned`:t.provenance===`unverified`||!this.#r.has(e)&&n?.tainted===!0?`unverified`:r===void 0?t.provenance===`owner`?`owner`:`unverified`:r.kind}#f(e,n){if(this.#e.tagAuthorship!==void 0)try{return this.#e.tagAuthorship(n,g(e))}catch(e){if((0,t.isArtifactLockedError)(e))return`locked`;throw e}}#p(e,n,r){if(n.kind!==`sealed`)return _(r);if(!(0,t.isCurrentSealedArtifactBytes)(r))return;let i=D(this.#e,e,r);return i.kind===`locked`?`locked`:i.kind===`text`?i.text:void 0}#m(e,t,n,r){let i=o.Buffer.from(n,`utf8`),a=this.#f(e,i);return a===`locked`?(this.#n.setPending(e,t),`pending`):a===void 0||this.#h(e,i,n,a,t,r)?`adopted`:`changed`}#h(e,t,n,r,i,a){let o=he(r,t),s;try{s=this.#e.sealBytes(o,g(e))}finally{o.fill(0)}let c=b(this.#t.current(e));if(c===void 0||m(c)!==i)return!1;let l={stored:s,text:n,heldAs:`owner`,tagPending:!1};try{this.#t.replace(e,s)}catch(t){throw a&&this.wroteIfPresent(e,l,this.#t.current(e),!1),t}return this.#n.clearPending(e),a&&this.wrote(e,l,!1),!0}#g(){for(let[e,t]of this.#n.pending()){this.#n.clearPending(e);try{this.#i(e,()=>this.#_(e,t))}catch{}}}#_(e,t){let n=this.#t.current(e),r=b(n);if(r===void 0||m(r)!==t)return;let i=this.#n.state(e)?.held,a=i?.digest===t,s=a?i.text:this.#p(e,n,r);if(s===void 0||s===`locked`||y(e,s).status!==`valid`)return;let c=o.Buffer.from(s,`utf8`),l=this.#f(e,c);l instanceof Uint8Array&&this.#h(e,c,s,l,t,a)}};function be(e){let t=e;if(typeof t?.acquire!=`function`||typeof t.takeOver!=`function`||typeof t.endLease!=`function`||typeof t.inspect!=`function`)throw TypeError(`A session store holds a writer marker for every id it writes: build it with the markers of its claims directory.`)}function O(e){if(typeof e!=`object`||!e)throw TypeError(`Session store options must be an object, such as { sealing }.`);return k(e.sealing),e.sealing}function k(e){if(e===`plain`)return;let t=typeof e==`object`&&e?e.sealer:void 0;if(!(typeof t==`object`&&t&&typeof t.sealBytes==`function`&&typeof t.openBytes==`function`))throw TypeError(`A session store states how it seals: { sealer }, or 'plain'.`)}var xe=class{#e;#t;#n;#r;#i;authorship;constructor(t,n,r,i={}){if(k(t),be(r),this.#e=t===`plain`?void 0:t.sealer,this.#t=n,this.#n=r,this.#r=new e.n(i.releaseCommand===void 0?{}:{releaseCommand:i.releaseCommand},{pid:process.pid,windows:process.platform===`win32`}),this.#e===void 0){this.#i=void 0,this.authorship=void 0;return}let a=new ye(this.#e,n,new oe(e=>this.#r.has(e)),this.#r,(e,t)=>this.#l(e,t));this.#i=a,this.authorship=Object.freeze({adopt:(t,n)=>{e.m(t);let r=this.#l(t,()=>a.adopt(t,n));return r===`has_writer`?`has_writer`:r},heldDigest:t=>(e.m(t),a.heldDigest(t)),onUnlock:e=>a.onUnlock(e)})}get seals(){return this.#e!==void 0}load(e,t={}){return this.#u(e,t.hold===!0?`hold`:`probe`)}listed(e){return this.#u(e,`list`)}claim(e,t={}){this.#r.assertUnclaimed(e);let n=t.fresh===!0;this.#i?.beforeClaim(e,n,t.lease!==void 0);let r=t.copy===!0?void 0:this.#o(e,t.lease),i=()=>this.#r.open(e,n,r,()=>{let{file:t,unreadable:r}=this.#t.load(e);return this.#i===void 0?this.#d(e,t,r):this.#i.claimRead(e,n,t,r,()=>this.#p(e))},()=>this.#i?.discardHeld(e));if(r===void 0)return i();try{return this.#c(e,r,i)}catch(e){throw r.release(),e}}lend(t){this.#r.assertUnclaimed(t);let n=(0,s.randomBytes)(32).toString(`hex`),r=(0,s.createHash)(`sha256`).update(n,`utf8`).digest(`hex`),i=this.#n.acquire(t,{leaseDigest:r});if(i.status!==`acquired`)throw this.#r.refusal(t,`has_writer`,{holder:e.i(i.holder)});let a=this.#r.lend(t,()=>{let e=this.#n.inspect(t);return e.status===`held`?e.holder:void 0}),o=!1;return Object.freeze({nonce:n,end:()=>{if(!o){o=!0;try{this.#n.endLease(t,r)}finally{a()}}}})}hasWriter(e){if(this.#r.has(e)||this.#r.isLent(e))return!0;let t=this.#n.inspect(e);return t.status===`held`&&t.holder.liveness!==`gone`}save(e,t={}){let n=e.id,r=this.#r.markerForSave(n,t.claim);if(r!==void 0){this.#c(n,r,()=>this.#a(e,t));return}this.#s(n,()=>this.#a(e,t))}delete(e,t){this.#r.markerForSave(e,void 0),this.#s(e,()=>{this.forget(e),t()})}#a(e,t){let n=e.id,r=this.#t.current(n),i=this.#i;if(i===void 0){this.#f(n,r),this.#t.replace(n,ee(e,void 0).stored);return}i.assertReplaceable(n,r);let a=i.prepare(n,v(e),t),o=t.handoff===!0;try{this.#t.replace(n,a.stored)}catch(e){throw i.wroteIfPresent(n,a,this.#m(n),o),e}i.wrote(n,a,o)}loadHeld(e){return this.#i?.held(e,this.#t.current(e))}exportHeld(e,t={}){return this.#i?.exportHeld(e,this.#t.current(e),t)}importHeld(e,t){if(this.#i===void 0)throw TypeError(`A store that seals nothing does not take a held record: it would write it in plaintext.`);this.#i.importHeld(e,t)}forget(e){this.#i?.forget(e)}#o(t,n){if(n===void 0){let n=this.#n.acquire(t);if(n.status===`acquired`)return n.handle;throw this.#r.refusal(t,`has_writer`,{holder:e.i(n.holder)})}let r=this.#n.takeOver(t,n);if(r.status===`acquired`)return r.handle;throw r.status===`absent`?this.#r.refusal(t,`released`,{lease:!0}):this.#r.refusal(t,`has_writer`,{holder:e.i(r.holder)})}#s(t,n){let r=this.#n.acquire(t);if(r.status!==`acquired`)throw this.#r.refusal(t,`has_writer`,{holder:e.i(r.holder)});try{return this.#c(t,r.handle,n)}finally{r.handle.release()}}#c(e,t,n){let r=t.withGuard(n);if(r.status===`ran`)return r.value;throw this.#r.refusal(e,r.status===`lost`?`released`:`has_writer`)}#l(t,n){try{let e=this.#r.markerForWrite(t);if(e!==void 0)return this.#c(t,e,n)}catch(t){if(e.r(t))return`has_writer`;throw t}let r=this.#n.acquire(t);if(r.status!==`acquired`)return`has_writer`;try{return this.#c(t,r.handle,n)}catch(t){if(e.r(t))return`has_writer`;throw t}finally{r.handle.release()}}#u(e,t){let{file:n,unreadable:r}=this.#t.load(e);return this.#i===void 0?this.#d(e,n,r):this.#i.read(e,n,r,()=>this.#p(e),t)}#d(e,n,r){if(n.kind===`absent`)return this.#p(e);let i=b(n);return i===void 0?r:(0,t.isSealedArtifactBytes)(i)?(0,t.isCurrentSealedArtifactBytes)(i)?C:{status:`unsupported`,schemaVersion:void 0}:y(e,_(i))}#f(n,r){switch(r.kind){case`absent`:case`plain`:case`oversized`:return;case`unreadable`:throw new e.a(n,`unreadable`);case`sealed`:throw new e.a(n,(0,t.isCurrentSealedArtifactBytes)(r.bytes)?`no-keys`:`newer-format`)}}#p(e){return this.#t.rebuild?.(e)??_e}#m(e){try{return this.#t.current(e)}catch{return{kind:`unreadable`}}}};function A(e){return typeof e==`object`&&e?e.code:void 0}function Se(e){let t=A(e);return typeof t==`string`&&/^E[A-Z0-9]+$/.test(t)?`could not read the session file (${t})`:`could not read the session file`}function Ce(e,t){let n=Buffer.alloc(Math.max((0,r.fstatSync)(e).size,t.length));t.copy(n,0);let i=t.length;for(;i<n.length;){let t=(0,r.readSync)(e,n,i,n.length-i,i);if(t===0)break;i+=t}return n.subarray(0,i)}const we=Object.freeze({status:`missing`}),j=`claims`;function Te(e){let t=0,n=0;for(let{outcome:r}of e)r.status===`locked`&&(r.reason===`no-keys`?n+=1:t+=1);return n===0?{locked:t}:{locked:t,noKeys:n}}function Ee(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var De=class{supportsClaimDiscard=!0;baseDir;ownedRoot;records;constructor(e,t){let r=O(t);this.records=new xe(r,{load:e=>this.loadFile(e),current:e=>this.readExisting(this.filePath(e)),replace:(e,t)=>{this.ensureDir(),(0,a.writeOwnerOnlyFile)(this.filePath(e),t)}},(0,a.createProcessMarkers)((0,i.join)((0,i.resolve)(e),j),{operationLock:(0,n.createProcessOperationLock)((0,i.join)((0,i.resolve)(e),j))}),t.releaseCommand===void 0?{}:{releaseCommand:t.releaseCommand}),this.baseDir=e,this.ownedRoot=t.ownedRoot;let o=this.records.authorship;o!==void 0&&(this.authorship=o)}claim(e,t){return this.filePath(e),this.records.claim(e,t)}lend(e){return this.filePath(e),this.records.lend(e)}hasWriter(e){return this.filePath(e),this.records.hasWriter(e)}ensureDir(){(0,a.ensureOwnerOnlyDirectory)(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(t){e.m(t);let n=(0,i.resolve)(this.baseDir),r=(0,i.resolve)(n,`${t}.json`);if(!r.startsWith(n+i.sep))throw Error(`Invalid session id: ${JSON.stringify(t)} resolves outside the session store.`);return r}save(e,t={}){this.ensureDir(),this.filePath(e.id),this.records.save(e,t)}saveRestoreTransaction(e,t){if(!t?.claim)throw TypeError(`A live session claim is required for restore commit.`);try{return this.save(e,t),{status:`committed`}}catch(e){return{status:`unknown`,error:e}}}readExisting(e){let n;try{n=(0,r.openSync)(e,`r`)}catch(e){return A(e)===`ENOENT`?{kind:`absent`}:{kind:`unreadable`}}try{let e=Buffer.alloc(t.SEALED_ARTIFACT_MAGIC.length),i=(0,r.readSync)(n,e,0,e.length,0);return(0,t.isSealedArtifactBytes)(e.subarray(0,i))?{kind:`sealed`,bytes:Ce(n,e)}:this.records.seals?{kind:`plain`,bytes:Ce(n,e.subarray(0,i))}:{kind:`plain`}}catch{return{kind:`unreadable`}}finally{(0,r.closeSync)(n)}}load(e,t={}){return this.filePath(e),this.records.load(e,t)}loadFile(e){let t=this.filePath(e),n;try{n=(0,r.readFileSync)(t)}catch(e){return A(e)===`ENOENT`?{file:{kind:`absent`},unreadable:we}:{file:{kind:`unreadable`},unreadable:{status:`corrupt`,issues:[{path:``,message:Se(e)}]}}}try{(0,a.tightenExistingFile)(t)}catch{}return{file:ae(n),unreadable:we}}loadHeld(e){return this.filePath(e),this.records.loadHeld(e)}exportHeld(e,t){return this.filePath(e),this.records.exportHeld(e,t)}importHeld(e,t){this.filePath(e),this.records.importHeld(e,t)}list(){return this.scan().entries}scan(){let e=this.readAll();return{entries:e.filter(e=>e.outcome.status!==`locked`).sort(Ee),...Te(e)}}readAll(){return(0,r.existsSync)(this.baseDir)?(0,r.readdirSync)(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})):[]}outcomeForListedId(t){return e.g(t)?this.records.listed(t):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){let t=this.filePath(e);this.records.delete(e,()=>{(0,r.existsSync)(t)&&(0,r.unlinkSync)(t)})}};const Oe=Object.freeze({kind:`does-not-open`}),ke=Object.freeze({kind:`newer-format`}),Ae=Object.freeze({kind:`locked`,reason:`no-keys`}),je=/^R(?:S(?:L[0-9]?)?)?$/;function Me(e){return k(e),e===`plain`?void 0:e.sealer}function Ne(e){return e.reason===`no-keys`?`no-keys`:`locked`}var M=class{#e;#t;constructor(e,t){this.#e=Me(e),this.#t=t}encode(e,t){return this.#e===void 0?e:`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./session-claims-CVHnnUhA.cjs");let t=require("@robota-sdk/agent-core"),n=require("@robota-sdk/agent-os/node-lock"),r=require("fs"),i=require("path"),a=require("@robota-sdk/agent-core/node"),o=require("node:buffer"),s=require("node:crypto"),c=require("node:fs"),l=require("node:path"),u=require("@robota-sdk/agent-os/file-authority");const d=`the sealed session file does not open for this session: it is damaged or sealed with other keys`,f=/^[0-9a-f]{64}$/;function p(e){return typeof e==`string`&&f.test(e)}function m(e){return(0,s.createHash)(`sha256`).update(e).digest(`hex`)}function h(e,t){return o.Buffer.from(e.buffer,e.byteOffset,e.byteLength).equals(t)}function g(e){return{kind:`session-record`,id:e}}function _(e){return o.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`)}function v(e){return JSON.stringify({schemaVersion:2,record:e},null,2)}function ee(e,t){let n=v(e),r=o.Buffer.from(n,`utf8`);return{stored:t===void 0?r:t.sealBytes(r,g(e.id)),text:n}}function te(e,n,r){if(!(0,t.isSealedArtifactBytes)(n))return`plain`;if(!(0,t.isCurrentSealedArtifactBytes)(n))return`newer-format`;let i;try{i=r.openBytes(n,g(e))}catch(e){if((0,t.isArtifactLockedError)(e))throw e;return`does-not-open`}return i.fill(0),`sealed`}function ne(e,t,n){return n.sealBytes(t,g(e))}function re(t){let n;try{n=JSON.parse(t)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let r=e.b(n);return r.status===`valid`?{status:`valid`,record:r.record}:r.status===`unsupported`?{status:`unsupported`,schemaVersion:r.schemaVersion,...r.cwd===void 0?{}:{cwd:r.cwd}}:{status:`corrupt`,issues:r.issues,...r.cwd===void 0?{}:{cwd:r.cwd}}}function y(e,t){let n=re(t);return n.status!==`valid`||n.record.id===e?n:{status:`corrupt`,issues:[{path:`id`,message:`the record belongs to another session id`}]}}function ie(e,t){return y(e,_(t)).status===`valid`}function ae(e){return e===void 0?{kind:`absent`}:(0,t.isSealedArtifactBytes)(e)?{kind:`sealed`,bytes:e}:{kind:`plain`,bytes:e}}function b(e){return e.kind===`sealed`||e.kind===`plain`?e.bytes:void 0}var oe=class{#e=new Map;#t=new Set;#n=new Set;#r;constructor(e=()=>!1){this.#r=e}get size(){return this.#t.size}state(e){return this.#e.get(e)}hold(e,t){this.#i(e).held=t,this.#t.delete(e),this.#t.add(e);for(let e of this.#t){if(this.#t.size<=32)break;this.#e.get(e)?.held?.kind===`pinned`||this.#r(e)||this.dropHeld(e)}}holdHandoff(e,t){this.#i(e).handoff=t,this.#n.delete(e),this.#n.add(e);for(let e of this.#n){if(this.#n.size<=8)break;this.dropHandoff(e)}}dropHeld(e){this.#t.delete(e),this.#a(e,e=>delete e.held)}dropHandoff(e){this.#n.delete(e),this.#a(e,e=>delete e.handoff)}taint(e){this.#i(e).tainted=!0}untaint(e){this.#a(e,e=>e.tainted=!1)}setPending(e,t){this.#i(e).pendingDigest=t}clearPending(e){this.#a(e,e=>delete e.pendingDigest)}pending(){let e=[];for(let[t,n]of this.#e)n.pendingDigest!==void 0&&e.push([t,n.pendingDigest]);return e}forget(e){this.#t.delete(e),this.#n.delete(e),this.#a(e,e=>{delete e.held,delete e.handoff,delete e.pendingDigest})}#i(e){let t=this.#e.get(e);return t===void 0&&(t={tainted:!1},this.#e.set(e,t)),t}#a(e,t){let n=this.#e.get(e);n!==void 0&&(t(n),n.held===void 0&&n.handoff===void 0&&n.pendingDigest===void 0&&!n.tainted&&this.#e.delete(e))}};const se=`rsh2.`,ce={owner:!0,unverified:!1},le=/^[A-Za-z0-9_-]+$/,ue=new TextDecoder(`utf-8`,{fatal:!0});function de(e,t,n){return`${se}${n?`owner`:`unverified`}.${e}.${o.Buffer.from(t,`utf8`).toString(`base64url`)}`}function fe(e){if(typeof e!=`string`||!e.startsWith(se))return;let[t,n,r,...i]=e.slice(5).split(`.`);if(t!==`owner`&&t!==`unverified`||i.length>0||n===void 0||r===void 0||!p(n)||!le.test(r))return;let a=o.Buffer.from(r,`base64url`);if(a.toString(`base64url`)===r)try{return{digest:n,text:ue.decode(a),owner:ce[t]}}catch{return}}const pe=`robota-authorship/v1 `,x=o.Buffer.from(pe,`ascii`),me=/^[A-Za-z0-9_-]+$/;function he(e,t){let n=o.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64url`);return o.Buffer.concat([o.Buffer.from(`${pe}${n}\n`,`ascii`),t])}function ge(e){let t=o.Buffer.from(e.buffer,e.byteOffset,e.byteLength);if(t.length<x.length||!t.subarray(0,x.length).equals(x))return{envelope:e,tag:void 0};let n=t.indexOf(10,x.length);if(n<0)return{envelope:e,tag:`malformed`};let r=t.subarray(x.length,n).toString(`latin1`),i=e.subarray(n+1);if(!me.test(r))return{envelope:i,tag:`malformed`};let a=o.Buffer.from(r,`base64url`);return a.length!==32||a.toString(`base64url`)!==r?{envelope:i,tag:`malformed`}:{envelope:i,tag:a}}const S={probe:{writer:!1,takes:!1,holds:!1,taints:!0},hold:{writer:!0,takes:!0,holds:!0,taints:!0},list:{writer:!1,takes:!1,holds:!1,taints:!1},held:{writer:!0,takes:!0,holds:!1,taints:!0},export:{writer:!0,takes:!1,holds:!1,taints:!0},claim:{writer:!0,takes:!0,holds:!0,taints:!0},save:{writer:!0,takes:!1,holds:!1,taints:!1}},C=Object.freeze({status:`locked`,reason:`no-keys`}),w=Object.freeze({status:`locked`,reason:`changed`}),T=Object.freeze({status:`locked`}),_e=Object.freeze({status:`missing`});function E(e,t,n,r){return{status:`valid`,record:e.record,authorship:t?`verified`:`unverified`,...n===void 0?{}:{digest:n},...r?{diverged:!0}:{}}}function D(e,n,r){let i;try{i=e.openBytes(r,g(n))}catch(e){return(0,t.isArtifactLockedError)(e)?e.reason===`no-keys`?{kind:`no-keys`}:{kind:`locked`}:{kind:`does-not-open`}}try{let{envelope:t,tag:r}=ge(i),a=!1;if(r instanceof Uint8Array&&e.verifyAuthorship!==void 0)try{a=e.verifyAuthorship(t,r,g(n))===!0}catch{a=!1}return{kind:`text`,text:_(t),verified:a}}finally{i.fill(0)}}function ve(e,n,r){let i,a=!1;if(!(0,t.isSealedArtifactBytes)(n))i=_(n);else{if(!(0,t.isCurrentSealedArtifactBytes)(n))return{status:`unsupported`,schemaVersion:void 0};let o=D(r,e,n);if(o.kind===`locked`)return T;if(o.kind===`no-keys`)return C;if(o.kind===`does-not-open`)return{status:`corrupt`,issues:[{path:``,message:d}]};i=o.text,a=o.verified}let o=y(e,i);return o.status===`valid`?E(o,a,m(n),!1):o}var ye=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n,r,i){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,e.tagAuthorship!==void 0&&e.onUnlock!==void 0&&(this.#a=()=>this.#g(),e.onUnlock(this.#a))}read(e,t,n,r,i){let a=this.guarded(e,t,i);if(a!==void 0)return a;if(t.kind===`absent`){let t=r();return t.status===`valid`?this.#l(e,t,`unverified`,void 0,i,!1):t}let o=b(t);return o===void 0?n:this.decode(e,o,i)}decode(e,n,r){let i,a=!1;if(!(0,t.isSealedArtifactBytes)(n))i=_(n);else{if(!(0,t.isCurrentSealedArtifactBytes)(n))return{status:`unsupported`,schemaVersion:void 0};let r=D(this.#e,e,n);if(r.kind===`locked`)return T;if(r.kind===`no-keys`)return C;if(r.kind===`does-not-open`)return{status:`corrupt`,issues:[{path:``,message:d}]};i=r.text,a=r.verified}let o=y(e,i);if(o.status!==`valid`)return o;let s=m(n),c=this.#n.state(e),l=a||this.#s(c,c?.held,s)?`owner`:`unverified`;return S[r].holds&&this.#n.hold(e,{digest:s,text:i,kind:l}),this.#l(e,o,l,s,r,!1)}claimRead(e,t,n,r,i){let a=this.#n.state(e)?.held,o=b(n);return!t&&a!==void 0&&o!==void 0&&m(o)===a.digest?this.#c(e,a,`claim`,!1):this.read(e,n,r,i,`claim`)}beforeClaim(e,t,n){if(this.#n.state(e)?.held?.kind===`pinned`&&!n)throw this.#r.refusal(e,`has_writer`);t&&(this.#n.dropHeld(e),this.#n.dropHandoff(e))}guarded(e,n,r){let i=this.#n.state(e),a=this.#o(e,i),o=a?void 0:i?.handoff;if(!a&&o===void 0)return;let s=S[r],c=b(n),l=c===void 0?void 0:m(c);if(o!==void 0)return s.takes&&this.#n.dropHandoff(e),c===void 0||l!==o.digest?w:(s.takes&&this.#n.hold(e,o),this.#c(e,o,r,!1));let u=i?.held;if(u!==void 0&&l===u.digest)return this.#c(e,u,r,!1);let d=!1;if(u?.kind!==`pinned`&&n.kind===`sealed`&&(0,t.isCurrentSealedArtifactBytes)(n.bytes)){let t=D(this.#e,e,n.bytes);if(t.kind===`text`&&t.verified&&l!==void 0){let n=y(e,t.text);if(n.status===`valid`)return r!==`save`&&this.#n.hold(e,{digest:l,text:t.text,kind:`owner`}),E(n,!0,l,!1)}d=t.kind===`locked`}return n.kind===`absent`?u===void 0?_e:this.#c(e,u,r,!0):s.writer||u===void 0?d?T:w:this.#c(e,u,r,!0)}assertReplaceable(n,r){let i=this.guarded(n,r,`save`);if(i!==void 0){if(i.status!==`locked`)return;throw new e.a(n,i.reason===`changed`?`changed`:`locked`)}switch(r.kind){case`absent`:case`plain`:return;case`unreadable`:case`oversized`:throw new e.a(n,`unreadable`);case`sealed`:break}let a=r.bytes;if(!(0,t.isCurrentSealedArtifactBytes)(a))throw new e.a(n,`newer-format`);let o=this.#n.state(n)?.held;if(o!==void 0&&o.digest===m(a))return;let s=D(this.#e,n,a);if(s.kind!==`text`)throw new e.a(n,o===void 0?s.kind===`locked`||s.kind===`no-keys`?s.kind:`does-not-open`:`changed`)}prepare(e,t,n){let r=o.Buffer.from(t,`utf8`),i=this.#d(e,n),a=r,s=!1;if(i===`owner`){let t=this.#f(e,r);t===`locked`?s=n.handoff!==!0:t!==void 0&&(a=he(t,r))}try{return{stored:this.#e.sealBytes(a,g(e)),text:t,heldAs:i,tagPending:s}}finally{a!==r&&a.fill(0)}}wrote(e,t,n){let r=this.#n.state(e)?.held,i=t.heldAs===`pinned`&&r?.kind===`pinned`&&r.vouched,a={digest:m(t.stored),text:t.text,kind:t.heldAs,...i===!0?{vouched:i}:{}};n&&!this.#r.has(e)&&t.heldAs!==`pinned`?(this.#n.dropHeld(e),this.#n.holdHandoff(e,a)):(this.#n.dropHandoff(e),this.#n.hold(e,a)),t.tagPending?this.#n.setPending(e,a.digest):this.#n.clearPending(e)}wroteIfPresent(e,t,n,r){n.kind===`sealed`&&h(n.bytes,t.stored)&&this.wrote(e,t,r)}held(e,t){let n=this.guarded(e,t,`held`);if(n!==void 0)return n;let r=this.#n.state(e)?.held;if(r===void 0)return;let i=b(t);return i===void 0||m(i)!==r.digest?w:this.#c(e,r,`held`,!1)}exportHeld(e,n,r){if(n.kind!==`sealed`||!(0,t.isCurrentSealedArtifactBytes)(n.bytes))return;let i=m(n.bytes),a=(e,t)=>de(i,e,t===`owner`),o=this.#n.state(e);if(this.#o(e,o)){if(r.handoffOnly===!0)return;let t=this.guarded(e,n,`export`),o=this.#n.state(e)?.held;return t?.status!==`valid`||t.diverged===!0||o?.digest!==i?void 0:a(o.text,t.authorship===`verified`?`owner`:`unverified`)}let s=o?.handoff;if(s!==void 0)return r.keep!==!0&&this.#n.dropHandoff(e),s.digest===i?(this.#u(e,s.kind,`export`),a(s.text,s.kind)):void 0;if(r.handoffOnly===!0)return;let c=D(this.#e,e,n.bytes);if(c.kind!==`text`||y(e,c.text).status!==`valid`)return;let l=c.verified||this.#s(o,o?.held,i)?`owner`:`unverified`;return this.#u(e,l,`export`),a(c.text,l)}importHeld(e,t){let n=fe(t);if(n===void 0)throw TypeError(`The held record is not a token this build issues.`);if(y(e,n.text).status!==`valid`)throw TypeError(`The held record is not a valid record of this session.`);this.#r.assertUnclaimed(e),this.#n.dropHandoff(e),this.#n.hold(e,{digest:n.digest,text:n.text,kind:`pinned`,...n.owner?{vouched:!0}:{}})}adopt(e,t){if(!p(t))return`changed`;let n=this.#n.state(e),r=this.#t.current(e),i=b(r),a=i===void 0?void 0:m(i),o=n?.held;if(o!==void 0&&o.digest===t&&o.kind!==`pinned`)return this.#n.hold(e,{...o,kind:`owner`}),this.#n.untaint(e),a===t&&this.#m(e,t,o.text,!0)===`pending`?`pending`:`adopted`;if(i===void 0||a!==t||this.#e.tagAuthorship===void 0)return`changed`;let s=this.#p(e,r,i);if(s===`locked`)return this.#n.untaint(e),this.#n.setPending(e,t),`pending`;if(s===void 0||y(e,s).status!==`valid`)return`changed`;let c=this.#m(e,t,s,!1);return c!==`changed`&&this.#n.untaint(e),c}heldDigest(e){return this.#n.state(e)?.held?.digest}forget(e){this.#n.forget(e)}discardHeld(e){this.#n.dropHeld(e)}onUnlock(e){return this.#e.onUnlock?.(e)??(()=>void 0)}#o(e,t){return this.#r.has(e)||t?.held?.kind===`pinned`}#s(e,t,n){return e?.pendingDigest===n||t?.kind===`owner`&&t.digest===n}#c(e,t,n,r){let i=y(e,t.text);if(i.status!==`valid`)return i;if(t.kind===`pinned`)return E(i,t.vouched===!0,t.digest,r);let a=this.#s(this.#n.state(e),t,t.digest)?`owner`:`unverified`;return this.#l(e,i,a,t.digest,n,r)}#l(e,t,n,r,i,a){return this.#u(e,n,i),E(t,n===`owner`,r,a)}#u(e,t,n){t!==`owner`&&S[n].taints&&!this.#o(e,this.#n.state(e))&&this.#n.taint(e)}#d(e,t){let n=this.#n.state(e),r=n?.held??n?.handoff;return r?.kind===`pinned`?`pinned`:t.provenance===`unverified`||!this.#r.has(e)&&n?.tainted===!0?`unverified`:r===void 0?t.provenance===`owner`?`owner`:`unverified`:r.kind}#f(e,n){if(this.#e.tagAuthorship!==void 0)try{return this.#e.tagAuthorship(n,g(e))}catch(e){if((0,t.isArtifactLockedError)(e))return`locked`;throw e}}#p(e,n,r){if(n.kind!==`sealed`)return _(r);if(!(0,t.isCurrentSealedArtifactBytes)(r))return;let i=D(this.#e,e,r);return i.kind===`locked`?`locked`:i.kind===`text`?i.text:void 0}#m(e,t,n,r){let i=o.Buffer.from(n,`utf8`),a=this.#f(e,i);return a===`locked`?(this.#n.setPending(e,t),`pending`):a===void 0||this.#h(e,i,n,a,t,r)?`adopted`:`changed`}#h(e,t,n,r,i,a){let o=he(r,t),s;try{s=this.#e.sealBytes(o,g(e))}finally{o.fill(0)}let c=b(this.#t.current(e));if(c===void 0||m(c)!==i)return!1;let l={stored:s,text:n,heldAs:`owner`,tagPending:!1};try{this.#t.replace(e,s)}catch(t){throw a&&this.wroteIfPresent(e,l,this.#t.current(e),!1),t}return this.#n.clearPending(e),a&&this.wrote(e,l,!1),!0}#g(){for(let[e,t]of this.#n.pending()){this.#n.clearPending(e);try{this.#i(e,()=>this.#_(e,t))}catch{}}}#_(e,t){let n=this.#t.current(e),r=b(n);if(r===void 0||m(r)!==t)return;let i=this.#n.state(e)?.held,a=i?.digest===t,s=a?i.text:this.#p(e,n,r);if(s===void 0||s===`locked`||y(e,s).status!==`valid`)return;let c=o.Buffer.from(s,`utf8`),l=this.#f(e,c);l instanceof Uint8Array&&this.#h(e,c,s,l,t,a)}};function be(e){let t=e;if(typeof t?.acquire!=`function`||typeof t.takeOver!=`function`||typeof t.endLease!=`function`||typeof t.inspect!=`function`)throw TypeError(`A session store holds a writer marker for every id it writes: build it with the markers of its claims directory.`)}function O(e){if(typeof e!=`object`||!e)throw TypeError(`Session store options must be an object, such as { sealing }.`);return k(e.sealing),e.sealing}function k(e){if(e===`plain`)return;let t=typeof e==`object`&&e?e.sealer:void 0;if(!(typeof t==`object`&&t&&typeof t.sealBytes==`function`&&typeof t.openBytes==`function`))throw TypeError(`A session store states how it seals: { sealer }, or 'plain'.`)}var xe=class{#e;#t;#n;#r;#i;authorship;constructor(t,n,r,i={}){if(k(t),be(r),this.#e=t===`plain`?void 0:t.sealer,this.#t=n,this.#n=r,this.#r=new e.n(i.releaseCommand===void 0?{}:{releaseCommand:i.releaseCommand},{pid:process.pid,windows:process.platform===`win32`}),this.#e===void 0){this.#i=void 0,this.authorship=void 0;return}let a=new ye(this.#e,n,new oe(e=>this.#r.has(e)),this.#r,(e,t)=>this.#l(e,t));this.#i=a,this.authorship=Object.freeze({adopt:(t,n)=>{e.m(t);let r=this.#l(t,()=>a.adopt(t,n));return r===`has_writer`?`has_writer`:r},heldDigest:t=>(e.m(t),a.heldDigest(t)),onUnlock:e=>a.onUnlock(e)})}get seals(){return this.#e!==void 0}load(e,t={}){return this.#u(e,t.hold===!0?`hold`:`probe`)}listed(e){return this.#u(e,`list`)}claim(e,t={}){this.#r.assertUnclaimed(e);let n=t.fresh===!0;this.#i?.beforeClaim(e,n,t.lease!==void 0);let r=t.copy===!0?void 0:this.#o(e,t.lease),i=()=>this.#r.open(e,n,r,()=>{let{file:t,unreadable:r}=this.#t.load(e);return this.#i===void 0?this.#d(e,t,r):this.#i.claimRead(e,n,t,r,()=>this.#p(e))},()=>this.#i?.discardHeld(e));if(r===void 0)return i();try{return this.#c(e,r,i)}catch(e){throw r.release(),e}}lend(t){this.#r.assertUnclaimed(t);let n=(0,s.randomBytes)(32).toString(`hex`),r=(0,s.createHash)(`sha256`).update(n,`utf8`).digest(`hex`),i=this.#n.acquire(t,{leaseDigest:r});if(i.status!==`acquired`)throw this.#r.refusal(t,`has_writer`,{holder:e.i(i.holder)});let a=this.#r.lend(t,()=>{let e=this.#n.inspect(t);return e.status===`held`?e.holder:void 0}),o=!1;return Object.freeze({nonce:n,end:()=>{if(!o){o=!0;try{this.#n.endLease(t,r)}finally{a()}}}})}hasWriter(e){if(this.#r.has(e)||this.#r.isLent(e))return!0;let t=this.#n.inspect(e);return t.status===`held`&&t.holder.liveness!==`gone`}save(e,t={}){let n=e.id,r=this.#r.markerForSave(n,t.claim);if(r!==void 0){this.#c(n,r,()=>this.#a(e,t));return}this.#s(n,()=>this.#a(e,t))}delete(e,t){this.#r.markerForSave(e,void 0),this.#s(e,()=>{this.forget(e),t()})}#a(e,t){let n=e.id,r=this.#t.current(n),i=this.#i;if(i===void 0){this.#f(n,r),this.#t.replace(n,ee(e,void 0).stored);return}i.assertReplaceable(n,r);let a=i.prepare(n,v(e),t),o=t.handoff===!0;try{this.#t.replace(n,a.stored)}catch(e){throw i.wroteIfPresent(n,a,this.#m(n),o),e}i.wrote(n,a,o)}loadHeld(e){return this.#i?.held(e,this.#t.current(e))}exportHeld(e,t={}){return this.#i?.exportHeld(e,this.#t.current(e),t)}importHeld(e,t){if(this.#i===void 0)throw TypeError(`A store that seals nothing does not take a held record: it would write it in plaintext.`);this.#i.importHeld(e,t)}forget(e){this.#i?.forget(e)}#o(t,n){if(n===void 0){let n=this.#n.acquire(t);if(n.status===`acquired`)return n.handle;throw this.#r.refusal(t,`has_writer`,{holder:e.i(n.holder)})}let r=this.#n.takeOver(t,n);if(r.status===`acquired`)return r.handle;throw r.status===`absent`?this.#r.refusal(t,`released`,{lease:!0}):this.#r.refusal(t,`has_writer`,{holder:e.i(r.holder)})}#s(t,n){let r=this.#n.acquire(t);if(r.status!==`acquired`)throw this.#r.refusal(t,`has_writer`,{holder:e.i(r.holder)});try{return this.#c(t,r.handle,n)}finally{r.handle.release()}}#c(e,t,n){let r=t.withGuard(n);if(r.status===`ran`)return r.value;throw this.#r.refusal(e,r.status===`lost`?`released`:`has_writer`)}#l(t,n){try{let e=this.#r.markerForWrite(t);if(e!==void 0)return this.#c(t,e,n)}catch(t){if(e.r(t))return`has_writer`;throw t}let r=this.#n.acquire(t);if(r.status!==`acquired`)return`has_writer`;try{return this.#c(t,r.handle,n)}catch(t){if(e.r(t))return`has_writer`;throw t}finally{r.handle.release()}}#u(e,t){let{file:n,unreadable:r}=this.#t.load(e);return this.#i===void 0?this.#d(e,n,r):this.#i.read(e,n,r,()=>this.#p(e),t)}#d(e,n,r){if(n.kind===`absent`)return this.#p(e);let i=b(n);return i===void 0?r:(0,t.isSealedArtifactBytes)(i)?(0,t.isCurrentSealedArtifactBytes)(i)?C:{status:`unsupported`,schemaVersion:void 0}:y(e,_(i))}#f(n,r){switch(r.kind){case`absent`:case`plain`:case`oversized`:return;case`unreadable`:throw new e.a(n,`unreadable`);case`sealed`:throw new e.a(n,(0,t.isCurrentSealedArtifactBytes)(r.bytes)?`no-keys`:`newer-format`)}}#p(e){return this.#t.rebuild?.(e)??_e}#m(e){try{return this.#t.current(e)}catch{return{kind:`unreadable`}}}};function A(e){return typeof e==`object`&&e?e.code:void 0}function Se(e){let t=A(e);return typeof t==`string`&&/^E[A-Z0-9]+$/.test(t)?`could not read the session file (${t})`:`could not read the session file`}function Ce(e,t){let n=Buffer.alloc(Math.max((0,r.fstatSync)(e).size,t.length));t.copy(n,0);let i=t.length;for(;i<n.length;){let t=(0,r.readSync)(e,n,i,n.length-i,i);if(t===0)break;i+=t}return n.subarray(0,i)}const we=Object.freeze({status:`missing`}),j=`claims`;function Te(e){let t=0,n=0;for(let{outcome:r}of e)r.status===`locked`&&(r.reason===`no-keys`?n+=1:t+=1);return n===0?{locked:t}:{locked:t,noKeys:n}}function Ee(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var De=class{supportsClaimDiscard=!0;baseDir;ownedRoot;records;constructor(e,t){let r=O(t);this.records=new xe(r,{load:e=>this.loadFile(e),current:e=>this.readExisting(this.filePath(e)),replace:(e,t)=>{this.ensureDir(),(0,a.writeOwnerOnlyFile)(this.filePath(e),t)}},(0,a.createProcessMarkers)((0,i.join)((0,i.resolve)(e),j),{operationLock:(0,n.createProcessOperationLock)((0,i.join)((0,i.resolve)(e),j))}),t.releaseCommand===void 0?{}:{releaseCommand:t.releaseCommand}),this.baseDir=e,this.ownedRoot=t.ownedRoot;let o=this.records.authorship;o!==void 0&&(this.authorship=o)}claim(e,t){return this.filePath(e),this.records.claim(e,t)}lend(e){return this.filePath(e),this.records.lend(e)}hasWriter(e){return this.filePath(e),this.records.hasWriter(e)}ensureDir(){(0,a.ensureOwnerOnlyDirectory)(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(t){e.m(t);let n=(0,i.resolve)(this.baseDir),r=(0,i.resolve)(n,`${t}.json`);if(!r.startsWith(n+i.sep))throw Error(`Invalid session id: ${JSON.stringify(t)} resolves outside the session store.`);return r}save(e,t={}){this.ensureDir(),this.filePath(e.id),this.records.save(e,t)}saveRestoreTransaction(e,t){if(!t?.claim)throw TypeError(`A live session claim is required for restore commit.`);try{return this.save(e,t),{status:`committed`}}catch(e){return{status:`unknown`,error:e}}}readExisting(e){let n;try{n=(0,r.openSync)(e,`r`)}catch(e){return A(e)===`ENOENT`?{kind:`absent`}:{kind:`unreadable`}}try{let e=Buffer.alloc(t.SEALED_ARTIFACT_MAGIC.length),i=(0,r.readSync)(n,e,0,e.length,0);return(0,t.isSealedArtifactBytes)(e.subarray(0,i))?{kind:`sealed`,bytes:Ce(n,e)}:this.records.seals?{kind:`plain`,bytes:Ce(n,e.subarray(0,i))}:{kind:`plain`}}catch{return{kind:`unreadable`}}finally{(0,r.closeSync)(n)}}load(e,t={}){return this.filePath(e),this.records.load(e,t)}loadFile(e){let t=this.filePath(e),n;try{n=(0,r.readFileSync)(t)}catch(e){return A(e)===`ENOENT`?{file:{kind:`absent`},unreadable:we}:{file:{kind:`unreadable`},unreadable:{status:`corrupt`,issues:[{path:``,message:Se(e)}]}}}try{(0,a.tightenExistingFile)(t)}catch{}return{file:ae(n),unreadable:we}}loadHeld(e){return this.filePath(e),this.records.loadHeld(e)}exportHeld(e,t){return this.filePath(e),this.records.exportHeld(e,t)}importHeld(e,t){this.filePath(e),this.records.importHeld(e,t)}list(){return this.scan().entries}scan(){let e=this.readAll();return{entries:e.filter(e=>e.outcome.status!==`locked`).sort(Ee),...Te(e)}}readAll(){return(0,r.existsSync)(this.baseDir)?(0,r.readdirSync)(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})):[]}outcomeForListedId(t){return e.g(t)?this.records.listed(t):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){let t=this.filePath(e);this.records.delete(e,()=>{(0,r.existsSync)(t)&&(0,r.unlinkSync)(t)})}};const Oe=Object.freeze({kind:`does-not-open`}),ke=Object.freeze({kind:`newer-format`}),Ae=Object.freeze({kind:`locked`,reason:`no-keys`}),je=/^R(?:S(?:L[0-9]?)?)?$/;function Me(e){return k(e),e===`plain`?void 0:e.sealer}function Ne(e){return e.reason===`no-keys`?`no-keys`:`locked`}var M=class{#e;#t;constructor(e,t){this.#e=Me(e),this.#t=t}encode(e,t){return this.#e===void 0?e:`
2
2
  ${this.#e.sealLine(e,{kind:this.#t,id:t})}
3
3
  `}decode(e,t){try{return this.#n(e,t)}catch{return Oe}}openText(e,t){let n=N(e),r=e=>this.#n(e,t);return Pe((function*(){for(let e of n)yield r(e)})())}#n(e,n){if(!(0,t.isSealedArtifactLine)(e))return{kind:`lines`,lines:[e]};if(!(0,t.isCurrentSealedArtifactLine)(e))return ke;if(this.#e===void 0)return Ae;let r;try{r=this.#e.openLine(e,{kind:this.#t,id:n})}catch(e){if((0,t.isArtifactLockedError)(e))return{kind:`locked`,reason:Ne(e)};if((0,t.isArtifactCorruptError)(e))return Oe;throw e}return{kind:`lines`,lines:r.split(`
4
4
  `).filter(e=>e.length>0)}}};function N(e){let n=e.split(`
5
5
  `),r=n[n.length-1];return r.length>0&&((0,t.isSealedArtifactLine)(r)||je.test(r))&&n.pop(),n}function Pe(n){let r=[],i=0;for(let a of n)switch(i+=1,a.kind){case`lines`:r.push(a.lines.join(`
6
6
  `));break;case`locked`:throw new t.ArtifactLockedError(a.reason);case`does-not-open`:throw new t.ArtifactCorruptError;case`newer-format`:throw new e.c(`UNSUPPORTED_VERSION`,[{path:`line ${i}`,message:`the line is sealed in a framing version this build does not open`}])}return r.join(`
7
- `)}function P(t,n,r){return t===`PAYLOAD_UNREADABLE`?new e.s(t,`External payload is sealed and does not open here: ${n}.`,{relativePath:n}):new e.s(t,`External payload exceeds the remaining byte budget of ${r}.`,{relativePath:n,expected:r})}var F=class{#e;#t=new Map;constructor(e){this.#e=Me(e)}place(t,n,r,i){let a=e.u(t,n,r);if(this.#e===void 0)return i({relativePath:a.relativePath,data:r,contentAddressed:!0}),a;let o=this.#t.get(t)??new Map,c=o.get(n);if(c!==void 0)return{...a,relativePath:c};let l=`${t}.payloads/${(0,s.randomBytes)(16).toString(`base64url`)}.sealed`,u=Buffer.from(r,`utf8`),d;try{d=this.#e.sealBytes(u,{kind:`session-log-payload`,id:t})}finally{u.fill(0)}return i({relativePath:l,data:d,contentAddressed:!1}),o.set(n,l),this.#t.set(t,o),{...a,relativePath:l}}rawBudget(e){return this.#e===void 0?e:Math.min(e+t.SEALED_ARTIFACT_MAX_OVERHEAD_BYTES,2**53-1)}open(e,n,r,i){if(this.#e===void 0)return e;if(!(0,t.isSealedArtifactBytes)(e)){if(e.byteLength>n)throw P(`MAX_TOTAL_BYTES_EXCEEDED`,i,n);return e}if(!(0,t.isCurrentSealedArtifactBytes)(e)||r===void 0)throw P(`PAYLOAD_UNREADABLE`,i,n);let a;try{a=this.#e.openBytes(e,{kind:`session-log-payload`,id:r})}catch(e){throw(0,t.isArtifactLockedError)(e)?new t.ArtifactLockedError(Ne(e)):(0,t.isArtifactCorruptError)(e)?P(`PAYLOAD_UNREADABLE`,i,n):e}if(a.byteLength>n)throw a.fill(0),P(`MAX_TOTAL_BYTES_EXCEEDED`,i,n);return a}};function Fe(e){return{kind:`session-log-payload`,id:e}}function I(e,n,r){if(!(0,t.isSealedArtifactBytes)(e))return`plain`;if(!(0,t.isCurrentSealedArtifactBytes)(e))return`newer-format`;let i;try{i=r.openBytes(e,Fe(n))}catch(e){if((0,t.isArtifactLockedError)(e))throw e;return`does-not-open`}return i.fill(0),`sealed`}function Ie(e,t,n){return n.sealBytes(e,Fe(t))}function L(e){return e.endsWith(`\r`)?e.slice(0,-1):e}var R=class{ownerId;sealedLines=0;carriedLines=0;#e;constructor(e,t){this.ownerId=t,this.#e=new M({sealer:e},`session-log-line`)}rewrite(e,n,r){for(let i of e){let e=L(i);if(e.length===0)continue;if((0,t.isSealedArtifactLine)(e)){n.write(`${r?`
7
+ `)}function P(t,n,r){return t===`PAYLOAD_UNREADABLE`?new e.s(t,`External payload is sealed and does not open here: ${n}.`,{relativePath:n}):new e.s(t,`External payload exceeds the remaining byte budget of ${r}.`,{relativePath:n,expected:r})}var F=class{#e;#t=new Map;constructor(e){this.#e=Me(e)}place(t,n,r,i){let a=e.u(t,n,r);if(this.#e===void 0)return i({relativePath:a.relativePath,data:r,contentAddressed:!0}),a;let o=this.#t.get(t)??new Map,c=o.get(n);if(c!==void 0)return{...a,relativePath:c};let l=`${t}.payloads/${(0,s.randomBytes)(16).toString(`base64url`)}.sealed`,u=Buffer.from(r,`utf8`),d;try{d=this.#e.sealBytes(u,{kind:`session-log-payload`,id:t})}finally{u.fill(0)}return i({relativePath:l,data:d,contentAddressed:!1}),o.set(n,l),this.#t.set(t,o),{...a,relativePath:l}}rawBudget(e){return this.#e===void 0?e:Math.min(e+t.SEALED_ARTIFACT_MAX_OVERHEAD_BYTES,2**53-1)}open(e,n,r,i){if(this.#e===void 0)return e;if(!(0,t.isSealedArtifactBytes)(e)){if(e.byteLength>n)throw P(`MAX_TOTAL_BYTES_EXCEEDED`,i,n);return e}if(!(0,t.isCurrentSealedArtifactBytes)(e)||r===void 0)throw P(`PAYLOAD_UNREADABLE`,i,n);let a;try{a=this.#e.openBytes(e,{kind:`session-log-payload`,id:r})}catch(e){throw(0,t.isArtifactLockedError)(e)?new t.ArtifactLockedError(Ne(e)):(0,t.isArtifactCorruptError)(e)?P(`PAYLOAD_UNREADABLE`,i,n):e}if(a.byteLength>n)throw a.fill(0),P(`MAX_TOTAL_BYTES_EXCEEDED`,i,n);return a}};function Fe(e){return{kind:`session-log-payload`,id:e}}function I(e,n,r){if(!(0,t.isSealedArtifactBytes)(e))return`plain`;if(!(0,t.isCurrentSealedArtifactBytes)(e))return`newer-format`;let i;try{i=r.openBytes(e,Fe(n))}catch(e){if((0,t.isArtifactLockedError)(e))throw e;return`does-not-open`}return i.fill(0),`sealed`}function Ie(e,t,n){return n.sealBytes(e,Fe(t))}function Le(e){return e.endsWith(`\r`)?e.slice(0,-1):e}var Re=class{ownerId;sealedLines=0;carriedLines=0;#e;constructor(e,t){this.ownerId=t,this.#e=new M({sealer:e},`session-log-line`)}rewrite(e,n,r){for(let i of e){let e=Le(i);if(e.length===0)continue;if((0,t.isSealedArtifactLine)(e)){n.write(`${r?`
8
8
  `:``}${e}
9
9
  `),this.carriedLines+=1;continue}let a=this.#e.encode(`${e}
10
- `,this.ownerId);n.write(r?a:a.slice(1)),this.sealedLines+=1}}};function Le(e){return N(e).filter(e=>{let n=L(e);return n.length>0&&!(0,t.isSealedArtifactLine)(n)}).length}function Re(e,t,n){let r=new R(n,t),i=[];return r.rewrite(N(e),{write:e=>i.push(e)},!1),{text:i.join(``),sealedLines:r.sealedLines,carriedLines:r.carriedLines}}const ze=(0,t.createLogger)(`NodeSessionLogSink`);var Be=class{logDirectory;externalPayloadSink=this;enabled;lines;payloads;constructor(e,t){this.logDirectory=e;let n=O(t);this.lines=new M(n,`session-log-line`),this.payloads=new F(n);try{(0,a.ensureOwnerOnlyDirectory)(e),this.enabled=!0}catch(t){this.enabled=!1,ze.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(t,n){if(e.m(t),!this.enabled)return;let r=(0,l.join)(this.logDirectory,`${t}.jsonl`),i=this.lines.encode(n,t);(0,a.tightenExistingFile)(r),(0,c.appendFileSync)(r,i,{mode:a.OWNER_ONLY_FILE_MODE})}writeJson(e,t,n){return this.payloads.place(e,t,n,t=>this.writePayload(e,t))}writePayload(e,t){if(!this.enabled)return;(0,a.ensureOwnerOnlyDirectory)((0,l.join)(this.logDirectory,`${e}.payloads`));let n=(0,l.join)(this.logDirectory,t.relativePath);try{(0,c.writeFileSync)(n,t.data,{...typeof t.data==`string`?{encoding:`utf8`}:{},mode:a.OWNER_ONLY_FILE_MODE,flag:`wx`})}catch(e){if(!t.contentAddressed||e.code!==`EEXIST`)throw e;(0,a.tightenExistingFile)(n)}}};function Ve(e){if(e.trim().length===0||e.includes(`\0`)||(0,l.isAbsolute)(e)||l.win32.isAbsolute(e))throw z(e);let t=e.split(/[\\/]+/u);if(t.some(e=>e===`.`||e===`..`))throw z(e);return t}function He(t){if(!Number.isFinite(t)||!Number.isSafeInteger(t)||t<0)throw new e.s(`INVALID_LIMIT`,`External-payload maxBytes must be a finite, non-negative safe integer.`,{actual:String(t)})}function z(t,n){return new e.s(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${t}.`,{relativePath:t},n)}function Ue(t,n,r){return t.code===`INVALID_PATH`||t.code===`UNSAFE_ENTRY`?z(n,t):t.code===`UNSUPPORTED_BACKEND`?new e.s(`STABLE_PAYLOAD_READ_UNAVAILABLE`,`Stable root-relative external-payload reads are unavailable on this host.`,{relativePath:n},t):t.code===`OVER_BUDGET`?new e.s(`MAX_TOTAL_BYTES_EXCEEDED`,`External payload exceeds the remaining byte budget of ${r}.`,{relativePath:n,expected:r},t):new e.s(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${n}.`,{relativePath:n},t)}function We(e){let t=e.length===2?e[0]:void 0;if(!(t===void 0||!t.endsWith(`.payloads`)))return t.slice(0,-9)||void 0}var B=class{baseDirectory;payloads;ownerId;constructor(e,t){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=(0,l.resolve)(e),this.payloads=new F(O(t)),this.ownerId=t.ownerId}readBytes(e,t){He(t);let n=Ve(e),r=this.readStored(e,n,t);if(r!==void 0)return this.payloads.open(r,t,this.ownerId??We(n),e)}readStored(t,n,r){try{let e=(0,u.createStableRootedFileReader)(this.baseDirectory);try{return e.readBytes(n,this.payloads.rawBudget(r))}finally{e.close()}}catch(n){throw n instanceof e.s?n:n instanceof u.StableFileAuthorityError?Ue(n,t,r):new e.s(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${t}.`,{relativePath:t},n)}}},Ge=class{logFile;externalPayloadSource;lines;ownerId;constructor(e,t){if(this.logFile=e,e.trim().length===0)throw Error(`Session log-file path must not be empty.`);let n=O(t);this.lines=new M(n,`session-log-line`),this.ownerId=(0,l.basename)(e,(0,l.extname)(e)),this.externalPayloadSource=new B((0,l.dirname)(e),{sealing:n,ownerId:this.ownerId})}readText(){if((0,c.existsSync)(this.logFile))return this.lines.openText((0,c.readFileSync)(this.logFile,`utf8`),this.ownerId)}readStoredLines(){if((0,c.existsSync)(this.logFile))return N((0,c.readFileSync)(this.logFile,`utf8`)).map(e=>this.lines.decode(e,this.ownerId))}};function V(e){return e?.code}function H(e){let t;try{t=(0,c.lstatSync)(e)}catch(e){if(V(e)===`ENOENT`)return{status:`missing`};throw e}if(!t.isFile())return{status:`refused`,reason:`not-a-regular-file`};let n;try{n=(0,c.openSync)(e,c.constants.O_RDONLY|(c.constants.O_NOFOLLOW??0))}catch(e){if(V(e)===`ENOENT`)return{status:`missing`};if(V(e)===`ELOOP`)return{status:`refused`,reason:`not-a-regular-file`};throw e}let r=(0,c.fstatSync)(n),i=r.isFile()&&r.ino===t.ino&&r.dev===t.dev;return!i||r.nlink>1?((0,c.closeSync)(n),{status:`refused`,reason:i?`hard-linked`:`not-a-regular-file`}):{status:`open`,descriptor:n}}function U(e,t,n){let r=Buffer.alloc(Math.max(0,n-t)),i=0;for(;i<r.length;){let n=(0,c.readSync)(e,r,i,r.length-i,t+i);if(n===0)break;i+=n}return r.subarray(0,i)}function W(e){return U(e,0,(0,c.fstatSync)(e).size)}function*Ke(e){let t=0;for(;t<e.length;){let n=e.indexOf(10,t),r=n===-1?e.length:n;yield e.toString(`utf8`,t,r),t=r+1}}function qe(e,t){let n=Buffer.from(t,`utf8`),r=0;for(;r<n.length;)r+=(0,c.writeSync)(e,n,r,n.length-r)}var Je=class{descriptor;#e=[];#t=0;constructor(e){this.descriptor=e}write(e){this.#e.push(e),this.#t+=e.length,this.#t>=1048576&&this.flush()}flush(){this.#e.length!==0&&(qe(this.descriptor,this.#e.join(``)),this.#e=[],this.#t=0)}};function Ye(e){let t;try{t=(0,c.openSync)(e,c.constants.O_RDONLY),(0,c.fsyncSync)(t)}catch{}finally{t!==void 0&&(0,c.closeSync)(t)}}function Xe(e){try{(0,c.unlinkSync)(e)}catch{}}function Ze(e){let n=H(e);if(n.status!==`open`)return 0;try{return N(W(n.descriptor).toString(`utf8`)).filter(e=>e.length>0&&!(0,t.isSealedArtifactLine)(e)).length}finally{(0,c.closeSync)(n.descriptor)}}async function Qe(e,t,n,r,i){let a=0;for(;;){let o=(0,c.fstatSync)(e).size;if(o>t.read){let i=U(e,t.read,o),s=i.lastIndexOf(10);if(s!==-1){n.rewrite(Ke(i.subarray(0,s+1)),r,!0),r.flush(),t.read+=s+1,a=0;continue}}if(a>=2)break;a+=1,await i()}let o=(0,c.fstatSync)(e).size,s=U(e,t.read,o).toString(`utf8`);if(s.length===0)return!1;let l=N(s);return n.rewrite(l,r,!0),r.flush(),t.read=o,l.length===0}function $e(e,t){let n;try{n=(0,c.lstatSync)(e)}catch(e){if(V(e)===`ENOENT`)return`removed`;throw e}let r=(0,c.fstatSync)(t);return n.isFile()&&n.ino===r.ino&&n.dev===r.dev?`same`:`replaced`}function et(){return new Promise(e=>setTimeout(e,20))}async function tt(e,t,n={}){let r=H(e);if(r.status!==`open`)return r;let i=r.descriptor,o=(0,l.dirname)(e),u=(0,l.join)(o,`.${(0,l.basename)(e)}.${process.pid}.${(0,s.randomBytes)(6).toString(`hex`)}.tmp`),d,f=!1;try{let r=W(i),s=r.lastIndexOf(10)+1;(0,a.ensureOwnerOnlyDirectory)(o,n.ownedRoot===void 0?{}:{withinRoot:n.ownedRoot}),d=(0,c.openSync)(u,c.constants.O_WRONLY|c.constants.O_CREAT|c.constants.O_EXCL|c.constants.O_APPEND|(c.constants.O_NOFOLLOW??0),a.OWNER_ONLY_FILE_MODE);let l=new Je(d);t.rewrite(Ke(r.subarray(0,s)),l,!1),l.flush(),(0,c.fsyncSync)(d),n.beforeCommit?.();let p=$e(e,i);if(p!==`same`)return{status:p};(0,c.renameSync)(u,e),f=!0,Ye(o);let m={read:s},h=!1,g;try{h=await Qe(i,m,t,l,n.pause??et)}catch(e){g={unreadBytes:Math.max(0,(0,c.fstatSync)(i).size-m.read),reason:e instanceof Error?e.name:`unknown`}}return(0,c.fsyncSync)(d),{status:`rewritten`,droppedTail:h,plainLinesAfter:Ze(e),...g===void 0?{}:{catchUpFailed:g}}}finally{d!==void 0&&(0,c.closeSync)(d),(0,c.closeSync)(i),f||Xe(u)}}const nt=/^.+\.(\d{1,10})\.tmp$/u,rt=/^\..+\.(\d{1,10})\.[0-9a-f]{12}\.tmp$/u;function it(e){let t=(rt.exec(e)??nt.exec(e))?.[1];return t===void 0?void 0:Number(t)}function G(e,t,n){let r,i;try{let t=(0,c.lstatSync)(e);if(!t.isDirectory())return 0;r=Math.max(t.mtimeMs,n??-1/0),i=(0,c.readdirSync)(e)}catch{return 0}let a=0;for(let n of i){let i=it(n);if(i===void 0||i===process.pid)continue;let o=(0,l.join)(e,n);try{let e=(0,c.lstatSync)(o);if(!e.isFile()||r-e.mtimeMs<=3e5)continue;t&&(0,c.unlinkSync)(o),a+=1}catch{}}return a}function K(e){let t;try{t=(0,c.openSync)(e,c.constants.O_RDONLY|(c.constants.O_NOFOLLOW??0))}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=(0,c.fstatSync)(t);return e.isFile()?{bytes:W(t),links:e.nlink}:void 0}finally{(0,c.closeSync)(t)}}const at=e=>(0,s.createHash)(`sha256`).update(e).digest(`hex`);var ot=class extends Error{constructor(){super(`The file changed while its replacement was staged.`),this.name=`FileChangedError`}};function st(e,t,n=(e,t)=>(t(),!0)){let r=[],i=[],o=0;try{e((e,t,n)=>{r.push({path:e,file:(0,a.stageOwnerOnlyFile)(e,n),digest:at(t)})});for(let{path:e,file:a,digest:s}of r)try{n(e,()=>a.commit(()=>{t?.();let n=K(e);if(n===void 0||n.links>1||at(n.bytes)!==s)throw new ot}))?o+=1:i.push(e)}catch(t){if(!(t instanceof ot))throw t;i.push(e)}}finally{for(let{file:e}of r)e.discard()}return{replaced:o,changed:i}}const q=`.jsonl`,J=`.payloads`,ct=`.tmp`;function Y(e){let t=new Map,n;try{n=(0,c.readdirSync)(e)}catch(e){if(e.code===`ENOENT`)return t;throw e}for(let r of n.sort())try{let n=(0,c.lstatSync)((0,l.join)(e,r));t.set(r,n.isFile()?`file`:n.isDirectory()?`directory`:`other`)}catch(e){if(e.code!==`ENOENT`)throw e}return t}function lt(t,n){let r=new Map;for(let[i,a]of Y(t)){let o=i.endsWith(q),s=i.endsWith(J);if(!o&&!s)continue;let c=i.slice(0,-(o?q:J).length);if((o?a!==`file`:a!==`directory`)||!e.g(c)){n.refused.push((0,l.join)(t,i));continue}let u=r.get(c)??{log:!1,payloads:!1};o?u.log=!0:u.payloads=!0,r.set(c,u)}return r}function ut(e,t,n,r){let i=new Set,a=st(a=>{for(let[o,s]of Y(e)){if(o.endsWith(ct))continue;i.add(o);let c=(0,l.join)(e,o);if(s!==`file`){r.refused.push(c);continue}let u=K(c);if(u===void 0)continue;let d=I(u.bytes,t,n.sealer);if(d===`sealed`?r.alreadySealed+=1:d!==`plain`&&r.unopenable.push(c),d===`plain`){if(u.links>1){r.refused.push(c);continue}if(!n.apply){r.payloads+=1;continue}a(c,u.bytes,Ie(u.bytes,t,n.sealer))}}},n.beforeCommit);return r.payloads+=a.replaced,r.changed.push(...a.changed),r.staleTemporaries+=G(e,n.apply&&n.sweepTemporaries===!0,n.migrationStartedAt),i}function dt(e,t,n,r){let i=[];for(let[a,o]of Y(e)){if(n.has(a)||a.endsWith(ct)||o!==`file`)continue;let s=K((0,l.join)(e,a));s!==void 0&&I(s.bytes,t,r)===`plain`&&i.push((0,l.join)(e,a))}return i}function ft(e){let t=H(e);if(t.status===`missing`)return`missing`;if(t.status===`refused`)return`refused`;try{return Le(W(t.descriptor).toString(`utf8`))}finally{(0,c.closeSync)(t.descriptor)}}async function pt(e,t,n,r){let i=ft(e);if(i===`missing`)return;if(i===`refused`){r.refused.push(e);return}if(i===0){r.alreadySealed+=1;return}let a=n.apply?await tt(e,new R(n.sealer,t),{...n.ownedRoot===void 0?{}:{ownedRoot:n.ownedRoot},...n.beforeCommit===void 0?{}:{beforeCommit:n.beforeCommit},...n.pause===void 0?{}:{pause:n.pause}}):void 0;a?.status!==`missing`&&a?.status!==`removed`&&(r.logs+=1,r.lines+=i,a!==void 0&&(a.status===`refused`?r.refused.push(e):a.status===`replaced`?r.changed.push(e):a.status===`rewritten`&&(a.plainLinesAfter>0&&r.changed.push(e),a.catchUpFailed!==void 0&&r.catchUpFailed.push({path:e,...a.catchUpFailed}))))}async function mt(e,t){let n={logs:0,lines:0,payloads:0,alreadySealed:0,unopenable:[],refused:[],changed:[],catchUpFailed:[],staleTemporaries:0};try{if(!(0,c.lstatSync)(e).isDirectory())return n.refused.push(e),n}catch(e){if(e.code===`ENOENT`)return n;throw e}for(let[r,i]of lt(e,n)){let a=(0,l.join)(e,`${r}${J}`),o=i.payloads?ut(a,r,t,n):new Set;i.log&&await pt((0,l.join)(e,`${r}${q}`),r,t,n),t.apply&&i.payloads&&n.changed.push(...dt(a,r,o,t.sealer))}return n.staleTemporaries+=G(e,t.apply&&t.sweepTemporaries===!0,t.migrationStartedAt),n}function ht(e){let t=[],n=[],r;try{if(!(0,c.lstatSync)(e).isDirectory())return{files:t,refused:[e]};r=(0,c.readdirSync)(e)}catch(e){if(e.code===`ENOENT`)return{files:t,refused:n};throw e}for(let i of r.sort())if(i.endsWith(`.json`))try{((0,c.lstatSync)((0,l.join)(e,i)).isFile()?t:n).push(i)}catch(e){if(e.code!==`ENOENT`)throw e}return{files:t,refused:n.map(t=>(0,l.join)(e,t))}}function gt(t,r){let{files:i,refused:o}=ht(t),s={sealed:0,alreadySealed:0,unopenable:[],unsafeNames:[],refused:o,changed:[],held:[],staleTemporaries:0,sealedRecords:[]},c=(0,a.createProcessMarkers)((0,l.join)(t,j),{operationLock:(0,n.createProcessOperationLock)((0,l.join)(t,j))}),u=[],d=st(n=>{for(let a of i){let i=(0,l.join)(t,a),o=a.slice(0,-5);if(!e.g(o)){s.unsafeNames.push(i);continue}let d=c.inspect(o);if(d.status===`held`&&d.holder.liveness!==`gone`){s.held.push(o);continue}let f=K(i);if(f===void 0)continue;let p=te(o,f.bytes,r.sealer);if(p===`sealed`?s.alreadySealed+=1:p!==`plain`&&s.unopenable.push(i),p!==`plain`)continue;if(f.links>1){s.refused.push(i);continue}if(!r.apply){s.sealed+=1;continue}let h=ne(o,f.bytes,r.sealer);ie(o,f.bytes)&&u.push({path:i,id:o,digest:m(h)}),n(i,f.bytes,h)}},r.beforeCommit,(e,t)=>{let n=(0,l.basename)(e).slice(0,-5),r=c.acquire(n);if(r.status!==`acquired`)return s.held.push(n),!1;try{return r.handle.withGuard(t).status===`ran`?!0:(s.held.push(n),!1)}finally{r.handle.release()}});s.sealed+=d.replaced,s.changed.push(...d.changed);for(let{path:e,id:t,digest:n}of u)d.changed.includes(e)||s.sealedRecords.push({id:t,digest:n});return s.staleTemporaries=G(t,r.apply&&r.sweepTemporaries===!0,r.migrationStartedAt),s}function _t(t,n){let r=new Set;for(let i of ht(t).files){let a=i.slice(0,-5);if(!e.g(a))continue;let o=K((0,l.join)(t,i));if(o===void 0)continue;let s=ve(a,o.bytes,n.sealer),c=s.status===`valid`?s.record.cwd:s.status===`corrupt`||s.status===`unsupported`?s.cwd:void 0;typeof c==`string`&&c.length>0&&r.add(c)}return[...r]}const vt=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,yt=`agent-tool-results-`,X=8*1024*1024,bt=c.constants.O_WRONLY|c.constants.O_CREAT|c.constants.O_EXCL|(c.constants.O_NOFOLLOW??0);var Z=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}};function xt(e){return(0,a.sweepStaleProcessScopedDirectories)(e,yt)}const St=X+t.SEALED_ARTIFACT_MAX_OVERHEAD_BYTES;function Ct(e){return{kind:`tool-result-spill`,id:e}}var wt=class{directory;retentionMs;now;onCleanupFailure;sealer;entries=new Map;opened;expiryTimer;cancelExitRemoval;closed=!1;constructor(e){let t=e?.parentDirectory;if(typeof t!=`string`||t.length===0||(this.retentionMs=e.retentionMs??36e5,this.now=e.now??Date.now,this.onCleanupFailure=e.onCleanupFailure,!Number.isSafeInteger(this.retentionMs)||this.retentionMs<=0))throw new Z(`invalid-options`);let n;try{n=O(e)}catch{throw new Z(`invalid-options`)}this.sealer=n===`plain`?void 0:n.sealer;try{let e=(0,c.lstatSync)(t);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=(0,a.createProcessScopedDirectory)(t,yt,{prepareParent:!1}),this.assertRoot()}catch{throw new Z(`unsafe-root`)}this.cancelExitRemoval=(0,a.removeDirectoryOnProcessExit)(this.directory)}assertRoot(){try{let e=(0,c.lstatSync)(this.directory);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe directory`);if(process.platform!==`win32`&&e.mode&63)throw Error(`directory is not owner-only`)}catch{throw new Z(`unsafe-root`)}}scheduleExpiry(e=1){if(this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.closed||this.entries.size===0)return;let t=1/0;for(let e of this.entries.values())e.expiresAt<t&&(t=e.expiresAt);let n=Math.min(2147483647,Math.max(e,t-this.now()));this.expiryTimer=setTimeout(()=>{this.expiryTimer=void 0,this.cleanupExpired().catch(()=>{try{this.onCleanupFailure?this.onCleanupFailure(`cleanup-failed`):process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}catch{process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}this.scheduleExpiry(6e4)})},n),this.expiryTimer.unref?.()}async write(e){if(this.closed)throw new Z(`closed`);if(await this.cleanupExpired(),this.assertRoot(),Buffer.byteLength(e,`utf8`)>X)throw new Z(`write-failed`);let t=(0,s.randomBytes)(18).toString(`base64url`),n=`${(0,s.randomBytes)(18).toString(`base64url`)}.partial`,r=`${t}${this.sealer===void 0?`.txt`:`.sealed`}`,i=(0,l.join)(this.directory,n),a=(0,l.join)(this.directory,r),o;try{o=this.storedForm(e,t)}catch{throw new Z(`write-failed`)}let u,d=!1;try{u=(0,c.openSync)(i,bt,384),(0,c.writeFileSync)(u,o,`utf8`),(0,c.fsyncSync)(u),(0,c.closeSync)(u),u=void 0,(0,c.linkSync)(i,a),d=!0,(0,c.unlinkSync)(i);let e=`tool-result:${t}`;return this.entries.set(e,{fileName:r,token:t,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:e}}catch{let e=!1;if(u!==void 0)try{(0,c.closeSync)(u)}catch{e=!0}try{(0,c.unlinkSync)(i)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(d)try{(0,c.unlinkSync)(a)}catch{e=!0}throw new Z(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new Z(`closed`);if(!vt.test(e))throw new Z(`invalid-reference`);let t=this.entries.get(e);if(!t)throw new Z(`missing`);if(this.now()>=t.expiresAt)throw this.removeEntry(e,t),this.scheduleExpiry(),new Z(`expired`);if(this.opened?.reference===e)return this.opened.content;this.assertRoot();try{let n=new B(this.directory,{sealing:`plain`}).readBytes(t.fileName,this.sealer===void 0?X:St);if(n===void 0)throw new Z(`missing`);if(this.sealer===void 0)return Buffer.from(n).toString(`utf8`);let r=this.openStored(this.sealer,n,t.token);return this.opened={reference:e,content:r},r}catch(e){throw e instanceof Z?e:new Z(`read-failed`)}}storedForm(e,t){if(this.sealer===void 0)return e;let n=Buffer.from(e,`utf8`);try{return this.sealer.sealBytes(n,Ct(t))}finally{n.fill(0)}}openStored(e,t,n){let r=e.openBytes(t,Ct(n));try{if(r.byteLength>X)throw new Z(`read-failed`);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString(`utf8`)}finally{r.fill(0)}}removeEntry(e,t){this.assertRoot(),this.opened?.reference===e&&(this.opened=void 0);try{(0,c.unlinkSync)((0,l.join)(this.directory,t.fileName))}catch(e){if(e.code!==`ENOENT`)throw new Z(`cleanup-failed`)}this.entries.delete(e)}async cleanupExpired(){if(this.closed)throw new Z(`closed`);for(let[e,t]of this.entries)this.now()>=t.expiresAt&&this.removeEntry(e,t);this.scheduleExpiry()}async shutdown(){if(!this.closed){this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.opened=void 0;for(let[e,t]of this.entries)this.removeEntry(e,t);this.assertRoot();try{if((0,c.readdirSync)(this.directory).filter(e=>e!==a.PROCESS_OWNER_RECORD_NAME).length!==0)throw Error(`unexpected files`);(0,c.rmSync)((0,l.join)(this.directory,a.PROCESS_OWNER_RECORD_NAME),{force:!0}),(0,c.rmdirSync)(this.directory),this.closed=!0,this.cancelExitRemoval?.()}catch{throw new Z(`cleanup-failed`)}}}};const Q=`user`;function Tt(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.at==`string`&&typeof t.sessionId==`string`&&typeof t.project==`string`&&typeof t.text==`string`}function $(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(Tt(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function Et(e,t){let n=[],r=0,i=0,a=0;for(let o of e){if(o.length===0)continue;let e=t.decode(o,Q);if(e.kind===`locked`){e.reason===`no-keys`?a+=1:i+=1;continue}if(e.kind!==`lines`){r+=1;continue}for(let t=e.lines.length-1;t>=0;--t){let i=$(e.lines[t]);i===void 0?r+=1:n.push(i)}}return i+a===0?{entries:n,skippedLines:r}:{entries:n,skippedLines:r,unreadable:{locked:i,noKeys:a}}}function Dt(e){return e.code===`ENOENT`}var Ot=class{path;blockBytes;ownedRoot;lines;constructor(e,t){this.path=e,this.lines=new M(O(t),`prompt-history-line`),this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){let t=this.lines.encode(`${JSON.stringify(e)}\n`,Q);(0,a.ensureOwnerOnlyDirectory)((0,l.dirname)(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),(0,a.tightenExistingFile)(this.path),(0,c.appendFileSync)(this.path,t,{mode:a.OWNER_ONLY_FILE_MODE})}async*read(e){let t;try{t=(0,c.openSync)(this.path,c.constants.O_RDONLY|(c.constants.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&Dt(e))return;throw e}try{let n=(0,c.fstatSync)(t).size,r=Buffer.alloc(0),i=!0;for(;n>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,n);n-=e;let a=Buffer.alloc(e),o=(0,c.readSync)(t,a,0,e,n),s=Buffer.concat([a.subarray(0,o),r]),l=n===0?-1:s.indexOf(10);r=l===-1&&n>0?s:s.subarray(0,l+1);let u=n===0?s:l===-1?Buffer.alloc(0):s.subarray(l+1);if(n>0&&l===-1)continue;let d=u.toString(`utf8`),f=(i?N(d):d.split(`
11
- `)).reverse();i=!1,yield Et(f,this.lines)}}finally{(0,c.closeSync)(t)}}},kt=class{counts={entries:0,fromPlain:0,carriedOver:0};#e;constructor(e){this.#e=new M({sealer:e},`prompt-history-line`)}rewrite(e,n,r){for(let i of e){if(i.length===0)continue;let e=this.#e.decode(i,Q);if(e.kind===`locked`)throw new t.ArtifactLockedError(e.reason);if(e.kind!==`lines`){n.write(`${i}
10
+ `,this.ownerId);n.write(r?a:a.slice(1)),this.sealedLines+=1}}};function ze(e){return N(e).filter(e=>{let n=Le(e);return n.length>0&&!(0,t.isSealedArtifactLine)(n)}).length}function Be(e,t,n){let r=new Re(n,t),i=[];return r.rewrite(N(e),{write:e=>i.push(e)},!1),{text:i.join(``),sealedLines:r.sealedLines,carriedLines:r.carriedLines}}const Ve=(0,t.createLogger)(`NodeSessionLogSink`);var He=class{logDirectory;externalPayloadSink=this;enabled;lines;payloads;constructor(e,t){this.logDirectory=e;let n=O(t);this.lines=new M(n,`session-log-line`),this.payloads=new F(n);try{(0,a.ensureOwnerOnlyDirectory)(e),this.enabled=!0}catch(t){this.enabled=!1,Ve.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(t,n){if(e.m(t),!this.enabled)return;let r=(0,l.join)(this.logDirectory,`${t}.jsonl`),i=this.lines.encode(n,t);(0,a.tightenExistingFile)(r),(0,c.appendFileSync)(r,i,{mode:a.OWNER_ONLY_FILE_MODE})}writeJson(e,t,n){return this.payloads.place(e,t,n,t=>this.writePayload(e,t))}writePayload(e,t){if(!this.enabled)return;(0,a.ensureOwnerOnlyDirectory)((0,l.join)(this.logDirectory,`${e}.payloads`));let n=(0,l.join)(this.logDirectory,t.relativePath);try{(0,c.writeFileSync)(n,t.data,{...typeof t.data==`string`?{encoding:`utf8`}:{},mode:a.OWNER_ONLY_FILE_MODE,flag:`wx`})}catch(e){if(!t.contentAddressed||e.code!==`EEXIST`)throw e;(0,a.tightenExistingFile)(n)}}};function Ue(e){if(e.trim().length===0||e.includes(`\0`)||(0,l.isAbsolute)(e)||l.win32.isAbsolute(e))throw L(e);let t=e.split(/[\\/]+/u);if(t.some(e=>e===`.`||e===`..`))throw L(e);return t}function We(t){if(!Number.isFinite(t)||!Number.isSafeInteger(t)||t<0)throw new e.s(`INVALID_LIMIT`,`External-payload maxBytes must be a finite, non-negative safe integer.`,{actual:String(t)})}function L(t,n){return new e.s(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${t}.`,{relativePath:t},n)}function Ge(t,n,r){return t.code===`INVALID_PATH`||t.code===`UNSAFE_ENTRY`?L(n,t):t.code===`UNSUPPORTED_BACKEND`?new e.s(`STABLE_PAYLOAD_READ_UNAVAILABLE`,`Stable root-relative external-payload reads are unavailable on this host.`,{relativePath:n},t):t.code===`OVER_BUDGET`?new e.s(`MAX_TOTAL_BYTES_EXCEEDED`,`External payload exceeds the remaining byte budget of ${r}.`,{relativePath:n,expected:r},t):new e.s(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${n}.`,{relativePath:n},t)}function Ke(e){let t=e.length===2?e[0]:void 0;if(!(t===void 0||!t.endsWith(`.payloads`)))return t.slice(0,-9)||void 0}var R=class{baseDirectory;payloads;ownerId;constructor(e,t){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=(0,l.resolve)(e),this.payloads=new F(O(t)),this.ownerId=t.ownerId}readBytes(e,t){We(t);let n=Ue(e),r=this.readStored(e,n,t);if(r!==void 0)return this.payloads.open(r,t,this.ownerId??Ke(n),e)}readStored(t,n,r){try{let e=(0,u.createStableRootedFileReader)(this.baseDirectory);try{return e.readBytes(n,this.payloads.rawBudget(r))}finally{e.close()}}catch(n){throw n instanceof e.s?n:n instanceof u.StableFileAuthorityError?Ge(n,t,r):new e.s(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${t}.`,{relativePath:t},n)}}},qe=class{logFile;externalPayloadSource;lines;ownerId;constructor(e,t){if(this.logFile=e,e.trim().length===0)throw Error(`Session log-file path must not be empty.`);let n=O(t);this.lines=new M(n,`session-log-line`),this.ownerId=(0,l.basename)(e,(0,l.extname)(e)),this.externalPayloadSource=new R((0,l.dirname)(e),{sealing:n,ownerId:this.ownerId})}readText(){if((0,c.existsSync)(this.logFile))return this.lines.openText((0,c.readFileSync)(this.logFile,`utf8`),this.ownerId)}readStoredLines(){if((0,c.existsSync)(this.logFile))return N((0,c.readFileSync)(this.logFile,`utf8`)).map(e=>this.lines.decode(e,this.ownerId))}};const Je=new Set([`EPERM`,`EBUSY`,`EACCES`]);function z(e){return e?.code}function B(e,t,n=process.platform){return n===`win32`?e.ino!==0n&&e.ino===t.ino:e.ino===t.ino&&e.dev===t.dev}function V(e){let t;try{t=(0,c.lstatSync)(e,{bigint:!0})}catch(e){if(z(e)===`ENOENT`)return{status:`missing`};throw e}if(!t.isFile())return{status:`refused`,reason:`not-a-regular-file`};let n;try{n=(0,c.openSync)(e,c.constants.O_RDONLY|(c.constants.O_NOFOLLOW??0))}catch(e){if(z(e)===`ENOENT`)return{status:`missing`};if(z(e)===`ELOOP`)return{status:`refused`,reason:`not-a-regular-file`};throw e}let r=(0,c.fstatSync)(n,{bigint:!0}),i=r.isFile()&&B(t,r);return!i||r.nlink>1n?((0,c.closeSync)(n),{status:`refused`,reason:i?`hard-linked`:`not-a-regular-file`}):{status:`open`,descriptor:n}}function H(e,t,n){let r=Buffer.alloc(Math.max(0,n-t)),i=0;for(;i<r.length;){let n=(0,c.readSync)(e,r,i,r.length-i,t+i);if(n===0)break;i+=n}return r.subarray(0,i)}function U(e){return H(e,0,(0,c.fstatSync)(e).size)}function*Ye(e){let t=0;for(;t<e.length;){let n=e.indexOf(10,t),r=n===-1?e.length:n;yield e.toString(`utf8`,t,r),t=r+1}}function Xe(e,t){let n=Buffer.from(t,`utf8`),r=0;for(;r<n.length;)r+=(0,c.writeSync)(e,n,r,n.length-r)}var Ze=class{descriptor;#e=[];#t=0;constructor(e){this.descriptor=e}write(e){this.#e.push(e),this.#t+=e.length,this.#t>=1048576&&this.flush()}flush(){this.#e.length!==0&&(Xe(this.descriptor,this.#e.join(``)),this.#e=[],this.#t=0)}};function Qe(e){let t;try{t=(0,c.openSync)(e,c.constants.O_RDONLY),(0,c.fsyncSync)(t)}catch{}finally{t!==void 0&&(0,c.closeSync)(t)}}function $e(e){try{(0,c.unlinkSync)(e)}catch{}}function et(e){let n=V(e);if(n.status!==`open`)return 0;try{return N(U(n.descriptor).toString(`utf8`)).filter(e=>e.length>0&&!(0,t.isSealedArtifactLine)(e)).length}finally{(0,c.closeSync)(n.descriptor)}}async function tt(e,t,n,r,i){let a=0;for(;;){let o=(0,c.fstatSync)(e).size;if(o>t.read){let i=H(e,t.read,o),s=i.lastIndexOf(10);if(s!==-1){n.rewrite(Ye(i.subarray(0,s+1)),r,!0),r.flush(),t.read+=s+1,a=0;continue}}if(a>=2)break;a+=1,await i()}let o=(0,c.fstatSync)(e).size,s=H(e,t.read,o).toString(`utf8`);if(s.length===0)return!1;let l=N(s);return n.rewrite(l,r,!0),r.flush(),t.read=o,l.length===0}function nt(e,t){let n;try{n=(0,c.lstatSync)(e,{bigint:!0})}catch(e){if(z(e)===`ENOENT`)return`removed`;throw e}let r=(0,c.fstatSync)(t,{bigint:!0});return n.isFile()&&B(n,r)?`same`:`replaced`}function rt(){return new Promise(e=>setTimeout(e,20))}async function it(e,t,n,r,i,a,o,s){let l=(0,c.fstatSync)(n.descriptor,{bigint:!0}),u=!1;for(let d=1;;d+=1){u=await tt(n.descriptor,r,i,a,s)||u,(0,c.fsyncSync)(o);let f=nt(e,n.descriptor);if(f!==`same`)return{status:f};(0,c.closeSync)(n.descriptor),n.descriptor=void 0;try{return(0,c.renameSync)(t,e),{droppedTail:u}}catch(e){let t=z(e);if(t===void 0||!Je.has(t)||d>=10)throw e}await s();let p=V(e);if(p.status===`missing`)return{status:`removed`};if(p.status!==`open`)return p;if(!B((0,c.fstatSync)(p.descriptor,{bigint:!0}),l))return(0,c.closeSync)(p.descriptor),{status:`replaced`};n.descriptor=p.descriptor}}async function at(e,t,n={}){let r=V(e);if(r.status!==`open`)return r;let i=r.descriptor,o={descriptor:i},u=(0,l.dirname)(e),d=(0,l.join)(u,`.${(0,l.basename)(e)}.${process.pid}.${(0,s.randomBytes)(6).toString(`hex`)}.tmp`),f=n.pause??rt,p,m=!1;try{let r=U(i),s=r.lastIndexOf(10)+1;(0,a.ensureOwnerOnlyDirectory)(u,n.ownedRoot===void 0?{}:{withinRoot:n.ownedRoot}),p=(0,c.openSync)(d,c.constants.O_WRONLY|c.constants.O_CREAT|c.constants.O_EXCL|c.constants.O_APPEND|(c.constants.O_NOFOLLOW??0),a.OWNER_ONLY_FILE_MODE);let l=new Ze(p);t.rewrite(Ye(r.subarray(0,s)),l,!1),l.flush(),(0,c.fsyncSync)(p),n.beforeCommit?.();let h=nt(e,i);if(h!==`same`)return{status:h};let g={read:s},_=!1,v;if((n.platform??process.platform)===`win32`){let n=await it(e,d,o,g,t,l,p,f);if(`status`in n)return n;m=!0,_=n.droppedTail}else{(0,c.renameSync)(d,e),m=!0,Qe(u);try{_=await tt(i,g,t,l,f)}catch(e){v={unreadBytes:Math.max(0,(0,c.fstatSync)(i).size-g.read),reason:e instanceof Error?e.name:`unknown`}}(0,c.fsyncSync)(p)}return{status:`rewritten`,droppedTail:_,plainLinesAfter:et(e),...v===void 0?{}:{catchUpFailed:v}}}finally{p!==void 0&&(0,c.closeSync)(p),o.descriptor!==void 0&&(0,c.closeSync)(o.descriptor),m||$e(d)}}const ot=/^.+\.(\d{1,10})\.tmp$/u,st=/^\..+\.(\d{1,10})\.[0-9a-f]{12}\.tmp$/u;function ct(e){let t=(st.exec(e)??ot.exec(e))?.[1];return t===void 0?void 0:Number(t)}function W(e,t,n){let r,i;try{let t=(0,c.lstatSync)(e);if(!t.isDirectory())return 0;r=Math.max(t.mtimeMs,n??-1/0),i=(0,c.readdirSync)(e)}catch{return 0}let a=0;for(let n of i){let i=ct(n);if(i===void 0||i===process.pid)continue;let o=(0,l.join)(e,n);try{let e=(0,c.lstatSync)(o);if(!e.isFile()||r-e.mtimeMs<=3e5)continue;t&&(0,c.unlinkSync)(o),a+=1}catch{}}return a}function G(e){let t;try{t=(0,c.openSync)(e,c.constants.O_RDONLY|(c.constants.O_NOFOLLOW??0))}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=(0,c.fstatSync)(t);return e.isFile()?{bytes:U(t),links:e.nlink}:void 0}finally{(0,c.closeSync)(t)}}const lt=e=>(0,s.createHash)(`sha256`).update(e).digest(`hex`);var ut=class extends Error{constructor(){super(`The file changed while its replacement was staged.`),this.name=`FileChangedError`}};function dt(e,t,n=(e,t)=>(t(),!0)){let r=[],i=[],o=0;try{e((e,t,n)=>{r.push({path:e,file:(0,a.stageOwnerOnlyFile)(e,n),digest:lt(t)})});for(let{path:e,file:a,digest:s}of r)try{n(e,()=>a.commit(()=>{t?.();let n=G(e);if(n===void 0||n.links>1||lt(n.bytes)!==s)throw new ut}))?o+=1:i.push(e)}catch(t){if(!(t instanceof ut))throw t;i.push(e)}}finally{for(let{file:e}of r)e.discard()}return{replaced:o,changed:i}}const K=`.jsonl`,q=`.payloads`,ft=`.tmp`;function J(e){let t=new Map,n;try{n=(0,c.readdirSync)(e)}catch(e){if(e.code===`ENOENT`)return t;throw e}for(let r of n.sort())try{let n=(0,c.lstatSync)((0,l.join)(e,r));t.set(r,n.isFile()?`file`:n.isDirectory()?`directory`:`other`)}catch(e){if(e.code!==`ENOENT`)throw e}return t}function pt(t,n){let r=new Map;for(let[i,a]of J(t)){let o=i.endsWith(K),s=i.endsWith(q);if(!o&&!s)continue;let c=i.slice(0,-(o?K:q).length);if((o?a!==`file`:a!==`directory`)||!e.g(c)){n.refused.push((0,l.join)(t,i));continue}let u=r.get(c)??{log:!1,payloads:!1};o?u.log=!0:u.payloads=!0,r.set(c,u)}return r}function mt(e,t,n,r){let i=new Set,a=dt(a=>{for(let[o,s]of J(e)){if(o.endsWith(ft))continue;i.add(o);let c=(0,l.join)(e,o);if(s!==`file`){r.refused.push(c);continue}let u=G(c);if(u===void 0)continue;let d=I(u.bytes,t,n.sealer);if(d===`sealed`?r.alreadySealed+=1:d!==`plain`&&r.unopenable.push(c),d===`plain`){if(u.links>1){r.refused.push(c);continue}if(!n.apply){r.payloads+=1;continue}a(c,u.bytes,Ie(u.bytes,t,n.sealer))}}},n.beforeCommit);return r.payloads+=a.replaced,r.changed.push(...a.changed),r.staleTemporaries+=W(e,n.apply&&n.sweepTemporaries===!0,n.migrationStartedAt),i}function ht(e,t,n,r){let i=[];for(let[a,o]of J(e)){if(n.has(a)||a.endsWith(ft)||o!==`file`)continue;let s=G((0,l.join)(e,a));s!==void 0&&I(s.bytes,t,r)===`plain`&&i.push((0,l.join)(e,a))}return i}function gt(e){let t=V(e);if(t.status===`missing`)return`missing`;if(t.status===`refused`)return`refused`;try{return ze(U(t.descriptor).toString(`utf8`))}finally{(0,c.closeSync)(t.descriptor)}}async function _t(e,t,n,r){let i=gt(e);if(i===`missing`)return;if(i===`refused`){r.refused.push(e);return}if(i===0){r.alreadySealed+=1;return}let a=n.apply?await at(e,new Re(n.sealer,t),{...n.ownedRoot===void 0?{}:{ownedRoot:n.ownedRoot},...n.beforeCommit===void 0?{}:{beforeCommit:n.beforeCommit},...n.pause===void 0?{}:{pause:n.pause}}):void 0;a?.status!==`missing`&&a?.status!==`removed`&&(r.logs+=1,r.lines+=i,a!==void 0&&(a.status===`refused`?r.refused.push(e):a.status===`replaced`?r.changed.push(e):a.status===`rewritten`&&(a.plainLinesAfter>0&&r.changed.push(e),a.catchUpFailed!==void 0&&r.catchUpFailed.push({path:e,...a.catchUpFailed}))))}async function vt(e,t){let n={logs:0,lines:0,payloads:0,alreadySealed:0,unopenable:[],refused:[],changed:[],catchUpFailed:[],staleTemporaries:0};try{if(!(0,c.lstatSync)(e).isDirectory())return n.refused.push(e),n}catch(e){if(e.code===`ENOENT`)return n;throw e}for(let[r,i]of pt(e,n)){let a=(0,l.join)(e,`${r}${q}`),o=i.payloads?mt(a,r,t,n):new Set;i.log&&await _t((0,l.join)(e,`${r}${K}`),r,t,n),t.apply&&i.payloads&&n.changed.push(...ht(a,r,o,t.sealer))}return n.staleTemporaries+=W(e,t.apply&&t.sweepTemporaries===!0,t.migrationStartedAt),n}function yt(e){let t=[],n=[],r;try{if(!(0,c.lstatSync)(e).isDirectory())return{files:t,refused:[e]};r=(0,c.readdirSync)(e)}catch(e){if(e.code===`ENOENT`)return{files:t,refused:n};throw e}for(let i of r.sort())if(i.endsWith(`.json`))try{((0,c.lstatSync)((0,l.join)(e,i)).isFile()?t:n).push(i)}catch(e){if(e.code!==`ENOENT`)throw e}return{files:t,refused:n.map(t=>(0,l.join)(e,t))}}function bt(t,r){let{files:i,refused:o}=yt(t),s={sealed:0,alreadySealed:0,unopenable:[],unsafeNames:[],refused:o,changed:[],held:[],staleTemporaries:0,sealedRecords:[]},c=(0,a.createProcessMarkers)((0,l.join)(t,j),{operationLock:(0,n.createProcessOperationLock)((0,l.join)(t,j))}),u=[],d=dt(n=>{for(let a of i){let i=(0,l.join)(t,a),o=a.slice(0,-5);if(!e.g(o)){s.unsafeNames.push(i);continue}let d=c.inspect(o);if(d.status===`held`&&d.holder.liveness!==`gone`){s.held.push(o);continue}let f=G(i);if(f===void 0)continue;let p=te(o,f.bytes,r.sealer);if(p===`sealed`?s.alreadySealed+=1:p!==`plain`&&s.unopenable.push(i),p!==`plain`)continue;if(f.links>1){s.refused.push(i);continue}if(!r.apply){s.sealed+=1;continue}let h=ne(o,f.bytes,r.sealer);ie(o,f.bytes)&&u.push({path:i,id:o,digest:m(h)}),n(i,f.bytes,h)}},r.beforeCommit,(e,t)=>{let n=(0,l.basename)(e).slice(0,-5),r=c.acquire(n);if(r.status!==`acquired`)return s.held.push(n),!1;try{return r.handle.withGuard(t).status===`ran`?!0:(s.held.push(n),!1)}finally{r.handle.release()}});s.sealed+=d.replaced,s.changed.push(...d.changed);for(let{path:e,id:t,digest:n}of u)d.changed.includes(e)||s.sealedRecords.push({id:t,digest:n});return s.staleTemporaries=W(t,r.apply&&r.sweepTemporaries===!0,r.migrationStartedAt),s}function xt(t,n){let r=new Set;for(let i of yt(t).files){let a=i.slice(0,-5);if(!e.g(a))continue;let o=G((0,l.join)(t,i));if(o===void 0)continue;let s=ve(a,o.bytes,n.sealer),c=s.status===`valid`?s.record.cwd:s.status===`corrupt`||s.status===`unsupported`?s.cwd:void 0;typeof c==`string`&&c.length>0&&r.add(c)}return[...r]}const St=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,Y=`agent-tool-results-`,X=8*1024*1024,Ct=c.constants.O_WRONLY|c.constants.O_CREAT|c.constants.O_EXCL|(c.constants.O_NOFOLLOW??0);var Z=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}};function wt(e){return(0,a.sweepStaleProcessScopedDirectories)(e,Y)}const Tt=X+t.SEALED_ARTIFACT_MAX_OVERHEAD_BYTES;function Et(e){return{kind:`tool-result-spill`,id:e}}var Dt=class{directory;retentionMs;now;onCleanupFailure;sealer;entries=new Map;opened;expiryTimer;cancelExitRemoval;closed=!1;constructor(e){let t=e?.parentDirectory;if(typeof t!=`string`||t.length===0||(this.retentionMs=e.retentionMs??36e5,this.now=e.now??Date.now,this.onCleanupFailure=e.onCleanupFailure,!Number.isSafeInteger(this.retentionMs)||this.retentionMs<=0))throw new Z(`invalid-options`);let n;try{n=O(e)}catch{throw new Z(`invalid-options`)}this.sealer=n===`plain`?void 0:n.sealer;try{let e=(0,c.lstatSync)(t);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=(0,a.createProcessScopedDirectory)(t,Y,{prepareParent:!1}),this.assertRoot()}catch{throw new Z(`unsafe-root`)}this.cancelExitRemoval=(0,a.removeDirectoryOnProcessExit)(this.directory)}assertRoot(){try{let e=(0,c.lstatSync)(this.directory);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe directory`);if(process.platform!==`win32`&&e.mode&63)throw Error(`directory is not owner-only`)}catch{throw new Z(`unsafe-root`)}}scheduleExpiry(e=1){if(this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.closed||this.entries.size===0)return;let t=1/0;for(let e of this.entries.values())e.expiresAt<t&&(t=e.expiresAt);let n=Math.min(2147483647,Math.max(e,t-this.now()));this.expiryTimer=setTimeout(()=>{this.expiryTimer=void 0,this.cleanupExpired().catch(()=>{try{this.onCleanupFailure?this.onCleanupFailure(`cleanup-failed`):process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}catch{process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}this.scheduleExpiry(6e4)})},n),this.expiryTimer.unref?.()}async write(e){if(this.closed)throw new Z(`closed`);if(await this.cleanupExpired(),this.assertRoot(),Buffer.byteLength(e,`utf8`)>X)throw new Z(`write-failed`);let t=(0,s.randomBytes)(18).toString(`base64url`),n=`${(0,s.randomBytes)(18).toString(`base64url`)}.partial`,r=`${t}${this.sealer===void 0?`.txt`:`.sealed`}`,i=(0,l.join)(this.directory,n),a=(0,l.join)(this.directory,r),o;try{o=this.storedForm(e,t)}catch{throw new Z(`write-failed`)}let u,d=!1;try{u=(0,c.openSync)(i,Ct,384),(0,c.writeFileSync)(u,o,`utf8`),(0,c.fsyncSync)(u),(0,c.closeSync)(u),u=void 0,(0,c.linkSync)(i,a),d=!0,(0,c.unlinkSync)(i);let e=`tool-result:${t}`;return this.entries.set(e,{fileName:r,token:t,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:e}}catch{let e=!1;if(u!==void 0)try{(0,c.closeSync)(u)}catch{e=!0}try{(0,c.unlinkSync)(i)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(d)try{(0,c.unlinkSync)(a)}catch{e=!0}throw new Z(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new Z(`closed`);if(!St.test(e))throw new Z(`invalid-reference`);let t=this.entries.get(e);if(!t)throw new Z(`missing`);if(this.now()>=t.expiresAt)throw this.removeEntry(e,t),this.scheduleExpiry(),new Z(`expired`);if(this.opened?.reference===e)return this.opened.content;this.assertRoot();try{let n=new R(this.directory,{sealing:`plain`}).readBytes(t.fileName,this.sealer===void 0?X:Tt);if(n===void 0)throw new Z(`missing`);if(this.sealer===void 0)return Buffer.from(n).toString(`utf8`);let r=this.openStored(this.sealer,n,t.token);return this.opened={reference:e,content:r},r}catch(e){throw e instanceof Z?e:new Z(`read-failed`)}}storedForm(e,t){if(this.sealer===void 0)return e;let n=Buffer.from(e,`utf8`);try{return this.sealer.sealBytes(n,Et(t))}finally{n.fill(0)}}openStored(e,t,n){let r=e.openBytes(t,Et(n));try{if(r.byteLength>X)throw new Z(`read-failed`);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString(`utf8`)}finally{r.fill(0)}}removeEntry(e,t){this.assertRoot(),this.opened?.reference===e&&(this.opened=void 0);try{(0,c.unlinkSync)((0,l.join)(this.directory,t.fileName))}catch(e){if(e.code!==`ENOENT`)throw new Z(`cleanup-failed`)}this.entries.delete(e)}async cleanupExpired(){if(this.closed)throw new Z(`closed`);for(let[e,t]of this.entries)this.now()>=t.expiresAt&&this.removeEntry(e,t);this.scheduleExpiry()}async shutdown(){if(!this.closed){this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.opened=void 0;for(let[e,t]of this.entries)this.removeEntry(e,t);this.assertRoot();try{if((0,c.readdirSync)(this.directory).filter(e=>e!==a.PROCESS_OWNER_RECORD_NAME).length!==0)throw Error(`unexpected files`);(0,c.rmSync)((0,l.join)(this.directory,a.PROCESS_OWNER_RECORD_NAME),{force:!0}),(0,c.rmdirSync)(this.directory),this.closed=!0,this.cancelExitRemoval?.()}catch{throw new Z(`cleanup-failed`)}}}};const Q=`user`;function Ot(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.at==`string`&&typeof t.sessionId==`string`&&typeof t.project==`string`&&typeof t.text==`string`}function $(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(Ot(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function kt(e,t){let n=[],r=0,i=0,a=0;for(let o of e){if(o.length===0)continue;let e=t.decode(o,Q);if(e.kind===`locked`){e.reason===`no-keys`?a+=1:i+=1;continue}if(e.kind!==`lines`){r+=1;continue}for(let t=e.lines.length-1;t>=0;--t){let i=$(e.lines[t]);i===void 0?r+=1:n.push(i)}}return i+a===0?{entries:n,skippedLines:r}:{entries:n,skippedLines:r,unreadable:{locked:i,noKeys:a}}}function At(e){return e.code===`ENOENT`}var jt=class{path;blockBytes;ownedRoot;lines;constructor(e,t){this.path=e,this.lines=new M(O(t),`prompt-history-line`),this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){let t=this.lines.encode(`${JSON.stringify(e)}\n`,Q);(0,a.ensureOwnerOnlyDirectory)((0,l.dirname)(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),(0,a.tightenExistingFile)(this.path),(0,c.appendFileSync)(this.path,t,{mode:a.OWNER_ONLY_FILE_MODE})}async*read(e){let t;try{t=(0,c.openSync)(this.path,c.constants.O_RDONLY|(c.constants.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&At(e))return;throw e}try{let n=(0,c.fstatSync)(t);if(n.isDirectory())throw Object.assign(Error(`EISDIR: illegal operation on a directory, read`),{code:`EISDIR`});let r=n.size,i=Buffer.alloc(0),a=!0;for(;r>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,r);r-=e;let n=Buffer.alloc(e),o=(0,c.readSync)(t,n,0,e,r),s=Buffer.concat([n.subarray(0,o),i]),l=r===0?-1:s.indexOf(10);i=l===-1&&r>0?s:s.subarray(0,l+1);let u=r===0?s:l===-1?Buffer.alloc(0):s.subarray(l+1);if(r>0&&l===-1)continue;let d=u.toString(`utf8`),f=(a?N(d):d.split(`
11
+ `)).reverse();a=!1,yield kt(f,this.lines)}}finally{(0,c.closeSync)(t)}}},Mt=class{counts={entries:0,fromPlain:0,carriedOver:0};#e;constructor(e){this.#e=new M({sealer:e},`prompt-history-line`)}rewrite(e,n,r){for(let i of e){if(i.length===0)continue;let e=this.#e.decode(i,Q);if(e.kind===`locked`)throw new t.ArtifactLockedError(e.reason);if(e.kind!==`lines`){n.write(`${i}
12
12
  `),this.counts.carriedOver+=1;continue}(0,t.isSealedArtifactLine)(i)||(this.counts.fromPlain+=e.lines.length);for(let t of e.lines){let e=this.#e.encode(`${t}
13
- `,Q);n.write(r?e:e.slice(1)),this.counts.entries+=1}}}};function At(e,n){let r=H(e);if(r.status!==`open`)return r;let i=new M({sealer:n.sealer},`prompt-history-line`),a=0,o=0,s=0;try{for(let e of N(W(r.descriptor).toString(`utf8`))){if(e.length===0)continue;let n=i.decode(e,Q);if(n.kind===`locked`)throw new t.ArtifactLockedError(n.reason);n.kind===`lines`?(0,t.isSealedArtifactLine)(e)?o+=1:a+=1:s+=1}}finally{(0,c.closeSync)(r.descriptor)}return{status:`present`,plainLines:a,sealedLines:o,unreadableLines:s}}function jt(e,n){let r=H(e);if(r.status!==`open`)return[];let i=new M({sealer:n.sealer},`prompt-history-line`),a=new Set;try{for(let e of N(W(r.descriptor).toString(`utf8`))){if(e.length===0)continue;let n=i.decode(e,Q);if(n.kind===`locked`)throw new t.ArtifactLockedError(n.reason);if(n.kind===`lines`)for(let e of n.lines){let t=$(e);t!==void 0&&t.project.length>0&&a.add(t.project)}}}finally{(0,c.closeSync)(r.descriptor)}return[...a]}async function Mt(e,t){let n=new kt(t.sealer),r=0,i=await tt(e,n,{...t.ownedRoot===void 0?{}:{ownedRoot:t.ownedRoot},...t.pause===void 0?{}:{pause:t.pause},beforeCommit:()=>{r=n.counts.entries,t.beforeCommit?.()}});return i.status===`rewritten`?{status:`compacted`,...n.counts,caughtUp:n.counts.entries-r,droppedTail:i.droppedTail,plainLinesAfter:i.plainLinesAfter,...i.catchUpFailed===void 0?{}:{catchUpFailed:i.catchUpFailed}}:i}function Nt(e){let t=e,n=[];for(;;)try{let e=(0,c.realpathSync)(t);return n.length===0?e:(0,l.resolve)(e,...n.reverse())}catch{let r=(0,l.dirname)(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[\\/]/,``)),t=r}}function Pt(e,t){let n=(0,l.relative)(e,t);return n===``||!n.startsWith(`..`)&&!(0,l.isAbsolute)(n)}function Ft(e){return(t,n)=>{let r=Nt(e),i=Nt((0,l.resolve)(t??r,n));return Pt(r,i)?i:void 0}}function It(e){typeof process>`u`||typeof process.on!=`function`||process.on(`exit`,e)}exports.DEFAULT_PROMPT_HISTORY_BLOCK_BYTES=65536,exports.NodeExternalPayloadSource=B,exports.NodePromptHistoryFile=Ot,exports.NodeSessionLogSink=Be,exports.NodeSessionLogSource=Ge,exports.NodeSessionStore=De,exports.NodeToolResultSpillStore=wt,exports.SESSION_CLAIMS_DIRECTORY=j,exports.StoredLines=M,exports.StoredPayloads=F,exports.StoredSessionRecords=xe,exports.ToolResultSpillError=Z,exports.assertSessionSealing=k,exports.classifyStoredSessionBytes=ae,exports.compactPromptHistoryFile=Mt,exports.countPlainSessionLogLines=Le,exports.createNodeWorkspacePathResolver=Ft,Object.defineProperty(exports,"createProcessOperationLock",{enumerable:!0,get:function(){return n.createProcessOperationLock}}),exports.inspectPromptHistoryFile=At,exports.isPlainSessionRecordOf=ie,exports.migrateNodeSessionStore=gt,exports.migrateSessionLogDirectory=mt,exports.parsePromptHistoryLine=$,exports.readPromptHistoryProjects=jt,exports.readSessionStoreWorkingDirectories=_t,exports.registerProcessExitFlush=It,exports.sealSessionLogText=Re,exports.sealStoredPayloadBytes=Ie,exports.sealStoredSessionBytes=ne,exports.sessionSealingOf=O,exports.splitStoredLines=N,exports.storedPayloadMigrationState=I,exports.storedSessionMigrationState=te,exports.sweepStaleToolResultSpillDirectories=xt;
13
+ `,Q);n.write(r?e:e.slice(1)),this.counts.entries+=1}}}};function Nt(e,n){let r=V(e);if(r.status!==`open`)return r;let i=new M({sealer:n.sealer},`prompt-history-line`),a=0,o=0,s=0;try{for(let e of N(U(r.descriptor).toString(`utf8`))){if(e.length===0)continue;let n=i.decode(e,Q);if(n.kind===`locked`)throw new t.ArtifactLockedError(n.reason);n.kind===`lines`?(0,t.isSealedArtifactLine)(e)?o+=1:a+=1:s+=1}}finally{(0,c.closeSync)(r.descriptor)}return{status:`present`,plainLines:a,sealedLines:o,unreadableLines:s}}function Pt(e,n){let r=V(e);if(r.status!==`open`)return[];let i=new M({sealer:n.sealer},`prompt-history-line`),a=new Set;try{for(let e of N(U(r.descriptor).toString(`utf8`))){if(e.length===0)continue;let n=i.decode(e,Q);if(n.kind===`locked`)throw new t.ArtifactLockedError(n.reason);if(n.kind===`lines`)for(let e of n.lines){let t=$(e);t!==void 0&&t.project.length>0&&a.add(t.project)}}}finally{(0,c.closeSync)(r.descriptor)}return[...a]}async function Ft(e,t){let n=new Mt(t.sealer),r=0,i=await at(e,n,{...t.ownedRoot===void 0?{}:{ownedRoot:t.ownedRoot},...t.pause===void 0?{}:{pause:t.pause},beforeCommit:()=>{r=n.counts.entries,t.beforeCommit?.()}});return i.status===`rewritten`?{status:`compacted`,...n.counts,caughtUp:n.counts.entries-r,droppedTail:i.droppedTail,plainLinesAfter:i.plainLinesAfter,...i.catchUpFailed===void 0?{}:{catchUpFailed:i.catchUpFailed}}:i}function It(e){let t=e,n=[];for(;;)try{let e=(0,c.realpathSync)(t);return n.length===0?e:(0,l.resolve)(e,...n.reverse())}catch{let r=(0,l.dirname)(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[\\/]/,``)),t=r}}function Lt(e,t){let n=(0,l.relative)(e,t);return n===``||!n.startsWith(`..`)&&!(0,l.isAbsolute)(n)}function Rt(e){return(t,n)=>{let r=It(e),i=It((0,l.resolve)(t??r,n));return Lt(r,i)?i:void 0}}function zt(e){typeof process>`u`||typeof process.on!=`function`||process.on(`exit`,e)}exports.DEFAULT_PROMPT_HISTORY_BLOCK_BYTES=65536,exports.NodeExternalPayloadSource=R,exports.NodePromptHistoryFile=jt,exports.NodeSessionLogSink=He,exports.NodeSessionLogSource=qe,exports.NodeSessionStore=De,exports.NodeToolResultSpillStore=Dt,exports.SESSION_CLAIMS_DIRECTORY=j,exports.StoredLines=M,exports.StoredPayloads=F,exports.StoredSessionRecords=xe,exports.ToolResultSpillError=Z,exports.assertSessionSealing=k,exports.classifyStoredSessionBytes=ae,exports.compactPromptHistoryFile=Ft,exports.countPlainSessionLogLines=ze,exports.createNodeWorkspacePathResolver=Rt,Object.defineProperty(exports,"createProcessOperationLock",{enumerable:!0,get:function(){return n.createProcessOperationLock}}),exports.inspectPromptHistoryFile=Nt,exports.isPlainSessionRecordOf=ie,exports.migrateNodeSessionStore=bt,exports.migrateSessionLogDirectory=vt,exports.parsePromptHistoryLine=$,exports.readPromptHistoryProjects=Pt,exports.readSessionStoreWorkingDirectories=xt,exports.registerProcessExitFlush=zt,exports.sealSessionLogText=Be,exports.sealStoredPayloadBytes=Ie,exports.sealStoredSessionBytes=ne,exports.sessionSealingOf=O,exports.splitStoredLines=N,exports.storedPayloadMigrationState=I,exports.storedSessionMigrationState=te,exports.sweepStaleToolResultSpillDirectories=wt;
package/dist/node.d.cts CHANGED
@@ -1,7 +1,7 @@
1
- import { c as IExternalPayloadSink, d as IExternalPayloadReference, l as ISessionLogSink, o as IExternalPayloadSource, s as ISessionLogSource, t as ISessionClaimRefusalWords } from "./session-claims-DELiAZkZ.cjs";
1
+ import { c as IExternalPayloadSink, d as IExternalPayloadReference, l as ISessionLogSink, o as IExternalPayloadSource, s as ISessionLogSource, t as ISessionClaimRefusalWords } from "./session-claims-Rlw8sRxi.cjs";
2
2
  import { IArtifactSealer, IProcessMarkers, IToolResultSpillStore, TArtifactKind, TArtifactLockedReason, TArtifactSealing, TResolveInWorkspace } from "@robota-sdk/agent-core";
3
- import { IInteractiveSessionRecord, IInteractiveSessionStore, IPromptHistoryBlock, IPromptHistoryEntry, IPromptHistoryReadOptions, IPromptHistorySource, IPromptHistoryWriter, ISessionAuthorship, ISessionClaim, ISessionClaimOptions, ISessionExportOptions, ISessionLease, ISessionListEntry, ISessionLoadOptions, ISessionSaveOptions, ISessionStoreScan, TSessionLoadOutcome, TSessionRestoreCommitOutcome } from "@robota-sdk/agent-interface-session";
4
- import { createProcessOperationLock } from "@robota-sdk/agent-node-lock";
3
+ import { IInteractiveSessionRecord, IInteractiveSessionStore, IPromptHistoryBlock, IPromptHistoryEntry, IPromptHistoryReadOptions, IPromptHistorySource, IPromptHistoryWriter, ISessionAuthorship, ISessionClaim, ISessionClaimOptions, ISessionExportOptions, ISessionLease, ISessionListEntry, ISessionLoadOptions, ISessionSaveOptions, ISessionStoreScan, TSessionLoadOutcome, TSessionRestoreCommitOutcome } from "@robota-sdk/agent-interface/session";
4
+ import { createProcessOperationLock } from "@robota-sdk/agent-os/node-lock";
5
5
  //#region src/stored-session-codec.d.ts
6
6
  /** A stored record: the bytes that go on disk and the plaintext envelope they were made from. */
7
7
  interface IEncodedSession {
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.cts","names":[],"sources":["../src/stored-session-codec.ts","../src/stored-session-record.ts","../src/session-store.ts","../src/node-session-log-sink.ts","../src/stored-append-lines.ts","../src/session-log-sources.ts","../src/append-file-rewrite.ts","../src/session-log-migration.ts","../src/session-record-migration.ts","../src/tool-result-spill-store.ts","../src/prompt-history-file.ts","../src/prompt-history-compaction.ts","../src/workspace-path-resolver.ts","../src/process-exit-flush.ts"],"mappings":";;;;;;UAmEiB;WACN,QAAQ;WACR;;;KAiBC;;;;;;;;;;;;;;iBAeI,4BACd,YACA,QAAQ,YACR,QAAQ,kBACP;;;;;;iBAmBa,uBACd,YACA,KAAK,YACL,QAAQ,kBACP;;iBA2Ca,uBAAuB,YAAY,OAAO;;KAK9C;;;WAEG;;;;;;;WAKA;WAAwB,QAAQ;;;;WAEhC;WAAyB,OAAO;;;;WAEhC;;;;WAEA;;;iBAGC,2BAA2B,OAAO,yBAAyB;;;;;;;;;;UCzH1D,6BAA6B;WACnC,SAAS;;;iBAmBJ,iBAAiB,SAAS,uBAAuB;;iBASjD,qBAAqB,yBAAyB,SAAS;;;;;UAqBtD;;;;;EAKf,KAAK;aAAwB,MAAM;aAA6B,YAAY;;;EAE5E,QAAQ,aAAa;;EAErB,QAAQ,YAAY,QAAQ;;EAE5B,SAAS,aAAa;;;;;;;cAQX;;;WAOF,YAAY;;;;;;EAQnB,YAAA,SAAS,kBACT,OAAO,qBACP,SAAS,iBACT,QAAO;;MAwCL;;;;;;;EAUJ,KAAK,YAAY,UAAS,sBAA2B;;EAKrD,OAAO,aAAa;;;;;;;;;EAYpB,MAAM,YAAY,UAAS,uBAA4B;;;;;;EA0BvD,KAAK,aAAa;;;;;;EAgClB,UAAU;;;;;;;;;;EAeV,KAAK,QAAQ,2BAA2B,UAAS;;EAWjD,OAAO,YAAY;;;;;;;EAsCnB,SAAS,aAAa;;;;;;EAStB,WAAW,YAAY,UAAS;;;;;;EAShC,WAAW,YAAY;;EAUvB,OAAO;;;;;;;;cCzRI;;UA2BI,iCAAiC;;;;;;;;WAQvC;;;;;;;;cASE,4BAA4B;WAC9B;mBACQ;mBACA;;mBAEA;;WAEA,aAAa;;;;;;;EAQlB,YAAA,iBAAiB,SAAS;;;;;;EA6BtC,MAAM,YAAY,UAAU,uBAAuB;;EAMnD,KAAK,aAAa;;EAMlB,UAAU;;;;;;;;;;UAcF;;;;;;;;;;;;;;UAoBA;;;;;;;;;;;;;;;EA0BR,KAAK,SAAS,2BAA2B,UAAS;EAiBlD,uBACE,SAAS,2BACT,UAAU,sBACT;;;;;;;;;UAmBK;;;;;;;;;;;;;EAmCR,KAAK,YAAY,UAAS,sBAA2B;;UAM7C;;;;;;;EA8CR,SAAS,aAAa;;EAMtB,WAAW,YAAY,UAAU;;EAMjC,WAAW,YAAY;;;;;;;;;;;;;EAiBvB,iBAAiB;;;;;;EASjB,QAAQ;UAUA;;;;;;;;;;;;;UAsBA;;;;;EAcR,OAAO;;;;;cC1bI,8BAA8B,iBAAiB;mBAWvC;WAVV,qBAAqB;mBACb;mBACA;mBACA;;;;;EAOE,YAAA,sBACjB,SAAS;EAyBX,OAAO,mBAAmB;EAa1B,UAAU,mBAAmB,gBAAgB,qBAAqB;UAM1D;;;;;KCzBE,kBAAkB,QAAQ;;KAG1B;;;WAEG;WAAwB;;;;WAExB;WAAyB,QAAQ;;;;WAEjC;;;;WAEA;;;cAmBF;;EAIC,YAAA,SAAS,kBAAkB,MAAM;;;;;;EAU7C,OAAO,cAAc;;EAMrB,OAAO,cAAc,kBAAkB;;;;;;;EAgBvC,SAAS,cAAc;;;;;;;;iBAkCT,iBAAiB;;UA8ChB;WACN;WACA,eAAe;;;;;WAKf;;;;;;;;cA2BE;;EAKC,YAAA,SAAS;;;;;;EASrB,MACE,mBACA,gBACA,oBACA,QAAQ,QAAQ,+BACf;;EA0BH,UAAU;;;;;;;;;;;;EAgBV,KACE,QAAQ,YACR,kBACA,6BACA,uBACC;;;KA+BO;;;;;iBAUI,4BACd,QAAQ,YACR,iBACA,QAAQ,kBACP;;;;;;iBAmBa,uBACd,OAAO,YACP,iBACA,QAAQ,kBACP;;iBAiDa,0BAA0B;;UAQzB;WACN;WACA;WACA;;;;;;;iBAQK,mBACd,cACA,iBACA,QAAQ,kBACP;;;UCjWc,0CAA0C;;;;;WAKhD;;;cAaE,qCAAqC;mBAC/B;mBACA;mBACA;;;;;EAML,YAAA,uBAAuB,SAAS;EAS5C,UAAU,sBAAsB,mBAAmB;;UAc3C;;;;;;;cAgCG,gCAAgC;mBAUxB;WATV,uBAAuB;mBACf;mBACA;;;;;EAOE,YAAA,iBACjB,SAAS;;EAeX;;EAMA,4BAA4B;;;;;KC7IlB;;;;;;UA2JK;;WAEN;;WAEA;;;;UC/KM;;WAEN,QAAQ;;WAER;;WAEA;;WAEA;;WAEA,cAAc;;;;;WAKd;;;;;WAKA;;;UAIM,kCAAkC;WACxC;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;;;;;WAKA;;WAEA,wBAAwB;;WAExB;;;iBAgLW,2BACpB,mBACA,SAAS,6BACR,QAAQ;;;UC7OM;;WAEN,QAAQ;;WAER;;;;;WAKA;;;;;WAKA;;;;;WAKA;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA;;;;;WAKA;;WAEA;;;;;WAKA;;WAEA;;;;;;WAMA,wBAAwB;;;UAIlB;WACN;WACA;;;iBA4BK,wBACd,iBACA,SAAS,gCACR;;;;;;iBA8Fa,mCACd,iBACA;WAAoB,QAAQ;;;;KCjLlB;cAWC,6BAA6B;WACnB,MAAM;EAAN,YAAA,MAAM;;;;;;iBAUb,qCAAqC;UAIpC;;;;;;;WAON;WACA;WACA;;WAEA,oBAAoB;;;;;;WAMpB,SAAS;;;;;;cAwBP,oCAAoC;mBAC9B;mBACA;mBACA;mBACA;mBACA;mBACA;;UAET;UACA;UACA;UACA;EAEI,YAAA,SAAS;UAqCb;UAYA;EAwBF,MAAM,kBAAkB;aAAmB;;EA0D3C,KAAK,oBAAoB;;UA+BvB;;;;;UAcA;;;;;;UAeA;EAaF,kBAAkB;EAQlB,YAAY;;;;;cC1SP;UAMI,sCAAsC;;WAE5C;;WAEA;;;iBAeK,uBAAuB,eAAe;cAmDzC,iCAAiC,sBAAsB;mBAW/C;mBAVF;mBACA;mBACA;;;;;;EAQE,YAAA,cACjB,SAAS;EAOX,OAAO,OAAO;;;;;EAiBP,KAAK,SAAS,4BAA4B,cAAc;;;;;KCtHrD,wBAAwB;UAEnB;;WAEN,QAAQ;;UAGF;;;;;;WAMN,QAAQ;;WAER;;;;;WAKA;;WAEA,cAAc;;KAGb;WACG;;WACA;WAA4B,QAAQ;;WAEpC;;WAEA;;WAEA;;WAEA;;KAGH;WACG;;WACA;WAA4B,QAAQ;;;;WAEpC;;;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA,gBAAgB;;;iBA4Cf,yBACd,cACA,SAAS,+BACR;;;;;;iBA2Ba,0BACd,cACA,SAAS;;;;;iBA2BW,yBACpB,cACA,SAAS,+BACR,QAAQ;;;iBCzKK,gCAAgC,cAAc;;;;;;;;;iBC3B9C,yBAAyB"}
1
+ {"version":3,"file":"node.d.cts","names":[],"sources":["../src/stored-session-codec.ts","../src/stored-session-record.ts","../src/session-store.ts","../src/node-session-log-sink.ts","../src/stored-append-lines.ts","../src/session-log-sources.ts","../src/append-file-rewrite.ts","../src/session-log-migration.ts","../src/session-record-migration.ts","../src/tool-result-spill-store.ts","../src/prompt-history-file.ts","../src/prompt-history-compaction.ts","../src/workspace-path-resolver.ts","../src/process-exit-flush.ts"],"mappings":"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"}
package/dist/node.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { c as IExternalPayloadSink, d as IExternalPayloadReference, l as ISessionLogSink, o as IExternalPayloadSource, s as ISessionLogSource, t as ISessionClaimRefusalWords } from "./session-claims-DELiAZkZ.js";
1
+ import { c as IExternalPayloadSink, d as IExternalPayloadReference, l as ISessionLogSink, o as IExternalPayloadSource, s as ISessionLogSource, t as ISessionClaimRefusalWords } from "./session-claims-Rlw8sRxi.js";
2
2
  import { IArtifactSealer, IProcessMarkers, IToolResultSpillStore, TArtifactKind, TArtifactLockedReason, TArtifactSealing, TResolveInWorkspace } from "@robota-sdk/agent-core";
3
- import { createProcessOperationLock } from "@robota-sdk/agent-node-lock";
4
- import { IInteractiveSessionRecord, IInteractiveSessionStore, IPromptHistoryBlock, IPromptHistoryEntry, IPromptHistoryReadOptions, IPromptHistorySource, IPromptHistoryWriter, ISessionAuthorship, ISessionClaim, ISessionClaimOptions, ISessionExportOptions, ISessionLease, ISessionListEntry, ISessionLoadOptions, ISessionSaveOptions, ISessionStoreScan, TSessionLoadOutcome, TSessionRestoreCommitOutcome } from "@robota-sdk/agent-interface-session";
3
+ import { createProcessOperationLock } from "@robota-sdk/agent-os/node-lock";
4
+ import { IInteractiveSessionRecord, IInteractiveSessionStore, IPromptHistoryBlock, IPromptHistoryEntry, IPromptHistoryReadOptions, IPromptHistorySource, IPromptHistoryWriter, ISessionAuthorship, ISessionClaim, ISessionClaimOptions, ISessionExportOptions, ISessionLease, ISessionListEntry, ISessionLoadOptions, ISessionSaveOptions, ISessionStoreScan, TSessionLoadOutcome, TSessionRestoreCommitOutcome } from "@robota-sdk/agent-interface/session";
5
5
  //#region src/stored-session-codec.d.ts
6
6
  /** A stored record: the bytes that go on disk and the plaintext envelope they were made from. */
7
7
  interface IEncodedSession {
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.ts","names":[],"sources":["../src/stored-session-codec.ts","../src/stored-session-record.ts","../src/session-store.ts","../src/node-session-log-sink.ts","../src/stored-append-lines.ts","../src/session-log-sources.ts","../src/append-file-rewrite.ts","../src/session-log-migration.ts","../src/session-record-migration.ts","../src/tool-result-spill-store.ts","../src/prompt-history-file.ts","../src/prompt-history-compaction.ts","../src/workspace-path-resolver.ts","../src/process-exit-flush.ts"],"mappings":"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"}
1
+ {"version":3,"file":"node.d.ts","names":[],"sources":["../src/stored-session-codec.ts","../src/stored-session-record.ts","../src/session-store.ts","../src/node-session-log-sink.ts","../src/stored-append-lines.ts","../src/session-log-sources.ts","../src/append-file-rewrite.ts","../src/session-log-migration.ts","../src/session-record-migration.ts","../src/tool-result-spill-store.ts","../src/prompt-history-file.ts","../src/prompt-history-compaction.ts","../src/workspace-path-resolver.ts","../src/process-exit-flush.ts"],"mappings":"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"}
package/dist/node.js CHANGED
@@ -1,14 +1,14 @@
1
- import{a as e,b as t,c as n,g as r,i,m as a,n as o,r as s,s as c,u as l}from"./session-claims-DB4Q00_J.js";import{ArtifactCorruptError as u,ArtifactLockedError as d,SEALED_ARTIFACT_MAGIC as f,SEALED_ARTIFACT_MAX_OVERHEAD_BYTES as p,createLogger as m,isArtifactCorruptError as ee,isArtifactLockedError as h,isCurrentSealedArtifactBytes as g,isCurrentSealedArtifactLine as te,isSealedArtifactBytes as _,isSealedArtifactLine as v}from"@robota-sdk/agent-core";import{createProcessOperationLock as ne,createProcessOperationLock as re}from"@robota-sdk/agent-node-lock";import{closeSync as ie,existsSync as ae,fstatSync as oe,openSync as se,readFileSync as ce,readSync as le,readdirSync as ue,unlinkSync as de}from"fs";import{join as fe,resolve as y,sep as pe}from"path";import{OWNER_ONLY_FILE_MODE as b,PROCESS_OWNER_RECORD_NAME as me,createProcessMarkers as he,createProcessScopedDirectory as ge,ensureOwnerOnlyDirectory as x,removeDirectoryOnProcessExit as _e,stageOwnerOnlyFile as ve,sweepStaleProcessScopedDirectories as ye,tightenExistingFile as S,writeOwnerOnlyFile as be}from"@robota-sdk/agent-core/node";import{Buffer as C}from"node:buffer";import{createHash as xe,randomBytes as w}from"node:crypto";import{appendFileSync as Se,closeSync as T,constants as E,existsSync as Ce,fstatSync as D,fsyncSync as O,linkSync as we,lstatSync as k,openSync as A,readFileSync as Te,readSync as Ee,readdirSync as De,realpathSync as Oe,renameSync as ke,rmSync as Ae,rmdirSync as je,unlinkSync as j,writeFileSync as Me,writeSync as Ne}from"node:fs";import{basename as Pe,dirname as M,extname as Fe,isAbsolute as Ie,join as N,relative as Le,resolve as Re,win32 as ze}from"node:path";import{StableFileAuthorityError as Be,createStableRootedFileReader as Ve}from"@robota-sdk/agent-file-authority";const He=`the sealed session file does not open for this session: it is damaged or sealed with other keys`,Ue=/^[0-9a-f]{64}$/;function We(e){return typeof e==`string`&&Ue.test(e)}function P(e){return xe(`sha256`).update(e).digest(`hex`)}function Ge(e,t){return C.from(e.buffer,e.byteOffset,e.byteLength).equals(t)}function F(e){return{kind:`session-record`,id:e}}function I(e){return C.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`)}function Ke(e){return JSON.stringify({schemaVersion:2,record:e},null,2)}function qe(e,t){let n=Ke(e),r=C.from(n,`utf8`);return{stored:t===void 0?r:t.sealBytes(r,F(e.id)),text:n}}function Je(e,t,n){if(!_(t))return`plain`;if(!g(t))return`newer-format`;let r;try{r=n.openBytes(t,F(e))}catch(e){if(h(e))throw e;return`does-not-open`}return r.fill(0),`sealed`}function Ye(e,t,n){return n.sealBytes(t,F(e))}function Xe(e){let n;try{n=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let r=t(n);return r.status===`valid`?{status:`valid`,record:r.record}:r.status===`unsupported`?{status:`unsupported`,schemaVersion:r.schemaVersion,...r.cwd===void 0?{}:{cwd:r.cwd}}:{status:`corrupt`,issues:r.issues,...r.cwd===void 0?{}:{cwd:r.cwd}}}function L(e,t){let n=Xe(t);return n.status!==`valid`||n.record.id===e?n:{status:`corrupt`,issues:[{path:`id`,message:`the record belongs to another session id`}]}}function Ze(e,t){return L(e,I(t)).status===`valid`}function Qe(e){return e===void 0?{kind:`absent`}:_(e)?{kind:`sealed`,bytes:e}:{kind:`plain`,bytes:e}}function R(e){return e.kind===`sealed`||e.kind===`plain`?e.bytes:void 0}var $e=class{#e=new Map;#t=new Set;#n=new Set;#r;constructor(e=()=>!1){this.#r=e}get size(){return this.#t.size}state(e){return this.#e.get(e)}hold(e,t){this.#i(e).held=t,this.#t.delete(e),this.#t.add(e);for(let e of this.#t){if(this.#t.size<=32)break;this.#e.get(e)?.held?.kind===`pinned`||this.#r(e)||this.dropHeld(e)}}holdHandoff(e,t){this.#i(e).handoff=t,this.#n.delete(e),this.#n.add(e);for(let e of this.#n){if(this.#n.size<=8)break;this.dropHandoff(e)}}dropHeld(e){this.#t.delete(e),this.#a(e,e=>delete e.held)}dropHandoff(e){this.#n.delete(e),this.#a(e,e=>delete e.handoff)}taint(e){this.#i(e).tainted=!0}untaint(e){this.#a(e,e=>e.tainted=!1)}setPending(e,t){this.#i(e).pendingDigest=t}clearPending(e){this.#a(e,e=>delete e.pendingDigest)}pending(){let e=[];for(let[t,n]of this.#e)n.pendingDigest!==void 0&&e.push([t,n.pendingDigest]);return e}forget(e){this.#t.delete(e),this.#n.delete(e),this.#a(e,e=>{delete e.held,delete e.handoff,delete e.pendingDigest})}#i(e){let t=this.#e.get(e);return t===void 0&&(t={tainted:!1},this.#e.set(e,t)),t}#a(e,t){let n=this.#e.get(e);n!==void 0&&(t(n),n.held===void 0&&n.handoff===void 0&&n.pendingDigest===void 0&&!n.tainted&&this.#e.delete(e))}};const et=`rsh2.`,tt={owner:!0,unverified:!1},nt=/^[A-Za-z0-9_-]+$/,rt=new TextDecoder(`utf-8`,{fatal:!0});function it(e,t,n){return`${et}${n?`owner`:`unverified`}.${e}.${C.from(t,`utf8`).toString(`base64url`)}`}function at(e){if(typeof e!=`string`||!e.startsWith(et))return;let[t,n,r,...i]=e.slice(5).split(`.`);if(t!==`owner`&&t!==`unverified`||i.length>0||n===void 0||r===void 0||!We(n)||!nt.test(r))return;let a=C.from(r,`base64url`);if(a.toString(`base64url`)===r)try{return{digest:n,text:rt.decode(a),owner:tt[t]}}catch{return}}const ot=`robota-authorship/v1 `,z=C.from(ot,`ascii`),st=/^[A-Za-z0-9_-]+$/;function ct(e,t){let n=C.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64url`);return C.concat([C.from(`${ot}${n}\n`,`ascii`),t])}function lt(e){let t=C.from(e.buffer,e.byteOffset,e.byteLength);if(t.length<z.length||!t.subarray(0,z.length).equals(z))return{envelope:e,tag:void 0};let n=t.indexOf(10,z.length);if(n<0)return{envelope:e,tag:`malformed`};let r=t.subarray(z.length,n).toString(`latin1`),i=e.subarray(n+1);if(!st.test(r))return{envelope:i,tag:`malformed`};let a=C.from(r,`base64url`);return a.length!==32||a.toString(`base64url`)!==r?{envelope:i,tag:`malformed`}:{envelope:i,tag:a}}const ut={probe:{writer:!1,takes:!1,holds:!1,taints:!0},hold:{writer:!0,takes:!0,holds:!0,taints:!0},list:{writer:!1,takes:!1,holds:!1,taints:!1},held:{writer:!0,takes:!0,holds:!1,taints:!0},export:{writer:!0,takes:!1,holds:!1,taints:!0},claim:{writer:!0,takes:!0,holds:!0,taints:!0},save:{writer:!0,takes:!1,holds:!1,taints:!1}},dt=Object.freeze({status:`locked`,reason:`no-keys`}),ft=Object.freeze({status:`locked`,reason:`changed`}),pt=Object.freeze({status:`locked`}),mt=Object.freeze({status:`missing`});function B(e,t,n,r){return{status:`valid`,record:e.record,authorship:t?`verified`:`unverified`,...n===void 0?{}:{digest:n},...r?{diverged:!0}:{}}}function V(e,t,n){let r;try{r=e.openBytes(n,F(t))}catch(e){return h(e)?e.reason===`no-keys`?{kind:`no-keys`}:{kind:`locked`}:{kind:`does-not-open`}}try{let{envelope:n,tag:i}=lt(r),a=!1;if(i instanceof Uint8Array&&e.verifyAuthorship!==void 0)try{a=e.verifyAuthorship(n,i,F(t))===!0}catch{a=!1}return{kind:`text`,text:I(n),verified:a}}finally{r.fill(0)}}function ht(e,t,n){let r,i=!1;if(!_(t))r=I(t);else{if(!g(t))return{status:`unsupported`,schemaVersion:void 0};let a=V(n,e,t);if(a.kind===`locked`)return pt;if(a.kind===`no-keys`)return dt;if(a.kind===`does-not-open`)return{status:`corrupt`,issues:[{path:``,message:He}]};r=a.text,i=a.verified}let a=L(e,r);return a.status===`valid`?B(a,i,P(t),!1):a}var gt=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n,r,i){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,e.tagAuthorship!==void 0&&e.onUnlock!==void 0&&(this.#a=()=>this.#g(),e.onUnlock(this.#a))}read(e,t,n,r,i){let a=this.guarded(e,t,i);if(a!==void 0)return a;if(t.kind===`absent`){let t=r();return t.status===`valid`?this.#l(e,t,`unverified`,void 0,i,!1):t}let o=R(t);return o===void 0?n:this.decode(e,o,i)}decode(e,t,n){let r,i=!1;if(!_(t))r=I(t);else{if(!g(t))return{status:`unsupported`,schemaVersion:void 0};let n=V(this.#e,e,t);if(n.kind===`locked`)return pt;if(n.kind===`no-keys`)return dt;if(n.kind===`does-not-open`)return{status:`corrupt`,issues:[{path:``,message:He}]};r=n.text,i=n.verified}let a=L(e,r);if(a.status!==`valid`)return a;let o=P(t),s=this.#n.state(e),c=i||this.#s(s,s?.held,o)?`owner`:`unverified`;return ut[n].holds&&this.#n.hold(e,{digest:o,text:r,kind:c}),this.#l(e,a,c,o,n,!1)}claimRead(e,t,n,r,i){let a=this.#n.state(e)?.held,o=R(n);return!t&&a!==void 0&&o!==void 0&&P(o)===a.digest?this.#c(e,a,`claim`,!1):this.read(e,n,r,i,`claim`)}beforeClaim(e,t,n){if(this.#n.state(e)?.held?.kind===`pinned`&&!n)throw this.#r.refusal(e,`has_writer`);t&&(this.#n.dropHeld(e),this.#n.dropHandoff(e))}guarded(e,t,n){let r=this.#n.state(e),i=this.#o(e,r),a=i?void 0:r?.handoff;if(!i&&a===void 0)return;let o=ut[n],s=R(t),c=s===void 0?void 0:P(s);if(a!==void 0)return o.takes&&this.#n.dropHandoff(e),s===void 0||c!==a.digest?ft:(o.takes&&this.#n.hold(e,a),this.#c(e,a,n,!1));let l=r?.held;if(l!==void 0&&c===l.digest)return this.#c(e,l,n,!1);let u=!1;if(l?.kind!==`pinned`&&t.kind===`sealed`&&g(t.bytes)){let r=V(this.#e,e,t.bytes);if(r.kind===`text`&&r.verified&&c!==void 0){let t=L(e,r.text);if(t.status===`valid`)return n!==`save`&&this.#n.hold(e,{digest:c,text:r.text,kind:`owner`}),B(t,!0,c,!1)}u=r.kind===`locked`}return t.kind===`absent`?l===void 0?mt:this.#c(e,l,n,!0):o.writer||l===void 0?u?pt:ft:this.#c(e,l,n,!0)}assertReplaceable(t,n){let r=this.guarded(t,n,`save`);if(r!==void 0){if(r.status!==`locked`)return;throw new e(t,r.reason===`changed`?`changed`:`locked`)}switch(n.kind){case`absent`:case`plain`:return;case`unreadable`:case`oversized`:throw new e(t,`unreadable`);case`sealed`:break}let i=n.bytes;if(!g(i))throw new e(t,`newer-format`);let a=this.#n.state(t)?.held;if(a!==void 0&&a.digest===P(i))return;let o=V(this.#e,t,i);if(o.kind!==`text`)throw new e(t,a===void 0?o.kind===`locked`||o.kind===`no-keys`?o.kind:`does-not-open`:`changed`)}prepare(e,t,n){let r=C.from(t,`utf8`),i=this.#d(e,n),a=r,o=!1;if(i===`owner`){let t=this.#f(e,r);t===`locked`?o=n.handoff!==!0:t!==void 0&&(a=ct(t,r))}try{return{stored:this.#e.sealBytes(a,F(e)),text:t,heldAs:i,tagPending:o}}finally{a!==r&&a.fill(0)}}wrote(e,t,n){let r=this.#n.state(e)?.held,i=t.heldAs===`pinned`&&r?.kind===`pinned`&&r.vouched,a={digest:P(t.stored),text:t.text,kind:t.heldAs,...i===!0?{vouched:i}:{}};n&&!this.#r.has(e)&&t.heldAs!==`pinned`?(this.#n.dropHeld(e),this.#n.holdHandoff(e,a)):(this.#n.dropHandoff(e),this.#n.hold(e,a)),t.tagPending?this.#n.setPending(e,a.digest):this.#n.clearPending(e)}wroteIfPresent(e,t,n,r){n.kind===`sealed`&&Ge(n.bytes,t.stored)&&this.wrote(e,t,r)}held(e,t){let n=this.guarded(e,t,`held`);if(n!==void 0)return n;let r=this.#n.state(e)?.held;if(r===void 0)return;let i=R(t);return i===void 0||P(i)!==r.digest?ft:this.#c(e,r,`held`,!1)}exportHeld(e,t,n){if(t.kind!==`sealed`||!g(t.bytes))return;let r=P(t.bytes),i=(e,t)=>it(r,e,t===`owner`),a=this.#n.state(e);if(this.#o(e,a)){if(n.handoffOnly===!0)return;let a=this.guarded(e,t,`export`),o=this.#n.state(e)?.held;return a?.status!==`valid`||a.diverged===!0||o?.digest!==r?void 0:i(o.text,a.authorship===`verified`?`owner`:`unverified`)}let o=a?.handoff;if(o!==void 0)return n.keep!==!0&&this.#n.dropHandoff(e),o.digest===r?(this.#u(e,o.kind,`export`),i(o.text,o.kind)):void 0;if(n.handoffOnly===!0)return;let s=V(this.#e,e,t.bytes);if(s.kind!==`text`||L(e,s.text).status!==`valid`)return;let c=s.verified||this.#s(a,a?.held,r)?`owner`:`unverified`;return this.#u(e,c,`export`),i(s.text,c)}importHeld(e,t){let n=at(t);if(n===void 0)throw TypeError(`The held record is not a token this build issues.`);if(L(e,n.text).status!==`valid`)throw TypeError(`The held record is not a valid record of this session.`);this.#r.assertUnclaimed(e),this.#n.dropHandoff(e),this.#n.hold(e,{digest:n.digest,text:n.text,kind:`pinned`,...n.owner?{vouched:!0}:{}})}adopt(e,t){if(!We(t))return`changed`;let n=this.#n.state(e),r=this.#t.current(e),i=R(r),a=i===void 0?void 0:P(i),o=n?.held;if(o!==void 0&&o.digest===t&&o.kind!==`pinned`)return this.#n.hold(e,{...o,kind:`owner`}),this.#n.untaint(e),a===t&&this.#m(e,t,o.text,!0)===`pending`?`pending`:`adopted`;if(i===void 0||a!==t||this.#e.tagAuthorship===void 0)return`changed`;let s=this.#p(e,r,i);if(s===`locked`)return this.#n.untaint(e),this.#n.setPending(e,t),`pending`;if(s===void 0||L(e,s).status!==`valid`)return`changed`;let c=this.#m(e,t,s,!1);return c!==`changed`&&this.#n.untaint(e),c}heldDigest(e){return this.#n.state(e)?.held?.digest}forget(e){this.#n.forget(e)}discardHeld(e){this.#n.dropHeld(e)}onUnlock(e){return this.#e.onUnlock?.(e)??(()=>void 0)}#o(e,t){return this.#r.has(e)||t?.held?.kind===`pinned`}#s(e,t,n){return e?.pendingDigest===n||t?.kind===`owner`&&t.digest===n}#c(e,t,n,r){let i=L(e,t.text);if(i.status!==`valid`)return i;if(t.kind===`pinned`)return B(i,t.vouched===!0,t.digest,r);let a=this.#s(this.#n.state(e),t,t.digest)?`owner`:`unverified`;return this.#l(e,i,a,t.digest,n,r)}#l(e,t,n,r,i,a){return this.#u(e,n,i),B(t,n===`owner`,r,a)}#u(e,t,n){t!==`owner`&&ut[n].taints&&!this.#o(e,this.#n.state(e))&&this.#n.taint(e)}#d(e,t){let n=this.#n.state(e),r=n?.held??n?.handoff;return r?.kind===`pinned`?`pinned`:t.provenance===`unverified`||!this.#r.has(e)&&n?.tainted===!0?`unverified`:r===void 0?t.provenance===`owner`?`owner`:`unverified`:r.kind}#f(e,t){if(this.#e.tagAuthorship!==void 0)try{return this.#e.tagAuthorship(t,F(e))}catch(e){if(h(e))return`locked`;throw e}}#p(e,t,n){if(t.kind!==`sealed`)return I(n);if(!g(n))return;let r=V(this.#e,e,n);return r.kind===`locked`?`locked`:r.kind===`text`?r.text:void 0}#m(e,t,n,r){let i=C.from(n,`utf8`),a=this.#f(e,i);return a===`locked`?(this.#n.setPending(e,t),`pending`):a===void 0||this.#h(e,i,n,a,t,r)?`adopted`:`changed`}#h(e,t,n,r,i,a){let o=ct(r,t),s;try{s=this.#e.sealBytes(o,F(e))}finally{o.fill(0)}let c=R(this.#t.current(e));if(c===void 0||P(c)!==i)return!1;let l={stored:s,text:n,heldAs:`owner`,tagPending:!1};try{this.#t.replace(e,s)}catch(t){throw a&&this.wroteIfPresent(e,l,this.#t.current(e),!1),t}return this.#n.clearPending(e),a&&this.wrote(e,l,!1),!0}#g(){for(let[e,t]of this.#n.pending()){this.#n.clearPending(e);try{this.#i(e,()=>this.#_(e,t))}catch{}}}#_(e,t){let n=this.#t.current(e),r=R(n);if(r===void 0||P(r)!==t)return;let i=this.#n.state(e)?.held,a=i?.digest===t,o=a?i.text:this.#p(e,n,r);if(o===void 0||o===`locked`||L(e,o).status!==`valid`)return;let s=C.from(o,`utf8`),c=this.#f(e,s);c instanceof Uint8Array&&this.#h(e,s,o,c,t,a)}};function _t(e){let t=e;if(typeof t?.acquire!=`function`||typeof t.takeOver!=`function`||typeof t.endLease!=`function`||typeof t.inspect!=`function`)throw TypeError(`A session store holds a writer marker for every id it writes: build it with the markers of its claims directory.`)}function H(e){if(typeof e!=`object`||!e)throw TypeError(`Session store options must be an object, such as { sealing }.`);return U(e.sealing),e.sealing}function U(e){if(e===`plain`)return;let t=typeof e==`object`&&e?e.sealer:void 0;if(!(typeof t==`object`&&t&&typeof t.sealBytes==`function`&&typeof t.openBytes==`function`))throw TypeError(`A session store states how it seals: { sealer }, or 'plain'.`)}var vt=class{#e;#t;#n;#r;#i;authorship;constructor(e,t,n,r={}){if(U(e),_t(n),this.#e=e===`plain`?void 0:e.sealer,this.#t=t,this.#n=n,this.#r=new o(r.releaseCommand===void 0?{}:{releaseCommand:r.releaseCommand},{pid:process.pid,windows:process.platform===`win32`}),this.#e===void 0){this.#i=void 0,this.authorship=void 0;return}let i=new gt(this.#e,t,new $e(e=>this.#r.has(e)),this.#r,(e,t)=>this.#l(e,t));this.#i=i,this.authorship=Object.freeze({adopt:(e,t)=>{a(e);let n=this.#l(e,()=>i.adopt(e,t));return n===`has_writer`?`has_writer`:n},heldDigest:e=>(a(e),i.heldDigest(e)),onUnlock:e=>i.onUnlock(e)})}get seals(){return this.#e!==void 0}load(e,t={}){return this.#u(e,t.hold===!0?`hold`:`probe`)}listed(e){return this.#u(e,`list`)}claim(e,t={}){this.#r.assertUnclaimed(e);let n=t.fresh===!0;this.#i?.beforeClaim(e,n,t.lease!==void 0);let r=t.copy===!0?void 0:this.#o(e,t.lease),i=()=>this.#r.open(e,n,r,()=>{let{file:t,unreadable:r}=this.#t.load(e);return this.#i===void 0?this.#d(e,t,r):this.#i.claimRead(e,n,t,r,()=>this.#p(e))},()=>this.#i?.discardHeld(e));if(r===void 0)return i();try{return this.#c(e,r,i)}catch(e){throw r.release(),e}}lend(e){this.#r.assertUnclaimed(e);let t=w(32).toString(`hex`),n=xe(`sha256`).update(t,`utf8`).digest(`hex`),r=this.#n.acquire(e,{leaseDigest:n});if(r.status!==`acquired`)throw this.#r.refusal(e,`has_writer`,{holder:i(r.holder)});let a=this.#r.lend(e,()=>{let t=this.#n.inspect(e);return t.status===`held`?t.holder:void 0}),o=!1;return Object.freeze({nonce:t,end:()=>{if(!o){o=!0;try{this.#n.endLease(e,n)}finally{a()}}}})}hasWriter(e){if(this.#r.has(e)||this.#r.isLent(e))return!0;let t=this.#n.inspect(e);return t.status===`held`&&t.holder.liveness!==`gone`}save(e,t={}){let n=e.id,r=this.#r.markerForSave(n,t.claim);if(r!==void 0){this.#c(n,r,()=>this.#a(e,t));return}this.#s(n,()=>this.#a(e,t))}delete(e,t){this.#r.markerForSave(e,void 0),this.#s(e,()=>{this.forget(e),t()})}#a(e,t){let n=e.id,r=this.#t.current(n),i=this.#i;if(i===void 0){this.#f(n,r),this.#t.replace(n,qe(e,void 0).stored);return}i.assertReplaceable(n,r);let a=i.prepare(n,Ke(e),t),o=t.handoff===!0;try{this.#t.replace(n,a.stored)}catch(e){throw i.wroteIfPresent(n,a,this.#m(n),o),e}i.wrote(n,a,o)}loadHeld(e){return this.#i?.held(e,this.#t.current(e))}exportHeld(e,t={}){return this.#i?.exportHeld(e,this.#t.current(e),t)}importHeld(e,t){if(this.#i===void 0)throw TypeError(`A store that seals nothing does not take a held record: it would write it in plaintext.`);this.#i.importHeld(e,t)}forget(e){this.#i?.forget(e)}#o(e,t){if(t===void 0){let t=this.#n.acquire(e);if(t.status===`acquired`)return t.handle;throw this.#r.refusal(e,`has_writer`,{holder:i(t.holder)})}let n=this.#n.takeOver(e,t);if(n.status===`acquired`)return n.handle;throw n.status===`absent`?this.#r.refusal(e,`released`,{lease:!0}):this.#r.refusal(e,`has_writer`,{holder:i(n.holder)})}#s(e,t){let n=this.#n.acquire(e);if(n.status!==`acquired`)throw this.#r.refusal(e,`has_writer`,{holder:i(n.holder)});try{return this.#c(e,n.handle,t)}finally{n.handle.release()}}#c(e,t,n){let r=t.withGuard(n);if(r.status===`ran`)return r.value;throw this.#r.refusal(e,r.status===`lost`?`released`:`has_writer`)}#l(e,t){try{let n=this.#r.markerForWrite(e);if(n!==void 0)return this.#c(e,n,t)}catch(e){if(s(e))return`has_writer`;throw e}let n=this.#n.acquire(e);if(n.status!==`acquired`)return`has_writer`;try{return this.#c(e,n.handle,t)}catch(e){if(s(e))return`has_writer`;throw e}finally{n.handle.release()}}#u(e,t){let{file:n,unreadable:r}=this.#t.load(e);return this.#i===void 0?this.#d(e,n,r):this.#i.read(e,n,r,()=>this.#p(e),t)}#d(e,t,n){if(t.kind===`absent`)return this.#p(e);let r=R(t);return r===void 0?n:_(r)?g(r)?dt:{status:`unsupported`,schemaVersion:void 0}:L(e,I(r))}#f(t,n){switch(n.kind){case`absent`:case`plain`:case`oversized`:return;case`unreadable`:throw new e(t,`unreadable`);case`sealed`:throw new e(t,g(n.bytes)?`no-keys`:`newer-format`)}}#p(e){return this.#t.rebuild?.(e)??mt}#m(e){try{return this.#t.current(e)}catch{return{kind:`unreadable`}}}};function yt(e){return typeof e==`object`&&e?e.code:void 0}function bt(e){let t=yt(e);return typeof t==`string`&&/^E[A-Z0-9]+$/.test(t)?`could not read the session file (${t})`:`could not read the session file`}function xt(e,t){let n=Buffer.alloc(Math.max(oe(e).size,t.length));t.copy(n,0);let r=t.length;for(;r<n.length;){let t=le(e,n,r,n.length-r,r);if(t===0)break;r+=t}return n.subarray(0,r)}const St=Object.freeze({status:`missing`}),W=`claims`;function Ct(e){let t=0,n=0;for(let{outcome:r}of e)r.status===`locked`&&(r.reason===`no-keys`?n+=1:t+=1);return n===0?{locked:t}:{locked:t,noKeys:n}}function wt(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var Tt=class{supportsClaimDiscard=!0;baseDir;ownedRoot;records;constructor(e,t){let n=H(t);this.records=new vt(n,{load:e=>this.loadFile(e),current:e=>this.readExisting(this.filePath(e)),replace:(e,t)=>{this.ensureDir(),be(this.filePath(e),t)}},he(fe(y(e),W),{operationLock:re(fe(y(e),W))}),t.releaseCommand===void 0?{}:{releaseCommand:t.releaseCommand}),this.baseDir=e,this.ownedRoot=t.ownedRoot;let r=this.records.authorship;r!==void 0&&(this.authorship=r)}claim(e,t){return this.filePath(e),this.records.claim(e,t)}lend(e){return this.filePath(e),this.records.lend(e)}hasWriter(e){return this.filePath(e),this.records.hasWriter(e)}ensureDir(){x(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){a(e);let t=y(this.baseDir),n=y(t,`${e}.json`);if(!n.startsWith(t+pe))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e,t={}){this.ensureDir(),this.filePath(e.id),this.records.save(e,t)}saveRestoreTransaction(e,t){if(!t?.claim)throw TypeError(`A live session claim is required for restore commit.`);try{return this.save(e,t),{status:`committed`}}catch(e){return{status:`unknown`,error:e}}}readExisting(e){let t;try{t=se(e,`r`)}catch(e){return yt(e)===`ENOENT`?{kind:`absent`}:{kind:`unreadable`}}try{let e=Buffer.alloc(f.length),n=le(t,e,0,e.length,0);return _(e.subarray(0,n))?{kind:`sealed`,bytes:xt(t,e)}:this.records.seals?{kind:`plain`,bytes:xt(t,e.subarray(0,n))}:{kind:`plain`}}catch{return{kind:`unreadable`}}finally{ie(t)}}load(e,t={}){return this.filePath(e),this.records.load(e,t)}loadFile(e){let t=this.filePath(e),n;try{n=ce(t)}catch(e){return yt(e)===`ENOENT`?{file:{kind:`absent`},unreadable:St}:{file:{kind:`unreadable`},unreadable:{status:`corrupt`,issues:[{path:``,message:bt(e)}]}}}try{S(t)}catch{}return{file:Qe(n),unreadable:St}}loadHeld(e){return this.filePath(e),this.records.loadHeld(e)}exportHeld(e,t){return this.filePath(e),this.records.exportHeld(e,t)}importHeld(e,t){this.filePath(e),this.records.importHeld(e,t)}list(){return this.scan().entries}scan(){let e=this.readAll();return{entries:e.filter(e=>e.outcome.status!==`locked`).sort(wt),...Ct(e)}}readAll(){return ae(this.baseDir)?ue(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})):[]}outcomeForListedId(e){return r(e)?this.records.listed(e):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){let t=this.filePath(e);this.records.delete(e,()=>{ae(t)&&de(t)})}};const Et=Object.freeze({kind:`does-not-open`}),Dt=Object.freeze({kind:`newer-format`}),Ot=Object.freeze({kind:`locked`,reason:`no-keys`}),kt=/^R(?:S(?:L[0-9]?)?)?$/;function At(e){return U(e),e===`plain`?void 0:e.sealer}function jt(e){return e.reason===`no-keys`?`no-keys`:`locked`}var G=class{#e;#t;constructor(e,t){this.#e=At(e),this.#t=t}encode(e,t){return this.#e===void 0?e:`
1
+ import{a as e,b as t,c as n,g as r,i,m as a,n as o,r as s,s as c,u as l}from"./session-claims-DB4Q00_J.js";import{ArtifactCorruptError as u,ArtifactLockedError as d,SEALED_ARTIFACT_MAGIC as f,SEALED_ARTIFACT_MAX_OVERHEAD_BYTES as p,createLogger as m,isArtifactCorruptError as h,isArtifactLockedError as g,isCurrentSealedArtifactBytes as _,isCurrentSealedArtifactLine as ee,isSealedArtifactBytes as v,isSealedArtifactLine as y}from"@robota-sdk/agent-core";import{createProcessOperationLock as te,createProcessOperationLock as ne}from"@robota-sdk/agent-os/node-lock";import{closeSync as re,existsSync as ie,fstatSync as ae,openSync as oe,readFileSync as se,readSync as ce,readdirSync as le,unlinkSync as ue}from"fs";import{join as de,resolve as b,sep as fe}from"path";import{OWNER_ONLY_FILE_MODE as x,PROCESS_OWNER_RECORD_NAME as pe,createProcessMarkers as me,createProcessScopedDirectory as he,ensureOwnerOnlyDirectory as S,removeDirectoryOnProcessExit as ge,stageOwnerOnlyFile as _e,sweepStaleProcessScopedDirectories as ve,tightenExistingFile as C,writeOwnerOnlyFile as ye}from"@robota-sdk/agent-core/node";import{Buffer as w}from"node:buffer";import{createHash as be,randomBytes as T}from"node:crypto";import{appendFileSync as xe,closeSync as E,constants as D,existsSync as Se,fstatSync as O,fsyncSync as k,linkSync as Ce,lstatSync as A,openSync as j,readFileSync as we,readSync as Te,readdirSync as Ee,realpathSync as De,renameSync as Oe,rmSync as ke,rmdirSync as Ae,unlinkSync as M,writeFileSync as je,writeSync as Me}from"node:fs";import{basename as Ne,dirname as N,extname as Pe,isAbsolute as Fe,join as P,relative as Ie,resolve as Le,win32 as Re}from"node:path";import{StableFileAuthorityError as ze,createStableRootedFileReader as Be}from"@robota-sdk/agent-os/file-authority";const Ve=`the sealed session file does not open for this session: it is damaged or sealed with other keys`,He=/^[0-9a-f]{64}$/;function Ue(e){return typeof e==`string`&&He.test(e)}function F(e){return be(`sha256`).update(e).digest(`hex`)}function We(e,t){return w.from(e.buffer,e.byteOffset,e.byteLength).equals(t)}function I(e){return{kind:`session-record`,id:e}}function L(e){return w.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`)}function Ge(e){return JSON.stringify({schemaVersion:2,record:e},null,2)}function Ke(e,t){let n=Ge(e),r=w.from(n,`utf8`);return{stored:t===void 0?r:t.sealBytes(r,I(e.id)),text:n}}function qe(e,t,n){if(!v(t))return`plain`;if(!_(t))return`newer-format`;let r;try{r=n.openBytes(t,I(e))}catch(e){if(g(e))throw e;return`does-not-open`}return r.fill(0),`sealed`}function Je(e,t,n){return n.sealBytes(t,I(e))}function Ye(e){let n;try{n=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let r=t(n);return r.status===`valid`?{status:`valid`,record:r.record}:r.status===`unsupported`?{status:`unsupported`,schemaVersion:r.schemaVersion,...r.cwd===void 0?{}:{cwd:r.cwd}}:{status:`corrupt`,issues:r.issues,...r.cwd===void 0?{}:{cwd:r.cwd}}}function R(e,t){let n=Ye(t);return n.status!==`valid`||n.record.id===e?n:{status:`corrupt`,issues:[{path:`id`,message:`the record belongs to another session id`}]}}function Xe(e,t){return R(e,L(t)).status===`valid`}function Ze(e){return e===void 0?{kind:`absent`}:v(e)?{kind:`sealed`,bytes:e}:{kind:`plain`,bytes:e}}function z(e){return e.kind===`sealed`||e.kind===`plain`?e.bytes:void 0}var Qe=class{#e=new Map;#t=new Set;#n=new Set;#r;constructor(e=()=>!1){this.#r=e}get size(){return this.#t.size}state(e){return this.#e.get(e)}hold(e,t){this.#i(e).held=t,this.#t.delete(e),this.#t.add(e);for(let e of this.#t){if(this.#t.size<=32)break;this.#e.get(e)?.held?.kind===`pinned`||this.#r(e)||this.dropHeld(e)}}holdHandoff(e,t){this.#i(e).handoff=t,this.#n.delete(e),this.#n.add(e);for(let e of this.#n){if(this.#n.size<=8)break;this.dropHandoff(e)}}dropHeld(e){this.#t.delete(e),this.#a(e,e=>delete e.held)}dropHandoff(e){this.#n.delete(e),this.#a(e,e=>delete e.handoff)}taint(e){this.#i(e).tainted=!0}untaint(e){this.#a(e,e=>e.tainted=!1)}setPending(e,t){this.#i(e).pendingDigest=t}clearPending(e){this.#a(e,e=>delete e.pendingDigest)}pending(){let e=[];for(let[t,n]of this.#e)n.pendingDigest!==void 0&&e.push([t,n.pendingDigest]);return e}forget(e){this.#t.delete(e),this.#n.delete(e),this.#a(e,e=>{delete e.held,delete e.handoff,delete e.pendingDigest})}#i(e){let t=this.#e.get(e);return t===void 0&&(t={tainted:!1},this.#e.set(e,t)),t}#a(e,t){let n=this.#e.get(e);n!==void 0&&(t(n),n.held===void 0&&n.handoff===void 0&&n.pendingDigest===void 0&&!n.tainted&&this.#e.delete(e))}};const $e=`rsh2.`,et={owner:!0,unverified:!1},tt=/^[A-Za-z0-9_-]+$/,nt=new TextDecoder(`utf-8`,{fatal:!0});function rt(e,t,n){return`${$e}${n?`owner`:`unverified`}.${e}.${w.from(t,`utf8`).toString(`base64url`)}`}function it(e){if(typeof e!=`string`||!e.startsWith($e))return;let[t,n,r,...i]=e.slice(5).split(`.`);if(t!==`owner`&&t!==`unverified`||i.length>0||n===void 0||r===void 0||!Ue(n)||!tt.test(r))return;let a=w.from(r,`base64url`);if(a.toString(`base64url`)===r)try{return{digest:n,text:nt.decode(a),owner:et[t]}}catch{return}}const at=`robota-authorship/v1 `,B=w.from(at,`ascii`),ot=/^[A-Za-z0-9_-]+$/;function st(e,t){let n=w.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64url`);return w.concat([w.from(`${at}${n}\n`,`ascii`),t])}function ct(e){let t=w.from(e.buffer,e.byteOffset,e.byteLength);if(t.length<B.length||!t.subarray(0,B.length).equals(B))return{envelope:e,tag:void 0};let n=t.indexOf(10,B.length);if(n<0)return{envelope:e,tag:`malformed`};let r=t.subarray(B.length,n).toString(`latin1`),i=e.subarray(n+1);if(!ot.test(r))return{envelope:i,tag:`malformed`};let a=w.from(r,`base64url`);return a.length!==32||a.toString(`base64url`)!==r?{envelope:i,tag:`malformed`}:{envelope:i,tag:a}}const lt={probe:{writer:!1,takes:!1,holds:!1,taints:!0},hold:{writer:!0,takes:!0,holds:!0,taints:!0},list:{writer:!1,takes:!1,holds:!1,taints:!1},held:{writer:!0,takes:!0,holds:!1,taints:!0},export:{writer:!0,takes:!1,holds:!1,taints:!0},claim:{writer:!0,takes:!0,holds:!0,taints:!0},save:{writer:!0,takes:!1,holds:!1,taints:!1}},ut=Object.freeze({status:`locked`,reason:`no-keys`}),dt=Object.freeze({status:`locked`,reason:`changed`}),ft=Object.freeze({status:`locked`}),pt=Object.freeze({status:`missing`});function V(e,t,n,r){return{status:`valid`,record:e.record,authorship:t?`verified`:`unverified`,...n===void 0?{}:{digest:n},...r?{diverged:!0}:{}}}function H(e,t,n){let r;try{r=e.openBytes(n,I(t))}catch(e){return g(e)?e.reason===`no-keys`?{kind:`no-keys`}:{kind:`locked`}:{kind:`does-not-open`}}try{let{envelope:n,tag:i}=ct(r),a=!1;if(i instanceof Uint8Array&&e.verifyAuthorship!==void 0)try{a=e.verifyAuthorship(n,i,I(t))===!0}catch{a=!1}return{kind:`text`,text:L(n),verified:a}}finally{r.fill(0)}}function mt(e,t,n){let r,i=!1;if(!v(t))r=L(t);else{if(!_(t))return{status:`unsupported`,schemaVersion:void 0};let a=H(n,e,t);if(a.kind===`locked`)return ft;if(a.kind===`no-keys`)return ut;if(a.kind===`does-not-open`)return{status:`corrupt`,issues:[{path:``,message:Ve}]};r=a.text,i=a.verified}let a=R(e,r);return a.status===`valid`?V(a,i,F(t),!1):a}var ht=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n,r,i){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,e.tagAuthorship!==void 0&&e.onUnlock!==void 0&&(this.#a=()=>this.#g(),e.onUnlock(this.#a))}read(e,t,n,r,i){let a=this.guarded(e,t,i);if(a!==void 0)return a;if(t.kind===`absent`){let t=r();return t.status===`valid`?this.#l(e,t,`unverified`,void 0,i,!1):t}let o=z(t);return o===void 0?n:this.decode(e,o,i)}decode(e,t,n){let r,i=!1;if(!v(t))r=L(t);else{if(!_(t))return{status:`unsupported`,schemaVersion:void 0};let n=H(this.#e,e,t);if(n.kind===`locked`)return ft;if(n.kind===`no-keys`)return ut;if(n.kind===`does-not-open`)return{status:`corrupt`,issues:[{path:``,message:Ve}]};r=n.text,i=n.verified}let a=R(e,r);if(a.status!==`valid`)return a;let o=F(t),s=this.#n.state(e),c=i||this.#s(s,s?.held,o)?`owner`:`unverified`;return lt[n].holds&&this.#n.hold(e,{digest:o,text:r,kind:c}),this.#l(e,a,c,o,n,!1)}claimRead(e,t,n,r,i){let a=this.#n.state(e)?.held,o=z(n);return!t&&a!==void 0&&o!==void 0&&F(o)===a.digest?this.#c(e,a,`claim`,!1):this.read(e,n,r,i,`claim`)}beforeClaim(e,t,n){if(this.#n.state(e)?.held?.kind===`pinned`&&!n)throw this.#r.refusal(e,`has_writer`);t&&(this.#n.dropHeld(e),this.#n.dropHandoff(e))}guarded(e,t,n){let r=this.#n.state(e),i=this.#o(e,r),a=i?void 0:r?.handoff;if(!i&&a===void 0)return;let o=lt[n],s=z(t),c=s===void 0?void 0:F(s);if(a!==void 0)return o.takes&&this.#n.dropHandoff(e),s===void 0||c!==a.digest?dt:(o.takes&&this.#n.hold(e,a),this.#c(e,a,n,!1));let l=r?.held;if(l!==void 0&&c===l.digest)return this.#c(e,l,n,!1);let u=!1;if(l?.kind!==`pinned`&&t.kind===`sealed`&&_(t.bytes)){let r=H(this.#e,e,t.bytes);if(r.kind===`text`&&r.verified&&c!==void 0){let t=R(e,r.text);if(t.status===`valid`)return n!==`save`&&this.#n.hold(e,{digest:c,text:r.text,kind:`owner`}),V(t,!0,c,!1)}u=r.kind===`locked`}return t.kind===`absent`?l===void 0?pt:this.#c(e,l,n,!0):o.writer||l===void 0?u?ft:dt:this.#c(e,l,n,!0)}assertReplaceable(t,n){let r=this.guarded(t,n,`save`);if(r!==void 0){if(r.status!==`locked`)return;throw new e(t,r.reason===`changed`?`changed`:`locked`)}switch(n.kind){case`absent`:case`plain`:return;case`unreadable`:case`oversized`:throw new e(t,`unreadable`);case`sealed`:break}let i=n.bytes;if(!_(i))throw new e(t,`newer-format`);let a=this.#n.state(t)?.held;if(a!==void 0&&a.digest===F(i))return;let o=H(this.#e,t,i);if(o.kind!==`text`)throw new e(t,a===void 0?o.kind===`locked`||o.kind===`no-keys`?o.kind:`does-not-open`:`changed`)}prepare(e,t,n){let r=w.from(t,`utf8`),i=this.#d(e,n),a=r,o=!1;if(i===`owner`){let t=this.#f(e,r);t===`locked`?o=n.handoff!==!0:t!==void 0&&(a=st(t,r))}try{return{stored:this.#e.sealBytes(a,I(e)),text:t,heldAs:i,tagPending:o}}finally{a!==r&&a.fill(0)}}wrote(e,t,n){let r=this.#n.state(e)?.held,i=t.heldAs===`pinned`&&r?.kind===`pinned`&&r.vouched,a={digest:F(t.stored),text:t.text,kind:t.heldAs,...i===!0?{vouched:i}:{}};n&&!this.#r.has(e)&&t.heldAs!==`pinned`?(this.#n.dropHeld(e),this.#n.holdHandoff(e,a)):(this.#n.dropHandoff(e),this.#n.hold(e,a)),t.tagPending?this.#n.setPending(e,a.digest):this.#n.clearPending(e)}wroteIfPresent(e,t,n,r){n.kind===`sealed`&&We(n.bytes,t.stored)&&this.wrote(e,t,r)}held(e,t){let n=this.guarded(e,t,`held`);if(n!==void 0)return n;let r=this.#n.state(e)?.held;if(r===void 0)return;let i=z(t);return i===void 0||F(i)!==r.digest?dt:this.#c(e,r,`held`,!1)}exportHeld(e,t,n){if(t.kind!==`sealed`||!_(t.bytes))return;let r=F(t.bytes),i=(e,t)=>rt(r,e,t===`owner`),a=this.#n.state(e);if(this.#o(e,a)){if(n.handoffOnly===!0)return;let a=this.guarded(e,t,`export`),o=this.#n.state(e)?.held;return a?.status!==`valid`||a.diverged===!0||o?.digest!==r?void 0:i(o.text,a.authorship===`verified`?`owner`:`unverified`)}let o=a?.handoff;if(o!==void 0)return n.keep!==!0&&this.#n.dropHandoff(e),o.digest===r?(this.#u(e,o.kind,`export`),i(o.text,o.kind)):void 0;if(n.handoffOnly===!0)return;let s=H(this.#e,e,t.bytes);if(s.kind!==`text`||R(e,s.text).status!==`valid`)return;let c=s.verified||this.#s(a,a?.held,r)?`owner`:`unverified`;return this.#u(e,c,`export`),i(s.text,c)}importHeld(e,t){let n=it(t);if(n===void 0)throw TypeError(`The held record is not a token this build issues.`);if(R(e,n.text).status!==`valid`)throw TypeError(`The held record is not a valid record of this session.`);this.#r.assertUnclaimed(e),this.#n.dropHandoff(e),this.#n.hold(e,{digest:n.digest,text:n.text,kind:`pinned`,...n.owner?{vouched:!0}:{}})}adopt(e,t){if(!Ue(t))return`changed`;let n=this.#n.state(e),r=this.#t.current(e),i=z(r),a=i===void 0?void 0:F(i),o=n?.held;if(o!==void 0&&o.digest===t&&o.kind!==`pinned`)return this.#n.hold(e,{...o,kind:`owner`}),this.#n.untaint(e),a===t&&this.#m(e,t,o.text,!0)===`pending`?`pending`:`adopted`;if(i===void 0||a!==t||this.#e.tagAuthorship===void 0)return`changed`;let s=this.#p(e,r,i);if(s===`locked`)return this.#n.untaint(e),this.#n.setPending(e,t),`pending`;if(s===void 0||R(e,s).status!==`valid`)return`changed`;let c=this.#m(e,t,s,!1);return c!==`changed`&&this.#n.untaint(e),c}heldDigest(e){return this.#n.state(e)?.held?.digest}forget(e){this.#n.forget(e)}discardHeld(e){this.#n.dropHeld(e)}onUnlock(e){return this.#e.onUnlock?.(e)??(()=>void 0)}#o(e,t){return this.#r.has(e)||t?.held?.kind===`pinned`}#s(e,t,n){return e?.pendingDigest===n||t?.kind===`owner`&&t.digest===n}#c(e,t,n,r){let i=R(e,t.text);if(i.status!==`valid`)return i;if(t.kind===`pinned`)return V(i,t.vouched===!0,t.digest,r);let a=this.#s(this.#n.state(e),t,t.digest)?`owner`:`unverified`;return this.#l(e,i,a,t.digest,n,r)}#l(e,t,n,r,i,a){return this.#u(e,n,i),V(t,n===`owner`,r,a)}#u(e,t,n){t!==`owner`&&lt[n].taints&&!this.#o(e,this.#n.state(e))&&this.#n.taint(e)}#d(e,t){let n=this.#n.state(e),r=n?.held??n?.handoff;return r?.kind===`pinned`?`pinned`:t.provenance===`unverified`||!this.#r.has(e)&&n?.tainted===!0?`unverified`:r===void 0?t.provenance===`owner`?`owner`:`unverified`:r.kind}#f(e,t){if(this.#e.tagAuthorship!==void 0)try{return this.#e.tagAuthorship(t,I(e))}catch(e){if(g(e))return`locked`;throw e}}#p(e,t,n){if(t.kind!==`sealed`)return L(n);if(!_(n))return;let r=H(this.#e,e,n);return r.kind===`locked`?`locked`:r.kind===`text`?r.text:void 0}#m(e,t,n,r){let i=w.from(n,`utf8`),a=this.#f(e,i);return a===`locked`?(this.#n.setPending(e,t),`pending`):a===void 0||this.#h(e,i,n,a,t,r)?`adopted`:`changed`}#h(e,t,n,r,i,a){let o=st(r,t),s;try{s=this.#e.sealBytes(o,I(e))}finally{o.fill(0)}let c=z(this.#t.current(e));if(c===void 0||F(c)!==i)return!1;let l={stored:s,text:n,heldAs:`owner`,tagPending:!1};try{this.#t.replace(e,s)}catch(t){throw a&&this.wroteIfPresent(e,l,this.#t.current(e),!1),t}return this.#n.clearPending(e),a&&this.wrote(e,l,!1),!0}#g(){for(let[e,t]of this.#n.pending()){this.#n.clearPending(e);try{this.#i(e,()=>this.#_(e,t))}catch{}}}#_(e,t){let n=this.#t.current(e),r=z(n);if(r===void 0||F(r)!==t)return;let i=this.#n.state(e)?.held,a=i?.digest===t,o=a?i.text:this.#p(e,n,r);if(o===void 0||o===`locked`||R(e,o).status!==`valid`)return;let s=w.from(o,`utf8`),c=this.#f(e,s);c instanceof Uint8Array&&this.#h(e,s,o,c,t,a)}};function gt(e){let t=e;if(typeof t?.acquire!=`function`||typeof t.takeOver!=`function`||typeof t.endLease!=`function`||typeof t.inspect!=`function`)throw TypeError(`A session store holds a writer marker for every id it writes: build it with the markers of its claims directory.`)}function U(e){if(typeof e!=`object`||!e)throw TypeError(`Session store options must be an object, such as { sealing }.`);return W(e.sealing),e.sealing}function W(e){if(e===`plain`)return;let t=typeof e==`object`&&e?e.sealer:void 0;if(!(typeof t==`object`&&t&&typeof t.sealBytes==`function`&&typeof t.openBytes==`function`))throw TypeError(`A session store states how it seals: { sealer }, or 'plain'.`)}var _t=class{#e;#t;#n;#r;#i;authorship;constructor(e,t,n,r={}){if(W(e),gt(n),this.#e=e===`plain`?void 0:e.sealer,this.#t=t,this.#n=n,this.#r=new o(r.releaseCommand===void 0?{}:{releaseCommand:r.releaseCommand},{pid:process.pid,windows:process.platform===`win32`}),this.#e===void 0){this.#i=void 0,this.authorship=void 0;return}let i=new ht(this.#e,t,new Qe(e=>this.#r.has(e)),this.#r,(e,t)=>this.#l(e,t));this.#i=i,this.authorship=Object.freeze({adopt:(e,t)=>{a(e);let n=this.#l(e,()=>i.adopt(e,t));return n===`has_writer`?`has_writer`:n},heldDigest:e=>(a(e),i.heldDigest(e)),onUnlock:e=>i.onUnlock(e)})}get seals(){return this.#e!==void 0}load(e,t={}){return this.#u(e,t.hold===!0?`hold`:`probe`)}listed(e){return this.#u(e,`list`)}claim(e,t={}){this.#r.assertUnclaimed(e);let n=t.fresh===!0;this.#i?.beforeClaim(e,n,t.lease!==void 0);let r=t.copy===!0?void 0:this.#o(e,t.lease),i=()=>this.#r.open(e,n,r,()=>{let{file:t,unreadable:r}=this.#t.load(e);return this.#i===void 0?this.#d(e,t,r):this.#i.claimRead(e,n,t,r,()=>this.#p(e))},()=>this.#i?.discardHeld(e));if(r===void 0)return i();try{return this.#c(e,r,i)}catch(e){throw r.release(),e}}lend(e){this.#r.assertUnclaimed(e);let t=T(32).toString(`hex`),n=be(`sha256`).update(t,`utf8`).digest(`hex`),r=this.#n.acquire(e,{leaseDigest:n});if(r.status!==`acquired`)throw this.#r.refusal(e,`has_writer`,{holder:i(r.holder)});let a=this.#r.lend(e,()=>{let t=this.#n.inspect(e);return t.status===`held`?t.holder:void 0}),o=!1;return Object.freeze({nonce:t,end:()=>{if(!o){o=!0;try{this.#n.endLease(e,n)}finally{a()}}}})}hasWriter(e){if(this.#r.has(e)||this.#r.isLent(e))return!0;let t=this.#n.inspect(e);return t.status===`held`&&t.holder.liveness!==`gone`}save(e,t={}){let n=e.id,r=this.#r.markerForSave(n,t.claim);if(r!==void 0){this.#c(n,r,()=>this.#a(e,t));return}this.#s(n,()=>this.#a(e,t))}delete(e,t){this.#r.markerForSave(e,void 0),this.#s(e,()=>{this.forget(e),t()})}#a(e,t){let n=e.id,r=this.#t.current(n),i=this.#i;if(i===void 0){this.#f(n,r),this.#t.replace(n,Ke(e,void 0).stored);return}i.assertReplaceable(n,r);let a=i.prepare(n,Ge(e),t),o=t.handoff===!0;try{this.#t.replace(n,a.stored)}catch(e){throw i.wroteIfPresent(n,a,this.#m(n),o),e}i.wrote(n,a,o)}loadHeld(e){return this.#i?.held(e,this.#t.current(e))}exportHeld(e,t={}){return this.#i?.exportHeld(e,this.#t.current(e),t)}importHeld(e,t){if(this.#i===void 0)throw TypeError(`A store that seals nothing does not take a held record: it would write it in plaintext.`);this.#i.importHeld(e,t)}forget(e){this.#i?.forget(e)}#o(e,t){if(t===void 0){let t=this.#n.acquire(e);if(t.status===`acquired`)return t.handle;throw this.#r.refusal(e,`has_writer`,{holder:i(t.holder)})}let n=this.#n.takeOver(e,t);if(n.status===`acquired`)return n.handle;throw n.status===`absent`?this.#r.refusal(e,`released`,{lease:!0}):this.#r.refusal(e,`has_writer`,{holder:i(n.holder)})}#s(e,t){let n=this.#n.acquire(e);if(n.status!==`acquired`)throw this.#r.refusal(e,`has_writer`,{holder:i(n.holder)});try{return this.#c(e,n.handle,t)}finally{n.handle.release()}}#c(e,t,n){let r=t.withGuard(n);if(r.status===`ran`)return r.value;throw this.#r.refusal(e,r.status===`lost`?`released`:`has_writer`)}#l(e,t){try{let n=this.#r.markerForWrite(e);if(n!==void 0)return this.#c(e,n,t)}catch(e){if(s(e))return`has_writer`;throw e}let n=this.#n.acquire(e);if(n.status!==`acquired`)return`has_writer`;try{return this.#c(e,n.handle,t)}catch(e){if(s(e))return`has_writer`;throw e}finally{n.handle.release()}}#u(e,t){let{file:n,unreadable:r}=this.#t.load(e);return this.#i===void 0?this.#d(e,n,r):this.#i.read(e,n,r,()=>this.#p(e),t)}#d(e,t,n){if(t.kind===`absent`)return this.#p(e);let r=z(t);return r===void 0?n:v(r)?_(r)?ut:{status:`unsupported`,schemaVersion:void 0}:R(e,L(r))}#f(t,n){switch(n.kind){case`absent`:case`plain`:case`oversized`:return;case`unreadable`:throw new e(t,`unreadable`);case`sealed`:throw new e(t,_(n.bytes)?`no-keys`:`newer-format`)}}#p(e){return this.#t.rebuild?.(e)??pt}#m(e){try{return this.#t.current(e)}catch{return{kind:`unreadable`}}}};function vt(e){return typeof e==`object`&&e?e.code:void 0}function yt(e){let t=vt(e);return typeof t==`string`&&/^E[A-Z0-9]+$/.test(t)?`could not read the session file (${t})`:`could not read the session file`}function bt(e,t){let n=Buffer.alloc(Math.max(ae(e).size,t.length));t.copy(n,0);let r=t.length;for(;r<n.length;){let t=ce(e,n,r,n.length-r,r);if(t===0)break;r+=t}return n.subarray(0,r)}const xt=Object.freeze({status:`missing`}),G=`claims`;function St(e){let t=0,n=0;for(let{outcome:r}of e)r.status===`locked`&&(r.reason===`no-keys`?n+=1:t+=1);return n===0?{locked:t}:{locked:t,noKeys:n}}function Ct(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var wt=class{supportsClaimDiscard=!0;baseDir;ownedRoot;records;constructor(e,t){let n=U(t);this.records=new _t(n,{load:e=>this.loadFile(e),current:e=>this.readExisting(this.filePath(e)),replace:(e,t)=>{this.ensureDir(),ye(this.filePath(e),t)}},me(de(b(e),G),{operationLock:ne(de(b(e),G))}),t.releaseCommand===void 0?{}:{releaseCommand:t.releaseCommand}),this.baseDir=e,this.ownedRoot=t.ownedRoot;let r=this.records.authorship;r!==void 0&&(this.authorship=r)}claim(e,t){return this.filePath(e),this.records.claim(e,t)}lend(e){return this.filePath(e),this.records.lend(e)}hasWriter(e){return this.filePath(e),this.records.hasWriter(e)}ensureDir(){S(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){a(e);let t=b(this.baseDir),n=b(t,`${e}.json`);if(!n.startsWith(t+fe))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e,t={}){this.ensureDir(),this.filePath(e.id),this.records.save(e,t)}saveRestoreTransaction(e,t){if(!t?.claim)throw TypeError(`A live session claim is required for restore commit.`);try{return this.save(e,t),{status:`committed`}}catch(e){return{status:`unknown`,error:e}}}readExisting(e){let t;try{t=oe(e,`r`)}catch(e){return vt(e)===`ENOENT`?{kind:`absent`}:{kind:`unreadable`}}try{let e=Buffer.alloc(f.length),n=ce(t,e,0,e.length,0);return v(e.subarray(0,n))?{kind:`sealed`,bytes:bt(t,e)}:this.records.seals?{kind:`plain`,bytes:bt(t,e.subarray(0,n))}:{kind:`plain`}}catch{return{kind:`unreadable`}}finally{re(t)}}load(e,t={}){return this.filePath(e),this.records.load(e,t)}loadFile(e){let t=this.filePath(e),n;try{n=se(t)}catch(e){return vt(e)===`ENOENT`?{file:{kind:`absent`},unreadable:xt}:{file:{kind:`unreadable`},unreadable:{status:`corrupt`,issues:[{path:``,message:yt(e)}]}}}try{C(t)}catch{}return{file:Ze(n),unreadable:xt}}loadHeld(e){return this.filePath(e),this.records.loadHeld(e)}exportHeld(e,t){return this.filePath(e),this.records.exportHeld(e,t)}importHeld(e,t){this.filePath(e),this.records.importHeld(e,t)}list(){return this.scan().entries}scan(){let e=this.readAll();return{entries:e.filter(e=>e.outcome.status!==`locked`).sort(Ct),...St(e)}}readAll(){return ie(this.baseDir)?le(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})):[]}outcomeForListedId(e){return r(e)?this.records.listed(e):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){let t=this.filePath(e);this.records.delete(e,()=>{ie(t)&&ue(t)})}};const Tt=Object.freeze({kind:`does-not-open`}),Et=Object.freeze({kind:`newer-format`}),Dt=Object.freeze({kind:`locked`,reason:`no-keys`}),Ot=/^R(?:S(?:L[0-9]?)?)?$/;function kt(e){return W(e),e===`plain`?void 0:e.sealer}function At(e){return e.reason===`no-keys`?`no-keys`:`locked`}var K=class{#e;#t;constructor(e,t){this.#e=kt(e),this.#t=t}encode(e,t){return this.#e===void 0?e:`
2
2
  ${this.#e.sealLine(e,{kind:this.#t,id:t})}
3
- `}decode(e,t){try{return this.#n(e,t)}catch{return Et}}openText(e,t){let n=K(e),r=e=>this.#n(e,t);return Mt((function*(){for(let e of n)yield r(e)})())}#n(e,t){if(!v(e))return{kind:`lines`,lines:[e]};if(!te(e))return Dt;if(this.#e===void 0)return Ot;let n;try{n=this.#e.openLine(e,{kind:this.#t,id:t})}catch(e){if(h(e))return{kind:`locked`,reason:jt(e)};if(ee(e))return Et;throw e}return{kind:`lines`,lines:n.split(`
4
- `).filter(e=>e.length>0)}}};function K(e){let t=e.split(`
5
- `),n=t[t.length-1];return n.length>0&&(v(n)||kt.test(n))&&t.pop(),t}function Mt(e){let t=[],r=0;for(let i of e)switch(r+=1,i.kind){case`lines`:t.push(i.lines.join(`
3
+ `}decode(e,t){try{return this.#n(e,t)}catch{return Tt}}openText(e,t){let n=q(e),r=e=>this.#n(e,t);return jt((function*(){for(let e of n)yield r(e)})())}#n(e,t){if(!y(e))return{kind:`lines`,lines:[e]};if(!ee(e))return Et;if(this.#e===void 0)return Dt;let n;try{n=this.#e.openLine(e,{kind:this.#t,id:t})}catch(e){if(g(e))return{kind:`locked`,reason:At(e)};if(h(e))return Tt;throw e}return{kind:`lines`,lines:n.split(`
4
+ `).filter(e=>e.length>0)}}};function q(e){let t=e.split(`
5
+ `),n=t[t.length-1];return n.length>0&&(y(n)||Ot.test(n))&&t.pop(),t}function jt(e){let t=[],r=0;for(let i of e)switch(r+=1,i.kind){case`lines`:t.push(i.lines.join(`
6
6
  `));break;case`locked`:throw new d(i.reason);case`does-not-open`:throw new u;case`newer-format`:throw new n(`UNSUPPORTED_VERSION`,[{path:`line ${r}`,message:`the line is sealed in a framing version this build does not open`}])}return t.join(`
7
- `)}function q(e,t,n){return e===`PAYLOAD_UNREADABLE`?new c(e,`External payload is sealed and does not open here: ${t}.`,{relativePath:t}):new c(e,`External payload exceeds the remaining byte budget of ${n}.`,{relativePath:t,expected:n})}var Nt=class{#e;#t=new Map;constructor(e){this.#e=At(e)}place(e,t,n,r){let i=l(e,t,n);if(this.#e===void 0)return r({relativePath:i.relativePath,data:n,contentAddressed:!0}),i;let a=this.#t.get(e)??new Map,o=a.get(t);if(o!==void 0)return{...i,relativePath:o};let s=`${e}.payloads/${w(16).toString(`base64url`)}.sealed`,c=Buffer.from(n,`utf8`),u;try{u=this.#e.sealBytes(c,{kind:`session-log-payload`,id:e})}finally{c.fill(0)}return r({relativePath:s,data:u,contentAddressed:!1}),a.set(t,s),this.#t.set(e,a),{...i,relativePath:s}}rawBudget(e){return this.#e===void 0?e:Math.min(e+p,2**53-1)}open(e,t,n,r){if(this.#e===void 0)return e;if(!_(e)){if(e.byteLength>t)throw q(`MAX_TOTAL_BYTES_EXCEEDED`,r,t);return e}if(!g(e)||n===void 0)throw q(`PAYLOAD_UNREADABLE`,r,t);let i;try{i=this.#e.openBytes(e,{kind:`session-log-payload`,id:n})}catch(e){throw h(e)?new d(jt(e)):ee(e)?q(`PAYLOAD_UNREADABLE`,r,t):e}if(i.byteLength>t)throw i.fill(0),q(`MAX_TOTAL_BYTES_EXCEEDED`,r,t);return i}};function Pt(e){return{kind:`session-log-payload`,id:e}}function Ft(e,t,n){if(!_(e))return`plain`;if(!g(e))return`newer-format`;let r;try{r=n.openBytes(e,Pt(t))}catch(e){if(h(e))throw e;return`does-not-open`}return r.fill(0),`sealed`}function It(e,t,n){return n.sealBytes(e,Pt(t))}function Lt(e){return e.endsWith(`\r`)?e.slice(0,-1):e}var Rt=class{ownerId;sealedLines=0;carriedLines=0;#e;constructor(e,t){this.ownerId=t,this.#e=new G({sealer:e},`session-log-line`)}rewrite(e,t,n){for(let r of e){let e=Lt(r);if(e.length===0)continue;if(v(e)){t.write(`${n?`
7
+ `)}function Mt(e,t,n){return e===`PAYLOAD_UNREADABLE`?new c(e,`External payload is sealed and does not open here: ${t}.`,{relativePath:t}):new c(e,`External payload exceeds the remaining byte budget of ${n}.`,{relativePath:t,expected:n})}var Nt=class{#e;#t=new Map;constructor(e){this.#e=kt(e)}place(e,t,n,r){let i=l(e,t,n);if(this.#e===void 0)return r({relativePath:i.relativePath,data:n,contentAddressed:!0}),i;let a=this.#t.get(e)??new Map,o=a.get(t);if(o!==void 0)return{...i,relativePath:o};let s=`${e}.payloads/${T(16).toString(`base64url`)}.sealed`,c=Buffer.from(n,`utf8`),u;try{u=this.#e.sealBytes(c,{kind:`session-log-payload`,id:e})}finally{c.fill(0)}return r({relativePath:s,data:u,contentAddressed:!1}),a.set(t,s),this.#t.set(e,a),{...i,relativePath:s}}rawBudget(e){return this.#e===void 0?e:Math.min(e+p,2**53-1)}open(e,t,n,r){if(this.#e===void 0)return e;if(!v(e)){if(e.byteLength>t)throw Mt(`MAX_TOTAL_BYTES_EXCEEDED`,r,t);return e}if(!_(e)||n===void 0)throw Mt(`PAYLOAD_UNREADABLE`,r,t);let i;try{i=this.#e.openBytes(e,{kind:`session-log-payload`,id:n})}catch(e){throw g(e)?new d(At(e)):h(e)?Mt(`PAYLOAD_UNREADABLE`,r,t):e}if(i.byteLength>t)throw i.fill(0),Mt(`MAX_TOTAL_BYTES_EXCEEDED`,r,t);return i}};function Pt(e){return{kind:`session-log-payload`,id:e}}function Ft(e,t,n){if(!v(e))return`plain`;if(!_(e))return`newer-format`;let r;try{r=n.openBytes(e,Pt(t))}catch(e){if(g(e))throw e;return`does-not-open`}return r.fill(0),`sealed`}function It(e,t,n){return n.sealBytes(e,Pt(t))}function Lt(e){return e.endsWith(`\r`)?e.slice(0,-1):e}var Rt=class{ownerId;sealedLines=0;carriedLines=0;#e;constructor(e,t){this.ownerId=t,this.#e=new K({sealer:e},`session-log-line`)}rewrite(e,t,n){for(let r of e){let e=Lt(r);if(e.length===0)continue;if(y(e)){t.write(`${n?`
8
8
  `:``}${e}
9
9
  `),this.carriedLines+=1;continue}let i=this.#e.encode(`${e}
10
- `,this.ownerId);t.write(n?i:i.slice(1)),this.sealedLines+=1}}};function zt(e){return K(e).filter(e=>{let t=Lt(e);return t.length>0&&!v(t)}).length}function Bt(e,t,n){let r=new Rt(n,t),i=[];return r.rewrite(K(e),{write:e=>i.push(e)},!1),{text:i.join(``),sealedLines:r.sealedLines,carriedLines:r.carriedLines}}const Vt=m(`NodeSessionLogSink`);var Ht=class{logDirectory;externalPayloadSink=this;enabled;lines;payloads;constructor(e,t){this.logDirectory=e;let n=H(t);this.lines=new G(n,`session-log-line`),this.payloads=new Nt(n);try{x(e),this.enabled=!0}catch(t){this.enabled=!1,Vt.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(e,t){if(a(e),!this.enabled)return;let n=N(this.logDirectory,`${e}.jsonl`),r=this.lines.encode(t,e);S(n),Se(n,r,{mode:b})}writeJson(e,t,n){return this.payloads.place(e,t,n,t=>this.writePayload(e,t))}writePayload(e,t){if(!this.enabled)return;x(N(this.logDirectory,`${e}.payloads`));let n=N(this.logDirectory,t.relativePath);try{Me(n,t.data,{...typeof t.data==`string`?{encoding:`utf8`}:{},mode:b,flag:`wx`})}catch(e){if(!t.contentAddressed||e.code!==`EEXIST`)throw e;S(n)}}};function Ut(e){if(e.trim().length===0||e.includes(`\0`)||Ie(e)||ze.isAbsolute(e))throw Gt(e);let t=e.split(/[\\/]+/u);if(t.some(e=>e===`.`||e===`..`))throw Gt(e);return t}function Wt(e){if(!Number.isFinite(e)||!Number.isSafeInteger(e)||e<0)throw new c(`INVALID_LIMIT`,`External-payload maxBytes must be a finite, non-negative safe integer.`,{actual:String(e)})}function Gt(e,t){return new c(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function Kt(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?Gt(t,e):e.code===`UNSUPPORTED_BACKEND`?new c(`STABLE_PAYLOAD_READ_UNAVAILABLE`,`Stable root-relative external-payload reads are unavailable on this host.`,{relativePath:t},e):e.code===`OVER_BUDGET`?new c(`MAX_TOTAL_BYTES_EXCEEDED`,`External payload exceeds the remaining byte budget of ${n}.`,{relativePath:t,expected:n},e):new c(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${t}.`,{relativePath:t},e)}function qt(e){let t=e.length===2?e[0]:void 0;if(!(t===void 0||!t.endsWith(`.payloads`)))return t.slice(0,-9)||void 0}var Jt=class{baseDirectory;payloads;ownerId;constructor(e,t){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=Re(e),this.payloads=new Nt(H(t)),this.ownerId=t.ownerId}readBytes(e,t){Wt(t);let n=Ut(e),r=this.readStored(e,n,t);if(r!==void 0)return this.payloads.open(r,t,this.ownerId??qt(n),e)}readStored(e,t,n){try{let e=Ve(this.baseDirectory);try{return e.readBytes(t,this.payloads.rawBudget(n))}finally{e.close()}}catch(t){throw t instanceof c?t:t instanceof Be?Kt(t,e,n):new c(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},t)}}},Yt=class{logFile;externalPayloadSource;lines;ownerId;constructor(e,t){if(this.logFile=e,e.trim().length===0)throw Error(`Session log-file path must not be empty.`);let n=H(t);this.lines=new G(n,`session-log-line`),this.ownerId=Pe(e,Fe(e)),this.externalPayloadSource=new Jt(M(e),{sealing:n,ownerId:this.ownerId})}readText(){if(Ce(this.logFile))return this.lines.openText(Te(this.logFile,`utf8`),this.ownerId)}readStoredLines(){if(Ce(this.logFile))return K(Te(this.logFile,`utf8`)).map(e=>this.lines.decode(e,this.ownerId))}};function J(e){return e?.code}function Y(e){let t;try{t=k(e)}catch(e){if(J(e)===`ENOENT`)return{status:`missing`};throw e}if(!t.isFile())return{status:`refused`,reason:`not-a-regular-file`};let n;try{n=A(e,E.O_RDONLY|(E.O_NOFOLLOW??0))}catch(e){if(J(e)===`ENOENT`)return{status:`missing`};if(J(e)===`ELOOP`)return{status:`refused`,reason:`not-a-regular-file`};throw e}let r=D(n),i=r.isFile()&&r.ino===t.ino&&r.dev===t.dev;return!i||r.nlink>1?(T(n),{status:`refused`,reason:i?`hard-linked`:`not-a-regular-file`}):{status:`open`,descriptor:n}}function Xt(e,t,n){let r=Buffer.alloc(Math.max(0,n-t)),i=0;for(;i<r.length;){let n=Ee(e,r,i,r.length-i,t+i);if(n===0)break;i+=n}return r.subarray(0,i)}function X(e){return Xt(e,0,D(e).size)}function*Zt(e){let t=0;for(;t<e.length;){let n=e.indexOf(10,t),r=n===-1?e.length:n;yield e.toString(`utf8`,t,r),t=r+1}}function Qt(e,t){let n=Buffer.from(t,`utf8`),r=0;for(;r<n.length;)r+=Ne(e,n,r,n.length-r)}var $t=class{descriptor;#e=[];#t=0;constructor(e){this.descriptor=e}write(e){this.#e.push(e),this.#t+=e.length,this.#t>=1048576&&this.flush()}flush(){this.#e.length!==0&&(Qt(this.descriptor,this.#e.join(``)),this.#e=[],this.#t=0)}};function en(e){let t;try{t=A(e,E.O_RDONLY),O(t)}catch{}finally{t!==void 0&&T(t)}}function tn(e){try{j(e)}catch{}}function nn(e){let t=Y(e);if(t.status!==`open`)return 0;try{return K(X(t.descriptor).toString(`utf8`)).filter(e=>e.length>0&&!v(e)).length}finally{T(t.descriptor)}}async function rn(e,t,n,r,i){let a=0;for(;;){let o=D(e).size;if(o>t.read){let i=Xt(e,t.read,o),s=i.lastIndexOf(10);if(s!==-1){n.rewrite(Zt(i.subarray(0,s+1)),r,!0),r.flush(),t.read+=s+1,a=0;continue}}if(a>=2)break;a+=1,await i()}let o=D(e).size,s=Xt(e,t.read,o).toString(`utf8`);if(s.length===0)return!1;let c=K(s);return n.rewrite(c,r,!0),r.flush(),t.read=o,c.length===0}function an(e,t){let n;try{n=k(e)}catch(e){if(J(e)===`ENOENT`)return`removed`;throw e}let r=D(t);return n.isFile()&&n.ino===r.ino&&n.dev===r.dev?`same`:`replaced`}function on(){return new Promise(e=>setTimeout(e,20))}async function sn(e,t,n={}){let r=Y(e);if(r.status!==`open`)return r;let i=r.descriptor,a=M(e),o=N(a,`.${Pe(e)}.${process.pid}.${w(6).toString(`hex`)}.tmp`),s,c=!1;try{let r=X(i),l=r.lastIndexOf(10)+1;x(a,n.ownedRoot===void 0?{}:{withinRoot:n.ownedRoot}),s=A(o,E.O_WRONLY|E.O_CREAT|E.O_EXCL|E.O_APPEND|(E.O_NOFOLLOW??0),b);let u=new $t(s);t.rewrite(Zt(r.subarray(0,l)),u,!1),u.flush(),O(s),n.beforeCommit?.();let d=an(e,i);if(d!==`same`)return{status:d};ke(o,e),c=!0,en(a);let f={read:l},p=!1,m;try{p=await rn(i,f,t,u,n.pause??on)}catch(e){m={unreadBytes:Math.max(0,D(i).size-f.read),reason:e instanceof Error?e.name:`unknown`}}return O(s),{status:`rewritten`,droppedTail:p,plainLinesAfter:nn(e),...m===void 0?{}:{catchUpFailed:m}}}finally{s!==void 0&&T(s),T(i),c||tn(o)}}const cn=/^.+\.(\d{1,10})\.tmp$/u,ln=/^\..+\.(\d{1,10})\.[0-9a-f]{12}\.tmp$/u;function un(e){let t=(ln.exec(e)??cn.exec(e))?.[1];return t===void 0?void 0:Number(t)}function dn(e,t,n){let r,i;try{let t=k(e);if(!t.isDirectory())return 0;r=Math.max(t.mtimeMs,n??-1/0),i=De(e)}catch{return 0}let a=0;for(let n of i){let i=un(n);if(i===void 0||i===process.pid)continue;let o=N(e,n);try{let e=k(o);if(!e.isFile()||r-e.mtimeMs<=3e5)continue;t&&j(o),a+=1}catch{}}return a}function Z(e){let t;try{t=A(e,E.O_RDONLY|(E.O_NOFOLLOW??0))}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=D(t);return e.isFile()?{bytes:X(t),links:e.nlink}:void 0}finally{T(t)}}const fn=e=>xe(`sha256`).update(e).digest(`hex`);var pn=class extends Error{constructor(){super(`The file changed while its replacement was staged.`),this.name=`FileChangedError`}};function mn(e,t,n=(e,t)=>(t(),!0)){let r=[],i=[],a=0;try{e((e,t,n)=>{r.push({path:e,file:ve(e,n),digest:fn(t)})});for(let{path:e,file:o,digest:s}of r)try{n(e,()=>o.commit(()=>{t?.();let n=Z(e);if(n===void 0||n.links>1||fn(n.bytes)!==s)throw new pn}))?a+=1:i.push(e)}catch(t){if(!(t instanceof pn))throw t;i.push(e)}}finally{for(let{file:e}of r)e.discard()}return{replaced:a,changed:i}}const hn=`.jsonl`,gn=`.payloads`,_n=`.tmp`;function vn(e){let t=new Map,n;try{n=De(e)}catch(e){if(e.code===`ENOENT`)return t;throw e}for(let r of n.sort())try{let n=k(N(e,r));t.set(r,n.isFile()?`file`:n.isDirectory()?`directory`:`other`)}catch(e){if(e.code!==`ENOENT`)throw e}return t}function yn(e,t){let n=new Map;for(let[i,a]of vn(e)){let o=i.endsWith(hn),s=i.endsWith(gn);if(!o&&!s)continue;let c=i.slice(0,-(o?hn:gn).length);if((o?a!==`file`:a!==`directory`)||!r(c)){t.refused.push(N(e,i));continue}let l=n.get(c)??{log:!1,payloads:!1};o?l.log=!0:l.payloads=!0,n.set(c,l)}return n}function bn(e,t,n,r){let i=new Set,a=mn(a=>{for(let[o,s]of vn(e)){if(o.endsWith(_n))continue;i.add(o);let c=N(e,o);if(s!==`file`){r.refused.push(c);continue}let l=Z(c);if(l===void 0)continue;let u=Ft(l.bytes,t,n.sealer);if(u===`sealed`?r.alreadySealed+=1:u!==`plain`&&r.unopenable.push(c),u===`plain`){if(l.links>1){r.refused.push(c);continue}if(!n.apply){r.payloads+=1;continue}a(c,l.bytes,It(l.bytes,t,n.sealer))}}},n.beforeCommit);return r.payloads+=a.replaced,r.changed.push(...a.changed),r.staleTemporaries+=dn(e,n.apply&&n.sweepTemporaries===!0,n.migrationStartedAt),i}function xn(e,t,n,r){let i=[];for(let[a,o]of vn(e)){if(n.has(a)||a.endsWith(_n)||o!==`file`)continue;let s=Z(N(e,a));s!==void 0&&Ft(s.bytes,t,r)===`plain`&&i.push(N(e,a))}return i}function Sn(e){let t=Y(e);if(t.status===`missing`)return`missing`;if(t.status===`refused`)return`refused`;try{return zt(X(t.descriptor).toString(`utf8`))}finally{T(t.descriptor)}}async function Cn(e,t,n,r){let i=Sn(e);if(i===`missing`)return;if(i===`refused`){r.refused.push(e);return}if(i===0){r.alreadySealed+=1;return}let a=n.apply?await sn(e,new Rt(n.sealer,t),{...n.ownedRoot===void 0?{}:{ownedRoot:n.ownedRoot},...n.beforeCommit===void 0?{}:{beforeCommit:n.beforeCommit},...n.pause===void 0?{}:{pause:n.pause}}):void 0;a?.status!==`missing`&&a?.status!==`removed`&&(r.logs+=1,r.lines+=i,a!==void 0&&(a.status===`refused`?r.refused.push(e):a.status===`replaced`?r.changed.push(e):a.status===`rewritten`&&(a.plainLinesAfter>0&&r.changed.push(e),a.catchUpFailed!==void 0&&r.catchUpFailed.push({path:e,...a.catchUpFailed}))))}async function wn(e,t){let n={logs:0,lines:0,payloads:0,alreadySealed:0,unopenable:[],refused:[],changed:[],catchUpFailed:[],staleTemporaries:0};try{if(!k(e).isDirectory())return n.refused.push(e),n}catch(e){if(e.code===`ENOENT`)return n;throw e}for(let[r,i]of yn(e,n)){let a=N(e,`${r}${gn}`),o=i.payloads?bn(a,r,t,n):new Set;i.log&&await Cn(N(e,`${r}${hn}`),r,t,n),t.apply&&i.payloads&&n.changed.push(...xn(a,r,o,t.sealer))}return n.staleTemporaries+=dn(e,t.apply&&t.sweepTemporaries===!0,t.migrationStartedAt),n}function Tn(e){let t=[],n=[],r;try{if(!k(e).isDirectory())return{files:t,refused:[e]};r=De(e)}catch(e){if(e.code===`ENOENT`)return{files:t,refused:n};throw e}for(let i of r.sort())if(i.endsWith(`.json`))try{(k(N(e,i)).isFile()?t:n).push(i)}catch(e){if(e.code!==`ENOENT`)throw e}return{files:t,refused:n.map(t=>N(e,t))}}function En(e,t){let{files:n,refused:i}=Tn(e),a={sealed:0,alreadySealed:0,unopenable:[],unsafeNames:[],refused:i,changed:[],held:[],staleTemporaries:0,sealedRecords:[]},o=he(N(e,W),{operationLock:re(N(e,W))}),s=[],c=mn(i=>{for(let c of n){let n=N(e,c),l=c.slice(0,-5);if(!r(l)){a.unsafeNames.push(n);continue}let u=o.inspect(l);if(u.status===`held`&&u.holder.liveness!==`gone`){a.held.push(l);continue}let d=Z(n);if(d===void 0)continue;let f=Je(l,d.bytes,t.sealer);if(f===`sealed`?a.alreadySealed+=1:f!==`plain`&&a.unopenable.push(n),f!==`plain`)continue;if(d.links>1){a.refused.push(n);continue}if(!t.apply){a.sealed+=1;continue}let p=Ye(l,d.bytes,t.sealer);Ze(l,d.bytes)&&s.push({path:n,id:l,digest:P(p)}),i(n,d.bytes,p)}},t.beforeCommit,(e,t)=>{let n=Pe(e).slice(0,-5),r=o.acquire(n);if(r.status!==`acquired`)return a.held.push(n),!1;try{return r.handle.withGuard(t).status===`ran`?!0:(a.held.push(n),!1)}finally{r.handle.release()}});a.sealed+=c.replaced,a.changed.push(...c.changed);for(let{path:e,id:t,digest:n}of s)c.changed.includes(e)||a.sealedRecords.push({id:t,digest:n});return a.staleTemporaries=dn(e,t.apply&&t.sweepTemporaries===!0,t.migrationStartedAt),a}function Dn(e,t){let n=new Set;for(let i of Tn(e).files){let a=i.slice(0,-5);if(!r(a))continue;let o=Z(N(e,i));if(o===void 0)continue;let s=ht(a,o.bytes,t.sealer),c=s.status===`valid`?s.record.cwd:s.status===`corrupt`||s.status===`unsupported`?s.cwd:void 0;typeof c==`string`&&c.length>0&&n.add(c)}return[...n]}const On=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,kn=`agent-tool-results-`,An=8*1024*1024,jn=E.O_WRONLY|E.O_CREAT|E.O_EXCL|(E.O_NOFOLLOW??0);var Q=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}};function Mn(e){return ye(e,kn)}const Nn=An+p;function Pn(e){return{kind:`tool-result-spill`,id:e}}var Fn=class{directory;retentionMs;now;onCleanupFailure;sealer;entries=new Map;opened;expiryTimer;cancelExitRemoval;closed=!1;constructor(e){let t=e?.parentDirectory;if(typeof t!=`string`||t.length===0||(this.retentionMs=e.retentionMs??36e5,this.now=e.now??Date.now,this.onCleanupFailure=e.onCleanupFailure,!Number.isSafeInteger(this.retentionMs)||this.retentionMs<=0))throw new Q(`invalid-options`);let n;try{n=H(e)}catch{throw new Q(`invalid-options`)}this.sealer=n===`plain`?void 0:n.sealer;try{let e=k(t);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=ge(t,kn,{prepareParent:!1}),this.assertRoot()}catch{throw new Q(`unsafe-root`)}this.cancelExitRemoval=_e(this.directory)}assertRoot(){try{let e=k(this.directory);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe directory`);if(process.platform!==`win32`&&e.mode&63)throw Error(`directory is not owner-only`)}catch{throw new Q(`unsafe-root`)}}scheduleExpiry(e=1){if(this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.closed||this.entries.size===0)return;let t=1/0;for(let e of this.entries.values())e.expiresAt<t&&(t=e.expiresAt);let n=Math.min(2147483647,Math.max(e,t-this.now()));this.expiryTimer=setTimeout(()=>{this.expiryTimer=void 0,this.cleanupExpired().catch(()=>{try{this.onCleanupFailure?this.onCleanupFailure(`cleanup-failed`):process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}catch{process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}this.scheduleExpiry(6e4)})},n),this.expiryTimer.unref?.()}async write(e){if(this.closed)throw new Q(`closed`);if(await this.cleanupExpired(),this.assertRoot(),Buffer.byteLength(e,`utf8`)>An)throw new Q(`write-failed`);let t=w(18).toString(`base64url`),n=`${w(18).toString(`base64url`)}.partial`,r=`${t}${this.sealer===void 0?`.txt`:`.sealed`}`,i=N(this.directory,n),a=N(this.directory,r),o;try{o=this.storedForm(e,t)}catch{throw new Q(`write-failed`)}let s,c=!1;try{s=A(i,jn,384),Me(s,o,`utf8`),O(s),T(s),s=void 0,we(i,a),c=!0,j(i);let e=`tool-result:${t}`;return this.entries.set(e,{fileName:r,token:t,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:e}}catch{let e=!1;if(s!==void 0)try{T(s)}catch{e=!0}try{j(i)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(c)try{j(a)}catch{e=!0}throw new Q(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new Q(`closed`);if(!On.test(e))throw new Q(`invalid-reference`);let t=this.entries.get(e);if(!t)throw new Q(`missing`);if(this.now()>=t.expiresAt)throw this.removeEntry(e,t),this.scheduleExpiry(),new Q(`expired`);if(this.opened?.reference===e)return this.opened.content;this.assertRoot();try{let n=new Jt(this.directory,{sealing:`plain`}).readBytes(t.fileName,this.sealer===void 0?An:Nn);if(n===void 0)throw new Q(`missing`);if(this.sealer===void 0)return Buffer.from(n).toString(`utf8`);let r=this.openStored(this.sealer,n,t.token);return this.opened={reference:e,content:r},r}catch(e){throw e instanceof Q?e:new Q(`read-failed`)}}storedForm(e,t){if(this.sealer===void 0)return e;let n=Buffer.from(e,`utf8`);try{return this.sealer.sealBytes(n,Pn(t))}finally{n.fill(0)}}openStored(e,t,n){let r=e.openBytes(t,Pn(n));try{if(r.byteLength>An)throw new Q(`read-failed`);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString(`utf8`)}finally{r.fill(0)}}removeEntry(e,t){this.assertRoot(),this.opened?.reference===e&&(this.opened=void 0);try{j(N(this.directory,t.fileName))}catch(e){if(e.code!==`ENOENT`)throw new Q(`cleanup-failed`)}this.entries.delete(e)}async cleanupExpired(){if(this.closed)throw new Q(`closed`);for(let[e,t]of this.entries)this.now()>=t.expiresAt&&this.removeEntry(e,t);this.scheduleExpiry()}async shutdown(){if(!this.closed){this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.opened=void 0;for(let[e,t]of this.entries)this.removeEntry(e,t);this.assertRoot();try{if(De(this.directory).filter(e=>e!==me).length!==0)throw Error(`unexpected files`);Ae(N(this.directory,me),{force:!0}),je(this.directory),this.closed=!0,this.cancelExitRemoval?.()}catch{throw new Q(`cleanup-failed`)}}}};const In=64*1024,$=`user`;function Ln(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.at==`string`&&typeof t.sessionId==`string`&&typeof t.project==`string`&&typeof t.text==`string`}function Rn(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(Ln(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function zn(e,t){let n=[],r=0,i=0,a=0;for(let o of e){if(o.length===0)continue;let e=t.decode(o,$);if(e.kind===`locked`){e.reason===`no-keys`?a+=1:i+=1;continue}if(e.kind!==`lines`){r+=1;continue}for(let t=e.lines.length-1;t>=0;--t){let i=Rn(e.lines[t]);i===void 0?r+=1:n.push(i)}}return i+a===0?{entries:n,skippedLines:r}:{entries:n,skippedLines:r,unreadable:{locked:i,noKeys:a}}}function Bn(e){return e.code===`ENOENT`}var Vn=class{path;blockBytes;ownedRoot;lines;constructor(e,t){this.path=e,this.lines=new G(H(t),`prompt-history-line`),this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){let t=this.lines.encode(`${JSON.stringify(e)}\n`,$);x(M(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),S(this.path),Se(this.path,t,{mode:b})}async*read(e){let t;try{t=A(this.path,E.O_RDONLY|(E.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&Bn(e))return;throw e}try{let n=D(t).size,r=Buffer.alloc(0),i=!0;for(;n>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,n);n-=e;let a=Buffer.alloc(e),o=Ee(t,a,0,e,n),s=Buffer.concat([a.subarray(0,o),r]),c=n===0?-1:s.indexOf(10);r=c===-1&&n>0?s:s.subarray(0,c+1);let l=n===0?s:c===-1?Buffer.alloc(0):s.subarray(c+1);if(n>0&&c===-1)continue;let u=l.toString(`utf8`),d=(i?K(u):u.split(`
11
- `)).reverse();i=!1,yield zn(d,this.lines)}}finally{T(t)}}},Hn=class{counts={entries:0,fromPlain:0,carriedOver:0};#e;constructor(e){this.#e=new G({sealer:e},`prompt-history-line`)}rewrite(e,t,n){for(let r of e){if(r.length===0)continue;let e=this.#e.decode(r,$);if(e.kind===`locked`)throw new d(e.reason);if(e.kind!==`lines`){t.write(`${r}
12
- `),this.counts.carriedOver+=1;continue}v(r)||(this.counts.fromPlain+=e.lines.length);for(let r of e.lines){let e=this.#e.encode(`${r}
13
- `,$);t.write(n?e:e.slice(1)),this.counts.entries+=1}}}};function Un(e,t){let n=Y(e);if(n.status!==`open`)return n;let r=new G({sealer:t.sealer},`prompt-history-line`),i=0,a=0,o=0;try{for(let e of K(X(n.descriptor).toString(`utf8`))){if(e.length===0)continue;let t=r.decode(e,$);if(t.kind===`locked`)throw new d(t.reason);t.kind===`lines`?v(e)?a+=1:i+=1:o+=1}}finally{T(n.descriptor)}return{status:`present`,plainLines:i,sealedLines:a,unreadableLines:o}}function Wn(e,t){let n=Y(e);if(n.status!==`open`)return[];let r=new G({sealer:t.sealer},`prompt-history-line`),i=new Set;try{for(let e of K(X(n.descriptor).toString(`utf8`))){if(e.length===0)continue;let t=r.decode(e,$);if(t.kind===`locked`)throw new d(t.reason);if(t.kind===`lines`)for(let e of t.lines){let t=Rn(e);t!==void 0&&t.project.length>0&&i.add(t.project)}}}finally{T(n.descriptor)}return[...i]}async function Gn(e,t){let n=new Hn(t.sealer),r=0,i=await sn(e,n,{...t.ownedRoot===void 0?{}:{ownedRoot:t.ownedRoot},...t.pause===void 0?{}:{pause:t.pause},beforeCommit:()=>{r=n.counts.entries,t.beforeCommit?.()}});return i.status===`rewritten`?{status:`compacted`,...n.counts,caughtUp:n.counts.entries-r,droppedTail:i.droppedTail,plainLinesAfter:i.plainLinesAfter,...i.catchUpFailed===void 0?{}:{catchUpFailed:i.catchUpFailed}}:i}function Kn(e){let t=e,n=[];for(;;)try{let e=Oe(t);return n.length===0?e:Re(e,...n.reverse())}catch{let r=M(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[\\/]/,``)),t=r}}function qn(e,t){let n=Le(e,t);return n===``||!n.startsWith(`..`)&&!Ie(n)}function Jn(e){return(t,n)=>{let r=Kn(e),i=Kn(Re(t??r,n));return qn(r,i)?i:void 0}}function Yn(e){typeof process>`u`||typeof process.on!=`function`||process.on(`exit`,e)}export{In as DEFAULT_PROMPT_HISTORY_BLOCK_BYTES,Jt as NodeExternalPayloadSource,Vn as NodePromptHistoryFile,Ht as NodeSessionLogSink,Yt as NodeSessionLogSource,Tt as NodeSessionStore,Fn as NodeToolResultSpillStore,W as SESSION_CLAIMS_DIRECTORY,G as StoredLines,Nt as StoredPayloads,vt as StoredSessionRecords,Q as ToolResultSpillError,U as assertSessionSealing,Qe as classifyStoredSessionBytes,Gn as compactPromptHistoryFile,zt as countPlainSessionLogLines,Jn as createNodeWorkspacePathResolver,ne as createProcessOperationLock,Un as inspectPromptHistoryFile,Ze as isPlainSessionRecordOf,En as migrateNodeSessionStore,wn as migrateSessionLogDirectory,Rn as parsePromptHistoryLine,Wn as readPromptHistoryProjects,Dn as readSessionStoreWorkingDirectories,Yn as registerProcessExitFlush,Bt as sealSessionLogText,It as sealStoredPayloadBytes,Ye as sealStoredSessionBytes,H as sessionSealingOf,K as splitStoredLines,Ft as storedPayloadMigrationState,Je as storedSessionMigrationState,Mn as sweepStaleToolResultSpillDirectories};
10
+ `,this.ownerId);t.write(n?i:i.slice(1)),this.sealedLines+=1}}};function zt(e){return q(e).filter(e=>{let t=Lt(e);return t.length>0&&!y(t)}).length}function Bt(e,t,n){let r=new Rt(n,t),i=[];return r.rewrite(q(e),{write:e=>i.push(e)},!1),{text:i.join(``),sealedLines:r.sealedLines,carriedLines:r.carriedLines}}const Vt=m(`NodeSessionLogSink`);var Ht=class{logDirectory;externalPayloadSink=this;enabled;lines;payloads;constructor(e,t){this.logDirectory=e;let n=U(t);this.lines=new K(n,`session-log-line`),this.payloads=new Nt(n);try{S(e),this.enabled=!0}catch(t){this.enabled=!1,Vt.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(e,t){if(a(e),!this.enabled)return;let n=P(this.logDirectory,`${e}.jsonl`),r=this.lines.encode(t,e);C(n),xe(n,r,{mode:x})}writeJson(e,t,n){return this.payloads.place(e,t,n,t=>this.writePayload(e,t))}writePayload(e,t){if(!this.enabled)return;S(P(this.logDirectory,`${e}.payloads`));let n=P(this.logDirectory,t.relativePath);try{je(n,t.data,{...typeof t.data==`string`?{encoding:`utf8`}:{},mode:x,flag:`wx`})}catch(e){if(!t.contentAddressed||e.code!==`EEXIST`)throw e;C(n)}}};function Ut(e){if(e.trim().length===0||e.includes(`\0`)||Fe(e)||Re.isAbsolute(e))throw Gt(e);let t=e.split(/[\\/]+/u);if(t.some(e=>e===`.`||e===`..`))throw Gt(e);return t}function Wt(e){if(!Number.isFinite(e)||!Number.isSafeInteger(e)||e<0)throw new c(`INVALID_LIMIT`,`External-payload maxBytes must be a finite, non-negative safe integer.`,{actual:String(e)})}function Gt(e,t){return new c(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function Kt(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?Gt(t,e):e.code===`UNSUPPORTED_BACKEND`?new c(`STABLE_PAYLOAD_READ_UNAVAILABLE`,`Stable root-relative external-payload reads are unavailable on this host.`,{relativePath:t},e):e.code===`OVER_BUDGET`?new c(`MAX_TOTAL_BYTES_EXCEEDED`,`External payload exceeds the remaining byte budget of ${n}.`,{relativePath:t,expected:n},e):new c(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${t}.`,{relativePath:t},e)}function qt(e){let t=e.length===2?e[0]:void 0;if(!(t===void 0||!t.endsWith(`.payloads`)))return t.slice(0,-9)||void 0}var Jt=class{baseDirectory;payloads;ownerId;constructor(e,t){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=Le(e),this.payloads=new Nt(U(t)),this.ownerId=t.ownerId}readBytes(e,t){Wt(t);let n=Ut(e),r=this.readStored(e,n,t);if(r!==void 0)return this.payloads.open(r,t,this.ownerId??qt(n),e)}readStored(e,t,n){try{let e=Be(this.baseDirectory);try{return e.readBytes(t,this.payloads.rawBudget(n))}finally{e.close()}}catch(t){throw t instanceof c?t:t instanceof ze?Kt(t,e,n):new c(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},t)}}},Yt=class{logFile;externalPayloadSource;lines;ownerId;constructor(e,t){if(this.logFile=e,e.trim().length===0)throw Error(`Session log-file path must not be empty.`);let n=U(t);this.lines=new K(n,`session-log-line`),this.ownerId=Ne(e,Pe(e)),this.externalPayloadSource=new Jt(N(e),{sealing:n,ownerId:this.ownerId})}readText(){if(Se(this.logFile))return this.lines.openText(we(this.logFile,`utf8`),this.ownerId)}readStoredLines(){if(Se(this.logFile))return q(we(this.logFile,`utf8`)).map(e=>this.lines.decode(e,this.ownerId))}};const Xt=new Set([`EPERM`,`EBUSY`,`EACCES`]);function J(e){return e?.code}function Zt(e,t,n=process.platform){return n===`win32`?e.ino!==0n&&e.ino===t.ino:e.ino===t.ino&&e.dev===t.dev}function Y(e){let t;try{t=A(e,{bigint:!0})}catch(e){if(J(e)===`ENOENT`)return{status:`missing`};throw e}if(!t.isFile())return{status:`refused`,reason:`not-a-regular-file`};let n;try{n=j(e,D.O_RDONLY|(D.O_NOFOLLOW??0))}catch(e){if(J(e)===`ENOENT`)return{status:`missing`};if(J(e)===`ELOOP`)return{status:`refused`,reason:`not-a-regular-file`};throw e}let r=O(n,{bigint:!0}),i=r.isFile()&&Zt(t,r);return!i||r.nlink>1n?(E(n),{status:`refused`,reason:i?`hard-linked`:`not-a-regular-file`}):{status:`open`,descriptor:n}}function Qt(e,t,n){let r=Buffer.alloc(Math.max(0,n-t)),i=0;for(;i<r.length;){let n=Te(e,r,i,r.length-i,t+i);if(n===0)break;i+=n}return r.subarray(0,i)}function X(e){return Qt(e,0,O(e).size)}function*$t(e){let t=0;for(;t<e.length;){let n=e.indexOf(10,t),r=n===-1?e.length:n;yield e.toString(`utf8`,t,r),t=r+1}}function en(e,t){let n=Buffer.from(t,`utf8`),r=0;for(;r<n.length;)r+=Me(e,n,r,n.length-r)}var tn=class{descriptor;#e=[];#t=0;constructor(e){this.descriptor=e}write(e){this.#e.push(e),this.#t+=e.length,this.#t>=1048576&&this.flush()}flush(){this.#e.length!==0&&(en(this.descriptor,this.#e.join(``)),this.#e=[],this.#t=0)}};function nn(e){let t;try{t=j(e,D.O_RDONLY),k(t)}catch{}finally{t!==void 0&&E(t)}}function rn(e){try{M(e)}catch{}}function an(e){let t=Y(e);if(t.status!==`open`)return 0;try{return q(X(t.descriptor).toString(`utf8`)).filter(e=>e.length>0&&!y(e)).length}finally{E(t.descriptor)}}async function on(e,t,n,r,i){let a=0;for(;;){let o=O(e).size;if(o>t.read){let i=Qt(e,t.read,o),s=i.lastIndexOf(10);if(s!==-1){n.rewrite($t(i.subarray(0,s+1)),r,!0),r.flush(),t.read+=s+1,a=0;continue}}if(a>=2)break;a+=1,await i()}let o=O(e).size,s=Qt(e,t.read,o).toString(`utf8`);if(s.length===0)return!1;let c=q(s);return n.rewrite(c,r,!0),r.flush(),t.read=o,c.length===0}function sn(e,t){let n;try{n=A(e,{bigint:!0})}catch(e){if(J(e)===`ENOENT`)return`removed`;throw e}let r=O(t,{bigint:!0});return n.isFile()&&Zt(n,r)?`same`:`replaced`}function cn(){return new Promise(e=>setTimeout(e,20))}async function ln(e,t,n,r,i,a,o,s){let c=O(n.descriptor,{bigint:!0}),l=!1;for(let u=1;;u+=1){l=await on(n.descriptor,r,i,a,s)||l,k(o);let d=sn(e,n.descriptor);if(d!==`same`)return{status:d};E(n.descriptor),n.descriptor=void 0;try{return Oe(t,e),{droppedTail:l}}catch(e){let t=J(e);if(t===void 0||!Xt.has(t)||u>=10)throw e}await s();let f=Y(e);if(f.status===`missing`)return{status:`removed`};if(f.status!==`open`)return f;if(!Zt(O(f.descriptor,{bigint:!0}),c))return E(f.descriptor),{status:`replaced`};n.descriptor=f.descriptor}}async function un(e,t,n={}){let r=Y(e);if(r.status!==`open`)return r;let i=r.descriptor,a={descriptor:i},o=N(e),s=P(o,`.${Ne(e)}.${process.pid}.${T(6).toString(`hex`)}.tmp`),c=n.pause??cn,l,u=!1;try{let r=X(i),d=r.lastIndexOf(10)+1;S(o,n.ownedRoot===void 0?{}:{withinRoot:n.ownedRoot}),l=j(s,D.O_WRONLY|D.O_CREAT|D.O_EXCL|D.O_APPEND|(D.O_NOFOLLOW??0),x);let f=new tn(l);t.rewrite($t(r.subarray(0,d)),f,!1),f.flush(),k(l),n.beforeCommit?.();let p=sn(e,i);if(p!==`same`)return{status:p};let m={read:d},h=!1,g;if((n.platform??process.platform)===`win32`){let n=await ln(e,s,a,m,t,f,l,c);if(`status`in n)return n;u=!0,h=n.droppedTail}else{Oe(s,e),u=!0,nn(o);try{h=await on(i,m,t,f,c)}catch(e){g={unreadBytes:Math.max(0,O(i).size-m.read),reason:e instanceof Error?e.name:`unknown`}}k(l)}return{status:`rewritten`,droppedTail:h,plainLinesAfter:an(e),...g===void 0?{}:{catchUpFailed:g}}}finally{l!==void 0&&E(l),a.descriptor!==void 0&&E(a.descriptor),u||rn(s)}}const dn=/^.+\.(\d{1,10})\.tmp$/u,fn=/^\..+\.(\d{1,10})\.[0-9a-f]{12}\.tmp$/u;function pn(e){let t=(fn.exec(e)??dn.exec(e))?.[1];return t===void 0?void 0:Number(t)}function mn(e,t,n){let r,i;try{let t=A(e);if(!t.isDirectory())return 0;r=Math.max(t.mtimeMs,n??-1/0),i=Ee(e)}catch{return 0}let a=0;for(let n of i){let i=pn(n);if(i===void 0||i===process.pid)continue;let o=P(e,n);try{let e=A(o);if(!e.isFile()||r-e.mtimeMs<=3e5)continue;t&&M(o),a+=1}catch{}}return a}function Z(e){let t;try{t=j(e,D.O_RDONLY|(D.O_NOFOLLOW??0))}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=O(t);return e.isFile()?{bytes:X(t),links:e.nlink}:void 0}finally{E(t)}}const hn=e=>be(`sha256`).update(e).digest(`hex`);var gn=class extends Error{constructor(){super(`The file changed while its replacement was staged.`),this.name=`FileChangedError`}};function _n(e,t,n=(e,t)=>(t(),!0)){let r=[],i=[],a=0;try{e((e,t,n)=>{r.push({path:e,file:_e(e,n),digest:hn(t)})});for(let{path:e,file:o,digest:s}of r)try{n(e,()=>o.commit(()=>{t?.();let n=Z(e);if(n===void 0||n.links>1||hn(n.bytes)!==s)throw new gn}))?a+=1:i.push(e)}catch(t){if(!(t instanceof gn))throw t;i.push(e)}}finally{for(let{file:e}of r)e.discard()}return{replaced:a,changed:i}}const vn=`.jsonl`,yn=`.payloads`,bn=`.tmp`;function xn(e){let t=new Map,n;try{n=Ee(e)}catch(e){if(e.code===`ENOENT`)return t;throw e}for(let r of n.sort())try{let n=A(P(e,r));t.set(r,n.isFile()?`file`:n.isDirectory()?`directory`:`other`)}catch(e){if(e.code!==`ENOENT`)throw e}return t}function Sn(e,t){let n=new Map;for(let[i,a]of xn(e)){let o=i.endsWith(vn),s=i.endsWith(yn);if(!o&&!s)continue;let c=i.slice(0,-(o?vn:yn).length);if((o?a!==`file`:a!==`directory`)||!r(c)){t.refused.push(P(e,i));continue}let l=n.get(c)??{log:!1,payloads:!1};o?l.log=!0:l.payloads=!0,n.set(c,l)}return n}function Cn(e,t,n,r){let i=new Set,a=_n(a=>{for(let[o,s]of xn(e)){if(o.endsWith(bn))continue;i.add(o);let c=P(e,o);if(s!==`file`){r.refused.push(c);continue}let l=Z(c);if(l===void 0)continue;let u=Ft(l.bytes,t,n.sealer);if(u===`sealed`?r.alreadySealed+=1:u!==`plain`&&r.unopenable.push(c),u===`plain`){if(l.links>1){r.refused.push(c);continue}if(!n.apply){r.payloads+=1;continue}a(c,l.bytes,It(l.bytes,t,n.sealer))}}},n.beforeCommit);return r.payloads+=a.replaced,r.changed.push(...a.changed),r.staleTemporaries+=mn(e,n.apply&&n.sweepTemporaries===!0,n.migrationStartedAt),i}function wn(e,t,n,r){let i=[];for(let[a,o]of xn(e)){if(n.has(a)||a.endsWith(bn)||o!==`file`)continue;let s=Z(P(e,a));s!==void 0&&Ft(s.bytes,t,r)===`plain`&&i.push(P(e,a))}return i}function Tn(e){let t=Y(e);if(t.status===`missing`)return`missing`;if(t.status===`refused`)return`refused`;try{return zt(X(t.descriptor).toString(`utf8`))}finally{E(t.descriptor)}}async function En(e,t,n,r){let i=Tn(e);if(i===`missing`)return;if(i===`refused`){r.refused.push(e);return}if(i===0){r.alreadySealed+=1;return}let a=n.apply?await un(e,new Rt(n.sealer,t),{...n.ownedRoot===void 0?{}:{ownedRoot:n.ownedRoot},...n.beforeCommit===void 0?{}:{beforeCommit:n.beforeCommit},...n.pause===void 0?{}:{pause:n.pause}}):void 0;a?.status!==`missing`&&a?.status!==`removed`&&(r.logs+=1,r.lines+=i,a!==void 0&&(a.status===`refused`?r.refused.push(e):a.status===`replaced`?r.changed.push(e):a.status===`rewritten`&&(a.plainLinesAfter>0&&r.changed.push(e),a.catchUpFailed!==void 0&&r.catchUpFailed.push({path:e,...a.catchUpFailed}))))}async function Dn(e,t){let n={logs:0,lines:0,payloads:0,alreadySealed:0,unopenable:[],refused:[],changed:[],catchUpFailed:[],staleTemporaries:0};try{if(!A(e).isDirectory())return n.refused.push(e),n}catch(e){if(e.code===`ENOENT`)return n;throw e}for(let[r,i]of Sn(e,n)){let a=P(e,`${r}${yn}`),o=i.payloads?Cn(a,r,t,n):new Set;i.log&&await En(P(e,`${r}${vn}`),r,t,n),t.apply&&i.payloads&&n.changed.push(...wn(a,r,o,t.sealer))}return n.staleTemporaries+=mn(e,t.apply&&t.sweepTemporaries===!0,t.migrationStartedAt),n}function On(e){let t=[],n=[],r;try{if(!A(e).isDirectory())return{files:t,refused:[e]};r=Ee(e)}catch(e){if(e.code===`ENOENT`)return{files:t,refused:n};throw e}for(let i of r.sort())if(i.endsWith(`.json`))try{(A(P(e,i)).isFile()?t:n).push(i)}catch(e){if(e.code!==`ENOENT`)throw e}return{files:t,refused:n.map(t=>P(e,t))}}function kn(e,t){let{files:n,refused:i}=On(e),a={sealed:0,alreadySealed:0,unopenable:[],unsafeNames:[],refused:i,changed:[],held:[],staleTemporaries:0,sealedRecords:[]},o=me(P(e,G),{operationLock:ne(P(e,G))}),s=[],c=_n(i=>{for(let c of n){let n=P(e,c),l=c.slice(0,-5);if(!r(l)){a.unsafeNames.push(n);continue}let u=o.inspect(l);if(u.status===`held`&&u.holder.liveness!==`gone`){a.held.push(l);continue}let d=Z(n);if(d===void 0)continue;let f=qe(l,d.bytes,t.sealer);if(f===`sealed`?a.alreadySealed+=1:f!==`plain`&&a.unopenable.push(n),f!==`plain`)continue;if(d.links>1){a.refused.push(n);continue}if(!t.apply){a.sealed+=1;continue}let p=Je(l,d.bytes,t.sealer);Xe(l,d.bytes)&&s.push({path:n,id:l,digest:F(p)}),i(n,d.bytes,p)}},t.beforeCommit,(e,t)=>{let n=Ne(e).slice(0,-5),r=o.acquire(n);if(r.status!==`acquired`)return a.held.push(n),!1;try{return r.handle.withGuard(t).status===`ran`?!0:(a.held.push(n),!1)}finally{r.handle.release()}});a.sealed+=c.replaced,a.changed.push(...c.changed);for(let{path:e,id:t,digest:n}of s)c.changed.includes(e)||a.sealedRecords.push({id:t,digest:n});return a.staleTemporaries=mn(e,t.apply&&t.sweepTemporaries===!0,t.migrationStartedAt),a}function An(e,t){let n=new Set;for(let i of On(e).files){let a=i.slice(0,-5);if(!r(a))continue;let o=Z(P(e,i));if(o===void 0)continue;let s=mt(a,o.bytes,t.sealer),c=s.status===`valid`?s.record.cwd:s.status===`corrupt`||s.status===`unsupported`?s.cwd:void 0;typeof c==`string`&&c.length>0&&n.add(c)}return[...n]}const jn=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,Mn=`agent-tool-results-`,Nn=8*1024*1024,Pn=D.O_WRONLY|D.O_CREAT|D.O_EXCL|(D.O_NOFOLLOW??0);var Q=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}};function Fn(e){return ve(e,Mn)}const In=Nn+p;function Ln(e){return{kind:`tool-result-spill`,id:e}}var Rn=class{directory;retentionMs;now;onCleanupFailure;sealer;entries=new Map;opened;expiryTimer;cancelExitRemoval;closed=!1;constructor(e){let t=e?.parentDirectory;if(typeof t!=`string`||t.length===0||(this.retentionMs=e.retentionMs??36e5,this.now=e.now??Date.now,this.onCleanupFailure=e.onCleanupFailure,!Number.isSafeInteger(this.retentionMs)||this.retentionMs<=0))throw new Q(`invalid-options`);let n;try{n=U(e)}catch{throw new Q(`invalid-options`)}this.sealer=n===`plain`?void 0:n.sealer;try{let e=A(t);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=he(t,Mn,{prepareParent:!1}),this.assertRoot()}catch{throw new Q(`unsafe-root`)}this.cancelExitRemoval=ge(this.directory)}assertRoot(){try{let e=A(this.directory);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe directory`);if(process.platform!==`win32`&&e.mode&63)throw Error(`directory is not owner-only`)}catch{throw new Q(`unsafe-root`)}}scheduleExpiry(e=1){if(this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.closed||this.entries.size===0)return;let t=1/0;for(let e of this.entries.values())e.expiresAt<t&&(t=e.expiresAt);let n=Math.min(2147483647,Math.max(e,t-this.now()));this.expiryTimer=setTimeout(()=>{this.expiryTimer=void 0,this.cleanupExpired().catch(()=>{try{this.onCleanupFailure?this.onCleanupFailure(`cleanup-failed`):process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}catch{process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}this.scheduleExpiry(6e4)})},n),this.expiryTimer.unref?.()}async write(e){if(this.closed)throw new Q(`closed`);if(await this.cleanupExpired(),this.assertRoot(),Buffer.byteLength(e,`utf8`)>Nn)throw new Q(`write-failed`);let t=T(18).toString(`base64url`),n=`${T(18).toString(`base64url`)}.partial`,r=`${t}${this.sealer===void 0?`.txt`:`.sealed`}`,i=P(this.directory,n),a=P(this.directory,r),o;try{o=this.storedForm(e,t)}catch{throw new Q(`write-failed`)}let s,c=!1;try{s=j(i,Pn,384),je(s,o,`utf8`),k(s),E(s),s=void 0,Ce(i,a),c=!0,M(i);let e=`tool-result:${t}`;return this.entries.set(e,{fileName:r,token:t,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:e}}catch{let e=!1;if(s!==void 0)try{E(s)}catch{e=!0}try{M(i)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(c)try{M(a)}catch{e=!0}throw new Q(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new Q(`closed`);if(!jn.test(e))throw new Q(`invalid-reference`);let t=this.entries.get(e);if(!t)throw new Q(`missing`);if(this.now()>=t.expiresAt)throw this.removeEntry(e,t),this.scheduleExpiry(),new Q(`expired`);if(this.opened?.reference===e)return this.opened.content;this.assertRoot();try{let n=new Jt(this.directory,{sealing:`plain`}).readBytes(t.fileName,this.sealer===void 0?Nn:In);if(n===void 0)throw new Q(`missing`);if(this.sealer===void 0)return Buffer.from(n).toString(`utf8`);let r=this.openStored(this.sealer,n,t.token);return this.opened={reference:e,content:r},r}catch(e){throw e instanceof Q?e:new Q(`read-failed`)}}storedForm(e,t){if(this.sealer===void 0)return e;let n=Buffer.from(e,`utf8`);try{return this.sealer.sealBytes(n,Ln(t))}finally{n.fill(0)}}openStored(e,t,n){let r=e.openBytes(t,Ln(n));try{if(r.byteLength>Nn)throw new Q(`read-failed`);return Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString(`utf8`)}finally{r.fill(0)}}removeEntry(e,t){this.assertRoot(),this.opened?.reference===e&&(this.opened=void 0);try{M(P(this.directory,t.fileName))}catch(e){if(e.code!==`ENOENT`)throw new Q(`cleanup-failed`)}this.entries.delete(e)}async cleanupExpired(){if(this.closed)throw new Q(`closed`);for(let[e,t]of this.entries)this.now()>=t.expiresAt&&this.removeEntry(e,t);this.scheduleExpiry()}async shutdown(){if(!this.closed){this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.opened=void 0;for(let[e,t]of this.entries)this.removeEntry(e,t);this.assertRoot();try{if(Ee(this.directory).filter(e=>e!==pe).length!==0)throw Error(`unexpected files`);ke(P(this.directory,pe),{force:!0}),Ae(this.directory),this.closed=!0,this.cancelExitRemoval?.()}catch{throw new Q(`cleanup-failed`)}}}};const zn=64*1024,$=`user`;function Bn(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.at==`string`&&typeof t.sessionId==`string`&&typeof t.project==`string`&&typeof t.text==`string`}function Vn(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(Bn(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function Hn(e,t){let n=[],r=0,i=0,a=0;for(let o of e){if(o.length===0)continue;let e=t.decode(o,$);if(e.kind===`locked`){e.reason===`no-keys`?a+=1:i+=1;continue}if(e.kind!==`lines`){r+=1;continue}for(let t=e.lines.length-1;t>=0;--t){let i=Vn(e.lines[t]);i===void 0?r+=1:n.push(i)}}return i+a===0?{entries:n,skippedLines:r}:{entries:n,skippedLines:r,unreadable:{locked:i,noKeys:a}}}function Un(e){return e.code===`ENOENT`}var Wn=class{path;blockBytes;ownedRoot;lines;constructor(e,t){this.path=e,this.lines=new K(U(t),`prompt-history-line`),this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){let t=this.lines.encode(`${JSON.stringify(e)}\n`,$);S(N(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),C(this.path),xe(this.path,t,{mode:x})}async*read(e){let t;try{t=j(this.path,D.O_RDONLY|(D.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&Un(e))return;throw e}try{let n=O(t);if(n.isDirectory())throw Object.assign(Error(`EISDIR: illegal operation on a directory, read`),{code:`EISDIR`});let r=n.size,i=Buffer.alloc(0),a=!0;for(;r>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,r);r-=e;let n=Buffer.alloc(e),o=Te(t,n,0,e,r),s=Buffer.concat([n.subarray(0,o),i]),c=r===0?-1:s.indexOf(10);i=c===-1&&r>0?s:s.subarray(0,c+1);let l=r===0?s:c===-1?Buffer.alloc(0):s.subarray(c+1);if(r>0&&c===-1)continue;let u=l.toString(`utf8`),d=(a?q(u):u.split(`
11
+ `)).reverse();a=!1,yield Hn(d,this.lines)}}finally{E(t)}}},Gn=class{counts={entries:0,fromPlain:0,carriedOver:0};#e;constructor(e){this.#e=new K({sealer:e},`prompt-history-line`)}rewrite(e,t,n){for(let r of e){if(r.length===0)continue;let e=this.#e.decode(r,$);if(e.kind===`locked`)throw new d(e.reason);if(e.kind!==`lines`){t.write(`${r}
12
+ `),this.counts.carriedOver+=1;continue}y(r)||(this.counts.fromPlain+=e.lines.length);for(let r of e.lines){let e=this.#e.encode(`${r}
13
+ `,$);t.write(n?e:e.slice(1)),this.counts.entries+=1}}}};function Kn(e,t){let n=Y(e);if(n.status!==`open`)return n;let r=new K({sealer:t.sealer},`prompt-history-line`),i=0,a=0,o=0;try{for(let e of q(X(n.descriptor).toString(`utf8`))){if(e.length===0)continue;let t=r.decode(e,$);if(t.kind===`locked`)throw new d(t.reason);t.kind===`lines`?y(e)?a+=1:i+=1:o+=1}}finally{E(n.descriptor)}return{status:`present`,plainLines:i,sealedLines:a,unreadableLines:o}}function qn(e,t){let n=Y(e);if(n.status!==`open`)return[];let r=new K({sealer:t.sealer},`prompt-history-line`),i=new Set;try{for(let e of q(X(n.descriptor).toString(`utf8`))){if(e.length===0)continue;let t=r.decode(e,$);if(t.kind===`locked`)throw new d(t.reason);if(t.kind===`lines`)for(let e of t.lines){let t=Vn(e);t!==void 0&&t.project.length>0&&i.add(t.project)}}}finally{E(n.descriptor)}return[...i]}async function Jn(e,t){let n=new Gn(t.sealer),r=0,i=await un(e,n,{...t.ownedRoot===void 0?{}:{ownedRoot:t.ownedRoot},...t.pause===void 0?{}:{pause:t.pause},beforeCommit:()=>{r=n.counts.entries,t.beforeCommit?.()}});return i.status===`rewritten`?{status:`compacted`,...n.counts,caughtUp:n.counts.entries-r,droppedTail:i.droppedTail,plainLinesAfter:i.plainLinesAfter,...i.catchUpFailed===void 0?{}:{catchUpFailed:i.catchUpFailed}}:i}function Yn(e){let t=e,n=[];for(;;)try{let e=De(t);return n.length===0?e:Le(e,...n.reverse())}catch{let r=N(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[\\/]/,``)),t=r}}function Xn(e,t){let n=Ie(e,t);return n===``||!n.startsWith(`..`)&&!Fe(n)}function Zn(e){return(t,n)=>{let r=Yn(e),i=Yn(Le(t??r,n));return Xn(r,i)?i:void 0}}function Qn(e){typeof process>`u`||typeof process.on!=`function`||process.on(`exit`,e)}export{zn as DEFAULT_PROMPT_HISTORY_BLOCK_BYTES,Jt as NodeExternalPayloadSource,Wn as NodePromptHistoryFile,Ht as NodeSessionLogSink,Yt as NodeSessionLogSource,wt as NodeSessionStore,Rn as NodeToolResultSpillStore,G as SESSION_CLAIMS_DIRECTORY,K as StoredLines,Nt as StoredPayloads,_t as StoredSessionRecords,Q as ToolResultSpillError,W as assertSessionSealing,Ze as classifyStoredSessionBytes,Jn as compactPromptHistoryFile,zt as countPlainSessionLogLines,Zn as createNodeWorkspacePathResolver,te as createProcessOperationLock,Kn as inspectPromptHistoryFile,Xe as isPlainSessionRecordOf,kn as migrateNodeSessionStore,Dn as migrateSessionLogDirectory,Vn as parsePromptHistoryLine,qn as readPromptHistoryProjects,An as readSessionStoreWorkingDirectories,Qn as registerProcessExitFlush,Bt as sealSessionLogText,It as sealStoredPayloadBytes,Je as sealStoredSessionBytes,U as sessionSealingOf,q as splitStoredLines,Ft as storedPayloadMigrationState,qe as storedSessionMigrationState,Fn as sweepStaleToolResultSpillDirectories};
14
14
  //# sourceMappingURL=node.js.map