@robota-sdk/agent-cli 3.0.0-beta.93 → 3.0.0-beta.94

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.
@@ -1,2 +1,2 @@
1
- import{D as e,E as t,O as n,t as r}from"./product-host-zZ2TTtQk.js";import{join as i}from"node:path";const a=[`PATH`,`HOME`,`USERPROFILE`,`SystemRoot`,`TEMP`,`TMP`,`LANG`,`LC_ALL`,`XDG_RUNTIME_DIR`,`DISPLAY`,`WAYLAND_DISPLAY`,`XAUTHORITY`,`DBUS_SESSION_BUS_ADDRESS`,`APPDATA`,`LOCALAPPDATA`,`PROGRAMDATA`],o=/^ws:\/\/127\.0\.0\.1:([0-9]{1,5})\/?\?token=([A-Za-z0-9%._~-]+)$/u;function s(e){let t=e.split(/\r?\n/u).filter(e=>e.trim()!==``);if(t.length===1)try{let e=JSON.parse(t[0]);return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}catch{return}}function c(e){let t=s(e);if(t===void 0)return;let n=t.providerEnvRefs;if(!(n!==void 0&&(!Array.isArray(n)||n.length>128||!n.every(e=>typeof e==`string`&&/^[A-Za-z_][A-Za-z0-9_]*$/u.test(e))))){if(t.state===`trusted`)return t.askable===!1?{trusted:!0,providerEnvRefs:Object.freeze([...new Set(n??[])])}:void 0;if(t.askable===!0&&typeof t.workspace==`string`&&t.workspace.trim()!==``){let e=Array.isArray(t.loads)?t.loads.filter(e=>typeof e==`string`):[];return{trusted:!1,question:{folder:t.workspace,loads:e.slice(0,64)},providerEnvRefs:[]}}return{trusted:!1,providerEnvRefs:[]}}}function l(e){let t=s(e);if(typeof t?.id!=`string`||t.id.trim()===``||typeof t.url!=`string`)return;let n=o.exec(t.url);if(!n)return;let r=Number(n[1]);return Number.isInteger(r)&&r>0&&r<=65535?{id:t.id,url:t.url,port:r}:void 0}function u(e){return`default-src 'self'; connect-src ${e===void 0?`'none'`:`ws://127.0.0.1:${e}`}; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'`}function d(o){let s=Object.freeze({...o.environment}),d=r(o.artifact).resolveRuntime({environment:s}).config,f=n(s,t(d)),p=null,m=null,h,g=!1,_=(t=[])=>{let n={};for(let e of a)f[e]!==void 0&&(n[e]=f[e]);for(let e of t)f[e]!==void 0&&(n[e]=f[e]);for(let{section:t,field:r,descriptor:i}of e()){if(i.exposure===`private`||!i.consumers.includes(`cli`))continue;let e=d[t][r];e!==void 0&&(n[i.variable]=typeof e==`string`?e:JSON.stringify(e))}return f.PRODUCT_CONFIG_FILE!==void 0&&(n.PRODUCT_CONFIG_FILE=f.PRODUCT_CONFIG_FILE),n};async function v(){let e=[],t=g?void 0:await o.execute([`trust`,`status`,`--json`],_()),n=t?.exitCode===0?c(t.stdout):void 0;if(!g&&n?.question!==void 0){let t=await o.chooseTrust(n.question);if(t!==`trust`&&t!==`restricted`&&t!==`quit`)return{ok:!1,detail:`Desktop trust answer was invalid.`};if(t===`quit`)return{ok:!1,detail:`Desktop launch cancelled.`};if(t===`restricted`&&(g=!0),t===`trust`){let t=await o.execute([`trust`,`--yes`],_());if(t.exitCode!==0)return{ok:!1,detail:t.stderr.trim()||`Workspace trust grant failed.`};let n=await o.execute([`trust`,`status`,`--json`],_()),r=n.exitCode===0?c(n.stdout):void 0;if(r?.trusted!==!0)return{ok:!1,detail:`Workspace trust could not be confirmed after grant.`};e=r.providerEnvRefs}}else e=n?.providerEnvRefs??[];let r=await o.execute([`daemon`,`start`,`--json`,...g?[`--restricted-workspace`]:[]],_(g?[]:e)),i=r.exitCode===0?l(r.stdout):void 0;return i===void 0?{ok:!1,detail:r.stderr.trim()||`Desktop daemon did not return a loopback endpoint.`}:{ok:!0,endpoint:i}}let y=()=>{if(m!==null)return m;let e=v().then(e=>(h=e.ok?e.endpoint.port:void 0,m=null,e),e=>{throw h=void 0,m=null,e});return p=m=e,e};return Object.freeze({config:d,userDataPath:i(d.storage.userRoot,`desktop`),start:y,reconnect:y,current:()=>p,port:()=>h,csp:()=>u(h)})}export{d as createDesktopCliController,u as desktopContentSecurityPolicy,l as parseDesktopDaemonStart,c as parseDesktopTrustStatus};
1
+ import{D as e,E as t,O as n,t as r}from"./product-host-CBylXlR9.js";import{join as i}from"node:path";const a=[`PATH`,`HOME`,`USERPROFILE`,`SystemRoot`,`TEMP`,`TMP`,`LANG`,`LC_ALL`,`XDG_RUNTIME_DIR`,`DISPLAY`,`WAYLAND_DISPLAY`,`XAUTHORITY`,`DBUS_SESSION_BUS_ADDRESS`,`APPDATA`,`LOCALAPPDATA`,`PROGRAMDATA`],o=/^ws:\/\/127\.0\.0\.1:([0-9]{1,5})\/?\?token=([A-Za-z0-9%._~-]+)$/u;function s(e){let t=e.split(/\r?\n/u).filter(e=>e.trim()!==``);if(t.length===1)try{let e=JSON.parse(t[0]);return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}catch{return}}function c(e){let t=s(e);if(t===void 0)return;let n=t.providerEnvRefs;if(!(n!==void 0&&(!Array.isArray(n)||n.length>128||!n.every(e=>typeof e==`string`&&/^[A-Za-z_][A-Za-z0-9_]*$/u.test(e))))){if(t.state===`trusted`)return t.askable===!1?{trusted:!0,providerEnvRefs:Object.freeze([...new Set(n??[])])}:void 0;if(t.askable===!0&&typeof t.workspace==`string`&&t.workspace.trim()!==``){let e=Array.isArray(t.loads)?t.loads.filter(e=>typeof e==`string`):[];return{trusted:!1,question:{folder:t.workspace,loads:e.slice(0,64)},providerEnvRefs:[]}}return{trusted:!1,providerEnvRefs:[]}}}function l(e){let t=s(e);if(typeof t?.id!=`string`||t.id.trim()===``||typeof t.url!=`string`)return;let n=o.exec(t.url);if(!n)return;let r=Number(n[1]);return Number.isInteger(r)&&r>0&&r<=65535?{id:t.id,url:t.url,port:r}:void 0}function u(e){return`default-src 'self'; connect-src ${e===void 0?`'none'`:`ws://127.0.0.1:${e}`}; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'`}function d(o){let s=Object.freeze({...o.environment}),d=r(o.artifact).resolveRuntime({environment:s}).config,f=n(s,t(d)),p=null,m=null,h,g=!1,_=(t=[])=>{let n={};for(let e of a)f[e]!==void 0&&(n[e]=f[e]);for(let e of t)f[e]!==void 0&&(n[e]=f[e]);for(let{section:t,field:r,descriptor:i}of e()){if(i.exposure===`private`||!i.consumers.includes(`cli`))continue;let e=d[t][r];e!==void 0&&(n[i.variable]=typeof e==`string`?e:JSON.stringify(e))}return f.PRODUCT_CONFIG_FILE!==void 0&&(n.PRODUCT_CONFIG_FILE=f.PRODUCT_CONFIG_FILE),n};async function v(){let e=[],t=g?void 0:await o.execute([`trust`,`status`,`--json`],_()),n=t?.exitCode===0?c(t.stdout):void 0;if(!g&&n?.question!==void 0){let t=await o.chooseTrust(n.question);if(t!==`trust`&&t!==`restricted`&&t!==`quit`)return{ok:!1,detail:`Desktop trust answer was invalid.`};if(t===`quit`)return{ok:!1,detail:`Desktop launch cancelled.`};if(t===`restricted`&&(g=!0),t===`trust`){let t=await o.execute([`trust`,`--yes`],_());if(t.exitCode!==0)return{ok:!1,detail:t.stderr.trim()||`Workspace trust grant failed.`};let n=await o.execute([`trust`,`status`,`--json`],_()),r=n.exitCode===0?c(n.stdout):void 0;if(r?.trusted!==!0)return{ok:!1,detail:`Workspace trust could not be confirmed after grant.`};e=r.providerEnvRefs}}else e=n?.providerEnvRefs??[];let r=await o.execute([`daemon`,`start`,`--json`,...g?[`--restricted-workspace`]:[]],_(g?[]:e)),i=r.exitCode===0?l(r.stdout):void 0;return i===void 0?{ok:!1,detail:r.stderr.trim()||`Desktop daemon did not return a loopback endpoint.`}:{ok:!0,endpoint:i}}let y=()=>{if(m!==null)return m;let e=v().then(e=>(h=e.ok?e.endpoint.port:void 0,m=null,e),e=>{throw h=void 0,m=null,e});return p=m=e,e};return Object.freeze({config:d,userDataPath:i(d.storage.userRoot,`desktop`),start:y,reconnect:y,current:()=>p,port:()=>h,csp:()=>u(h)})}export{d as createDesktopCliController,u as desktopContentSecurityPolicy,l as parseDesktopDaemonStart,c as parseDesktopTrustStatus};
2
2
  //# sourceMappingURL=desktop-host.js.map
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  ;(function(){var v=parseInt(process.versions.node.split('.')[0],10);if(v<22){process.stderr.write('\n✗ Node.js 22+ is required (current: '+process.version+')\n\nUpgrade:\n nvm: nvm install 22 && nvm use 22\n Volta: volta install node@22\n Download: https://nodejs.org/en/download\n\n');process.exit(1);}})();
3
- import{R as e,c as t,g as n,h as r,l as i,m as a,o,p as s,s as c,t as l,u}from"./cli-core-DutvpRdJ.js";if(r(c(process.argv)))try{let e=u({});s(e),a(e.config.identity.cliName),i(e.environment),n(o(e))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}else try{let n=u({});s(n),a(n.config.identity.cliName);let r=t();!r.serve||r.printMode||r.goal!==void 0||r.positional.length>0||r.reset||r.configure||r.configureProvider!==void 0||r.checkUpdate||r.help||r.version?(process.stderr.write(`This headless runtime accepts only --serve.
3
+ import{R as e,c as t,g as n,h as r,l as i,m as a,o,p as s,s as c,t as l,u}from"./cli-core-Davokkgi.js";if(r(c(process.argv)))try{let e=u({});s(e),a(e.config.identity.cliName),i(e.environment),n(o(e))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}else try{let n=u({});s(n),a(n.config.identity.cliName);let r=t();!r.serve||r.printMode||r.goal!==void 0||r.positional.length>0||r.reset||r.configure||r.configureProvider!==void 0||r.checkUpdate||r.help||r.version?(process.stderr.write(`This headless runtime accepts only --serve.
4
4
  `),process.exitCode=2):l({productRuntime:n},e).catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1})}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exitCode=2}export{};
package/dist/node/host.js CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./product-host-zZ2TTtQk.js";export{e as createProductCliHost};
1
+ import{t as e}from"./product-host-CBylXlR9.js";export{e as createProductCliHost};
@@ -1,4 +1,4 @@
1
- import{C as e,S as t,T as n,_ as r,b as i,c as a,d as o,f as s,g as c,h as l,l as u,m as d,n as f,p,r as m,t as h,u as g,v as _,w as v,x as y,y as b}from"./product-host-zZ2TTtQk.js";import"node:module";import{createHash as x,createPublicKey as ee,randomBytes as S,randomUUID as C,verify as te}from"node:crypto";import{isAbsolute as w,join as T,posix as E}from"node:path";import"node:child_process";import{open as D,realpath as ne,rename as re,stat as ie,unlink as ae}from"node:fs/promises";import{closeSync as O,constants as k,existsSync as oe,fstatSync as se,fsyncSync as ce,lstatSync as le,mkdirSync as ue,openSync as de,readFileSync as fe,realpathSync as pe,renameSync as me,rmdirSync as he,unlinkSync as ge,writeFileSync as _e}from"node:fs";import{isIP as ve}from"node:net";import{ServerResponse as ye}from"node:http";import{performance as A}from"node:perf_hooks";import{Sandbox as j,SandboxNotFoundError as be}from"e2b/dist/index.mjs";import{WebSocket as M,WebSocketServer as xe}from"ws";var N=class extends Error{reason=`invalid-schema`;constructor(){super(`Invalid organization schema`)}};function Se(e){for(let t of e){let e=t.codePointAt(0);if(e>=55296&&e<=57343)throw new N}}function Ce(e){let t=new Set,n=0;function r(e,i){if(++n>4096||i>32)throw new N;if(e===null||typeof e==`boolean`)return JSON.stringify(e);if(typeof e==`string`)return Se(e),JSON.stringify(e);if(typeof e==`number`){if(!Number.isSafeInteger(e)||Object.is(e,-0))throw new N;return JSON.stringify(e)}if(typeof e!=`object`||t.has(e))throw new N;t.add(e);try{if(Array.isArray(e)){if(Reflect.ownKeys(e).length!==e.length+1)throw new N;return`[${Array.from({length:e.length},(t,n)=>{let a=Object.getOwnPropertyDescriptor(e,String(n));if(a===void 0||!(`value`in a))throw new N;return r(a.value,i+1)}).join(`,`)}]`}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new N;let t=Reflect.ownKeys(e);if(t.some(e=>typeof e!=`string`))throw new N;return`{${t.sort().map(t=>{Se(t);let n=Object.getOwnPropertyDescriptor(e,t);if(!n.enumerable||!(`value`in n))throw new N;return`${JSON.stringify(t)}:${r(n.value,i+1)}`}).join(`,`)}}`}finally{t.delete(e)}}let i=r(e,0);if(new TextEncoder().encode(i).byteLength>64*1024)throw new N;return i}function we(e,t){if(Ce(e),typeof e!=`object`||!e||Array.isArray(e))throw new N;let n=e;if(Object.keys(n).length!==t.length||t.some(e=>!Object.hasOwn(n,e)))throw new N;return n}function P(e,t=0){if(typeof e!=`number`||!Number.isSafeInteger(e)||Object.is(e,-0)||e<t)throw new N;return e}function Te(e){let t=we(e,[`tokens`,`timeMs`,`costMicros`]);return Object.freeze({tokens:P(t.tokens),timeMs:P(t.timeMs),costMicros:P(t.costMicros)})}var F=class extends Error{reason;constructor(e){super(`Organization operation refused: ${e}`),this.reason=e}};function I(e){try{return Ce(e)}catch(e){throw e instanceof N?new F(`invalid-schema`):e}}function Ee(e,t){if(![`workload`,`request`,`approval`].includes(e))throw new F(`invalid-schema`);return Buffer.from(I([`robota/organization-${e}/v1`,t]),`utf8`)}function L(e){return x(`sha256`).update(I([`robota/organization-operation/v1`,e.grantId,e.tenant,e.task,e.actor,e.audience,e.epoch,e.operation]),`utf8`).digest(`hex`)}function R(e,t){if(I(e),typeof e!=`object`||!e||Array.isArray(e))throw new F(`invalid-schema`);let n=e;if(Object.keys(n).length!==t.length||t.some(e=>!Object.hasOwn(n,e)))throw new F(`invalid-schema`);return n}function z(e){if(typeof e!=`string`||e.length<1||e.length>256||[...e].some(e=>{let t=e.codePointAt(0);return t<32||t===127||t>=55296&&t<=57343}))throw new F(`invalid-schema`);return e}function B(e,t=0){if(typeof e!=`number`||!Number.isSafeInteger(e)||Object.is(e,-0)||e<t)throw new F(`invalid-schema`);return e}function V(e){try{return Te(e)}catch(e){throw e instanceof N?new F(`invalid-schema`):e}}function De(e){let t=R(e,[`value`,`usage`]);return Object.freeze({value:H(JSON.parse(I(t.value))),usage:V(t.usage)})}function Oe(e){if(typeof e!=`string`||e.length>4096||!e.startsWith(`-----BEGIN PUBLIC KEY-----`))throw new F(`invalid-schema`);try{let t=ee(e);if(t.asymmetricKeyType!==`ed25519`)throw Error(`wrong type`);return t}catch{throw new F(`invalid-proof`)}}function H(e){if(typeof e==`object`&&e){for(let t of Object.values(e))H(t);Object.freeze(e)}return e}function ke(e){if(e.version!==1||B(e.expiresAt,1)<=B(e.notBefore))throw new F(`invalid-schema`);B(e.epoch,1)}function Ae(e){let t=R(e,[`version`,`grantId`,`tenant`,`task`,`actor`,`audience`,`epoch`,`nonce`,`notBefore`,`expiresAt`,`operation`]);ke(t);let n=R(t.operation,[`idempotencyKey`,`resource`,`operation`,`environment`,`parameters`]);return Object.freeze({version:1,grantId:z(t.grantId),tenant:z(t.tenant),task:z(t.task),actor:z(t.actor),audience:z(t.audience),epoch:B(t.epoch,1),nonce:z(t.nonce),notBefore:B(t.notBefore),expiresAt:B(t.expiresAt,1),operation:Object.freeze({idempotencyKey:z(n.idempotencyKey),resource:z(n.resource),operation:z(n.operation),environment:z(n.environment),parameters:H(JSON.parse(I(n.parameters)))})})}function je(e){let t=R(e,[`version`,`id`,`tenant`,`task`,`actor`,`audience`,`epoch`,`environment`,`operationDigest`,`notBefore`,`expiresAt`]);if(ke(t),typeof t.operationDigest!=`string`||!/^[a-f0-9]{64}$/.test(t.operationDigest))throw new F(`invalid-schema`);return Object.freeze({version:1,id:z(t.id),tenant:z(t.tenant),task:z(t.task),actor:z(t.actor),audience:z(t.audience),epoch:B(t.epoch,1),environment:z(t.environment),operationDigest:t.operationDigest,notBefore:B(t.notBefore),expiresAt:B(t.expiresAt,1)})}var Me=class extends Error{constructor(){super(`Organization audit append conflict`)}};const Ne=/^[0-9a-f]{64}$/,Pe=[`dispatch`,`complete`,`refused`,`unknown`];function U(e){return x(`sha256`).update(I(e),`utf8`).digest(`hex`)}function W(e){if(typeof e!=`string`||!Ne.test(e))throw new F(`invalid-schema`);return e}function Fe(e,t){let n=R(e,[`version`,`stream`,`sequence`,`hash`]);if(n.version!==1||n.stream!==t)throw new F(`invalid-schema`);return Object.freeze({version:1,stream:t,sequence:B(n.sequence),hash:W(n.hash)})}function G(e){let t=R(e,[`phase`,`operationDigest`,`tenantDigest`,`taskDigest`,`actorDigest`,`grantDigest`,`epoch`]);if(typeof t.phase!=`string`||!Pe.includes(t.phase))throw new F(`invalid-schema`);return Object.freeze({phase:t.phase,operationDigest:W(t.operationDigest),tenantDigest:W(t.tenantDigest),taskDigest:W(t.taskDigest),actorDigest:W(t.actorDigest),grantDigest:W(t.grantDigest),epoch:B(t.epoch,1)})}function K(e,t){if(!Pe.includes(t))throw new F(`invalid-schema`);let n=Ae(e),r=(e,t)=>U([`robota/organization-audit-identity/v1`,e,t]);return Object.freeze({phase:t,operationDigest:L(n),tenantDigest:r(`tenant`,[n.tenant]),taskDigest:r(`task`,[n.tenant,n.task]),actorDigest:r(`actor`,[n.tenant,n.actor]),grantDigest:r(`grant`,[n.grantId]),epoch:n.epoch})}function Ie(e){return z(e),Object.freeze({version:1,stream:e,sequence:0,hash:U([`robota/organization-audit-genesis/v1`,e])})}function Le(e,t,n,r){return U([`robota/organization-audit-entry/v1`,z(e),B(t,1),W(n),G(r)])}function Re(e){return Buffer.from(I([`robota/organization-audit-checkpoint/v1`,Fe(e,z(e.stream))]),`utf8`)}function q(e,t,n){let r=R(e,[`claims`,`signature`]),i=Fe(r.claims,t);if(typeof r.signature!=`string`||!/^[A-Za-z0-9_-]{86}$/.test(r.signature))throw new F(`invalid-proof`);let a=Buffer.from(r.signature,`base64url`);if(a.length!==64||a.toString(`base64url`)!==r.signature||!te(null,Re(i),n,a)||i.sequence===0&&i.hash!==Ie(t).hash)throw new F(`invalid-proof`);return Object.freeze({claims:i,signature:r.signature})}function ze(e,t){let n=R(e,[`stream`,`sequence`,`previous`,`event`,`hash`]),r=G(n.event);if(n.stream!==t.stream||n.sequence!==t.sequence+1||n.previous!==t.hash)throw new F(`invalid-proof`);let i=Le(t.stream,B(n.sequence,1),t.hash,r);if(n.hash!==i)throw new F(`invalid-proof`);return Object.freeze({stream:t.stream,sequence:n.sequence,previous:t.hash,event:r,hash:i})}function J(e,t){return e.stream===t.stream&&e.sequence===t.sequence&&e.hash===t.hash}function Be(e,t,n){let r=R(e,[`entries`,`head`]);if(!Array.isArray(r.entries)||r.entries.length>128)throw new F(`invalid-schema`);let i=q(r.head,t.stream,n),a=t;for(let e of r.entries){let t=ze(e,a);a={version:1,stream:t.stream,sequence:t.sequence,hash:t.hash}}if(!J(a,i.claims))throw new F(`invalid-proof`);return i}function Ve(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(o),t.removeEventListener(`abort`,a)},a=()=>{i(),r(new F(`policy-unavailable`))},o=setTimeout(()=>{i(),n()},e);t.addEventListener(`abort`,a,{once:!0}),t.aborted&&a()})}function Y(e){if(e.aborted)throw new F(`policy-unavailable`)}var He=class{stream;key;sink;anchor;timeout;constructor(e){if(this.stream=z(e.stream),this.key=Oe(e.publicKey),this.timeout=B(e.timeoutMs??1e3,1),this.timeout>3e4||typeof e.sink?.read!=`function`||typeof e.sink?.append!=`function`||typeof e.anchor?.load!=`function`||typeof e.anchor?.compareAndSet!=`function`)throw new F(`invalid-schema`);this.sink=Object.freeze({read:e.sink.read.bind(e.sink),append:e.sink.append.bind(e.sink)}),this.anchor=Object.freeze({load:e.anchor.load.bind(e.anchor),compareAndSet:e.anchor.compareAndSet.bind(e.anchor)})}async bounded(e,t){let n=new AbortController,r=()=>n.abort();t?.addEventListener(`abort`,r,{once:!0}),t?.aborted&&n.abort();let i,a=new Promise((e,t)=>{i=()=>t(new F(`policy-unavailable`)),n.signal.addEventListener(`abort`,i,{once:!0}),n.signal.aborted&&i()}),o=setTimeout(r,this.timeout);try{return await Promise.race([Promise.resolve().then(()=>(Y(n.signal),e(n.signal))),a])}catch{throw new F(`policy-unavailable`)}finally{clearTimeout(o),t?.removeEventListener(`abort`,r),n.signal.removeEventListener(`abort`,i),n.abort()}}async record(e,t){let n=G(e);await this.bounded(async e=>{let t=5;for(;;){Y(e);let r=q(await this.anchor.load(e),this.stream,this.key);Y(e);let i=Be(await this.sink.read(r.claims,e),r.claims,this.key);if(Y(e),!J(i.claims,r.claims)){await Ve(t,e),t=Math.min(t*2,50);continue}let a;try{a=R(await this.sink.append(r.claims,n,e),[`entry`,`head`])}catch(n){if(Y(e),!(n instanceof Me))throw n;await Ve(t,e),t=Math.min(t*2,50);continue}Y(e);let o=ze(a.entry,r.claims),s=q(a.head,this.stream,this.key);if(I(o.event)!==I(n)||!J(s.claims,{version:1,stream:o.stream,sequence:o.sequence,hash:o.hash}))throw new F(`invalid-proof`);let c=await this.anchor.compareAndSet(r.claims,s,e);if(Y(e),c!==!0)throw new F(`policy-unavailable`);return}},t)}async recover(e){return this.bounded(async e=>{let t=q(await this.anchor.load(e),this.stream,this.key);Y(e);let n=Be(await this.sink.read(t.claims,e),t.claims,this.key);if(Y(e),J(n.claims,t.claims))return n.claims;let r=await this.anchor.compareAndSet(t.claims,n,e);if(Y(e),r!==!0)throw new F(`policy-unavailable`);return n.claims},e)}async verify(e){return this.bounded(async e=>{let t=5;for(;;){let n=q(await this.anchor.load(e),this.stream,this.key);Y(e);let r=Be(await this.sink.read(n.claims,e),n.claims,this.key);if(Y(e),J(r.claims,n.claims))return n.claims;await Ve(t,e),t=Math.min(t*2,50)}},e)}};const Ue=[`budget-exhausted`,`not-authorized`,`invalid-schema`,`expired`,`revoked`,`operation-conflict`,`operation-pending`];function We(e){if(typeof e!=`string`||!Ue.includes(e))throw new F(`invalid-schema`);return e}var Ge=class extends F{usage;constructor(e,t){super(We(e)),this.usage=V(t)}};function Ke(e){let t=R(e,[`request`,`approval`]),n=R(t.request,[`claims`,`signature`]),r=t.approval===null?null:R(t.approval,[`claims`,`signature`]);if(typeof n.signature!=`string`||r!==null&&typeof r.signature!=`string`)throw new F(`invalid-proof`);return Object.freeze({request:Object.freeze({claims:Ae(n.claims),signature:n.signature}),approval:r===null?null:Object.freeze({claims:je(r.claims),signature:r.signature})})}var qe=class{audience;ledger;actions=new Map;interval;now;active=new Set;audit;auditReadiness;closed=!1;constructor(e){if(this.ledger=e.ledger,e.hosted===!0){if(this.ledger.verifyAnchoredAuthority(),!(e.audit instanceof He))throw new F(`policy-unavailable`);this.auditReadiness=e.audit.verify.bind(e.audit)}if(e.audit!==void 0){if(typeof e.audit?.record!=`function`)throw new F(`invalid-schema`);this.audit=Object.freeze({record:e.audit.record.bind(e.audit)})}if(this.audience=e.ledger.audience,this.interval=B(e.policyIntervalMs??100,1),this.interval>1e3)throw new F(`invalid-schema`);this.now=e.now??Date.now;for(let t of e.actions){let e=z(t.resource),n=z(t.operation),r=t.roles.map(z);if(r.length===0||new Set(r).size!==r.length||typeof t.requiresApproval!=`boolean`||typeof t.reserve!=`function`||typeof t.execute!=`function`)throw new F(`invalid-schema`);let i=I([e,n]);if(this.actions.has(i))throw new F(`invalid-schema`);this.actions.set(i,Object.freeze({resource:e,operation:n,roles:Object.freeze(r),requiresApproval:t.requiresApproval,reserve:t.reserve.bind(t),execute:t.execute.bind(t)}))}}async apply(e,t){if(this.closed)throw new F(`policy-unavailable`);if(t?.aborted||(await this.auditReadiness?.(t),this.closed||t?.aborted))throw new F(`not-authorized`);let n=Ke(e),{request:r,grant:i}=this.ledger.authenticate(n.request),a=this.actions.get(I([r.operation.resource,r.operation.operation]));if(a===void 0||!a.roles.includes(i.role))throw new F(`not-authorized`);let o=V(a.reserve(r.operation));if(B(o.timeMs,1),o.timeMs>2147483647)throw new F(`invalid-schema`);let s=this.ledger.reserve(n.request,o,n.approval,a.requiresApproval);if(s.kind===`complete`)return s.receipt;if(s.kind===`refused`)throw new F(s.reason);return this.execute(n.request,a,s,t)}async auditRecord(e,t,n){if(this.audit===void 0)return;let r,i=new Promise((e,t)=>{r=()=>t(new F(`outcome-unknown`)),n.addEventListener(`abort`,r,{once:!0}),n.aborted&&r()});try{if(await Promise.race([Promise.resolve().then(()=>{if(n.aborted)throw new F(`outcome-unknown`);return this.audit.record(K(e,t),n)}),i]),n.aborted)throw new F(`outcome-unknown`)}finally{n.removeEventListener(`abort`,r)}}async execute(e,t,n,r){let i=e.claims,a=new AbortController;this.active.add(a);let o=()=>a.abort();r?.addEventListener(`abort`,o,{once:!0}),(r?.aborted||this.closed)&&a.abort();let s=Math.min(n.reservation.timeMs,i.expiresAt-this.now(),n.grant.expiresAt-this.now()),c=setTimeout(o,Math.max(0,s)),l=setInterval(()=>{try{this.ledger.authenticate(e)}catch{a.abort()}},this.interval),u=A.now(),d;try{let r=new Promise((e,t)=>{d=()=>t(new F(`outcome-unknown`)),a.signal.addEventListener(`abort`,d,{once:!0}),a.signal.aborted&&d()}),o=Promise.resolve().then(async()=>{if(a.signal.aborted||(this.ledger.authenticate(e),await this.auditRecord(i,`dispatch`,a.signal),a.signal.aborted||A.now()-u>s))throw new F(`outcome-unknown`);return this.ledger.authenticate(e),t.execute(i.operation,{signal:a.signal,proof:e,operationDigest:n.digest,identity:n.grant,reservation:n.reservation})}),c=De(await Promise.race([o,r]));if(this.ledger.authenticate(e),a.signal.aborted||A.now()-u>s||(await this.auditRecord(i,`complete`,a.signal),this.ledger.authenticate(e),a.signal.aborted||A.now()-u>s))throw new F(`outcome-unknown`);let l=De({value:c.value,usage:{...c.usage,timeMs:Math.max(c.usage.timeMs,Math.ceil(A.now()-u))}});return this.ledger.settle(i,l),l}catch(e){if(e instanceof Ge&&!a.signal.aborted&&A.now()-u<=s){try{if(await this.auditRecord(i,`refused`,a.signal),a.signal.aborted||A.now()-u>s)throw new F(`outcome-unknown`);this.ledger.confirmNoEffect(i,We(e.reason),{...e.usage,timeMs:Math.max(e.usage.timeMs,Math.ceil(A.now()-u))})}catch{a.abort();try{this.ledger.markUnknown(i)}catch{}throw new F(`outcome-unknown`)}throw new F(e.reason)}a.abort();try{this.ledger.markUnknown(i)}catch{}try{await this.auditRecord(i,`unknown`,AbortSignal.timeout(1e3))}catch{}throw new F(`outcome-unknown`)}finally{clearTimeout(c),clearInterval(l),r?.removeEventListener(`abort`,o),d!==void 0&&a.signal.removeEventListener(`abort`,d),this.active.delete(a)}}close(){this.closed=!0;for(let e of this.active)e.abort()}},Je=class{ledger;audit;broker;inventory;incidents;timeout;timer;calls=new Map;sweepPending;closed=!1;quarantined=!1;constructor(e){this.ledger=e.ledger,this.audit=e.audit,this.broker=new qe({ledger:e.ledger,audit:e.audit,actions:e.actions,hosted:!0,policyIntervalMs:e.policyIntervalMs});let t=e.policyIntervalMs??100;if(this.timeout=e.providerTimeoutMs??1e4,!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>3e4||typeof e.inventory?.list!=`function`||typeof e.inventory.terminate!=`function`||typeof e.incidentOwners?.report!=`function`||[`detection`,`containment`,`assessment`,`recovery`].some(t=>{let n=e.incidentOwners[t];return typeof n!=`string`||n.trim().length===0}))throw new F(`invalid-schema`);this.inventory=Object.freeze({list:e.inventory.list.bind(e.inventory),terminate:e.inventory.terminate.bind(e.inventory)}),this.incidents=Object.freeze({...e.incidentOwners,report:e.incidentOwners.report.bind(e.incidentOwners)}),this.timer=setInterval(()=>{this.sweep().catch(()=>void 0)},t),this.timer.unref()}identity(e,t,n){let r=this.ledger.currentGrant(e);if(r.tenant!==t.tenant||r.task!==t.task||r.actor!==t.actor||r.epoch!==n)throw new F(`not-authorized`);return r}async admit(e,t){if(this.closed||this.quarantined)throw new F(`policy-unavailable`);this.ledger.verifyAnchoredAuthority();let n=this.identity(e.grantId,e.identity,e.epoch);if(await this.audit.verify(t),!(await this.inventory.list(t===void 0?AbortSignal.timeout(this.timeout):AbortSignal.any([t,AbortSignal.timeout(this.timeout)]))).some(t=>t.resource===e.resource&&t.grantId===e.grantId&&t.epoch===e.epoch&&Object.entries(e.identity).every(([e,n])=>t.identity[e]===n))||this.closed||this.quarantined||t?.aborted)throw new F(`not-authorized`);return this.identity(e.grantId,e.identity,e.epoch),n}async apply(e,t,n){if(this.closed||this.quarantined)throw new F(`policy-unavailable`);let r=new AbortController,i=()=>{n?.()};r.signal.addEventListener(`abort`,i,{once:!0});let a=()=>r.abort();t?.addEventListener(`abort`,a,{once:!0}),t?.aborted&&r.abort(),this.calls.set(r,e.request.claims.grantId);try{return await this.broker.apply(e,r.signal)}catch(t){throw t instanceof F&&t.reason===`outcome-unknown`&&await this.incidents.report({kind:`unknown-effect`,resources:[e.request.claims.operation.resource],operationDigest:L(e.request.claims)}).catch(()=>void 0),t}finally{this.calls.delete(r),t?.removeEventListener(`abort`,a),r.signal.removeEventListener(`abort`,i)}}async afterWithdrawal(){await this.sweepPending?.catch(()=>void 0),await this.sweep()}async stopGrant(e){this.ledger.revokeGrant(e),await this.afterWithdrawal()}async stopTask(e,t){this.ledger.stopTask(e,t),await this.afterWithdrawal()}async stopTenant(e){this.ledger.stopTenant(e),await this.afterWithdrawal()}async emergencyStop(){this.ledger.emergencyStop(),await this.afterWithdrawal()}async reconcileExternalOperation(e,t,n){this.ledger.verifyAnchoredAuthority();let r=K(e,`complete`),i=await t.confirm(r.operationDigest,n);return await this.audit.record(r,n),this.ledger.reconcileExternalOperation(e,i)}sweep(){return this.sweepPending===void 0&&(this.sweepPending=this.sweepOnce().finally(()=>{this.sweepPending=void 0})),this.sweepPending}async sweepOnce(){let e=!this.closed&&!this.quarantined,t=this.closed||this.quarantined;try{this.ledger.verifyAnchoredAuthority(),await this.audit.verify(AbortSignal.timeout(this.timeout))}catch{t=!0}t&&!this.closed&&(this.quarantined=!0,this.broker.close());for(let[e,n]of this.calls)try{if(t)throw new F(`policy-unavailable`);this.ledger.currentGrant(n)}catch{e.abort()}let n;try{n=await this.inventory.list(AbortSignal.timeout(this.timeout))}catch{this.quarantined=!0,this.broker.close();for(let e of this.calls.keys())e.abort();throw await this.incidents.report({kind:`cleanup-unresolved`,resources:[]}),new F(`policy-unavailable`)}let r=n.filter(e=>{try{return t?!0:(this.identity(e.grantId,e.identity,e.epoch),!1)}catch{return!0}}),i=await Promise.allSettled(r.map(e=>this.inventory.terminate(e,AbortSignal.timeout(this.timeout)))),a=r.filter((e,t)=>i[t].status===`rejected`).map(e=>e.resource);if(t&&e&&await this.incidents.report({kind:`authority-unavailable`,resources:r.map(e=>e.resource)}),a.length>0)throw await this.incidents.report({kind:`cleanup-unresolved`,resources:a}),new F(`policy-unavailable`)}async close(){this.closed=!0,clearInterval(this.timer),this.broker.close();for(let e of this.calls.keys())e.abort();await this.afterWithdrawal()}};function Ye(t){let n=e(t.controlPlane,`organization control plane`),r=e(t.tenant,`organization tenant`),i={apiKey:e(t.apiKey,`E2B management credential`),requestTimeoutMs:v(t.requestTimeoutMs??1e4,`E2B request timeout`,3e4),apiUrl:`https://api.e2b.app`,sandboxUrl:`https://sandbox.e2b.app`,domain:`e2b.app`,debug:!1,retries:0};function a(t){if(t.metadata.organizationControlPlane!==n||t.metadata.tenant!==r)throw Error(`Organization inventory ownership mismatch`);return Object.freeze({resource:e(t.sandboxId,`organization worker`),grantId:e(t.metadata.organizationGrant,`organization grant`),epoch:v(Number(t.metadata.epoch),`organization epoch`),identity:b({tenant:t.metadata.tenant,task:t.metadata.task,rootTask:t.metadata.rootTask,actor:t.metadata.actor,runtime:t.metadata.runtime})})}return{async list(e){let t=j.list({...i,query:{metadata:{organizationControlPlane:n,tenant:r},state:[`running`,`paused`]},limit:100}),o=[],s=new Set;for(;t.hasNext;){e.throwIfAborted();for(let n of await t.nextItems({...i,signal:e})){let e=a(n);if(s.has(e.resource)||o.length>=1e4)throw Error(`Organization inventory is incomplete`);s.add(e.resource),o.push(e)}}return o},async terminate(e,t){t.throwIfAborted();let n;try{n=await j.getInfo(e.resource,{...i,signal:t})}catch(e){if(e instanceof be)return;throw Error(`Organization cleanup is unresolved`)}let r=a(n);if(r.grantId!==e.grantId||r.epoch!==e.epoch||Object.entries(e.identity).some(([e,t])=>r.identity[e]!==t))throw Error(`Organization cleanup ownership mismatch`);await j.kill(e.resource,i)}}}function Xe(e){let t=[...e.bindings],n=new Set,i=new Set,a=new Set;for(let r of t){if(!/^[A-Za-z0-9_-]{32,256}$/u.test(r.token)||n.has(r.token)||i.has(r.config.identity.runtime)||a.has(r.grantId))throw new F(`invalid-schema`);let t=e.ledger.currentGrant(r.grantId);if(t.scopes.length!==1||t.scopes[0].resource!==e.modelResource||t.scopes[0].operations.length!==1||t.scopes[0].operations[0]!==`generate`)throw new F(`not-authorized`);n.add(r.token),i.add(r.config.identity.runtime),a.add(r.grantId)}let o=t=>{let n=e.ledger.budgetState(`grant`,t.grantId);return{sessions:1,modelCalls:e.ledger.grantOperationCount(t.grantId),modelTokens:n.spent.tokens,costMicros:n.spent.costMicros}};return(n,i)=>{let a=new AbortController,s=()=>{i.writableFinished||a.abort()};i.once(`close`,s);let c=setTimeout(()=>{a.abort(),n.destroy(),i.destroy()},3e4),l=(e,t)=>{i.destroyed||i.writableEnded||(i.writeHead(e,{"content-type":`application/json`,"cache-control":`no-store`}),i.end(JSON.stringify(t)))};(async()=>{try{let s=new Set;for(let e=0;e<n.rawHeaders.length;e+=2){let t=n.rawHeaders[e].toLowerCase();if([`host`,`authorization`,`idempotency-key`,`content-type`,`content-length`,`transfer-encoding`,`origin`].includes(t)){if(s.has(t))throw new F(`invalid-schema`);s.add(t)}}if(n.method!==`POST`||n.headers.origin!==void 0||n.headers[`content-type`]!==`application/json`||n.headers[`content-encoding`]!==void 0)throw new F(`not-authorized`);let c=[],u=0;for await(let e of n){let t=Buffer.from(e);if(u+=t.length,u>4*1024*1024)throw new F(`invalid-schema`);c.push(t)}let d=Buffer.concat(c),f=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(d));if(!f||Array.isArray(f))throw new F(`invalid-schema`);let p=[`/v1/chat/completions`,`/v1/responses`].includes(n.url??``),m=p?t.find(e=>n.headers.authorization===`Bearer ${e.token}`):t.find(e=>f.identity?.runtime===e.config.identity.runtime);if(!m||m.expiresAt<=Date.now())throw new F(`expired`);let h=m.config;if(n.headers.host!==new URL(h.broker.endpoint).host||new URL(h.worker.endpoint).origin!==new URL(h.broker.endpoint).origin)throw new F(`not-authorized`);let g=await e.control.admit({resource:h.worker.resource,grantId:m.grantId,identity:h.identity,epoch:h.epoch},a.signal);if(!p){let e=n.url===new URL(h.worker.endpoint).pathname?`worker`:n.url===new URL(h.broker.endpoint).pathname?`broker`:void 0;if(!e||typeof f.nonce!=`string`||f.version!==3||f.role!==e||f.resource!==h[e].resource||f.epoch!==h.epoch||Object.entries(h.identity).some(([e,t])=>f.identity?.[e]!==t)||JSON.stringify(f.snapshot)!==JSON.stringify(h.snapshot)||JSON.stringify(f.limits)!==JSON.stringify(h.limits))throw new F(`not-authorized`);let t=Date.now(),i={version:3,identity:h.identity,role:e,resource:h[e].resource,nonce:f.nonce,epoch:h.epoch,issuedAt:t,expiresAt:Math.min(t+6e4,m.expiresAt,g.expiresAt),snapshot:h.snapshot,ready:!0,limits:h.limits,usage:e===`broker`?o(m):null},a={...i,signature:m.signAdmission(e,r(i))};_(a,h,e,f.nonce,Date.now()),l(200,a);return}let v=n.headers[`idempotency-key`];if(typeof v!=`string`||!/^[A-Za-z0-9_-]{1,128}$/u.test(v))throw new F(`invalid-schema`);let y=await e.payloads.put(g.id,d),b=Date.now(),x={version:1,grantId:g.id,tenant:g.tenant,task:g.task,actor:g.actor,audience:g.audience,epoch:g.epoch,nonce:C(),notBefore:b,expiresAt:Math.min(b+25e3,m.expiresAt,g.expiresAt),operation:{idempotencyKey:v,resource:e.modelResource,operation:`generate`,environment:`hosted`,parameters:{request:y,surface:n.url===`/v1/responses`?`responses`:`chat-completions`}}},ee={claims:x,signature:m.signRequest(Ee(`request`,x))};await e.payloads.recordOperation(x);let S=(await e.control.apply({request:ee,approval:null},a.signal,()=>i.destroy())).value?.response;if(typeof S!=`string`)throw new F(`outcome-unknown`);let te=await e.payloads.get(g.id,S),w=JSON.parse(te.toString(`utf8`));if(f.stream===!0)if(i.writeHead(200,{"content-type":`text/event-stream`,"cache-control":`no-store`}),n.url===`/v1/responses`){let e=w.output;if(Array.isArray(e)){for(let t of e)if(t.type===`message`&&Array.isArray(t.content))for(let e of t.content)e.type===`output_text`&&typeof e.text==`string`&&i.write(`data: ${JSON.stringify({type:`response.output_text.delta`,delta:e.text})}\n\n`)}i.end(`data: ${JSON.stringify({type:`response.completed`,response:w})}\n\n`)}else{let e=w.choices;if(!Array.isArray(e))throw new F(`outcome-unknown`);i.write(`data: ${JSON.stringify({...w,object:`chat.completion.chunk`,choices:e.map(e=>({index:e.index,delta:{...e.message,...Array.isArray(e.message.tool_calls)?{tool_calls:e.message.tool_calls.map((e,t)=>({...e,index:t}))}:{}},finish_reason:null}))})}\n\n`),i.end(`data: ${JSON.stringify({...w,object:`chat.completion.chunk`,choices:e.map(e=>({index:e.index,delta:{},finish_reason:e.finish_reason}))})}\n\ndata: [DONE]\n\n`)}else l(200,w)}catch(e){i.headersSent?i.destroy():l(e instanceof F&&[`policy-unavailable`,`outcome-unknown`].includes(e.reason)?503:403,{error:{message:e instanceof F?e.message:`Organization ingress refused`,type:`organization_refusal`}}),n.resume()}finally{clearTimeout(c),i.removeListener(`close`,s)}})()}}var Ze=class e{directory;constructor(e){this.directory=e}static async open(t){if(!w(t))throw new F(`policy-unavailable`);let n=await ne(t),r=await ie(n);if(!r.isDirectory()||r.mode&63||process.getuid!==void 0&&r.uid!==process.getuid())throw new F(`policy-unavailable`);return new e(n)}path(e,t){if(!/^[a-f0-9]{64}$/u.test(t))throw new F(`invalid-schema`);let n=x(`sha256`).update(e).digest(`hex`);return T(this.directory,`${n}-${t}.json`)}async put(e,t){if(t.length>4*1024*1024)throw new F(`invalid-schema`);let n=x(`sha256`).update(t).digest(`hex`),r=this.path(e,n);return await this.persist(r,t),n}async persist(e,t){let n=T(this.directory,`${C()}.tmp`);try{let r=await D(n,`wx`,384);try{await r.writeFile(t),await r.sync()}finally{await r.close()}await re(n,e);let i=await D(this.directory,k.O_RDONLY);try{await i.sync()}finally{await i.close()}}catch{throw new F(`policy-unavailable`)}finally{await ae(n).catch(()=>void 0)}}async recordOperation(e){let t=L(e),n=await this.put(e.grantId,Buffer.from(JSON.stringify(e)));await this.persist(`${this.path(e.grantId,t)}.operation`,Buffer.from(JSON.stringify({requestDigest:n})))}async operation(e,t){let n=await D(`${this.path(e,t)}.operation`,k.O_RDONLY|k.O_NOFOLLOW|k.O_NONBLOCK);try{let r=await n.stat();if(!r.isFile()||r.size>4096||r.mode&63||process.getuid!==void 0&&r.uid!==process.getuid())throw new F(`policy-unavailable`);let i=JSON.parse(await n.readFile(`utf8`));if(typeof i.requestDigest!=`string`)throw new F(`policy-unavailable`);let a=JSON.parse((await this.get(e,i.requestDigest)).toString(`utf8`));if(K(a,`complete`),a.grantId!==e||L(a)!==t)throw new F(`policy-unavailable`);return a}finally{await n.close()}}async get(e,t){try{let n=await D(this.path(e,t),k.O_RDONLY|k.O_NOFOLLOW|k.O_NONBLOCK);try{let e=await n.stat();if(!e.isFile()||e.size>4*1024*1024||e.mode&63||process.getuid!==void 0&&e.uid!==process.getuid())throw Error(`unowned content`);let r=await n.readFile();if(x(`sha256`).update(r).digest(`hex`)!==t)throw Error(`changed content`);return r}finally{await n.close()}}catch{throw new F(`policy-unavailable`)}}};function Qe(e){let t=new URL(e.endpoint);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(t.hostname))||t.username||t.password||t.search||t.hash||typeof e.apiKey!=`string`||/[\r\n]/u.test(e.apiKey)||e.apiKey.length===0||!Number.isSafeInteger(e.maxInputBytes)||e.maxInputBytes<1||e.maxInputBytes>4*1024*1024||!Number.isSafeInteger(e.maxOutputTokens)||e.maxOutputTokens<1||!Number.isSafeInteger(e.costMicrosPerToken)||e.costMicrosPerToken<0||typeof e.countInputTokens!=`function`)throw new F(`invalid-schema`);let n=Object.freeze({...e.reservation}),r=e.countInputTokens.bind(e),i=e=>{let t=e;if(!t||Object.keys(t).sort().join(`,`)!==`request,surface`||typeof t.request!=`string`||!/^[a-f0-9]{64}$/u.test(t.request)||![`responses`,`chat-completions`].includes(String(t.surface)))throw new F(`invalid-schema`);return t};return{resource:e.resource,operation:`generate`,roles:[...e.roles],requiresApproval:!1,reserve:e=>(i(e.parameters),n),execute:async(a,o)=>{let s=i(a.parameters),c=await e.payloads.get(o.identity.id,s.request);if(c.length>e.maxInputBytes)throw new F(`invalid-schema`);let l=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(c));if(!l||Array.isArray(l)||l.model!==e.model)throw new F(`not-authorized`);let u={...l,stream:!1};if([`conversation`,`previous_response_id`,`prompt`].some(e=>u[e]!=null)||Array.isArray(u.tools)&&u.tools.some(e=>e?.type!==`function`))throw new Ge(`not-authorized`,{tokens:0,timeMs:0,costMicros:0});delete u.max_tokens,delete u.max_completion_tokens,delete u.max_output_tokens,delete u.stream_options,u[s.surface===`responses`?`max_output_tokens`:`max_completion_tokens`]=e.maxOutputTokens,u.store=!1,u.n=s.surface===`chat-completions`?1:void 0,s.surface===`responses`&&(delete u.n,u.background=!1);let d=JSON.stringify(u),f=await r(s.surface,JSON.parse(d),o.signal),p=f+e.maxOutputTokens;if(!Number.isSafeInteger(f)||f<0||!Number.isSafeInteger(p)||p>n.tokens||!Number.isSafeInteger(p*e.costMicrosPerToken)||p*e.costMicrosPerToken>n.costMicros)throw new Ge(`budget-exhausted`,{tokens:0,timeMs:0,costMicros:0});o.signal.throwIfAborted();let m=await fetch(`${t.href.replace(/\/$/u,``)}/${s.surface===`responses`?`responses`:`chat/completions`}`,{method:`POST`,redirect:`error`,signal:o.signal,headers:{authorization:`Bearer ${e.apiKey}`,"content-type":`application/json`,...e.providerIdempotency?{"Idempotency-Key":o.operationDigest}:{}},body:d});if(!m.ok||m.body===null)throw await m.body?.cancel(),new F(`outcome-unknown`);let h=[],g=0,_=m.body.getReader();try{for(;;){let e=await _.read();if(e.done)break;if(g+=e.value.length,g>4*1024*1024)throw new F(`outcome-unknown`);h.push(e.value)}}finally{await _.cancel()}let v=Buffer.concat(h),y=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(v))?.usage?.total_tokens;if(typeof y!=`number`||!Number.isSafeInteger(y)||y<0||y>n.tokens||!Number.isSafeInteger(y*e.costMicrosPerToken)||y*e.costMicrosPerToken>n.costMicros)throw new F(`outcome-unknown`);return{value:{response:await e.payloads.put(o.identity.id,v)},usage:{tokens:y,timeMs:0,costMicros:y*e.costMicrosPerToken}}}}}function $e(e){let t=new URL(e.endpoint);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(t.hostname))||t.username||t.password||t.search||t.hash||typeof e.encode!=`function`||typeof e.apiKey!=`string`||e.apiKey.length===0||/[\r\n]/u.test(e.apiKey))throw new F(`invalid-schema`);let n=e.apiKey,r=e.encode.bind(e);return async(e,i,a)=>{let o=await fetch(t,{method:`POST`,redirect:`error`,signal:a,headers:{authorization:`Bearer ${n}`,"content-type":`application/json`},body:JSON.stringify(r(e,i))});if(!o.ok||o.body===null)throw await o.body?.cancel(),new F(`policy-unavailable`);let s=[],c=0,l=o.body.getReader();try{for(;;){let e=await l.read();if(e.done)break;if(c+=e.value.length,c>64*1024)throw new F(`policy-unavailable`);s.push(e.value)}}finally{await l.cancel()}let u=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(Buffer.concat(s)));if(!Number.isSafeInteger(u?.input_tokens)||u.input_tokens<0)throw new F(`policy-unavailable`);return u.input_tokens}}function et(r,i,a){if(r.byteLength>48*1024*1024||x(`sha256`).update(r).digest(`hex`)!==i.digest)throw t(`filesystem checkpoint digest or size is invalid`);let o;try{o=n(JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(r)),`checkpoint`)}catch{throw t(`filesystem checkpoint is not valid UTF-8 JSON`)}if(y(o,[`version`,`id`,`identity`,`epoch`,`worker`,`files`,...o.version===2?[`session`]:[]],`checkpoint`),o.version!==1&&o.version!==2||o.id!==i.id)throw t(`filesystem checkpoint version or identity does not match`);let s=b(o.identity),c=v(o.epoch,`checkpoint epoch`),l=e(o.worker,`checkpoint worker`);if([`tenant`,`task`,`rootTask`].some(e=>s[e]!==a.identity[e])||s.runtime===a.identity.runtime||c>=a.epoch)throw t(`filesystem checkpoint requires the same task and a fresh identity/epoch`);if(!Array.isArray(o.files)||o.files.length>1e3)throw t(`filesystem checkpoint file inventory is invalid`);let u=new Set,f=0,p=o.files.map(r=>{let i=n(r,`checkpoint file`);y(i,[`path`,`base64`],`checkpoint file`);let a=e(i.path,`checkpoint file path`),o=a.split(`/`)[0];if(E.isAbsolute(a)||E.normalize(a)!==a||a===`.`||a===`..`||a.startsWith(`../`)||a.endsWith(`/`)||a.includes(`\\`)||o===`.home`||o===`.tmp`||u.has(a))throw t(`filesystem checkpoint path escapes or replaces private state`);if(typeof i.base64!=`string`||i.base64.length>44*1024*1024)throw t(`filesystem checkpoint file encoding is invalid`);let s=Buffer.from(i.base64,`base64`);if(f+=s.byteLength,s.toString(`base64`)!==i.base64||f>32*1024*1024)throw t(`filesystem checkpoint encoding or byte budget is invalid`);return u.add(a),Object.freeze({path:a,bytes:new Uint8Array(s)})});for(let e of u){let n=E.dirname(e);for(;n!==`.`;){if(u.has(n))throw t(`filesystem checkpoint file conflicts with a directory`);n=E.dirname(n)}}return Object.freeze({sourceWorker:l,sourceRuntime:s.runtime,sourceEpoch:c,files:p,...o.version===2?{session:d(o.session,`/`)}:{}})}var X=class extends Error{outcome;operationId;resource;constructor(e,t,n){super(`E2B worker provisioning ${e}; owner reconciliation is required`),this.outcome=e,this.operationId=t,this.resource=n,this.name=`E2BWorkerProvisioningError`}};async function tt(n){let r=b(n.identity),a=v(n.epoch,`worker epoch`),o=e(n.templateId,`E2B clean template`),s=i(n.snapshot);if(s===null!=(n.checkpoint===void 0)||s?.id===o)throw t(`worker recovery requires checkpoint bytes and a separate clean template`);let c=s===null?void 0:et(n.checkpoint,s,{identity:r,epoch:a}),l;try{l=new URL(n.brokerEndpoint)}catch{throw t(`worker broker endpoint is invalid`)}if(l.protocol!==`https:`&&!(l.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(l.hostname))||l.username||l.password||l.search||l.hash)throw t(`worker broker endpoint requires owner-selected TLS or literal loopback`);let u={apiKey:e(n.apiKey,`E2B management credential`),requestTimeoutMs:v(n.requestTimeoutMs,`E2B request timeout`,3e4),apiUrl:`https://api.e2b.app`,sandboxUrl:`https://sandbox.e2b.app`,domain:`e2b.app`,debug:!1,retries:0},d=v(n.lifetimeMs,`E2B lifetime`,864e5),f=C(),m={...r,epoch:String(a),operationId:f,...n.organization===void 0?{}:{organizationControlPlane:e(n.organization.controlPlane,`organization control plane`),organizationGrant:e(n.organization.grantId,`organization grant`)},...s===null?{}:{restoreMode:`filesystem-v1`,checkpointId:s.id,checkpointDigest:s.digest,sourceWorker:c.sourceWorker,sourceRuntime:c.sourceRuntime,sourceEpoch:String(c.sourceEpoch)}};n.signal.throwIfAborted();let h;try{h=await j.create(o,{...u,timeoutMs:d,metadata:m,envs:{},allowInternetAccess:!1,network:{allowPublicTraffic:!1,allowOut:[l.hostname]},lifecycle:{onTimeout:`kill`,autoResume:!1}})}catch{throw new X(`allocation-unknown`,f)}let g;try{g=e(h.sandboxId,`allocated worker`)}catch{throw new X(`allocation-unknown`,f)}let _,y=()=>(_===void 0&&(_=j.kill(g,u).then(()=>void 0).catch(()=>{throw new X(`cleanup-unresolved`,f,g)})),_);try{let e=await j.getInfo(g,u).catch(()=>{throw new X(`allocation-unknown`,f,g)});if(e.sandboxId!==g||Object.entries(m).some(([t,n])=>e.metadata[t]!==n))throw new X(`allocation-unknown`,f,g);if(g===c?.sourceWorker)throw t(`provider returned the checkpoint source instead of a fresh worker`);if(e.templateId!==o||e.state!==`running`||e.lifecycle?.onTimeout!==`kill`||e.lifecycle.autoResume!==!1||e.allowInternetAccess!==!1||e.network?.allowPublicTraffic!==!1||JSON.stringify(e.network.allowOut??[])!==JSON.stringify([l.hostname])||(e.volumeMounts?.length??0)!==0||e.network.egressProxy!==void 0||Object.keys(e.network.rules??{}).length!==0)throw t(`allocated worker ownership, clean template or network posture is invalid`);n.signal.throwIfAborted();let r=await h.commands.run(`umask 077; mktemp -d "\${TMPDIR:-/tmp}/agent-task-${f}-XXXXXXXXXX"`,{cwd:`/`,envs:{},timeoutMs:n.requestTimeoutMs,requestTimeoutMs:n.requestTimeoutMs});if(r.exitCode!==0||typeof r.stdout!=`string`)throw t(`fresh worker workspace creation failed`);let i=r.stdout.trim();if(!/^\/[A-Za-z0-9._/-]+$/u.test(i)||E.normalize(i)!==i||!RegExp(`^agent-task-${f}-[A-Za-z0-9]{10}$`,`u`).test(E.basename(i)))throw t(`fresh worker workspace receipt is invalid`);for(let e of c?.files??[]){n.signal.throwIfAborted();let r=E.join(i,e.path);await h.files.write(r,e.bytes.slice().buffer,{requestTimeoutMs:n.requestTimeoutMs});let a=await h.files.read(r,{format:`bytes`,requestTimeoutMs:n.requestTimeoutMs});if(!Buffer.from(a).equals(Buffer.from(e.bytes)))throw t(`restored filesystem checkpoint bytes do not match`)}let a;if(c?.session!==void 0){n.signal.throwIfAborted();let e={...c.session,cwd:i},r=p(e),o=E.join(i,`.home`,`.checkpoint-sessions`,`${e.id}.json`);await h.files.write(o,Uint8Array.from(r).buffer,{requestTimeoutMs:n.requestTimeoutMs});let s=await h.files.read(o,{format:`bytes`,requestTimeoutMs:n.requestTimeoutMs});if(!Buffer.from(s).equals(r))throw t(`restored conversation checkpoint bytes do not match`);a=Object.freeze({id:e.id,path:o,digest:x(`sha256`).update(r).digest(`hex`)})}return n.signal.throwIfAborted(),Object.freeze({resource:g,workspaceRoot:i,operationId:f,snapshot:s,release:y,...a===void 0?{}:{resumeSession:a}})}catch(e){throw e instanceof X&&e.outcome===`allocation-unknown`||(await y(),n.signal.aborted&&n.signal.throwIfAborted(),e instanceof Error&&e.message.startsWith(`Hosted runtime admission refused:`))?e:t(`fresh worker provisioning or filesystem restoration failed`)}}var Z=class extends Error{reason;constructor(e){super(`Remote desktop refused: ${e}`),this.reason=e}};function Q(e){return JSON.stringify([e.id,e.user,e.client,e.session,e.worker.resource,e.worker.grantId,e.worker.epoch,e.worker.identity.tenant,e.worker.identity.task,e.worker.identity.rootTask,e.worker.identity.actor,e.worker.identity.runtime])}var nt=class{options;url;now;bindings;constructor(e){if(this.options=e,this.url=u(e.publicUrl,`Desktop runtime`),u(e.issuer,`Desktop issuer`),this.now=e.now??Date.now,this.bindings=e.bindings.map(e=>{let t=structuredClone(e);return Object.freeze(t.worker.identity),Object.freeze(t.worker),Object.freeze(t)}),e.bindings.length===0||e.bindings.length>100||e.bindings.some(e=>[e.id,e.user,e.client,e.session].some(e=>typeof e!=`string`||e.length===0||e.length>256||/[\r\n]/u.test(e)))||new Set(e.bindings.map(e=>e.id)).size!==e.bindings.length)throw new Z(`owner-bindings`)}binding(e){let t=this.bindings.find(t=>t.id===e);if(!t)throw new Z(`owner-binding`);return t}async verify(e,t,n=!1,r){if(r?.throwIfAborted(),!this.bindings.some(e=>Q(e)===Q(t)))throw new Z(`owner-binding`);let i=await g({issuer:this.options.issuer,resource:n?`${this.url.href.replace(/\/$/u,``)}/approval`:this.url.href,algorithms:[`EdDSA`,`ES256`,`RS256`],allowedSubjects:[t.user],requiredScopes:n?[`desktop:approve`]:[`desktop:pair`,`desktop:drive`]},this.options.verifierDeps).verify(e);if(!i.admitted)throw new Z(i.refusal);let a=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`)),o=this.now();if(typeof a.iat!=`number`||!Number.isSafeInteger(a.iat)||typeof a.exp!=`number`||!Number.isSafeInteger(a.exp)||a.iat*1e3>o||a.exp*1e3<=o||a.exp-a.iat>120||a.nbf!==void 0&&(typeof a.nbf!=`number`||!Number.isSafeInteger(a.nbf)||a.nbf*1e3>o)||typeof a.jti!=`string`||!/^[A-Za-z0-9_-]{8,256}$/u.test(a.jti))throw new Z(`short-lived-credential`);if(a.sub!==t.user||a.client_id!==t.client||a.tenant!==t.worker.identity.tenant||a.task!==t.worker.identity.task||a.session!==t.session||a.workload!==t.worker.identity.runtime||a.epoch!==t.worker.epoch)throw new Z(`session-ownership`);r?.throwIfAborted();let s=await this.options.control.admit(t.worker,r);return r?.throwIfAborted(),{binding:t,jti:a.jti,credentialExpiresAt:a.exp*1e3,expiresAt:Math.min(a.exp*1e3,s.expiresAt,o+6e4)}}async current(e,t){if(!this.bindings.some(t=>Q(t)===Q(e)))throw new Z(`owner-binding`);await this.options.control.admit(e.worker,t)}};const $=e=>x(`sha256`).update(e).digest(`hex`),rt=(e,t)=>e?.version===t.version&&e.ledger===t.ledger&&e.revision===t.revision&&e.digest===t.digest;var it=class{now;directory;file;lock;constructor(e,t=Date.now){if(this.now=t,this.anchor=e.anchor,!w(e.directory))throw new Z(`store-unavailable`);this.directory=pe(e.directory);let n=le(this.directory);if(!n.isDirectory()||n.mode&63||process.getuid!==void 0&&n.uid!==process.getuid())throw new Z(`store-unavailable`);if(this.file=T(this.directory,`desktop-authority.json`),this.lock=T(this.directory,`desktop-authority.lock`),e.create===!0){if(oe(this.file)||this.anchor.read()!==void 0)throw new Z(`store-unavailable`);this.locked(()=>this.write(void 0,{version:1,revision:1,spent:{},connections:{}}))}this.read()}anchor;head(e){return{version:1,ledger:this.anchor.ledger,revision:e.revision,digest:$(JSON.stringify(e))}}read(){let e=de(this.file,k.O_RDONLY|k.O_NOFOLLOW|k.O_NONBLOCK);try{let t=se(e);if(!t.isFile()||t.size>2*1024*1024||t.mode&63||process.getuid!==void 0&&t.uid!==process.getuid())throw new Z(`store-unavailable`);let n=JSON.parse(fe(e,`utf8`)),r=this.anchor.read();if(n.version!==1||!Number.isSafeInteger(n.revision)||n.revision<1||!n.spent||!n.connections||!rt(r,this.head(n)))throw new Z(`store-unavailable`);return n}finally{O(e)}}locked(e){ue(this.lock,{mode:448});try{return e()}finally{he(this.lock)}}write(e,t){let n=T(this.directory,`desktop-${C()}.tmp`);try{let r=de(n,`wx`,384);try{_e(r,JSON.stringify(t)),ce(r)}finally{O(r)}let i=this.head(t);if(this.anchor.compareAndSet(e===void 0?void 0:this.head(e),i),!rt(this.anchor.read(),i))throw new Z(`store-unavailable`);me(n,this.file);let a=de(this.directory,k.O_RDONLY);try{ce(a)}finally{O(a)}}finally{oe(n)&&ge(n)}}change(e){return this.locked(()=>{let t=this.read(),n=structuredClone(t),r=e(n);return n.revision++,this.write(t,n),r})}pair(e,t,n,r){let i=S(32).toString(`base64url`),a=r?S(32).toString(`base64url`):null;return this.change(r=>{for(let[e,t]of Object.entries(r.spent))t<=this.now()&&delete r.spent[e];if(n<=this.now()||t.length===0||new Set(t.map(e=>e.id)).size!==t.length||t.some(e=>!Number.isSafeInteger(e.expiresAt)||e.expiresAt<n)||Object.keys(r.spent).length+t.length>4096||t.some(e=>r.spent[$(e.id)]!==void 0))throw new Z(`replayed-pairing`);let o=$(e);if(r.connections[o]===void 0&&Object.keys(r.connections).length>=100)throw new Z(`connection-capacity`);let s=(r.connections[o]?.generation??0)+1;r.connections[o]={generation:s,access:$(i),approval:a===null?null:$(a),expiresAt:n,connected:!1};for(let e of t)r.spent[$(e.id)]=e.expiresAt;return{key:e,generation:s,token:i,approvalToken:a,expiresAt:n}})}authorize(e,t,n,r=!1){let i=this.read().connections[$(e)];if(!i||i.generation!==t||i.expiresAt<=this.now()||(r?i.approval:i.access)!==$(n))throw new Z(`withdrawn-connection`)}connect(e,t,n){this.authorize(e,t,n),this.change(n=>{let r=n.connections[$(e)];if(r.generation!==t||r.expiresAt<=this.now()||r.connected)throw new Z(`replayed-connection`);r.connected=!0})}approveOnce(e,t,n,r){this.authorize(e,t,n,!0),this.change(i=>{let a=i.connections[$(e)];if(a.generation!==t||a.expiresAt<=this.now()||a.approval!==$(n))throw new Z(`withdrawn-connection`);let o=$(`approval:${e}:${r}`);if(i.spent[o]!==void 0)throw new Z(`replayed-approval`);if(Object.keys(i.spent).length>=4096)throw new Z(`approval-capacity`);i.spent[o]=2**53-1})}revoke(e){this.change(t=>{let n=t.connections[$(e)];n&&(n.generation++,n.expiresAt=0)})}};const at=128*1024,ot=new Set([`get-messages`,`get-status`,`get-context`,`get-history`,`get-prompts`,`get-pending`,`get-executing`,`get-execution-workspace`,`get-execution-detail`,`project-status`,`project-diff`,`project-memory`,`get-usage-report`,`get-background-tasks`,`list-models`,`get-agent-definitions`]),st=new Set([`sessions`,`session_list`,`session_renamed_in_list`,`session_deleted`,`ui_intent`,`settings`,`commands`]);function ct(e){return x(`sha256`).update(`robota/desktop-permission/v1\0`).update(JSON.stringify(e)).digest(`hex`)}var lt=class e{socket;worker;session;listeners=new Set;ended=new Set;pending=new Map;constructor(e,t,n){this.socket=e,this.worker=n,this.session=t,e.on(`message`,(e,t)=>{try{if(t||Buffer.byteLength(String(e))>131072)throw new Z(`worker-frame`);let n=JSON.parse(String(e));if(!n||typeof n!=`object`||typeof n.type!=`string`)throw new Z(`worker-frame`);if(n.type===`session_status`&&n.status?.sessionId!==this.session||n.type===`session_switched`)throw new Z(`worker-session-changed`);if(st.has(n.type))return;if(n.type===`permission_request`){let e=n.event;if(!e||typeof e.id!=`string`||e.id.length>256||typeof e.toolName!=`string`||this.pending.size>=32)throw new Z(`worker-prompt`);this.pending.set(e.id,{digest:ct(e),event:e})}n.type===`prompt_resolved`&&this.pending.delete(n.event?.id);for(let e of this.listeners)e(n)}catch{this.close()}}),e.on(`error`,()=>this.close()),e.on(`close`,()=>{for(let e of this.ended)e();this.listeners.clear(),this.ended.clear(),this.pending.clear()})}static async connect(t){let n=new URL(t.endpoint);if(n.protocol!==`ws:`||![`127.0.0.1`,`[::1]`].includes(n.hostname)||n.username||n.password||n.search||n.hash||n.pathname!==`/`||typeof t.token!=`string`||t.token.length<16||t.token.length>8192)throw new Z(`owner-worker-endpoint`);let r=AbortSignal.any([AbortSignal.timeout(5e3),...t.signal?[t.signal]:[]]);await t.control.admit(t.worker,r),n.searchParams.set(`token`,t.token);let i=new M(n,{maxPayload:at,handshakeTimeout:5e3,followRedirects:!1});try{let n=await new Promise((e,n)=>{let a=0,o=()=>n(new Z(`worker-unavailable`)),s=(n,r)=>{try{if(a+=Buffer.byteLength(String(n)),r||a>1024*1024)return o();let i=JSON.parse(String(n));if(i.type!==`session_status`)return;let s=i.status?.sessionId;if(typeof s!=`string`||s.length===0||s.length>256||t.session!==void 0&&s!==t.session)return o();e(s)}catch{o()}};i.once(`open`,()=>i.send(JSON.stringify({type:`get-status`}))),i.on(`message`,s),i.once(`error`,o),i.once(`close`,o),r.addEventListener(`abort`,o,{once:!0});let c=()=>{i.off(`message`,s),i.off(`error`,o),i.off(`close`,o),r.removeEventListener(`abort`,o)};i.once(`close`,c),i.on(`message`,function e(t){try{JSON.parse(String(t)).type===`session_status`&&(c(),i.off(`message`,e))}catch{}})});return r.throwIfAborted(),await t.control.admit(t.worker,r),r.throwIfAborted(),new e(i,n,Object.freeze(structuredClone(t.worker)))}catch{throw i.terminate(),new Z(`worker-unavailable`)}}onFrame(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onClose(e){return this.ended.add(e),()=>this.ended.delete(e)}ready(){if(this.socket.readyState!==M.OPEN)throw new Z(`worker-unavailable`)}send(e){this.ready();let t=JSON.stringify(e);if(Buffer.byteLength(t)>131072||this.socket.bufferedAmount>1024*1024)throw new Z(`frame-capacity`);if(e.type===`get-commands`)return{type:`commands`,commands:[],skills:[]};if(e.type===`list-sessions`&&typeof e.requestId==`string`)return{type:`sessions`,requestId:e.requestId,listing:{currentSessionId:this.session,sessions:[],unreadableSessionIds:[]}};if(e.type===`submit`){if(typeof e.prompt!=`string`||/^\s*\//u.test(e.prompt)||Object.keys(e).some(e=>![`type`,`prompt`].includes(e)))throw new Z(`remote-command`)}else if(!ot.has(String(e.type))&&e.type!==`abort`&&e.type!==`ask-response`)throw new Z(`remote-capability`);if(`sessionId`in e||`driverId`in e||`tenant`in e||`task`in e)throw new Z(`remote-ownership`);this.socket.send(t)}prompt(e,t){if(this.pending.get(e)?.digest!==t)throw new Z(`stale-approval`)}approve(e,t,n){this.ready(),this.prompt(e,t),this.pending.delete(e),this.socket.send(JSON.stringify({type:`permission-response`,id:e,result:n}))}close(){this.socket.terminate()}};const ut=new Set([`authorization`,`x-desktop-operator-authorization`,`host`,`origin`,`x-forwarded-for`,`x-forwarded-host`,`x-forwarded-proto`]),dt=e=>(e??``).replace(/^::ffff:/u,``).toLowerCase();var ft=class{options;wss=new xe({noServer:!0,maxPayload:at});paired=new Map;active=new Map;names;proxies;interval;closed=!1;upgrades=new Set;constructor(e){if(this.options=e,this.interval=e.policyIntervalMs??1e3,!Number.isSafeInteger(this.interval)||this.interval<100||this.interval>5e3||(e.trustedProxies??[]).some(e=>ve(e)===0))throw new Z(`gateway-configuration`);this.proxies=new Set((e.trustedProxies??[]).map(dt)),this.names=a({publicUrl:e.authorization.url.href,label:`Desktop runtime`,trustedProxies:e.trustedProxies});for(let[t,n]of e.ports){let r=e.authorization.binding(t);if(r.session!==n.session||JSON.stringify(r.worker)!==JSON.stringify(n.worker))throw new Z(`owner-worker-binding`);n.ready()}e.server.on(`request`,this.request),e.server.on(`upgrade`,this.upgrade)}boundary(e,t){let n=new Set;for(let r=0;r<e.rawHeaders.length;r+=2){let i=e.rawHeaders[r].toLowerCase();if(ut.has(i)&&n.has(i))return t.writeHead(403).end(),!1;n.add(i)}let r=[...n].some(e=>e.startsWith(`x-forwarded-`)),i=this.proxies.has(dt(e.socket.remoteAddress));return r&&!i||!e.socket.encrypted&&(!i||e.headers[`x-forwarded-proto`]!==`https`)||r&&(e.headers[`x-forwarded-proto`]!==`https`||e.headers[`x-forwarded-host`]!==this.names.url.host)?(t.writeHead(403).end(),!1):this.names.checkNames(e,t)}async bounded(e){let t=new AbortController,n;try{return await Promise.race([e(t.signal),new Promise((e,r)=>{n=setTimeout(()=>{t.abort(),r(new Z(`authority-timeout`))},5e3)})])}finally{n&&clearTimeout(n),t.abort()}}async body(e){let t=[],n=0;for await(let r of e){let e=Buffer.from(r);if(n+=e.length,n>8192)throw new Z(`request-capacity`);t.push(e)}let r=JSON.parse(Buffer.concat(t).toString(`utf8`));if(!r||typeof r!=`object`||Array.isArray(r))throw new Z(`request-shape`);return r}request=(e,t)=>{this.handle(e,t).catch(()=>{t.headersSent||t.writeHead(403),t.end()})};async handle(e,t){if(this.closed||!this.boundary(e,t))return;if(e.method!==`POST`||![`${this.names.url.pathname.replace(/\/$/u,``)}/pair`,`${this.names.url.pathname.replace(/\/$/u,``)}/approval`].includes(e.url??``)){t.writeHead(404).end();return}let n=setTimeout(()=>e.destroy(),5e3);try{let n=await this.body(e);if(e.url?.endsWith(`/pair`)){if(Object.keys(n).join(`,`)!==`binding`||typeof n.binding!=`string`)throw new Z(`request-shape`);let r=this.options.authorization.binding(n.binding),i=this.options.ports.get(r.id);if(!i)throw new Z(`worker-unavailable`);i.ready();let a=o(e.headers.authorization);if(!a)throw new Z(`missing-token`);let s=o(e.headers[`x-desktop-operator-authorization`]);if(e.headers[`x-desktop-operator-authorization`]!==void 0&&!s)throw new Z(`operator-token`);let{drive:c,operator:l}=await this.bounded(async e=>{let t=await this.options.authorization.verify(a,r,!1,e),n=s===void 0?void 0:await this.options.authorization.verify(s,r,!0,e);return e.throwIfAborted(),{drive:t,operator:n}});if(e.aborted||t.destroyed||this.closed)throw new Z(`connection-withdrawn`);let u=Q(r),d=this.options.store.pair(u,[c,...l?[l]:[]].map(e=>({id:e.jti,expiresAt:e.credentialExpiresAt})),Math.min(c.expiresAt,l?.expiresAt??c.expiresAt),l!==void 0);this.paired.set(r.id,{binding:r,access:d,jwt:a,operatorJwt:s,port:i});for(let[e,t]of this.active)t.binding.id===r.id&&e.terminate();t.setHeader(`cache-control`,`no-store`),t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({binding:r.id,generation:d.generation,token:d.token,approvalToken:d.approvalToken,expiresAt:d.expiresAt,session:r.session}))}else{if(Object.keys(n).sort().join(`,`)!==`allow,binding,digest,generation,id`||typeof n.binding!=`string`||!Number.isSafeInteger(n.generation)||typeof n.id!=`string`||typeof n.digest!=`string`||!/^[a-f0-9]{64}$/u.test(n.digest)||typeof n.allow!=`boolean`)throw new Z(`request-shape`);let r=this.paired.get(n.binding),i=o(e.headers.authorization);if(!r||r.access.generation!==n.generation||!i||!r.operatorJwt)throw new Z(`operator-token`);if(this.options.store.authorize(r.access.key,r.access.generation,i,!0),await this.bounded(e=>this.options.authorization.verify(r.operatorJwt,r.binding,!0,e)),e.aborted||t.destroyed||this.closed)throw new Z(`connection-withdrawn`);r.port.prompt(n.id,n.digest),this.options.store.approveOnce(r.access.key,r.access.generation,i,n.digest),r.port.approve(n.id,n.digest,n.allow),t.writeHead(204).end()}}finally{clearTimeout(n)}}upgrade=(e,t,n)=>{this.upgrades.add(t),t.once(`close`,()=>this.upgrades.delete(t)),t.once(`error`,()=>t.destroy());let r=new ye(e);if(r.assignSocket(t),!this.boundary(e,r)){r.on(`finish`,()=>t.destroy());return}r.detachSocket(t),this.connect(e,t,n).catch(()=>{t.end(`HTTP/1.1 403 Forbidden\r
1
+ import{C as e,S as t,T as n,_ as r,b as i,c as a,d as o,f as s,g as c,h as l,l as u,m as d,n as f,p,r as m,t as h,u as g,v as _,w as v,x as y,y as b}from"./product-host-CBylXlR9.js";import"node:module";import{createHash as x,createPublicKey as ee,randomBytes as S,randomUUID as C,verify as te}from"node:crypto";import{isAbsolute as w,join as T,posix as E}from"node:path";import"node:child_process";import{open as D,realpath as ne,rename as re,stat as ie,unlink as ae}from"node:fs/promises";import{closeSync as O,constants as k,existsSync as oe,fstatSync as se,fsyncSync as ce,lstatSync as le,mkdirSync as ue,openSync as de,readFileSync as fe,realpathSync as pe,renameSync as me,rmdirSync as he,unlinkSync as ge,writeFileSync as _e}from"node:fs";import{isIP as ve}from"node:net";import{ServerResponse as ye}from"node:http";import{performance as A}from"node:perf_hooks";import{Sandbox as j,SandboxNotFoundError as be}from"e2b/dist/index.mjs";import{WebSocket as M,WebSocketServer as xe}from"ws";var N=class extends Error{reason=`invalid-schema`;constructor(){super(`Invalid organization schema`)}};function Se(e){for(let t of e){let e=t.codePointAt(0);if(e>=55296&&e<=57343)throw new N}}function Ce(e){let t=new Set,n=0;function r(e,i){if(++n>4096||i>32)throw new N;if(e===null||typeof e==`boolean`)return JSON.stringify(e);if(typeof e==`string`)return Se(e),JSON.stringify(e);if(typeof e==`number`){if(!Number.isSafeInteger(e)||Object.is(e,-0))throw new N;return JSON.stringify(e)}if(typeof e!=`object`||t.has(e))throw new N;t.add(e);try{if(Array.isArray(e)){if(Reflect.ownKeys(e).length!==e.length+1)throw new N;return`[${Array.from({length:e.length},(t,n)=>{let a=Object.getOwnPropertyDescriptor(e,String(n));if(a===void 0||!(`value`in a))throw new N;return r(a.value,i+1)}).join(`,`)}]`}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new N;let t=Reflect.ownKeys(e);if(t.some(e=>typeof e!=`string`))throw new N;return`{${t.sort().map(t=>{Se(t);let n=Object.getOwnPropertyDescriptor(e,t);if(!n.enumerable||!(`value`in n))throw new N;return`${JSON.stringify(t)}:${r(n.value,i+1)}`}).join(`,`)}}`}finally{t.delete(e)}}let i=r(e,0);if(new TextEncoder().encode(i).byteLength>64*1024)throw new N;return i}function we(e,t){if(Ce(e),typeof e!=`object`||!e||Array.isArray(e))throw new N;let n=e;if(Object.keys(n).length!==t.length||t.some(e=>!Object.hasOwn(n,e)))throw new N;return n}function P(e,t=0){if(typeof e!=`number`||!Number.isSafeInteger(e)||Object.is(e,-0)||e<t)throw new N;return e}function Te(e){let t=we(e,[`tokens`,`timeMs`,`costMicros`]);return Object.freeze({tokens:P(t.tokens),timeMs:P(t.timeMs),costMicros:P(t.costMicros)})}var F=class extends Error{reason;constructor(e){super(`Organization operation refused: ${e}`),this.reason=e}};function I(e){try{return Ce(e)}catch(e){throw e instanceof N?new F(`invalid-schema`):e}}function Ee(e,t){if(![`workload`,`request`,`approval`].includes(e))throw new F(`invalid-schema`);return Buffer.from(I([`robota/organization-${e}/v1`,t]),`utf8`)}function L(e){return x(`sha256`).update(I([`robota/organization-operation/v1`,e.grantId,e.tenant,e.task,e.actor,e.audience,e.epoch,e.operation]),`utf8`).digest(`hex`)}function R(e,t){if(I(e),typeof e!=`object`||!e||Array.isArray(e))throw new F(`invalid-schema`);let n=e;if(Object.keys(n).length!==t.length||t.some(e=>!Object.hasOwn(n,e)))throw new F(`invalid-schema`);return n}function z(e){if(typeof e!=`string`||e.length<1||e.length>256||[...e].some(e=>{let t=e.codePointAt(0);return t<32||t===127||t>=55296&&t<=57343}))throw new F(`invalid-schema`);return e}function B(e,t=0){if(typeof e!=`number`||!Number.isSafeInteger(e)||Object.is(e,-0)||e<t)throw new F(`invalid-schema`);return e}function V(e){try{return Te(e)}catch(e){throw e instanceof N?new F(`invalid-schema`):e}}function De(e){let t=R(e,[`value`,`usage`]);return Object.freeze({value:H(JSON.parse(I(t.value))),usage:V(t.usage)})}function Oe(e){if(typeof e!=`string`||e.length>4096||!e.startsWith(`-----BEGIN PUBLIC KEY-----`))throw new F(`invalid-schema`);try{let t=ee(e);if(t.asymmetricKeyType!==`ed25519`)throw Error(`wrong type`);return t}catch{throw new F(`invalid-proof`)}}function H(e){if(typeof e==`object`&&e){for(let t of Object.values(e))H(t);Object.freeze(e)}return e}function ke(e){if(e.version!==1||B(e.expiresAt,1)<=B(e.notBefore))throw new F(`invalid-schema`);B(e.epoch,1)}function Ae(e){let t=R(e,[`version`,`grantId`,`tenant`,`task`,`actor`,`audience`,`epoch`,`nonce`,`notBefore`,`expiresAt`,`operation`]);ke(t);let n=R(t.operation,[`idempotencyKey`,`resource`,`operation`,`environment`,`parameters`]);return Object.freeze({version:1,grantId:z(t.grantId),tenant:z(t.tenant),task:z(t.task),actor:z(t.actor),audience:z(t.audience),epoch:B(t.epoch,1),nonce:z(t.nonce),notBefore:B(t.notBefore),expiresAt:B(t.expiresAt,1),operation:Object.freeze({idempotencyKey:z(n.idempotencyKey),resource:z(n.resource),operation:z(n.operation),environment:z(n.environment),parameters:H(JSON.parse(I(n.parameters)))})})}function je(e){let t=R(e,[`version`,`id`,`tenant`,`task`,`actor`,`audience`,`epoch`,`environment`,`operationDigest`,`notBefore`,`expiresAt`]);if(ke(t),typeof t.operationDigest!=`string`||!/^[a-f0-9]{64}$/.test(t.operationDigest))throw new F(`invalid-schema`);return Object.freeze({version:1,id:z(t.id),tenant:z(t.tenant),task:z(t.task),actor:z(t.actor),audience:z(t.audience),epoch:B(t.epoch,1),environment:z(t.environment),operationDigest:t.operationDigest,notBefore:B(t.notBefore),expiresAt:B(t.expiresAt,1)})}var Me=class extends Error{constructor(){super(`Organization audit append conflict`)}};const Ne=/^[0-9a-f]{64}$/,Pe=[`dispatch`,`complete`,`refused`,`unknown`];function U(e){return x(`sha256`).update(I(e),`utf8`).digest(`hex`)}function W(e){if(typeof e!=`string`||!Ne.test(e))throw new F(`invalid-schema`);return e}function Fe(e,t){let n=R(e,[`version`,`stream`,`sequence`,`hash`]);if(n.version!==1||n.stream!==t)throw new F(`invalid-schema`);return Object.freeze({version:1,stream:t,sequence:B(n.sequence),hash:W(n.hash)})}function G(e){let t=R(e,[`phase`,`operationDigest`,`tenantDigest`,`taskDigest`,`actorDigest`,`grantDigest`,`epoch`]);if(typeof t.phase!=`string`||!Pe.includes(t.phase))throw new F(`invalid-schema`);return Object.freeze({phase:t.phase,operationDigest:W(t.operationDigest),tenantDigest:W(t.tenantDigest),taskDigest:W(t.taskDigest),actorDigest:W(t.actorDigest),grantDigest:W(t.grantDigest),epoch:B(t.epoch,1)})}function K(e,t){if(!Pe.includes(t))throw new F(`invalid-schema`);let n=Ae(e),r=(e,t)=>U([`robota/organization-audit-identity/v1`,e,t]);return Object.freeze({phase:t,operationDigest:L(n),tenantDigest:r(`tenant`,[n.tenant]),taskDigest:r(`task`,[n.tenant,n.task]),actorDigest:r(`actor`,[n.tenant,n.actor]),grantDigest:r(`grant`,[n.grantId]),epoch:n.epoch})}function Ie(e){return z(e),Object.freeze({version:1,stream:e,sequence:0,hash:U([`robota/organization-audit-genesis/v1`,e])})}function Le(e,t,n,r){return U([`robota/organization-audit-entry/v1`,z(e),B(t,1),W(n),G(r)])}function Re(e){return Buffer.from(I([`robota/organization-audit-checkpoint/v1`,Fe(e,z(e.stream))]),`utf8`)}function q(e,t,n){let r=R(e,[`claims`,`signature`]),i=Fe(r.claims,t);if(typeof r.signature!=`string`||!/^[A-Za-z0-9_-]{86}$/.test(r.signature))throw new F(`invalid-proof`);let a=Buffer.from(r.signature,`base64url`);if(a.length!==64||a.toString(`base64url`)!==r.signature||!te(null,Re(i),n,a)||i.sequence===0&&i.hash!==Ie(t).hash)throw new F(`invalid-proof`);return Object.freeze({claims:i,signature:r.signature})}function ze(e,t){let n=R(e,[`stream`,`sequence`,`previous`,`event`,`hash`]),r=G(n.event);if(n.stream!==t.stream||n.sequence!==t.sequence+1||n.previous!==t.hash)throw new F(`invalid-proof`);let i=Le(t.stream,B(n.sequence,1),t.hash,r);if(n.hash!==i)throw new F(`invalid-proof`);return Object.freeze({stream:t.stream,sequence:n.sequence,previous:t.hash,event:r,hash:i})}function J(e,t){return e.stream===t.stream&&e.sequence===t.sequence&&e.hash===t.hash}function Be(e,t,n){let r=R(e,[`entries`,`head`]);if(!Array.isArray(r.entries)||r.entries.length>128)throw new F(`invalid-schema`);let i=q(r.head,t.stream,n),a=t;for(let e of r.entries){let t=ze(e,a);a={version:1,stream:t.stream,sequence:t.sequence,hash:t.hash}}if(!J(a,i.claims))throw new F(`invalid-proof`);return i}function Ve(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(o),t.removeEventListener(`abort`,a)},a=()=>{i(),r(new F(`policy-unavailable`))},o=setTimeout(()=>{i(),n()},e);t.addEventListener(`abort`,a,{once:!0}),t.aborted&&a()})}function Y(e){if(e.aborted)throw new F(`policy-unavailable`)}var He=class{stream;key;sink;anchor;timeout;constructor(e){if(this.stream=z(e.stream),this.key=Oe(e.publicKey),this.timeout=B(e.timeoutMs??1e3,1),this.timeout>3e4||typeof e.sink?.read!=`function`||typeof e.sink?.append!=`function`||typeof e.anchor?.load!=`function`||typeof e.anchor?.compareAndSet!=`function`)throw new F(`invalid-schema`);this.sink=Object.freeze({read:e.sink.read.bind(e.sink),append:e.sink.append.bind(e.sink)}),this.anchor=Object.freeze({load:e.anchor.load.bind(e.anchor),compareAndSet:e.anchor.compareAndSet.bind(e.anchor)})}async bounded(e,t){let n=new AbortController,r=()=>n.abort();t?.addEventListener(`abort`,r,{once:!0}),t?.aborted&&n.abort();let i,a=new Promise((e,t)=>{i=()=>t(new F(`policy-unavailable`)),n.signal.addEventListener(`abort`,i,{once:!0}),n.signal.aborted&&i()}),o=setTimeout(r,this.timeout);try{return await Promise.race([Promise.resolve().then(()=>(Y(n.signal),e(n.signal))),a])}catch{throw new F(`policy-unavailable`)}finally{clearTimeout(o),t?.removeEventListener(`abort`,r),n.signal.removeEventListener(`abort`,i),n.abort()}}async record(e,t){let n=G(e);await this.bounded(async e=>{let t=5;for(;;){Y(e);let r=q(await this.anchor.load(e),this.stream,this.key);Y(e);let i=Be(await this.sink.read(r.claims,e),r.claims,this.key);if(Y(e),!J(i.claims,r.claims)){await Ve(t,e),t=Math.min(t*2,50);continue}let a;try{a=R(await this.sink.append(r.claims,n,e),[`entry`,`head`])}catch(n){if(Y(e),!(n instanceof Me))throw n;await Ve(t,e),t=Math.min(t*2,50);continue}Y(e);let o=ze(a.entry,r.claims),s=q(a.head,this.stream,this.key);if(I(o.event)!==I(n)||!J(s.claims,{version:1,stream:o.stream,sequence:o.sequence,hash:o.hash}))throw new F(`invalid-proof`);let c=await this.anchor.compareAndSet(r.claims,s,e);if(Y(e),c!==!0)throw new F(`policy-unavailable`);return}},t)}async recover(e){return this.bounded(async e=>{let t=q(await this.anchor.load(e),this.stream,this.key);Y(e);let n=Be(await this.sink.read(t.claims,e),t.claims,this.key);if(Y(e),J(n.claims,t.claims))return n.claims;let r=await this.anchor.compareAndSet(t.claims,n,e);if(Y(e),r!==!0)throw new F(`policy-unavailable`);return n.claims},e)}async verify(e){return this.bounded(async e=>{let t=5;for(;;){let n=q(await this.anchor.load(e),this.stream,this.key);Y(e);let r=Be(await this.sink.read(n.claims,e),n.claims,this.key);if(Y(e),J(r.claims,n.claims))return n.claims;await Ve(t,e),t=Math.min(t*2,50)}},e)}};const Ue=[`budget-exhausted`,`not-authorized`,`invalid-schema`,`expired`,`revoked`,`operation-conflict`,`operation-pending`];function We(e){if(typeof e!=`string`||!Ue.includes(e))throw new F(`invalid-schema`);return e}var Ge=class extends F{usage;constructor(e,t){super(We(e)),this.usage=V(t)}};function Ke(e){let t=R(e,[`request`,`approval`]),n=R(t.request,[`claims`,`signature`]),r=t.approval===null?null:R(t.approval,[`claims`,`signature`]);if(typeof n.signature!=`string`||r!==null&&typeof r.signature!=`string`)throw new F(`invalid-proof`);return Object.freeze({request:Object.freeze({claims:Ae(n.claims),signature:n.signature}),approval:r===null?null:Object.freeze({claims:je(r.claims),signature:r.signature})})}var qe=class{audience;ledger;actions=new Map;interval;now;active=new Set;audit;auditReadiness;closed=!1;constructor(e){if(this.ledger=e.ledger,e.hosted===!0){if(this.ledger.verifyAnchoredAuthority(),!(e.audit instanceof He))throw new F(`policy-unavailable`);this.auditReadiness=e.audit.verify.bind(e.audit)}if(e.audit!==void 0){if(typeof e.audit?.record!=`function`)throw new F(`invalid-schema`);this.audit=Object.freeze({record:e.audit.record.bind(e.audit)})}if(this.audience=e.ledger.audience,this.interval=B(e.policyIntervalMs??100,1),this.interval>1e3)throw new F(`invalid-schema`);this.now=e.now??Date.now;for(let t of e.actions){let e=z(t.resource),n=z(t.operation),r=t.roles.map(z);if(r.length===0||new Set(r).size!==r.length||typeof t.requiresApproval!=`boolean`||typeof t.reserve!=`function`||typeof t.execute!=`function`)throw new F(`invalid-schema`);let i=I([e,n]);if(this.actions.has(i))throw new F(`invalid-schema`);this.actions.set(i,Object.freeze({resource:e,operation:n,roles:Object.freeze(r),requiresApproval:t.requiresApproval,reserve:t.reserve.bind(t),execute:t.execute.bind(t)}))}}async apply(e,t){if(this.closed)throw new F(`policy-unavailable`);if(t?.aborted||(await this.auditReadiness?.(t),this.closed||t?.aborted))throw new F(`not-authorized`);let n=Ke(e),{request:r,grant:i}=this.ledger.authenticate(n.request),a=this.actions.get(I([r.operation.resource,r.operation.operation]));if(a===void 0||!a.roles.includes(i.role))throw new F(`not-authorized`);let o=V(a.reserve(r.operation));if(B(o.timeMs,1),o.timeMs>2147483647)throw new F(`invalid-schema`);let s=this.ledger.reserve(n.request,o,n.approval,a.requiresApproval);if(s.kind===`complete`)return s.receipt;if(s.kind===`refused`)throw new F(s.reason);return this.execute(n.request,a,s,t)}async auditRecord(e,t,n){if(this.audit===void 0)return;let r,i=new Promise((e,t)=>{r=()=>t(new F(`outcome-unknown`)),n.addEventListener(`abort`,r,{once:!0}),n.aborted&&r()});try{if(await Promise.race([Promise.resolve().then(()=>{if(n.aborted)throw new F(`outcome-unknown`);return this.audit.record(K(e,t),n)}),i]),n.aborted)throw new F(`outcome-unknown`)}finally{n.removeEventListener(`abort`,r)}}async execute(e,t,n,r){let i=e.claims,a=new AbortController;this.active.add(a);let o=()=>a.abort();r?.addEventListener(`abort`,o,{once:!0}),(r?.aborted||this.closed)&&a.abort();let s=Math.min(n.reservation.timeMs,i.expiresAt-this.now(),n.grant.expiresAt-this.now()),c=setTimeout(o,Math.max(0,s)),l=setInterval(()=>{try{this.ledger.authenticate(e)}catch{a.abort()}},this.interval),u=A.now(),d;try{let r=new Promise((e,t)=>{d=()=>t(new F(`outcome-unknown`)),a.signal.addEventListener(`abort`,d,{once:!0}),a.signal.aborted&&d()}),o=Promise.resolve().then(async()=>{if(a.signal.aborted||(this.ledger.authenticate(e),await this.auditRecord(i,`dispatch`,a.signal),a.signal.aborted||A.now()-u>s))throw new F(`outcome-unknown`);return this.ledger.authenticate(e),t.execute(i.operation,{signal:a.signal,proof:e,operationDigest:n.digest,identity:n.grant,reservation:n.reservation})}),c=De(await Promise.race([o,r]));if(this.ledger.authenticate(e),a.signal.aborted||A.now()-u>s||(await this.auditRecord(i,`complete`,a.signal),this.ledger.authenticate(e),a.signal.aborted||A.now()-u>s))throw new F(`outcome-unknown`);let l=De({value:c.value,usage:{...c.usage,timeMs:Math.max(c.usage.timeMs,Math.ceil(A.now()-u))}});return this.ledger.settle(i,l),l}catch(e){if(e instanceof Ge&&!a.signal.aborted&&A.now()-u<=s){try{if(await this.auditRecord(i,`refused`,a.signal),a.signal.aborted||A.now()-u>s)throw new F(`outcome-unknown`);this.ledger.confirmNoEffect(i,We(e.reason),{...e.usage,timeMs:Math.max(e.usage.timeMs,Math.ceil(A.now()-u))})}catch{a.abort();try{this.ledger.markUnknown(i)}catch{}throw new F(`outcome-unknown`)}throw new F(e.reason)}a.abort();try{this.ledger.markUnknown(i)}catch{}try{await this.auditRecord(i,`unknown`,AbortSignal.timeout(1e3))}catch{}throw new F(`outcome-unknown`)}finally{clearTimeout(c),clearInterval(l),r?.removeEventListener(`abort`,o),d!==void 0&&a.signal.removeEventListener(`abort`,d),this.active.delete(a)}}close(){this.closed=!0;for(let e of this.active)e.abort()}},Je=class{ledger;audit;broker;inventory;incidents;timeout;timer;calls=new Map;sweepPending;closed=!1;quarantined=!1;constructor(e){this.ledger=e.ledger,this.audit=e.audit,this.broker=new qe({ledger:e.ledger,audit:e.audit,actions:e.actions,hosted:!0,policyIntervalMs:e.policyIntervalMs});let t=e.policyIntervalMs??100;if(this.timeout=e.providerTimeoutMs??1e4,!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>3e4||typeof e.inventory?.list!=`function`||typeof e.inventory.terminate!=`function`||typeof e.incidentOwners?.report!=`function`||[`detection`,`containment`,`assessment`,`recovery`].some(t=>{let n=e.incidentOwners[t];return typeof n!=`string`||n.trim().length===0}))throw new F(`invalid-schema`);this.inventory=Object.freeze({list:e.inventory.list.bind(e.inventory),terminate:e.inventory.terminate.bind(e.inventory)}),this.incidents=Object.freeze({...e.incidentOwners,report:e.incidentOwners.report.bind(e.incidentOwners)}),this.timer=setInterval(()=>{this.sweep().catch(()=>void 0)},t),this.timer.unref()}identity(e,t,n){let r=this.ledger.currentGrant(e);if(r.tenant!==t.tenant||r.task!==t.task||r.actor!==t.actor||r.epoch!==n)throw new F(`not-authorized`);return r}async admit(e,t){if(this.closed||this.quarantined)throw new F(`policy-unavailable`);this.ledger.verifyAnchoredAuthority();let n=this.identity(e.grantId,e.identity,e.epoch);if(await this.audit.verify(t),!(await this.inventory.list(t===void 0?AbortSignal.timeout(this.timeout):AbortSignal.any([t,AbortSignal.timeout(this.timeout)]))).some(t=>t.resource===e.resource&&t.grantId===e.grantId&&t.epoch===e.epoch&&Object.entries(e.identity).every(([e,n])=>t.identity[e]===n))||this.closed||this.quarantined||t?.aborted)throw new F(`not-authorized`);return this.identity(e.grantId,e.identity,e.epoch),n}async apply(e,t,n){if(this.closed||this.quarantined)throw new F(`policy-unavailable`);let r=new AbortController,i=()=>{n?.()};r.signal.addEventListener(`abort`,i,{once:!0});let a=()=>r.abort();t?.addEventListener(`abort`,a,{once:!0}),t?.aborted&&r.abort(),this.calls.set(r,e.request.claims.grantId);try{return await this.broker.apply(e,r.signal)}catch(t){throw t instanceof F&&t.reason===`outcome-unknown`&&await this.incidents.report({kind:`unknown-effect`,resources:[e.request.claims.operation.resource],operationDigest:L(e.request.claims)}).catch(()=>void 0),t}finally{this.calls.delete(r),t?.removeEventListener(`abort`,a),r.signal.removeEventListener(`abort`,i)}}async afterWithdrawal(){await this.sweepPending?.catch(()=>void 0),await this.sweep()}async stopGrant(e){this.ledger.revokeGrant(e),await this.afterWithdrawal()}async stopTask(e,t){this.ledger.stopTask(e,t),await this.afterWithdrawal()}async stopTenant(e){this.ledger.stopTenant(e),await this.afterWithdrawal()}async emergencyStop(){this.ledger.emergencyStop(),await this.afterWithdrawal()}async reconcileExternalOperation(e,t,n){this.ledger.verifyAnchoredAuthority();let r=K(e,`complete`),i=await t.confirm(r.operationDigest,n);return await this.audit.record(r,n),this.ledger.reconcileExternalOperation(e,i)}sweep(){return this.sweepPending===void 0&&(this.sweepPending=this.sweepOnce().finally(()=>{this.sweepPending=void 0})),this.sweepPending}async sweepOnce(){let e=!this.closed&&!this.quarantined,t=this.closed||this.quarantined;try{this.ledger.verifyAnchoredAuthority(),await this.audit.verify(AbortSignal.timeout(this.timeout))}catch{t=!0}t&&!this.closed&&(this.quarantined=!0,this.broker.close());for(let[e,n]of this.calls)try{if(t)throw new F(`policy-unavailable`);this.ledger.currentGrant(n)}catch{e.abort()}let n;try{n=await this.inventory.list(AbortSignal.timeout(this.timeout))}catch{this.quarantined=!0,this.broker.close();for(let e of this.calls.keys())e.abort();throw await this.incidents.report({kind:`cleanup-unresolved`,resources:[]}),new F(`policy-unavailable`)}let r=n.filter(e=>{try{return t?!0:(this.identity(e.grantId,e.identity,e.epoch),!1)}catch{return!0}}),i=await Promise.allSettled(r.map(e=>this.inventory.terminate(e,AbortSignal.timeout(this.timeout)))),a=r.filter((e,t)=>i[t].status===`rejected`).map(e=>e.resource);if(t&&e&&await this.incidents.report({kind:`authority-unavailable`,resources:r.map(e=>e.resource)}),a.length>0)throw await this.incidents.report({kind:`cleanup-unresolved`,resources:a}),new F(`policy-unavailable`)}async close(){this.closed=!0,clearInterval(this.timer),this.broker.close();for(let e of this.calls.keys())e.abort();await this.afterWithdrawal()}};function Ye(t){let n=e(t.controlPlane,`organization control plane`),r=e(t.tenant,`organization tenant`),i={apiKey:e(t.apiKey,`E2B management credential`),requestTimeoutMs:v(t.requestTimeoutMs??1e4,`E2B request timeout`,3e4),apiUrl:`https://api.e2b.app`,sandboxUrl:`https://sandbox.e2b.app`,domain:`e2b.app`,debug:!1,retries:0};function a(t){if(t.metadata.organizationControlPlane!==n||t.metadata.tenant!==r)throw Error(`Organization inventory ownership mismatch`);return Object.freeze({resource:e(t.sandboxId,`organization worker`),grantId:e(t.metadata.organizationGrant,`organization grant`),epoch:v(Number(t.metadata.epoch),`organization epoch`),identity:b({tenant:t.metadata.tenant,task:t.metadata.task,rootTask:t.metadata.rootTask,actor:t.metadata.actor,runtime:t.metadata.runtime})})}return{async list(e){let t=j.list({...i,query:{metadata:{organizationControlPlane:n,tenant:r},state:[`running`,`paused`]},limit:100}),o=[],s=new Set;for(;t.hasNext;){e.throwIfAborted();for(let n of await t.nextItems({...i,signal:e})){let e=a(n);if(s.has(e.resource)||o.length>=1e4)throw Error(`Organization inventory is incomplete`);s.add(e.resource),o.push(e)}}return o},async terminate(e,t){t.throwIfAborted();let n;try{n=await j.getInfo(e.resource,{...i,signal:t})}catch(e){if(e instanceof be)return;throw Error(`Organization cleanup is unresolved`)}let r=a(n);if(r.grantId!==e.grantId||r.epoch!==e.epoch||Object.entries(e.identity).some(([e,t])=>r.identity[e]!==t))throw Error(`Organization cleanup ownership mismatch`);await j.kill(e.resource,i)}}}function Xe(e){let t=[...e.bindings],n=new Set,i=new Set,a=new Set;for(let r of t){if(!/^[A-Za-z0-9_-]{32,256}$/u.test(r.token)||n.has(r.token)||i.has(r.config.identity.runtime)||a.has(r.grantId))throw new F(`invalid-schema`);let t=e.ledger.currentGrant(r.grantId);if(t.scopes.length!==1||t.scopes[0].resource!==e.modelResource||t.scopes[0].operations.length!==1||t.scopes[0].operations[0]!==`generate`)throw new F(`not-authorized`);n.add(r.token),i.add(r.config.identity.runtime),a.add(r.grantId)}let o=t=>{let n=e.ledger.budgetState(`grant`,t.grantId);return{sessions:1,modelCalls:e.ledger.grantOperationCount(t.grantId),modelTokens:n.spent.tokens,costMicros:n.spent.costMicros}};return(n,i)=>{let a=new AbortController,s=()=>{i.writableFinished||a.abort()};i.once(`close`,s);let c=setTimeout(()=>{a.abort(),n.destroy(),i.destroy()},3e4),l=(e,t)=>{i.destroyed||i.writableEnded||(i.writeHead(e,{"content-type":`application/json`,"cache-control":`no-store`}),i.end(JSON.stringify(t)))};(async()=>{try{let s=new Set;for(let e=0;e<n.rawHeaders.length;e+=2){let t=n.rawHeaders[e].toLowerCase();if([`host`,`authorization`,`idempotency-key`,`content-type`,`content-length`,`transfer-encoding`,`origin`].includes(t)){if(s.has(t))throw new F(`invalid-schema`);s.add(t)}}if(n.method!==`POST`||n.headers.origin!==void 0||n.headers[`content-type`]!==`application/json`||n.headers[`content-encoding`]!==void 0)throw new F(`not-authorized`);let c=[],u=0;for await(let e of n){let t=Buffer.from(e);if(u+=t.length,u>4*1024*1024)throw new F(`invalid-schema`);c.push(t)}let d=Buffer.concat(c),f=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(d));if(!f||Array.isArray(f))throw new F(`invalid-schema`);let p=[`/v1/chat/completions`,`/v1/responses`].includes(n.url??``),m=p?t.find(e=>n.headers.authorization===`Bearer ${e.token}`):t.find(e=>f.identity?.runtime===e.config.identity.runtime);if(!m||m.expiresAt<=Date.now())throw new F(`expired`);let h=m.config;if(n.headers.host!==new URL(h.broker.endpoint).host||new URL(h.worker.endpoint).origin!==new URL(h.broker.endpoint).origin)throw new F(`not-authorized`);let g=await e.control.admit({resource:h.worker.resource,grantId:m.grantId,identity:h.identity,epoch:h.epoch},a.signal);if(!p){let e=n.url===new URL(h.worker.endpoint).pathname?`worker`:n.url===new URL(h.broker.endpoint).pathname?`broker`:void 0;if(!e||typeof f.nonce!=`string`||f.version!==3||f.role!==e||f.resource!==h[e].resource||f.epoch!==h.epoch||Object.entries(h.identity).some(([e,t])=>f.identity?.[e]!==t)||JSON.stringify(f.snapshot)!==JSON.stringify(h.snapshot)||JSON.stringify(f.limits)!==JSON.stringify(h.limits))throw new F(`not-authorized`);let t=Date.now(),i={version:3,identity:h.identity,role:e,resource:h[e].resource,nonce:f.nonce,epoch:h.epoch,issuedAt:t,expiresAt:Math.min(t+6e4,m.expiresAt,g.expiresAt),snapshot:h.snapshot,ready:!0,limits:h.limits,usage:e===`broker`?o(m):null},a={...i,signature:m.signAdmission(e,r(i))};_(a,h,e,f.nonce,Date.now()),l(200,a);return}let v=n.headers[`idempotency-key`];if(typeof v!=`string`||!/^[A-Za-z0-9_-]{1,128}$/u.test(v))throw new F(`invalid-schema`);let y=await e.payloads.put(g.id,d),b=Date.now(),x={version:1,grantId:g.id,tenant:g.tenant,task:g.task,actor:g.actor,audience:g.audience,epoch:g.epoch,nonce:C(),notBefore:b,expiresAt:Math.min(b+25e3,m.expiresAt,g.expiresAt),operation:{idempotencyKey:v,resource:e.modelResource,operation:`generate`,environment:`hosted`,parameters:{request:y,surface:n.url===`/v1/responses`?`responses`:`chat-completions`}}},ee={claims:x,signature:m.signRequest(Ee(`request`,x))};await e.payloads.recordOperation(x);let S=(await e.control.apply({request:ee,approval:null},a.signal,()=>i.destroy())).value?.response;if(typeof S!=`string`)throw new F(`outcome-unknown`);let te=await e.payloads.get(g.id,S),w=JSON.parse(te.toString(`utf8`));if(f.stream===!0)if(i.writeHead(200,{"content-type":`text/event-stream`,"cache-control":`no-store`}),n.url===`/v1/responses`){let e=w.output;if(Array.isArray(e)){for(let t of e)if(t.type===`message`&&Array.isArray(t.content))for(let e of t.content)e.type===`output_text`&&typeof e.text==`string`&&i.write(`data: ${JSON.stringify({type:`response.output_text.delta`,delta:e.text})}\n\n`)}i.end(`data: ${JSON.stringify({type:`response.completed`,response:w})}\n\n`)}else{let e=w.choices;if(!Array.isArray(e))throw new F(`outcome-unknown`);i.write(`data: ${JSON.stringify({...w,object:`chat.completion.chunk`,choices:e.map(e=>({index:e.index,delta:{...e.message,...Array.isArray(e.message.tool_calls)?{tool_calls:e.message.tool_calls.map((e,t)=>({...e,index:t}))}:{}},finish_reason:null}))})}\n\n`),i.end(`data: ${JSON.stringify({...w,object:`chat.completion.chunk`,choices:e.map(e=>({index:e.index,delta:{},finish_reason:e.finish_reason}))})}\n\ndata: [DONE]\n\n`)}else l(200,w)}catch(e){i.headersSent?i.destroy():l(e instanceof F&&[`policy-unavailable`,`outcome-unknown`].includes(e.reason)?503:403,{error:{message:e instanceof F?e.message:`Organization ingress refused`,type:`organization_refusal`}}),n.resume()}finally{clearTimeout(c),i.removeListener(`close`,s)}})()}}var Ze=class e{directory;constructor(e){this.directory=e}static async open(t){if(!w(t))throw new F(`policy-unavailable`);let n=await ne(t),r=await ie(n);if(!r.isDirectory()||r.mode&63||process.getuid!==void 0&&r.uid!==process.getuid())throw new F(`policy-unavailable`);return new e(n)}path(e,t){if(!/^[a-f0-9]{64}$/u.test(t))throw new F(`invalid-schema`);let n=x(`sha256`).update(e).digest(`hex`);return T(this.directory,`${n}-${t}.json`)}async put(e,t){if(t.length>4*1024*1024)throw new F(`invalid-schema`);let n=x(`sha256`).update(t).digest(`hex`),r=this.path(e,n);return await this.persist(r,t),n}async persist(e,t){let n=T(this.directory,`${C()}.tmp`);try{let r=await D(n,`wx`,384);try{await r.writeFile(t),await r.sync()}finally{await r.close()}await re(n,e);let i=await D(this.directory,k.O_RDONLY);try{await i.sync()}finally{await i.close()}}catch{throw new F(`policy-unavailable`)}finally{await ae(n).catch(()=>void 0)}}async recordOperation(e){let t=L(e),n=await this.put(e.grantId,Buffer.from(JSON.stringify(e)));await this.persist(`${this.path(e.grantId,t)}.operation`,Buffer.from(JSON.stringify({requestDigest:n})))}async operation(e,t){let n=await D(`${this.path(e,t)}.operation`,k.O_RDONLY|k.O_NOFOLLOW|k.O_NONBLOCK);try{let r=await n.stat();if(!r.isFile()||r.size>4096||r.mode&63||process.getuid!==void 0&&r.uid!==process.getuid())throw new F(`policy-unavailable`);let i=JSON.parse(await n.readFile(`utf8`));if(typeof i.requestDigest!=`string`)throw new F(`policy-unavailable`);let a=JSON.parse((await this.get(e,i.requestDigest)).toString(`utf8`));if(K(a,`complete`),a.grantId!==e||L(a)!==t)throw new F(`policy-unavailable`);return a}finally{await n.close()}}async get(e,t){try{let n=await D(this.path(e,t),k.O_RDONLY|k.O_NOFOLLOW|k.O_NONBLOCK);try{let e=await n.stat();if(!e.isFile()||e.size>4*1024*1024||e.mode&63||process.getuid!==void 0&&e.uid!==process.getuid())throw Error(`unowned content`);let r=await n.readFile();if(x(`sha256`).update(r).digest(`hex`)!==t)throw Error(`changed content`);return r}finally{await n.close()}}catch{throw new F(`policy-unavailable`)}}};function Qe(e){let t=new URL(e.endpoint);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(t.hostname))||t.username||t.password||t.search||t.hash||typeof e.apiKey!=`string`||/[\r\n]/u.test(e.apiKey)||e.apiKey.length===0||!Number.isSafeInteger(e.maxInputBytes)||e.maxInputBytes<1||e.maxInputBytes>4*1024*1024||!Number.isSafeInteger(e.maxOutputTokens)||e.maxOutputTokens<1||!Number.isSafeInteger(e.costMicrosPerToken)||e.costMicrosPerToken<0||typeof e.countInputTokens!=`function`)throw new F(`invalid-schema`);let n=Object.freeze({...e.reservation}),r=e.countInputTokens.bind(e),i=e=>{let t=e;if(!t||Object.keys(t).sort().join(`,`)!==`request,surface`||typeof t.request!=`string`||!/^[a-f0-9]{64}$/u.test(t.request)||![`responses`,`chat-completions`].includes(String(t.surface)))throw new F(`invalid-schema`);return t};return{resource:e.resource,operation:`generate`,roles:[...e.roles],requiresApproval:!1,reserve:e=>(i(e.parameters),n),execute:async(a,o)=>{let s=i(a.parameters),c=await e.payloads.get(o.identity.id,s.request);if(c.length>e.maxInputBytes)throw new F(`invalid-schema`);let l=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(c));if(!l||Array.isArray(l)||l.model!==e.model)throw new F(`not-authorized`);let u={...l,stream:!1};if([`conversation`,`previous_response_id`,`prompt`].some(e=>u[e]!=null)||Array.isArray(u.tools)&&u.tools.some(e=>e?.type!==`function`))throw new Ge(`not-authorized`,{tokens:0,timeMs:0,costMicros:0});delete u.max_tokens,delete u.max_completion_tokens,delete u.max_output_tokens,delete u.stream_options,u[s.surface===`responses`?`max_output_tokens`:`max_completion_tokens`]=e.maxOutputTokens,u.store=!1,u.n=s.surface===`chat-completions`?1:void 0,s.surface===`responses`&&(delete u.n,u.background=!1);let d=JSON.stringify(u),f=await r(s.surface,JSON.parse(d),o.signal),p=f+e.maxOutputTokens;if(!Number.isSafeInteger(f)||f<0||!Number.isSafeInteger(p)||p>n.tokens||!Number.isSafeInteger(p*e.costMicrosPerToken)||p*e.costMicrosPerToken>n.costMicros)throw new Ge(`budget-exhausted`,{tokens:0,timeMs:0,costMicros:0});o.signal.throwIfAborted();let m=await fetch(`${t.href.replace(/\/$/u,``)}/${s.surface===`responses`?`responses`:`chat/completions`}`,{method:`POST`,redirect:`error`,signal:o.signal,headers:{authorization:`Bearer ${e.apiKey}`,"content-type":`application/json`,...e.providerIdempotency?{"Idempotency-Key":o.operationDigest}:{}},body:d});if(!m.ok||m.body===null)throw await m.body?.cancel(),new F(`outcome-unknown`);let h=[],g=0,_=m.body.getReader();try{for(;;){let e=await _.read();if(e.done)break;if(g+=e.value.length,g>4*1024*1024)throw new F(`outcome-unknown`);h.push(e.value)}}finally{await _.cancel()}let v=Buffer.concat(h),y=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(v))?.usage?.total_tokens;if(typeof y!=`number`||!Number.isSafeInteger(y)||y<0||y>n.tokens||!Number.isSafeInteger(y*e.costMicrosPerToken)||y*e.costMicrosPerToken>n.costMicros)throw new F(`outcome-unknown`);return{value:{response:await e.payloads.put(o.identity.id,v)},usage:{tokens:y,timeMs:0,costMicros:y*e.costMicrosPerToken}}}}}function $e(e){let t=new URL(e.endpoint);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(t.hostname))||t.username||t.password||t.search||t.hash||typeof e.encode!=`function`||typeof e.apiKey!=`string`||e.apiKey.length===0||/[\r\n]/u.test(e.apiKey))throw new F(`invalid-schema`);let n=e.apiKey,r=e.encode.bind(e);return async(e,i,a)=>{let o=await fetch(t,{method:`POST`,redirect:`error`,signal:a,headers:{authorization:`Bearer ${n}`,"content-type":`application/json`},body:JSON.stringify(r(e,i))});if(!o.ok||o.body===null)throw await o.body?.cancel(),new F(`policy-unavailable`);let s=[],c=0,l=o.body.getReader();try{for(;;){let e=await l.read();if(e.done)break;if(c+=e.value.length,c>64*1024)throw new F(`policy-unavailable`);s.push(e.value)}}finally{await l.cancel()}let u=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(Buffer.concat(s)));if(!Number.isSafeInteger(u?.input_tokens)||u.input_tokens<0)throw new F(`policy-unavailable`);return u.input_tokens}}function et(r,i,a){if(r.byteLength>48*1024*1024||x(`sha256`).update(r).digest(`hex`)!==i.digest)throw t(`filesystem checkpoint digest or size is invalid`);let o;try{o=n(JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(r)),`checkpoint`)}catch{throw t(`filesystem checkpoint is not valid UTF-8 JSON`)}if(y(o,[`version`,`id`,`identity`,`epoch`,`worker`,`files`,...o.version===2?[`session`]:[]],`checkpoint`),o.version!==1&&o.version!==2||o.id!==i.id)throw t(`filesystem checkpoint version or identity does not match`);let s=b(o.identity),c=v(o.epoch,`checkpoint epoch`),l=e(o.worker,`checkpoint worker`);if([`tenant`,`task`,`rootTask`].some(e=>s[e]!==a.identity[e])||s.runtime===a.identity.runtime||c>=a.epoch)throw t(`filesystem checkpoint requires the same task and a fresh identity/epoch`);if(!Array.isArray(o.files)||o.files.length>1e3)throw t(`filesystem checkpoint file inventory is invalid`);let u=new Set,f=0,p=o.files.map(r=>{let i=n(r,`checkpoint file`);y(i,[`path`,`base64`],`checkpoint file`);let a=e(i.path,`checkpoint file path`),o=a.split(`/`)[0];if(E.isAbsolute(a)||E.normalize(a)!==a||a===`.`||a===`..`||a.startsWith(`../`)||a.endsWith(`/`)||a.includes(`\\`)||o===`.home`||o===`.tmp`||u.has(a))throw t(`filesystem checkpoint path escapes or replaces private state`);if(typeof i.base64!=`string`||i.base64.length>44*1024*1024)throw t(`filesystem checkpoint file encoding is invalid`);let s=Buffer.from(i.base64,`base64`);if(f+=s.byteLength,s.toString(`base64`)!==i.base64||f>32*1024*1024)throw t(`filesystem checkpoint encoding or byte budget is invalid`);return u.add(a),Object.freeze({path:a,bytes:new Uint8Array(s)})});for(let e of u){let n=E.dirname(e);for(;n!==`.`;){if(u.has(n))throw t(`filesystem checkpoint file conflicts with a directory`);n=E.dirname(n)}}return Object.freeze({sourceWorker:l,sourceRuntime:s.runtime,sourceEpoch:c,files:p,...o.version===2?{session:d(o.session,`/`)}:{}})}var X=class extends Error{outcome;operationId;resource;constructor(e,t,n){super(`E2B worker provisioning ${e}; owner reconciliation is required`),this.outcome=e,this.operationId=t,this.resource=n,this.name=`E2BWorkerProvisioningError`}};async function tt(n){let r=b(n.identity),a=v(n.epoch,`worker epoch`),o=e(n.templateId,`E2B clean template`),s=i(n.snapshot);if(s===null!=(n.checkpoint===void 0)||s?.id===o)throw t(`worker recovery requires checkpoint bytes and a separate clean template`);let c=s===null?void 0:et(n.checkpoint,s,{identity:r,epoch:a}),l;try{l=new URL(n.brokerEndpoint)}catch{throw t(`worker broker endpoint is invalid`)}if(l.protocol!==`https:`&&!(l.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(l.hostname))||l.username||l.password||l.search||l.hash)throw t(`worker broker endpoint requires owner-selected TLS or literal loopback`);let u={apiKey:e(n.apiKey,`E2B management credential`),requestTimeoutMs:v(n.requestTimeoutMs,`E2B request timeout`,3e4),apiUrl:`https://api.e2b.app`,sandboxUrl:`https://sandbox.e2b.app`,domain:`e2b.app`,debug:!1,retries:0},d=v(n.lifetimeMs,`E2B lifetime`,864e5),f=C(),m={...r,epoch:String(a),operationId:f,...n.organization===void 0?{}:{organizationControlPlane:e(n.organization.controlPlane,`organization control plane`),organizationGrant:e(n.organization.grantId,`organization grant`)},...s===null?{}:{restoreMode:`filesystem-v1`,checkpointId:s.id,checkpointDigest:s.digest,sourceWorker:c.sourceWorker,sourceRuntime:c.sourceRuntime,sourceEpoch:String(c.sourceEpoch)}};n.signal.throwIfAborted();let h;try{h=await j.create(o,{...u,timeoutMs:d,metadata:m,envs:{},allowInternetAccess:!1,network:{allowPublicTraffic:!1,allowOut:[l.hostname]},lifecycle:{onTimeout:`kill`,autoResume:!1}})}catch{throw new X(`allocation-unknown`,f)}let g;try{g=e(h.sandboxId,`allocated worker`)}catch{throw new X(`allocation-unknown`,f)}let _,y=()=>(_===void 0&&(_=j.kill(g,u).then(()=>void 0).catch(()=>{throw new X(`cleanup-unresolved`,f,g)})),_);try{let e=await j.getInfo(g,u).catch(()=>{throw new X(`allocation-unknown`,f,g)});if(e.sandboxId!==g||Object.entries(m).some(([t,n])=>e.metadata[t]!==n))throw new X(`allocation-unknown`,f,g);if(g===c?.sourceWorker)throw t(`provider returned the checkpoint source instead of a fresh worker`);if(e.templateId!==o||e.state!==`running`||e.lifecycle?.onTimeout!==`kill`||e.lifecycle.autoResume!==!1||e.allowInternetAccess!==!1||e.network?.allowPublicTraffic!==!1||JSON.stringify(e.network.allowOut??[])!==JSON.stringify([l.hostname])||(e.volumeMounts?.length??0)!==0||e.network.egressProxy!==void 0||Object.keys(e.network.rules??{}).length!==0)throw t(`allocated worker ownership, clean template or network posture is invalid`);n.signal.throwIfAborted();let r=await h.commands.run(`umask 077; mktemp -d "\${TMPDIR:-/tmp}/agent-task-${f}-XXXXXXXXXX"`,{cwd:`/`,envs:{},timeoutMs:n.requestTimeoutMs,requestTimeoutMs:n.requestTimeoutMs});if(r.exitCode!==0||typeof r.stdout!=`string`)throw t(`fresh worker workspace creation failed`);let i=r.stdout.trim();if(!/^\/[A-Za-z0-9._/-]+$/u.test(i)||E.normalize(i)!==i||!RegExp(`^agent-task-${f}-[A-Za-z0-9]{10}$`,`u`).test(E.basename(i)))throw t(`fresh worker workspace receipt is invalid`);for(let e of c?.files??[]){n.signal.throwIfAborted();let r=E.join(i,e.path);await h.files.write(r,e.bytes.slice().buffer,{requestTimeoutMs:n.requestTimeoutMs});let a=await h.files.read(r,{format:`bytes`,requestTimeoutMs:n.requestTimeoutMs});if(!Buffer.from(a).equals(Buffer.from(e.bytes)))throw t(`restored filesystem checkpoint bytes do not match`)}let a;if(c?.session!==void 0){n.signal.throwIfAborted();let e={...c.session,cwd:i},r=p(e),o=E.join(i,`.home`,`.checkpoint-sessions`,`${e.id}.json`);await h.files.write(o,Uint8Array.from(r).buffer,{requestTimeoutMs:n.requestTimeoutMs});let s=await h.files.read(o,{format:`bytes`,requestTimeoutMs:n.requestTimeoutMs});if(!Buffer.from(s).equals(r))throw t(`restored conversation checkpoint bytes do not match`);a=Object.freeze({id:e.id,path:o,digest:x(`sha256`).update(r).digest(`hex`)})}return n.signal.throwIfAborted(),Object.freeze({resource:g,workspaceRoot:i,operationId:f,snapshot:s,release:y,...a===void 0?{}:{resumeSession:a}})}catch(e){throw e instanceof X&&e.outcome===`allocation-unknown`||(await y(),n.signal.aborted&&n.signal.throwIfAborted(),e instanceof Error&&e.message.startsWith(`Hosted runtime admission refused:`))?e:t(`fresh worker provisioning or filesystem restoration failed`)}}var Z=class extends Error{reason;constructor(e){super(`Remote desktop refused: ${e}`),this.reason=e}};function Q(e){return JSON.stringify([e.id,e.user,e.client,e.session,e.worker.resource,e.worker.grantId,e.worker.epoch,e.worker.identity.tenant,e.worker.identity.task,e.worker.identity.rootTask,e.worker.identity.actor,e.worker.identity.runtime])}var nt=class{options;url;now;bindings;constructor(e){if(this.options=e,this.url=u(e.publicUrl,`Desktop runtime`),u(e.issuer,`Desktop issuer`),this.now=e.now??Date.now,this.bindings=e.bindings.map(e=>{let t=structuredClone(e);return Object.freeze(t.worker.identity),Object.freeze(t.worker),Object.freeze(t)}),e.bindings.length===0||e.bindings.length>100||e.bindings.some(e=>[e.id,e.user,e.client,e.session].some(e=>typeof e!=`string`||e.length===0||e.length>256||/[\r\n]/u.test(e)))||new Set(e.bindings.map(e=>e.id)).size!==e.bindings.length)throw new Z(`owner-bindings`)}binding(e){let t=this.bindings.find(t=>t.id===e);if(!t)throw new Z(`owner-binding`);return t}async verify(e,t,n=!1,r){if(r?.throwIfAborted(),!this.bindings.some(e=>Q(e)===Q(t)))throw new Z(`owner-binding`);let i=await g({issuer:this.options.issuer,resource:n?`${this.url.href.replace(/\/$/u,``)}/approval`:this.url.href,algorithms:[`EdDSA`,`ES256`,`RS256`],allowedSubjects:[t.user],requiredScopes:n?[`desktop:approve`]:[`desktop:pair`,`desktop:drive`]},this.options.verifierDeps).verify(e);if(!i.admitted)throw new Z(i.refusal);let a=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`)),o=this.now();if(typeof a.iat!=`number`||!Number.isSafeInteger(a.iat)||typeof a.exp!=`number`||!Number.isSafeInteger(a.exp)||a.iat*1e3>o||a.exp*1e3<=o||a.exp-a.iat>120||a.nbf!==void 0&&(typeof a.nbf!=`number`||!Number.isSafeInteger(a.nbf)||a.nbf*1e3>o)||typeof a.jti!=`string`||!/^[A-Za-z0-9_-]{8,256}$/u.test(a.jti))throw new Z(`short-lived-credential`);if(a.sub!==t.user||a.client_id!==t.client||a.tenant!==t.worker.identity.tenant||a.task!==t.worker.identity.task||a.session!==t.session||a.workload!==t.worker.identity.runtime||a.epoch!==t.worker.epoch)throw new Z(`session-ownership`);r?.throwIfAborted();let s=await this.options.control.admit(t.worker,r);return r?.throwIfAborted(),{binding:t,jti:a.jti,credentialExpiresAt:a.exp*1e3,expiresAt:Math.min(a.exp*1e3,s.expiresAt,o+6e4)}}async current(e,t){if(!this.bindings.some(t=>Q(t)===Q(e)))throw new Z(`owner-binding`);await this.options.control.admit(e.worker,t)}};const $=e=>x(`sha256`).update(e).digest(`hex`),rt=(e,t)=>e?.version===t.version&&e.ledger===t.ledger&&e.revision===t.revision&&e.digest===t.digest;var it=class{now;directory;file;lock;constructor(e,t=Date.now){if(this.now=t,this.anchor=e.anchor,!w(e.directory))throw new Z(`store-unavailable`);this.directory=pe(e.directory);let n=le(this.directory);if(!n.isDirectory()||n.mode&63||process.getuid!==void 0&&n.uid!==process.getuid())throw new Z(`store-unavailable`);if(this.file=T(this.directory,`desktop-authority.json`),this.lock=T(this.directory,`desktop-authority.lock`),e.create===!0){if(oe(this.file)||this.anchor.read()!==void 0)throw new Z(`store-unavailable`);this.locked(()=>this.write(void 0,{version:1,revision:1,spent:{},connections:{}}))}this.read()}anchor;head(e){return{version:1,ledger:this.anchor.ledger,revision:e.revision,digest:$(JSON.stringify(e))}}read(){let e=de(this.file,k.O_RDONLY|k.O_NOFOLLOW|k.O_NONBLOCK);try{let t=se(e);if(!t.isFile()||t.size>2*1024*1024||t.mode&63||process.getuid!==void 0&&t.uid!==process.getuid())throw new Z(`store-unavailable`);let n=JSON.parse(fe(e,`utf8`)),r=this.anchor.read();if(n.version!==1||!Number.isSafeInteger(n.revision)||n.revision<1||!n.spent||!n.connections||!rt(r,this.head(n)))throw new Z(`store-unavailable`);return n}finally{O(e)}}locked(e){ue(this.lock,{mode:448});try{return e()}finally{he(this.lock)}}write(e,t){let n=T(this.directory,`desktop-${C()}.tmp`);try{let r=de(n,`wx`,384);try{_e(r,JSON.stringify(t)),ce(r)}finally{O(r)}let i=this.head(t);if(this.anchor.compareAndSet(e===void 0?void 0:this.head(e),i),!rt(this.anchor.read(),i))throw new Z(`store-unavailable`);me(n,this.file);let a=de(this.directory,k.O_RDONLY);try{ce(a)}finally{O(a)}}finally{oe(n)&&ge(n)}}change(e){return this.locked(()=>{let t=this.read(),n=structuredClone(t),r=e(n);return n.revision++,this.write(t,n),r})}pair(e,t,n,r){let i=S(32).toString(`base64url`),a=r?S(32).toString(`base64url`):null;return this.change(r=>{for(let[e,t]of Object.entries(r.spent))t<=this.now()&&delete r.spent[e];if(n<=this.now()||t.length===0||new Set(t.map(e=>e.id)).size!==t.length||t.some(e=>!Number.isSafeInteger(e.expiresAt)||e.expiresAt<n)||Object.keys(r.spent).length+t.length>4096||t.some(e=>r.spent[$(e.id)]!==void 0))throw new Z(`replayed-pairing`);let o=$(e);if(r.connections[o]===void 0&&Object.keys(r.connections).length>=100)throw new Z(`connection-capacity`);let s=(r.connections[o]?.generation??0)+1;r.connections[o]={generation:s,access:$(i),approval:a===null?null:$(a),expiresAt:n,connected:!1};for(let e of t)r.spent[$(e.id)]=e.expiresAt;return{key:e,generation:s,token:i,approvalToken:a,expiresAt:n}})}authorize(e,t,n,r=!1){let i=this.read().connections[$(e)];if(!i||i.generation!==t||i.expiresAt<=this.now()||(r?i.approval:i.access)!==$(n))throw new Z(`withdrawn-connection`)}connect(e,t,n){this.authorize(e,t,n),this.change(n=>{let r=n.connections[$(e)];if(r.generation!==t||r.expiresAt<=this.now()||r.connected)throw new Z(`replayed-connection`);r.connected=!0})}approveOnce(e,t,n,r){this.authorize(e,t,n,!0),this.change(i=>{let a=i.connections[$(e)];if(a.generation!==t||a.expiresAt<=this.now()||a.approval!==$(n))throw new Z(`withdrawn-connection`);let o=$(`approval:${e}:${r}`);if(i.spent[o]!==void 0)throw new Z(`replayed-approval`);if(Object.keys(i.spent).length>=4096)throw new Z(`approval-capacity`);i.spent[o]=2**53-1})}revoke(e){this.change(t=>{let n=t.connections[$(e)];n&&(n.generation++,n.expiresAt=0)})}};const at=128*1024,ot=new Set([`get-messages`,`get-status`,`get-context`,`get-history`,`get-prompts`,`get-pending`,`get-executing`,`get-execution-workspace`,`get-execution-detail`,`project-status`,`project-diff`,`project-memory`,`get-usage-report`,`get-background-tasks`,`list-models`,`get-agent-definitions`]),st=new Set([`sessions`,`session_list`,`session_renamed_in_list`,`session_deleted`,`ui_intent`,`settings`,`commands`]);function ct(e){return x(`sha256`).update(`robota/desktop-permission/v1\0`).update(JSON.stringify(e)).digest(`hex`)}var lt=class e{socket;worker;session;listeners=new Set;ended=new Set;pending=new Map;constructor(e,t,n){this.socket=e,this.worker=n,this.session=t,e.on(`message`,(e,t)=>{try{if(t||Buffer.byteLength(String(e))>131072)throw new Z(`worker-frame`);let n=JSON.parse(String(e));if(!n||typeof n!=`object`||typeof n.type!=`string`)throw new Z(`worker-frame`);if(n.type===`session_status`&&n.status?.sessionId!==this.session||n.type===`session_switched`)throw new Z(`worker-session-changed`);if(st.has(n.type))return;if(n.type===`permission_request`){let e=n.event;if(!e||typeof e.id!=`string`||e.id.length>256||typeof e.toolName!=`string`||this.pending.size>=32)throw new Z(`worker-prompt`);this.pending.set(e.id,{digest:ct(e),event:e})}n.type===`prompt_resolved`&&this.pending.delete(n.event?.id);for(let e of this.listeners)e(n)}catch{this.close()}}),e.on(`error`,()=>this.close()),e.on(`close`,()=>{for(let e of this.ended)e();this.listeners.clear(),this.ended.clear(),this.pending.clear()})}static async connect(t){let n=new URL(t.endpoint);if(n.protocol!==`ws:`||![`127.0.0.1`,`[::1]`].includes(n.hostname)||n.username||n.password||n.search||n.hash||n.pathname!==`/`||typeof t.token!=`string`||t.token.length<16||t.token.length>8192)throw new Z(`owner-worker-endpoint`);let r=AbortSignal.any([AbortSignal.timeout(5e3),...t.signal?[t.signal]:[]]);await t.control.admit(t.worker,r),n.searchParams.set(`token`,t.token);let i=new M(n,{maxPayload:at,handshakeTimeout:5e3,followRedirects:!1});try{let n=await new Promise((e,n)=>{let a=0,o=()=>n(new Z(`worker-unavailable`)),s=(n,r)=>{try{if(a+=Buffer.byteLength(String(n)),r||a>1024*1024)return o();let i=JSON.parse(String(n));if(i.type!==`session_status`)return;let s=i.status?.sessionId;if(typeof s!=`string`||s.length===0||s.length>256||t.session!==void 0&&s!==t.session)return o();e(s)}catch{o()}};i.once(`open`,()=>i.send(JSON.stringify({type:`get-status`}))),i.on(`message`,s),i.once(`error`,o),i.once(`close`,o),r.addEventListener(`abort`,o,{once:!0});let c=()=>{i.off(`message`,s),i.off(`error`,o),i.off(`close`,o),r.removeEventListener(`abort`,o)};i.once(`close`,c),i.on(`message`,function e(t){try{JSON.parse(String(t)).type===`session_status`&&(c(),i.off(`message`,e))}catch{}})});return r.throwIfAborted(),await t.control.admit(t.worker,r),r.throwIfAborted(),new e(i,n,Object.freeze(structuredClone(t.worker)))}catch{throw i.terminate(),new Z(`worker-unavailable`)}}onFrame(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onClose(e){return this.ended.add(e),()=>this.ended.delete(e)}ready(){if(this.socket.readyState!==M.OPEN)throw new Z(`worker-unavailable`)}send(e){this.ready();let t=JSON.stringify(e);if(Buffer.byteLength(t)>131072||this.socket.bufferedAmount>1024*1024)throw new Z(`frame-capacity`);if(e.type===`get-commands`)return{type:`commands`,commands:[],skills:[]};if(e.type===`list-sessions`&&typeof e.requestId==`string`)return{type:`sessions`,requestId:e.requestId,listing:{currentSessionId:this.session,sessions:[],unreadableSessionIds:[]}};if(e.type===`submit`){if(typeof e.prompt!=`string`||/^\s*\//u.test(e.prompt)||Object.keys(e).some(e=>![`type`,`prompt`].includes(e)))throw new Z(`remote-command`)}else if(!ot.has(String(e.type))&&e.type!==`abort`&&e.type!==`ask-response`)throw new Z(`remote-capability`);if(`sessionId`in e||`driverId`in e||`tenant`in e||`task`in e)throw new Z(`remote-ownership`);this.socket.send(t)}prompt(e,t){if(this.pending.get(e)?.digest!==t)throw new Z(`stale-approval`)}approve(e,t,n){this.ready(),this.prompt(e,t),this.pending.delete(e),this.socket.send(JSON.stringify({type:`permission-response`,id:e,result:n}))}close(){this.socket.terminate()}};const ut=new Set([`authorization`,`x-desktop-operator-authorization`,`host`,`origin`,`x-forwarded-for`,`x-forwarded-host`,`x-forwarded-proto`]),dt=e=>(e??``).replace(/^::ffff:/u,``).toLowerCase();var ft=class{options;wss=new xe({noServer:!0,maxPayload:at});paired=new Map;active=new Map;names;proxies;interval;closed=!1;upgrades=new Set;constructor(e){if(this.options=e,this.interval=e.policyIntervalMs??1e3,!Number.isSafeInteger(this.interval)||this.interval<100||this.interval>5e3||(e.trustedProxies??[]).some(e=>ve(e)===0))throw new Z(`gateway-configuration`);this.proxies=new Set((e.trustedProxies??[]).map(dt)),this.names=a({publicUrl:e.authorization.url.href,label:`Desktop runtime`,trustedProxies:e.trustedProxies});for(let[t,n]of e.ports){let r=e.authorization.binding(t);if(r.session!==n.session||JSON.stringify(r.worker)!==JSON.stringify(n.worker))throw new Z(`owner-worker-binding`);n.ready()}e.server.on(`request`,this.request),e.server.on(`upgrade`,this.upgrade)}boundary(e,t){let n=new Set;for(let r=0;r<e.rawHeaders.length;r+=2){let i=e.rawHeaders[r].toLowerCase();if(ut.has(i)&&n.has(i))return t.writeHead(403).end(),!1;n.add(i)}let r=[...n].some(e=>e.startsWith(`x-forwarded-`)),i=this.proxies.has(dt(e.socket.remoteAddress));return r&&!i||!e.socket.encrypted&&(!i||e.headers[`x-forwarded-proto`]!==`https`)||r&&(e.headers[`x-forwarded-proto`]!==`https`||e.headers[`x-forwarded-host`]!==this.names.url.host)?(t.writeHead(403).end(),!1):this.names.checkNames(e,t)}async bounded(e){let t=new AbortController,n;try{return await Promise.race([e(t.signal),new Promise((e,r)=>{n=setTimeout(()=>{t.abort(),r(new Z(`authority-timeout`))},5e3)})])}finally{n&&clearTimeout(n),t.abort()}}async body(e){let t=[],n=0;for await(let r of e){let e=Buffer.from(r);if(n+=e.length,n>8192)throw new Z(`request-capacity`);t.push(e)}let r=JSON.parse(Buffer.concat(t).toString(`utf8`));if(!r||typeof r!=`object`||Array.isArray(r))throw new Z(`request-shape`);return r}request=(e,t)=>{this.handle(e,t).catch(()=>{t.headersSent||t.writeHead(403),t.end()})};async handle(e,t){if(this.closed||!this.boundary(e,t))return;if(e.method!==`POST`||![`${this.names.url.pathname.replace(/\/$/u,``)}/pair`,`${this.names.url.pathname.replace(/\/$/u,``)}/approval`].includes(e.url??``)){t.writeHead(404).end();return}let n=setTimeout(()=>e.destroy(),5e3);try{let n=await this.body(e);if(e.url?.endsWith(`/pair`)){if(Object.keys(n).join(`,`)!==`binding`||typeof n.binding!=`string`)throw new Z(`request-shape`);let r=this.options.authorization.binding(n.binding),i=this.options.ports.get(r.id);if(!i)throw new Z(`worker-unavailable`);i.ready();let a=o(e.headers.authorization);if(!a)throw new Z(`missing-token`);let s=o(e.headers[`x-desktop-operator-authorization`]);if(e.headers[`x-desktop-operator-authorization`]!==void 0&&!s)throw new Z(`operator-token`);let{drive:c,operator:l}=await this.bounded(async e=>{let t=await this.options.authorization.verify(a,r,!1,e),n=s===void 0?void 0:await this.options.authorization.verify(s,r,!0,e);return e.throwIfAborted(),{drive:t,operator:n}});if(e.aborted||t.destroyed||this.closed)throw new Z(`connection-withdrawn`);let u=Q(r),d=this.options.store.pair(u,[c,...l?[l]:[]].map(e=>({id:e.jti,expiresAt:e.credentialExpiresAt})),Math.min(c.expiresAt,l?.expiresAt??c.expiresAt),l!==void 0);this.paired.set(r.id,{binding:r,access:d,jwt:a,operatorJwt:s,port:i});for(let[e,t]of this.active)t.binding.id===r.id&&e.terminate();t.setHeader(`cache-control`,`no-store`),t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({binding:r.id,generation:d.generation,token:d.token,approvalToken:d.approvalToken,expiresAt:d.expiresAt,session:r.session}))}else{if(Object.keys(n).sort().join(`,`)!==`allow,binding,digest,generation,id`||typeof n.binding!=`string`||!Number.isSafeInteger(n.generation)||typeof n.id!=`string`||typeof n.digest!=`string`||!/^[a-f0-9]{64}$/u.test(n.digest)||typeof n.allow!=`boolean`)throw new Z(`request-shape`);let r=this.paired.get(n.binding),i=o(e.headers.authorization);if(!r||r.access.generation!==n.generation||!i||!r.operatorJwt)throw new Z(`operator-token`);if(this.options.store.authorize(r.access.key,r.access.generation,i,!0),await this.bounded(e=>this.options.authorization.verify(r.operatorJwt,r.binding,!0,e)),e.aborted||t.destroyed||this.closed)throw new Z(`connection-withdrawn`);r.port.prompt(n.id,n.digest),this.options.store.approveOnce(r.access.key,r.access.generation,i,n.digest),r.port.approve(n.id,n.digest,n.allow),t.writeHead(204).end()}}finally{clearTimeout(n)}}upgrade=(e,t,n)=>{this.upgrades.add(t),t.once(`close`,()=>this.upgrades.delete(t)),t.once(`error`,()=>t.destroy());let r=new ye(e);if(r.assignSocket(t),!this.boundary(e,r)){r.on(`finish`,()=>t.destroy());return}r.detachSocket(t),this.connect(e,t,n).catch(()=>{t.end(`HTTP/1.1 403 Forbidden\r
2
2
  Connection: close\r
3
3
  Content-Length: 0\r
4
4
  \r
@@ -1,2 +1,2 @@
1
- import{a as e,i as t,o as n,s as r}from"./product-host-zZ2TTtQk.js";import{z as i}from"zod";var a=class{port;constructor(e){this.port=e.skillPort}async resolvePrompt(e){let t;try{t=this.port.loadCommands()}catch(e){return{ok:!1,error:n(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Failed to load skills: ${e instanceof Error?e.message:String(e)}`,!0)}}let i=t.find(t=>t.name===e.skillName);return i?i.context===`fork`?{ok:!1,error:r(`DAG_VALIDATION_SKILL_FORK_UNSUPPORTED`,`Skill "${e.skillName}" uses fork context, which the resolver node does not support (no subagent runtime). Use an inject-context skill.`,{skillName:e.skillName})}:this.resolveInject(i,e):{ok:!1,error:r(`DAG_VALIDATION_SKILL_NOT_FOUND`,`Skill "${e.skillName}" was not found in the injected contribution sources`,{skillName:e.skillName},{action:`set_config`,suggestion:`Set skillName to an available skill`,options:t.map(e=>e.name)})}}async resolveInject(e,t){try{let r=await this.port.resolveSkill(e,t.args,t.sessionId===void 0?void 0:{sessionId:t.sessionId});return typeof r.prompt==`string`?{ok:!0,value:{prompt:r.prompt,mode:r.mode}}:{ok:!1,error:n(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Skill "${t.skillName}" did not resolve to an inject prompt`,!1,{skillName:t.skillName,mode:r.mode})}}catch(e){let r=e instanceof Error?e.message:String(e);return{ok:!1,error:n(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Failed to resolve skill "${t.skillName}": ${r}`,!1,{skillName:t.skillName})}}}};const o=i.object({skillName:i.string().min(1),args:i.string().default(``),sessionId:i.string().optional(),baseCredits:i.number().nonnegative().default(0)}),s=[{key:`args`,label:`Args`,order:0,type:`string`,required:!1}],c=[{key:`prompt`,label:`Prompt`,order:0,type:`string`,required:!0},{key:`mode`,label:`Mode`,order:1,type:`string`,required:!0}];var l=class extends t{nodeType=`skill`;displayName=`Skill`;category=`Integration`;inputs=s;outputs=c;configSchemaDefinition=o;defaultInputPort=`args`;defaultOutputPort=`prompt`;runtime;constructor(e){super(),this.runtime=new a(e)}async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:n.baseCredits}}}async executeWithConfig(t,n,i){let a=new e(t,n.nodeDefinition.nodeId),o=a.getInput(`args`),s=typeof o==`string`&&o.trim().length>0?o:i.args,c=await this.runtime.resolvePrompt({skillName:i.skillName,args:s,...i.sessionId===void 0?{}:{sessionId:i.sessionId}});return c.ok?c.value.prompt.trim().length===0?{ok:!1,error:r(`DAG_VALIDATION_SKILL_EMPTY_PROMPT`,`Skill "${i.skillName}" resolved to an empty prompt`,{skillName:i.skillName})}:(a.setOutput(`prompt`,c.value.prompt),a.setOutput(`mode`,c.value.mode),a.setOutput(`_agentSummary`,`Skill "${i.skillName}" resolved (${c.value.mode}): ${c.value.prompt.length} chars.`),{ok:!0,value:a.toOutput()}):c}};export{l as SkillNodeDefinition};
2
- //# sourceMappingURL=node-CVEUtnXS.js.map
1
+ import{a as e,i as t,o as n,s as r}from"./product-host-CBylXlR9.js";import{z as i}from"zod";var a=class{port;constructor(e){this.port=e.skillPort}async resolvePrompt(e){let t;try{t=this.port.loadCommands()}catch(e){return{ok:!1,error:n(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Failed to load skills: ${e instanceof Error?e.message:String(e)}`,!0)}}let i=t.find(t=>t.name===e.skillName);return i?i.context===`fork`?{ok:!1,error:r(`DAG_VALIDATION_SKILL_FORK_UNSUPPORTED`,`Skill "${e.skillName}" uses fork context, which the resolver node does not support (no subagent runtime). Use an inject-context skill.`,{skillName:e.skillName})}:this.resolveInject(i,e):{ok:!1,error:r(`DAG_VALIDATION_SKILL_NOT_FOUND`,`Skill "${e.skillName}" was not found in the injected contribution sources`,{skillName:e.skillName},{action:`set_config`,suggestion:`Set skillName to an available skill`,options:t.map(e=>e.name)})}}async resolveInject(e,t){try{let r=await this.port.resolveSkill(e,t.args,t.sessionId===void 0?void 0:{sessionId:t.sessionId});return typeof r.prompt==`string`?{ok:!0,value:{prompt:r.prompt,mode:r.mode}}:{ok:!1,error:n(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Skill "${t.skillName}" did not resolve to an inject prompt`,!1,{skillName:t.skillName,mode:r.mode})}}catch(e){let r=e instanceof Error?e.message:String(e);return{ok:!1,error:n(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Failed to resolve skill "${t.skillName}": ${r}`,!1,{skillName:t.skillName})}}}};const o=i.object({skillName:i.string().min(1),args:i.string().default(``),sessionId:i.string().optional(),baseCredits:i.number().nonnegative().default(0)}),s=[{key:`args`,label:`Args`,order:0,type:`string`,required:!1}],c=[{key:`prompt`,label:`Prompt`,order:0,type:`string`,required:!0},{key:`mode`,label:`Mode`,order:1,type:`string`,required:!0}];var l=class extends t{nodeType=`skill`;displayName=`Skill`;category=`Integration`;inputs=s;outputs=c;configSchemaDefinition=o;defaultInputPort=`args`;defaultOutputPort=`prompt`;runtime;constructor(e){super(),this.runtime=new a(e)}async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:n.baseCredits}}}async executeWithConfig(t,n,i){let a=new e(t,n.nodeDefinition.nodeId),o=a.getInput(`args`),s=typeof o==`string`&&o.trim().length>0?o:i.args,c=await this.runtime.resolvePrompt({skillName:i.skillName,args:s,...i.sessionId===void 0?{}:{sessionId:i.sessionId}});return c.ok?c.value.prompt.trim().length===0?{ok:!1,error:r(`DAG_VALIDATION_SKILL_EMPTY_PROMPT`,`Skill "${i.skillName}" resolved to an empty prompt`,{skillName:i.skillName})}:(a.setOutput(`prompt`,c.value.prompt),a.setOutput(`mode`,c.value.mode),a.setOutput(`_agentSummary`,`Skill "${i.skillName}" resolved (${c.value.mode}): ${c.value.prompt.length} chars.`),{ok:!0,value:a.toOutput()}):c}};export{l as SkillNodeDefinition};
2
+ //# sourceMappingURL=node-BX6uQ1k-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-CVEUtnXS.js","names":[],"sources":["../../../dag-nodes/skill/dist/node/index.js"],"sourcesContent":["import { AbstractNodeDefinition, NodeIoAccessor } from \"@robota-sdk/dag-node\";\nimport { buildTaskExecutionError, buildValidationError } from \"@robota-sdk/dag-core\";\nimport { z } from \"zod\";\n//#region src/runtime-core.ts\n/**\n* Resolves a configured skill (by name) to its inject-mode prompt string through the injected\n* {@link ISkillExecutionPort}. No LLM, no provider, no shell: the port resolves with empty callbacks so shell\n* interpolations are stripped rather than executed, and fork skills are rejected here before resolution.\n*/\nvar SkillResolverRuntime = class {\n\tport;\n\tconstructor(options) {\n\t\tthis.port = options.skillPort;\n\t}\n\tasync resolvePrompt(request) {\n\t\tlet commands;\n\t\ttry {\n\t\t\tcommands = this.port.loadCommands();\n\t\t} catch (err) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: buildTaskExecutionError(\"DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED\", `Failed to load skills: ${err instanceof Error ? err.message : String(err)}`, true)\n\t\t\t};\n\t\t}\n\t\tconst skill = commands.find((command) => command.name === request.skillName);\n\t\tif (!skill) return {\n\t\t\tok: false,\n\t\t\terror: buildValidationError(\"DAG_VALIDATION_SKILL_NOT_FOUND\", `Skill \"${request.skillName}\" was not found in the injected contribution sources`, { skillName: request.skillName }, {\n\t\t\t\taction: \"set_config\",\n\t\t\t\tsuggestion: \"Set skillName to an available skill\",\n\t\t\t\toptions: commands.map((command) => command.name)\n\t\t\t})\n\t\t};\n\t\tif (skill.context === \"fork\") return {\n\t\t\tok: false,\n\t\t\terror: buildValidationError(\"DAG_VALIDATION_SKILL_FORK_UNSUPPORTED\", `Skill \"${request.skillName}\" uses fork context, which the resolver node does not support (no subagent runtime). Use an inject-context skill.`, { skillName: request.skillName })\n\t\t};\n\t\treturn this.resolveInject(skill, request);\n\t}\n\tasync resolveInject(skill, request) {\n\t\ttry {\n\t\t\tconst result = await this.port.resolveSkill(skill, request.args, request.sessionId !== void 0 ? { sessionId: request.sessionId } : void 0);\n\t\t\tif (typeof result.prompt !== \"string\") return {\n\t\t\t\tok: false,\n\t\t\t\terror: buildTaskExecutionError(\"DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED\", `Skill \"${request.skillName}\" did not resolve to an inject prompt`, false, {\n\t\t\t\t\tskillName: request.skillName,\n\t\t\t\t\tmode: result.mode\n\t\t\t\t})\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tvalue: {\n\t\t\t\t\tprompt: result.prompt,\n\t\t\t\t\tmode: result.mode\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: buildTaskExecutionError(\"DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED\", `Failed to resolve skill \"${request.skillName}\": ${message}`, false, { skillName: request.skillName })\n\t\t\t};\n\t\t}\n\t}\n};\n//#endregion\n//#region src/index.ts\nconst SkillNodeConfigSchema = z.object({\n\t/** Name of the skill to resolve (as discovered by SkillCommandSource). */\n\tskillName: z.string().min(1),\n\t/** Static skill arguments; the `args` input port overrides this when non-empty. */\n\targs: z.string().default(\"\"),\n\t/** Session id substituted for `${CLAUDE_SESSION_ID}` in the skill body. */\n\tsessionId: z.string().optional(),\n\t/** Base credit cost (resolution runs no model — default 0). */\n\tbaseCredits: z.number().nonnegative().default(0)\n});\nconst SKILL_INPUTS = [{\n\tkey: \"args\",\n\tlabel: \"Args\",\n\torder: 0,\n\ttype: \"string\",\n\trequired: false\n}];\nconst SKILL_OUTPUTS = [{\n\tkey: \"prompt\",\n\tlabel: \"Prompt\",\n\torder: 0,\n\ttype: \"string\",\n\trequired: true\n}, {\n\tkey: \"mode\",\n\tlabel: \"Mode\",\n\torder: 1,\n\ttype: \"string\",\n\trequired: true\n}];\n/**\n* DAG node that resolves a configured skill to its inject-mode prompt string.\n*\n* Emits the expanded `<skill>` prompt for a downstream LLM node to execute;\n* it does not run the skill itself.\n*\n* @extends AbstractNodeDefinition\n*/\nvar SkillNodeDefinition = class extends AbstractNodeDefinition {\n\tnodeType = \"skill\";\n\tdisplayName = \"Skill\";\n\tcategory = \"Integration\";\n\tinputs = SKILL_INPUTS;\n\toutputs = SKILL_OUTPUTS;\n\tconfigSchemaDefinition = SkillNodeConfigSchema;\n\tdefaultInputPort = \"args\";\n\tdefaultOutputPort = \"prompt\";\n\truntime;\n\tconstructor(options) {\n\t\tsuper();\n\t\tthis.runtime = new SkillResolverRuntime(options);\n\t}\n\tasync estimateCostWithConfig(_input, _context, config) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: { estimatedCredits: config.baseCredits }\n\t\t};\n\t}\n\tasync executeWithConfig(input, context, config) {\n\t\tconst io = new NodeIoAccessor(input, context.nodeDefinition.nodeId);\n\t\tconst argsInput = io.getInput(\"args\");\n\t\tconst args = typeof argsInput === \"string\" && argsInput.trim().length > 0 ? argsInput : config.args;\n\t\tconst resolved = await this.runtime.resolvePrompt({\n\t\t\tskillName: config.skillName,\n\t\t\targs,\n\t\t\t...config.sessionId !== void 0 ? { sessionId: config.sessionId } : {}\n\t\t});\n\t\tif (!resolved.ok) return resolved;\n\t\tif (resolved.value.prompt.trim().length === 0) return {\n\t\t\tok: false,\n\t\t\terror: buildValidationError(\"DAG_VALIDATION_SKILL_EMPTY_PROMPT\", `Skill \"${config.skillName}\" resolved to an empty prompt`, { skillName: config.skillName })\n\t\t};\n\t\tio.setOutput(\"prompt\", resolved.value.prompt);\n\t\tio.setOutput(\"mode\", resolved.value.mode);\n\t\tio.setOutput(\"_agentSummary\", `Skill \"${config.skillName}\" resolved (${resolved.value.mode}): ${resolved.value.prompt.length} chars.`);\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: io.toOutput()\n\t\t};\n\t}\n};\n//#endregion\nexport { SkillNodeConfigSchema, SkillNodeDefinition, SkillResolverRuntime };\n\n//# sourceMappingURL=index.js.map"],"mappings":"4FASA,IAAI,EAAuB,KAAM,CAChC,KACA,YAAY,EAAS,CACpB,KAAK,KAAO,EAAQ,SACrB,CACA,MAAM,cAAc,EAAS,CAC5B,IAAI,EACJ,GAAI,CACH,EAAW,KAAK,KAAK,aAAa,CACnC,OAAS,EAAK,CACb,MAAO,CACN,GAAI,GACJ,MAAO,EAAwB,0CAA2C,0BAA0B,aAAe,MAAQ,EAAI,QAAU,OAAO,CAAG,IAAK,EAAI,CAC7J,CACD,CACA,IAAM,EAAQ,EAAS,KAAM,GAAY,EAAQ,OAAS,EAAQ,SAAS,EAa3E,OAZK,EAQD,EAAM,UAAY,OAAe,CACpC,GAAI,GACJ,MAAO,EAAqB,wCAAyC,UAAU,EAAQ,UAAU,mHAAoH,CAAE,UAAW,EAAQ,SAAU,CAAC,CACtP,EACO,KAAK,cAAc,EAAO,CAAO,EAZrB,CAClB,GAAI,GACJ,MAAO,EAAqB,iCAAkC,UAAU,EAAQ,UAAU,sDAAuD,CAAE,UAAW,EAAQ,SAAU,EAAG,CAClL,OAAQ,aACR,WAAY,sCACZ,QAAS,EAAS,IAAK,GAAY,EAAQ,IAAI,CAChD,CAAC,CACF,CAMD,CACA,MAAM,cAAc,EAAO,EAAS,CACnC,GAAI,CACH,IAAM,EAAS,MAAM,KAAK,KAAK,aAAa,EAAO,EAAQ,KAAM,EAAQ,YAAc,IAAK,GAAuC,IAAK,GAAxC,CAAE,UAAW,EAAQ,SAAU,CAAU,EAQzI,OAPI,OAAO,EAAO,QAAW,SAOtB,CACN,GAAI,GACJ,MAAO,CACN,OAAQ,EAAO,OACf,KAAM,EAAO,IACd,CACD,EAb8C,CAC7C,GAAI,GACJ,MAAO,EAAwB,0CAA2C,UAAU,EAAQ,UAAU,uCAAwC,GAAO,CACpJ,UAAW,EAAQ,UACnB,KAAM,EAAO,IACd,CAAC,CACF,CAQD,OAAS,EAAK,CACb,IAAM,EAAU,aAAe,MAAQ,EAAI,QAAU,OAAO,CAAG,EAC/D,MAAO,CACN,GAAI,GACJ,MAAO,EAAwB,0CAA2C,4BAA4B,EAAQ,UAAU,KAAK,IAAW,GAAO,CAAE,UAAW,EAAQ,SAAU,CAAC,CAChL,CACD,CACD,CACD,EAGA,MAAM,EAAwB,EAAE,OAAO,CAEtC,UAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAE3B,KAAM,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,EAE3B,UAAW,EAAE,OAAO,CAAC,CAAC,SAAS,EAE/B,YAAa,EAAE,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,CAAC,CAChD,CAAC,EACK,EAAe,CAAC,CACrB,IAAK,OACL,MAAO,OACP,MAAO,EACP,KAAM,SACN,SAAU,EACX,CAAC,EACK,EAAgB,CAAC,CACtB,IAAK,SACL,MAAO,SACP,MAAO,EACP,KAAM,SACN,SAAU,EACX,EAAG,CACF,IAAK,OACL,MAAO,OACP,MAAO,EACP,KAAM,SACN,SAAU,EACX,CAAC,EASD,IAAI,EAAsB,cAAc,CAAuB,CAC9D,SAAW,QACX,YAAc,QACd,SAAW,cACX,OAAS,EACT,QAAU,EACV,uBAAyB,EACzB,iBAAmB,OACnB,kBAAoB,SACpB,QACA,YAAY,EAAS,CACpB,MAAM,EACN,KAAK,QAAU,IAAI,EAAqB,CAAO,CAChD,CACA,MAAM,uBAAuB,EAAQ,EAAU,EAAQ,CACtD,MAAO,CACN,GAAI,GACJ,MAAO,CAAE,iBAAkB,EAAO,WAAY,CAC/C,CACD,CACA,MAAM,kBAAkB,EAAO,EAAS,EAAQ,CAC/C,IAAM,EAAK,IAAI,EAAe,EAAO,EAAQ,eAAe,MAAM,EAC5D,EAAY,EAAG,SAAS,MAAM,EAC9B,EAAO,OAAO,GAAc,UAAY,EAAU,KAAK,CAAC,CAAC,OAAS,EAAI,EAAY,EAAO,KACzF,EAAW,MAAM,KAAK,QAAQ,cAAc,CACjD,UAAW,EAAO,UAClB,OACA,GAAG,EAAO,YAAc,IAAK,GAAsC,CAAC,EAAnC,CAAE,UAAW,EAAO,SAAU,CAChE,CAAC,EASD,OARK,EAAS,GACV,EAAS,MAAM,OAAO,KAAK,CAAC,CAAC,SAAW,EAAU,CACrD,GAAI,GACJ,MAAO,EAAqB,oCAAqC,UAAU,EAAO,UAAU,+BAAgC,CAAE,UAAW,EAAO,SAAU,CAAC,CAC5J,GACA,EAAG,UAAU,SAAU,EAAS,MAAM,MAAM,EAC5C,EAAG,UAAU,OAAQ,EAAS,MAAM,IAAI,EACxC,EAAG,UAAU,gBAAiB,UAAU,EAAO,UAAU,cAAc,EAAS,MAAM,KAAK,KAAK,EAAS,MAAM,OAAO,OAAO,QAAQ,EAC9H,CACN,GAAI,GACJ,MAAO,EAAG,SAAS,CACpB,GAXyB,CAY1B,CACD"}
1
+ {"version":3,"file":"node-BX6uQ1k-.js","names":[],"sources":["../../../dag-nodes/skill/dist/node/index.js"],"sourcesContent":["import { AbstractNodeDefinition, NodeIoAccessor } from \"@robota-sdk/dag-node\";\nimport { buildTaskExecutionError, buildValidationError } from \"@robota-sdk/dag-core\";\nimport { z } from \"zod\";\n//#region src/runtime-core.ts\n/**\n* Resolves a configured skill (by name) to its inject-mode prompt string through the injected\n* {@link ISkillExecutionPort}. No LLM, no provider, no shell: the port resolves with empty callbacks so shell\n* interpolations are stripped rather than executed, and fork skills are rejected here before resolution.\n*/\nvar SkillResolverRuntime = class {\n\tport;\n\tconstructor(options) {\n\t\tthis.port = options.skillPort;\n\t}\n\tasync resolvePrompt(request) {\n\t\tlet commands;\n\t\ttry {\n\t\t\tcommands = this.port.loadCommands();\n\t\t} catch (err) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: buildTaskExecutionError(\"DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED\", `Failed to load skills: ${err instanceof Error ? err.message : String(err)}`, true)\n\t\t\t};\n\t\t}\n\t\tconst skill = commands.find((command) => command.name === request.skillName);\n\t\tif (!skill) return {\n\t\t\tok: false,\n\t\t\terror: buildValidationError(\"DAG_VALIDATION_SKILL_NOT_FOUND\", `Skill \"${request.skillName}\" was not found in the injected contribution sources`, { skillName: request.skillName }, {\n\t\t\t\taction: \"set_config\",\n\t\t\t\tsuggestion: \"Set skillName to an available skill\",\n\t\t\t\toptions: commands.map((command) => command.name)\n\t\t\t})\n\t\t};\n\t\tif (skill.context === \"fork\") return {\n\t\t\tok: false,\n\t\t\terror: buildValidationError(\"DAG_VALIDATION_SKILL_FORK_UNSUPPORTED\", `Skill \"${request.skillName}\" uses fork context, which the resolver node does not support (no subagent runtime). Use an inject-context skill.`, { skillName: request.skillName })\n\t\t};\n\t\treturn this.resolveInject(skill, request);\n\t}\n\tasync resolveInject(skill, request) {\n\t\ttry {\n\t\t\tconst result = await this.port.resolveSkill(skill, request.args, request.sessionId !== void 0 ? { sessionId: request.sessionId } : void 0);\n\t\t\tif (typeof result.prompt !== \"string\") return {\n\t\t\t\tok: false,\n\t\t\t\terror: buildTaskExecutionError(\"DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED\", `Skill \"${request.skillName}\" did not resolve to an inject prompt`, false, {\n\t\t\t\t\tskillName: request.skillName,\n\t\t\t\t\tmode: result.mode\n\t\t\t\t})\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tvalue: {\n\t\t\t\t\tprompt: result.prompt,\n\t\t\t\t\tmode: result.mode\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: buildTaskExecutionError(\"DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED\", `Failed to resolve skill \"${request.skillName}\": ${message}`, false, { skillName: request.skillName })\n\t\t\t};\n\t\t}\n\t}\n};\n//#endregion\n//#region src/index.ts\nconst SkillNodeConfigSchema = z.object({\n\t/** Name of the skill to resolve (as discovered by SkillCommandSource). */\n\tskillName: z.string().min(1),\n\t/** Static skill arguments; the `args` input port overrides this when non-empty. */\n\targs: z.string().default(\"\"),\n\t/** Session id substituted for `${CLAUDE_SESSION_ID}` in the skill body. */\n\tsessionId: z.string().optional(),\n\t/** Base credit cost (resolution runs no model — default 0). */\n\tbaseCredits: z.number().nonnegative().default(0)\n});\nconst SKILL_INPUTS = [{\n\tkey: \"args\",\n\tlabel: \"Args\",\n\torder: 0,\n\ttype: \"string\",\n\trequired: false\n}];\nconst SKILL_OUTPUTS = [{\n\tkey: \"prompt\",\n\tlabel: \"Prompt\",\n\torder: 0,\n\ttype: \"string\",\n\trequired: true\n}, {\n\tkey: \"mode\",\n\tlabel: \"Mode\",\n\torder: 1,\n\ttype: \"string\",\n\trequired: true\n}];\n/**\n* DAG node that resolves a configured skill to its inject-mode prompt string.\n*\n* Emits the expanded `<skill>` prompt for a downstream LLM node to execute;\n* it does not run the skill itself.\n*\n* @extends AbstractNodeDefinition\n*/\nvar SkillNodeDefinition = class extends AbstractNodeDefinition {\n\tnodeType = \"skill\";\n\tdisplayName = \"Skill\";\n\tcategory = \"Integration\";\n\tinputs = SKILL_INPUTS;\n\toutputs = SKILL_OUTPUTS;\n\tconfigSchemaDefinition = SkillNodeConfigSchema;\n\tdefaultInputPort = \"args\";\n\tdefaultOutputPort = \"prompt\";\n\truntime;\n\tconstructor(options) {\n\t\tsuper();\n\t\tthis.runtime = new SkillResolverRuntime(options);\n\t}\n\tasync estimateCostWithConfig(_input, _context, config) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: { estimatedCredits: config.baseCredits }\n\t\t};\n\t}\n\tasync executeWithConfig(input, context, config) {\n\t\tconst io = new NodeIoAccessor(input, context.nodeDefinition.nodeId);\n\t\tconst argsInput = io.getInput(\"args\");\n\t\tconst args = typeof argsInput === \"string\" && argsInput.trim().length > 0 ? argsInput : config.args;\n\t\tconst resolved = await this.runtime.resolvePrompt({\n\t\t\tskillName: config.skillName,\n\t\t\targs,\n\t\t\t...config.sessionId !== void 0 ? { sessionId: config.sessionId } : {}\n\t\t});\n\t\tif (!resolved.ok) return resolved;\n\t\tif (resolved.value.prompt.trim().length === 0) return {\n\t\t\tok: false,\n\t\t\terror: buildValidationError(\"DAG_VALIDATION_SKILL_EMPTY_PROMPT\", `Skill \"${config.skillName}\" resolved to an empty prompt`, { skillName: config.skillName })\n\t\t};\n\t\tio.setOutput(\"prompt\", resolved.value.prompt);\n\t\tio.setOutput(\"mode\", resolved.value.mode);\n\t\tio.setOutput(\"_agentSummary\", `Skill \"${config.skillName}\" resolved (${resolved.value.mode}): ${resolved.value.prompt.length} chars.`);\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: io.toOutput()\n\t\t};\n\t}\n};\n//#endregion\nexport { SkillNodeConfigSchema, SkillNodeDefinition, SkillResolverRuntime };\n\n//# sourceMappingURL=index.js.map"],"mappings":"4FASA,IAAI,EAAuB,KAAM,CAChC,KACA,YAAY,EAAS,CACpB,KAAK,KAAO,EAAQ,SACrB,CACA,MAAM,cAAc,EAAS,CAC5B,IAAI,EACJ,GAAI,CACH,EAAW,KAAK,KAAK,aAAa,CACnC,OAAS,EAAK,CACb,MAAO,CACN,GAAI,GACJ,MAAO,EAAwB,0CAA2C,0BAA0B,aAAe,MAAQ,EAAI,QAAU,OAAO,CAAG,IAAK,EAAI,CAC7J,CACD,CACA,IAAM,EAAQ,EAAS,KAAM,GAAY,EAAQ,OAAS,EAAQ,SAAS,EAa3E,OAZK,EAQD,EAAM,UAAY,OAAe,CACpC,GAAI,GACJ,MAAO,EAAqB,wCAAyC,UAAU,EAAQ,UAAU,mHAAoH,CAAE,UAAW,EAAQ,SAAU,CAAC,CACtP,EACO,KAAK,cAAc,EAAO,CAAO,EAZrB,CAClB,GAAI,GACJ,MAAO,EAAqB,iCAAkC,UAAU,EAAQ,UAAU,sDAAuD,CAAE,UAAW,EAAQ,SAAU,EAAG,CAClL,OAAQ,aACR,WAAY,sCACZ,QAAS,EAAS,IAAK,GAAY,EAAQ,IAAI,CAChD,CAAC,CACF,CAMD,CACA,MAAM,cAAc,EAAO,EAAS,CACnC,GAAI,CACH,IAAM,EAAS,MAAM,KAAK,KAAK,aAAa,EAAO,EAAQ,KAAM,EAAQ,YAAc,IAAK,GAAuC,IAAK,GAAxC,CAAE,UAAW,EAAQ,SAAU,CAAU,EAQzI,OAPI,OAAO,EAAO,QAAW,SAOtB,CACN,GAAI,GACJ,MAAO,CACN,OAAQ,EAAO,OACf,KAAM,EAAO,IACd,CACD,EAb8C,CAC7C,GAAI,GACJ,MAAO,EAAwB,0CAA2C,UAAU,EAAQ,UAAU,uCAAwC,GAAO,CACpJ,UAAW,EAAQ,UACnB,KAAM,EAAO,IACd,CAAC,CACF,CAQD,OAAS,EAAK,CACb,IAAM,EAAU,aAAe,MAAQ,EAAI,QAAU,OAAO,CAAG,EAC/D,MAAO,CACN,GAAI,GACJ,MAAO,EAAwB,0CAA2C,4BAA4B,EAAQ,UAAU,KAAK,IAAW,GAAO,CAAE,UAAW,EAAQ,SAAU,CAAC,CAChL,CACD,CACD,CACD,EAGA,MAAM,EAAwB,EAAE,OAAO,CAEtC,UAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAE3B,KAAM,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,EAE3B,UAAW,EAAE,OAAO,CAAC,CAAC,SAAS,EAE/B,YAAa,EAAE,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,CAAC,CAChD,CAAC,EACK,EAAe,CAAC,CACrB,IAAK,OACL,MAAO,OACP,MAAO,EACP,KAAM,SACN,SAAU,EACX,CAAC,EACK,EAAgB,CAAC,CACtB,IAAK,SACL,MAAO,SACP,MAAO,EACP,KAAM,SACN,SAAU,EACX,EAAG,CACF,IAAK,OACL,MAAO,OACP,MAAO,EACP,KAAM,SACN,SAAU,EACX,CAAC,EASD,IAAI,EAAsB,cAAc,CAAuB,CAC9D,SAAW,QACX,YAAc,QACd,SAAW,cACX,OAAS,EACT,QAAU,EACV,uBAAyB,EACzB,iBAAmB,OACnB,kBAAoB,SACpB,QACA,YAAY,EAAS,CACpB,MAAM,EACN,KAAK,QAAU,IAAI,EAAqB,CAAO,CAChD,CACA,MAAM,uBAAuB,EAAQ,EAAU,EAAQ,CACtD,MAAO,CACN,GAAI,GACJ,MAAO,CAAE,iBAAkB,EAAO,WAAY,CAC/C,CACD,CACA,MAAM,kBAAkB,EAAO,EAAS,EAAQ,CAC/C,IAAM,EAAK,IAAI,EAAe,EAAO,EAAQ,eAAe,MAAM,EAC5D,EAAY,EAAG,SAAS,MAAM,EAC9B,EAAO,OAAO,GAAc,UAAY,EAAU,KAAK,CAAC,CAAC,OAAS,EAAI,EAAY,EAAO,KACzF,EAAW,MAAM,KAAK,QAAQ,cAAc,CACjD,UAAW,EAAO,UAClB,OACA,GAAG,EAAO,YAAc,IAAK,GAAsC,CAAC,EAAnC,CAAE,UAAW,EAAO,SAAU,CAChE,CAAC,EASD,OARK,EAAS,GACV,EAAS,MAAM,OAAO,KAAK,CAAC,CAAC,SAAW,EAAU,CACrD,GAAI,GACJ,MAAO,EAAqB,oCAAqC,UAAU,EAAO,UAAU,+BAAgC,CAAE,UAAW,EAAO,SAAU,CAAC,CAC5J,GACA,EAAG,UAAU,SAAU,EAAS,MAAM,MAAM,EAC5C,EAAG,UAAU,OAAQ,EAAS,MAAM,IAAI,EACxC,EAAG,UAAU,gBAAiB,UAAU,EAAO,UAAU,cAAc,EAAS,MAAM,KAAK,KAAK,EAAS,MAAM,OAAO,OAAO,QAAQ,EAC9H,CACN,GAAI,GACJ,MAAO,EAAG,SAAS,CACpB,GAXyB,CAY1B,CACD"}
@@ -1,2 +1,2 @@
1
1
  ;(function(){var v=parseInt(process.versions.node.split('.')[0],10);if(v<22){process.stderr.write('\n✗ Node.js 22+ is required (current: '+process.version+')\n\nUpgrade:\n nvm: nvm install 22 && nvm use 22\n Volta: volta install node@22\n Download: https://nodejs.org/en/download\n\n');process.exit(1);}})();
2
- import{a as e,i as t,n,r}from"./cli-core-DutvpRdJ.js";import{z as i}from"zod";var a=class{port;constructor(e){this.port=e.skillPort}async resolvePrompt(n){let r;try{r=this.port.loadCommands()}catch(e){return{ok:!1,error:t(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Failed to load skills: ${e instanceof Error?e.message:String(e)}`,!0)}}let i=r.find(e=>e.name===n.skillName);return i?i.context===`fork`?{ok:!1,error:e(`DAG_VALIDATION_SKILL_FORK_UNSUPPORTED`,`Skill "${n.skillName}" uses fork context, which the resolver node does not support (no subagent runtime). Use an inject-context skill.`,{skillName:n.skillName})}:this.resolveInject(i,n):{ok:!1,error:e(`DAG_VALIDATION_SKILL_NOT_FOUND`,`Skill "${n.skillName}" was not found in the injected contribution sources`,{skillName:n.skillName},{action:`set_config`,suggestion:`Set skillName to an available skill`,options:r.map(e=>e.name)})}}async resolveInject(e,n){try{let r=await this.port.resolveSkill(e,n.args,n.sessionId===void 0?void 0:{sessionId:n.sessionId});return typeof r.prompt==`string`?{ok:!0,value:{prompt:r.prompt,mode:r.mode}}:{ok:!1,error:t(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Skill "${n.skillName}" did not resolve to an inject prompt`,!1,{skillName:n.skillName,mode:r.mode})}}catch(e){let r=e instanceof Error?e.message:String(e);return{ok:!1,error:t(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Failed to resolve skill "${n.skillName}": ${r}`,!1,{skillName:n.skillName})}}}};const o=i.object({skillName:i.string().min(1),args:i.string().default(``),sessionId:i.string().optional(),baseCredits:i.number().nonnegative().default(0)}),s=[{key:`args`,label:`Args`,order:0,type:`string`,required:!1}],c=[{key:`prompt`,label:`Prompt`,order:0,type:`string`,required:!0},{key:`mode`,label:`Mode`,order:1,type:`string`,required:!0}];var l=class extends n{nodeType=`skill`;displayName=`Skill`;category=`Integration`;inputs=s;outputs=c;configSchemaDefinition=o;defaultInputPort=`args`;defaultOutputPort=`prompt`;runtime;constructor(e){super(),this.runtime=new a(e)}async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:n.baseCredits}}}async executeWithConfig(t,n,i){let a=new r(t,n.nodeDefinition.nodeId),o=a.getInput(`args`),s=typeof o==`string`&&o.trim().length>0?o:i.args,c=await this.runtime.resolvePrompt({skillName:i.skillName,args:s,...i.sessionId===void 0?{}:{sessionId:i.sessionId}});return c.ok?c.value.prompt.trim().length===0?{ok:!1,error:e(`DAG_VALIDATION_SKILL_EMPTY_PROMPT`,`Skill "${i.skillName}" resolved to an empty prompt`,{skillName:i.skillName})}:(a.setOutput(`prompt`,c.value.prompt),a.setOutput(`mode`,c.value.mode),a.setOutput(`_agentSummary`,`Skill "${i.skillName}" resolved (${c.value.mode}): ${c.value.prompt.length} chars.`),{ok:!0,value:a.toOutput()}):c}};export{l as SkillNodeDefinition};
2
+ import{a as e,i as t,n,r}from"./cli-core-Davokkgi.js";import{z as i}from"zod";var a=class{port;constructor(e){this.port=e.skillPort}async resolvePrompt(n){let r;try{r=this.port.loadCommands()}catch(e){return{ok:!1,error:t(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Failed to load skills: ${e instanceof Error?e.message:String(e)}`,!0)}}let i=r.find(e=>e.name===n.skillName);return i?i.context===`fork`?{ok:!1,error:e(`DAG_VALIDATION_SKILL_FORK_UNSUPPORTED`,`Skill "${n.skillName}" uses fork context, which the resolver node does not support (no subagent runtime). Use an inject-context skill.`,{skillName:n.skillName})}:this.resolveInject(i,n):{ok:!1,error:e(`DAG_VALIDATION_SKILL_NOT_FOUND`,`Skill "${n.skillName}" was not found in the injected contribution sources`,{skillName:n.skillName},{action:`set_config`,suggestion:`Set skillName to an available skill`,options:r.map(e=>e.name)})}}async resolveInject(e,n){try{let r=await this.port.resolveSkill(e,n.args,n.sessionId===void 0?void 0:{sessionId:n.sessionId});return typeof r.prompt==`string`?{ok:!0,value:{prompt:r.prompt,mode:r.mode}}:{ok:!1,error:t(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Skill "${n.skillName}" did not resolve to an inject prompt`,!1,{skillName:n.skillName,mode:r.mode})}}catch(e){let r=e instanceof Error?e.message:String(e);return{ok:!1,error:t(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Failed to resolve skill "${n.skillName}": ${r}`,!1,{skillName:n.skillName})}}}};const o=i.object({skillName:i.string().min(1),args:i.string().default(``),sessionId:i.string().optional(),baseCredits:i.number().nonnegative().default(0)}),s=[{key:`args`,label:`Args`,order:0,type:`string`,required:!1}],c=[{key:`prompt`,label:`Prompt`,order:0,type:`string`,required:!0},{key:`mode`,label:`Mode`,order:1,type:`string`,required:!0}];var l=class extends n{nodeType=`skill`;displayName=`Skill`;category=`Integration`;inputs=s;outputs=c;configSchemaDefinition=o;defaultInputPort=`args`;defaultOutputPort=`prompt`;runtime;constructor(e){super(),this.runtime=new a(e)}async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:n.baseCredits}}}async executeWithConfig(t,n,i){let a=new r(t,n.nodeDefinition.nodeId),o=a.getInput(`args`),s=typeof o==`string`&&o.trim().length>0?o:i.args,c=await this.runtime.resolvePrompt({skillName:i.skillName,args:s,...i.sessionId===void 0?{}:{sessionId:i.sessionId}});return c.ok?c.value.prompt.trim().length===0?{ok:!1,error:e(`DAG_VALIDATION_SKILL_EMPTY_PROMPT`,`Skill "${i.skillName}" resolved to an empty prompt`,{skillName:i.skillName})}:(a.setOutput(`prompt`,c.value.prompt),a.setOutput(`mode`,c.value.mode),a.setOutput(`_agentSummary`,`Skill "${i.skillName}" resolved (${c.value.mode}): ${c.value.prompt.length} chars.`),{ok:!0,value:a.toOutput()}):c}};export{l as SkillNodeDefinition};
@@ -159,7 +159,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => {
159
159
  `],{env:{BUN_BE_BUN:`1`,...process.env.SystemRoot?{SystemRoot:process.env.SystemRoot}:{}},cwd:le(),stdio:`pipe`});closed;constructor(){super();let e=``;this.child.stdout.setEncoding(`utf8`),this.child.stdout.on(`data`,t=>{if(e+=t,Buffer.byteLength(e,`utf8`)>25166848){this.emit(`error`);return}let n;for(;(n=e.indexOf(`
160
160
  `))>=0;){let t=e.slice(0,n);e=e.slice(n+1);try{this.emit(`message`,JSON.parse(t))}catch{this.emit(`error`)}}}),this.child.stderr.resume(),this.child.on(`error`,()=>this.emit(`error`)),this.child.stdin.on(`error`,()=>this.emit(`error`)),this.closed=new Promise(e=>{this.child.once(`close`,()=>{this.emit(`exit`),e()})})}postMessage(e){this.child.stdin.write(JSON.stringify(e)+`
161
161
  `)}async terminate(){this.child.exitCode===null&&this.child.signalCode===null&&this.child.kill(`SIGKILL`),await this.closed}},sa=class{pattern;signal;worker=process.versions.bun?new oa:new Y(aa,{eval:!0,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128,maxYoungGenerationSizeMb:32}});pending=new Map;nextId=0;stopped=!1;termination;timer;abort=()=>{this.stop(Error(`Grep search cancelled`))};constructor(e,t){this.pattern=e,this.signal=t,this.worker.on(`message`,e=>{let t=this.pending.get(e.id);!t||this.stopped||(this.pending.delete(e.id),Array.isArray(e.matches)&&e.matches.every(e=>typeof e==`string`)?t.resolve(e.matches):t.reject(Error(e.error??`Invalid grep worker response`)))}),this.worker.on(`error`,()=>{this.stop(Error(`Grep search worker failed`))}),this.worker.once(`exit`,()=>{this.stop(Error(`Grep search worker exited`))}),this.timer=setTimeout(()=>{this.stop(Error(`Grep search timed out`))},2e3),t?.addEventListener(`abort`,this.abort,{once:!0}),t?.aborted&&this.abort()}search(e,t,n,r){if(this.stopped)return Promise.reject(Error(this.signal?.aborted?`Grep search cancelled`:`Grep search timed out`));let i=this.nextId++;return new Promise((a,o)=>{this.pending.set(i,{resolve:a,reject:o});try{this.worker.postMessage({id:i,content:e,filePath:t,pattern:this.pattern,contextLines:n,outputMode:r})}catch{this.stop(Error(`Grep search worker failed`))}})}async stop(e){return this.termination?this.termination:(this.stopped=!0,clearTimeout(this.timer),this.signal?.removeEventListener(`abort`,this.abort),this.termination=(async()=>{try{await this.worker.terminate()}catch{}for(let t of this.pending.values())t.reject(e??Error(`Grep search stopped`));this.pending.clear()})(),this.termination)}};const ca=q.object({pattern:q.string().describe(`The regular expression pattern to search for in file contents`),path:q.string().optional().describe(`File or directory to search in. Defaults to the current working directory`),glob:q.string().optional().describe(`Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}"). Only files matching this pattern will be searched`),contextLines:q.number().optional().describe(`Number of context lines to show before and after each match. Only applies when outputMode is "content". Default: 0`),outputMode:q.enum([`files_with_matches`,`content`,`count`]).optional().describe(`Output mode: "files_with_matches" shows only file paths (default), "content" shows matching lines with context, "count" shows per-file match counts`),headLimit:q.number().int().positive().optional().describe(`Maximum number of result lines (file paths, content lines, or count rows) to return. Excess results are truncated with a marker line`)}),la=4*1024*1024;var ua=class extends u{reason;constructor(e){super(`Grep search ${e===`timeout`?`timed out`:e===`cancelled`?`cancelled`:e===`limit`?`exceeded its byte limit`:`worker failed`}`,`Grep`),this.reason=e}};async function da(e,t){let{pattern:n,path:r,glob:i,contextLines:a=0,outputMode:o=`files_with_matches`,headLimit:s}=e,c=t.cwd,{root:l,error:u}=Ei(r,c);if(u)return u;try{new RegExp(n)}catch{let e={success:!1,output:``,error:`Invalid regex pattern: ${n}`};return JSON.stringify(e)}let d;try{d=await F(l)}catch{let e={success:!1,output:``,error:`Path not found: ${l}`};return JSON.stringify(e)}let f,p=!1;if(d.isFile())f=[l];else{let e=await ra(l,i,c);f=e.files,p=e.truncated}let m=new sa(n,t.signal),h=new AbortController,g=()=>h.abort();t.signal?.addEventListener(`abort`,g,{once:!0}),t.signal?.aborted&&g();let _;try{if(h.signal.aborted)throw new ua(`cancelled`);let e=Array(f.length),t=0,n,r=async e=>{let t;try{if((await F(e)).size>la)throw new ua(`limit`);let n=B(e,{highWaterMark:65536,signal:h.signal}),r=[],i=0;try{for await(let e of n){if(h.signal.aborted)throw new ua(`cancelled`);let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=t.length,i>la)throw new ua(`limit`);r.push(t)}}finally{n.destroy()}let a=Buffer.concat(r,i),o=Math.min(a.length,8192),s=!1;for(let e=0;e<o;e++)if(a[e]===0){s=!0;break}if(s)return[];t=a.toString(`utf8`)}catch(e){if(e instanceof ua)throw e;if(h.signal.aborted)throw new ua(`cancelled`);return[]}return m.search(t,e,a,o)};if(await Promise.all(Array.from({length:Math.min(8,f.length)},async()=>{for(;n===void 0&&t<f.length;){let i=t++;try{e[i]=await r(f[i])}catch(e){n===void 0&&(n=e,h.abort(),m.stop(e instanceof Error?e:Error(`Grep search failed`)))}}})),n!==void 0)throw n;_=e}catch(e){let t=e instanceof Error?e.message:``;throw e instanceof ua?e:new ua(t.includes(`timed out`)?`timeout`:t.includes(`cancelled`)?`cancelled`:t.includes(`byte limit`)?`limit`:`failed`)}finally{t.signal?.removeEventListener(`abort`,g),await m.stop()}let v=0;for(let e of _)for(let t of e)if(v+=Buffer.byteLength(t,`utf8`)+1,v>4*1024*1024)throw new ua(`limit`);let y=_.flat();if(s!==void 0&&y.length>s){let e=y.length-s;y=[...y.slice(0,s),`(+${e} more results truncated by headLimit)`]}p&&(y=[...y,`[File enumeration stopped early; the search tree has more files than this tool scans in one call. Results may be incomplete — narrow the path or glob.]`]);let b={success:!0,output:y.length>0?y.join(`
162
- `):`(no matches)`};return JSON.stringify(b)}function fa(e){return`A powerful search tool built on regex matching.\n\nSupports full regex syntax (e.g., 'log.*Error', 'function\\\\s+\\\\w+'). Filter files with glob parameter (e.g., '*.js', '**/*.tsx').\n\nOutput modes: 'content' shows matching lines with context, 'files_with_matches' shows only file paths (default), 'count' shows per-file match counts.\n\nPrefer this tool over running grep or rg through the ${e} tool — it returns structured results directly.\n\nUse headLimit to control result size and save context space.`}function pa(e){return Vr(`Grep`,e.description??fa(e.shellToolName??`Shell`),ca,async t=>da(t,e))}const ma=3e4,ha=5e6,ga=q.object({url:q.string().describe(`The URL to fetch`),headers:q.record(q.string()).optional().describe(`Optional HTTP headers as key-value pairs`)});function _a(e,t){let n=`<${t}`,r=`</${t}>`,i=e.replace(/[A-Z]/g,e=>e.toLowerCase()),a=[],o=0;for(;;){let t=i.indexOf(n,o);if(t<0)break;let s=i.indexOf(r,t+n.length);if(s<0)break;a.push(e.slice(o,t)),o=s+r.length}return a.push(e.slice(o)),a.join(``)}function va(e){let t=[],n=0;for(;;){let r=e.indexOf(`<`,n);if(r<0)break;let i=e.indexOf(`>`,r+1);if(i<0)break;if(i===r+1){t.push(e.slice(n,r+1)),n=r+1;continue}t.push(e.slice(n,r),` `),n=i+1}return t.push(e.slice(n)),t.join(``)}const ya={"&amp;":`&`,"&lt;":`<`,"&gt;":`>`,"&quot;":`"`,"&#39;":`'`,"&nbsp;":` `},ba=/&(?:amp|lt|gt|quot|nbsp|#39);/g;function xa(e){return va(_a(_a(e,`script`),`style`)).replace(ba,e=>ya[e]).replace(/\s+/g,` `).trim()}function Sa(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${ma/1e3}s. The server did not respond in time.`;let t=e.code;return t===`ENOTFOUND`||t===`EAI_AGAIN`?`Network error: DNS resolution failed for this host. The URL may be incorrect or the host does not exist. Do not retry with the same URL.`:t===`ECONNREFUSED`?`Network error: Connection refused. The server is not accepting connections at this address. Do not retry with the same URL.`:t===`ECONNRESET`?`Network error: Connection was reset by the server. The server may be temporarily unavailable.`:t===`ETIMEDOUT`?`Network error: Connection timed out. The server is not reachable within the expected time.`:t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?`Network error: SSL certificate error (${t}). The server's certificate is invalid. Do not retry with the same URL.`:`Network error: ${e.message} Check that the URL is correct and the server is reachable.`}async function Ca(e,t,n,r){let{url:i,headers:a}=e;try{new URL(i)}catch{let e={success:!1,output:``,error:`Invalid URL: "${i}". Fix the URL format before retrying.`};return JSON.stringify(e)}try{let e=await Gn(i,{headers:{...n===void 0?{}:{"User-Agent":n},...a??{}},signal:r,timeoutMs:ma,maxResponseBytes:ha},t.policy,t.deps);if(!e.ok){let{rejection:t}=e,n={success:!1,output:``,error:t.reason===`response_too_large`?`Response too large (max ${ha} bytes). Consider fetching a more specific URL or a paginated endpoint.`:`Blocked by egress policy: ${t.message} Do not retry with the same URL.`};return JSON.stringify(n)}if(e.status<200||e.status>=300){let t=e.status>=500?` The server is temporarily unavailable — retrying may help.`:` Do not retry with the same URL.`,n={success:!1,output:``,error:`HTTP ${e.status} ${e.statusText}.${t}`};return JSON.stringify(n)}let o=e.headers.get(`content-type`)??``,s=new TextDecoder().decode(e.body);return o.includes(`html`)&&(s=xa(s)),JSON.stringify({success:!0,output:s})}catch(e){let t={success:!1,output:``,error:Sa(e)};return JSON.stringify(t)}}function wa(e={}){let t=e.egress??{};return Vr(`WebFetch`,e.description??`Fetch a URL and return its content as text. HTML pages are converted to plain text.`,ga,async(n,r)=>Ca(n,t,e.userAgent,r?.signal))}const Ta=wa();function Ea(){return{async search({query:e,limit:t},n){let r=process.env.BRAVE_API_KEY;if(!r)throw Error(`Web search requires BRAVE_API_KEY environment variable for the default Brave Search provider, or inject a custom search provider at the composition root.`);let i=new URLSearchParams({q:e,count:String(Math.min(t,20))}),a=await fetch(`https://api.search.brave.com/res/v1/web/search?${i}`,{headers:{Accept:`application/json`,"Accept-Encoding":`gzip`,"X-Subscription-Token":r},...n?{signal:n}:{}});if(!a.ok)throw Error(`Brave Search API error: HTTP ${a.status} ${a.statusText}`);return((await a.json()).web?.results??[]).map(e=>({title:e.title,url:e.url,snippet:e.description}))}}}const Da=q.object({query:q.string().describe(`The search query`),limit:q.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function Oa(e,t,n){let{query:r,limit:i=10}=e;try{let e=new AbortController,a=setTimeout(()=>e.abort(),15e3),o=n?AbortSignal.any([e.signal,n]):e.signal;try{let e=await t.search({query:r,limit:i},o),n={success:!0,output:JSON.stringify(e,null,2)};return JSON.stringify(n)}finally{clearTimeout(a)}}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}function ka(e={}){let t=e.provider??Ea();return Vr(`WebSearch`,e.description??`Search the web and return results with title, URL, and snippet.`,Da,async(e,n)=>Oa(e,t,n?.signal))}const Aa=ka(),ja=q.object({question:q.string().min(1).describe(`The complete question to ask the user.`),header:q.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:q.array(q.union([q.string().min(1).describe(`Display text of this choice.`),q.object({label:q.string().min(1).describe(`Display text of this choice.`),description:q.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:q.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:q.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),Ma=q.object({questions:q.array(ja).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),Na=[`Ask the user one or more structured questions and wait for their answers.`,``,`Use this when you are blocked on a decision only the user can make — ambiguous requirements,`,`mutually exclusive approaches, or choices with real trade-offs. Do not use it for decisions with`,`a conventional default or facts you can verify yourself.`,``,`Provide 1-4 questions. Each question offers predefined options and/or free text:`,` - options + default: user picks one option (or types a custom answer unless allowFreeText: false)`,` - multiSelect: true: user may pick several options`,` - no options: pure free-text entry`,``,"The result is a JSON array with one entry per question: the selected option labels in `values`","and/or the typed answer in `text`, or `cancelled: true` if the user dismissed the question.","If no interactive user is attached (headless run), the result is `{ unavailable: true }` —",`continue autonomously with your best judgment and say what you assumed.`].join(`
163
- `);function Pa(e){let t=(e.options??[]).map(e=>typeof e==`string`?{label:e}:e),n=e.multiSelect===!0&&t.length>1;return{id:`ask_${h()}`,title:e.question,...e.header===void 0?{}:{description:e.header},...t.length>0?{options:t.map(e=>({value:e.label,label:e.label,...e.description===void 0?{}:{description:e.description}}))}:{},minSelect:+(t.length>0),maxSelect:n?t.length:1,allowFreeText:e.allowFreeText!==!1||t.length===0}}async function Fa(e,t){let n=[],r=!1;for(let i of e.questions){if(r){n.push({question:i.question,cancelled:!0});continue}let e=await t(Pa(i));if(e.type===`cancelled`){r=!0,n.push({question:i.question,cancelled:!0});continue}n.push({question:i.question,values:[...e.values],...e.text===void 0?{}:{text:e.text}})}return{answers:n}}function Ia(e={}){return Vr(`AskUserQuestion`,e.description??Na,Ma,async(e,t)=>{let n=e,r=t?.ask,i=r?await Fa(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)})}Ia();const La=1/0;function Ra(e,t){e.description!==void 0&&t.push(e.description);for(let[n,r]of Object.entries(e.properties??{}))t.push(n),Ra(r,t);e.items!==void 0&&Ra(e.items,t);for(let n of e.anyOf??[])Ra(n,t)}function za(e,t){let n=e.name.toLowerCase();if(n===t)return 0;if(n.includes(t))return 1;if(e.description.toLowerCase().includes(t))return 2;let r=[];return Ra(e.parameters,r),r.some(e=>e.toLowerCase().includes(t))?3:La}function Ba(e,t,n){let r=t.trim().toLowerCase();return r.length===0?[]:e.map(e=>({schema:e,rank:za(e,r)})).filter(e=>e.rank!==La).sort((e,t)=>e.rank-t.rank||(e.schema.name<t.schema.name?-1:1)).slice(0,n).map(e=>e.schema)}const Va=o,Ha=q.object({query:q.string().optional().describe(`Text matched case-insensitively against each withheld tool's name, description, and its parameters' names and descriptions. An exact tool name is a valid query.`),names:q.array(q.string().min(1)).optional().describe(`Exact tool names to load, skipping the search. An unknown name is an error naming it.`),limit:q.number().int().positive().optional().describe(`Maximum tools to load from a query match (default 5).`)}),Ua=[`Load tools whose definitions are withheld from your tool list, so you can call them.`,``,`Some tools are deferred: they exist and are callable, but their schemas are not sent to you until`,`you load them here. If a capability you need is not in your tool list, search for it before`,`concluding it is unavailable — and if a tool call fails as "deferred and not yet loaded", load it`,`with this tool and call it again.`,``,` - query: what you are trying to do (e.g. "read a spreadsheet", "postgres"). Matched against tool`,` names, descriptions, and parameter names and descriptions. An exact tool name works too.`,` - names: load exactly these tools, skipping the search. Unknown names are an error.`,` - limit: how many matches to load (default 5).`,``,`The result lists what is now loaded; those tools appear in your tool list from your next turn and`,`stay available. A query that matches nothing returns an empty list — that is a normal answer, not`,"a failure. `unavailableSources` names any tool source that could not be consulted."].join(`
164
- `);function Wa(e){let t=e?.deferredTools;if(!t)throw Error(`${Va} requires the deferred-tool catalog, which the execution runtime injects; it was not present, so this tool was called outside the agent execution loop.`);return t}function Ga(e,t){if(e.names!==void 0)return t.loadDeferredTools(e.names);if(e.query===void 0)throw Error(`${Va} needs either "query" to search for tools or "names" to load exact ones.`);let n=Ba(t.listDeferredTools(),e.query,e.limit??5);return t.loadDeferredTools(n.map(e=>e.name))}function Ka(e={}){return Vr(Va,e.description??Ua,Ha,async(e,t)=>{let n={loaded:Ga(e,Wa(t)).map(({name:e,description:t})=>({name:e,description:t})),unavailableSources:[]},r={success:!0,output:JSON.stringify(n)};return JSON.stringify(r)})}Ka();export{On as A,Pr as C,xn as D,Aa as E,Gn as F,Tn as I,ve as L,An as M,Cn as N,Vn as O,Kn as P,pe as R,$n as S,Ta as T,Ka as _,ki as a,Ui as b,Ia as c,Yi as d,ea as f,vi as g,Jr as h,Br as i,kn as j,Wn as k,yi as l,Ii as m,Qn as n,Ai as o,pa as p,ua as r,ir as s,jr as t,ci as u,wa as v,er as w,Vr as x,ka as y};
165
- //# sourceMappingURL=node-BrAmtuTw.js.map
162
+ `):`(no matches)`};return JSON.stringify(b)}function fa(e){return`A powerful search tool built on regex matching.\n\nSupports full regex syntax (e.g., 'log.*Error', 'function\\\\s+\\\\w+'). Filter files with glob parameter (e.g., '*.js', '**/*.tsx').\n\nOutput modes: 'content' shows matching lines with context, 'files_with_matches' shows only file paths (default), 'count' shows per-file match counts.\n\nPrefer this tool over running grep or rg through the ${e} tool — it returns structured results directly.\n\nUse headLimit to control result size and save context space.`}function pa(e){return Vr(`Grep`,e.description??fa(e.shellToolName??`Shell`),ca,async t=>da(t,e))}const ma=3e4,ha=5e6,ga=q.object({url:q.string().describe(`The URL to fetch`),headers:q.record(q.string()).optional().describe(`Optional HTTP headers as key-value pairs`)});function _a(e,t){let n=`<${t}`,r=`</${t}>`,i=e.replace(/[A-Z]/g,e=>e.toLowerCase()),a=[],o=0;for(;;){let t=i.indexOf(n,o);if(t<0)break;let s=i.indexOf(r,t+n.length);if(s<0)break;a.push(e.slice(o,t)),o=s+r.length}return a.push(e.slice(o)),a.join(``)}function va(e){let t=[],n=0;for(;;){let r=e.indexOf(`<`,n);if(r<0)break;let i=e.indexOf(`>`,r+1);if(i<0)break;if(i===r+1){t.push(e.slice(n,r+1)),n=r+1;continue}t.push(e.slice(n,r),` `),n=i+1}return t.push(e.slice(n)),t.join(``)}const ya={"&amp;":`&`,"&lt;":`<`,"&gt;":`>`,"&quot;":`"`,"&#39;":`'`,"&nbsp;":` `},ba=/&(?:amp|lt|gt|quot|nbsp|#39);/g;function xa(e){return va(_a(_a(e,`script`),`style`)).replace(ba,e=>ya[e]).replace(/\s+/g,` `).trim()}function Sa(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${ma/1e3}s. The server did not respond in time.`;let t=e.code;return t===`ENOTFOUND`||t===`EAI_AGAIN`?`Network error: DNS resolution failed for this host. The URL may be incorrect or the host does not exist. Do not retry with the same URL.`:t===`ECONNREFUSED`?`Network error: Connection refused. The server is not accepting connections at this address. Do not retry with the same URL.`:t===`ECONNRESET`?`Network error: Connection was reset by the server. The server may be temporarily unavailable.`:t===`ETIMEDOUT`?`Network error: Connection timed out. The server is not reachable within the expected time.`:t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?`Network error: SSL certificate error (${t}). The server's certificate is invalid. Do not retry with the same URL.`:`Network error: ${e.message} Check that the URL is correct and the server is reachable.`}function Ca(e,t){return/text\/(plain|markdown)/i.test(e)?new TextDecoder().decode(t).split(/\r?\n/).find(e=>e.trim()!==``)?.startsWith(`# `)??!1:!1}async function wa(e,t,n,r){let i=`${e}/llms.txt`;try{let e=await Gn(i,{headers:n===void 0?{}:{"User-Agent":n},signal:r,timeoutMs:2e3,maxResponseBytes:512e3},t.policy,t.deps);return!e.ok||e.status<200||e.status>=300?void 0:Ca(e.headers.get(`content-type`)??``,e.body)?i:void 0}catch{return}}function Ta(e){return`\n\nThis site publishes an LLM index at ${e} (llms.txt); fetch it for a curated map of the docs.`}async function Ea(e,t,n,r,i){let{url:a,headers:o}=e;try{new URL(a)}catch{let e={success:!1,output:``,error:`Invalid URL: "${a}". Fix the URL format before retrying.`};return JSON.stringify(e)}try{let e=await Gn(a,{headers:{...n===void 0?{}:{"User-Agent":n},...o??{}},signal:i,timeoutMs:ma,maxResponseBytes:ha},t.policy,t.deps);if(!e.ok){let{rejection:t}=e,n={success:!1,output:``,error:t.reason===`response_too_large`?`Response too large (max ${ha} bytes). Consider fetching a more specific URL or a paginated endpoint.`:`Blocked by egress policy: ${t.message} Do not retry with the same URL.`};return JSON.stringify(n)}if(e.status<200||e.status>=300){let t=e.status>=500?` The server is temporarily unavailable — retrying may help.`:` Do not retry with the same URL.`,n={success:!1,output:``,error:`HTTP ${e.status} ${e.statusText}.${t}`};return JSON.stringify(n)}let s=e.headers.get(`content-type`)??``,c=new TextDecoder().decode(e.body);if(s.includes(`html`)){let a=new URL(e.finalUrl).origin,o=r?.get(a);if(r&&o===void 0){let e=wa(a,t,n,i).then(t=>(t===void 0&&i?.aborted&&r.get(a)===e&&r.delete(a),t));o=e,r.set(a,o)}c=xa(c);let s=await o;s!==void 0&&(c+=Ta(s))}return JSON.stringify({success:!0,output:c})}catch(e){let t={success:!1,output:``,error:Sa(e)};return JSON.stringify(t)}}const Da=`Fetch a URL and return its content as text. HTML pages are converted to plain text. Documentation sites may publish a curated index at /llms.txt (full text at /llms-full.txt)`,Oa=`${Da}; when a fetched page's site has one, the result points to it.`,ka=`${Da}.`;function Aa(e={}){let t=e.egress??{},n=e.llmsTxtProbe===!1?void 0:new Map;return Vr(`WebFetch`,e.description??(n?Oa:ka),ga,async(r,i)=>Ea(r,t,e.userAgent,n,i?.signal))}const ja=Aa();function Ma(){return{async search({query:e,limit:t},n){let r=process.env.BRAVE_API_KEY;if(!r)throw Error(`Web search requires BRAVE_API_KEY environment variable for the default Brave Search provider, or inject a custom search provider at the composition root.`);let i=new URLSearchParams({q:e,count:String(Math.min(t,20))}),a=await fetch(`https://api.search.brave.com/res/v1/web/search?${i}`,{headers:{Accept:`application/json`,"Accept-Encoding":`gzip`,"X-Subscription-Token":r},...n?{signal:n}:{}});if(!a.ok)throw Error(`Brave Search API error: HTTP ${a.status} ${a.statusText}`);return((await a.json()).web?.results??[]).map(e=>({title:e.title,url:e.url,snippet:e.description}))}}}const Na=q.object({query:q.string().describe(`The search query`),limit:q.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function Pa(e,t,n){let{query:r,limit:i=10}=e;try{let e=new AbortController,a=setTimeout(()=>e.abort(),15e3),o=n?AbortSignal.any([e.signal,n]):e.signal;try{let e=await t.search({query:r,limit:i},o),n={success:!0,output:JSON.stringify(e,null,2)};return JSON.stringify(n)}finally{clearTimeout(a)}}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}function Fa(e={}){let t=e.provider??Ma();return Vr(`WebSearch`,e.description??`Search the web and return results with title, URL, and snippet.`,Na,async(e,n)=>Pa(e,t,n?.signal))}const Ia=Fa(),La=q.object({question:q.string().min(1).describe(`The complete question to ask the user.`),header:q.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:q.array(q.union([q.string().min(1).describe(`Display text of this choice.`),q.object({label:q.string().min(1).describe(`Display text of this choice.`),description:q.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:q.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:q.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),Ra=q.object({questions:q.array(La).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),za=[`Ask the user one or more structured questions and wait for their answers.`,``,`Use this when you are blocked on a decision only the user can make — ambiguous requirements,`,`mutually exclusive approaches, or choices with real trade-offs. Do not use it for decisions with`,`a conventional default or facts you can verify yourself.`,``,`Provide 1-4 questions. Each question offers predefined options and/or free text:`,` - options + default: user picks one option (or types a custom answer unless allowFreeText: false)`,` - multiSelect: true: user may pick several options`,` - no options: pure free-text entry`,``,"The result is a JSON array with one entry per question: the selected option labels in `values`","and/or the typed answer in `text`, or `cancelled: true` if the user dismissed the question.","If no interactive user is attached (headless run), the result is `{ unavailable: true }` —",`continue autonomously with your best judgment and say what you assumed.`].join(`
163
+ `);function Ba(e){let t=(e.options??[]).map(e=>typeof e==`string`?{label:e}:e),n=e.multiSelect===!0&&t.length>1;return{id:`ask_${h()}`,title:e.question,...e.header===void 0?{}:{description:e.header},...t.length>0?{options:t.map(e=>({value:e.label,label:e.label,...e.description===void 0?{}:{description:e.description}}))}:{},minSelect:+(t.length>0),maxSelect:n?t.length:1,allowFreeText:e.allowFreeText!==!1||t.length===0}}async function Va(e,t){let n=[],r=!1;for(let i of e.questions){if(r){n.push({question:i.question,cancelled:!0});continue}let e=await t(Ba(i));if(e.type===`cancelled`){r=!0,n.push({question:i.question,cancelled:!0});continue}n.push({question:i.question,values:[...e.values],...e.text===void 0?{}:{text:e.text}})}return{answers:n}}function Ha(e={}){return Vr(`AskUserQuestion`,e.description??za,Ra,async(e,t)=>{let n=e,r=t?.ask,i=r?await Va(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)})}Ha();const Ua=1/0;function Wa(e,t){e.description!==void 0&&t.push(e.description);for(let[n,r]of Object.entries(e.properties??{}))t.push(n),Wa(r,t);e.items!==void 0&&Wa(e.items,t);for(let n of e.anyOf??[])Wa(n,t)}function Ga(e,t){let n=e.name.toLowerCase();if(n===t)return 0;if(n.includes(t))return 1;if(e.description.toLowerCase().includes(t))return 2;let r=[];return Wa(e.parameters,r),r.some(e=>e.toLowerCase().includes(t))?3:Ua}function Ka(e,t,n){let r=t.trim().toLowerCase();return r.length===0?[]:e.map(e=>({schema:e,rank:Ga(e,r)})).filter(e=>e.rank!==Ua).sort((e,t)=>e.rank-t.rank||(e.schema.name<t.schema.name?-1:1)).slice(0,n).map(e=>e.schema)}const qa=o,Ja=q.object({query:q.string().optional().describe(`Text matched case-insensitively against each withheld tool's name, description, and its parameters' names and descriptions. An exact tool name is a valid query.`),names:q.array(q.string().min(1)).optional().describe(`Exact tool names to load, skipping the search. An unknown name is an error naming it.`),limit:q.number().int().positive().optional().describe(`Maximum tools to load from a query match (default 5).`)}),Ya=[`Load tools whose definitions are withheld from your tool list, so you can call them.`,``,`Some tools are deferred: they exist and are callable, but their schemas are not sent to you until`,`you load them here. If a capability you need is not in your tool list, search for it before`,`concluding it is unavailable — and if a tool call fails as "deferred and not yet loaded", load it`,`with this tool and call it again.`,``,` - query: what you are trying to do (e.g. "read a spreadsheet", "postgres"). Matched against tool`,` names, descriptions, and parameter names and descriptions. An exact tool name works too.`,` - names: load exactly these tools, skipping the search. Unknown names are an error.`,` - limit: how many matches to load (default 5).`,``,`The result lists what is now loaded; those tools appear in your tool list from your next turn and`,`stay available. A query that matches nothing returns an empty list — that is a normal answer, not`,"a failure. `unavailableSources` names any tool source that could not be consulted."].join(`
164
+ `);function Xa(e){let t=e?.deferredTools;if(!t)throw Error(`${qa} requires the deferred-tool catalog, which the execution runtime injects; it was not present, so this tool was called outside the agent execution loop.`);return t}function Za(e,t){if(e.names!==void 0)return t.loadDeferredTools(e.names);if(e.query===void 0)throw Error(`${qa} needs either "query" to search for tools or "names" to load exact ones.`);let n=Ka(t.listDeferredTools(),e.query,e.limit??5);return t.loadDeferredTools(n.map(e=>e.name))}function Qa(e={}){return Vr(qa,e.description??Ya,Ja,async(e,t)=>{let n={loaded:Za(e,Xa(t)).map(({name:e,description:t})=>({name:e,description:t})),unavailableSources:[]},r={success:!0,output:JSON.stringify(n)};return JSON.stringify(r)})}Qa();export{On as A,Pr as C,xn as D,Ia as E,Gn as F,Tn as I,ve as L,An as M,Cn as N,Vn as O,Kn as P,pe as R,$n as S,ja as T,Qa as _,ki as a,Ui as b,Ha as c,Yi as d,ea as f,vi as g,Jr as h,Br as i,kn as j,Wn as k,yi as l,Ii as m,Qn as n,Ai as o,pa as p,ua as r,ir as s,jr as t,ci as u,Aa as v,er as w,Vr as x,Fa as y};
165
+ //# sourceMappingURL=node-CtG-zp83.js.map