@robota-sdk/agent-session 3.0.7 → 3.1.2

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 ADDED
@@ -0,0 +1,13 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require("./session-claims-BQGdD3Fe.cjs");let l=require("@robota-sdk/agent-core"),u=require("node:fs"),d=require("node:path"),f=require("koffi");f=s(f,1);let p=require("fs"),m=require("path"),h=require("@robota-sdk/agent-core/node"),g=require("node:buffer"),_=require("node:crypto"),ee=require("@robota-sdk/agent-file-authority"),v;const te=[];function ne(){if(v!==void 0)return v;let e=f.load(`kernel32.dll`);te.push(e);let t=f.pointer(`RobotaSessionOperationGuardHandle`,f.opaque()),n=f.struct(`RobotaSessionOperationGuardAttributes`,{FileAttributes:`uint32_t`,ReparseTag:`uint32_t`}),r=f.struct(`RobotaSessionOperationGuardStandard`,{AllocationSize:`int64_t`,EndOfFile:`int64_t`,NumberOfLinks:`uint32_t`,DeletePending:`uint8_t`,Directory:`uint8_t`});return v={open:e.func(`CreateFileW`,t,[f.pointer(`char16_t`),`uint32_t`,`uint32_t`,`void *`,`uint32_t`,`uint32_t`,t]),close:e.func(`CloseHandle`,`bool`,[t]),lastError:e.func(`GetLastError`,`uint32_t`,[]),attributes:e.func(`GetFileInformationByHandleEx`,`bool`,[t,`int32_t`,f.out(f.pointer(n)),`uint32_t`]),attributeType:n,standard:e.func(`GetFileInformationByHandleEx`,`bool`,[t,`int32_t`,f.out(f.pointer(r)),`uint32_t`]),standardType:r},v}function re(e){let t=ne(),n=t.open(e,3221225472,0,null,4,2097280,null);if(n===null||BigInt.asIntN(64,n)===-1n){let e=t.lastError();if(e===32)return;throw Error(`Could not acquire a process operation lock (Windows error ${e}).`)}try{let e={},r={};if(!t.attributes(n,9,e,f.sizeof(t.attributeType))||!t.standard(n,1,r,f.sizeof(t.standardType))||(e.FileAttributes??0)&1024||r.Directory!==0||r.NumberOfLinks!==1)throw Error(`The process operation lock is not a unique regular file.`);let i=!1;return Object.freeze({release:()=>{if(!i&&(i=!0,!t.close(n)))throw Error(`Could not release a process operation lock.`)}})}catch(e){throw t.close(n),e}}const ie=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;let y;const ae=[];function oe(){if(y===void 0){let e=f.load(process.platform===`darwin`?`/usr/lib/libSystem.B.dylib`:`libc.so.6`);ae.push(e),y=e.func(`int flock(int fd, int operation)`)}return y}function se(e){let t=(0,u.openSync)(e,u.constants.O_RDWR|u.constants.O_CREAT|(u.constants.O_NOFOLLOW??0),384);try{let n=(0,u.fstatSync)(t,{bigint:!0}),r=(0,u.lstatSync)(e,{bigint:!0});if(!n.isFile()||n.nlink!==1n||n.dev!==r.dev||n.ino!==r.ino)throw Error(`The process operation lock is not a unique regular file.`);(0,u.fchmodSync)(t,384);let i=oe();if(i(t,6)!==0){let e=f.errno();if(e===f.os.errno.EAGAIN||e===f.os.errno.EWOULDBLOCK){(0,u.closeSync)(t);return}throw Error(`Could not acquire a process operation lock (errno ${e}).`)}let a=!1;return Object.freeze({release:()=>{if(!a){a=!0;try{i(t,8)}finally{(0,u.closeSync)(t)}}}})}catch(e){throw(0,u.closeSync)(t),e}}function b(e){let t=(0,d.resolve)(e);return Object.freeze({tryAcquire:e=>{if(!ie.test(e))throw Error(`A process operation lock name must be one safe path component.`);let n=(0,d.join)(t,`${e}.guard`);if(process.platform===`win32`)return re(n);if(process.platform===`darwin`||process.platform===`linux`)return se(n);throw Error(`Process operation locking is unsupported on this platform.`)}})}const ce=`the sealed session file does not open for this session: it is damaged or sealed with other keys`,le=/^[0-9a-f]{64}$/;function ue(e){return typeof e==`string`&&le.test(e)}function x(e){return(0,_.createHash)(`sha256`).update(e).digest(`hex`)}function de(e,t){return g.Buffer.from(e.buffer,e.byteOffset,e.byteLength).equals(t)}function S(e){return{kind:`session-record`,id:e}}function C(e){return g.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`)}function fe(e){return JSON.stringify({schemaVersion:2,record:e},null,2)}function pe(e,t){let n=fe(e),r=g.Buffer.from(n,`utf8`);return{stored:t===void 0?r:t.sealBytes(r,S(e.id)),text:n}}function me(e,t,n){if(!(0,l.isSealedArtifactBytes)(t))return`plain`;if(!(0,l.isCurrentSealedArtifactBytes)(t))return`newer-format`;let r;try{r=n.openBytes(t,S(e))}catch(e){if((0,l.isArtifactLockedError)(e))throw e;return`does-not-open`}return r.fill(0),`sealed`}function he(e,t,n){return n.sealBytes(t,S(e))}function ge(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=c.b(t);return n.status===`valid`?{status:`valid`,record:n.record}:n.status===`unsupported`?{status:`unsupported`,schemaVersion:n.schemaVersion,...n.cwd===void 0?{}:{cwd:n.cwd}}:{status:`corrupt`,issues:n.issues,...n.cwd===void 0?{}:{cwd:n.cwd}}}function w(e,t){let n=ge(t);return n.status!==`valid`||n.record.id===e?n:{status:`corrupt`,issues:[{path:`id`,message:`the record belongs to another session id`}]}}function _e(e,t){return w(e,C(t)).status===`valid`}function ve(e){return e===void 0?{kind:`absent`}:(0,l.isSealedArtifactBytes)(e)?{kind:`sealed`,bytes:e}:{kind:`plain`,bytes:e}}function T(e){return e.kind===`sealed`||e.kind===`plain`?e.bytes:void 0}var ye=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 be=`rsh2.`,xe={owner:!0,unverified:!1},Se=/^[A-Za-z0-9_-]+$/,Ce=new TextDecoder(`utf-8`,{fatal:!0});function we(e,t,n){return`${be}${n?`owner`:`unverified`}.${e}.${g.Buffer.from(t,`utf8`).toString(`base64url`)}`}function Te(e){if(typeof e!=`string`||!e.startsWith(be))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)||!Se.test(r))return;let a=g.Buffer.from(r,`base64url`);if(a.toString(`base64url`)===r)try{return{digest:n,text:Ce.decode(a),owner:xe[t]}}catch{return}}const Ee=`robota-authorship/v1 `,E=g.Buffer.from(Ee,`ascii`),De=/^[A-Za-z0-9_-]+$/;function Oe(e,t){let n=g.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64url`);return g.Buffer.concat([g.Buffer.from(`${Ee}${n}\n`,`ascii`),t])}function ke(e){let t=g.Buffer.from(e.buffer,e.byteOffset,e.byteLength);if(t.length<E.length||!t.subarray(0,E.length).equals(E))return{envelope:e,tag:void 0};let n=t.indexOf(10,E.length);if(n<0)return{envelope:e,tag:`malformed`};let r=t.subarray(E.length,n).toString(`latin1`),i=e.subarray(n+1);if(!De.test(r))return{envelope:i,tag:`malformed`};let a=g.Buffer.from(r,`base64url`);return a.length!==32||a.toString(`base64url`)!==r?{envelope:i,tag:`malformed`}:{envelope:i,tag:a}}const D={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}},O=Object.freeze({status:`locked`,reason:`no-keys`}),k=Object.freeze({status:`locked`,reason:`changed`}),Ae=Object.freeze({status:`locked`}),je=Object.freeze({status:`missing`});function A(e,t,n,r){return{status:`valid`,record:e.record,authorship:t?`verified`:`unverified`,...n===void 0?{}:{digest:n},...r?{diverged:!0}:{}}}function j(e,t,n){let r;try{r=e.openBytes(n,S(t))}catch(e){return(0,l.isArtifactLockedError)(e)?e.reason===`no-keys`?{kind:`no-keys`}:{kind:`locked`}:{kind:`does-not-open`}}try{let{envelope:n,tag:i}=ke(r),a=!1;if(i instanceof Uint8Array&&e.verifyAuthorship!==void 0)try{a=e.verifyAuthorship(n,i,S(t))===!0}catch{a=!1}return{kind:`text`,text:C(n),verified:a}}finally{r.fill(0)}}function Me(e,t,n){let r,i=!1;if(!(0,l.isSealedArtifactBytes)(t))r=C(t);else{if(!(0,l.isCurrentSealedArtifactBytes)(t))return{status:`unsupported`,schemaVersion:void 0};let a=j(n,e,t);if(a.kind===`locked`)return Ae;if(a.kind===`no-keys`)return O;if(a.kind===`does-not-open`)return{status:`corrupt`,issues:[{path:``,message:ce}]};r=a.text,i=a.verified}let a=w(e,r);return a.status===`valid`?A(a,i,x(t),!1):a}var Ne=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=T(t);return o===void 0?n:this.decode(e,o,i)}decode(e,t,n){let r,i=!1;if(!(0,l.isSealedArtifactBytes)(t))r=C(t);else{if(!(0,l.isCurrentSealedArtifactBytes)(t))return{status:`unsupported`,schemaVersion:void 0};let n=j(this.#e,e,t);if(n.kind===`locked`)return Ae;if(n.kind===`no-keys`)return O;if(n.kind===`does-not-open`)return{status:`corrupt`,issues:[{path:``,message:ce}]};r=n.text,i=n.verified}let a=w(e,r);if(a.status!==`valid`)return a;let o=x(t),s=this.#n.state(e),c=i||this.#s(s,s?.held,o)?`owner`:`unverified`;return D[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=T(n);return!t&&a!==void 0&&o!==void 0&&x(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=D[n],s=T(t),c=s===void 0?void 0:x(s);if(a!==void 0)return o.takes&&this.#n.dropHandoff(e),s===void 0||c!==a.digest?k:(o.takes&&this.#n.hold(e,a),this.#c(e,a,n,!1));let u=r?.held;if(u!==void 0&&c===u.digest)return this.#c(e,u,n,!1);let d=!1;if(u?.kind!==`pinned`&&t.kind===`sealed`&&(0,l.isCurrentSealedArtifactBytes)(t.bytes)){let r=j(this.#e,e,t.bytes);if(r.kind===`text`&&r.verified&&c!==void 0){let t=w(e,r.text);if(t.status===`valid`)return n!==`save`&&this.#n.hold(e,{digest:c,text:r.text,kind:`owner`}),A(t,!0,c,!1)}d=r.kind===`locked`}return t.kind===`absent`?u===void 0?je:this.#c(e,u,n,!0):o.writer||u===void 0?d?Ae:k:this.#c(e,u,n,!0)}assertReplaceable(e,t){let n=this.guarded(e,t,`save`);if(n!==void 0){if(n.status!==`locked`)return;throw new c.a(e,n.reason===`changed`?`changed`:`locked`)}switch(t.kind){case`absent`:case`plain`:return;case`unreadable`:case`oversized`:throw new c.a(e,`unreadable`);case`sealed`:break}let r=t.bytes;if(!(0,l.isCurrentSealedArtifactBytes)(r))throw new c.a(e,`newer-format`);let i=this.#n.state(e)?.held;if(i!==void 0&&i.digest===x(r))return;let a=j(this.#e,e,r);if(a.kind!==`text`)throw new c.a(e,i===void 0?a.kind===`locked`||a.kind===`no-keys`?a.kind:`does-not-open`:`changed`)}prepare(e,t,n){let r=g.Buffer.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=Oe(t,r))}try{return{stored:this.#e.sealBytes(a,S(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:x(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`&&de(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=T(t);return i===void 0||x(i)!==r.digest?k:this.#c(e,r,`held`,!1)}exportHeld(e,t,n){if(t.kind!==`sealed`||!(0,l.isCurrentSealedArtifactBytes)(t.bytes))return;let r=x(t.bytes),i=(e,t)=>we(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=j(this.#e,e,t.bytes);if(s.kind!==`text`||w(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=Te(t);if(n===void 0)throw TypeError(`The held record is not a token this build issues.`);if(w(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=T(r),a=i===void 0?void 0:x(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||w(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)}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=w(e,t.text);if(i.status!==`valid`)return i;if(t.kind===`pinned`)return A(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),A(t,n===`owner`,r,a)}#u(e,t,n){t!==`owner`&&D[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,S(e))}catch(e){if((0,l.isArtifactLockedError)(e))return`locked`;throw e}}#p(e,t,n){if(t.kind!==`sealed`)return C(n);if(!(0,l.isCurrentSealedArtifactBytes)(n))return;let r=j(this.#e,e,n);return r.kind===`locked`?`locked`:r.kind===`text`?r.text:void 0}#m(e,t,n,r){let i=g.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=Oe(r,t),s;try{s=this.#e.sealBytes(o,S(e))}finally{o.fill(0)}let c=T(this.#t.current(e));if(c===void 0||x(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=T(n);if(r===void 0||x(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`||w(e,o).status!==`valid`)return;let s=g.Buffer.from(o,`utf8`),c=this.#f(e,s);c instanceof Uint8Array&&this.#h(e,s,o,c,t,a)}};function Pe(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 M(e){if(typeof e!=`object`||!e)throw TypeError(`Session store options must be an object, such as { sealing }.`);return N(e.sealing),e.sealing}function N(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 Fe=class{#e;#t;#n;#r;#i;authorship;constructor(e,t,n,r={}){if(N(e),Pe(n),this.#e=e===`plain`?void 0:e.sealer,this.#t=t,this.#n=n,this.#r=new c.n(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 Ne(this.#e,t,new ye(e=>this.#r.has(e)),this.#r,(e,t)=>this.#l(e,t));this.#i=i,this.authorship=Object.freeze({adopt:(e,t)=>{c.m(e);let n=this.#l(e,()=>i.adopt(e,t));return n===`has_writer`?`has_writer`:n},heldDigest:e=>(c.m(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))});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=(0,_.randomBytes)(32).toString(`hex`),n=(0,_.createHash)(`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:c.i(r.holder)});let i=this.#r.lend(e,()=>{let t=this.#n.inspect(e);return t.status===`held`?t.holder:void 0}),a=!1;return Object.freeze({nonce:t,end:()=>{if(!a){a=!0;try{this.#n.endLease(e,n)}finally{i()}}}})}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,pe(e,void 0).stored);return}i.assertReplaceable(n,r);let a=i.prepare(n,fe(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:c.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:c.i(n.holder)})}#s(e,t){let n=this.#n.acquire(e);if(n.status!==`acquired`)throw this.#r.refusal(e,`has_writer`,{holder:c.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(c.r(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(c.r(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=T(t);return r===void 0?n:(0,l.isSealedArtifactBytes)(r)?(0,l.isCurrentSealedArtifactBytes)(r)?O:{status:`unsupported`,schemaVersion:void 0}:w(e,C(r))}#f(e,t){switch(t.kind){case`absent`:case`plain`:case`oversized`:return;case`unreadable`:throw new c.a(e,`unreadable`);case`sealed`:throw new c.a(e,(0,l.isCurrentSealedArtifactBytes)(t.bytes)?`no-keys`:`newer-format`)}}#p(e){return this.#t.rebuild?.(e)??je}#m(e){try{return this.#t.current(e)}catch{return{kind:`unreadable`}}}};function P(e){return typeof e==`object`&&e?e.code:void 0}function Ie(e){let t=P(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 Le(e,t){let n=Buffer.alloc(Math.max((0,p.fstatSync)(e).size,t.length));t.copy(n,0);let r=t.length;for(;r<n.length;){let t=(0,p.readSync)(e,n,r,n.length-r,r);if(t===0)break;r+=t}return n.subarray(0,r)}const Re=Object.freeze({status:`missing`}),F=`claims`;function ze(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 Be(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var Ve=class{baseDir;ownedRoot;records;constructor(e,t){let n=M(t);this.records=new Fe(n,{load:e=>this.loadFile(e),current:e=>this.readExisting(this.filePath(e)),replace:(e,t)=>{this.ensureDir(),(0,h.writeOwnerOnlyFile)(this.filePath(e),t)}},(0,h.createProcessMarkers)((0,m.join)((0,m.resolve)(e),F),{operationLock:b((0,m.join)((0,m.resolve)(e),F))}),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(){(0,h.ensureOwnerOnlyDirectory)(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){c.m(e);let t=(0,m.resolve)(this.baseDir),n=(0,m.resolve)(t,`${e}.json`);if(!n.startsWith(t+m.sep))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)}readExisting(e){let t;try{t=(0,p.openSync)(e,`r`)}catch(e){return P(e)===`ENOENT`?{kind:`absent`}:{kind:`unreadable`}}try{let e=Buffer.alloc(l.SEALED_ARTIFACT_MAGIC.length),n=(0,p.readSync)(t,e,0,e.length,0);return(0,l.isSealedArtifactBytes)(e.subarray(0,n))?{kind:`sealed`,bytes:Le(t,e)}:this.records.seals?{kind:`plain`,bytes:Le(t,e.subarray(0,n))}:{kind:`plain`}}catch{return{kind:`unreadable`}}finally{(0,p.closeSync)(t)}}load(e,t={}){return this.filePath(e),this.records.load(e,t)}loadFile(e){let t=this.filePath(e),n;try{n=(0,p.readFileSync)(t)}catch(e){return P(e)===`ENOENT`?{file:{kind:`absent`},unreadable:Re}:{file:{kind:`unreadable`},unreadable:{status:`corrupt`,issues:[{path:``,message:Ie(e)}]}}}try{(0,h.tightenExistingFile)(t)}catch{}return{file:ve(n),unreadable:Re}}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(Be),...ze(e)}}readAll(){return(0,p.existsSync)(this.baseDir)?(0,p.readdirSync)(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})):[]}outcomeForListedId(e){return c.g(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,()=>{(0,p.existsSync)(t)&&(0,p.unlinkSync)(t)})}};const He=Object.freeze({kind:`does-not-open`}),Ue=Object.freeze({kind:`newer-format`}),We=Object.freeze({kind:`locked`,reason:`no-keys`}),Ge=/^R(?:S(?:L[0-9]?)?)?$/;function Ke(e){return N(e),e===`plain`?void 0:e.sealer}function qe(e){return e.reason===`no-keys`?`no-keys`:`locked`}var I=class{#e;#t;constructor(e,t){this.#e=Ke(e),this.#t=t}encode(e,t){return this.#e===void 0?e:`
2
+ ${this.#e.sealLine(e,{kind:this.#t,id:t})}
3
+ `}decode(e,t){try{return this.#n(e,t)}catch{return He}}openText(e,t){let n=L(e),r=e=>this.#n(e,t);return Je((function*(){for(let e of n)yield r(e)})())}#n(e,t){if(!(0,l.isSealedArtifactLine)(e))return{kind:`lines`,lines:[e]};if(!(0,l.isCurrentSealedArtifactLine)(e))return Ue;if(this.#e===void 0)return We;let n;try{n=this.#e.openLine(e,{kind:this.#t,id:t})}catch(e){if((0,l.isArtifactLockedError)(e))return{kind:`locked`,reason:qe(e)};if((0,l.isArtifactCorruptError)(e))return He;throw e}return{kind:`lines`,lines:n.split(`
4
+ `).filter(e=>e.length>0)}}};function L(e){let t=e.split(`
5
+ `),n=t[t.length-1];return n.length>0&&((0,l.isSealedArtifactLine)(n)||Ge.test(n))&&t.pop(),t}function Je(e){let t=[],n=0;for(let r of e)switch(n+=1,r.kind){case`lines`:t.push(r.lines.join(`
6
+ `));break;case`locked`:throw new l.ArtifactLockedError(r.reason);case`does-not-open`:throw new l.ArtifactCorruptError;case`newer-format`:throw new c.c(`UNSUPPORTED_VERSION`,[{path:`line ${n}`,message:`the line is sealed in a framing version this build does not open`}])}return t.join(`
7
+ `)}function R(e,t,n){return e===`PAYLOAD_UNREADABLE`?new c.s(e,`External payload is sealed and does not open here: ${t}.`,{relativePath:t}):new c.s(e,`External payload exceeds the remaining byte budget of ${n}.`,{relativePath:t,expected:n})}var z=class{#e;#t=new Map;constructor(e){this.#e=Ke(e)}place(e,t,n,r){let i=c.u(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/${(0,_.randomBytes)(16).toString(`base64url`)}.sealed`,l=Buffer.from(n,`utf8`),u;try{u=this.#e.sealBytes(l,{kind:`session-log-payload`,id:e})}finally{l.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+l.SEALED_ARTIFACT_MAX_OVERHEAD_BYTES,2**53-1)}open(e,t,n,r){if(this.#e===void 0)return e;if(!(0,l.isSealedArtifactBytes)(e)){if(e.byteLength>t)throw R(`MAX_TOTAL_BYTES_EXCEEDED`,r,t);return e}if(!(0,l.isCurrentSealedArtifactBytes)(e)||n===void 0)throw R(`PAYLOAD_UNREADABLE`,r,t);let i;try{i=this.#e.openBytes(e,{kind:`session-log-payload`,id:n})}catch(e){throw(0,l.isArtifactLockedError)(e)?new l.ArtifactLockedError(qe(e)):(0,l.isArtifactCorruptError)(e)?R(`PAYLOAD_UNREADABLE`,r,t):e}if(i.byteLength>t)throw i.fill(0),R(`MAX_TOTAL_BYTES_EXCEEDED`,r,t);return i}};function Ye(e){return{kind:`session-log-payload`,id:e}}function B(e,t,n){if(!(0,l.isSealedArtifactBytes)(e))return`plain`;if(!(0,l.isCurrentSealedArtifactBytes)(e))return`newer-format`;let r;try{r=n.openBytes(e,Ye(t))}catch(e){if((0,l.isArtifactLockedError)(e))throw e;return`does-not-open`}return r.fill(0),`sealed`}function Xe(e,t,n){return n.sealBytes(e,Ye(t))}function Ze(e){return e.endsWith(`\r`)?e.slice(0,-1):e}var Qe=class{ownerId;sealedLines=0;carriedLines=0;#e;constructor(e,t){this.ownerId=t,this.#e=new I({sealer:e},`session-log-line`)}rewrite(e,t,n){for(let r of e){let e=Ze(r);if(e.length===0)continue;if((0,l.isSealedArtifactLine)(e)){t.write(`${n?`
8
+ `:``}${e}
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 $e(e){return L(e).filter(e=>{let t=Ze(e);return t.length>0&&!(0,l.isSealedArtifactLine)(t)}).length}function et(e,t,n){let r=new Qe(n,t),i=[];return r.rewrite(L(e),{write:e=>i.push(e)},!1),{text:i.join(``),sealedLines:r.sealedLines,carriedLines:r.carriedLines}}const tt=(0,l.createLogger)(`NodeSessionLogSink`);var nt=class{logDirectory;externalPayloadSink=this;enabled;lines;payloads;constructor(e,t){this.logDirectory=e;let n=M(t);this.lines=new I(n,`session-log-line`),this.payloads=new z(n);try{(0,h.ensureOwnerOnlyDirectory)(e),this.enabled=!0}catch(t){this.enabled=!1,tt.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(c.m(e),!this.enabled)return;let n=(0,d.join)(this.logDirectory,`${e}.jsonl`),r=this.lines.encode(t,e);(0,h.tightenExistingFile)(n),(0,u.appendFileSync)(n,r,{mode:h.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,h.ensureOwnerOnlyDirectory)((0,d.join)(this.logDirectory,`${e}.payloads`));let n=(0,d.join)(this.logDirectory,t.relativePath);try{(0,u.writeFileSync)(n,t.data,{...typeof t.data==`string`?{encoding:`utf8`}:{},mode:h.OWNER_ONLY_FILE_MODE,flag:`wx`})}catch(e){if(!t.contentAddressed||e.code!==`EEXIST`)throw e;(0,h.tightenExistingFile)(n)}}};function rt(e){if(e.trim().length===0||e.includes(`\0`)||(0,d.isAbsolute)(e)||d.win32.isAbsolute(e))throw V(e);let t=e.split(/[\\/]+/u);if(t.some(e=>e===`.`||e===`..`))throw V(e);return t}function it(e){if(!Number.isFinite(e)||!Number.isSafeInteger(e)||e<0)throw new c.s(`INVALID_LIMIT`,`External-payload maxBytes must be a finite, non-negative safe integer.`,{actual:String(e)})}function V(e,t){return new c.s(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function at(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?V(t,e):e.code===`UNSUPPORTED_BACKEND`?new c.s(`STABLE_PAYLOAD_READ_UNAVAILABLE`,`Stable root-relative external-payload reads are unavailable on this host.`,{relativePath:t},e):e.code===`OVER_BUDGET`?new c.s(`MAX_TOTAL_BYTES_EXCEEDED`,`External payload exceeds the remaining byte budget of ${n}.`,{relativePath:t,expected:n},e):new c.s(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${t}.`,{relativePath:t},e)}function ot(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 H=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,d.resolve)(e),this.payloads=new z(M(t)),this.ownerId=t.ownerId}readBytes(e,t){it(t);let n=rt(e),r=this.readStored(e,n,t);if(r!==void 0)return this.payloads.open(r,t,this.ownerId??ot(n),e)}readStored(e,t,n){try{let e=(0,ee.createStableRootedFileReader)(this.baseDirectory);try{return e.readBytes(t,this.payloads.rawBudget(n))}finally{e.close()}}catch(t){throw t instanceof c.s?t:t instanceof ee.StableFileAuthorityError?at(t,e,n):new c.s(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},t)}}},st=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=M(t);this.lines=new I(n,`session-log-line`),this.ownerId=(0,d.basename)(e,(0,d.extname)(e)),this.externalPayloadSource=new H((0,d.dirname)(e),{sealing:n,ownerId:this.ownerId})}readText(){if((0,u.existsSync)(this.logFile))return this.lines.openText((0,u.readFileSync)(this.logFile,`utf8`),this.ownerId)}readStoredLines(){if((0,u.existsSync)(this.logFile))return L((0,u.readFileSync)(this.logFile,`utf8`)).map(e=>this.lines.decode(e,this.ownerId))}};function U(e){return e?.code}function W(e){let t;try{t=(0,u.lstatSync)(e)}catch(e){if(U(e)===`ENOENT`)return{status:`missing`};throw e}if(!t.isFile())return{status:`refused`,reason:`not-a-regular-file`};let n;try{n=(0,u.openSync)(e,u.constants.O_RDONLY|(u.constants.O_NOFOLLOW??0))}catch(e){if(U(e)===`ENOENT`)return{status:`missing`};if(U(e)===`ELOOP`)return{status:`refused`,reason:`not-a-regular-file`};throw e}let r=(0,u.fstatSync)(n),i=r.isFile()&&r.ino===t.ino&&r.dev===t.dev;return!i||r.nlink>1?((0,u.closeSync)(n),{status:`refused`,reason:i?`hard-linked`:`not-a-regular-file`}):{status:`open`,descriptor:n}}function G(e,t,n){let r=Buffer.alloc(Math.max(0,n-t)),i=0;for(;i<r.length;){let n=(0,u.readSync)(e,r,i,r.length-i,t+i);if(n===0)break;i+=n}return r.subarray(0,i)}function K(e){return G(e,0,(0,u.fstatSync)(e).size)}function*ct(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 lt(e,t){let n=Buffer.from(t,`utf8`),r=0;for(;r<n.length;)r+=(0,u.writeSync)(e,n,r,n.length-r)}var ut=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&&(lt(this.descriptor,this.#e.join(``)),this.#e=[],this.#t=0)}};function dt(e){let t;try{t=(0,u.openSync)(e,u.constants.O_RDONLY),(0,u.fsyncSync)(t)}catch{}finally{t!==void 0&&(0,u.closeSync)(t)}}function ft(e){try{(0,u.unlinkSync)(e)}catch{}}function pt(e){let t=W(e);if(t.status!==`open`)return 0;try{return L(K(t.descriptor).toString(`utf8`)).filter(e=>e.length>0&&!(0,l.isSealedArtifactLine)(e)).length}finally{(0,u.closeSync)(t.descriptor)}}async function mt(e,t,n,r,i){let a=0;for(;;){let o=(0,u.fstatSync)(e).size;if(o>t.read){let i=G(e,t.read,o),s=i.lastIndexOf(10);if(s!==-1){n.rewrite(ct(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,u.fstatSync)(e).size,s=G(e,t.read,o).toString(`utf8`);if(s.length===0)return!1;let c=L(s);return n.rewrite(c,r,!0),r.flush(),t.read=o,c.length===0}function ht(e,t){let n;try{n=(0,u.lstatSync)(e)}catch(e){if(U(e)===`ENOENT`)return`removed`;throw e}let r=(0,u.fstatSync)(t);return n.isFile()&&n.ino===r.ino&&n.dev===r.dev?`same`:`replaced`}function gt(){return new Promise(e=>setTimeout(e,20))}async function _t(e,t,n={}){let r=W(e);if(r.status!==`open`)return r;let i=r.descriptor,a=(0,d.dirname)(e),o=(0,d.join)(a,`.${(0,d.basename)(e)}.${process.pid}.${(0,_.randomBytes)(6).toString(`hex`)}.tmp`),s,c=!1;try{let r=K(i),l=r.lastIndexOf(10)+1;(0,h.ensureOwnerOnlyDirectory)(a,n.ownedRoot===void 0?{}:{withinRoot:n.ownedRoot}),s=(0,u.openSync)(o,u.constants.O_WRONLY|u.constants.O_CREAT|u.constants.O_EXCL|u.constants.O_APPEND|(u.constants.O_NOFOLLOW??0),h.OWNER_ONLY_FILE_MODE);let d=new ut(s);t.rewrite(ct(r.subarray(0,l)),d,!1),d.flush(),(0,u.fsyncSync)(s),n.beforeCommit?.();let f=ht(e,i);if(f!==`same`)return{status:f};(0,u.renameSync)(o,e),c=!0,dt(a);let p={read:l},m=!1,g;try{m=await mt(i,p,t,d,n.pause??gt)}catch(e){g={unreadBytes:Math.max(0,(0,u.fstatSync)(i).size-p.read),reason:e instanceof Error?e.name:`unknown`}}return(0,u.fsyncSync)(s),{status:`rewritten`,droppedTail:m,plainLinesAfter:pt(e),...g===void 0?{}:{catchUpFailed:g}}}finally{s!==void 0&&(0,u.closeSync)(s),(0,u.closeSync)(i),c||ft(o)}}const vt=/^.+\.(\d{1,10})\.tmp$/u,yt=/^\..+\.(\d{1,10})\.[0-9a-f]{12}\.tmp$/u;function bt(e){let t=(yt.exec(e)??vt.exec(e))?.[1];return t===void 0?void 0:Number(t)}function q(e,t,n){let r,i;try{let t=(0,u.lstatSync)(e);if(!t.isDirectory())return 0;r=Math.max(t.mtimeMs,n??-1/0),i=(0,u.readdirSync)(e)}catch{return 0}let a=0;for(let n of i){let i=bt(n);if(i===void 0||i===process.pid)continue;let o=(0,d.join)(e,n);try{let e=(0,u.lstatSync)(o);if(!e.isFile()||r-e.mtimeMs<=3e5)continue;t&&(0,u.unlinkSync)(o),a+=1}catch{}}return a}function J(e){let t;try{t=(0,u.openSync)(e,u.constants.O_RDONLY|(u.constants.O_NOFOLLOW??0))}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=(0,u.fstatSync)(t);return e.isFile()?{bytes:K(t),links:e.nlink}:void 0}finally{(0,u.closeSync)(t)}}const xt=e=>(0,_.createHash)(`sha256`).update(e).digest(`hex`);var St=class extends Error{constructor(){super(`The file changed while its replacement was staged.`),this.name=`FileChangedError`}};function Ct(e,t,n=(e,t)=>(t(),!0)){let r=[],i=[],a=0;try{e((e,t,n)=>{r.push({path:e,file:(0,h.stageOwnerOnlyFile)(e,n),digest:xt(t)})});for(let{path:e,file:o,digest:s}of r)try{n(e,()=>o.commit(()=>{t?.();let n=J(e);if(n===void 0||n.links>1||xt(n.bytes)!==s)throw new St}))?a+=1:i.push(e)}catch(t){if(!(t instanceof St))throw t;i.push(e)}}finally{for(let{file:e}of r)e.discard()}return{replaced:a,changed:i}}const Y=`.jsonl`,X=`.payloads`,wt=`.tmp`;function Tt(e){let t=new Map,n;try{n=(0,u.readdirSync)(e)}catch(e){if(e.code===`ENOENT`)return t;throw e}for(let r of n.sort())try{let n=(0,u.lstatSync)((0,d.join)(e,r));t.set(r,n.isFile()?`file`:n.isDirectory()?`directory`:`other`)}catch(e){if(e.code!==`ENOENT`)throw e}return t}function Et(e,t){let n=new Map;for(let[r,i]of Tt(e)){let a=r.endsWith(Y),o=r.endsWith(X);if(!a&&!o)continue;let s=r.slice(0,-(a?Y:X).length);if((a?i!==`file`:i!==`directory`)||!c.g(s)){t.refused.push((0,d.join)(e,r));continue}let l=n.get(s)??{log:!1,payloads:!1};a?l.log=!0:l.payloads=!0,n.set(s,l)}return n}function Dt(e,t,n,r){let i=new Set,a=Ct(a=>{for(let[o,s]of Tt(e)){if(o.endsWith(wt))continue;i.add(o);let c=(0,d.join)(e,o);if(s!==`file`){r.refused.push(c);continue}let l=J(c);if(l===void 0)continue;let u=B(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,Xe(l.bytes,t,n.sealer))}}},n.beforeCommit);return r.payloads+=a.replaced,r.changed.push(...a.changed),r.staleTemporaries+=q(e,n.apply&&n.sweepTemporaries===!0,n.migrationStartedAt),i}function Ot(e,t,n,r){let i=[];for(let[a,o]of Tt(e)){if(n.has(a)||a.endsWith(wt)||o!==`file`)continue;let s=J((0,d.join)(e,a));s!==void 0&&B(s.bytes,t,r)===`plain`&&i.push((0,d.join)(e,a))}return i}function kt(e){let t=W(e);if(t.status===`missing`)return`missing`;if(t.status===`refused`)return`refused`;try{return $e(K(t.descriptor).toString(`utf8`))}finally{(0,u.closeSync)(t.descriptor)}}async function At(e,t,n,r){let i=kt(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 _t(e,new Qe(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 jt(e,t){let n={logs:0,lines:0,payloads:0,alreadySealed:0,unopenable:[],refused:[],changed:[],catchUpFailed:[],staleTemporaries:0};try{if(!(0,u.lstatSync)(e).isDirectory())return n.refused.push(e),n}catch(e){if(e.code===`ENOENT`)return n;throw e}for(let[r,i]of Et(e,n)){let a=(0,d.join)(e,`${r}${X}`),o=i.payloads?Dt(a,r,t,n):new Set;i.log&&await At((0,d.join)(e,`${r}${Y}`),r,t,n),t.apply&&i.payloads&&n.changed.push(...Ot(a,r,o,t.sealer))}return n.staleTemporaries+=q(e,t.apply&&t.sweepTemporaries===!0,t.migrationStartedAt),n}function Mt(e){let t=[],n=[],r;try{if(!(0,u.lstatSync)(e).isDirectory())return{files:t,refused:[e]};r=(0,u.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,u.lstatSync)((0,d.join)(e,i)).isFile()?t:n).push(i)}catch(e){if(e.code!==`ENOENT`)throw e}return{files:t,refused:n.map(t=>(0,d.join)(e,t))}}function Nt(e,t){let{files:n,refused:r}=Mt(e),i={sealed:0,alreadySealed:0,unopenable:[],unsafeNames:[],refused:r,changed:[],held:[],staleTemporaries:0,sealedRecords:[]},a=(0,h.createProcessMarkers)((0,d.join)(e,F),{operationLock:b((0,d.join)(e,F))}),o=[],s=Ct(r=>{for(let s of n){let n=(0,d.join)(e,s),l=s.slice(0,-5);if(!c.g(l)){i.unsafeNames.push(n);continue}let u=a.inspect(l);if(u.status===`held`&&u.holder.liveness!==`gone`){i.held.push(l);continue}let f=J(n);if(f===void 0)continue;let p=me(l,f.bytes,t.sealer);if(p===`sealed`?i.alreadySealed+=1:p!==`plain`&&i.unopenable.push(n),p!==`plain`)continue;if(f.links>1){i.refused.push(n);continue}if(!t.apply){i.sealed+=1;continue}let m=he(l,f.bytes,t.sealer);_e(l,f.bytes)&&o.push({path:n,id:l,digest:x(m)}),r(n,f.bytes,m)}},t.beforeCommit,(e,t)=>{let n=(0,d.basename)(e).slice(0,-5),r=a.acquire(n);if(r.status!==`acquired`)return i.held.push(n),!1;try{return r.handle.withGuard(t).status===`ran`?!0:(i.held.push(n),!1)}finally{r.handle.release()}});i.sealed+=s.replaced,i.changed.push(...s.changed);for(let{path:e,id:t,digest:n}of o)s.changed.includes(e)||i.sealedRecords.push({id:t,digest:n});return i.staleTemporaries=q(e,t.apply&&t.sweepTemporaries===!0,t.migrationStartedAt),i}function Pt(e,t){let n=new Set;for(let r of Mt(e).files){let i=r.slice(0,-5);if(!c.g(i))continue;let a=J((0,d.join)(e,r));if(a===void 0)continue;let o=Me(i,a.bytes,t.sealer),s=o.status===`valid`?o.record.cwd:o.status===`corrupt`||o.status===`unsupported`?o.cwd:void 0;typeof s==`string`&&s.length>0&&n.add(s)}return[...n]}const Ft=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,It=`agent-tool-results-`,Z=8*1024*1024,Lt=u.constants.O_WRONLY|u.constants.O_CREAT|u.constants.O_EXCL|(u.constants.O_NOFOLLOW??0);var Q=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}};function Rt(e){return(0,h.sweepStaleProcessScopedDirectories)(e,It)}const zt=Z+l.SEALED_ARTIFACT_MAX_OVERHEAD_BYTES;function Bt(e){return{kind:`tool-result-spill`,id:e}}var Vt=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=M(e)}catch{throw new Q(`invalid-options`)}this.sealer=n===`plain`?void 0:n.sealer;try{let e=(0,u.lstatSync)(t);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=(0,h.createProcessScopedDirectory)(t,It,{prepareParent:!1}),this.assertRoot()}catch{throw new Q(`unsafe-root`)}this.cancelExitRemoval=(0,h.removeDirectoryOnProcessExit)(this.directory)}assertRoot(){try{let e=(0,u.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 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`)>Z)throw new Q(`write-failed`);let t=(0,_.randomBytes)(18).toString(`base64url`),n=`${(0,_.randomBytes)(18).toString(`base64url`)}.partial`,r=`${t}${this.sealer===void 0?`.txt`:`.sealed`}`,i=(0,d.join)(this.directory,n),a=(0,d.join)(this.directory,r),o;try{o=this.storedForm(e,t)}catch{throw new Q(`write-failed`)}let s,c=!1;try{s=(0,u.openSync)(i,Lt,384),(0,u.writeFileSync)(s,o,`utf8`),(0,u.fsyncSync)(s),(0,u.closeSync)(s),s=void 0,(0,u.linkSync)(i,a),c=!0,(0,u.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(s!==void 0)try{(0,u.closeSync)(s)}catch{e=!0}try{(0,u.unlinkSync)(i)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(c)try{(0,u.unlinkSync)(a)}catch{e=!0}throw new Q(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new Q(`closed`);if(!Ft.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 H(this.directory,{sealing:`plain`}).readBytes(t.fileName,this.sealer===void 0?Z:zt);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,Bt(t))}finally{n.fill(0)}}openStored(e,t,n){let r=e.openBytes(t,Bt(n));try{if(r.byteLength>Z)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{(0,u.unlinkSync)((0,d.join)(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((0,u.readdirSync)(this.directory).filter(e=>e!==h.PROCESS_OWNER_RECORD_NAME).length!==0)throw Error(`unexpected files`);(0,u.rmSync)((0,d.join)(this.directory,h.PROCESS_OWNER_RECORD_NAME),{force:!0}),(0,u.rmdirSync)(this.directory),this.closed=!0,this.cancelExitRemoval?.()}catch{throw new Q(`cleanup-failed`)}}}};const $=`user`;function Ht(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 Ut(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(Ht(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function Wt(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=Ut(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 Gt(e){return e.code===`ENOENT`}var Kt=class{path;blockBytes;ownedRoot;lines;constructor(e,t){this.path=e,this.lines=new I(M(t),`prompt-history-line`),this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){let t=this.lines.encode(`${JSON.stringify(e)}\n`,$);(0,h.ensureOwnerOnlyDirectory)((0,d.dirname)(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),(0,h.tightenExistingFile)(this.path),(0,u.appendFileSync)(this.path,t,{mode:h.OWNER_ONLY_FILE_MODE})}async*read(e){let t;try{t=(0,u.openSync)(this.path,u.constants.O_RDONLY|(u.constants.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&Gt(e))return;throw e}try{let n=(0,u.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,u.readSync)(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 d=l.toString(`utf8`),f=(i?L(d):d.split(`
11
+ `)).reverse();i=!1,yield Wt(f,this.lines)}}finally{(0,u.closeSync)(t)}}},qt=class{counts={entries:0,fromPlain:0,carriedOver:0};#e;constructor(e){this.#e=new I({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 l.ArtifactLockedError(e.reason);if(e.kind!==`lines`){t.write(`${r}
12
+ `),this.counts.carriedOver+=1;continue}(0,l.isSealedArtifactLine)(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 Jt(e,t){let n=W(e);if(n.status!==`open`)return n;let r=new I({sealer:t.sealer},`prompt-history-line`),i=0,a=0,o=0;try{for(let e of L(K(n.descriptor).toString(`utf8`))){if(e.length===0)continue;let t=r.decode(e,$);if(t.kind===`locked`)throw new l.ArtifactLockedError(t.reason);t.kind===`lines`?(0,l.isSealedArtifactLine)(e)?a+=1:i+=1:o+=1}}finally{(0,u.closeSync)(n.descriptor)}return{status:`present`,plainLines:i,sealedLines:a,unreadableLines:o}}function Yt(e,t){let n=W(e);if(n.status!==`open`)return[];let r=new I({sealer:t.sealer},`prompt-history-line`),i=new Set;try{for(let e of L(K(n.descriptor).toString(`utf8`))){if(e.length===0)continue;let t=r.decode(e,$);if(t.kind===`locked`)throw new l.ArtifactLockedError(t.reason);if(t.kind===`lines`)for(let e of t.lines){let t=Ut(e);t!==void 0&&t.project.length>0&&i.add(t.project)}}}finally{(0,u.closeSync)(n.descriptor)}return[...i]}async function Xt(e,t){let n=new qt(t.sealer),r=0,i=await _t(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 Zt(e){let t=e,n=[];for(;;)try{let e=(0,u.realpathSync)(t);return n.length===0?e:(0,d.resolve)(e,...n.reverse())}catch{let r=(0,d.dirname)(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[\\/]/,``)),t=r}}function Qt(e,t){let n=(0,d.relative)(e,t);return n===``||!n.startsWith(`..`)&&!(0,d.isAbsolute)(n)}function $t(e){return(t,n)=>{let r=Zt(e),i=Zt((0,d.resolve)(t??r,n));return Qt(r,i)?i:void 0}}function en(e){typeof process>`u`||typeof process.on!=`function`||process.on(`exit`,e)}exports.DEFAULT_PROMPT_HISTORY_BLOCK_BYTES=65536,exports.NodeExternalPayloadSource=H,exports.NodePromptHistoryFile=Kt,exports.NodeSessionLogSink=nt,exports.NodeSessionLogSource=st,exports.NodeSessionStore=Ve,exports.NodeToolResultSpillStore=Vt,exports.SESSION_CLAIMS_DIRECTORY=F,exports.StoredLines=I,exports.StoredPayloads=z,exports.StoredSessionRecords=Fe,exports.ToolResultSpillError=Q,exports.assertSessionSealing=N,exports.classifyStoredSessionBytes=ve,exports.compactPromptHistoryFile=Xt,exports.countPlainSessionLogLines=$e,exports.createNodeWorkspacePathResolver=$t,exports.createProcessOperationLock=b,exports.inspectPromptHistoryFile=Jt,exports.isPlainSessionRecordOf=_e,exports.migrateNodeSessionStore=Nt,exports.migrateSessionLogDirectory=jt,exports.parsePromptHistoryLine=Ut,exports.readPromptHistoryProjects=Yt,exports.readSessionStoreWorkingDirectories=Pt,exports.registerProcessExitFlush=en,exports.sealSessionLogText=et,exports.sealStoredPayloadBytes=Xe,exports.sealStoredSessionBytes=he,exports.sessionSealingOf=M,exports.splitStoredLines=L,exports.storedPayloadMigrationState=B,exports.storedSessionMigrationState=me,exports.sweepStaleToolResultSpillDirectories=Rt;