@draht/coding-agent 2026.11.14 → 2026.11.18-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/bundle/chunks/{anthropic-messages-FKSSTO6N.js → anthropic-messages-AFT3AY2S.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-AHIW4IRP.js → azure-openai-responses-A52AJ5P5.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +21 -21
  5. package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
  6. package/dist/bundle/chunks/chunk-2XOICIOV.js +9 -0
  7. package/dist/bundle/chunks/{chunk-G7DJ6PIU.js → chunk-4FPBO5KP.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-XEVRP72T.js → chunk-5PDANNKW.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-46NQOOTO.js → chunk-6EVZEBYO.js} +1 -1
  10. package/dist/bundle/chunks/chunk-6M3D4XVD.js +2 -0
  11. package/dist/bundle/chunks/{chunk-KVH4HR57.js → chunk-6WESOD4H.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-NLVN7RG3.js → chunk-ACQFXG5D.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-NJDELBDB.js → chunk-CAOOVEOM.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-PPJRJAR3.js → chunk-CP35SXCN.js} +30 -31
  15. package/dist/bundle/chunks/{chunk-GR3JEDCL.js → chunk-CXCOVS2M.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-5K3TBDND.js → chunk-GAABJAG4.js} +3 -3
  17. package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
  18. package/dist/bundle/chunks/{chunk-ITP6IDBA.js → chunk-GQXRTK54.js} +2 -2
  19. package/dist/bundle/chunks/{chunk-ROB5AWV5.js → chunk-HTSLUWLE.js} +3 -3
  20. package/dist/bundle/chunks/{chunk-RIPTEKPX.js → chunk-JMYX7QEX.js} +8 -8
  21. package/dist/bundle/chunks/{chunk-QVGSXIKT.js → chunk-KFREX3FS.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-ZZAOELWU.js → chunk-LKMWSNTE.js} +1 -1
  23. package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
  24. package/dist/bundle/chunks/{chunk-4ALYWMDD.js → chunk-O2P5SYXT.js} +4 -3
  25. package/dist/bundle/chunks/{chunk-XY64T2H6.js → chunk-RI7HJ6AF.js} +10 -10
  26. package/dist/bundle/chunks/{chunk-DFFQ5ETM.js → chunk-TUIWJI22.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-HIL6BIBX.js → chunk-YFDWS2SA.js} +1 -1
  28. package/dist/bundle/chunks/{cli-JDGPEN7N.js → cli-L6U4GJHK.js} +1 -1
  29. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-ZPDQKK4H.js → cloudflare-workers-ai-system-one-KYAP5L2X.js} +1 -1
  30. package/dist/bundle/chunks/{execute-YOMYOVUT.js → execute-KGJOWTPG.js} +1 -1
  31. package/dist/bundle/chunks/{google-generative-ai-EEDLVZAQ.js → google-generative-ai-WR6OZ27M.js} +1 -1
  32. package/dist/bundle/chunks/{google-vertex-YQDP6U25.js → google-vertex-FUYYVM54.js} +1 -1
  33. package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
  34. package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
  35. package/dist/bundle/chunks/{llama-cpp-classify-SRUYBPZS.js → llama-cpp-classify-6LLMLBUC.js} +1 -1
  36. package/dist/bundle/chunks/{mistral-conversations-QKVAIF57.js → mistral-conversations-WVGS4PN2.js} +1 -1
  37. package/dist/bundle/chunks/{multipart-parser-AZP5BX2W.js → multipart-parser-HMCXZ4BD.js} +1 -1
  38. package/dist/bundle/chunks/{node-BZAVEWJ3.js → node-DXZFQBEO.js} +1 -1
  39. package/dist/bundle/chunks/{node-C2JGH2OB.js → node-LBZLUIBE.js} +1 -1
  40. package/dist/bundle/chunks/{openai-codex-responses-2FIT2Z3L.js → openai-codex-responses-CTLT3QUI.js} +1 -1
  41. package/dist/bundle/chunks/{openai-completions-42OND4EW.js → openai-completions-V37FD5ZZ.js} +1 -1
  42. package/dist/bundle/chunks/{openai-decisions-FAP6LRGH.js → openai-decisions-WTY6DQT4.js} +1 -1
  43. package/dist/bundle/chunks/{openai-responses-BGC7WCIQ.js → openai-responses-R7W5BVUV.js} +1 -1
  44. package/dist/bundle/chunks/{openrouter-images-EAWW57ZG.js → openrouter-images-7GGRYAYP.js} +1 -1
  45. package/dist/bundle/chunks/{pi-messages-JM6JDMH5.js → pi-messages-O7OXMCNL.js} +1 -1
  46. package/dist/bundle/chunks/{runtime-F63NCS5Y.js → runtime-73OLLYOI.js} +1 -1
  47. package/dist/bundle/chunks/{runtime-S5WBSLTE.js → runtime-FZKS2BWI.js} +1 -1
  48. package/dist/bundle/chunks/{settings-manager-H3QEOPQ3.js → settings-manager-CWRQW6PZ.js} +1 -1
  49. package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
  50. package/dist/bundle/chunks/{typesafe-system-one-QOA2PTJR.js → typesafe-system-one-FGISCLX2.js} +1 -1
  51. package/dist/bundle/chunks/{virtual-modules-2BURZRW7.js → virtual-modules-JL2BFG57.js} +1 -1
  52. package/dist/bundle/cli-runtime.js +1 -1
  53. package/dist/bundle/index.js +1 -1
  54. package/dist/bundle/rpc-entry.js +1 -1
  55. package/dist/extensions/mcp/index.d.ts.map +1 -1
  56. package/dist/extensions/mcp/index.js +4 -7
  57. package/dist/extensions/mcp/index.js.map +1 -1
  58. package/package.json +9 -9
  59. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +0 -6
  60. package/dist/bundle/chunks/chunk-736QBNUZ.js +0 -12
  61. package/dist/bundle/chunks/chunk-BIBUE2PO.js +0 -2
  62. package/dist/bundle/chunks/chunk-NLYBRJ3F.js +0 -9
  63. package/dist/bundle/chunks/chunk-TIA2T6EO.js +0 -3
  64. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +0 -13
  65. package/dist/bundle/chunks/lib-XOG5PI3Y.js +0 -9
  66. package/dist/bundle/chunks/src-TIBHS42X.js +0 -4
  67. /package/dist/bundle/chunks/{chunk-OPLOTJXH.js → chunk-ATYP3OSV.js} +0 -0
  68. /package/dist/bundle/chunks/{chunk-PX3CDFUB.js → chunk-ITKDPD4D.js} +0 -0
  69. /package/dist/bundle/chunks/{chunk-ZZD35WKM.js → chunk-MOOADNVS.js} +0 -0
@@ -0,0 +1,3 @@
1
+ import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
+ import{__commonJS,__require}from"./chunk-HZ2UHMBT.js";var require_polyfills=__commonJS({"node_modules/.bun/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js"(exports,module){var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch{}typeof process.chdir=="function"&&(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,chdir));var chdir;module.exports=patch;function patch(fs){constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&patchLchmod(fs),fs.lutimes||patchLutimes(fs),fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.chmod&&!fs.lchmod&&(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){}),fs.chown&&!fs.lchown&&(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){}),platform==="win32"&&(fs.rename=typeof fs.rename!="function"?fs.rename:(function(fs$rename){function rename(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<6e4){setTimeout(function(){fs.stat(to,function(stater,st){stater&&stater.code==="ENOENT"?fs$rename(from,to,CB):cb(er)})},backoff),backoff<100&&(backoff+=10);return}cb&&cb(er)})}return Object.setPrototypeOf&&Object.setPrototypeOf(rename,fs$rename),rename})(fs.rename)),fs.read=typeof fs.read!="function"?fs.read:(function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_=="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}return Object.setPrototypeOf&&Object.setPrototypeOf(read,fs$read),read})(fs.read),fs.readSync=typeof fs.readSync!="function"?fs.readSync:(function(fs$readSync){return function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}})(fs.readSync);function patchLchmod(fs2){fs2.lchmod=function(path,mode,callback){fs2.open(path,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){callback&&callback(err);return}fs2.fchmod(fd,mode,function(err2){fs2.close(fd,function(err22){callback&&callback(err2||err22)})})})},fs2.lchmodSync=function(path,mode){var fd=fs2.openSync(path,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs2.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}}function patchLutimes(fs2){constants.hasOwnProperty("O_SYMLINK")&&fs2.futimes?(fs2.lutimes=function(path,at,mt,cb){fs2.open(path,constants.O_SYMLINK,function(er,fd){if(er){cb&&cb(er);return}fs2.futimes(fd,at,mt,function(er2){fs2.close(fd,function(er22){cb&&cb(er2||er22)})})})},fs2.lutimesSync=function(path,at,mt){var fd=fs2.openSync(path,constants.O_SYMLINK),ret,threw=!0;try{ret=fs2.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}):fs2.futimes&&(fs2.lutimes=function(_a,_b,_c,cb){cb&&process.nextTick(cb)},fs2.lutimesSync=function(){})}function chmodFix(orig){return orig&&function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chmodFixSync(orig){return orig&&function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){return orig&&function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chownFixSync(orig){return orig&&function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){return orig&&function(target,options,cb){typeof options=="function"&&(cb=options,options=null);function callback(er,stats){stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),cb&&cb.apply(this,arguments)}return options?orig.call(fs,target,options,callback):orig.call(fs,target,callback)}}function statFixSync(orig){return orig&&function(target,options){var stats=options?orig.call(fs,target,options):orig.call(fs,target);return stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),stats}}function chownErOk(er){if(!er||er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;return!!(nonroot&&(er.code==="EINVAL"||er.code==="EPERM"))}}}});var require_legacy_streams=__commonJS({"node_modules/.bun/graceful-fs@4.2.11/node_modules/graceful-fs/legacy-streams.js"(exports,module){var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs){return{ReadStream,WriteStream};function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}}});var require_clone=__commonJS({"node_modules/.bun/graceful-fs@4.2.11/node_modules/graceful-fs/clone.js"(exports,module){"use strict";module.exports=clone;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone(obj){if(obj===null||typeof obj!="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}}});var require_graceful_fs=__commonJS({"node_modules/.bun/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js"(exports,module){var fs=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;typeof Symbol=="function"&&typeof Symbol.for=="function"?(gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous")):(gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous");function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
3
+ GFS4: `),console.error(m)});fs[gracefulQueue]||(queue=global[gracefulQueue]||[],publishQueue(fs,queue),fs.close=(function(fs$close){function close(fd,cb){return fs$close.call(fs,fd,function(err){err||resetQueue(),typeof cb=="function"&&cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close})(fs.close),fs.closeSync=(function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync})(fs.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(fs[gracefulQueue]),__require("assert").equal(fs[gracefulQueue].length,0)}));var queue;global[gracefulQueue]||publishQueue(global,fs[gracefulQueue]);module.exports=patch(clone(fs));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs.__patched&&(module.exports=patch(fs),fs.__patched=!0);function patch(fs2){polyfills(fs2),fs2.gracefulify=patch,fs2.createReadStream=createReadStream,fs2.createWriteStream=createWriteStream;var fs$readFile=fs2.readFile;fs2.readFile=readFile;function readFile(path,options,cb){return typeof options=="function"&&(cb=options,options=null),go$readFile(path,options,cb);function go$readFile(path2,options2,cb2,startTime){return fs$readFile(path2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readFile,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$writeFile=fs2.writeFile;fs2.writeFile=writeFile;function writeFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$writeFile(path,data,options,cb);function go$writeFile(path2,data2,options2,cb2,startTime){return fs$writeFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$writeFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$appendFile=fs2.appendFile;fs$appendFile&&(fs2.appendFile=appendFile);function appendFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$appendFile(path,data,options,cb);function go$appendFile(path2,data2,options2,cb2,startTime){return fs$appendFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$appendFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$copyFile=fs2.copyFile;fs$copyFile&&(fs2.copyFile=copyFile);function copyFile(src,dest,flags,cb){return typeof flags=="function"&&(cb=flags,flags=0),go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$readdir=fs2.readdir;fs2.readdir=readdir;var noReaddirOptionVersions=/^v[0-5]\./;function readdir(path,options,cb){typeof options=="function"&&(cb=options,options=null);var go$readdir=noReaddirOptionVersions.test(process.version)?function(path2,options2,cb2,startTime){return fs$readdir(path2,fs$readdirCallback(path2,options2,cb2,startTime))}:function(path2,options2,cb2,startTime){return fs$readdir(path2,options2,fs$readdirCallback(path2,options2,cb2,startTime))};return go$readdir(path,options,cb);function fs$readdirCallback(path2,options2,cb2,startTime){return function(err,files){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readdir,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):(files&&files.sort&&files.sort(),typeof cb2=="function"&&cb2.call(this,err,files))}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs2);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs2.ReadStream;fs$ReadStream&&(ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open);var fs$WriteStream=fs2.WriteStream;fs$WriteStream&&(WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open),Object.defineProperty(fs2,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs2,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs2,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs2,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}function createReadStream(path,options){return new fs2.ReadStream(path,options)}function createWriteStream(path,options){return new fs2.WriteStream(path,options)}var fs$open=fs2.open;fs2.open=open;function open(path,flags,mode,cb){return typeof mode=="function"&&(cb=mode,mode=null),go$open(path,flags,mode,cb);function go$open(path2,flags2,mode2,cb2,startTime){return fs$open(path2,flags2,mode2,function(err,fd){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$open,[path2,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}return fs2}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){for(var now=Date.now(),i=0;i<fs[gracefulQueue].length;++i)fs[gracefulQueue][i].length>2&&(fs[gracefulQueue][i][3]=now,fs[gracefulQueue][i][4]=now);retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs[gracefulQueue].length!==0){var elem=fs[gracefulQueue].shift(),fn=elem[0],args=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn.name,args),fn.apply(null,args);else if(Date.now()-startTime>=6e4){debug("TIMEOUT",fn.name,args);var cb=args.pop();typeof cb=="function"&&cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);sinceAttempt>=desiredDelay?(debug("RETRY",fn.name,args),fn.apply(null,args.concat([startTime]))):fs[gracefulQueue].push(elem)}retryTimer===void 0&&(retryTimer=setTimeout(retry,0))}}}});var require_retry_operation=__commonJS({"node_modules/.bun/retry@0.12.0/node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){self._attempts++,self._operationTimeoutCb&&(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref&&self._timeout.unref()),self._fn(self._attempts)},timeout);return this._options.unref&&timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/.bun/retry@0.12.0/node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/.bun/retry@0.12.0/node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_signals=__commonJS({"node_modules/.bun/signal-exit@3.0.7/node_modules/signal-exit/signals.js"(exports,module){module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}});var require_signal_exit=__commonJS({"node_modules/.bun/signal-exit@3.0.7/node_modules/signal-exit/index.js"(exports,module){var process2=global.process,processOk=function(process3){return process3&&typeof process3=="object"&&typeof process3.removeListener=="function"&&typeof process3.emit=="function"&&typeof process3.reallyExit=="function"&&typeof process3.listeners=="function"&&typeof process3.kill=="function"&&typeof process3.pid=="number"&&typeof process3.on=="function"};processOk(process2)?(assert=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process2.platform),EE=__require("events"),typeof EE!="function"&&(EE=EE.EventEmitter),process2.__signal_exit_emitter__?emitter=process2.__signal_exit_emitter__:(emitter=process2.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={}),emitter.infinite||(emitter.setMaxListeners(1/0),emitter.infinite=!0),module.exports=function(cb,opts){if(!processOk(global.process))return function(){};assert.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1&&load();var ev="exit";opts&&opts.alwaysLast&&(ev="afterexit");var remove=function(){emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0&&unload()};return emitter.on(ev,cb),remove},unload=function(){!loaded||!processOk(global.process)||(loaded=!1,signals.forEach(function(sig){try{process2.removeListener(sig,sigListeners[sig])}catch{}}),process2.emit=originalProcessEmit,process2.reallyExit=originalProcessReallyExit,emitter.count-=1)},module.exports.unload=unload,emit=function(event,code,signal){emitter.emitted[event]||(emitter.emitted[event]=!0,emitter.emit(event,code,signal))},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(processOk(global.process)){var listeners=process2.listeners(sig);listeners.length===emitter.count&&(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP"&&(sig="SIGINT"),process2.kill(process2.pid,sig))}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){loaded||!processOk(global.process)||(loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process2.on(sig,sigListeners[sig]),!0}catch{return!1}}),process2.emit=processEmit,process2.reallyExit=processReallyExit)},module.exports.load=load,originalProcessReallyExit=process2.reallyExit,processReallyExit=function(code){processOk(global.process)&&(process2.exitCode=code||0,emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),originalProcessReallyExit.call(process2,process2.exitCode))},originalProcessEmit=process2.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){arg!==void 0&&(process2.exitCode=arg);var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}):module.exports=function(){return function(){}};var assert,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit}});var require_mtime_precision=__commonJS({"node_modules/.bun/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/mtime-precision.js"(exports,module){"use strict";var cacheSymbol=Symbol();function probe(file,fs,callback){let cachedPrecision=fs[cacheSymbol];if(cachedPrecision)return fs.stat(file,(err,stat)=>{if(err)return callback(err);callback(null,stat.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1e3)*1e3+5);fs.utimes(file,mtime,mtime,err=>{if(err)return callback(err);fs.stat(file,(err2,stat)=>{if(err2)return callback(err2);let precision=stat.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(fs,cacheSymbol,{value:precision}),callback(null,stat.mtime,precision)})})}function getMtime(precision){let now=Date.now();return precision==="s"&&(now=Math.ceil(now/1e3)*1e3),new Date(now)}module.exports.probe=probe;module.exports.getMtime=getMtime}});var require_lockfile=__commonJS({"node_modules/.bun/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js"(exports,module){"use strict";var path=__require("path"),fs=require_graceful_fs(),retry=require_retry2(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file,options){return options.lockfilePath||`${file}.lock`}function resolveCanonicalPath(file,options,callback){if(!options.realpath)return callback(null,path.resolve(file));options.fs.realpath(file,callback)}function acquireLock(file,options,callback){let lockfilePath=getLockFile(file,options);options.fs.mkdir(lockfilePath,err=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));options.fs.stat(lockfilePath,(err2,stat)=>{if(err2)return err2.code==="ENOENT"?acquireLock(file,{...options,stale:0},callback):callback(err2);if(!isLockStale(stat,options))return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));removeLock(file,options,err3=>{if(err3)return callback(err3);acquireLock(file,{...options,stale:0},callback)})})})}function isLockStale(stat,options){return stat.mtime.getTime()<Date.now()-options.stale}function removeLock(file,options,callback){options.fs.rmdir(getLockFile(file,options),err=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file,options){let lock2=locks[file];lock2.updateTimeout||(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err)return err.code==="ENOENT"||isOverThreshold?setLockAsCompromised(file,lock2,Object.assign(err,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));if(!(lock2.mtime.getTime()===stat.mtime.getTime()))return setLockAsCompromised(file,lock2,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,err2=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(!lock2.released){if(err2)return err2.code==="ENOENT"||isOverThreshold2?setLockAsCompromised(file,lock2,Object.assign(err2,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file,options)}})})},lock2.updateDelay),lock2.updateTimeout.unref&&lock2.updateTimeout.unref())}function setLockAsCompromised(file,lock2,err){lock2.released=!0,lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),locks[file]===lock2&&delete locks[file],lock2.options.onCompromised(err)}function lock(file,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs,onCompromised:err=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries=="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2e3),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file2,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file2]={lockfilePath:getLockFile(file2,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file2,options),callback(null,releasedCallback=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));unlock(file2,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file,options,callback){options={fs,realpath:!0,...options},resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let lock2=locks[file2];if(!lock2)return callback(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file2],removeLock(file2,options,callback)})}function check(file,options,callback){options={stale:1e4,realpath:!0,fs,...options},options.stale=Math.max(options.stale||0,2e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);options.fs.stat(getLockFile(file2,options),(err2,stat)=>err2?err2.code==="ENOENT"?callback(null,!1):callback(err2):callback(null,!isLockStale(stat,options)))})}function getLocks(){return locks}onExit(()=>{for(let file in locks){let options=locks[file].options;try{options.fs.rmdirSync(getLockFile(file,options))}catch{}}});module.exports.lock=lock;module.exports.unlock=unlock;module.exports.check=check;module.exports.getLocks=getLocks}});var require_adapter=__commonJS({"node_modules/.bun/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/adapter.js"(exports,module){"use strict";var fs=require_graceful_fs();function createSyncFs(fs2){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs2};return methods.forEach(method=>{newFs[method]=(...args)=>{let callback=args.pop(),ret;try{ret=fs2[`${method}Sync`](...args)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args)=>new Promise((resolve,reject)=>{args.push((err,result)=>{err?reject(err):resolve(result)}),method(...args)})}function toSync(method){return(...args)=>{let err,result;if(args.push((_err,_result)=>{err=_err,result=_result}),method(...args),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs),typeof options.retries=="number"&&options.retries>0||options.retries&&typeof options.retries.retries=="number"&&options.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}}});var require_proper_lockfile=__commonJS({"node_modules/.bun/proper-lockfile@4.1.2/node_modules/proper-lockfile/index.js"(exports,module){"use strict";var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file,options){let release=await toPromise(lockfile.lock)(file,options);return toPromise(release)}function lockSync(file,options){let release=toSync(lockfile.lock)(file,toSyncOptions(options));return toSync(release)}function unlock(file,options){return toPromise(lockfile.unlock)(file,options)}function unlockSync(file,options){return toSync(lockfile.unlock)(file,toSyncOptions(options))}function check(file,options){return toPromise(lockfile.check)(file,options)}function checkSync(file,options){return toSync(lockfile.check)(file,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check;module.exports.checkSync=checkSync}});export{require_proper_lockfile};
@@ -0,0 +1,9 @@
1
+ import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
+ function contentText(content,separator=`
3
+ `){return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(separator)}function getSystemMessageText(message){let parts=[contentText(message.content)];for(let text of Object.values(message.sections??{}))text!==null&&parts.push(text);return parts.filter(part=>part.length>0).join(`
4
+
5
+ `)}function renderSystemMessageUpdate(message){let parts=[],text=contentText(message.content);text.length>0&&parts.push(text);for(let[name,value]of Object.entries(message.sections??{}))parts.push(value===null?`Removed system prompt section "${name}".`:`Updated system prompt section "${name}":
6
+
7
+ ${value}`);return parts.join(`
8
+
9
+ `)}function ownedSlice(text,start,end=text.length){return`${text.slice(start,end)} `.slice(0,-1)}var DRAHT_AI_VERSION="2026.11.18-1";var DRAHT_ATTRIBUTION={name:"draht",url:"https://github.com/draht-dev/draht",categories:["cli-agent"]},NVIDIA_NIM_HOST="integrate.api.nvidia.com",OPENCODE_HOST="opencode.ai";function mergeClientIdentity(...sources){let merged;for(let source of sources)source&&(merged={...merged},source.userAgent!==void 0&&(merged.userAgent=source.userAgent),source.attribution!==void 0&&(merged.attribution=source.attribution),source.version!==void 0&&(merged.version=source.version));return merged}function getClientVersion(identity){return identity?.version??DRAHT_AI_VERSION}function runtimeDescription(){if(typeof process>"u")return;let versions=process.versions;if(versions?.bun)return`bun/${versions.bun}`;if(versions?.node)return`node/${process.version}`}function formatUserAgent(identity){let mode=identity?.userAgent??"detailed";if(typeof mode=="object")return mode.custom;if(mode==="short")return"draht";let product=`draht/${getClientVersion(identity)}`,runtime=runtimeDescription();return runtime?`${product} (${process.platform}; ${runtime}; ${process.arch})`:`${product} (browser)`}function matchesHost(baseUrl,expectedHost){try{return new URL(baseUrl).hostname===expectedHost}catch{return!1}}function isOpenRouter(target){return target.provider==="openrouter"||target.baseUrl.includes("openrouter.ai")}function isNvidiaNim(target){return target.provider==="nvidia"||matchesHost(target.baseUrl,NVIDIA_NIM_HOST)}function isOpenCode(target){return target.provider==="opencode"||target.provider==="opencode-go"||matchesHost(target.baseUrl,OPENCODE_HOST)}function getAttributionHeaders(target,identity){let attribution=identity?.attribution;if(!attribution)return{};let{name,url,categories}=attribution;return isOpenRouter(target)?{"HTTP-Referer":url,"X-OpenRouter-Title":name,...categories===void 0||categories.length===0?{}:{"X-OpenRouter-Categories":categories.join(",")}}:isNvidiaNim(target)?{"X-BILLING-INVOKE-ORIGIN":name.charAt(0).toUpperCase()+name.slice(1)}:isOpenCode(target)?{"x-opencode-client":name}:{}}function getOpenCodeSessionHeaders(target,sessionId){return sessionId&&isOpenCode(target)?{"x-opencode-session":sessionId}:void 0}function getIdentityHeaders(target,identity){return{"User-Agent":formatUserAgent(identity),...getAttributionHeaders(target,identity)}}function isMutableModels(models){return"setProvider"in models&&"deleteProvider"in models&&"clearProviders"in models}function withClientIdentity(models,identity){let withIdentity=options=>({...options,identity:mergeClientIdentity(identity,options?.identity)}),wrapped={getProviders:()=>models.getProviders(),getProvider:id=>models.getProvider(id),getModels:provider=>models.getModels(provider),getModel:(provider,id)=>models.getModel(provider,id),getModelsOfType:(type,provider)=>models.getModelsOfType(type,provider),getModelOfType:(type,provider,id)=>models.getModelOfType(type,provider,id),getAllModels:provider=>models.getAllModels(provider),refresh:options=>models.refresh(options),checkAuth:(providerId,options)=>models.checkAuth(providerId,options),getAvailable:(providerId,options)=>models.getAvailable(providerId,options),getAvailableOfType:(type,providerId,options)=>models.getAvailableOfType(type,providerId,options),getAllAvailable:(providerId,options)=>models.getAllAvailable(providerId,options),getAuth:models.getAuth.bind(models),login:(providerId,type,interaction,options)=>models.login(providerId,type,interaction,options),logout:(providerId,options)=>models.logout(providerId,options),stream:(model,context,options)=>models.stream(model,context,withIdentity(options)),complete:(model,context,options)=>models.complete(model,context,withIdentity(options)),streamSimple:(model,context,options)=>models.streamSimple(model,context,withIdentity(options)),completeSimple:(model,context,options)=>models.completeSimple(model,context,withIdentity(options)),streamDeferred:(model,handle,options)=>models.streamDeferred(model,handle,withIdentity(options)),fetchDeferred:(model,handle,options)=>models.fetchDeferred(model,handle,withIdentity(options)),cancelDeferred:(model,handle,options)=>models.cancelDeferred(model,handle,withIdentity(options)),generateImages:(model,context,options)=>models.generateImages(model,context,withIdentity(options)),classify:(model,context,options)=>models.classify(model,context,withIdentity(options))};return isMutableModels(models)?{...wrapped,setProvider:provider=>models.setProvider(provider),deleteProvider:id=>models.deleteProvider(id),clearProviders:()=>models.clearProviders()}:wrapped}export{contentText,getSystemMessageText,renderSystemMessageUpdate,ownedSlice,DRAHT_AI_VERSION,DRAHT_ATTRIBUTION,mergeClientIdentity,getClientVersion,formatUserAgent,getAttributionHeaders,getOpenCodeSessionHeaders,getIdentityHeaders,withClientIdentity};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{getBinDir}from"./chunk-BIBUE2PO.js";import{accessSync,constants}from"node:fs";import{delimiter,join,win32}from"node:path";import{spawn,spawnSync}from"child_process";function isLegacyWslBashPath(path){let normalized=win32.normalize(path).toLowerCase(),systemRoot=process.env.SystemRoot;return systemRoot?/^[a-z]:[\\/]/i.test(systemRoot)?["System32","Sysnative"].some(directory=>normalized===win32.join(systemRoot,directory,"bash.exe").toLowerCase()):!1:/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin"}:{shell,args:["-c"]}}function shellPathExists(path){try{return accessSync(path,constants.F_OK),!0}catch{return!1}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync("where",[executable],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch&&shellPathExists(firstMatch))return firstMatch}}catch{}return null}try{let result=spawnSync("which",[executable],{encoding:"utf-8",timeout:5e3});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch)return firstMatch}}catch{}return null}function getShellConfig(customShellPath){if(customShellPath){if(shellPathExists(customShellPath))return getBashShellConfig(customShellPath);throw new Error(`Custom shell path not found: ${customShellPath}`)}if(process.platform==="win32"){let paths=[],programFiles=process.env.ProgramFiles;programFiles&&paths.push(`${programFiles}\\Git\\bin\\bash.exe`);let programFilesX86=process.env["ProgramFiles(x86)"];programFilesX86&&paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`);for(let path of paths)if(shellPathExists(path))return getBashShellConfig(path);let bashOnPath2=findExecutableOnPath("bash.exe");if(bashOnPath2)return getBashShellConfig(bashOnPath2);throw new Error(`No bash shell found. Options:
2
+ import{getBinDir}from"./chunk-6M3D4XVD.js";import{accessSync,constants}from"node:fs";import{delimiter,join,win32}from"node:path";import{spawn,spawnSync}from"child_process";function isLegacyWslBashPath(path){let normalized=win32.normalize(path).toLowerCase(),systemRoot=process.env.SystemRoot;return systemRoot?/^[a-z]:[\\/]/i.test(systemRoot)?["System32","Sysnative"].some(directory=>normalized===win32.join(systemRoot,directory,"bash.exe").toLowerCase()):!1:/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin"}:{shell,args:["-c"]}}function shellPathExists(path){try{return accessSync(path,constants.F_OK),!0}catch{return!1}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync("where",[executable],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch&&shellPathExists(firstMatch))return firstMatch}}catch{}return null}try{let result=spawnSync("which",[executable],{encoding:"utf-8",timeout:5e3});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch)return firstMatch}}catch{}return null}function getShellConfig(customShellPath){if(customShellPath){if(shellPathExists(customShellPath))return getBashShellConfig(customShellPath);throw new Error(`Custom shell path not found: ${customShellPath}`)}if(process.platform==="win32"){let paths=[],programFiles=process.env.ProgramFiles;programFiles&&paths.push(`${programFiles}\\Git\\bin\\bash.exe`);let programFilesX86=process.env["ProgramFiles(x86)"];programFilesX86&&paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`);for(let path of paths)if(shellPathExists(path))return getBashShellConfig(path);let bashOnPath2=findExecutableOnPath("bash.exe");if(bashOnPath2)return getBashShellConfig(bashOnPath2);throw new Error(`No bash shell found. Options:
3
3
  1. Install Git for Windows: https://git-scm.com/download/win
4
4
  2. Add your bash to PATH (Cygwin, MSYS2, etc.)
5
5
  3. Set shellPath in settings.json
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{shortHash}from"./chunk-HJ72RANT.js";import{appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-ZZAOELWU.js";import{sanitizeSurrogates}from"./chunk-63BK6WK2.js";import{ToolCallArgumentsStream}from"./chunk-QVGSXIKT.js";import{calculateCost,resolveTranscript,resolveTranscriptTools}from"./chunk-HIL6BIBX.js";import{getSystemMessageText,renderSystemMessageUpdate}from"./chunk-NLYBRJ3F.js";function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
2
+ import{shortHash}from"./chunk-HJ72RANT.js";import{appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-LKMWSNTE.js";import{sanitizeSurrogates}from"./chunk-63BK6WK2.js";import{ToolCallArgumentsStream}from"./chunk-KFREX3FS.js";import{calculateCost,resolveTranscript,resolveTranscriptTools}from"./chunk-YFDWS2SA.js";import{getSystemMessageText,renderSystemMessageUpdate}from"./chunk-2XOICIOV.js";function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
3
3
  `),images=content.filter(c=>c.type==="image"),hasText=textResult.trim().length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}function getResponsesToolSupport(options){return options.supportsMidConvoSystemMessages&&options.supportsAdditionalTools?"changes":options.supportsToolSearch?"additions":"none"}function renderIncrementalToolsNotice(unavailable){let notice="This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.";return unavailable.size>0?`${notice}
4
4
  Still unavailable: ${[...unavailable].join(", ")}.`:notice}function renderToolRemovalNotice(names){return`The following tools are no longer available. Do not call them:
5
5
  ${names.map(name=>`- ${name}`).join(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-GR3JEDCL.js";import{formatProviderError,normalizeProviderError}from"./chunk-NLVN7RG3.js";var IMAGE_OPT_IN_HEADERS={"TypeSafe-Danger-Zone-Images":"true"};function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.entries(context.questions)){let answer=value[id];if(!isRecord(answer))throw new Error(`${label} did not return an answer for ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${label} did not return a choice answer for ${id}`);answers.push([id,{type:"choice",choice:answer.choice,probabilities:probabilities(label,answer.probabilities,id),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else if(question.type==="score"){if(answer.type!=="score")throw new Error(`${label} did not return a score answer for ${id}`);answers.push([id,{type:"score",score:requiredNumber(label,answer.score,`score for ${id}`),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else{if(answer.type!=="noul")throw new Error(`${label} did not return a bool answer for ${id}`);answers.push([id,{type:"bool",probability:requiredNumber(label,answer.noul,`probability for ${id}`)}])}}return Object.fromEntries(answers)}var ASSET_FORMATS={"image/png":"png","image/jpeg":"jpeg"},DATA_URL_TYPES=new Set(["image/png","image/jpeg","image/webp"]),MAX_DATA_URL_IMAGES=4;function addImages(label,model,input,images,request){if(input==="images"){if(images.length>MAX_DATA_URL_IMAGES)throw new Error(`${label} accepts at most ${MAX_DATA_URL_IMAGES} images for ${model.id}, got ${images.length}`);request.images=images.map(image=>{if(!DATA_URL_TYPES.has(image.mimeType))throw new Error(`${label} accepts PNG, JPEG, and WebP images for ${model.id}, got ${image.mimeType}`);return`data:${image.mimeType};base64,${image.data}`});return}if(input==="state-image-urls"){let parts=images.map(image=>({type:"image_url",image_url:{url:`data:${image.mimeType};base64,${image.data}`}}));request.state=[...parts,request.state];return}let assets={};images.forEach((image,index)=>{let format=ASSET_FORMATS[image.mimeType];if(!format)throw new Error(`${label} accepts PNG and JPEG images for ${model.id}, got ${image.mimeType}`);assets[`<image-${index+1}>`]={type:"image",format,data_base64:image.data}}),request.assets=assets,request.state=[...Object.keys(assets),request.state]}function wireRequest(context){return{state:context.state,questions:Object.fromEntries(Object.entries(context.questions).map(([id,question])=>[id,question.type==="bool"?{...question,type:"noul"}:question]))}}async function classifySystemOne(transport,model,context,options){let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!==transport.api)throw new Error(`Unsupported classifier API: ${model.api}`);let request=wireRequest(context),requestOptions=options;if(context.images?.length){if(!model.input.includes("image"))throw new Error(`${transport.label} does not support image input for ${model.id}`);let detected=transport.detectCompat(model),imageInput=model.compat?.imageInput??detected.imageInput;addImages(transport.label,model,imageInput,context.images,request),(model.compat?.sendImageOptInHeader??detected.sendImageOptInHeader)&&(requestOptions={...options,headers:{...IMAGE_OPT_IN_HEADERS,...options?.headers}})}let body=await postClassifierRequest(transport.label,transport.url(model),model,transport.payload(model,request),requestOptions),result=transport.output(body),usage=parseClassifierUsage(result.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(transport.label,result.answers,context),output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error),`${transport.label} error`),output}}export{classifySystemOne};
2
+ import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-CXCOVS2M.js";import{formatProviderError,normalizeProviderError}from"./chunk-ACQFXG5D.js";var IMAGE_OPT_IN_HEADERS={"TypeSafe-Danger-Zone-Images":"true"};function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.entries(context.questions)){let answer=value[id];if(!isRecord(answer))throw new Error(`${label} did not return an answer for ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${label} did not return a choice answer for ${id}`);answers.push([id,{type:"choice",choice:answer.choice,probabilities:probabilities(label,answer.probabilities,id),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else if(question.type==="score"){if(answer.type!=="score")throw new Error(`${label} did not return a score answer for ${id}`);answers.push([id,{type:"score",score:requiredNumber(label,answer.score,`score for ${id}`),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else{if(answer.type!=="noul")throw new Error(`${label} did not return a bool answer for ${id}`);answers.push([id,{type:"bool",probability:requiredNumber(label,answer.noul,`probability for ${id}`)}])}}return Object.fromEntries(answers)}var ASSET_FORMATS={"image/png":"png","image/jpeg":"jpeg"},DATA_URL_TYPES=new Set(["image/png","image/jpeg","image/webp"]),MAX_DATA_URL_IMAGES=4;function addImages(label,model,input,images,request){if(input==="images"){if(images.length>MAX_DATA_URL_IMAGES)throw new Error(`${label} accepts at most ${MAX_DATA_URL_IMAGES} images for ${model.id}, got ${images.length}`);request.images=images.map(image=>{if(!DATA_URL_TYPES.has(image.mimeType))throw new Error(`${label} accepts PNG, JPEG, and WebP images for ${model.id}, got ${image.mimeType}`);return`data:${image.mimeType};base64,${image.data}`});return}if(input==="state-image-urls"){let parts=images.map(image=>({type:"image_url",image_url:{url:`data:${image.mimeType};base64,${image.data}`}}));request.state=[...parts,request.state];return}let assets={};images.forEach((image,index)=>{let format=ASSET_FORMATS[image.mimeType];if(!format)throw new Error(`${label} accepts PNG and JPEG images for ${model.id}, got ${image.mimeType}`);assets[`<image-${index+1}>`]={type:"image",format,data_base64:image.data}}),request.assets=assets,request.state=[...Object.keys(assets),request.state]}function wireRequest(context){return{state:context.state,questions:Object.fromEntries(Object.entries(context.questions).map(([id,question])=>[id,question.type==="bool"?{...question,type:"noul"}:question]))}}async function classifySystemOne(transport,model,context,options){let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!==transport.api)throw new Error(`Unsupported classifier API: ${model.api}`);let request=wireRequest(context),requestOptions=options;if(context.images?.length){if(!model.input.includes("image"))throw new Error(`${transport.label} does not support image input for ${model.id}`);let detected=transport.detectCompat(model),imageInput=model.compat?.imageInput??detected.imageInput;addImages(transport.label,model,imageInput,context.images,request),(model.compat?.sendImageOptInHeader??detected.sendImageOptInHeader)&&(requestOptions={...options,headers:{...IMAGE_OPT_IN_HEADERS,...options?.headers}})}let body=await postClassifierRequest(transport.label,transport.url(model),model,transport.payload(model,request),requestOptions),result=transport.output(body),usage=parseClassifierUsage(result.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(transport.label,result.answers,context),output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error),`${transport.label} error`),output}}export{classifySystemOne};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
+ import{__commonJS,__require,__toESM}from"./chunk-HZ2UHMBT.js";var require_windows=__commonJS({"node_modules/.bun/isexe@2.0.0/node_modules/isexe/windows.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs=__require("fs");function checkPathExt(path,options){var pathext=options.pathExt!==void 0?options.pathExt:process.env.PATHEXT;if(!pathext||(pathext=pathext.split(";"),pathext.indexOf("")!==-1))return!0;for(var i=0;i<pathext.length;i++){var p=pathext[i].toLowerCase();if(p&&path.substr(-p.length).toLowerCase()===p)return!0}return!1}function checkStat(stat,path,options){return!stat.isSymbolicLink()&&!stat.isFile()?!1:checkPathExt(path,options)}function isexe(path,options,cb){fs.stat(path,function(er,stat){cb(er,er?!1:checkStat(stat,path,options))})}function sync(path,options){return checkStat(fs.statSync(path),path,options)}}});var require_mode=__commonJS({"node_modules/.bun/isexe@2.0.0/node_modules/isexe/mode.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs=__require("fs");function isexe(path,options,cb){fs.stat(path,function(er,stat){cb(er,er?!1:checkStat(stat,options))})}function sync(path,options){return checkStat(fs.statSync(path),options)}function checkStat(stat,options){return stat.isFile()&&checkMode(stat,options)}function checkMode(stat,options){var mod=stat.mode,uid=stat.uid,gid=stat.gid,myUid=options.uid!==void 0?options.uid:process.getuid&&process.getuid(),myGid=options.gid!==void 0?options.gid:process.getgid&&process.getgid(),u=parseInt("100",8),g=parseInt("010",8),o=parseInt("001",8),ug=u|g,ret=mod&o||mod&g&&gid===myGid||mod&u&&uid===myUid||mod&ug&&myUid===0;return ret}}});var require_isexe=__commonJS({"node_modules/.bun/isexe@2.0.0/node_modules/isexe/index.js"(exports,module){var fs=__require("fs"),core;process.platform==="win32"||global.TESTING_WINDOWS?core=require_windows():core=require_mode();module.exports=isexe;isexe.sync=sync;function isexe(path,options,cb){if(typeof options=="function"&&(cb=options,options={}),!cb){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(resolve2,reject){isexe(path,options||{},function(er,is){er?reject(er):resolve2(is)})})}core(path,options||{},function(er,is){er&&(er.code==="EACCES"||options&&options.ignoreErrors)&&(er=null,is=!1),cb(er,is)})}function sync(path,options){try{return core.sync(path,options||{})}catch(er){if(options&&options.ignoreErrors||er.code==="EACCES")return!1;throw er}}}});var require_which=__commonJS({"node_modules/.bun/which@2.0.2/node_modules/which/which.js"(exports,module){var isWindows=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",path=__require("path"),COLON=isWindows?";":":",isexe=require_isexe(),getNotFoundError=cmd=>Object.assign(new Error(`not found: ${cmd}`),{code:"ENOENT"}),getPathInfo=(cmd,opt)=>{let colon=opt.colon||COLON,pathEnv=cmd.match(/\//)||isWindows&&cmd.match(/\\/)?[""]:[...isWindows?[process.cwd()]:[],...(opt.path||process.env.PATH||"").split(colon)],pathExtExe=isWindows?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",pathExt=isWindows?pathExtExe.split(colon):[""];return isWindows&&cmd.indexOf(".")!==-1&&pathExt[0]!==""&&pathExt.unshift(""),{pathEnv,pathExt,pathExtExe}},which=(cmd,opt,cb)=>{typeof opt=="function"&&(cb=opt,opt={}),opt||(opt={});let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[],step=i=>new Promise((resolve2,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve2(found):reject(getNotFoundError(cmd));let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;resolve2(subStep(p,i,0))}),subStep=(p,i,ii)=>new Promise((resolve2,reject)=>{if(ii===pathExt.length)return resolve2(step(i+1));let ext=pathExt[ii];isexe(p+ext,{pathExt:pathExtExe},(er,is)=>{if(!er&&is)if(opt.all)found.push(p+ext);else return resolve2(p+ext);return resolve2(subStep(p,i,ii+1))})});return cb?step(0).then(res=>cb(null,res),cb):step(0)},whichSync=(cmd,opt)=>{opt=opt||{};let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[];for(let i=0;i<pathEnv.length;i++){let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;for(let j=0;j<pathExt.length;j++){let cur=p+pathExt[j];try{if(isexe.sync(cur,{pathExt:pathExtExe}))if(opt.all)found.push(cur);else return cur}catch{}}}if(opt.all&&found.length)return found;if(opt.nothrow)return null;throw getNotFoundError(cmd)};module.exports=which;which.sync=whichSync}});var require_path_key=__commonJS({"node_modules/.bun/path-key@3.1.1/node_modules/path-key/index.js"(exports,module){"use strict";var pathKey=(options={})=>{let environment=options.env||process.env;return(options.platform||process.platform)!=="win32"?"PATH":Object.keys(environment).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"};module.exports=pathKey;module.exports.default=pathKey}});var require_resolveCommand=__commonJS({"node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports,module){"use strict";var path=__require("path"),which=require_which(),getPathKey=require_path_key();function resolveCommandAttempt(parsed,withoutPathExt){let env=parsed.options.env||process.env,cwd=process.cwd(),hasCustomCwd=parsed.options.cwd!=null,shouldSwitchCwd=hasCustomCwd&&process.chdir!==void 0&&!process.chdir.disabled;if(shouldSwitchCwd)try{process.chdir(parsed.options.cwd)}catch{}let resolved;try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path.delimiter:void 0})}catch{}finally{shouldSwitchCwd&&process.chdir(cwd)}return resolved&&(resolved=path.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)),resolved}function resolveCommand(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,!0)}module.exports=resolveCommand}});var require_escape=__commonJS({"node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(exports,module){"use strict";var metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(arg){return arg=arg.replace(metaCharsRegExp,"^$1"),arg}function escapeArgument(arg,doubleEscapeMetaChars){return arg=`${arg}`,arg=arg.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1"),arg=`"${arg}"`,arg=arg.replace(metaCharsRegExp,"^$1"),doubleEscapeMetaChars&&(arg=arg.replace(metaCharsRegExp,"^$1")),arg}module.exports.command=escapeCommand;module.exports.argument=escapeArgument}});var require_shebang_regex=__commonJS({"node_modules/.bun/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(exports,module){"use strict";module.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"node_modules/.bun/shebang-command@2.0.0/node_modules/shebang-command/index.js"(exports,module){"use strict";var shebangRegex=require_shebang_regex();module.exports=(string="")=>{let match=string.match(shebangRegex);if(!match)return null;let[path,argument]=match[0].replace(/#! ?/,"").split(" "),binary=path.split("/").pop();return binary==="env"?argument:argument?`${binary} ${argument}`:binary}}});var require_readShebang=__commonJS({"node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports,module){"use strict";var fs=__require("fs"),shebangCommand=require_shebang_command();function readShebang(command){let buffer=Buffer.alloc(150),fd;try{fd=fs.openSync(command,"r"),fs.readSync(fd,buffer,0,150,0),fs.closeSync(fd)}catch{}return shebangCommand(buffer.toString())}module.exports=readShebang}});var require_parse=__commonJS({"node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports,module){"use strict";var path=__require("path"),resolveCommand=require_resolveCommand(),escape=require_escape(),readShebang=require_readShebang(),isWin=process.platform==="win32",isExecutableRegExp=/\.(?:com|exe)$/i,isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand(parsed);let shebang=parsed.file&&readShebang(parsed.file);return shebang?(parsed.args.unshift(parsed.file),parsed.command=shebang,resolveCommand(parsed)):parsed.file}function parseNonShell(parsed){if(!isWin)return parsed;let commandFile=detectShebang(parsed),needsShell=!isExecutableRegExp.test(commandFile);if(parsed.options.forceShell||needsShell){let needsDoubleEscapeMetaChars=isCmdShimRegExp.test(commandFile);parsed.command=path.normalize(parsed.command),parsed.command=escape.command(parsed.command),parsed.args=parsed.args.map(arg=>escape.argument(arg,needsDoubleEscapeMetaChars));let shellCommand=[parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`],parsed.command=process.env.comspec||"cmd.exe",parsed.options.windowsVerbatimArguments=!0}return parsed}function parse(command,args,options){args&&!Array.isArray(args)&&(options=args,args=null),args=args?args.slice(0):[],options=Object.assign({},options);let parsed={command,args,options,file:void 0,original:{command,args}};return options.shell?parsed:parseNonShell(parsed)}module.exports=parse}});var require_enoent=__commonJS({"node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(exports,module){"use strict";var isWin=process.platform==="win32";function notFoundError(original,syscall){return Object.assign(new Error(`${syscall} ${original.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${syscall} ${original.command}`,path:original.command,spawnargs:original.args})}function hookChildProcess(cp,parsed){if(!isWin)return;let originalEmit=cp.emit;cp.emit=function(name,arg1){if(name==="exit"){let err=verifyENOENT(arg1,parsed);if(err)return originalEmit.call(cp,"error",err)}return originalEmit.apply(cp,arguments)}}function verifyENOENT(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawn"):null}function verifyENOENTSync(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawnSync"):null}module.exports={hookChildProcess,verifyENOENT,verifyENOENTSync,notFoundError}}});var require_cross_spawn=__commonJS({"node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(exports,module){"use strict";var cp=__require("child_process"),parse=require_parse(),enoent=require_enoent();function spawn(command,args,options){let parsed=parse(command,args,options),spawned=cp.spawn(parsed.command,parsed.args,parsed.options);return enoent.hookChildProcess(spawned,parsed),spawned}function spawnSync(command,args,options){let parsed=parse(command,args,options),result=cp.spawnSync(parsed.command,parsed.args,parsed.options);return result.error=result.error||enoent.verifyENOENTSync(result.status,parsed),result}module.exports=spawn;module.exports.spawn=spawn;module.exports.sync=spawnSync;module.exports._parse=parse;module.exports._enoent=enoent}});import{statSync}from"node:fs";import{homedir}from"node:os";import{isAbsolute,join,resolve as nodeResolvePath,posix,relative,sep,win32}from"node:path";import{fileURLToPath}from"node:url";var import_cross_spawn=__toESM(require_cross_spawn(),1);import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import{constants as osConstants}from"node:os";var EXIT_STDIO_GRACE_MS=100;function exitCodeForSignal(signal){return 128+(osConstants.signals[signal]??0)}function spawnProcess(command,args,options){return process.platform==="win32"?(0,import_cross_spawn.default)(command,args,options):nodeSpawn(command,args,options)}function spawnProcessSync(command,args,options){return process.platform==="win32"?import_cross_spawn.default.sync(command,args,options):nodeSpawnSync(command,args,options)}function waitForChildProcess(child,options={}){let graceMs=options.exitStdioGraceMs??EXIT_STDIO_GRACE_MS;return new Promise((resolve2,reject)=>{let settled=!1,exited=!1,exitCode=null,exitSignal=null,postExitTimer,stdoutEnded=child.stdout===null,stderrEnded=child.stderr===null,cleanup=()=>{postExitTimer&&(clearTimeout(postExitTimer),postExitTimer=void 0),child.removeListener("error",onError),child.removeListener("exit",onExit),child.removeListener("close",onClose),child.stdout?.removeListener("end",onStdoutEnd),child.stderr?.removeListener("end",onStderrEnd),child.stdout?.removeListener("data",onData),child.stderr?.removeListener("data",onData)},finalize=()=>{settled||(settled=!0,cleanup(),child.stdout?.destroy(),child.stderr?.destroy(),resolve2(exitCode??(exitSignal?exitCodeForSignal(exitSignal):null)))},maybeFinalizeAfterExit=()=>{!exited||settled||stdoutEnded&&stderrEnded&&finalize()},armIdleTimer=()=>{postExitTimer&&clearTimeout(postExitTimer),postExitTimer=setTimeout(()=>finalize(),graceMs)},onData=()=>{exited&&!settled&&armIdleTimer()},onStdoutEnd=()=>{stdoutEnded=!0,maybeFinalizeAfterExit()},onStderrEnd=()=>{stderrEnded=!0,maybeFinalizeAfterExit()},onError=err=>{settled||(settled=!0,cleanup(),reject(err))},onExit=(code,signal)=>{exited=!0,exitCode=code,exitSignal=signal,maybeFinalizeAfterExit(),settled||armIdleTimer()},onClose=(code,signal)=>{exitCode=code,exitSignal=signal,finalize()};child.stdout?.once("end",onStdoutEnd),child.stderr?.once("end",onStderrEnd),child.stdout?.on("data",onData),child.stderr?.on("data",onData),child.once("error",onError),child.once("exit",onExit),child.once("close",onClose)})}var UNICODE_SPACES=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;function getPathComparisonKey(path){let pathApi=getPlatformPathApi(),resolvedPath=pathApi.resolve(path);return pathApi===win32?resolvedPath.toLowerCase():resolvedPath}function getPlatformPathApi(){return process.platform==="win32"?win32:posix}function pathsEqual(left,right){return getPathComparisonKey(left)===getPathComparisonKey(right)}function isPathWithin(parent,child){let parentKey=getPathComparisonKey(parent),childKey=getPathComparisonKey(child);if(childKey===parentKey)return!0;let pathSep=getPlatformPathApi().sep;return childKey.startsWith(parentKey.endsWith(pathSep)?parentKey:`${parentKey}${pathSep}`)}function shortenHomePath(path,homeDir=homedir()){let pathApi=getPlatformPathApi();if(!homeDir||!pathApi.isAbsolute(path)||!isPathWithin(homeDir,path))return path;let relativePath=pathApi.relative(homeDir,path);return relativePath?`~${pathApi.sep}${relativePath}`:"~"}function getFileRevision(path){try{let stats=statSync(path,{bigint:!0});return`${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`}catch{return}}function isLocalPath(value){let trimmed=value.trim();return!(trimmed.startsWith("npm:")||trimmed.startsWith("git:")||trimmed.startsWith("github:")||trimmed.startsWith("http:")||trimmed.startsWith("https:")||trimmed.startsWith("ssh:")||trimmed.startsWith("builtin:"))}function normalizeWindowsShellPath(filePath){if(!filePath.startsWith("/")||filePath.startsWith("//")||filePath.includes("\\"))return filePath;let match=filePath.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(!match)return filePath;let suffix=match[2]?.replaceAll("/","\\");return`${match[1].toUpperCase()}:\\${suffix??""}`}function normalizePath(input,options={}){let normalized=options.trim?input.trim():input;if(options.normalizeUnicodeSpaces&&(normalized=normalized.replace(UNICODE_SPACES," ")),options.stripAtPrefix&&normalized.startsWith("@")&&(normalized=normalized.slice(1)),process.platform==="win32"&&(normalized=normalizeWindowsShellPath(normalized)),options.expandTilde??!0){let home=options.homeDir??homedir();if(normalized==="~")return home;if(normalized.startsWith("~/")||process.platform==="win32"&&normalized.startsWith("~\\"))return join(home,normalized.slice(2))}return/^file:\/\//.test(normalized)?fileURLToPath(normalized):normalized}function resolvePath(input,baseDir=process.cwd(),options={}){let normalized=normalizePath(input,options),normalizedBaseDir=normalizePath(baseDir);return isAbsolute(normalized)?nodeResolvePath(normalized):nodeResolvePath(normalizedBaseDir,normalized)}function getCwdRelativePath(filePath,cwd){let resolvedCwd=resolvePath(cwd),resolvedPath=resolvePath(filePath,resolvedCwd),relativePath=relative(resolvedCwd,resolvedPath);return relativePath===""||relativePath!==".."&&!relativePath.startsWith(`..${sep}`)&&!isAbsolute(relativePath)?relativePath||".":void 0}function formatPathRelativeToCwdOrAbsolute(filePath,cwd){let absolutePath=resolvePath(filePath,cwd);return(getCwdRelativePath(absolutePath,cwd)??absolutePath).split(sep).join("/")}function markPathIgnoredByCloudSync(path){let attrs=process.platform==="darwin"?["com.dropbox.ignored","com.apple.fileprovider.ignore#P"]:process.platform==="linux"?["user.com.dropbox.ignored"]:[];for(let attr of attrs)process.platform==="darwin"?spawnProcessSync("xattr",["-w",attr,"1",path],{encoding:"utf-8",stdio:"ignore"}):spawnProcessSync("setfattr",["-n",attr,"-v","1",path],{encoding:"utf-8",stdio:"ignore"})}function splitBom(content){return content.startsWith("\uFEFF")?{bom:"\uFEFF",text:content.slice(1)}:{bom:"",text:content}}function stripBom(content){return splitBom(content).text}import{accessSync,constants,existsSync,readFileSync,realpathSync}from"fs";import{createRequire}from"module";import{homedir as homedir2}from"os";import{basename,dirname,join as join2,resolve,sep as sep2,win32 as win322}from"path";import{fileURLToPath as fileURLToPath2}from"url";var __filename=fileURLToPath2(import.meta.url),__dirname=dirname(__filename),isBunBinary=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),isBunRuntime=!!process.versions.bun,isBundledNode=!0;function normalizeSelfUpdatePackageTarget(target){return typeof target=="string"?{packageName:target,installSpec:target}:{packageName:target.packageName,installSpec:target.installSpec??target.packageName}}function makeSelfUpdateCommand(installStep,uninstallStep){return uninstallStep?{...installStep,display:`${uninstallStep.display} && ${installStep.display}`,steps:[uninstallStep,installStep]}:installStep}function makeSelfUpdateCommandStep(command,args){return{command,args,display:[command,...args].map(arg=>/\s/.test(arg)?`"${arg}"`:arg).join(" ")}}function detectInstallMethod(){if(isBunBinary)return"bun-binary";let resolvedPath=`${__dirname}\0${process.execPath||""}`.toLowerCase().replace(/\\/g,"/");return resolvedPath.includes("/pnpm/")||resolvedPath.includes("/.pnpm/")?"pnpm":resolvedPath.includes("/yarn/")||resolvedPath.includes("/.yarn/")?"yarn":isBunRuntime||resolvedPath.includes("/install/global/node_modules/")?"bun":resolvedPath.includes("/npm/")||resolvedPath.includes("/node_modules/")?"npm":"unknown"}function getInferredNpmInstall(){let packageDir=getPackageDir(),path=process.platform==="win32"||packageDir.includes("\\")?win322:{basename,dirname},parent=path.dirname(packageDir),root;if(path.basename(parent).startsWith("@")&&path.basename(path.dirname(parent))==="node_modules"?root=path.dirname(parent):path.basename(parent)==="node_modules"&&(root=parent),!root)return;let rootParent=path.dirname(root);if(path.basename(rootParent)==="lib")return{root,prefix:path.dirname(rootParent)}}function getSelfUpdateCommandForMethod(method,installedPackageName,updatePackageTarget=installedPackageName,npmCommand){let target=normalizeSelfUpdatePackageTarget(updatePackageTarget);switch(method){case"bun-binary":return;case"pnpm":{let match=readCommandOutput("pnpm",["root","-g"])?void 0:/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(getPackageDir()),binDirArgs=match?[`--config.global-bin-dir=${process.env.PNPM_HOME||dirname(dirname(match[1]))}`]:[];return makeSelfUpdateCommand(makeSelfUpdateCommandStep("pnpm",["install","-g","--ignore-scripts","--config.minimumReleaseAge=0",...binDirArgs,target.installSpec]),target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep("pnpm",["remove","-g",...binDirArgs,installedPackageName]))}case"yarn":return makeSelfUpdateCommand(makeSelfUpdateCommandStep("yarn",["global","add","--ignore-scripts",target.installSpec]),target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep("yarn",["global","remove",installedPackageName]));case"bun":return makeSelfUpdateCommand(makeSelfUpdateCommandStep("bun",["install","-g","--ignore-scripts","--minimum-release-age=0",target.installSpec]),target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep("bun",["uninstall","-g",installedPackageName]));case"npm":{let[command="npm",...npmArgs]=npmCommand??[],inferred=npmCommand?.length?void 0:getInferredNpmInstall(),prefixArgs=[...npmArgs,...inferred?["--prefix",inferred.prefix]:[]],installStep=makeSelfUpdateCommandStep(command,[...prefixArgs,"install","-g","--ignore-scripts","--min-release-age=0",target.installSpec]),uninstallStep=target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep(command,[...prefixArgs,"uninstall","-g",installedPackageName]);return makeSelfUpdateCommand(installStep,uninstallStep)}case"unknown":return}}function readCommandOutput(command,args,options={}){let result=spawnProcessSync(command,args,{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});if(result.status===0)return result.stdout.trim()||void 0;if(options.requireSuccess){let reason=result.error?.message||result.stderr.trim()||`exit code ${result.status??"unknown"}`;throw new Error(`Failed to run ${[command,...args].join(" ")}: ${reason}`)}}function getGlobalPackageRoots(method,_packageName,npmCommand){switch(method){case"npm":{let configured=!!npmCommand?.length,[command="npm",...npmArgs]=npmCommand??[];if(configured&&command==="bun"){let bunBin=readCommandOutput(command,[...npmArgs,"pm","bin","-g"],{requireSuccess:!0}),roots=[join2(homedir2(),".bun","install","global","node_modules")];return bunBin&&roots.push(join2(dirname(bunBin),"install","global","node_modules")),roots}let root=readCommandOutput(command,[...npmArgs,"root","-g"],{requireSuccess:configured}),inferred=configured?void 0:getInferredNpmInstall();return[root,inferred?.root].filter(x=>!!x)}case"pnpm":{let root=readCommandOutput("pnpm",["root","-g"]);if(root)return[root,dirname(root)];let match=/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(getPackageDir());return match?[match[1]]:[]}case"yarn":{let dir=readCommandOutput("yarn",["global","dir"]);return dir?[dir,join2(dir,"node_modules")]:[]}case"bun":{let bunBin=readCommandOutput("bun",["pm","bin","-g"]),roots=[join2(homedir2(),".bun","install","global","node_modules")];return bunBin&&roots.push(join2(dirname(bunBin),"install","global","node_modules")),roots}case"bun-binary":case"unknown":return[]}}function normalizeExistingPathForComparison(path,resolveSymlinks){let resolvedPath=resolve(path);if(!existsSync(resolvedPath))return;let normalizedPath=resolvedPath;if(resolveSymlinks)try{normalizedPath=realpathSync(resolvedPath)}catch{return}return process.platform==="win32"&&(normalizedPath=normalizedPath.toLowerCase()),normalizedPath}function getPathComparisonCandidates(path){return Array.from(new Set([normalizeExistingPathForComparison(path,!1),normalizeExistingPathForComparison(path,!0)].filter(candidate=>!!candidate)))}function getEntrypointPackageDir(){let entrypoint=process.argv[1];if(!entrypoint)return;let dir=dirname(entrypoint);for(;dir!==dirname(dir);){if(existsSync(join2(dir,"package.json")))return dir;dir=dirname(dir)}}function isSelfUpdatePathWritable(){let packageDir=getPackageDir();try{return accessSync(packageDir,constants.W_OK),accessSync(dirname(packageDir),constants.W_OK),!0}catch{return!1}}function isManagedByGlobalPackageManager(method,packageName,npmCommand){let packageDirCandidates=[getPackageDir(),getEntrypointPackageDir()].filter(dir=>!!dir).flatMap(dir=>getPathComparisonCandidates(dir));return getGlobalPackageRoots(method,packageName,npmCommand).some(root=>getPathComparisonCandidates(root).some(normalizedRoot=>{let rootPrefix=normalizedRoot.endsWith(sep2)?normalizedRoot:`${normalizedRoot}${sep2}`;return packageDirCandidates.some(packageDir=>packageDir.startsWith(rootPrefix))}))}function getSelfUpdateCommand(packageName,npmCommand,updatePackageTarget=packageName){let method=detectInstallMethod(),command=getSelfUpdateCommandForMethod(method,packageName,updatePackageTarget,npmCommand);if(!(!command||!isManagedByGlobalPackageManager(method,packageName,npmCommand)||!isSelfUpdatePathWritable()))return command}function getConfiguredSelfUpdateArgv(setting){let fromEnv=process.env.DRAHT_SELF_UPDATE_COMMAND?.trim().split(/\s+/).filter(Boolean);return fromEnv?.length?fromEnv:setting?.length?setting:void 0}function makeConfiguredSelfUpdateCommand(argv,release){let values={packageName:release.packageName,version:release.version,installSpec:`${release.packageName}@${release.version}`},[command="",...args]=argv.map(arg=>arg.replace(/\{(packageName|version|installSpec)\}/g,(_,name)=>values[name]));return makeSelfUpdateCommandStep(command,args)}function getSelfUpdateUnavailableInstruction(packageName,npmCommand,updatePackageTarget=packageName){let method=detectInstallMethod(),target=normalizeSelfUpdatePackageTarget(updatePackageTarget);if(method==="bun-binary")return"Download from: https://github.com/draht-dev/draht/releases/latest";let command=getSelfUpdateCommandForMethod(method,packageName,target,npmCommand);return command&&isManagedByGlobalPackageManager(method,packageName,npmCommand)&&!isSelfUpdatePathWritable()?`This installation is managed by a global ${method} install, but the install path is not writable. Update it yourself with: ${command.display}`:`Update ${target.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`}function getPackageDir(){let envDir=process.env.DRAHT_PACKAGE_DIR;return envDir?normalizePath(envDir):isBunBinary?dirname(process.execPath):findPackageRoot(__dirname)}function isEmittedBundleDir(dir){return basename(dir)==="dist"&&existsSync(join2(dirname(dir),"package.json"))}function findPackageRoot(startDir){let dir=startDir;for(;dir!==dirname(dir);){if(existsSync(join2(dir,"package.json"))&&!isEmittedBundleDir(dir))return dir;dir=dirname(dir)}return startDir}function getThemesDir(){if(isBunBinary)return join2(getPackageDir(),"theme");let packageDir=getPackageDir(),srcOrDist=existsSync(join2(packageDir,"src"))?"src":"dist";return join2(packageDir,srcOrDist,"modes","interactive","theme")}function getExportTemplateDir(){if(isBunBinary)return join2(getPackageDir(),"export-html");let packageDir=getPackageDir(),srcOrDist=existsSync(join2(packageDir,"src"))?"src":"dist";return join2(packageDir,srcOrDist,"core","export-html")}function getPackageJsonPath(){return join2(getPackageDir(),"package.json")}function getReadmePath(){return resolve(join2(getPackageDir(),"README.md"))}function getDocsPath(){return resolve(join2(getPackageDir(),"docs"))}function getExamplesPath(){return resolve(join2(getPackageDir(),"examples"))}function getChangelogPath(){return resolve(join2(getPackageDir(),"CHANGELOG.md"))}function getInteractiveAssetsDir(){if(isBunBinary)return join2(getPackageDir(),"assets");let packageDir=getPackageDir(),srcOrDist=existsSync(join2(packageDir,"src"))?"src":"dist";return join2(packageDir,srcOrDist,"modes","interactive","assets")}function getBundledInteractiveAssetPath(name){return join2(getInteractiveAssetsDir(),name)}var quickJSWasmPath;function getQuickJSWasmPath(){return quickJSWasmPath??=createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),quickJSWasmPath}function resolveCodemodeWorkerSpecifier(runtime,moduleUrl){if(runtime==="bun-binary")return"./src/extensions/codemode/worker.ts";if(runtime==="bundled-node")return new URL("./codemode-worker.js",moduleUrl)}var codemodeWorkerDataUrl;function getCodemodeWorkerSpecifier(){let runtime=isBunBinary?"bun-binary":isBundledNode?"bundled-node":"unbundled",specifier=resolveCodemodeWorkerSpecifier(runtime,import.meta.url);return runtime!=="bundled-node"||!(specifier instanceof URL)?specifier:(codemodeWorkerDataUrl??=new URL(`data:text/javascript;base64,${readFileSync(specifier).toString("base64")}`),codemodeWorkerDataUrl)}function detectInstallChange(packageJsonPath=startupPackageJsonPath){if(isBunBinary||!packageJsonPath)return;let installed;try{installed=JSON.parse(stripBom(readFileSync(packageJsonPath,"utf-8")))}catch(error){return error.code==="ENOENT"?{kind:"removed"}:void 0}return installed.version&&installed.version!==VERSION?{kind:"updated",version:installed.version}:void 0}var pkg={},startupPackageJsonPath;try{let packageJsonPath=getPackageJsonPath();pkg=JSON.parse(stripBom(readFileSync(packageJsonPath,"utf-8"))),startupPackageJsonPath=packageJsonPath}catch(e){if(e.code!=="ENOENT")throw e}var drahtConfigName=pkg.drahtConfig?.name,PACKAGE_NAME=pkg.name||"@draht/coding-agent",APP_NAME=drahtConfigName||"draht",APP_TITLE=drahtConfigName?APP_NAME:"draht",CONFIG_DIR_NAME=pkg.drahtConfig?.configDir||".draht";var VERSION=pkg.version||"0.0.0",IS_DEV_MODE=existsSync(join2(getPackageDir(),"src")),DISPLAY_VERSION=IS_DEV_MODE?"dev":VERSION;var ENV_AGENT_DIR=`${APP_NAME.toUpperCase()}_CODING_AGENT_DIR`,ENV_SESSION_DIR=`${APP_NAME.toUpperCase()}_CODING_AGENT_SESSION_DIR`;function expandTildePath(path){return normalizePath(path)}function getShareViewerUrl(gistId){let baseUrl=process.env.DRAHT_SHARE_VIEWER_URL?.trim();if(baseUrl)return`${baseUrl}#${gistId}`}function getAgentDir(){let envDir=process.env[ENV_AGENT_DIR];return envDir?expandTildePath(envDir):join2(homedir2(),CONFIG_DIR_NAME,"agent")}function getCustomThemesDir(){return join2(getAgentDir(),"themes")}function getAuthPath(){return join2(getAgentDir(),"auth.json")}function getSettingsPath(){return join2(getAgentDir(),"settings.json")}function getBinDir(){return join2(getAgentDir(),"bin")}function getShippedPromptsDir(){return join2(getPackageDir(),"prompts")}function getShippedSkillsDir(){return join2(getPackageDir(),"skills")}function getSessionsDir(){return join2(getAgentDir(),"sessions")}function getDebugLogPath(){return join2(getAgentDir(),`${APP_NAME}-debug.log`)}export{require_cross_spawn,spawnProcess,spawnProcessSync,waitForChildProcess,getPathComparisonKey,pathsEqual,isPathWithin,shortenHomePath,getFileRevision,isLocalPath,normalizePath,resolvePath,getCwdRelativePath,formatPathRelativeToCwdOrAbsolute,markPathIgnoredByCloudSync,splitBom,stripBom,isBunBinary,detectInstallMethod,getSelfUpdateCommand,getConfiguredSelfUpdateArgv,makeConfiguredSelfUpdateCommand,getSelfUpdateUnavailableInstruction,getPackageDir,getThemesDir,getExportTemplateDir,getReadmePath,getDocsPath,getExamplesPath,getChangelogPath,getBundledInteractiveAssetPath,getQuickJSWasmPath,getCodemodeWorkerSpecifier,detectInstallChange,PACKAGE_NAME,APP_NAME,APP_TITLE,CONFIG_DIR_NAME,VERSION,DISPLAY_VERSION,ENV_AGENT_DIR,ENV_SESSION_DIR,expandTildePath,getShareViewerUrl,getAgentDir,getCustomThemesDir,getAuthPath,getSettingsPath,getBinDir,getShippedPromptsDir,getShippedSkillsDir,getSessionsDir,getDebugLogPath};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{__commonJS,__export,__toESM}from"./chunk-HZ2UHMBT.js";var require_x509_transport_state=__commonJS({"node_modules/openai/internal/auth/x509-transport-state.js"(exports,module){"use strict";if(typeof module<"u"&&module!==globalThis.module&&typeof exports<"u"&&module.exports===exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.findX509Credential=exports.rememberX509Credential=exports.findX509OAuthError=exports.rememberX509OAuthError=exports.isApprovedX509Client=exports.markApprovedX509Client=exports.isRetryableX509IssuerError=exports.markRetryableX509IssuerError=exports.isTransientX509ConnectionError=exports.markTransientX509ConnectionError=exports.rememberRegisteredX509Transport=exports.findRegisteredX509Transport=void 0;let registeredX509Transports2=new WeakMap,transientX509ConnectionErrors2=new WeakSet,retryableX509IssuerErrors2=new WeakSet,approvedX509Clients2=new WeakSet,approvedX509OAuthErrors2=new WeakMap,approvedX509Credentials2=new WeakMap;exports.findRegisteredX509Transport=WeakMap.prototype.get.bind(registeredX509Transports2),exports.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(registeredX509Transports2),exports.markTransientX509ConnectionError=WeakSet.prototype.add.bind(transientX509ConnectionErrors2),exports.isTransientX509ConnectionError=WeakSet.prototype.has.bind(transientX509ConnectionErrors2),exports.markRetryableX509IssuerError=WeakSet.prototype.add.bind(retryableX509IssuerErrors2),exports.isRetryableX509IssuerError=WeakSet.prototype.has.bind(retryableX509IssuerErrors2),exports.markApprovedX509Client=WeakSet.prototype.add.bind(approvedX509Clients2),exports.isApprovedX509Client=WeakSet.prototype.has.bind(approvedX509Clients2),exports.rememberX509OAuthError=WeakMap.prototype.set.bind(approvedX509OAuthErrors2),exports.findX509OAuthError=WeakMap.prototype.get.bind(approvedX509OAuthErrors2),exports.rememberX509Credential=WeakMap.prototype.set.bind(approvedX509Credentials2),exports.findX509Credential=WeakMap.prototype.get.bind(approvedX509Credentials2)}}});function __classPrivateFieldSet(receiver,state2,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state2=="function"?receiver!==state2||!f:!state2.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state2.set(receiver,value),value}function __classPrivateFieldGet(receiver,state2,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state2=="function"?receiver!==state2||!f:!state2.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state2.get(receiver)}var uuid4=function(){let{crypto:crypto2}=globalThis;if(crypto2?.randomUUID)return uuid4=crypto2.randomUUID.bind(crypto2),crypto2.randomUUID();let u8=new Uint8Array(1),randomByte=crypto2?()=>crypto2.getRandomValues(u8)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,c=>(+c^randomByte()&15>>+c/4).toString(16))};function isAbortError(err){return typeof err=="object"&&err!==null&&("name"in err&&err.name==="AbortError"||"message"in err&&String(err.message).includes("FetchRequestCanceledException"))}var castToError=err=>{if(err instanceof Error)return err;if(typeof err=="object"&&err!==null){try{if(Object.prototype.toString.call(err)==="[object Error]"){let hasCause="cause"in err,error=new Error(err.message,hasCause?{cause:err.cause}:{});return err.stack&&(error.stack=err.stack),hasCause&&!Object.prototype.hasOwnProperty.call(error,"cause")&&(error.cause=err.cause),err.name&&(error.name=err.name),error}}catch{}try{return new Error(JSON.stringify(err))}catch{}}return new Error(err)};var OpenAIError=class extends Error{},APIError=class _APIError extends OpenAIError{constructor(status,error,message,headers){super(`${_APIError.makeMessage(status,error,message)}`),this.status=status,this.headers=headers,this.requestID=headers?.get("x-request-id"),this.error=error;let data=error;this.code=data?.code,this.param=data?.param,this.type=data?.type}static makeMessage(status,error,message){let msg=error?.message?typeof error.message=="string"?error.message:JSON.stringify(error.message):error?JSON.stringify(error):message;return status&&msg?`${status} ${msg}`:status?`${status} status code (no body)`:msg||"(no status code or body)"}static generate(status,errorResponse,message,headers){if(!status||!headers)return new APIConnectionError({message,cause:castToError(errorResponse)});let error=errorResponse?.error;return status===400?new BadRequestError(status,error,message,headers):status===401?new AuthenticationError(status,error,message,headers):status===403?new PermissionDeniedError(status,error,message,headers):status===404?new NotFoundError(status,error,message,headers):status===409?new ConflictError(status,error,message,headers):status===422?new UnprocessableEntityError(status,error,message,headers):status===429?new RateLimitError(status,error,message,headers):status>=500?new InternalServerError(status,error,message,headers):new _APIError(status,error,message,headers)}},APIUserAbortError=class extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}},APIConnectionError=class extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0),cause&&(this.cause=cause)}},APIConnectionTimeoutError=class extends APIConnectionError{constructor({message}={}){super({message:message??"Request timed out."})}},BadRequestError=class extends APIError{},AuthenticationError=class extends APIError{},PermissionDeniedError=class extends APIError{},NotFoundError=class extends APIError{},ConflictError=class extends APIError{},UnprocessableEntityError=class extends APIError{},RateLimitError=class extends APIError{},InternalServerError=class extends APIError{},LengthFinishReasonError=class extends OpenAIError{constructor(){super("Could not parse response content as the length limit was reached")}},ContentFilterFinishReasonError=class extends OpenAIError{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},InvalidWebhookSignatureError=class extends Error{constructor(message){super(message)}},OAuthError=class extends APIError{constructor(status,error,headers){let finalMessage="OAuth2 authentication error",error_code;if(error&&typeof error=="object"){let errorData=error;error_code=errorData.error;let description=errorData.error_description;description&&typeof description=="string"?finalMessage=description:error_code&&(finalMessage=error_code)}super(status,error,finalMessage,headers),this.error_code=error_code}},SubjectTokenProviderError=class extends OpenAIError{constructor(message,provider,cause){super(message),this.provider=provider,this.cause=cause}};var startsWithSchemeRegexp=/^[a-z][a-z0-9+.-]*:/i,isAbsoluteURL=url=>startsWithSchemeRegexp.test(url),isArray=val=>(isArray=Array.isArray,isArray(val)),isReadonlyArray=isArray;function maybeObj(x){return typeof x!="object"?{}:x??{}}function isEmptyObj(obj){if(!obj)return!0;for(let _k in obj)return!1;return!0}function hasOwn(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}function isObj(obj){return obj!=null&&typeof obj=="object"&&!Array.isArray(obj)}var validatePositiveInteger=(name,n)=>{if(typeof n!="number"||!Number.isInteger(n))throw new OpenAIError(`${name} must be an integer`);if(n<0)throw new OpenAIError(`${name} must be a positive integer`);return n};var safeJSON=text=>{try{return JSON.parse(text)}catch{return}};var sleep=(ms,...signals)=>new Promise((resolve,reject)=>{let activeSignals=[...new Set(signals.filter(signal=>signal!=null))],timeout,settled=!1,cleanup=()=>{for(let signal of activeSignals)try{signal.removeEventListener("abort",abort)}catch{}},settle=callback=>{settled||(settled=!0,timeout!==void 0&&(clearTimeout(timeout),timeout=void 0),cleanup(),callback())},abort=()=>{settle(()=>reject())};if(activeSignals.some(signal=>signal.aborted)){abort();return}timeout=setTimeout(()=>{settle(resolve)},ms);for(let signal of activeSignals){if(settled)break;try{signal.addEventListener("abort",abort,{once:!0})}catch(error){settle(()=>reject(error))}}activeSignals.some(signal=>signal.aborted)&&abort()});var weakGlobals=globalThis,finalizer=typeof weakGlobals.FinalizationRegistry=="function"?new weakGlobals.FinalizationRegistry(cleanup=>{try{cleanup()}catch{}}):void 0,callbackOwners=new WeakMap,subscriptions=new WeakMap;function subscribeWeakly(signal,reference,registry){let subscription=subscriptions.get(signal);if(!subscription){let callbacks=new Set,abort=()=>{subscriptions.delete(signal);for(let callback of callbacks)registry.unregister(callback),callback.deref()?.();callbacks.clear()};subscription={callbacks,abort},signal.addEventListener("abort",abort,{once:!0}),subscriptions.set(signal,subscription)}let owner=subscription;return owner.callbacks.add(reference),()=>{owner.callbacks.delete(reference),registry.unregister(reference),owner.callbacks.size===0&&(subscriptions.get(signal)===owner&&subscriptions.delete(signal),signal.removeEventListener("abort",owner.abort))}}function releaseOnAbort(signal,callbacks,abort){signal.addEventListener("abort",()=>callbacks.deref()?.delete(abort),{once:!0})}function retainRequestAbortCallback(owner,abort,requestSignal){if(typeof weakGlobals.WeakRef=="function"&&finalizer&&!requestSignal.aborted){let callbacks=callbackOwners.get(owner);callbacks||(callbacks=new Set,callbackOwners.set(owner,callbacks)),callbacks.add(abort),releaseOnAbort(requestSignal,new weakGlobals.WeakRef(callbacks),abort)}}function addRequestAbortListener(signal,abort,requestSignal){if(signal.aborted)return abort(),()=>{};if(typeof weakGlobals.WeakRef!="function"||!finalizer)return signal.addEventListener("abort",abort,{once:!0}),()=>signal.removeEventListener("abort",abort);let reference=new weakGlobals.WeakRef(abort),cleanup=subscribeWeakly(signal,reference,finalizer);return finalizer.register(abort,cleanup,reference),retainRequestAbortCallback(requestSignal,abort,requestSignal),cleanup}function getDefaultFetch(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function makeReadableStream(...args){let ReadableStream2=globalThis.ReadableStream;if(typeof ReadableStream2>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new ReadableStream2(...args)}function ReadableStreamFrom(iterable){let iter=Symbol.asyncIterator in iterable?iterable[Symbol.asyncIterator]():iterable[Symbol.iterator]();return makeReadableStream({start(){},async pull(controller){let{done,value}=await iter.next();done?controller.close():controller.enqueue(value)},async cancel(){await iter.return?.()}})}function ReadableStreamToAsyncIterable(stream){if(stream[Symbol.asyncIterator])return stream;let reader=stream.getReader();return{async next(){try{let result=await reader.read();return result?.done&&reader.releaseLock(),result}catch(e){throw reader.releaseLock(),e}},async return(){let cancelPromise=reader.cancel();return reader.releaseLock(),await cancelPromise,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function CancelReadableStream(stream){if(stream===null||typeof stream!="object")return;if(stream[Symbol.asyncIterator]){await stream[Symbol.asyncIterator]().return?.();return}let reader=stream.getReader(),cancelPromise=reader.cancel();reader.releaseLock(),await cancelPromise}var encodeUTF8_;function encodeUTF8(str){let encoder;return(encodeUTF8_??(encoder=new globalThis.TextEncoder,encodeUTF8_=encoder.encode.bind(encoder)))(str)}var decodeUTF8_;function decodeUTF8(bytes){let decoder;return(decodeUTF8_??(decoder=new globalThis.TextDecoder,decodeUTF8_=decoder.decode.bind(decoder)))(bytes)}var _LineDecoder_instances,_LineDecoder_buffer,_LineDecoder_start,_LineDecoder_end,_LineDecoder_searchIndex,_LineDecoder_skipLeadingLF,_LineDecoder_append,MAX_RETAINED_BUFFER_BYTES=64*1024,LineDecoder=class{constructor(){_LineDecoder_instances.add(this),_LineDecoder_buffer.set(this,void 0),_LineDecoder_start.set(this,void 0),_LineDecoder_end.set(this,void 0),_LineDecoder_searchIndex.set(this,void 0),_LineDecoder_skipLeadingLF.set(this,void 0),__classPrivateFieldSet(this,_LineDecoder_buffer,new Uint8Array,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,0,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,0,"f"),__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f")}decode(chunk){if(chunk==null)return[];let binaryChunk;if(chunk instanceof ArrayBuffer?binaryChunk=new Uint8Array(chunk):typeof chunk=="string"?binaryChunk=encodeUTF8(chunk):binaryChunk=chunk,binaryChunk.length===0)return[];if(__classPrivateFieldGet(this,_LineDecoder_skipLeadingLF,"f")&&(__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f"),binaryChunk[0]===10&&(binaryChunk=binaryChunk.subarray(1)),binaryChunk.length===0))return[];__classPrivateFieldGet(this,_LineDecoder_instances,"m",_LineDecoder_append).call(this,binaryChunk);let lines=[],patternIndex;for(;(patternIndex=findNewlineIndex(__classPrivateFieldGet(this,_LineDecoder_buffer,"f"),__classPrivateFieldGet(this,_LineDecoder_searchIndex,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f")))!=null;){let line=decodeUTF8(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),patternIndex.preceding));lines.push(line),__classPrivateFieldSet(this,_LineDecoder_start,patternIndex.index,"f"),patternIndex.carriage&&(__classPrivateFieldGet(this,_LineDecoder_start,"f")<__classPrivateFieldGet(this,_LineDecoder_end,"f")&&__classPrivateFieldGet(this,_LineDecoder_buffer,"f")[__classPrivateFieldGet(this,_LineDecoder_start,"f")]===10?__classPrivateFieldSet(this,_LineDecoder_start,__classPrivateFieldGet(this,_LineDecoder_start,"f")+1,"f"):__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f")&&__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!0,"f")),__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_start,"f"),"f")}if(__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_end,"f"),"f"),__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f"))__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,0,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,0,"f"),__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>MAX_RETAINED_BUFFER_BYTES&&__classPrivateFieldSet(this,_LineDecoder_buffer,new Uint8Array,"f");else if(lines.length>0&&__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>MAX_RETAINED_BUFFER_BYTES){let length=__classPrivateFieldGet(this,_LineDecoder_end,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f");if(length<=MAX_RETAINED_BUFFER_BYTES||__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>length*4){let capacity=length<=MAX_RETAINED_BUFFER_BYTES?Math.min(Math.max(length*2,256),MAX_RETAINED_BUFFER_BYTES):length*2,buffer=new Uint8Array(capacity);buffer.set(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"))),__classPrivateFieldSet(this,_LineDecoder_buffer,buffer,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,length,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,length,"f")}}return lines}flush(){return __classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f"),__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f")?[]:this.decode(`
2
+ import{__commonJS,__export,__toESM}from"./chunk-HZ2UHMBT.js";var require_x509_transport_state=__commonJS({"node_modules/.bun/openai@7.19.0+16827b643d36304c/node_modules/openai/internal/auth/x509-transport-state.js"(exports,module){"use strict";if(typeof module<"u"&&module!==globalThis.module&&typeof exports<"u"&&module.exports===exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.findX509Credential=exports.rememberX509Credential=exports.findX509OAuthError=exports.rememberX509OAuthError=exports.isApprovedX509Client=exports.markApprovedX509Client=exports.isRetryableX509IssuerError=exports.markRetryableX509IssuerError=exports.isTransientX509ConnectionError=exports.markTransientX509ConnectionError=exports.rememberRegisteredX509Transport=exports.findRegisteredX509Transport=void 0;let registeredX509Transports2=new WeakMap,transientX509ConnectionErrors2=new WeakSet,retryableX509IssuerErrors2=new WeakSet,approvedX509Clients2=new WeakSet,approvedX509OAuthErrors2=new WeakMap,approvedX509Credentials2=new WeakMap;exports.findRegisteredX509Transport=WeakMap.prototype.get.bind(registeredX509Transports2),exports.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(registeredX509Transports2),exports.markTransientX509ConnectionError=WeakSet.prototype.add.bind(transientX509ConnectionErrors2),exports.isTransientX509ConnectionError=WeakSet.prototype.has.bind(transientX509ConnectionErrors2),exports.markRetryableX509IssuerError=WeakSet.prototype.add.bind(retryableX509IssuerErrors2),exports.isRetryableX509IssuerError=WeakSet.prototype.has.bind(retryableX509IssuerErrors2),exports.markApprovedX509Client=WeakSet.prototype.add.bind(approvedX509Clients2),exports.isApprovedX509Client=WeakSet.prototype.has.bind(approvedX509Clients2),exports.rememberX509OAuthError=WeakMap.prototype.set.bind(approvedX509OAuthErrors2),exports.findX509OAuthError=WeakMap.prototype.get.bind(approvedX509OAuthErrors2),exports.rememberX509Credential=WeakMap.prototype.set.bind(approvedX509Credentials2),exports.findX509Credential=WeakMap.prototype.get.bind(approvedX509Credentials2)}}});function __classPrivateFieldSet(receiver,state2,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state2=="function"?receiver!==state2||!f:!state2.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state2.set(receiver,value),value}function __classPrivateFieldGet(receiver,state2,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state2=="function"?receiver!==state2||!f:!state2.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state2.get(receiver)}var uuid4=function(){let{crypto:crypto2}=globalThis;if(crypto2?.randomUUID)return uuid4=crypto2.randomUUID.bind(crypto2),crypto2.randomUUID();let u8=new Uint8Array(1),randomByte=crypto2?()=>crypto2.getRandomValues(u8)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,c=>(+c^randomByte()&15>>+c/4).toString(16))};function isAbortError(err){return typeof err=="object"&&err!==null&&("name"in err&&err.name==="AbortError"||"message"in err&&String(err.message).includes("FetchRequestCanceledException"))}var castToError=err=>{if(err instanceof Error)return err;if(typeof err=="object"&&err!==null){try{if(Object.prototype.toString.call(err)==="[object Error]"){let hasCause="cause"in err,error=new Error(err.message,hasCause?{cause:err.cause}:{});return err.stack&&(error.stack=err.stack),hasCause&&!Object.prototype.hasOwnProperty.call(error,"cause")&&(error.cause=err.cause),err.name&&(error.name=err.name),error}}catch{}try{return new Error(JSON.stringify(err))}catch{}}return new Error(err)};var OpenAIError=class extends Error{},APIError=class _APIError extends OpenAIError{constructor(status,error,message,headers){super(`${_APIError.makeMessage(status,error,message)}`),this.status=status,this.headers=headers,this.requestID=headers?.get("x-request-id"),this.error=error;let data=error;this.code=data?.code,this.param=data?.param,this.type=data?.type}static makeMessage(status,error,message){let msg=error?.message?typeof error.message=="string"?error.message:JSON.stringify(error.message):error?JSON.stringify(error):message;return status&&msg?`${status} ${msg}`:status?`${status} status code (no body)`:msg||"(no status code or body)"}static generate(status,errorResponse,message,headers){if(!status||!headers)return new APIConnectionError({message,cause:castToError(errorResponse)});let error=errorResponse?.error;return status===400?new BadRequestError(status,error,message,headers):status===401?new AuthenticationError(status,error,message,headers):status===403?new PermissionDeniedError(status,error,message,headers):status===404?new NotFoundError(status,error,message,headers):status===409?new ConflictError(status,error,message,headers):status===422?new UnprocessableEntityError(status,error,message,headers):status===429?new RateLimitError(status,error,message,headers):status>=500?new InternalServerError(status,error,message,headers):new _APIError(status,error,message,headers)}},APIUserAbortError=class extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}},APIConnectionError=class extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0),cause&&(this.cause=cause)}},APIConnectionTimeoutError=class extends APIConnectionError{constructor({message}={}){super({message:message??"Request timed out."})}},BadRequestError=class extends APIError{},AuthenticationError=class extends APIError{},PermissionDeniedError=class extends APIError{},NotFoundError=class extends APIError{},ConflictError=class extends APIError{},UnprocessableEntityError=class extends APIError{},RateLimitError=class extends APIError{},InternalServerError=class extends APIError{},LengthFinishReasonError=class extends OpenAIError{constructor(){super("Could not parse response content as the length limit was reached")}},ContentFilterFinishReasonError=class extends OpenAIError{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},InvalidWebhookSignatureError=class extends Error{constructor(message){super(message)}},OAuthError=class extends APIError{constructor(status,error,headers){let finalMessage="OAuth2 authentication error",error_code;if(error&&typeof error=="object"){let errorData=error;error_code=errorData.error;let description=errorData.error_description;description&&typeof description=="string"?finalMessage=description:error_code&&(finalMessage=error_code)}super(status,error,finalMessage,headers),this.error_code=error_code}},SubjectTokenProviderError=class extends OpenAIError{constructor(message,provider,cause){super(message),this.provider=provider,this.cause=cause}};var startsWithSchemeRegexp=/^[a-z][a-z0-9+.-]*:/i,isAbsoluteURL=url=>startsWithSchemeRegexp.test(url),isArray=val=>(isArray=Array.isArray,isArray(val)),isReadonlyArray=isArray;function maybeObj(x){return typeof x!="object"?{}:x??{}}function isEmptyObj(obj){if(!obj)return!0;for(let _k in obj)return!1;return!0}function hasOwn(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}function isObj(obj){return obj!=null&&typeof obj=="object"&&!Array.isArray(obj)}var validatePositiveInteger=(name,n)=>{if(typeof n!="number"||!Number.isInteger(n))throw new OpenAIError(`${name} must be an integer`);if(n<0)throw new OpenAIError(`${name} must be a positive integer`);return n};var safeJSON=text=>{try{return JSON.parse(text)}catch{return}};var sleep=(ms,...signals)=>new Promise((resolve,reject)=>{let activeSignals=[...new Set(signals.filter(signal=>signal!=null))],timeout,settled=!1,cleanup=()=>{for(let signal of activeSignals)try{signal.removeEventListener("abort",abort)}catch{}},settle=callback=>{settled||(settled=!0,timeout!==void 0&&(clearTimeout(timeout),timeout=void 0),cleanup(),callback())},abort=()=>{settle(()=>reject())};if(activeSignals.some(signal=>signal.aborted)){abort();return}timeout=setTimeout(()=>{settle(resolve)},ms);for(let signal of activeSignals){if(settled)break;try{signal.addEventListener("abort",abort,{once:!0})}catch(error){settle(()=>reject(error))}}activeSignals.some(signal=>signal.aborted)&&abort()});var weakGlobals=globalThis,finalizer=typeof weakGlobals.FinalizationRegistry=="function"?new weakGlobals.FinalizationRegistry(cleanup=>{try{cleanup()}catch{}}):void 0,callbackOwners=new WeakMap,subscriptions=new WeakMap;function subscribeWeakly(signal,reference,registry){let subscription=subscriptions.get(signal);if(!subscription){let callbacks=new Set,abort=()=>{subscriptions.delete(signal);for(let callback of callbacks)registry.unregister(callback),callback.deref()?.();callbacks.clear()};subscription={callbacks,abort},signal.addEventListener("abort",abort,{once:!0}),subscriptions.set(signal,subscription)}let owner=subscription;return owner.callbacks.add(reference),()=>{owner.callbacks.delete(reference),registry.unregister(reference),owner.callbacks.size===0&&(subscriptions.get(signal)===owner&&subscriptions.delete(signal),signal.removeEventListener("abort",owner.abort))}}function releaseOnAbort(signal,callbacks,abort){signal.addEventListener("abort",()=>callbacks.deref()?.delete(abort),{once:!0})}function retainRequestAbortCallback(owner,abort,requestSignal){if(typeof weakGlobals.WeakRef=="function"&&finalizer&&!requestSignal.aborted){let callbacks=callbackOwners.get(owner);callbacks||(callbacks=new Set,callbackOwners.set(owner,callbacks)),callbacks.add(abort),releaseOnAbort(requestSignal,new weakGlobals.WeakRef(callbacks),abort)}}function addRequestAbortListener(signal,abort,requestSignal){if(signal.aborted)return abort(),()=>{};if(typeof weakGlobals.WeakRef!="function"||!finalizer)return signal.addEventListener("abort",abort,{once:!0}),()=>signal.removeEventListener("abort",abort);let reference=new weakGlobals.WeakRef(abort),cleanup=subscribeWeakly(signal,reference,finalizer);return finalizer.register(abort,cleanup,reference),retainRequestAbortCallback(requestSignal,abort,requestSignal),cleanup}function getDefaultFetch(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function makeReadableStream(...args){let ReadableStream2=globalThis.ReadableStream;if(typeof ReadableStream2>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new ReadableStream2(...args)}function ReadableStreamFrom(iterable){let iter=Symbol.asyncIterator in iterable?iterable[Symbol.asyncIterator]():iterable[Symbol.iterator]();return makeReadableStream({start(){},async pull(controller){let{done,value}=await iter.next();done?controller.close():controller.enqueue(value)},async cancel(){await iter.return?.()}})}function ReadableStreamToAsyncIterable(stream){if(stream[Symbol.asyncIterator])return stream;let reader=stream.getReader();return{async next(){try{let result=await reader.read();return result?.done&&reader.releaseLock(),result}catch(e){throw reader.releaseLock(),e}},async return(){let cancelPromise=reader.cancel();return reader.releaseLock(),await cancelPromise,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function CancelReadableStream(stream){if(stream===null||typeof stream!="object")return;if(stream[Symbol.asyncIterator]){await stream[Symbol.asyncIterator]().return?.();return}let reader=stream.getReader(),cancelPromise=reader.cancel();reader.releaseLock(),await cancelPromise}var encodeUTF8_;function encodeUTF8(str){let encoder;return(encodeUTF8_??(encoder=new globalThis.TextEncoder,encodeUTF8_=encoder.encode.bind(encoder)))(str)}var decodeUTF8_;function decodeUTF8(bytes){let decoder;return(decodeUTF8_??(decoder=new globalThis.TextDecoder,decodeUTF8_=decoder.decode.bind(decoder)))(bytes)}var _LineDecoder_instances,_LineDecoder_buffer,_LineDecoder_start,_LineDecoder_end,_LineDecoder_searchIndex,_LineDecoder_skipLeadingLF,_LineDecoder_append,MAX_RETAINED_BUFFER_BYTES=64*1024,LineDecoder=class{constructor(){_LineDecoder_instances.add(this),_LineDecoder_buffer.set(this,void 0),_LineDecoder_start.set(this,void 0),_LineDecoder_end.set(this,void 0),_LineDecoder_searchIndex.set(this,void 0),_LineDecoder_skipLeadingLF.set(this,void 0),__classPrivateFieldSet(this,_LineDecoder_buffer,new Uint8Array,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,0,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,0,"f"),__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f")}decode(chunk){if(chunk==null)return[];let binaryChunk;if(chunk instanceof ArrayBuffer?binaryChunk=new Uint8Array(chunk):typeof chunk=="string"?binaryChunk=encodeUTF8(chunk):binaryChunk=chunk,binaryChunk.length===0)return[];if(__classPrivateFieldGet(this,_LineDecoder_skipLeadingLF,"f")&&(__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f"),binaryChunk[0]===10&&(binaryChunk=binaryChunk.subarray(1)),binaryChunk.length===0))return[];__classPrivateFieldGet(this,_LineDecoder_instances,"m",_LineDecoder_append).call(this,binaryChunk);let lines=[],patternIndex;for(;(patternIndex=findNewlineIndex(__classPrivateFieldGet(this,_LineDecoder_buffer,"f"),__classPrivateFieldGet(this,_LineDecoder_searchIndex,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f")))!=null;){let line=decodeUTF8(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),patternIndex.preceding));lines.push(line),__classPrivateFieldSet(this,_LineDecoder_start,patternIndex.index,"f"),patternIndex.carriage&&(__classPrivateFieldGet(this,_LineDecoder_start,"f")<__classPrivateFieldGet(this,_LineDecoder_end,"f")&&__classPrivateFieldGet(this,_LineDecoder_buffer,"f")[__classPrivateFieldGet(this,_LineDecoder_start,"f")]===10?__classPrivateFieldSet(this,_LineDecoder_start,__classPrivateFieldGet(this,_LineDecoder_start,"f")+1,"f"):__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f")&&__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!0,"f")),__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_start,"f"),"f")}if(__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_end,"f"),"f"),__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f"))__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,0,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,0,"f"),__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>MAX_RETAINED_BUFFER_BYTES&&__classPrivateFieldSet(this,_LineDecoder_buffer,new Uint8Array,"f");else if(lines.length>0&&__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>MAX_RETAINED_BUFFER_BYTES){let length=__classPrivateFieldGet(this,_LineDecoder_end,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f");if(length<=MAX_RETAINED_BUFFER_BYTES||__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>length*4){let capacity=length<=MAX_RETAINED_BUFFER_BYTES?Math.min(Math.max(length*2,256),MAX_RETAINED_BUFFER_BYTES):length*2,buffer=new Uint8Array(capacity);buffer.set(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"))),__classPrivateFieldSet(this,_LineDecoder_buffer,buffer,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,length,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,length,"f")}}return lines}flush(){return __classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f"),__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f")?[]:this.decode(`
3
3
  `)}};_LineDecoder_buffer=new WeakMap,_LineDecoder_start=new WeakMap,_LineDecoder_end=new WeakMap,_LineDecoder_searchIndex=new WeakMap,_LineDecoder_skipLeadingLF=new WeakMap,_LineDecoder_instances=new WeakSet,_LineDecoder_append=function(chunk){if(__classPrivateFieldGet(this,_LineDecoder_end,"f")+chunk.length>__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length){let length=__classPrivateFieldGet(this,_LineDecoder_end,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f");if(__classPrivateFieldGet(this,_LineDecoder_start,"f")>=__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length/2&&length+chunk.length<=__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length)__classPrivateFieldGet(this,_LineDecoder_buffer,"f").copyWithin(0,__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"));else{let capacity=Math.max(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length*2,length+chunk.length,256),buffer=new Uint8Array(capacity);buffer.set(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"))),__classPrivateFieldSet(this,_LineDecoder_buffer,buffer,"f")}__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_searchIndex,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f"),"f"),__classPrivateFieldSet(this,_LineDecoder_end,length,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f")}__classPrivateFieldGet(this,_LineDecoder_buffer,"f").set(chunk,__classPrivateFieldGet(this,_LineDecoder_end,"f")),__classPrivateFieldSet(this,_LineDecoder_end,__classPrivateFieldGet(this,_LineDecoder_end,"f")+chunk.length,"f")};LineDecoder.NEWLINE_CHARS=new Set([`
4
4
  `,"\r"]);LineDecoder.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function findNewlineIndex(buffer,start,end){for(let i=start;i<end;i++){if(buffer[i]===10)return{preceding:i,index:i+1,carriage:!1};if(buffer[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function findDoubleNewlineIndex(buffer){for(let i=0;i<buffer.length-1;i++){let firstEndingLength=lineEndingLength(buffer,i);if(firstEndingLength>0){let secondEndingIndex=i+firstEndingLength,secondEndingLength=lineEndingLength(buffer,secondEndingIndex);if(secondEndingLength>0)return secondEndingIndex+secondEndingLength}}return-1}function lineEndingLength(buffer,index){return buffer[index]===10?1:buffer[index]===13?buffer[index+1]===10?2:1:0}var levelNumbers={off:0,error:200,warn:300,info:400,debug:500},parseLogLevel=(maybeLevel,sourceName,client)=>{if(maybeLevel){if(hasOwn(levelNumbers,maybeLevel))return maybeLevel;loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`)}};function noop(){}function makeLogFn(fnLevel,logger,logLevel){return!logger||levelNumbers[fnLevel]>levelNumbers[logLevel]?noop:logger[fnLevel].bind(logger)}var noopLogger={error:noop,warn:noop,info:noop,debug:noop},cachedLoggers=new WeakMap;function loggerFor(client){let logger=client.logger,logLevel=client.logLevel??"off";if(!logger)return noopLogger;let cachedLogger=cachedLoggers.get(logger);if(cachedLogger&&cachedLogger[0]===logLevel)return cachedLogger[1];let levelLogger={error:makeLogFn("error",logger,logLevel),warn:makeLogFn("warn",logger,logLevel),info:makeLogFn("info",logger,logLevel),debug:makeLogFn("debug",logger,logLevel)};return cachedLoggers.set(logger,[logLevel,levelLogger]),levelLogger}var sensitiveQueryNames=new Set(["apikey","accesstoken","refreshtoken","sessiontoken","sessionid","idtoken","authtoken","authorization","token","password","clientsecret","signingsecret","xamzsecuritytoken","xamzsignature","xamzcredential"]);function isSensitiveQueryParameter(name){let normalized=name.toLowerCase().replace(/[-_]/gu,"");return sensitiveQueryNames.has(normalized)||sensitiveQueryNames.has(normalized.replace(/^x/u,""))}var sensitiveHeaderNames=new Set(["authorization","proxy-authorization","api-key","x-api-key","x-amz-security-token","cookie","set-cookie","x-session-token","x-session-id","x-auth-token","x-id-token"]);function isSensitiveHeader(name){return sensitiveHeaderNames.has(name.toLowerCase().replace(/_/gu,"-"))||isSensitiveQueryParameter(name)}function redactURL(value){let url=new URL(value);url.username="",url.password="",url.hash="";for(let name of url.searchParams.keys())isSensitiveQueryParameter(name)&&url.searchParams.set(name,"***");return url.href}var formatRequestDetails=details=>{if(details.options){if(details.options={...details.options},delete details.options.headers,details.options.path){let path2=details.options.path,redacted=new URL(redactURL(new URL(path2,"https://redacted.invalid").href));details.options.path=redacted.origin==="https://redacted.invalid"?`${path2.startsWith("/")?"/":""}${redacted.pathname.slice(1)}${redacted.search}`:redacted.href}details.options.query&&(details.options.query=Object.fromEntries(Object.entries(details.options.query).map(([name,value])=>[name,isSensitiveQueryParameter(name)?"***":value])))}return details.url&&(details.url=redactURL(details.url)),details.headers&&(details.headers=Object.fromEntries((details.headers instanceof Headers?[...details.headers]:Object.entries(details.headers)).map(([name,value])=>[name,isSensitiveHeader(name)?"***":value]))),"retryOfRequestLogID"in details&&(details.retryOfRequestLogID&&(details.retryOf=details.retryOfRequestLogID),delete details.retryOfRequestLogID),details};var _Stream_instances,_Stream_client,_Stream_isTeeBranch,_Stream_cancelIterator;function isTransportAbortError(error){return!(error instanceof APIError)&&isAbortError(error)}function createStreamTeeQueue(){let entries=[],head=0,canceled=!1;return{get length(){return entries.length-head},get canceled(){return canceled},enqueue(value){canceled||entries.push(value)},dequeue(){if(head===entries.length)return;let value=entries[head];return entries[head]=void 0,head+=1,head===entries.length?(entries=[],head=0):head>=1024&&head*2>=entries.length&&(entries=entries.slice(head),head=0),value},cancel(){canceled=!0,entries.length=0,head=0}}}var Stream=class _Stream{constructor(iterator,controller,client){_Stream_instances.add(this),_Stream_client.set(this,void 0),_Stream_isTeeBranch.set(this,!1),this.iterator=iterator,this.controller=controller,__classPrivateFieldSet(this,_Stream_client,client,"f")}static fromSSEResponse(response,controller,client,synthesizeEventData){let consumed=!1,logger=client?loggerFor(client):console;async function*iterator(){if(consumed)throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");consumed=!0;let done=!1,receivedCompletionSentinel=!1,messages=_iterSSEMessages(response,controller),closeMessages=messages.return.bind(messages);messages.return=value=>(receivedCompletionSentinel||controller.abort(),closeMessages(value));try{for await(let sse of messages){if(sse.data==="[DONE]"){receivedCompletionSentinel=!0;break}if(sse.event===null||!sse.event.startsWith("thread.")){let data;try{data=JSON.parse(sse.data)}catch{throw logger.error("Could not parse message into JSON:"),logger.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}if(sse.event==="error")throw new APIError(void 0,data?.error??data,void 0,response.headers);if(data&&data.error)throw new APIError(void 0,data.error,void 0,response.headers);yield synthesizeEventData?{event:sse.event,data}:data}else{let data;try{data=JSON.parse(sse.data)}catch{throw logger.error("Could not parse message into JSON:"),logger.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}yield{event:sse.event,data}}}done=!0}catch(e){if(receivedCompletionSentinel||isTransportAbortError(e)||controller.signal.aborted&&e===controller.signal.reason)return;throw e}finally{done||controller.abort()}}return new _Stream(iterator,controller,client)}static fromReadableStream(readableStream,controller,client){let consumed=!1;async function*iterLines(){let lineDecoder=new LineDecoder,reader=readableStream.getReader(),closed=!1,cancelPromise,cancel=()=>{cancelPromise??(cancelPromise=reader.cancel()),cancelPromise.catch(()=>{})};controller.signal.addEventListener("abort",cancel,{once:!0});try{if(controller.signal.aborted){cancel();return}for(;;){let{value:chunk,done}=await reader.read();if(done){closed=!0;break}if(controller.signal.aborted)return;for(let line of lineDecoder.decode(chunk)){if(controller.signal.aborted)return;yield line}}if(controller.signal.aborted)return;for(let line of lineDecoder.flush()){if(controller.signal.aborted)return;yield line}}finally{controller.signal.removeEventListener("abort",cancel),closed||cancel(),reader.releaseLock()}}async function*iterator(){if(consumed)throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");consumed=!0;let done=!1;try{for await(let line of iterLines())if(line){let data;try{data=JSON.parse(line)}catch(error){throw error instanceof SyntaxError?new SyntaxError("Error reading response: malformed newline-delimited JSON."):error}yield data}done=!0}catch(e){if(controller.signal.aborted||isAbortError(e))return;throw e}finally{done||controller.abort()}}return new _Stream(iterator,controller,client)}[(_Stream_client=new WeakMap,_Stream_isTeeBranch=new WeakMap,_Stream_instances=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}tee(){let{controller}=this,left=createStreamTeeQueue(),right=createStreamTeeQueue(),iterator=this.iterator(),teeIterator=queue=>({next:()=>{if(queue.canceled)return Promise.resolve({value:void 0,done:!0});if(queue.length===0){let result=iterator.next();left.enqueue(result),right.enqueue(result)}return queue.dequeue()},return:async()=>(queue.canceled||(queue.cancel(),left.canceled&&right.canceled&&await __classPrivateFieldGet(this,_Stream_instances,"m",_Stream_cancelIterator).call(this,iterator,controller)),{value:void 0,done:!0})}),branch=queue=>{let stream=new _Stream(()=>teeIterator(queue),controller,__classPrivateFieldGet(this,_Stream_client,"f"));return __classPrivateFieldSet(stream,_Stream_isTeeBranch,!0,"f"),stream};return[branch(left),branch(right)]}toReadableStream(){let{controller}=this,iter,cancellation,cancel=()=>cancellation??(cancellation=__classPrivateFieldGet(this,_Stream_instances,"m",_Stream_cancelIterator).call(this,iter,controller));return makeReadableStream({start:async()=>{iter=this[Symbol.asyncIterator]()},async pull(ctrl){try{let{value,done}=await iter.next();if(done)return ctrl.close();let bytes=encodeUTF8(JSON.stringify(value)+`
5
5
  `);ctrl.enqueue(bytes)}catch(err){ctrl.error(err),cancel().catch(()=>{})}},cancel})}};_Stream_cancelIterator=async function(iterator,controller){let returnMethod=iterator.return;returnMethod&&(__classPrivateFieldGet(this,_Stream_isTeeBranch,"f")||controller.abort(),await Reflect.apply(returnMethod,iterator,[]))};function createAbortableSSESource(body,signal){let reader=typeof body.getReader=="function"?body.getReader():void 0,source=reader?{next:()=>reader.read(),return:()=>reader.cancel()}:ReadableStreamToAsyncIterable(body)[Symbol.asyncIterator](),ended={value:void 0,done:!0},closed=!1,canceled=!1,cancellation,interrupt,waitForAbort=()=>new Promise(resolve=>{interrupt=resolve}),cancel=()=>{if(canceled||closed)return cancellation;canceled=!0;try{cancellation=Promise.resolve(source.return?.())}catch(error){cancellation=Promise.reject(error)}return cancellation.catch(()=>{}),cancellation},abort=()=>{queueMicrotask(()=>{interrupt?.(),cancel()})};return{iterator:{async next(){if(signal.aborted)return ended;let aborted=waitForAbort().then(()=>ended);try{let result=await Promise.race([source.next(),aborted]);return signal.aborted?ended:result.done?(closed=!0,ended):{value:result.value,done:!1}}catch(error){if(signal.aborted&&(isAbortError(error)||error===signal.reason))return ended;throw error}finally{interrupt=void 0}},async return(){let pending=cancel();if(pending&&!signal.aborted){let aborted=waitForAbort();try{signal.aborted||await Promise.race([pending,aborted])}finally{interrupt=void 0}}return ended},[Symbol.asyncIterator](){return this}},start(){signal.addEventListener("abort",abort,{once:!0}),signal.aborted&&abort()},async cleanup(failed){let cleanupError;try{signal.removeEventListener("abort",abort)}catch(error){cleanupError=error}if(!closed){let pending=cancel();if(pending&&!failed&&!signal.aborted)try{await pending}catch(error){cleanupError??(cleanupError=error)}}if(reader)try{reader.releaseLock()}catch(error){cleanupError??(cleanupError=error)}if(cleanupError!==void 0&&!failed&&!signal.aborted)throw cleanupError}}}async function*_iterSSEMessages(response,controller){if(!response.body)throw controller.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product==="ReactNative"?new OpenAIError("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new OpenAIError("Attempted to iterate over a response with no body");let sseDecoder=new SSEDecoder,lineDecoder=new LineDecoder,{signal}=controller,source=createAbortableSSESource(response.body,signal),failed=!1;try{source.start();for await(let sseChunk of iterSSEChunks(source.iterator)){if(signal.aborted)return;for(let line of lineDecoder.decode(sseChunk)){if(signal.aborted)return;let sse=sseDecoder.decode(line);sse&&(yield sse)}}if(signal.aborted)return;for(let line of lineDecoder.flush()){if(signal.aborted)return;let sse=sseDecoder.decode(line);sse&&(yield sse)}if(signal.aborted)return;let pending=sseDecoder.flush();pending&&(yield pending)}catch(error){if(failed=!0,!signal.aborted||!isAbortError(error)&&error!==signal.reason)throw error}finally{await source.cleanup(failed)}}var DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES=3;async function*iterSSEChunks(iterator){let data=new Uint8Array,dataStart=0,dataEnd=0,searchStartIndex=0;for await(let chunk of iterator){if(chunk==null)continue;let binaryChunk;if(chunk instanceof ArrayBuffer?binaryChunk=new Uint8Array(chunk):typeof chunk=="string"?binaryChunk=encodeUTF8(chunk):binaryChunk=chunk,dataEnd+binaryChunk.length>data.length){let bufferedLength=dataEnd-dataStart;if(dataStart>=data.length/2&&bufferedLength+binaryChunk.length<=data.length)data.copyWithin(0,dataStart,dataEnd);else{let newData=new Uint8Array(Math.max(data.length*2,bufferedLength+binaryChunk.length));newData.set(data.subarray(dataStart,dataEnd)),data=newData}searchStartIndex-=dataStart,dataStart=0,dataEnd=bufferedLength}data.set(binaryChunk,dataEnd),dataEnd+=binaryChunk.length;let patternIndex;for(;(patternIndex=findDoubleNewlineIndex(data.subarray(searchStartIndex,dataEnd)))!==-1;)patternIndex+=searchStartIndex,yield data.slice(dataStart,patternIndex),dataStart=patternIndex,searchStartIndex=dataStart;searchStartIndex=Math.max(dataStart,dataEnd-DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES)}dataEnd>dataStart&&(yield data.slice(dataStart,dataEnd))}var SSEDecoder=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(line){if(line.endsWith("\r")&&(line=line.slice(0,-1)),!line){if(!this.event&&!this.data.length)return null;let sse={event:this.event,data:this.data.join(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{ownedSlice}from"./chunk-NLYBRJ3F.js";var MAX_PROVIDER_ERROR_BODY_CHARS=4e3;function normalizeProviderError(error){if(!(error instanceof Error))return{message:safeJsonStringify(error),messageCarriesBody:!1};let sdkError=error,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error.message.includes(body),message=status===void 0&&body===void 0?withCauseDetail(error):error.message;return{status,body,message,messageCarriesBody}}var MAX_CAUSE_DEPTH=5;function withCauseDetail(error){let deepest,current=error.cause;for(let depth=0;depth<MAX_CAUSE_DEPTH&&current instanceof Error;depth++)deepest=current,current=current.cause;if(!deepest)return error.message;let detail=(deepest.message||deepest.name).trim(),code=deepest.code;return(typeof code=="string"||typeof code=="number")&&!detail.includes(String(code))&&(detail=detail?`${detail} (${code})`:String(code)),!detail||error.message.includes(detail)?error.message:error.message?`${error.message}: ${detail}`:detail}function extractStatus(error){if(typeof error.statusCode=="number")return error.statusCode;if(typeof error.status=="number")return error.status;if(typeof error.$metadata?.httpStatusCode=="number")return error.$metadata.httpStatusCode;if(typeof error.$response?.statusCode=="number")return error.$response.statusCode}function extractBody(error){let bodyText=pickBodyText(error);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error){if(typeof error.body=="string")return error.body;if(isPlainNonEmptyObject(error.error))return safeJsonStringify(error.error);let responseBody=error.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function formatProviderError(norm,prefix){return norm.messageCarriesBody||norm.status===void 0||norm.body===void 0?prefix!==void 0&&norm.status!==void 0?`${prefix} (${norm.status}): ${norm.message}`:norm.message:prefix!==void 0?`${prefix} (${norm.status}): ${norm.body}`:`${norm.status}: ${norm.body}`}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${ownedSlice(text,0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}export{normalizeProviderError,withCauseDetail,formatProviderError,truncateErrorText};
2
+ import{ownedSlice}from"./chunk-2XOICIOV.js";var MAX_PROVIDER_ERROR_BODY_CHARS=4e3;function normalizeProviderError(error){if(!(error instanceof Error))return{message:safeJsonStringify(error),messageCarriesBody:!1};let sdkError=error,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error.message.includes(body),message=status===void 0&&body===void 0?withCauseDetail(error):error.message;return{status,body,message,messageCarriesBody}}var MAX_CAUSE_DEPTH=5;function withCauseDetail(error){let deepest,current=error.cause;for(let depth=0;depth<MAX_CAUSE_DEPTH&&current instanceof Error;depth++)deepest=current,current=current.cause;if(!deepest)return error.message;let detail=(deepest.message||deepest.name).trim(),code=deepest.code;return(typeof code=="string"||typeof code=="number")&&!detail.includes(String(code))&&(detail=detail?`${detail} (${code})`:String(code)),!detail||error.message.includes(detail)?error.message:error.message?`${error.message}: ${detail}`:detail}function extractStatus(error){if(typeof error.statusCode=="number")return error.statusCode;if(typeof error.status=="number")return error.status;if(typeof error.$metadata?.httpStatusCode=="number")return error.$metadata.httpStatusCode;if(typeof error.$response?.statusCode=="number")return error.$response.statusCode}function extractBody(error){let bodyText=pickBodyText(error);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error){if(typeof error.body=="string")return error.body;if(isPlainNonEmptyObject(error.error))return safeJsonStringify(error.error);let responseBody=error.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function formatProviderError(norm,prefix){return norm.messageCarriesBody||norm.status===void 0||norm.body===void 0?prefix!==void 0&&norm.status!==void 0?`${prefix} (${norm.status}): ${norm.message}`:norm.message:prefix!==void 0?`${prefix} (${norm.status}): ${norm.body}`:`${norm.status}: ${norm.body}`}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${ownedSlice(text,0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}export{normalizeProviderError,withCauseDetail,formatProviderError,truncateErrorText};