buckyos 0.7.185 → 0.7.187

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
- "use strict";var t=Object.defineProperty,e=(e,n,r)=>(((e,n,r)=>{n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r})(e,"symbol"!=typeof n?n+"":n,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./aicc-ccb36ef7.js"),r=require("./site_manager-334b1a51.js"),i=require("./openai-f560d518.js");function o(){const t=globalThis.Deno;if(!t)throw new Error("the xllm Deno host needs the Deno runtime");return t}function s(t){return t instanceof o().errors.NotFound}function a(t){return t instanceof o().errors.AlreadyExists}function c(t){return t instanceof Error?t.message:String(t)}function l(...t){let e="";for(const n of t)n&&(e=n.startsWith("/")||!e?n:e.endsWith("/")?e+n:`${e}/${n}`);return e}function u(t){const e=t.replace(/\/+$/,""),n=e.lastIndexOf("/");return n<0?".":0===n?"/":e.slice(0,n)}async function d(t){try{return(await o().stat(t)).isDirectory}catch{return!1}}async function h(t,e){const n=await o().open(t,{write:!0,create:!0,truncate:!0});try{let t=0;for(;t<e.length;)t+=await n.write(e.subarray(t));await n.sync()}finally{n.close()}}async function f(t){if("windows"===o().build.os)return;const e=await o().open(t,{read:!0});try{await e.sync()}finally{e.close()}}require("./krpc_client-26c2dc8b.js");const m=t=>t/2**32|0,p=t=>t>>>0;function w(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name&&"BYTES_PER_ELEMENT"in t&&1===t.BYTES_PER_ELEMENT}const g=t=>t?`"${t}" `:"";function y(t,e=""){if("number"!=typeof t)throw new TypeError(g(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(g(e)+"expected integer >= 0, got "+t);return t}function _(t,e,n=""){if(w(t)&&(void 0===e||t.length===e))return t;void 0!==e&&y(e,"length");const r=w(t),i=void 0!==e?` of length ${e}`:"",o=r?`length=${t.length}`:"type="+typeof t,s=g(n)+"expected Uint8Array"+i+", got "+o;if(!r)throw new TypeError(s);throw new RangeError(s)}const v=(t,e)=>{((t,e)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError(("object"===e?"":`"${e}" `)+"expected object, got type="+typeof t)})(t,e);const n=Object.getPrototypeOf(t);if(n!==Object.prototype&&null!==n)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function b(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function $(t,e){_(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function k(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function x(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function E(t,e){return t<<32-e|t>>>e}const O=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function I(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const S=O?t=>t:t=>I(t)>>>0;const T=O?t=>t:function(t){for(let e=0;e<t.length;e++)t[e]=I(t[e]);return t},A=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),L=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function P(t,e,n="opts"){v(t,"defaults"),void 0!==e&&v(e,n);return Object.assign(Object.create(null),t,e)}function R(t,e={}){if("function"!=typeof t)throw new TypeError('"hashCons" expected function, got type='+typeof t);e=P({},e,"info");const n=(e,n)=>t(n).update(e).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=e=>t(e),Object.assign(n,e),Object.freeze(n)}const D=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function j(t,e,n,r,i){return r=E(r^(t=t+e+i|0),16),{a:t,b:e=E(e^(n=n+r|0),12),c:n,d:r}}function X(t,e,n,r,i){return r=E(r^(t=t+e+i|0),8),{a:t,b:e=E(e^(n=n+r|0),7),c:n,d:r}}class M{constructor(t,n){e(this,"buffer"),e(this,"buffer32"),e(this,"finished",!1),e(this,"destroyed",!1),e(this,"length",0),e(this,"pos",0),e(this,"blockLen"),e(this,"outputLen"),e(this,"canXOF",!1),y(t),y(n),this.blockLen=t,this.outputLen=n,this.buffer=new Uint8Array(t),this.buffer32=k(this.buffer)}update(t){b(this),_(t);const{blockLen:e,buffer:n,buffer32:r}=this,i=t.length,o=t.byteOffset,s=t.buffer;for(let a=0;a<i;){this.pos===e&&(T(r),this.compress(r,0,!1),T(r),this.pos=0);const c=Math.min(e-this.pos,i-a),l=o+a;if(c!==e||l%4||!(a+c<i))n.set(0===a&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,this.length+=c,a+=c;else{const t=new Uint32Array(s,l,Math.floor((i-a)/4));T(t);for(let n=0;a+e<i;n+=r.length,a+=e)this.length+=e,this.compress(t,n,!1);T(t)}}return this}digestInto(t){if(b(this),$(t,this),3&t.byteOffset)throw new RangeError('"output" expected 4-byte aligned byteOffset, got '+t.byteOffset);const{pos:e,buffer32:n}=this;this.finished=!0,this.buffer.fill(0,e),T(n),this.compress(n,0,!0),T(n);const r=this.get(),i=t===this.buffer?n:k(t),o=Math.floor(this.outputLen/4);for(let l=0;l<o;l++)i[l]=S(r[l]);const s=this.outputLen%4;if(!s)return;const a=4*o,c=r[o];for(let l=0;l<s;l++)t[a+l]=c>>>8*l}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){const{buffer:e,length:n,finished:r,destroyed:i,outputLen:o,pos:s}=this;return t||(t=new this.constructor({dkLen:o})),t.set(...this.get()),t.buffer.set(e),t.destroyed=i,t.finished=r,t.length=n,t.pos=s,t.outputLen=o,t}clone(){return this._cloneInto()}}function N(t,e,n,r,i,o,s,a,c,l,u,d,h,f,m,p,w,g,y,_){let v=0;for(let b=0;b<r;b++)({a:i,b:c,c:h,d:w}=j(i,c,h,w,n[e+t[v++]])),({a:i,b:c,c:h,d:w}=X(i,c,h,w,n[e+t[v++]])),({a:o,b:l,c:f,d:g}=j(o,l,f,g,n[e+t[v++]])),({a:o,b:l,c:f,d:g}=X(o,l,f,g,n[e+t[v++]])),({a:s,b:u,c:m,d:y}=j(s,u,m,y,n[e+t[v++]])),({a:s,b:u,c:m,d:y}=X(s,u,m,y,n[e+t[v++]])),({a:a,b:d,c:p,d:_}=j(a,d,p,_,n[e+t[v++]])),({a:a,b:d,c:p,d:_}=X(a,d,p,_,n[e+t[v++]])),({a:i,b:l,c:m,d:_}=j(i,l,m,_,n[e+t[v++]])),({a:i,b:l,c:m,d:_}=X(i,l,m,_,n[e+t[v++]])),({a:o,b:u,c:p,d:w}=j(o,u,p,w,n[e+t[v++]])),({a:o,b:u,c:p,d:w}=X(o,u,p,w,n[e+t[v++]])),({a:s,b:d,c:h,d:g}=j(s,d,h,g,n[e+t[v++]])),({a:s,b:d,c:h,d:g}=X(s,d,h,g,n[e+t[v++]])),({a:a,b:c,c:f,d:y}=j(a,c,f,y,n[e+t[v++]])),({a:a,b:c,c:f,d:y}=X(a,c,f,y,n[e+t[v++]]));return{v0:i,v1:o,v2:s,v3:a,v4:c,v5:l,v6:u,v7:d,v8:h,v9:f,v10:m,v11:p,v12:w,v13:g,v14:y,v15:_}}const U=1,C=2,F=4,H=8,B=16,z=32,q=64,J=D.slice(),W=(()=>{const t=Array.from({length:16},((t,e)=>e)),e=t=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((e=>t[e])),n=[];for(let r=0,i=t;r<7;r++,i=e(i))n.push(...i);return Uint8Array.from(n)})();class V extends M{constructor(t={},n=0){super(64,void 0===(t=P({},t)).dkLen?32:t.dkLen),e(this,"canXOF",!0),e(this,"chunkPos",0),e(this,"chunksDone",0),e(this,"flags",0),e(this,"IV"),e(this,"state"),e(this,"stack",[]),e(this,"posOut",0),e(this,"bufferOut32",new Uint32Array(16)),e(this,"bufferOut"),e(this,"chunkOut",0),e(this,"enableXOF",!0);const{key:r,context:i}=t,o=void 0!==i;if(void 0!==r){if(o)throw new Error('cannot use both "key" and "context"');_(r,32,"key");const t=(s=r,Uint8Array.from(_(s)));this.IV=k(t),T(this.IV),this.flags=n|B}else if(o){_(i,void 0,"context");const t=i,e=new V({dkLen:32},z).update(t).digest();this.IV=k(e),T(this.IV),this.flags=n|q}else this.IV=J,this.flags=n;var s,a;this.state=this.IV.slice(),this.bufferOut=(a=this.bufferOut32,new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}get(){return[]}set(){}b2Compress(t,e,n,r=0){const{state:i,pos:o}=this,s=p(t),a=m(t),{v0:c,v1:l,v2:u,v3:d,v4:h,v5:f,v6:w,v7:g,v8:y,v9:_,v10:v,v11:b,v12:$,v13:k,v14:x,v15:E}=N(W,r,n,7,i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],J[0],J[1],J[2],J[3],s,a,o,e);i[0]=c^y,i[1]=l^_,i[2]=u^v,i[3]=d^b,i[4]=h^$,i[5]=f^k,i[6]=w^x,i[7]=g^E}compress(t,e=0,n=!1){let r=this.flags;if(this.chunkPos||(r|=U),(15===this.chunkPos||n)&&(r|=C),n||(this.pos=this.blockLen),this.b2Compress(this.chunksDone,r,t,e),this.chunkPos+=1,16===this.chunkPos||n){let t=this.state;this.state=this.IV.slice();for(let e,r=this.chunksDone+1;(n||!(1&r))&&(e=this.stack.pop());r=Math.floor(r/2))this.buffer32.set(e,0),this.buffer32.set(t,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|F,this.buffer32,0),t=this.state,this.state=this.IV.slice();this.chunksDone++,this.chunkPos=0,this.stack.push(t)}this.pos=0}_cloneInto(t){const e=!!t&&t.finished&&!t.destroyed;t=super._cloneInto(t);const{IV:n,flags:r,state:i,chunkPos:o,posOut:s,chunkOut:a,stack:c,chunksDone:l}=this;return t.state.set(i),t.stack=c.map((t=>Uint32Array.from(t))),n===J?(t.IV!==J&&x(t.IV),t.IV=J):t.IV===J?t.IV=n.slice():t.IV.set(n),t.flags=r,t.chunkPos=o,t.chunksDone=l,t.posOut=s,t.chunkOut=a,t.enableXOF=this.enableXOF,this.finished?t.bufferOut32.set(this.bufferOut32):e&&x(t.bufferOut32),t}destroy(){this.destroyed=!0,x(this.state,this.buffer32,this.bufferOut32),this.IV!==J&&x(this.IV),x(...this.stack)}b2CompressOut(){const{state:t,pos:e,flags:n,buffer32:r,bufferOut32:i}=this,o=this.chunkOut++,s=p(o),a=m(o);T(r);const{v0:c,v1:l,v2:u,v3:d,v4:h,v5:f,v6:w,v7:g,v8:y,v9:_,v10:v,v11:b,v12:$,v13:k,v14:x,v15:E}=N(W,0,r,7,t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],J[0],J[1],J[2],J[3],s,a,e,n);i[0]=c^y,i[1]=l^_,i[2]=u^v,i[3]=d^b,i[4]=h^$,i[5]=f^k,i[6]=w^x,i[7]=g^E,i[8]=t[0]^y,i[9]=t[1]^_,i[10]=t[2]^v,i[11]=t[3]^b,i[12]=t[4]^$,i[13]=t[5]^k,i[14]=t[6]^x,i[15]=t[7]^E,T(r),T(i),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,this.buffer.fill(0,this.pos);let t=this.flags|H;this.stack.length?(t|=F,T(this.buffer32),this.compress(this.buffer32,0,!0),T(this.buffer32),this.chunksDone=0,this.pos=this.blockLen):t|=(this.chunkPos?0:U)|C,this.flags=t,this.b2CompressOut()}writeInto(t){b(this,!1),_(t),this.finish();const{blockLen:e,bufferOut:n}=this;for(let r=0,i=t.length;r<i;){this.posOut>=e&&this.b2CompressOut();const o=Math.min(e-this.posOut,i-r);t.set(n.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("no XOF after digest()");return this.writeInto(t)}xof(t){return y(t),this.xofInto(new Uint8Array(t))}digestInto(t){if($(t,this),this.finished)throw new Error("digest() was already called");this.enableXOF=!1,this.writeInto(t.length===this.outputLen?t:t.subarray(0,this.outputLen)),this.destroy()}digest(){const t=new Uint8Array(this.outputLen);return this.digestInto(t),t}}const G=R(((t={})=>new V(t))),K="AGENT_TOOL_HOST_ID";function Y(t){return function(t){if(_(t),A)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=L[t[n]];return e}(G((new TextEncoder).encode(t)))}async function Z(t){try{return await o().readTextFile(t)}catch{return null}}function Q(t){var e;const n=null==(e=t.agent_tool_host_id)?void 0:e.trim();if(n)return`host:${n}:`;return`host:${(t.etc_hostname??t.hostname_env??"unknown").trim()}:${(t.machine_id??"").trim()}`}async function tt(){const t=o().env.get(K)??null;return(null==t?void 0:t.trim())?Q({agent_tool_host_id:t,etc_hostname:null,hostname_env:null,machine_id:null}):Q({agent_tool_host_id:t,etc_hostname:await Z("/etc/hostname"),hostname_env:o().env.get("HOSTNAME")??null,machine_id:await Z("/etc/machine-id")})}function et(t,e){return{host:t,uid:e}}function nt(t){return n.canonicalJson(t)}function rt(t,e,n){return t??it(e,n)}function it(t,e){return`${t}:${Y(nt(e)).slice(0,24)}`}function ot(t,e){return l(t,`${Y(e).slice(0,24)}.lock`)}const st="read_file",at="write_file",ct="edit_file",lt="shell",ut=[st,at,ct,lt],dt=65536,ht=2048,ft="native",mt=200;class pt extends Error{constructor(t,e,n=!1){super("invalid_args"===t?`invalid args: ${e}`:"exec_failed"===t?`execution failed: ${e}`:"timeout"===t?"timeout":"transport"===t?`runtime transport: ${e}`:`cancelled: ${e}`),this.kind=t,this.detail=e,this.effectUnknown=n,this.name="NativeToolError"}}const wt=t=>new pt("invalid_args",t),gt=t=>new pt("exec_failed",t);function yt(t){const e=[];let n="",r=!1,i=!1;const o=[...t];for(let s=0;s<o.length;s++){const t=o[s];"'"!==t||i?'"'!==t||r?"\\"!==t||r?!/\s/.test(t)||r||i?n+=t:n&&(e.push(n),n=""):s+1<o.length&&(n+=o[++s]):i=!i:r=!r}if(!r&&!i)return n&&e.push(n),e}function _t(t){var e;const n=void 0!==t.cmd_name?(null==(e=t.cmd_args)?void 0:e.trim())?`${t.cmd_name} ${t.cmd_args.trim()}`:t.cmd_name:void 0;return`${(void 0!==n?function(t,e){const n=[...t];return n.length<=e?t:`${n.slice(0,e).join("")}...[TRUNCATED]`}(n.trim(),96):"")||"action"} => ${"pending"===t.status?void 0!==t.pending_reason?`pending (${t.pending_reason})`:"pending":t.status}`}function vt(t,e,n,r){const i={agent_tool_protocol:"1",tool:t,status:"success",summary:r,detail:e},o=yt(n),s=o&&o.length?o:n.split(/\s+/).filter(Boolean);return s.length&&(i.cmd_name=s[0],s.length>1&&(i.cmd_args=s.slice(1).join(" "))),i.title=_t(i),i}function bt(t,e){return"/"===e?t.startsWith("/"):t===e||t.startsWith(`${e}/`)}function $t(t,e){if(0!==e.length&&!e.some((e=>bt(t,e))))throw wt(`path not allowed by policy: ${t}`)}async function kt(t){let e=t.replace(/\/+$/,"")||"/";const n=[];for(;;)try{const t=await o().realPath(e);return r.normalizePath(l(t,...n.slice().reverse()))}catch(i){if(!s(i))throw gt(c(i));try{throw await o().lstat(e),wt(`dangling symlink: ${e}`)}catch(a){if(a instanceof pt)throw a}const r=e.slice(e.lastIndexOf("/")+1);if(!r||".."===r)throw wt(`cannot resolve ${t}`);"."!==r&&n.push(r);const l=u(e);if(l===e||"/"===e)throw wt("path has no existing ancestor");e=l}}async function xt(t,e,n){if(!e.trim())throw wt("path cannot be empty");const i=e.startsWith("/")?e:l(t,e);$t(r.normalizePath(i),n);const o=await kt(i);return $t(o,await Promise.all(n.map(kt))),o}function Et(t){let e="";for(const n of(new TextEncoder).encode(t)){const t=String.fromCharCode(n);e+=/[A-Za-z0-9\-._~!$&'()*+,;=:@]/.test(t)?t:`%${n.toString(16).toUpperCase().padStart(2,"0")}`}return e}function Ot(t,e){if(!t)return;const n=r.normalizePath(t);if(!bt(e,n))return;return`cyfs://${["",...e.slice(n.length).split("/").filter((t=>t&&"."!==t))].map(Et).join("/")||"/"}`}function It(t){return null===t?"null":"boolean"==typeof t?`boolean \`${t}\``:"number"==typeof t?Number.isInteger(t)?`integer \`${t}\``:`floating point \`${t}\``:"string"==typeof t?`string ${JSON.stringify(t)}`:Array.isArray(t)?"sequence":"map"}function St(t,e){return wt(`invalid args for \`${t}\`: ${e}`)}function Tt(t,e,n){const r=e[n];if(void 0===r)throw St(t,`missing field \`${n}\``);if("string"!=typeof r)throw St(t,`invalid type: ${It(r)}, expected a string`);return r}function At(t,e,n){const r=e[n];if(null!=r){if("string"!=typeof r)throw St(t,`invalid type: ${It(r)}, expected a string`);return r}}const Lt=new TextEncoder;function Pt(t){return Lt.encode(t).length}function Rt(t){return new TextDecoder("utf-8",{ignoreBOM:!0}).decode(t)}function Dt(t){return t?t.match(/[^\n]*\n|[^\n]+$/g)??[]:[]}function jt(t){if(!t)return[];const e=t.split("\n");return""===e[e.length-1]&&e.pop(),e.map((t=>t.endsWith("\r")?t.slice(0,-1):t))}function Xt(t){const e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r/g,"\\r").replace(/\n/g,"\\n"),n=t?Math.max(jt(t).length,1):0,r=[...e];return r.length<=64?e:`${r.slice(0,32).join("")}...(total ${n} lines)...${r.slice(-32).join("")}`}function Mt(t,e){const n=t.trim();if("$"===n)return"end";if(n.startsWith("+")||!/^-?\d+$/.test(n))throw wt(`invalid range text \`${e}\``);const r=Number(n);if(0===r)throw wt("range must be 1-based, zero is invalid");return r}function Nt(t,e){const n=t.trim();if(!n.startsWith("+"))throw wt(`invalid range text \`${e}\``);const r=n.slice(1).trim();if(!/^\d+$/.test(r))throw wt(`invalid range text \`${e}\``);const i=Number(r);if(0===i)throw wt("range count must be positive integer");return i}function Ut(t,e){if("string"==typeof t)return Mt(t,e);if("number"==typeof t&&Number.isInteger(t)){if(0===t)throw wt(`${e} must be non-zero integer`);return t}throw wt(`${e} must be integer or \`$\``)}function Ct(t){if(null!=t){if(n.isObject(t)){const e=void 0!==t.start?Ut(t.start,"range.start"):void 0,n=void 0!==t.end?Ut(t.end,"range.end"):void 0,r=void 0!==t.count?function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<=0)throw wt(`${e} must be positive integer`);return t}(t.count,"range.count"):void 0;if(void 0!==r&&void 0!==n)throw wt("range cannot set both `end` and `count`");if(void 0!==r&&void 0===e)throw wt("range.count requires range.start");if(void 0===e&&void 0===n&&void 0===r)throw wt("range object must contain at least one of start/end/count");return{start:e,end:n,count:r,defaultEnd:"tail_if_start_negative"}}if(Array.isArray(t)){if(0===t.length||t.length>2)throw wt("range array must be [start] or [start,end]");return{start:Ut(t[0],"range[0]"),end:2===t.length?Ut(t[1],"range[1]"):void 0,defaultEnd:"same_as_start"}}if("number"==typeof t&&Number.isInteger(t))return{start:Ut(t,"range"),defaultEnd:"same_as_start"};if("string"==typeof t)return function(t){const e=t.trim();if(!e||"-"===e)return;if(e.includes(",")||e.includes(":")){if(e.includes(",")&&e.includes(":"))throw wt(`invalid range text \`${t}\``);const n=e.split(e.includes(",")?",":":");if(2!==n.length)throw wt(`invalid range text \`${t}\``);const r=n[0].trim()?Mt(n[0].trim(),t):void 0,i=n[1].trim();if(i.startsWith("+")){if(void 0===r)throw wt(`range \`${t}\` with \`+count\` requires start`);return{start:r,count:Nt(i,t),defaultEnd:"same_as_start"}}return{start:r,end:i?Mt(i,t):void 0,defaultEnd:"end"}}const n=e.indexOf("-");if(n>=0){const r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(r&&i&&/^\d+$/.test(r)&&/^\d+$/.test(i))return{start:Mt(r,t),end:Mt(i,t),defaultEnd:"same_as_start"}}return{start:Mt(e,t),defaultEnd:"same_as_start"}}(t);throw wt("range must be string/number/array/object")}}function Ft(t,e){return"end"===t?e:t>0?t:e+t+1}const Ht={name:st,description:'Read a text file. range selects 1-based lines ("120-200", "120:$", "120:+20", "-50:$" for the last 50); first_chunk starts the read at the first occurrence of that text. Paths are relative to the working directory; paths outside it only where the run\'s filesystem policy allows.',args_schema:{properties:{first_chunk:{description:"Start the read at the first occurrence of this text (range then counts from there).",type:"string"},path:{description:"File to read, relative to the working directory.",type:"string"},range:{description:'1-based line range: "120-200", "120:$" (to the end), "120:+20" (20 lines from 120); negative numbers count from the end ("-50:$").'}},required:["path"],type:"object"}},Bt={name:at,description:'Write a text file: mode "write" (default) creates or overwrites it, "append" adds to its end, "new" creates it and fails if it exists. Parent directories are created. Paths are relative to the working directory; paths outside it only where the run\'s filesystem policy allows.',args_schema:{properties:{content:{description:"The text to write.",type:"string"},mode:{description:"`write` (default): create or overwrite; `append`: add to the end; `new`: create, fail if the file exists.",type:"string"},path:{description:"File to write, relative to the working directory.",type:"string"}},required:["content","path"],type:"object"}},zt={name:ct,description:"Replace the one exact occurrence of old_string with new_string in a text file. Fails when old_string is absent or occurs more than once: include enough surrounding text to make it unique. Paths are relative to the working directory; paths outside it only where the run's filesystem policy allows.",args_schema:{properties:{new_string:{description:"The replacement text.",type:"string"},old_string:{description:"The exact text to replace; it must occur exactly once.",type:"string"},path:{description:"File to edit, relative to the working directory.",type:"string"}},required:["new_string","old_string","path"],type:"object"}};async function qt(t){try{return Rt(await o().readFile(t))}catch(e){throw gt(`read file failed: ${c(e)}`)}}async function Jt(t,e){try{await o().mkdir(u(t),{recursive:!0})}catch(n){throw gt(c(n))}try{await o().writeFile(t,Lt.encode(e))}catch(n){throw gt(`write file failed: ${c(n)}`)}}function Wt(t){return{spec:Ht,idempotent:!0,cancellable:!1,async call(e){const r=Tt(st,e,"path"),i=At(st,e,"first_chunk"),o=null===e.range?void 0:e.range,s=r.trim();if(!s)throw wt("missing required arg `path`");const a=await xt(t.root,s,t.allowedRead),c=await qt(a);let l,u=!0,d=1;if(void 0!==i){const t=c.indexOf(i);t>=0?(l=c.slice(t),d=(c.slice(0,t).match(/\n/g)??[]).length+1):(l="",u=!1)}else l=c;const h=Dt(l),f=h.length,m=Ct(o);let p,w,g="";m?([p,w]=function(t,e){const n=t.start??1,r=Ft(n,e);let i;return i=void 0!==t.count?r+t.count-1:void 0!==t.end?Ft(t.end,e):"same_as_start"===t.defaultEnd?r:"end"===t.defaultEnd||"number"==typeof n&&n<0?e:r,[Math.min(Math.max(r,1),e+1),Math.min(Math.max(i,0),e)]}(m,f),g=`${p}-${w}`):0===f?(p=1,w=0):(p=1,w=f);const y=Math.min(Math.max(p-1,0),f),_=Math.min(w,f),v=y<_?h.slice(y,_):[],b=v.join(""),$=v.length,k=0===$?null:d+y,x=null===k?null:k+Math.max($-1,0);let E="";null!==k&&(E=v.slice(0,mt).map(((t,e)=>{return`${k+e}: ${n=t,n.replace(/[\r\n]+$/,"")}`;var n})).join("\n"),v.length>mt&&(E+=(E?"\n":"")+"... truncated to 200 lines"));const O=Pt(b),I=function(t,e,r){let i=`${st} ${t}`;if(void 0!==e&&(i+=` first_chunk="${Xt(e)}"`),null!=r){const t="string"==typeof r?r:n.canonicalJson(r);t.trim()&&(i+=` range=${t}`)}return i}(s,i,o);let S;if(u){const t=`succeeded, read ${O} bytes across ${null!==k&&null!==x?k===x?`1 line at ${k}`:`${$} lines at ${k}-${x}`:"0 lines"}`;S=E?`${t}\n\`\`\`content\n${E}\n\`\`\``:t}else S="succeeded, first_chunk was not found, read 0 bytes across 0 lines";const T={},A=Ot(t.dfsRoot,a);void 0!==A&&(T.cyfs_url=A),Object.assign(T,{content:b,matched:u,line_range:g,bytes:O,line_count:$,start_line:k,end_line:x,preview_truncated:$>mt});const L=vt(st,T,I,S);return L.title=`${I} => ${u?"success":"anchor not found"}`,function(t,e,r){var i;if("success"!==t.status)return t;const o=(null==(i=t.output)?void 0:i.trim())?t.output:t.summary.trim()?t.summary:n.canonicalJson(t.detail);return t.dedup={key:`read:${e}#${r}:${Y(o).slice(0,16)}`,hint:`\`${e}\` is unchanged since you read it earlier in this run; use that content.`},t}(L,s,n.canonicalJson(Object.fromEntries(Object.entries(e).filter((([t])=>"path"!==t)))))}}}function Vt(t){const e=(t??"write").trim().toLowerCase();if("new"===e||"create"===e)return"new";if("append"===e)return"append";if(""===e||"write"===e||"overwrite"===e)return"write";throw wt(`invalid write mode \`${e}\`, expected new/append/write`)}function Gt(t){return{spec:Bt,idempotent:!1,cancellable:!1,async call(e){const n=Tt(at,e,"path"),r=Tt(at,e,"content"),i=At(at,e,"mode");let a;try{a=Vt(i)}catch{a="write"}const l=`${at} ${n} mode=${a}`,u=n.trim();if(!u)throw wt("missing required arg `path`");const d=Vt(i),h=await xt(t.root,u,t.allowedWrite),f=await async function(t){try{return await o().stat(t),!0}catch(e){if(s(e))return!1;throw gt(c(e))}}(h);if("new"===d&&f)throw wt(`write mode \`new\` requires target file not exist: ${u}`);const m=f?await qt(h):"",p="append"===d?"append":"new"===d?"new":f?"write":"create",w="append"===d?`${m}${r}`:r;await Jt(h,w);const g=Dt(r).length,y={},_=Ot(t.dfsRoot,h);void 0!==_&&(y.cyfs_url=_);const v=Pt(w);Object.assign(y,{created:!f,changed:m!==w,bytes_written:v,line_count:g});const b=`${"append"===p?"appended":"new"===p||"create"===p?"created":"wrote"} ${u}, wrote ${Pt(r)} bytes across ${1===g?"1 line":`${g} lines`}`,$=vt(at,y,l,b),k="append"===p?"append":"new"===p||"create"===p?"new":"write";return $.title=`${at} ${u} mode=${k} => success (${v} bytes)`,$}}}function Kt(t){return{spec:zt,idempotent:!1,cancellable:!1,async call(e){const n=Tt(ct,e,"path"),r=Tt(ct,e,"old_string"),i=Tt(ct,e,"new_string"),o=`${ct} ${n} old_string="${Xt(r)}"`,s=n.trim();if(!s)throw wt("missing required arg `path`");if(!r)throw wt("missing required arg `old_string`");if(r===i)throw wt("`new_string` must be different from `old_string`");const a=await xt(t.root,s,t.allowedWrite),c=await qt(a),l=[];for(let t=c.indexOf(r);t>=0;t=c.indexOf(r,t+r.length))l.push(t);if(0===l.length)throw wt("`old_string` was not found in the file");if(l.length>1)throw wt(`\`old_string\` must match exactly once, found ${l.length} matches`);const u=l[0],d=c.slice(0,u)+i+c.slice(u+r.length),h=c!==d;h&&await Jt(a,d);const f=function(t,e,n){const r=jt(e),i=jt(n),o=[];for(let s=0;s<Math.max(r.length,i.length);s++){const t=r[s],e=i[s];void 0!==t&&void 0!==e?t===e?o.push(` ${t}`):o.push(`-${t}`,`+${e}`):void 0!==t?o.push(`-${t}`):void 0!==e&&o.push(`+${e}`)}return[`--- a/${t}`,`+++ b/${t}`,`@@ -1,${r.length} +1,${i.length} @@`,...o].join("\n")}(s,c,d),m=(c.slice(0,u).match(/\n/g)??[]).length+1,p={},w=Ot(t.dfsRoot,a);void 0!==w&&(p.cyfs_url=w),Object.assign(p,{matched:!0,changed:h,mode:"replace",line:m,diff:f,diff_truncated:!1});const g=h?f.trim()?`edited ${s} with replace at line ${m}\n\`\`\`diff\n${f}\n\`\`\``:`edited ${s} with replace at line ${m}`:`edit ${s} made no change`,y=vt(ct,p,o,g);return y.title=`${ct} ${s} => ${h?`success (line ${m})`:"no change"}`,y}}}const Yt='if [ "$#" -ge 2 ]; then export PATH="$2"; fi\nprintf \'%s\\n\' "$0" > "$1/command"\n"$BASH" -c "$0" </dev/null >"$1/stdout" 2>"$1/stderr"\n__llm_ec=$?\nprintf \'%s\\n\' "$__llm_ec" > "$1/exit.tmp" && command -p mv -f "$1/exit.tmp" "$1/exit"\nexit $__llm_ec',Zt=["/usr/local/sbin","/usr/local/bin","/usr/sbin","/usr/bin","/sbin","/bin"];function Qt(t){const e=[...t].map((t=>/[A-Za-z0-9\-_.]/.test(t)?t:"_")).join("");return!e||e.startsWith(".")?`c_${e}`:e}function te(t,e){if(t&&e)return l(t,"exec",Qt(e))}function ee(t){const e=Math.floor(t/1e3);return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${String(e%60).padStart(2,"0")}s`:`${Math.floor(e/3600)}h${String(Math.floor(e%3600/60)).padStart(2,"0")}m`}async function ne(t){try{return await o().readFile(t)}catch{return}}async function re(t,e){const n=await ne(t);return n?function(t,e){const n=Math.floor(e/4),r=e-n,i=t.subarray(0,Math.min(n,t.length)),o=t.subarray(i.length),s=o.subarray(Math.max(0,o.length-r));return t.length>i.length+s.length?[`${Rt(i)}\n…[${t.length-i.length-s.length} bytes omitted]…\n${Rt(s)}`,!0]:[Rt(i)+Rt(s),!1]}(n,Math.max(e,16)):["",!1]}async function ie(t,e){const n=await ne(t);return n?Rt(n.subarray(Math.max(0,n.length-e))):""}async function oe(t){try{const e=(await o().readTextFile(l(t,"exit"))).trim();return/^[+-]?\d+$/.test(e)?Number(e):void 0}catch{return}}async function se(t,e,n,r,i,o){const[s,a]=await re(l(t,"stdout"),i),[c,u]=await re(l(t,"stderr"),i);let d=s;return c&&(d&&!d.endsWith("\n")&&(d+="\n"),d+=c),{exit_code:e,stdout:s,stderr:c,output:d,output_truncated:a||u,timed_out:n,duration_ms:Math.floor(r),cwd:o}}const ae={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15};const ce=["tool","cmd_name","task_id","pending_reason","estimated_wait","title","summary","cmd_args","partial_output","output"];function le(t){const e=t.maxTimeoutMs,n=`Run a command in this run's runtime (native) with bash syntax. It starts in the working directory unless cwd is given; it is not sandboxed and runs with the current user's permissions. The command is a child process of this executor: an interrupt or a timeout ends its process group; processes it leaves behind after returning are not managed. Waits for the command to finish. Default timeout ${Math.floor(t.timeoutMs/1e3)}s${0===e?", no upper limit":`, max ${Math.floor(e/1e3)}s`}; on timeout the command is stopped and the output so far is returned. Start a long-lived service with nohup / setsid and return at once; on Unix, processes started with \`&\` / nohup in the foreground command's process group also end when that command is interrupted or times out. Long output keeps its beginning and end.`,r={description:`Timeout in milliseconds (default ${t.timeoutMs}${0===e?"":`, max ${e}`}). Set it explicitly for long builds, tests or media commands.`,minimum:1,type:"integer"};return 0!==e&&(r.maximum=e),{name:lt,description:n,args_schema:{properties:{command:{description:"bash command to execute",type:"string"},cwd:{description:t.restrictCwd?"Working directory, relative to or within the configured workspace. Defaults to the workspace.":"Working directory, absolute or relative to the default working directory. Defaults to that directory; outside paths are allowed subject to OS permissions.",type:"string"},timeout_ms:r},required:["command"],type:"object"}}}function ue(t,e){if(null!=t){if("number"==typeof t&&Number.isInteger(t)&&t>=0)return t;if("string"==typeof t&&/^\d+$/.test(t.trim()))return Number(t.trim());throw wt(`\`${e}\` must be a non-negative integer`)}}let de=0;function he(t){let e;return{done:new Promise((n=>{e=setTimeout((()=>n("timeout")),Math.min(t,2**31-1))})),stop:()=>clearTimeout(e)}}function fe(t){return{spec:le(t),idempotent:!1,cancellable:!0,async call(e,i){const s="string"==typeof e.command?e.command.trim():"";if(!s)throw wt("`command` is required and must be non-empty");const a="string"==typeof e.cwd?e.cwd:void 0,u=r.normalizePath(t.workspace),h=await xt(u,a??".",t.restrictCwd?[u]:[]);if(!(await d(h)))throw wt(`cwd does not exist: ${h}`);const f=function(t){if(null==t)return[];if(!n.isObject(t))throw wt("`env` must be an object of string=>string");const e=[];for(const[r,i]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw wt(`invalid env key \`${r}\` (must match [A-Za-z_][A-Za-z0-9_]*)`);if("string"==typeof i)e.push([r,i]);else if("number"==typeof i||"boolean"==typeof i)e.push([r,String(i)]);else{if(null!==i)throw wt(`env value for \`${r}\` must be string/number/bool, got ${n.canonicalJson(i)}`);e.push([r,""])}}return e}(e.env),m=ue(e.timeout_ms,"timeout_ms");if(0===m&&0!==t.maxTimeoutMs)throw wt("`timeout_ms` must be a positive integer");const p=(e=>{const n=e??t.timeoutMs;return 0===t.maxTimeoutMs?n:Math.min(Math.max(n,1),t.maxTimeoutMs)})(m);ue(e.wait_ms,"wait_ms");const w=new Map(f);let g=(w.get("PATH")??o().env.get("PATH")??"").trim();for(const t of Zt)y=t,g=(_=g)?_.split(":").includes(y)?_:`${_}:${y}`:y;var y,_;w.set("PATH",g),i.call_id&&w.set("XLLM_CALL_ID",i.call_id),i.run_id&&w.set("XLLM_RUN_ID",i.run_id);const v={...t.env,...Object.fromEntries(w)};v.PATH=[...new Set(g.split(":").filter(Boolean))].join(":");const b=te(i.run_dir,i.call_id),$=void 0===b,k=b??l(o().env.get("TMPDIR")||"/tmp",`llm-shell-${o().pid}-${++de}`);try{await o().mkdir(k,{recursive:!0,mode:448})}catch(R){throw gt(`execution directory: ${c(R)}`)}for(const t of["exit","exit.tmp"])await o().remove(l(k,t)).catch((()=>{}));let x;const E=performance.now();try{x=new(o().Command)("/bin/bash",{args:["-c",Yt,s,k],cwd:h,env:v,stdin:"null",stdout:"null",stderr:"null"}).spawn()}catch(R){throw gt(`spawn shell failed: ${c(R)}`)}const O=async()=>{$&&await o().remove(k,{recursive:!0}).catch((()=>{}))},I=async()=>{try{x.kill("SIGKILL")}catch{}const t=he(5e3);await Promise.race([x.status,t.done]),t.stop();const e=await se(k,124,!0,performance.now()-E,dt,h);return await O(),e},S=he(0===p?31536e6:p),T=await Promise.race([x.status.then((t=>({exited:t}))),S.done.then((()=>({timeout:!0}))),i.call.cancelled().then((t=>({cancel:t})))]);let A;if(S.stop(),"exited"in T)A=await se(k,(P=T.exited,P.signal?128+(ae[P.signal]??0):P.code),!1,performance.now()-E,dt,h),await O();else{if(!("timeout"in T)){const t=(await ie(l(k,"stdout"),ht)).trimEnd(),e=await I();throw new pt("cancelled",`shell (native): \`${s}\` was stopped after ${e.duration_ms}ms because ${L=T.cancel,"finishing"===L?"the run is finishing":"deadline"===L?"the run's total time limit was reached":"the run was interrupted"}. It may have had partial side effects; check before repeating it.${t.trim()?`\n--- output so far (tail) ---\n${t}`:""}`)}A=await I()}var L,P;return function(t,e,r,i){if(!e.timed_out){const r=function(t,e){var r;if(function(t){let e=!1,n=!1,r=!1;for(const i of t)if(r)r=!1;else if("\\"!==i||e)if("'"!==i||n)if('"'!==i||e){if("|;&><\n\r".includes(i)&&!e&&!n)return!0}else n=!n;else e=!e;else r=!0;return!1}(t)||!(null==(r=yt(t))?void 0:r.length))return;const i=e.stdout.trim();if(!i)return;let o;try{o=JSON.parse(i)}catch{return}if(!n.isObject(o)||"1"!==o.agent_tool_protocol)return;const s=o.status??"success";if("success"!==s&&"error"!==s&&"pending"!==s)return;for(const n of ce)if(void 0!==o[n]&&null!==o[n]&&"string"!=typeof o[n])return;if("pending"===s&&"string"!=typeof o.task_id)return;const a={...o,status:s,summary:"string"==typeof o.summary?o.summary:"",detail:void 0===o.detail?{}:o.detail};return void 0===a.return_code&&0!==e.exit_code&&(a.return_code=e.exit_code),a}(t,e);if(r)return r}const o=e.timed_out?`timed out after ${e.duration_ms}ms (timeout_ms=${r}); the command was stopped. Retry with a larger timeout_ms${0===i?"":` (max ${i})`}, or start a long-lived service with nohup / setsid and return at once.`:`exit=${e.exit_code} in ${e.duration_ms}ms`,s={command:t,cwd:e.cwd,exit_code:e.exit_code,stdout:e.stdout,stderr:e.stderr,output:e.output,output_truncated:e.output_truncated,timed_out:e.timed_out,duration_ms:e.duration_ms,engine:ft,runtime:"native"},a=vt(lt,s,`${lt} ${t}`,o);return a.status=0!==e.exit_code||e.timed_out?"error":"success",a.return_code=e.exit_code,a.title=_t(a),function(t,e){return e.trim()?t.output=e:delete t.output,t}(a,e.output)}(s,A,p,t.maxTimeoutMs)}}}const me="native",pe='set -e\ncommand -v bash >/dev/null\nmachine_id="$(cat /etc/machine-id 2>/dev/null || true)"\n[ -n "$machine_id" ] || machine_id="$(hostname)"\nprintf \'%s\\0\' "$machine_id" "$(hostname)" "$(id -u)" "$(uname -s | tr \'[:upper:]\' \'[:lower:]\')" "$(uname -m)" "$(command -v bash)" "$(pwd -P)" "${PATH}" "$(date +%Y-%m-%dT%H:%M:%S%z)" "$(date +%Z%z)"\nfor tool in bash realpath base64; do if command -v "$tool" >/dev/null; then printf \'%s\\0\' "$tool"; fi; done\n';function we(t){let e=(new TextDecoder).decode(t);e.endsWith("\0")&&(e=e.slice(0,-1));const r=e.split("\0");if(r.length<10||r.slice(0,10).some((t=>""===t)))throw n.XllmError.capability("execution environment probe returned incomplete data");return{machine:r[0],hostname:r[1],uid:r[2],os:r[3],arch:r[4],shell:r[5],cwd:r[6],path:r[7],current_time:r[8],timezone:r[9],tools:r.slice(10,42)}}async function ge(t,e){if("windows"===o().build.os)throw n.XllmError.capability("the Deno host's native runtime needs bash (Linux / macOS); Windows PowerShell runtimes are Rust-only");let r;try{r=await new(o().Command)("/bin/bash",{args:["-c",pe],cwd:t,env:e,stdin:"null",stdout:"piped",stderr:"piped",signal:AbortSignal.timeout(1e4)}).output()}catch(i){throw n.XllmError.capability(c(i))}if(!r.success)throw n.XllmError.capability(`native capability probe failed: ${(new TextDecoder).decode(r.stderr)}`);return we(r.stdout)}function ye(t){return n.XllmError.config(".llm_context","runtime",t)}function _e(t){for(const[e,n]of Object.entries(t))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||n.includes("\0"))throw ye(`invalid env key or value \`${e}\``)}const ve="intent";class be{constructor(t,e,n){this.tools=t,this.workdir=e,this.advertised=n,this.binding={run_id:""},this.ledger=new r.MemoryHintLedger,this.written=[]}bindRun(t){this.binding={...t}}setRecovering(t,e){this.recovering={callId:t,reason:e}}artifacts(){return[...this.written]}has(t){return this.tools.has(t)}hintLedger(){return this.ledger}clearDedup(){this.ledger.clear(r.HINT_NS_DEDUP)}taskResolver(){}listToolSpecs(){return(this.advertised?[...this.advertised.values()]:[...this.tools.values()].map((t=>t.spec))).sort(((t,e)=>t.name<e.name?-1:t.name>e.name?1:0)).map((t=>ut.includes(t.name)?function(t){const e=n.cloneJson(t);let r=e.args_schema;return("object"!=typeof r||null===r||Array.isArray(r))&&(r=e.args_schema={type:"object"}),("object"!=typeof r.properties||null===r.properties||Array.isArray(r.properties))&&(r.properties={}),r.properties[ve]={type:"string",description:"Optional: why you make this call now and what you expect it to give you, in one short sentence. Shown as the progress of your work."},Array.isArray(r.required)&&(r.required=r.required.filter((t=>t!==ve))),e}(t):n.cloneJson(t)))}names(){return[...this.tools.keys()].sort().join(", ")}async callTool(t,e){var n,i;const o=t.call_id,s=this.tools.get(t.name);if(!s)return{kind:"error",call_id:o,message:`tool \`${t.name}\` is not available in this run (available: ${this.names()})`};const a={...t.args??{}};if(ut.includes(t.name)&&delete a[ve],(null==(n=this.recovering)?void 0:n.callId)===o){const t=this.recovering.reason;if(this.recovering=void 0,!s.idempotent)return{kind:"unresolved",call_id:o,reason:t,effect_unknown:!0}}const u=s.call(a,{call_id:o,run_id:this.binding.run_id,run_dir:this.binding.run_dir,call:e}).then((t=>({ok:t})),(t=>({err:t})));let d;if(s.cancellable)d=await u;else{const n=await Promise.race([u,e.cancelledHard().then((t=>({cancelled:t})))]);if("cancelled"in n)return{kind:"cancelled",call_id:o,reason:`tool \`${t.name}\` was abandoned while running (${h=n.cancelled,"deadline"===h?"Deadline":"finishing"===h?"Finishing":"Interrupted"}); it cannot be cancelled, so its effect is unknown`,effect_unknown:!0};d=n}var h;if("err"in d){const t=d.err;if(t instanceof pt){if("transport"===t.kind)throw new r.ToolDispatchException(t.detail,t.effectUnknown);return"cancelled"===t.kind?{kind:"cancelled",call_id:o,reason:t.detail,effect_unknown:t.effectUnknown}:{kind:"error",call_id:o,message:t.message}}return{kind:"error",call_id:o,message:`execution failed: ${c(t)}`}}const f=d.ok;if("success"===f.status&&(t.name===at||t.name===ct)){const t=a.path;if("string"==typeof t){const e=t.startsWith("/")?t:r.normalizePath(l(this.workdir,t));this.written.includes(e)||this.written.push(e)}}if("pending"===f.status){const e=null==(i=f.task_id)?void 0:i.trim();return e?r.taskStateObservation(o,e,{kind:"unknown",reason:"this runtime has no task backend"},{kind:"tools"}):{kind:"error",call_id:o,message:`tool \`${t.name}\` returned a pending result without a task_id`,host:r.toHost(f)}}return r.envelopeObservation(o,f,r.applyHints(f,this.ledger))}}function $e(t,e,n){return{runtime_id:t,kind:me,host:e.host,target:e,workdir:n.cwd,capabilities:{tools:Object.fromEntries(n.tools.map((t=>[t,"available"]))),network:!0,os:n.os}}}function ke(t){return t.wait_ms<t.timeout_ms}async function xe(t={}){const e=n.cloneJson(t.config??{env:{}});e.env=e.env??{},function(t){const e=t.kind??me;if(r.PLANNED_RUNTIME_KINDS.includes(e))throw n.XllmError.capability(`runtime \`${e}\` is planned but not implemented`);if("site"===e)throw n.XllmError.capability("runtime `site` is built by a website (createSiteRuntime); the Deno host runs `native`");if("remote_ssh"===e||"remote_node"===e)throw n.XllmError.capability(`runtime \`${e}\` is not available on the Deno host (only \`native\`)`);if(e!==me)throw ye(`unknown runtime kind \`${e}\``);if(t.remote_ssh&&void 0!==t.kind)throw ye("remote_ssh connection block requires kind: remote_ssh");if(t.remote_node&&void 0!==t.kind)throw ye("remote_node connection block requires kind: remote_node");if(t.remote_ssh||t.remote_node)throw ye("connection block does not match runtime kind");if(_e(t.env??{}),void 0!==t.id&&!t.id.trim())throw ye("id cannot be empty");if(0===t.task_wait_ms)throw ye("task_wait_ms must be positive")}(e);const i=e.workdir??t.workdir??o().cwd();let s;try{s=await o().realPath(i)}catch(_){throw n.XllmError.capability(`runtime cwd ${i}: ${c(_)}`)}if(!(await d(s)))throw n.XllmError.capability("runtime workdir must be a directory");const a=await ge(s,e.env),u=et(await tt(),a.uid),h=rt(e.id,me,u),f=function(t,e,n,r){const i=t.os.toLowerCase(),o=t.shell.split(/[/\\]/).pop()??"";return{id:e,kind:me,os:t.os,arch:t.arch,hostname:t.hostname,shell:t.shell,cwd:t.cwd,tools:t.tools,current_time:t.current_time,timezone:t.timezone,target:n,platform:"darwin"===i||"macos"===i?"macos":i,shell_kind:o.replace(/\.exe$/,"").replace(/\.EXE$/,"").toLowerCase(),baseline:r??""}}(a,h,u,e.baseline),m={...e,kind:me,id:h,workdir:f.cwd},p=$e(h,u,a),w=l(o().env.get("BUCKYOS_ROOT")||"/opt/buckyos","data"),g=(t,e,i,o,s,a)=>{const c=[];for(const l of t){const t=r.describeToolSource(l);if("mcp"===l.kind)throw n.XllmError.capability(`${e}: \`${t}\`: MCP tools are not available on the Deno host`);if("named"===l.kind)throw n.XllmError.capability(`${e}: \`${t}\`: named host tools are not available on the Deno host (only the \`bash\` group)`);if(l.groupname===r.BUILTIN_TOOL_GROUP_BASH_CORE||"executor"===l.groupname)throw n.XllmError.capability(`${e}: \`${t}\` needs a host task CLI / executor that the Deno host does not provide (use \`bash\`)`);if(l.groupname!==r.BUILTIN_TOOL_GROUP_BASH)throw n.XllmError.tools(`unknown builtin tool group \`${l.groupname}\` (available: ${r.BUILTIN_TOOL_GROUP_BASH}, ${r.BUILTIN_TOOL_GROUP_BASH_CORE}, executor)`);if(ke(i))throw n.XllmError.capability(`${e}: \`shell\` would hand commands still running after runtime.task_wait_ms (${i.wait_ms} ms) to a task backend, which the Deno host does not have; set runtime.task_wait_ms to at least tools.shell.timeout_ms (${i.timeout_ms} ms) so \`shell\` waits for its command`);const u="workspace"===o,d={root:f.cwd,allowedRead:u?[f.cwd]:[],allowedWrite:u?[f.cwd]:[],dfsRoot:w},h=[Wt(d),Gt(d),Kt(d),fe({workspace:f.cwd,restrictCwd:u,timeoutMs:i.timeout_ms,maxTimeoutMs:i.max_timeout_ms,env:s})];for(const e of h){if(a.has(e.spec.name))throw n.XllmError.tools(`tool name \`${e.spec.name}\` from ${t} conflicts with an already expanded tool of the same name`);a.set(e.spec.name,e),c.push({name:e.spec.name,description:e.spec.description,args_schema:n.cloneJson(e.spec.args_schema),source:t})}}return c};let y;return{kind:me,probe:a,descriptor:()=>n.cloneJson(p),config:()=>n.cloneJson(m),async info(){const t=await ge(f.cwd,m.env),e=y?[...new Set([...f.tools,...y])].sort().slice(0,32):f.tools;return{...n.cloneJson(f),tools:e,current_time:t.current_time,timezone:t.timezone}},async open(e,i){_e(e.env);const o={...m.env,...e.env};o.PATH=o.PATH??a.path;const s=t.takeover&&t.takeover.run_id===e.run_id?t.takeover.tools:void 0,c=s?{enabled:s.enabled,filesystem_policy:s.filesystem_policy,tools2actions:s.tools2actions,tools:s.tool_sources,actions:s.action_sources,bash_tools:s.bash_tools,shell:{timeout_ms:s.shell.timeout_ms,max_timeout_ms:s.shell.max_timeout_ms}}:i,l=c.enabled??!1,u=c.filesystem_policy??"workspace",d=c.tools2actions??!1,h=r.shellSettings(c.shell,e.task_wait_ms),p=e.loop_model,w={enabled:l,filesystem_policy:u,tools2actions:d,tool_sources:n.cloneJson(c.tools??[]),action_sources:n.cloneJson(c.actions??[]),native:[],actions:[],bash_tools:n.cloneJson(c.bash_tools??[]),shell:h,exec_enabled:!1,sources:{...e.sources}};if("function_call"===p){if(d)throw n.XllmError.capability("`tools2actions: true` requires `loop_model: behavior`; function_call cannot convert tools into actions");if((c.actions??[]).length>0)throw n.XllmError.capability("`actions` are configured but `loop_model` is function_call; use `loop_model: behavior` or remove `actions`")}const _=new Map;if(l){const t=c.tools??[{kind:"group",groupname:r.BUILTIN_TOOL_GROUP_BASH}];w.tool_sources=n.cloneJson(t);const e=g(t,"tools.tools",h,u,o,_),i=g(w.action_sources,"tools.actions",h,u,o,_);"behavior"===p&&d?w.actions=[...e,...i]:(w.native=e,w.actions=i),w.exec_enabled=_.has(lt)&&[...w.native,...w.actions].some((t=>t.name===lt))}let v;if(s){v=new Map;for(const t of[...s.native,...s.actions])_.has(t.name)&&v.set(t.name,{name:t.name,description:t.description,args_schema:n.cloneJson(t.args_schema)})}return y=[...w.native,...w.actions].map((t=>t.name)),{tools:w,manager:new be(_,f.cwd,v)}},async describeInterrupted(t,e){if(e.name!==lt)return r.unresolvedReason(e.name);const n=te(t.run_dir,e.call_id);return void 0===n?Ie(e,void 0,"(no execution directory)"):Ie(e,await Ee(n),n)}}}async function Ee(t){let e;try{const n=(await o().stat(l(t,"command"))).mtime;n&&(e=Math.floor(n.getTime()))}catch{e=void 0}return{exit_code:await oe(t),stdout_tail:await ie(l(t,"stdout"),ht),stderr_tail:await ie(l(t,"stderr"),ht),exists:await d(t),started_at_ms:e}}function Oe(t){let e="";return t.stdout_tail.trim()&&(e+=`\n--- stdout (tail) ---\n${t.stdout_tail.trimEnd()}`),t.stderr_tail.trim()&&(e+=`\n--- stderr (tail) ---\n${t.stderr_tail.trimEnd()}`),e}function Ie(t,e,n){const r=function(t){var e;const n=null==(e=t.args)?void 0:e.command;if("string"!=typeof n)return"";const r=n.split(/\s+/).filter(Boolean).join(" "),i=[...r];return i.length>160?`${i.slice(0,160).join("")}…`:r}(t),i=void 0!==(null==e?void 0:e.started_at_ms)?`started ${ee(Math.max(0,Date.now()-e.started_at_ms))} ago (at ${e.started_at_ms} ms since epoch)`:"start time unknown";return void 0!==(null==e?void 0:e.exit_code)?`shell (native): the previous executor exited while \`${r}\` was running (${i}). The command has since ended with exit code ${e.exit_code} (read from ${n}); its result was never returned, so review it before deciding whether to repeat anything.${Oe(e)}`:`shell (native): the previous executor exited while \`${r}\` was running (${i}). The command may have partly executed; it usually ended together with the executor, but not necessarily (e.g. after kill -9 it may still be running). Background processes it started are unaffected. Check the actual state before repeating it.${e?Oe(e):""}`}const Se="~/.xllm/runs",Te="~/.xllm/locks";function Ae(t,e){return r.resolveConfigPath(t,e,function(){const t=o().env;return t.get("HOME")??t.get("USERPROFILE")}())}function Le(t,e){if("disabled"===(null==t?void 0:t.kind))return;return Ae("path"===(null==t?void 0:t.kind)?t.path:Se,u(e.startsWith("/")?e:l(o().cwd(),e)))}class Pe{constructor(t,e){this.file=t,this.path=e,this.released=!1}static async tryAcquire(t){try{await o().mkdir(u(t),{recursive:!0})}catch(r){throw n.XllmError.storage(`cannot create lock directory ${u(t)}: ${c(r)}`)}let e;try{e=await o().open(t,{read:!0,write:!0,create:!0})}catch(r){throw n.XllmError.storage(`cannot open lock ${t}: ${c(r)}`)}if(!(await e.tryLock(!0)))return e.close(),null;try{await o().writeTextFile(t,`${o().pid}\n`)}catch{}return new Pe(e,t)}async release(){if(!this.released){this.released=!0;try{await this.file.unlock()}finally{this.file.close()}}}}async function Re(t){let e;try{e=await o().open(t,{read:!0,write:!0,create:!0})}catch{return!1}try{return!(await e.tryLock(!0))||(await e.unlock(),!1)}finally{e.close()}}let De=0;function je(t){return String(t).padStart(4,"0")}class Xe{constructor(t){this.persistent=!0,this.dir=Ae(t,o().cwd())}runsDir(){return this.dir}runDir(t){return l(this.dir,t)}async ensureWritable(){try{await o().mkdir(this.dir,{recursive:!0})}catch(e){throw n.XllmError.storage(`runs directory ${this.dir} cannot be created: ${c(e)}`)}const t=l(this.dir,`.probe-${o().pid}`);try{await o().writeFile(t,new Uint8Array)}catch(e){throw n.XllmError.storage(`runs directory ${this.dir} is not writable: ${c(e)}`)}await o().remove(t).catch((()=>{}))}async createRun(){await this.ensureWritable();for(let e=0;e<8;e++){const e=r.generateRunId(),i=this.runDir(e);try{await o().mkdir(i)}catch(t){if(a(t))continue;throw n.XllmError.storage(`cannot create run directory ${i}: ${c(t)}`)}return await o().mkdir(l(i,"snapshots"),{recursive:!0}),e}throw n.XllmError.storage("cannot allocate a unique run id")}async writeRecord(t){const e=this.runDir(t.run_id),r=l(e,"run.json"),i=l(e,`run.json.tmp-${o().pid}-${De++}`);try{await o().mkdir(e,{recursive:!0}),await h(i,(new TextEncoder).encode(JSON.stringify(t,null,2)))}catch(s){throw n.XllmError.storage(`write ${i}: ${c(s)}`)}try{await o().rename(i,r)}catch(s){throw n.XllmError.storage(`commit ${r}: ${c(s)}`)}try{await f(e)}catch(s){throw n.XllmError.storage(`sync ${e}: ${c(s)}`)}}async readRecord(t){const e=l(this.runDir(t),"run.json");let i,a;try{i=await o().readTextFile(e)}catch(d){if(s(d))throw new n.XllmError({kind:"run_not_found",run_id:t,runs_dir:this.dir});throw n.XllmError.storage(`read ${e}: ${c(d)}`)}try{a=JSON.parse(i)}catch(d){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:c(d)})}const u=a;if((null==u?void 0:u.version)!==r.RUN_RECORD_VERSION)throw n.XllmError.notResumable(t,"unsupported run record version");if("string"!=typeof u.run_id||"string"!=typeof u.status||"object"!=typeof u.config||"object"!=typeof u.prompt)throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:"run.json unreadable: missing run_id / status / config / prompt"});return a}async listRecords(){const t=[];let e;try{e=o().readDir(this.dir);for await(const n of e)if(n.isDirectory)try{const e=JSON.parse(await o().readTextFile(l(this.dir,n.name,"run.json")));e&&"string"==typeof e.run_id&&t.push(e)}catch{}}catch(r){if(s(r))return t;throw n.XllmError.storage(`read runs directory ${this.dir}: ${c(r)}`)}return t}async putSnapshot(t,e){const r=l(this.runDir(t),"snapshots");try{await o().mkdir(r,{recursive:!0});const n=await this.listSnapshots(t),i=n.length?n[n.length-1]+1:1,s=l(r,`${je(i)}.json`),a=l(r,`${je(i)}.json.tmp`);return await h(a,(new TextEncoder).encode(JSON.stringify(e))),await o().rename(a,s),await f(r),i}catch(i){if(i instanceof n.XllmError)throw i;throw n.XllmError.storage(`write snapshot of ${t}: ${c(i)}`)}}async getSnapshot(t,e){const r=l(this.runDir(t),"snapshots",`${je(e)}.json`);let i;try{i=await o().readTextFile(r)}catch(s){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${e} missing at ${r}: ${c(s)}`})}try{return JSON.parse(i)}catch(s){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${e} unreadable: ${c(s)}`})}}async listSnapshots(t){const e=l(this.runDir(t),"snapshots"),n=[];try{for await(const t of o().readDir(e)){const e=/^(\d+)\.json$/.exec(t.name);e&&n.push(Number(e[1]))}}catch(r){if(s(r))return[];throw r}return n.sort(((t,e)=>t-e))}lockRun(t){return Pe.tryAcquire(l(this.runDir(t),".lock"))}async isRunLive(t){return!!(await d(this.runDir(t)))&&Re(l(this.runDir(t),".lock"))}async removeRun(t){const e=this.runDir(t);try{await o().remove(e,{recursive:!0})}catch(r){if(!s(r))throw n.XllmError.storage(`remove ${e}: ${c(r)}`)}await f(this.dir).catch((()=>{}))}async importRun(t){const e=t.record.run_id;if(await this.isRunLive(e))throw new n.XllmError({kind:"run_busy",run_id:e});const r=this.runDir(e);await o().mkdir(l(r,"snapshots"),{recursive:!0});for(const[n,i]of t.snapshots){const t=l(r,"snapshots",`${je(n)}.json`),e=`${t}.tmp`;await h(e,(new TextEncoder).encode(JSON.stringify(i))),await o().rename(e,t)}await f(l(r,"snapshots")),await this.writeRecord(t.record)}}function Me(t=Te){const e=Ae(t,o().cwd());return async(t,n)=>{const r=await Pe.tryAcquire(ot(e,t));return r&&await o().writeTextFile(r.path,`${n}\n`).catch((()=>{})),r}}function Ne(t){return d(t)}const Ue="BUCKYOS_APPCLIENT_SESSION_TOKEN";async function Ce(t){if("env"===t.kind){const e=o().env.get(t.name);if(void 0===e)throw n.XllmError.capability(`environment variable \`${t.name}\` is not set`);return e}let e,r;try{e=await o().readTextFile(t.path)}catch(s){throw n.XllmError.capability(`cannot re-read credential source ${t.path}:${t.field}: ${c(s)}`)}try{r=JSON.parse(e)}catch(s){throw n.XllmError.capability(`cannot parse credential source ${t.path} (the Deno host reads JSON configuration): ${c(s)}`)}let i=r;for(const o of t.field.split(".")){if(!n.isObject(i)||!(o in i))throw n.XllmError.capability(`credential field \`${t.field}\` no longer exists in ${t.path}`);i=i[o]}if("string"!=typeof i||!i.trim())throw n.XllmError.capability(`credential field \`${t.field}\` in ${t.path} is empty or not a string`);return i}function Fe(t){return{async infer(){throw n.providerError({refused:{code:r.REFUSED_CREDENTIALS}},t)}}}async function He(t){var e,r,s;if("openai"===(t.kind??"buckyos")){const e=t.api_key?await Ce(t.api_key):o().env.get("OPENAI_API_KEY");if(!(null==e?void 0:e.trim()))throw n.XllmError.capability("openai provider: no API key; set `provider.api_key`, `provider.api_key_env` or the OPENAI_API_KEY environment variable");return new i.OpenAiLlmClient({baseUrl:t.base_url,apiKey:e,headers:t.headers})}if(void 0!==t.on_behalf_of&&null!==t.on_behalf_of)throw n.XllmError.capability("buckyos provider: `on_behalf_of` (a system service paying for a user) is not available on the Deno host");const a=t.session_token?await Ce(t.session_token):null==(e=o().env.get(Ue))?void 0:e.trim();if(!a)return Fe(`buckyos provider: no BuckyOS session on this host (set ${Ue}), sign in and resume`);const l=(null==(r=o().env.get("BUCKYOS_APP_ID"))?void 0:r.trim())||"buckycli",u=new((await async function(){const t=new URL("./node.mjs",self.location).href;return await import(t)}()).BuckyOSSDK)("node");try{await u.initBuckyOS(l,{zoneHost:(null==(s=o().env.get("BUCKYOS_ZONE_HOST"))?void 0:s.trim())??"",appId:l,defaultProtocol:"https://",runtimeType:"AppClient",sessionToken:a,privateKeySearchPaths:[],autoRenew:!1})}catch(d){throw n.XllmError.capability(`buckyos provider: cannot initialize the BuckyOS runtime (check zone/session setup): ${c(d)}`)}return new n.AiccLlmClient(u.getAiccClient())}function Be(t,e,n,r={}){const i={llm:n,runtime:t,store:e,pid:o().pid,lockWorkdir:Me(r.lockDir),workdirExists:Ne};return r.observer&&(i.observer=r.observer),r.tokenizer&&(i.tokenizer=r.tokenizer),i}const ze={infer(){throw n.XllmError.other("the model client is created after the task is prepared")}};function qe(t){const e=t instanceof n.XllmError?t:n.XllmError.capability(t instanceof Error?t.message:String(t)),r=()=>{throw e},i=()=>Promise.reject(e);return{descriptor:r,config:r,info:i,open:i,describeInterrupted:i}}exports.BASH_GROUP_TOOLS=ut,exports.DEFAULT_LOCK_DIR=Te,exports.DEFAULT_RUNS_DIR=Se,exports.EDIT_FILE_SPEC=zt,exports.EXEC_MAX_OUTPUT_BYTES=dt,exports.FileLock=Pe,exports.FileRunStore=Xe,exports.HOST_ID_ENV=K,exports.LOCAL_PROBE=pe,exports.NATIVE_KIND=me,exports.NATIVE_WRAPPER=Yt,exports.NativeToolManager=be,exports.READ_FILE_SPEC=Ht,exports.SESSION_TOKEN_ENV=Ue,exports.WRITE_FILE_SPEC=Bt,exports.blake3Hex=Y,exports.createLlmClient=He,exports.createNativeRuntime=xe,exports.credentialsRefusedClient=Fe,exports.deriveRuntimeId=rt,exports.execDirFor=te,exports.fmtElapsed=ee,exports.interruptedShellText=Ie,exports.isLocked=Re,exports.localProbe=ge,exports.nativeDeps=Be,exports.nativeDescriptor=$e,exports.nativeHostId=tt,exports.nativeHostIdFrom=Q,exports.nativeTarget=et,exports.parseProbe=we,exports.prepareNativeTask=async function(t,e,n,i,o={}){const s=r.mergeConfigLayers([{path:e,file:r.parseLlmContextJson(e,t??null)}]),a=await xe({config:s.runtime,workdir:o.workdir});let c=o.store;if(!c){const t=Le(s.runs_dir,e);c=void 0===t?new r.MemoryRunStore:new Xe(t)}const l=Be(a,c,o.llm??ze,o),u=await r.XllmTask.prepare(t,e,n,i,l);return{task:u,deps:{...l,llm:o.llm??await He(u.config.provider)}}},exports.readExecDir=Ee,exports.resolveHostPath=Ae,exports.resolveSecret=Ce,exports.resumeNativeRun=async function(t,e,i={},o={}){const s=await t.readRecord(e);let a,c=o.llm;if(r.isTerminal(s.status))a=qe(n.XllmError.other("a terminal run is not executed"));else{try{a=await xe({config:s.config.runtime,workdir:s.workdir,takeover:{run_id:s.run_id,tools:s.config.tools}})}catch(l){a=qe(l)}c=c??await He(s.config.provider)}return r.XllmRun.resume(t,e,i,Be(a,t,c??ze,o))},exports.runsDirOf=Le,exports.runtimeIdOf=it,exports.sanitizeCallId=Qt,exports.shellSpec=le,exports.targetText=nt,exports.workdirExists=Ne,exports.workdirLockPath=ot,exports.workdirLocker=Me;
1
+ "use strict";var t=Object.defineProperty,e=(e,n,r)=>(((e,n,r)=>{n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r})(e,"symbol"!=typeof n?n+"":n,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./aicc-ccb36ef7.js"),r=require("./site_manager-c832463b.js"),i=require("./openai-f560d518.js");function o(){const t=globalThis.Deno;if(!t)throw new Error("the xllm Deno host needs the Deno runtime");return t}function s(t){return t instanceof o().errors.NotFound}function a(t){return t instanceof o().errors.AlreadyExists}function c(t){return t instanceof Error?t.message:String(t)}function l(...t){let e="";for(const n of t)n&&(e=n.startsWith("/")||!e?n:e.endsWith("/")?e+n:`${e}/${n}`);return e}function u(t){const e=t.replace(/\/+$/,""),n=e.lastIndexOf("/");return n<0?".":0===n?"/":e.slice(0,n)}async function d(t){try{return(await o().stat(t)).isDirectory}catch{return!1}}async function h(t,e){const n=await o().open(t,{write:!0,create:!0,truncate:!0});try{let t=0;for(;t<e.length;)t+=await n.write(e.subarray(t));await n.sync()}finally{n.close()}}async function f(t){if("windows"===o().build.os)return;const e=await o().open(t,{read:!0});try{await e.sync()}finally{e.close()}}require("./krpc_client-26c2dc8b.js");const m=t=>t/2**32|0,p=t=>t>>>0;function w(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name&&"BYTES_PER_ELEMENT"in t&&1===t.BYTES_PER_ELEMENT}const g=t=>t?`"${t}" `:"";function y(t,e=""){if("number"!=typeof t)throw new TypeError(g(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(g(e)+"expected integer >= 0, got "+t);return t}function _(t,e,n=""){if(w(t)&&(void 0===e||t.length===e))return t;void 0!==e&&y(e,"length");const r=w(t),i=void 0!==e?` of length ${e}`:"",o=r?`length=${t.length}`:"type="+typeof t,s=g(n)+"expected Uint8Array"+i+", got "+o;if(!r)throw new TypeError(s);throw new RangeError(s)}const v=(t,e)=>{((t,e)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError(("object"===e?"":`"${e}" `)+"expected object, got type="+typeof t)})(t,e);const n=Object.getPrototypeOf(t);if(n!==Object.prototype&&null!==n)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function b(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function $(t,e){_(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function k(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function x(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function E(t,e){return t<<32-e|t>>>e}const O=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function I(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const S=O?t=>t:t=>I(t)>>>0;const T=O?t=>t:function(t){for(let e=0;e<t.length;e++)t[e]=I(t[e]);return t},A=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),L=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function P(t,e,n="opts"){v(t,"defaults"),void 0!==e&&v(e,n);return Object.assign(Object.create(null),t,e)}function R(t,e={}){if("function"!=typeof t)throw new TypeError('"hashCons" expected function, got type='+typeof t);e=P({},e,"info");const n=(e,n)=>t(n).update(e).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=e=>t(e),Object.assign(n,e),Object.freeze(n)}const D=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function j(t,e,n,r,i){return r=E(r^(t=t+e+i|0),16),{a:t,b:e=E(e^(n=n+r|0),12),c:n,d:r}}function X(t,e,n,r,i){return r=E(r^(t=t+e+i|0),8),{a:t,b:e=E(e^(n=n+r|0),7),c:n,d:r}}class M{constructor(t,n){e(this,"buffer"),e(this,"buffer32"),e(this,"finished",!1),e(this,"destroyed",!1),e(this,"length",0),e(this,"pos",0),e(this,"blockLen"),e(this,"outputLen"),e(this,"canXOF",!1),y(t),y(n),this.blockLen=t,this.outputLen=n,this.buffer=new Uint8Array(t),this.buffer32=k(this.buffer)}update(t){b(this),_(t);const{blockLen:e,buffer:n,buffer32:r}=this,i=t.length,o=t.byteOffset,s=t.buffer;for(let a=0;a<i;){this.pos===e&&(T(r),this.compress(r,0,!1),T(r),this.pos=0);const c=Math.min(e-this.pos,i-a),l=o+a;if(c!==e||l%4||!(a+c<i))n.set(0===a&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,this.length+=c,a+=c;else{const t=new Uint32Array(s,l,Math.floor((i-a)/4));T(t);for(let n=0;a+e<i;n+=r.length,a+=e)this.length+=e,this.compress(t,n,!1);T(t)}}return this}digestInto(t){if(b(this),$(t,this),3&t.byteOffset)throw new RangeError('"output" expected 4-byte aligned byteOffset, got '+t.byteOffset);const{pos:e,buffer32:n}=this;this.finished=!0,this.buffer.fill(0,e),T(n),this.compress(n,0,!0),T(n);const r=this.get(),i=t===this.buffer?n:k(t),o=Math.floor(this.outputLen/4);for(let l=0;l<o;l++)i[l]=S(r[l]);const s=this.outputLen%4;if(!s)return;const a=4*o,c=r[o];for(let l=0;l<s;l++)t[a+l]=c>>>8*l}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){const{buffer:e,length:n,finished:r,destroyed:i,outputLen:o,pos:s}=this;return t||(t=new this.constructor({dkLen:o})),t.set(...this.get()),t.buffer.set(e),t.destroyed=i,t.finished=r,t.length=n,t.pos=s,t.outputLen=o,t}clone(){return this._cloneInto()}}function N(t,e,n,r,i,o,s,a,c,l,u,d,h,f,m,p,w,g,y,_){let v=0;for(let b=0;b<r;b++)({a:i,b:c,c:h,d:w}=j(i,c,h,w,n[e+t[v++]])),({a:i,b:c,c:h,d:w}=X(i,c,h,w,n[e+t[v++]])),({a:o,b:l,c:f,d:g}=j(o,l,f,g,n[e+t[v++]])),({a:o,b:l,c:f,d:g}=X(o,l,f,g,n[e+t[v++]])),({a:s,b:u,c:m,d:y}=j(s,u,m,y,n[e+t[v++]])),({a:s,b:u,c:m,d:y}=X(s,u,m,y,n[e+t[v++]])),({a:a,b:d,c:p,d:_}=j(a,d,p,_,n[e+t[v++]])),({a:a,b:d,c:p,d:_}=X(a,d,p,_,n[e+t[v++]])),({a:i,b:l,c:m,d:_}=j(i,l,m,_,n[e+t[v++]])),({a:i,b:l,c:m,d:_}=X(i,l,m,_,n[e+t[v++]])),({a:o,b:u,c:p,d:w}=j(o,u,p,w,n[e+t[v++]])),({a:o,b:u,c:p,d:w}=X(o,u,p,w,n[e+t[v++]])),({a:s,b:d,c:h,d:g}=j(s,d,h,g,n[e+t[v++]])),({a:s,b:d,c:h,d:g}=X(s,d,h,g,n[e+t[v++]])),({a:a,b:c,c:f,d:y}=j(a,c,f,y,n[e+t[v++]])),({a:a,b:c,c:f,d:y}=X(a,c,f,y,n[e+t[v++]]));return{v0:i,v1:o,v2:s,v3:a,v4:c,v5:l,v6:u,v7:d,v8:h,v9:f,v10:m,v11:p,v12:w,v13:g,v14:y,v15:_}}const U=1,C=2,F=4,H=8,B=16,z=32,q=64,J=D.slice(),W=(()=>{const t=Array.from({length:16},((t,e)=>e)),e=t=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((e=>t[e])),n=[];for(let r=0,i=t;r<7;r++,i=e(i))n.push(...i);return Uint8Array.from(n)})();class V extends M{constructor(t={},n=0){super(64,void 0===(t=P({},t)).dkLen?32:t.dkLen),e(this,"canXOF",!0),e(this,"chunkPos",0),e(this,"chunksDone",0),e(this,"flags",0),e(this,"IV"),e(this,"state"),e(this,"stack",[]),e(this,"posOut",0),e(this,"bufferOut32",new Uint32Array(16)),e(this,"bufferOut"),e(this,"chunkOut",0),e(this,"enableXOF",!0);const{key:r,context:i}=t,o=void 0!==i;if(void 0!==r){if(o)throw new Error('cannot use both "key" and "context"');_(r,32,"key");const t=(s=r,Uint8Array.from(_(s)));this.IV=k(t),T(this.IV),this.flags=n|B}else if(o){_(i,void 0,"context");const t=i,e=new V({dkLen:32},z).update(t).digest();this.IV=k(e),T(this.IV),this.flags=n|q}else this.IV=J,this.flags=n;var s,a;this.state=this.IV.slice(),this.bufferOut=(a=this.bufferOut32,new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}get(){return[]}set(){}b2Compress(t,e,n,r=0){const{state:i,pos:o}=this,s=p(t),a=m(t),{v0:c,v1:l,v2:u,v3:d,v4:h,v5:f,v6:w,v7:g,v8:y,v9:_,v10:v,v11:b,v12:$,v13:k,v14:x,v15:E}=N(W,r,n,7,i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],J[0],J[1],J[2],J[3],s,a,o,e);i[0]=c^y,i[1]=l^_,i[2]=u^v,i[3]=d^b,i[4]=h^$,i[5]=f^k,i[6]=w^x,i[7]=g^E}compress(t,e=0,n=!1){let r=this.flags;if(this.chunkPos||(r|=U),(15===this.chunkPos||n)&&(r|=C),n||(this.pos=this.blockLen),this.b2Compress(this.chunksDone,r,t,e),this.chunkPos+=1,16===this.chunkPos||n){let t=this.state;this.state=this.IV.slice();for(let e,r=this.chunksDone+1;(n||!(1&r))&&(e=this.stack.pop());r=Math.floor(r/2))this.buffer32.set(e,0),this.buffer32.set(t,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|F,this.buffer32,0),t=this.state,this.state=this.IV.slice();this.chunksDone++,this.chunkPos=0,this.stack.push(t)}this.pos=0}_cloneInto(t){const e=!!t&&t.finished&&!t.destroyed;t=super._cloneInto(t);const{IV:n,flags:r,state:i,chunkPos:o,posOut:s,chunkOut:a,stack:c,chunksDone:l}=this;return t.state.set(i),t.stack=c.map((t=>Uint32Array.from(t))),n===J?(t.IV!==J&&x(t.IV),t.IV=J):t.IV===J?t.IV=n.slice():t.IV.set(n),t.flags=r,t.chunkPos=o,t.chunksDone=l,t.posOut=s,t.chunkOut=a,t.enableXOF=this.enableXOF,this.finished?t.bufferOut32.set(this.bufferOut32):e&&x(t.bufferOut32),t}destroy(){this.destroyed=!0,x(this.state,this.buffer32,this.bufferOut32),this.IV!==J&&x(this.IV),x(...this.stack)}b2CompressOut(){const{state:t,pos:e,flags:n,buffer32:r,bufferOut32:i}=this,o=this.chunkOut++,s=p(o),a=m(o);T(r);const{v0:c,v1:l,v2:u,v3:d,v4:h,v5:f,v6:w,v7:g,v8:y,v9:_,v10:v,v11:b,v12:$,v13:k,v14:x,v15:E}=N(W,0,r,7,t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],J[0],J[1],J[2],J[3],s,a,e,n);i[0]=c^y,i[1]=l^_,i[2]=u^v,i[3]=d^b,i[4]=h^$,i[5]=f^k,i[6]=w^x,i[7]=g^E,i[8]=t[0]^y,i[9]=t[1]^_,i[10]=t[2]^v,i[11]=t[3]^b,i[12]=t[4]^$,i[13]=t[5]^k,i[14]=t[6]^x,i[15]=t[7]^E,T(r),T(i),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,this.buffer.fill(0,this.pos);let t=this.flags|H;this.stack.length?(t|=F,T(this.buffer32),this.compress(this.buffer32,0,!0),T(this.buffer32),this.chunksDone=0,this.pos=this.blockLen):t|=(this.chunkPos?0:U)|C,this.flags=t,this.b2CompressOut()}writeInto(t){b(this,!1),_(t),this.finish();const{blockLen:e,bufferOut:n}=this;for(let r=0,i=t.length;r<i;){this.posOut>=e&&this.b2CompressOut();const o=Math.min(e-this.posOut,i-r);t.set(n.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("no XOF after digest()");return this.writeInto(t)}xof(t){return y(t),this.xofInto(new Uint8Array(t))}digestInto(t){if($(t,this),this.finished)throw new Error("digest() was already called");this.enableXOF=!1,this.writeInto(t.length===this.outputLen?t:t.subarray(0,this.outputLen)),this.destroy()}digest(){const t=new Uint8Array(this.outputLen);return this.digestInto(t),t}}const G=R(((t={})=>new V(t))),K="AGENT_TOOL_HOST_ID";function Y(t){return function(t){if(_(t),A)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=L[t[n]];return e}(G((new TextEncoder).encode(t)))}async function Z(t){try{return await o().readTextFile(t)}catch{return null}}function Q(t){var e;const n=null==(e=t.agent_tool_host_id)?void 0:e.trim();if(n)return`host:${n}:`;return`host:${(t.etc_hostname??t.hostname_env??"unknown").trim()}:${(t.machine_id??"").trim()}`}async function tt(){const t=o().env.get(K)??null;return(null==t?void 0:t.trim())?Q({agent_tool_host_id:t,etc_hostname:null,hostname_env:null,machine_id:null}):Q({agent_tool_host_id:t,etc_hostname:await Z("/etc/hostname"),hostname_env:o().env.get("HOSTNAME")??null,machine_id:await Z("/etc/machine-id")})}function et(t,e){return{host:t,uid:e}}function nt(t){return n.canonicalJson(t)}function rt(t,e,n){return t??it(e,n)}function it(t,e){return`${t}:${Y(nt(e)).slice(0,24)}`}function ot(t,e){return l(t,`${Y(e).slice(0,24)}.lock`)}const st="read_file",at="write_file",ct="edit_file",lt="shell",ut=[st,at,ct,lt],dt=65536,ht=2048,ft="native",mt=200;class pt extends Error{constructor(t,e,n=!1){super("invalid_args"===t?`invalid args: ${e}`:"exec_failed"===t?`execution failed: ${e}`:"timeout"===t?"timeout":"transport"===t?`runtime transport: ${e}`:`cancelled: ${e}`),this.kind=t,this.detail=e,this.effectUnknown=n,this.name="NativeToolError"}}const wt=t=>new pt("invalid_args",t),gt=t=>new pt("exec_failed",t);function yt(t){const e=[];let n="",r=!1,i=!1;const o=[...t];for(let s=0;s<o.length;s++){const t=o[s];"'"!==t||i?'"'!==t||r?"\\"!==t||r?!/\s/.test(t)||r||i?n+=t:n&&(e.push(n),n=""):s+1<o.length&&(n+=o[++s]):i=!i:r=!r}if(!r&&!i)return n&&e.push(n),e}function _t(t){var e;const n=void 0!==t.cmd_name?(null==(e=t.cmd_args)?void 0:e.trim())?`${t.cmd_name} ${t.cmd_args.trim()}`:t.cmd_name:void 0;return`${(void 0!==n?function(t,e){const n=[...t];return n.length<=e?t:`${n.slice(0,e).join("")}...[TRUNCATED]`}(n.trim(),96):"")||"action"} => ${"pending"===t.status?void 0!==t.pending_reason?`pending (${t.pending_reason})`:"pending":t.status}`}function vt(t,e,n,r){const i={agent_tool_protocol:"1",tool:t,status:"success",summary:r,detail:e},o=yt(n),s=o&&o.length?o:n.split(/\s+/).filter(Boolean);return s.length&&(i.cmd_name=s[0],s.length>1&&(i.cmd_args=s.slice(1).join(" "))),i.title=_t(i),i}function bt(t,e){return"/"===e?t.startsWith("/"):t===e||t.startsWith(`${e}/`)}function $t(t,e){if(0!==e.length&&!e.some((e=>bt(t,e))))throw wt(`path not allowed by policy: ${t}`)}async function kt(t){let e=t.replace(/\/+$/,"")||"/";const n=[];for(;;)try{const t=await o().realPath(e);return r.normalizePath(l(t,...n.slice().reverse()))}catch(i){if(!s(i))throw gt(c(i));try{throw await o().lstat(e),wt(`dangling symlink: ${e}`)}catch(a){if(a instanceof pt)throw a}const r=e.slice(e.lastIndexOf("/")+1);if(!r||".."===r)throw wt(`cannot resolve ${t}`);"."!==r&&n.push(r);const l=u(e);if(l===e||"/"===e)throw wt("path has no existing ancestor");e=l}}async function xt(t,e,n){if(!e.trim())throw wt("path cannot be empty");const i=e.startsWith("/")?e:l(t,e);$t(r.normalizePath(i),n);const o=await kt(i);return $t(o,await Promise.all(n.map(kt))),o}function Et(t){let e="";for(const n of(new TextEncoder).encode(t)){const t=String.fromCharCode(n);e+=/[A-Za-z0-9\-._~!$&'()*+,;=:@]/.test(t)?t:`%${n.toString(16).toUpperCase().padStart(2,"0")}`}return e}function Ot(t,e){if(!t)return;const n=r.normalizePath(t);if(!bt(e,n))return;return`cyfs://${["",...e.slice(n.length).split("/").filter((t=>t&&"."!==t))].map(Et).join("/")||"/"}`}function It(t){return null===t?"null":"boolean"==typeof t?`boolean \`${t}\``:"number"==typeof t?Number.isInteger(t)?`integer \`${t}\``:`floating point \`${t}\``:"string"==typeof t?`string ${JSON.stringify(t)}`:Array.isArray(t)?"sequence":"map"}function St(t,e){return wt(`invalid args for \`${t}\`: ${e}`)}function Tt(t,e,n){const r=e[n];if(void 0===r)throw St(t,`missing field \`${n}\``);if("string"!=typeof r)throw St(t,`invalid type: ${It(r)}, expected a string`);return r}function At(t,e,n){const r=e[n];if(null!=r){if("string"!=typeof r)throw St(t,`invalid type: ${It(r)}, expected a string`);return r}}const Lt=new TextEncoder;function Pt(t){return Lt.encode(t).length}function Rt(t){return new TextDecoder("utf-8",{ignoreBOM:!0}).decode(t)}function Dt(t){return t?t.match(/[^\n]*\n|[^\n]+$/g)??[]:[]}function jt(t){if(!t)return[];const e=t.split("\n");return""===e[e.length-1]&&e.pop(),e.map((t=>t.endsWith("\r")?t.slice(0,-1):t))}function Xt(t){const e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r/g,"\\r").replace(/\n/g,"\\n"),n=t?Math.max(jt(t).length,1):0,r=[...e];return r.length<=64?e:`${r.slice(0,32).join("")}...(total ${n} lines)...${r.slice(-32).join("")}`}function Mt(t,e){const n=t.trim();if("$"===n)return"end";if(n.startsWith("+")||!/^-?\d+$/.test(n))throw wt(`invalid range text \`${e}\``);const r=Number(n);if(0===r)throw wt("range must be 1-based, zero is invalid");return r}function Nt(t,e){const n=t.trim();if(!n.startsWith("+"))throw wt(`invalid range text \`${e}\``);const r=n.slice(1).trim();if(!/^\d+$/.test(r))throw wt(`invalid range text \`${e}\``);const i=Number(r);if(0===i)throw wt("range count must be positive integer");return i}function Ut(t,e){if("string"==typeof t)return Mt(t,e);if("number"==typeof t&&Number.isInteger(t)){if(0===t)throw wt(`${e} must be non-zero integer`);return t}throw wt(`${e} must be integer or \`$\``)}function Ct(t){if(null!=t){if(n.isObject(t)){const e=void 0!==t.start?Ut(t.start,"range.start"):void 0,n=void 0!==t.end?Ut(t.end,"range.end"):void 0,r=void 0!==t.count?function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<=0)throw wt(`${e} must be positive integer`);return t}(t.count,"range.count"):void 0;if(void 0!==r&&void 0!==n)throw wt("range cannot set both `end` and `count`");if(void 0!==r&&void 0===e)throw wt("range.count requires range.start");if(void 0===e&&void 0===n&&void 0===r)throw wt("range object must contain at least one of start/end/count");return{start:e,end:n,count:r,defaultEnd:"tail_if_start_negative"}}if(Array.isArray(t)){if(0===t.length||t.length>2)throw wt("range array must be [start] or [start,end]");return{start:Ut(t[0],"range[0]"),end:2===t.length?Ut(t[1],"range[1]"):void 0,defaultEnd:"same_as_start"}}if("number"==typeof t&&Number.isInteger(t))return{start:Ut(t,"range"),defaultEnd:"same_as_start"};if("string"==typeof t)return function(t){const e=t.trim();if(!e||"-"===e)return;if(e.includes(",")||e.includes(":")){if(e.includes(",")&&e.includes(":"))throw wt(`invalid range text \`${t}\``);const n=e.split(e.includes(",")?",":":");if(2!==n.length)throw wt(`invalid range text \`${t}\``);const r=n[0].trim()?Mt(n[0].trim(),t):void 0,i=n[1].trim();if(i.startsWith("+")){if(void 0===r)throw wt(`range \`${t}\` with \`+count\` requires start`);return{start:r,count:Nt(i,t),defaultEnd:"same_as_start"}}return{start:r,end:i?Mt(i,t):void 0,defaultEnd:"end"}}const n=e.indexOf("-");if(n>=0){const r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(r&&i&&/^\d+$/.test(r)&&/^\d+$/.test(i))return{start:Mt(r,t),end:Mt(i,t),defaultEnd:"same_as_start"}}return{start:Mt(e,t),defaultEnd:"same_as_start"}}(t);throw wt("range must be string/number/array/object")}}function Ft(t,e){return"end"===t?e:t>0?t:e+t+1}const Ht={name:st,description:'Read a text file. range selects 1-based lines ("120-200", "120:$", "120:+20", "-50:$" for the last 50); first_chunk starts the read at the first occurrence of that text. Paths are relative to the working directory; paths outside it only where the run\'s filesystem policy allows.',args_schema:{properties:{first_chunk:{description:"Start the read at the first occurrence of this text (range then counts from there).",type:"string"},path:{description:"File to read, relative to the working directory.",type:"string"},range:{description:'1-based line range: "120-200", "120:$" (to the end), "120:+20" (20 lines from 120); negative numbers count from the end ("-50:$").'}},required:["path"],type:"object"}},Bt={name:at,description:'Write a text file: mode "write" (default) creates or overwrites it, "append" adds to its end, "new" creates it and fails if it exists. Parent directories are created. Paths are relative to the working directory; paths outside it only where the run\'s filesystem policy allows.',args_schema:{properties:{content:{description:"The text to write.",type:"string"},mode:{description:"`write` (default): create or overwrite; `append`: add to the end; `new`: create, fail if the file exists.",type:"string"},path:{description:"File to write, relative to the working directory.",type:"string"}},required:["content","path"],type:"object"}},zt={name:ct,description:"Replace the one exact occurrence of old_string with new_string in a text file. Fails when old_string is absent or occurs more than once: include enough surrounding text to make it unique. Paths are relative to the working directory; paths outside it only where the run's filesystem policy allows.",args_schema:{properties:{new_string:{description:"The replacement text.",type:"string"},old_string:{description:"The exact text to replace; it must occur exactly once.",type:"string"},path:{description:"File to edit, relative to the working directory.",type:"string"}},required:["new_string","old_string","path"],type:"object"}};async function qt(t){try{return Rt(await o().readFile(t))}catch(e){throw gt(`read file failed: ${c(e)}`)}}async function Jt(t,e){try{await o().mkdir(u(t),{recursive:!0})}catch(n){throw gt(c(n))}try{await o().writeFile(t,Lt.encode(e))}catch(n){throw gt(`write file failed: ${c(n)}`)}}function Wt(t){return{spec:Ht,idempotent:!0,cancellable:!1,async call(e){const r=Tt(st,e,"path"),i=At(st,e,"first_chunk"),o=null===e.range?void 0:e.range,s=r.trim();if(!s)throw wt("missing required arg `path`");const a=await xt(t.root,s,t.allowedRead),c=await qt(a);let l,u=!0,d=1;if(void 0!==i){const t=c.indexOf(i);t>=0?(l=c.slice(t),d=(c.slice(0,t).match(/\n/g)??[]).length+1):(l="",u=!1)}else l=c;const h=Dt(l),f=h.length,m=Ct(o);let p,w,g="";m?([p,w]=function(t,e){const n=t.start??1,r=Ft(n,e);let i;return i=void 0!==t.count?r+t.count-1:void 0!==t.end?Ft(t.end,e):"same_as_start"===t.defaultEnd?r:"end"===t.defaultEnd||"number"==typeof n&&n<0?e:r,[Math.min(Math.max(r,1),e+1),Math.min(Math.max(i,0),e)]}(m,f),g=`${p}-${w}`):0===f?(p=1,w=0):(p=1,w=f);const y=Math.min(Math.max(p-1,0),f),_=Math.min(w,f),v=y<_?h.slice(y,_):[],b=v.join(""),$=v.length,k=0===$?null:d+y,x=null===k?null:k+Math.max($-1,0);let E="";null!==k&&(E=v.slice(0,mt).map(((t,e)=>{return`${k+e}: ${n=t,n.replace(/[\r\n]+$/,"")}`;var n})).join("\n"),v.length>mt&&(E+=(E?"\n":"")+"... truncated to 200 lines"));const O=Pt(b),I=function(t,e,r){let i=`${st} ${t}`;if(void 0!==e&&(i+=` first_chunk="${Xt(e)}"`),null!=r){const t="string"==typeof r?r:n.canonicalJson(r);t.trim()&&(i+=` range=${t}`)}return i}(s,i,o);let S;if(u){const t=`succeeded, read ${O} bytes across ${null!==k&&null!==x?k===x?`1 line at ${k}`:`${$} lines at ${k}-${x}`:"0 lines"}`;S=E?`${t}\n\`\`\`content\n${E}\n\`\`\``:t}else S="succeeded, first_chunk was not found, read 0 bytes across 0 lines";const T={},A=Ot(t.dfsRoot,a);void 0!==A&&(T.cyfs_url=A),Object.assign(T,{content:b,matched:u,line_range:g,bytes:O,line_count:$,start_line:k,end_line:x,preview_truncated:$>mt});const L=vt(st,T,I,S);return L.title=`${I} => ${u?"success":"anchor not found"}`,function(t,e,r){var i;if("success"!==t.status)return t;const o=(null==(i=t.output)?void 0:i.trim())?t.output:t.summary.trim()?t.summary:n.canonicalJson(t.detail);return t.dedup={key:`read:${e}#${r}:${Y(o).slice(0,16)}`,hint:`\`${e}\` is unchanged since you read it earlier in this run; use that content.`},t}(L,s,n.canonicalJson(Object.fromEntries(Object.entries(e).filter((([t])=>"path"!==t)))))}}}function Vt(t){const e=(t??"write").trim().toLowerCase();if("new"===e||"create"===e)return"new";if("append"===e)return"append";if(""===e||"write"===e||"overwrite"===e)return"write";throw wt(`invalid write mode \`${e}\`, expected new/append/write`)}function Gt(t){return{spec:Bt,idempotent:!1,cancellable:!1,async call(e){const n=Tt(at,e,"path"),r=Tt(at,e,"content"),i=At(at,e,"mode");let a;try{a=Vt(i)}catch{a="write"}const l=`${at} ${n} mode=${a}`,u=n.trim();if(!u)throw wt("missing required arg `path`");const d=Vt(i),h=await xt(t.root,u,t.allowedWrite),f=await async function(t){try{return await o().stat(t),!0}catch(e){if(s(e))return!1;throw gt(c(e))}}(h);if("new"===d&&f)throw wt(`write mode \`new\` requires target file not exist: ${u}`);const m=f?await qt(h):"",p="append"===d?"append":"new"===d?"new":f?"write":"create",w="append"===d?`${m}${r}`:r;await Jt(h,w);const g=Dt(r).length,y={},_=Ot(t.dfsRoot,h);void 0!==_&&(y.cyfs_url=_);const v=Pt(w);Object.assign(y,{created:!f,changed:m!==w,bytes_written:v,line_count:g});const b=`${"append"===p?"appended":"new"===p||"create"===p?"created":"wrote"} ${u}, wrote ${Pt(r)} bytes across ${1===g?"1 line":`${g} lines`}`,$=vt(at,y,l,b),k="append"===p?"append":"new"===p||"create"===p?"new":"write";return $.title=`${at} ${u} mode=${k} => success (${v} bytes)`,$}}}function Kt(t){return{spec:zt,idempotent:!1,cancellable:!1,async call(e){const n=Tt(ct,e,"path"),r=Tt(ct,e,"old_string"),i=Tt(ct,e,"new_string"),o=`${ct} ${n} old_string="${Xt(r)}"`,s=n.trim();if(!s)throw wt("missing required arg `path`");if(!r)throw wt("missing required arg `old_string`");if(r===i)throw wt("`new_string` must be different from `old_string`");const a=await xt(t.root,s,t.allowedWrite),c=await qt(a),l=[];for(let t=c.indexOf(r);t>=0;t=c.indexOf(r,t+r.length))l.push(t);if(0===l.length)throw wt("`old_string` was not found in the file");if(l.length>1)throw wt(`\`old_string\` must match exactly once, found ${l.length} matches`);const u=l[0],d=c.slice(0,u)+i+c.slice(u+r.length),h=c!==d;h&&await Jt(a,d);const f=function(t,e,n){const r=jt(e),i=jt(n),o=[];for(let s=0;s<Math.max(r.length,i.length);s++){const t=r[s],e=i[s];void 0!==t&&void 0!==e?t===e?o.push(` ${t}`):o.push(`-${t}`,`+${e}`):void 0!==t?o.push(`-${t}`):void 0!==e&&o.push(`+${e}`)}return[`--- a/${t}`,`+++ b/${t}`,`@@ -1,${r.length} +1,${i.length} @@`,...o].join("\n")}(s,c,d),m=(c.slice(0,u).match(/\n/g)??[]).length+1,p={},w=Ot(t.dfsRoot,a);void 0!==w&&(p.cyfs_url=w),Object.assign(p,{matched:!0,changed:h,mode:"replace",line:m,diff:f,diff_truncated:!1});const g=h?f.trim()?`edited ${s} with replace at line ${m}\n\`\`\`diff\n${f}\n\`\`\``:`edited ${s} with replace at line ${m}`:`edit ${s} made no change`,y=vt(ct,p,o,g);return y.title=`${ct} ${s} => ${h?`success (line ${m})`:"no change"}`,y}}}const Yt='if [ "$#" -ge 2 ]; then export PATH="$2"; fi\nprintf \'%s\\n\' "$0" > "$1/command"\n"$BASH" -c "$0" </dev/null >"$1/stdout" 2>"$1/stderr"\n__llm_ec=$?\nprintf \'%s\\n\' "$__llm_ec" > "$1/exit.tmp" && command -p mv -f "$1/exit.tmp" "$1/exit"\nexit $__llm_ec',Zt=["/usr/local/sbin","/usr/local/bin","/usr/sbin","/usr/bin","/sbin","/bin"];function Qt(t){const e=[...t].map((t=>/[A-Za-z0-9\-_.]/.test(t)?t:"_")).join("");return!e||e.startsWith(".")?`c_${e}`:e}function te(t,e){if(t&&e)return l(t,"exec",Qt(e))}function ee(t){const e=Math.floor(t/1e3);return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${String(e%60).padStart(2,"0")}s`:`${Math.floor(e/3600)}h${String(Math.floor(e%3600/60)).padStart(2,"0")}m`}async function ne(t){try{return await o().readFile(t)}catch{return}}async function re(t,e){const n=await ne(t);return n?function(t,e){const n=Math.floor(e/4),r=e-n,i=t.subarray(0,Math.min(n,t.length)),o=t.subarray(i.length),s=o.subarray(Math.max(0,o.length-r));return t.length>i.length+s.length?[`${Rt(i)}\n…[${t.length-i.length-s.length} bytes omitted]…\n${Rt(s)}`,!0]:[Rt(i)+Rt(s),!1]}(n,Math.max(e,16)):["",!1]}async function ie(t,e){const n=await ne(t);return n?Rt(n.subarray(Math.max(0,n.length-e))):""}async function oe(t){try{const e=(await o().readTextFile(l(t,"exit"))).trim();return/^[+-]?\d+$/.test(e)?Number(e):void 0}catch{return}}async function se(t,e,n,r,i,o){const[s,a]=await re(l(t,"stdout"),i),[c,u]=await re(l(t,"stderr"),i);let d=s;return c&&(d&&!d.endsWith("\n")&&(d+="\n"),d+=c),{exit_code:e,stdout:s,stderr:c,output:d,output_truncated:a||u,timed_out:n,duration_ms:Math.floor(r),cwd:o}}const ae={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15};const ce=["tool","cmd_name","task_id","pending_reason","estimated_wait","title","summary","cmd_args","partial_output","output"];function le(t){const e=t.maxTimeoutMs,n=`Run a command in this run's runtime (native) with bash syntax. It starts in the working directory unless cwd is given; it is not sandboxed and runs with the current user's permissions. The command is a child process of this executor: an interrupt or a timeout ends its process group; processes it leaves behind after returning are not managed. Waits for the command to finish. Default timeout ${Math.floor(t.timeoutMs/1e3)}s${0===e?", no upper limit":`, max ${Math.floor(e/1e3)}s`}; on timeout the command is stopped and the output so far is returned. Start a long-lived service with nohup / setsid and return at once; on Unix, processes started with \`&\` / nohup in the foreground command's process group also end when that command is interrupted or times out. Long output keeps its beginning and end.`,r={description:`Timeout in milliseconds (default ${t.timeoutMs}${0===e?"":`, max ${e}`}). Set it explicitly for long builds, tests or media commands.`,minimum:1,type:"integer"};return 0!==e&&(r.maximum=e),{name:lt,description:n,args_schema:{properties:{command:{description:"bash command to execute",type:"string"},cwd:{description:t.restrictCwd?"Working directory, relative to or within the configured workspace. Defaults to the workspace.":"Working directory, absolute or relative to the default working directory. Defaults to that directory; outside paths are allowed subject to OS permissions.",type:"string"},timeout_ms:r},required:["command"],type:"object"}}}function ue(t,e){if(null!=t){if("number"==typeof t&&Number.isInteger(t)&&t>=0)return t;if("string"==typeof t&&/^\d+$/.test(t.trim()))return Number(t.trim());throw wt(`\`${e}\` must be a non-negative integer`)}}let de=0;function he(t){let e;return{done:new Promise((n=>{e=setTimeout((()=>n("timeout")),Math.min(t,2**31-1))})),stop:()=>clearTimeout(e)}}function fe(t){return{spec:le(t),idempotent:!1,cancellable:!0,async call(e,i){const s="string"==typeof e.command?e.command.trim():"";if(!s)throw wt("`command` is required and must be non-empty");const a="string"==typeof e.cwd?e.cwd:void 0,u=r.normalizePath(t.workspace),h=await xt(u,a??".",t.restrictCwd?[u]:[]);if(!(await d(h)))throw wt(`cwd does not exist: ${h}`);const f=function(t){if(null==t)return[];if(!n.isObject(t))throw wt("`env` must be an object of string=>string");const e=[];for(const[r,i]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw wt(`invalid env key \`${r}\` (must match [A-Za-z_][A-Za-z0-9_]*)`);if("string"==typeof i)e.push([r,i]);else if("number"==typeof i||"boolean"==typeof i)e.push([r,String(i)]);else{if(null!==i)throw wt(`env value for \`${r}\` must be string/number/bool, got ${n.canonicalJson(i)}`);e.push([r,""])}}return e}(e.env),m=ue(e.timeout_ms,"timeout_ms");if(0===m&&0!==t.maxTimeoutMs)throw wt("`timeout_ms` must be a positive integer");const p=(e=>{const n=e??t.timeoutMs;return 0===t.maxTimeoutMs?n:Math.min(Math.max(n,1),t.maxTimeoutMs)})(m);ue(e.wait_ms,"wait_ms");const w=new Map(f);let g=(w.get("PATH")??o().env.get("PATH")??"").trim();for(const t of Zt)y=t,g=(_=g)?_.split(":").includes(y)?_:`${_}:${y}`:y;var y,_;w.set("PATH",g),i.call_id&&w.set("XLLM_CALL_ID",i.call_id),i.run_id&&w.set("XLLM_RUN_ID",i.run_id);const v={...t.env,...Object.fromEntries(w)};v.PATH=[...new Set(g.split(":").filter(Boolean))].join(":");const b=te(i.run_dir,i.call_id),$=void 0===b,k=b??l(o().env.get("TMPDIR")||"/tmp",`llm-shell-${o().pid}-${++de}`);try{await o().mkdir(k,{recursive:!0,mode:448})}catch(R){throw gt(`execution directory: ${c(R)}`)}for(const t of["exit","exit.tmp"])await o().remove(l(k,t)).catch((()=>{}));let x;const E=performance.now();try{x=new(o().Command)("/bin/bash",{args:["-c",Yt,s,k],cwd:h,env:v,stdin:"null",stdout:"null",stderr:"null"}).spawn()}catch(R){throw gt(`spawn shell failed: ${c(R)}`)}const O=async()=>{$&&await o().remove(k,{recursive:!0}).catch((()=>{}))},I=async()=>{try{x.kill("SIGKILL")}catch{}const t=he(5e3);await Promise.race([x.status,t.done]),t.stop();const e=await se(k,124,!0,performance.now()-E,dt,h);return await O(),e},S=he(0===p?31536e6:p),T=await Promise.race([x.status.then((t=>({exited:t}))),S.done.then((()=>({timeout:!0}))),i.call.cancelled().then((t=>({cancel:t})))]);let A;if(S.stop(),"exited"in T)A=await se(k,(P=T.exited,P.signal?128+(ae[P.signal]??0):P.code),!1,performance.now()-E,dt,h),await O();else{if(!("timeout"in T)){const t=(await ie(l(k,"stdout"),ht)).trimEnd(),e=await I();throw new pt("cancelled",`shell (native): \`${s}\` was stopped after ${e.duration_ms}ms because ${L=T.cancel,"finishing"===L?"the run is finishing":"deadline"===L?"the run's total time limit was reached":"the run was interrupted"}. It may have had partial side effects; check before repeating it.${t.trim()?`\n--- output so far (tail) ---\n${t}`:""}`)}A=await I()}var L,P;return function(t,e,r,i){if(!e.timed_out){const r=function(t,e){var r;if(function(t){let e=!1,n=!1,r=!1;for(const i of t)if(r)r=!1;else if("\\"!==i||e)if("'"!==i||n)if('"'!==i||e){if("|;&><\n\r".includes(i)&&!e&&!n)return!0}else n=!n;else e=!e;else r=!0;return!1}(t)||!(null==(r=yt(t))?void 0:r.length))return;const i=e.stdout.trim();if(!i)return;let o;try{o=JSON.parse(i)}catch{return}if(!n.isObject(o)||"1"!==o.agent_tool_protocol)return;const s=o.status??"success";if("success"!==s&&"error"!==s&&"pending"!==s)return;for(const n of ce)if(void 0!==o[n]&&null!==o[n]&&"string"!=typeof o[n])return;if("pending"===s&&"string"!=typeof o.task_id)return;const a={...o,status:s,summary:"string"==typeof o.summary?o.summary:"",detail:void 0===o.detail?{}:o.detail};return void 0===a.return_code&&0!==e.exit_code&&(a.return_code=e.exit_code),a}(t,e);if(r)return r}const o=e.timed_out?`timed out after ${e.duration_ms}ms (timeout_ms=${r}); the command was stopped. Retry with a larger timeout_ms${0===i?"":` (max ${i})`}, or start a long-lived service with nohup / setsid and return at once.`:`exit=${e.exit_code} in ${e.duration_ms}ms`,s={command:t,cwd:e.cwd,exit_code:e.exit_code,stdout:e.stdout,stderr:e.stderr,output:e.output,output_truncated:e.output_truncated,timed_out:e.timed_out,duration_ms:e.duration_ms,engine:ft,runtime:"native"},a=vt(lt,s,`${lt} ${t}`,o);return a.status=0!==e.exit_code||e.timed_out?"error":"success",a.return_code=e.exit_code,a.title=_t(a),function(t,e){return e.trim()?t.output=e:delete t.output,t}(a,e.output)}(s,A,p,t.maxTimeoutMs)}}}const me="native",pe='set -e\ncommand -v bash >/dev/null\nmachine_id="$(cat /etc/machine-id 2>/dev/null || true)"\n[ -n "$machine_id" ] || machine_id="$(hostname)"\nprintf \'%s\\0\' "$machine_id" "$(hostname)" "$(id -u)" "$(uname -s | tr \'[:upper:]\' \'[:lower:]\')" "$(uname -m)" "$(command -v bash)" "$(pwd -P)" "${PATH}" "$(date +%Y-%m-%dT%H:%M:%S%z)" "$(date +%Z%z)"\nfor tool in bash realpath base64; do if command -v "$tool" >/dev/null; then printf \'%s\\0\' "$tool"; fi; done\n';function we(t){let e=(new TextDecoder).decode(t);e.endsWith("\0")&&(e=e.slice(0,-1));const r=e.split("\0");if(r.length<10||r.slice(0,10).some((t=>""===t)))throw n.XllmError.capability("execution environment probe returned incomplete data");return{machine:r[0],hostname:r[1],uid:r[2],os:r[3],arch:r[4],shell:r[5],cwd:r[6],path:r[7],current_time:r[8],timezone:r[9],tools:r.slice(10,42)}}async function ge(t,e){if("windows"===o().build.os)throw n.XllmError.capability("the Deno host's native runtime needs bash (Linux / macOS); Windows PowerShell runtimes are Rust-only");let r;try{r=await new(o().Command)("/bin/bash",{args:["-c",pe],cwd:t,env:e,stdin:"null",stdout:"piped",stderr:"piped",signal:AbortSignal.timeout(1e4)}).output()}catch(i){throw n.XllmError.capability(c(i))}if(!r.success)throw n.XllmError.capability(`native capability probe failed: ${(new TextDecoder).decode(r.stderr)}`);return we(r.stdout)}function ye(t){return n.XllmError.config(".llm_context","runtime",t)}function _e(t){for(const[e,n]of Object.entries(t))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||n.includes("\0"))throw ye(`invalid env key or value \`${e}\``)}const ve="intent";class be{constructor(t,e,n){this.tools=t,this.workdir=e,this.advertised=n,this.binding={run_id:""},this.ledger=new r.MemoryHintLedger,this.written=[]}bindRun(t){this.binding={...t}}setRecovering(t,e){this.recovering={callId:t,reason:e}}artifacts(){return[...this.written]}has(t){return this.tools.has(t)}hintLedger(){return this.ledger}clearDedup(){this.ledger.clear(r.HINT_NS_DEDUP)}taskResolver(){}listToolSpecs(){return(this.advertised?[...this.advertised.values()]:[...this.tools.values()].map((t=>t.spec))).sort(((t,e)=>t.name<e.name?-1:t.name>e.name?1:0)).map((t=>ut.includes(t.name)?function(t){const e=n.cloneJson(t);let r=e.args_schema;return("object"!=typeof r||null===r||Array.isArray(r))&&(r=e.args_schema={type:"object"}),("object"!=typeof r.properties||null===r.properties||Array.isArray(r.properties))&&(r.properties={}),r.properties[ve]={type:"string",description:"Optional: why you make this call now and what you expect it to give you, in one short sentence. Shown as the progress of your work."},Array.isArray(r.required)&&(r.required=r.required.filter((t=>t!==ve))),e}(t):n.cloneJson(t)))}names(){return[...this.tools.keys()].sort().join(", ")}async callTool(t,e){var n,i;const o=t.call_id,s=this.tools.get(t.name);if(!s)return{kind:"error",call_id:o,message:`tool \`${t.name}\` is not available in this run (available: ${this.names()})`};const a={...t.args??{}};if(ut.includes(t.name)&&delete a[ve],(null==(n=this.recovering)?void 0:n.callId)===o){const t=this.recovering.reason;if(this.recovering=void 0,!s.idempotent)return{kind:"unresolved",call_id:o,reason:t,effect_unknown:!0}}const u=s.call(a,{call_id:o,run_id:this.binding.run_id,run_dir:this.binding.run_dir,call:e}).then((t=>({ok:t})),(t=>({err:t})));let d;if(s.cancellable)d=await u;else{const n=await Promise.race([u,e.cancelledHard().then((t=>({cancelled:t})))]);if("cancelled"in n)return{kind:"cancelled",call_id:o,reason:`tool \`${t.name}\` was abandoned while running (${h=n.cancelled,"deadline"===h?"Deadline":"finishing"===h?"Finishing":"Interrupted"}); it cannot be cancelled, so its effect is unknown`,effect_unknown:!0};d=n}var h;if("err"in d){const t=d.err;if(t instanceof pt){if("transport"===t.kind)throw new r.ToolDispatchException(t.detail,t.effectUnknown);return"cancelled"===t.kind?{kind:"cancelled",call_id:o,reason:t.detail,effect_unknown:t.effectUnknown}:{kind:"error",call_id:o,message:t.message}}return{kind:"error",call_id:o,message:`execution failed: ${c(t)}`}}const f=d.ok;if("success"===f.status&&(t.name===at||t.name===ct)){const t=a.path;if("string"==typeof t){const e=t.startsWith("/")?t:r.normalizePath(l(this.workdir,t));this.written.includes(e)||this.written.push(e)}}if("pending"===f.status){const e=null==(i=f.task_id)?void 0:i.trim();return e?r.taskStateObservation(o,e,{kind:"unknown",reason:"this runtime has no task backend"},{kind:"tools"}):{kind:"error",call_id:o,message:`tool \`${t.name}\` returned a pending result without a task_id`,host:r.toHost(f)}}return r.envelopeObservation(o,f,r.applyHints(f,this.ledger))}}function $e(t,e,n){return{runtime_id:t,kind:me,host:e.host,target:e,workdir:n.cwd,capabilities:{tools:Object.fromEntries(n.tools.map((t=>[t,"available"]))),network:!0,os:n.os}}}function ke(t){return t.wait_ms<t.timeout_ms}async function xe(t={}){const e=n.cloneJson(t.config??{env:{}});e.env=e.env??{},function(t){const e=t.kind??me;if(r.PLANNED_RUNTIME_KINDS.includes(e))throw n.XllmError.capability(`runtime \`${e}\` is planned but not implemented`);if("site"===e)throw n.XllmError.capability("runtime `site` is built by a website (createSiteRuntime); the Deno host runs `native`");if("remote_ssh"===e||"remote_node"===e)throw n.XllmError.capability(`runtime \`${e}\` is not available on the Deno host (only \`native\`)`);if(e!==me)throw ye(`unknown runtime kind \`${e}\``);if(t.remote_ssh&&void 0!==t.kind)throw ye("remote_ssh connection block requires kind: remote_ssh");if(t.remote_node&&void 0!==t.kind)throw ye("remote_node connection block requires kind: remote_node");if(t.remote_ssh||t.remote_node)throw ye("connection block does not match runtime kind");if(_e(t.env??{}),void 0!==t.id&&!t.id.trim())throw ye("id cannot be empty");if(0===t.task_wait_ms)throw ye("task_wait_ms must be positive")}(e);const i=e.workdir??t.workdir??o().cwd();let s;try{s=await o().realPath(i)}catch(_){throw n.XllmError.capability(`runtime cwd ${i}: ${c(_)}`)}if(!(await d(s)))throw n.XllmError.capability("runtime workdir must be a directory");const a=await ge(s,e.env),u=et(await tt(),a.uid),h=rt(e.id,me,u),f=function(t,e,n,r){const i=t.os.toLowerCase(),o=t.shell.split(/[/\\]/).pop()??"";return{id:e,kind:me,os:t.os,arch:t.arch,hostname:t.hostname,shell:t.shell,cwd:t.cwd,tools:t.tools,current_time:t.current_time,timezone:t.timezone,target:n,platform:"darwin"===i||"macos"===i?"macos":i,shell_kind:o.replace(/\.exe$/,"").replace(/\.EXE$/,"").toLowerCase(),baseline:r??""}}(a,h,u,e.baseline),m={...e,kind:me,id:h,workdir:f.cwd},p=$e(h,u,a),w=l(o().env.get("BUCKYOS_ROOT")||"/opt/buckyos","data"),g=(t,e,i,o,s,a)=>{const c=[];for(const l of t){const t=r.describeToolSource(l);if("mcp"===l.kind)throw n.XllmError.capability(`${e}: \`${t}\`: MCP tools are not available on the Deno host`);if("named"===l.kind)throw n.XllmError.capability(`${e}: \`${t}\`: named host tools are not available on the Deno host (only the \`bash\` group)`);if(l.groupname===r.BUILTIN_TOOL_GROUP_BASH_CORE||"executor"===l.groupname)throw n.XllmError.capability(`${e}: \`${t}\` needs a host task CLI / executor that the Deno host does not provide (use \`bash\`)`);if(l.groupname!==r.BUILTIN_TOOL_GROUP_BASH)throw n.XllmError.tools(`unknown builtin tool group \`${l.groupname}\` (available: ${r.BUILTIN_TOOL_GROUP_BASH}, ${r.BUILTIN_TOOL_GROUP_BASH_CORE}, executor)`);if(ke(i))throw n.XllmError.capability(`${e}: \`shell\` would hand commands still running after runtime.task_wait_ms (${i.wait_ms} ms) to a task backend, which the Deno host does not have; set runtime.task_wait_ms to at least tools.shell.timeout_ms (${i.timeout_ms} ms) so \`shell\` waits for its command`);const u="workspace"===o,d={root:f.cwd,allowedRead:u?[f.cwd]:[],allowedWrite:u?[f.cwd]:[],dfsRoot:w},h=[Wt(d),Gt(d),Kt(d),fe({workspace:f.cwd,restrictCwd:u,timeoutMs:i.timeout_ms,maxTimeoutMs:i.max_timeout_ms,env:s})];for(const e of h){if(a.has(e.spec.name))throw n.XllmError.tools(`tool name \`${e.spec.name}\` from ${t} conflicts with an already expanded tool of the same name`);a.set(e.spec.name,e),c.push({name:e.spec.name,description:e.spec.description,args_schema:n.cloneJson(e.spec.args_schema),source:t})}}return c};let y;return{kind:me,probe:a,descriptor:()=>n.cloneJson(p),config:()=>n.cloneJson(m),async info(){const t=await ge(f.cwd,m.env),e=y?[...new Set([...f.tools,...y])].sort().slice(0,32):f.tools;return{...n.cloneJson(f),tools:e,current_time:t.current_time,timezone:t.timezone}},async open(e,i){_e(e.env);const o={...m.env,...e.env};o.PATH=o.PATH??a.path;const s=t.takeover&&t.takeover.run_id===e.run_id?t.takeover.tools:void 0,c=s?{enabled:s.enabled,filesystem_policy:s.filesystem_policy,tools2actions:s.tools2actions,tools:s.tool_sources,actions:s.action_sources,bash_tools:s.bash_tools,shell:{timeout_ms:s.shell.timeout_ms,max_timeout_ms:s.shell.max_timeout_ms}}:i,l=c.enabled??!1,u=c.filesystem_policy??"workspace",d=c.tools2actions??!1,h=r.shellSettings(c.shell,e.task_wait_ms),p=e.loop_model,w={enabled:l,filesystem_policy:u,tools2actions:d,tool_sources:n.cloneJson(c.tools??[]),action_sources:n.cloneJson(c.actions??[]),native:[],actions:[],bash_tools:n.cloneJson(c.bash_tools??[]),shell:h,exec_enabled:!1,sources:{...e.sources}};if("function_call"===p){if(d)throw n.XllmError.capability("`tools2actions: true` requires `loop_model: behavior`; function_call cannot convert tools into actions");if((c.actions??[]).length>0)throw n.XllmError.capability("`actions` are configured but `loop_model` is function_call; use `loop_model: behavior` or remove `actions`")}const _=new Map;if(l){const t=c.tools??[{kind:"group",groupname:r.BUILTIN_TOOL_GROUP_BASH}];w.tool_sources=n.cloneJson(t);const e=g(t,"tools.tools",h,u,o,_),i=g(w.action_sources,"tools.actions",h,u,o,_);"behavior"===p&&d?w.actions=[...e,...i]:(w.native=e,w.actions=i),w.exec_enabled=_.has(lt)&&[...w.native,...w.actions].some((t=>t.name===lt))}let v;if(s){v=new Map;for(const t of[...s.native,...s.actions])_.has(t.name)&&v.set(t.name,{name:t.name,description:t.description,args_schema:n.cloneJson(t.args_schema)})}return y=[...w.native,...w.actions].map((t=>t.name)),{tools:w,manager:new be(_,f.cwd,v)}},async describeInterrupted(t,e){if(e.name!==lt)return r.unresolvedReason(e.name);const n=te(t.run_dir,e.call_id);return void 0===n?Ie(e,void 0,"(no execution directory)"):Ie(e,await Ee(n),n)}}}async function Ee(t){let e;try{const n=(await o().stat(l(t,"command"))).mtime;n&&(e=Math.floor(n.getTime()))}catch{e=void 0}return{exit_code:await oe(t),stdout_tail:await ie(l(t,"stdout"),ht),stderr_tail:await ie(l(t,"stderr"),ht),exists:await d(t),started_at_ms:e}}function Oe(t){let e="";return t.stdout_tail.trim()&&(e+=`\n--- stdout (tail) ---\n${t.stdout_tail.trimEnd()}`),t.stderr_tail.trim()&&(e+=`\n--- stderr (tail) ---\n${t.stderr_tail.trimEnd()}`),e}function Ie(t,e,n){const r=function(t){var e;const n=null==(e=t.args)?void 0:e.command;if("string"!=typeof n)return"";const r=n.split(/\s+/).filter(Boolean).join(" "),i=[...r];return i.length>160?`${i.slice(0,160).join("")}…`:r}(t),i=void 0!==(null==e?void 0:e.started_at_ms)?`started ${ee(Math.max(0,Date.now()-e.started_at_ms))} ago (at ${e.started_at_ms} ms since epoch)`:"start time unknown";return void 0!==(null==e?void 0:e.exit_code)?`shell (native): the previous executor exited while \`${r}\` was running (${i}). The command has since ended with exit code ${e.exit_code} (read from ${n}); its result was never returned, so review it before deciding whether to repeat anything.${Oe(e)}`:`shell (native): the previous executor exited while \`${r}\` was running (${i}). The command may have partly executed; it usually ended together with the executor, but not necessarily (e.g. after kill -9 it may still be running). Background processes it started are unaffected. Check the actual state before repeating it.${e?Oe(e):""}`}const Se="~/.xllm/runs",Te="~/.xllm/locks";function Ae(t,e){return r.resolveConfigPath(t,e,function(){const t=o().env;return t.get("HOME")??t.get("USERPROFILE")}())}function Le(t,e){if("disabled"===(null==t?void 0:t.kind))return;return Ae("path"===(null==t?void 0:t.kind)?t.path:Se,u(e.startsWith("/")?e:l(o().cwd(),e)))}class Pe{constructor(t,e){this.file=t,this.path=e,this.released=!1}static async tryAcquire(t){try{await o().mkdir(u(t),{recursive:!0})}catch(r){throw n.XllmError.storage(`cannot create lock directory ${u(t)}: ${c(r)}`)}let e;try{e=await o().open(t,{read:!0,write:!0,create:!0})}catch(r){throw n.XllmError.storage(`cannot open lock ${t}: ${c(r)}`)}if(!(await e.tryLock(!0)))return e.close(),null;try{await o().writeTextFile(t,`${o().pid}\n`)}catch{}return new Pe(e,t)}async release(){if(!this.released){this.released=!0;try{await this.file.unlock()}finally{this.file.close()}}}}async function Re(t){let e;try{e=await o().open(t,{read:!0,write:!0,create:!0})}catch{return!1}try{return!(await e.tryLock(!0))||(await e.unlock(),!1)}finally{e.close()}}let De=0;function je(t){return String(t).padStart(4,"0")}class Xe{constructor(t){this.persistent=!0,this.dir=Ae(t,o().cwd())}runsDir(){return this.dir}runDir(t){return l(this.dir,t)}async ensureWritable(){try{await o().mkdir(this.dir,{recursive:!0})}catch(e){throw n.XllmError.storage(`runs directory ${this.dir} cannot be created: ${c(e)}`)}const t=l(this.dir,`.probe-${o().pid}`);try{await o().writeFile(t,new Uint8Array)}catch(e){throw n.XllmError.storage(`runs directory ${this.dir} is not writable: ${c(e)}`)}await o().remove(t).catch((()=>{}))}async createRun(){await this.ensureWritable();for(let e=0;e<8;e++){const e=r.generateRunId(),i=this.runDir(e);try{await o().mkdir(i)}catch(t){if(a(t))continue;throw n.XllmError.storage(`cannot create run directory ${i}: ${c(t)}`)}return await o().mkdir(l(i,"snapshots"),{recursive:!0}),e}throw n.XllmError.storage("cannot allocate a unique run id")}async writeRecord(t){const e=this.runDir(t.run_id),r=l(e,"run.json"),i=l(e,`run.json.tmp-${o().pid}-${De++}`);try{await o().mkdir(e,{recursive:!0}),await h(i,(new TextEncoder).encode(JSON.stringify(t,null,2)))}catch(s){throw n.XllmError.storage(`write ${i}: ${c(s)}`)}try{await o().rename(i,r)}catch(s){throw n.XllmError.storage(`commit ${r}: ${c(s)}`)}try{await f(e)}catch(s){throw n.XllmError.storage(`sync ${e}: ${c(s)}`)}}async readRecord(t){const e=l(this.runDir(t),"run.json");let i,a;try{i=await o().readTextFile(e)}catch(d){if(s(d))throw new n.XllmError({kind:"run_not_found",run_id:t,runs_dir:this.dir});throw n.XllmError.storage(`read ${e}: ${c(d)}`)}try{a=JSON.parse(i)}catch(d){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:c(d)})}const u=a;if((null==u?void 0:u.version)!==r.RUN_RECORD_VERSION)throw n.XllmError.notResumable(t,"unsupported run record version");if("string"!=typeof u.run_id||"string"!=typeof u.status||"object"!=typeof u.config||"object"!=typeof u.prompt)throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:"run.json unreadable: missing run_id / status / config / prompt"});return a}async listRecords(){const t=[];let e;try{e=o().readDir(this.dir);for await(const n of e)if(n.isDirectory)try{const e=JSON.parse(await o().readTextFile(l(this.dir,n.name,"run.json")));e&&"string"==typeof e.run_id&&t.push(e)}catch{}}catch(r){if(s(r))return t;throw n.XllmError.storage(`read runs directory ${this.dir}: ${c(r)}`)}return t}async putSnapshot(t,e){const r=l(this.runDir(t),"snapshots");try{await o().mkdir(r,{recursive:!0});const n=await this.listSnapshots(t),i=n.length?n[n.length-1]+1:1,s=l(r,`${je(i)}.json`),a=l(r,`${je(i)}.json.tmp`);return await h(a,(new TextEncoder).encode(JSON.stringify(e))),await o().rename(a,s),await f(r),i}catch(i){if(i instanceof n.XllmError)throw i;throw n.XllmError.storage(`write snapshot of ${t}: ${c(i)}`)}}async getSnapshot(t,e){const r=l(this.runDir(t),"snapshots",`${je(e)}.json`);let i;try{i=await o().readTextFile(r)}catch(s){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${e} missing at ${r}: ${c(s)}`})}try{return JSON.parse(i)}catch(s){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${e} unreadable: ${c(s)}`})}}async listSnapshots(t){const e=l(this.runDir(t),"snapshots"),n=[];try{for await(const t of o().readDir(e)){const e=/^(\d+)\.json$/.exec(t.name);e&&n.push(Number(e[1]))}}catch(r){if(s(r))return[];throw r}return n.sort(((t,e)=>t-e))}lockRun(t){return Pe.tryAcquire(l(this.runDir(t),".lock"))}async isRunLive(t){return!!(await d(this.runDir(t)))&&Re(l(this.runDir(t),".lock"))}async removeRun(t){const e=this.runDir(t);try{await o().remove(e,{recursive:!0})}catch(r){if(!s(r))throw n.XllmError.storage(`remove ${e}: ${c(r)}`)}await f(this.dir).catch((()=>{}))}async importRun(t){const e=t.record.run_id;if(await this.isRunLive(e))throw new n.XllmError({kind:"run_busy",run_id:e});const r=this.runDir(e);await o().mkdir(l(r,"snapshots"),{recursive:!0});for(const[n,i]of t.snapshots){const t=l(r,"snapshots",`${je(n)}.json`),e=`${t}.tmp`;await h(e,(new TextEncoder).encode(JSON.stringify(i))),await o().rename(e,t)}await f(l(r,"snapshots")),await this.writeRecord(t.record)}}function Me(t=Te){const e=Ae(t,o().cwd());return async(t,n)=>{const r=await Pe.tryAcquire(ot(e,t));return r&&await o().writeTextFile(r.path,`${n}\n`).catch((()=>{})),r}}function Ne(t){return d(t)}const Ue="BUCKYOS_APPCLIENT_SESSION_TOKEN";async function Ce(t){if("env"===t.kind){const e=o().env.get(t.name);if(void 0===e)throw n.XllmError.capability(`environment variable \`${t.name}\` is not set`);return e}let e,r;try{e=await o().readTextFile(t.path)}catch(s){throw n.XllmError.capability(`cannot re-read credential source ${t.path}:${t.field}: ${c(s)}`)}try{r=JSON.parse(e)}catch(s){throw n.XllmError.capability(`cannot parse credential source ${t.path} (the Deno host reads JSON configuration): ${c(s)}`)}let i=r;for(const o of t.field.split(".")){if(!n.isObject(i)||!(o in i))throw n.XllmError.capability(`credential field \`${t.field}\` no longer exists in ${t.path}`);i=i[o]}if("string"!=typeof i||!i.trim())throw n.XllmError.capability(`credential field \`${t.field}\` in ${t.path} is empty or not a string`);return i}function Fe(t){return{async infer(){throw n.providerError({refused:{code:r.REFUSED_CREDENTIALS}},t)}}}async function He(t){var e,r,s;if("openai"===(t.kind??"buckyos")){const e=t.api_key?await Ce(t.api_key):o().env.get("OPENAI_API_KEY");if(!(null==e?void 0:e.trim()))throw n.XllmError.capability("openai provider: no API key; set `provider.api_key`, `provider.api_key_env` or the OPENAI_API_KEY environment variable");return new i.OpenAiLlmClient({baseUrl:t.base_url,apiKey:e,headers:t.headers})}if(void 0!==t.on_behalf_of&&null!==t.on_behalf_of)throw n.XllmError.capability("buckyos provider: `on_behalf_of` (a system service paying for a user) is not available on the Deno host");const a=t.session_token?await Ce(t.session_token):null==(e=o().env.get(Ue))?void 0:e.trim();if(!a)return Fe(`buckyos provider: no BuckyOS session on this host (set ${Ue}), sign in and resume`);const l=(null==(r=o().env.get("BUCKYOS_APP_ID"))?void 0:r.trim())||"buckycli",u=new((await async function(){const t=new URL("./node.mjs",self.location).href;return await import(t)}()).BuckyOSSDK)("node");try{await u.initBuckyOS(l,{zoneHost:(null==(s=o().env.get("BUCKYOS_ZONE_HOST"))?void 0:s.trim())??"",appId:l,defaultProtocol:"https://",runtimeType:"AppClient",sessionToken:a,privateKeySearchPaths:[],autoRenew:!1})}catch(d){throw n.XllmError.capability(`buckyos provider: cannot initialize the BuckyOS runtime (check zone/session setup): ${c(d)}`)}return new n.AiccLlmClient(u.getAiccClient())}function Be(t,e,n,r={}){const i={llm:n,runtime:t,store:e,pid:o().pid,lockWorkdir:Me(r.lockDir),workdirExists:Ne};return r.observer&&(i.observer=r.observer),r.tokenizer&&(i.tokenizer=r.tokenizer),i}const ze={infer(){throw n.XllmError.other("the model client is created after the task is prepared")}};function qe(t){const e=t instanceof n.XllmError?t:n.XllmError.capability(t instanceof Error?t.message:String(t)),r=()=>{throw e},i=()=>Promise.reject(e);return{descriptor:r,config:r,info:i,open:i,describeInterrupted:i}}exports.BASH_GROUP_TOOLS=ut,exports.DEFAULT_LOCK_DIR=Te,exports.DEFAULT_RUNS_DIR=Se,exports.EDIT_FILE_SPEC=zt,exports.EXEC_MAX_OUTPUT_BYTES=dt,exports.FileLock=Pe,exports.FileRunStore=Xe,exports.HOST_ID_ENV=K,exports.LOCAL_PROBE=pe,exports.NATIVE_KIND=me,exports.NATIVE_WRAPPER=Yt,exports.NativeToolManager=be,exports.READ_FILE_SPEC=Ht,exports.SESSION_TOKEN_ENV=Ue,exports.WRITE_FILE_SPEC=Bt,exports.blake3Hex=Y,exports.createLlmClient=He,exports.createNativeRuntime=xe,exports.credentialsRefusedClient=Fe,exports.deriveRuntimeId=rt,exports.execDirFor=te,exports.fmtElapsed=ee,exports.interruptedShellText=Ie,exports.isLocked=Re,exports.localProbe=ge,exports.nativeDeps=Be,exports.nativeDescriptor=$e,exports.nativeHostId=tt,exports.nativeHostIdFrom=Q,exports.nativeTarget=et,exports.parseProbe=we,exports.prepareNativeTask=async function(t,e,n,i,o={}){const s=r.mergeConfigLayers([{path:e,file:r.parseLlmContextJson(e,t??null)}]),a=await xe({config:s.runtime,workdir:o.workdir});let c=o.store;if(!c){const t=Le(s.runs_dir,e);c=void 0===t?new r.MemoryRunStore:new Xe(t)}const l=Be(a,c,o.llm??ze,o),u=await r.XllmTask.prepare(t,e,n,i,l);return{task:u,deps:{...l,llm:o.llm??await He(u.config.provider)}}},exports.readExecDir=Ee,exports.resolveHostPath=Ae,exports.resolveSecret=Ce,exports.resumeNativeRun=async function(t,e,i={},o={}){const s=await t.readRecord(e);let a,c=o.llm;if(r.isTerminal(s.status))a=qe(n.XllmError.other("a terminal run is not executed"));else{try{a=await xe({config:s.config.runtime,workdir:s.workdir,takeover:{run_id:s.run_id,tools:s.config.tools}})}catch(l){a=qe(l)}c=c??await He(s.config.provider)}return r.XllmRun.resume(t,e,i,Be(a,t,c??ze,o))},exports.runsDirOf=Le,exports.runtimeIdOf=it,exports.sanitizeCallId=Qt,exports.shellSpec=le,exports.targetText=nt,exports.workdirExists=Ne,exports.workdirLockPath=ot,exports.workdirLocker=Me;
2
2
  //# sourceMappingURL=xllm_deno.cjs.map
@@ -5,7 +5,7 @@ var __publicField = (obj, key, value) => {
5
5
  return value;
6
6
  };
7
7
  import { n as canonicalJson, i as isObject, X as XllmError, m as cloneJson, p as providerError, A as AiccLlmClient } from "./aicc-67851c41.mjs";
8
- import { aB as normalizePath, aq as MemoryHintLedger, ao as HINT_NS_DEDUP, T as ToolDispatchException, ab as toHost, ay as taskStateObservation, a6 as envelopeObservation, ar as applyHints, aC as PLANNED_RUNTIME_KINDS, s as shellSettings, aD as BUILTIN_TOOL_GROUP_BASH, u as unresolvedReason, d as describeToolSource, aE as BUILTIN_TOOL_GROUP_BASH_CORE, aF as resolveConfigPath, g as generateRunId, R as RUN_RECORD_VERSION, Y as REFUSED_CREDENTIALS, q as mergeConfigLayers, w as parseLlmContextJson, G as MemoryRunStore, $ as XllmTask, a2 as isTerminal, _ as XllmRun } from "./site_manager-11a7a468.mjs";
8
+ import { aB as normalizePath, aq as MemoryHintLedger, ao as HINT_NS_DEDUP, T as ToolDispatchException, ab as toHost, ay as taskStateObservation, a6 as envelopeObservation, ar as applyHints, aC as PLANNED_RUNTIME_KINDS, s as shellSettings, aD as BUILTIN_TOOL_GROUP_BASH, u as unresolvedReason, d as describeToolSource, aE as BUILTIN_TOOL_GROUP_BASH_CORE, aF as resolveConfigPath, g as generateRunId, R as RUN_RECORD_VERSION, Y as REFUSED_CREDENTIALS, q as mergeConfigLayers, w as parseLlmContextJson, G as MemoryRunStore, $ as XllmTask, a2 as isTerminal, _ as XllmRun } from "./site_manager-8adb478e.mjs";
9
9
  import { O as OpenAiLlmClient } from "./openai-ae2978de.mjs";
10
10
  import "./krpc_client-673448e5.mjs";
11
11
  function deno() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "buckyos",
3
- "version": "0.7.185",
3
+ "version": "0.7.187",
4
4
  "description": "BuckyOS WebSDK for browser and Node.js environments",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {