mu-agent 0.1.8 → 0.1.13

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 (176) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/README.md +34 -30
  3. package/dist/bundle/chunks/anthropic-messages-4PAJY4R6.js +6 -0
  4. package/dist/bundle/chunks/anthropic.js +1 -1
  5. package/dist/bundle/chunks/azure-openai-responses-Y4BBWQ3N.js +2 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +12 -9
  7. package/dist/bundle/chunks/{chunk-NG4PO5FP.js → chunk-3J3HSHLX.js} +128 -110
  8. package/dist/bundle/chunks/{chunk-TRDNDS6A.js → chunk-3V45WARH.js} +6 -3
  9. package/dist/bundle/chunks/{chunk-S3GGRYIO.js → chunk-5AGIVGSV.js} +1 -1
  10. package/dist/bundle/chunks/chunk-6QGV3IWD.js +6 -0
  11. package/dist/bundle/chunks/{chunk-4OBXYPH4.js → chunk-6Z2347ML.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-F5ZABL6Z.js → chunk-7CBJINYJ.js} +2 -2
  13. package/dist/bundle/chunks/{chunk-DRQDKNXA.js → chunk-7DDKXS2Q.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-H3QXYIF7.js → chunk-CF5GWZHW.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-RLZVFGW4.js → chunk-DYTENXHX.js} +29 -92
  16. package/dist/bundle/chunks/{chunk-NTSWBG4X.js → chunk-FLHKNMLQ.js} +1 -1
  17. package/dist/bundle/chunks/chunk-FTJT2X6E.js +2 -0
  18. package/dist/bundle/chunks/{chunk-4L3WN2XY.js → chunk-JXWJOIH4.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-TAOL3JFA.js → chunk-KIDDRTZP.js} +4 -4
  20. package/dist/bundle/chunks/chunk-LHRPMXVI.js +2 -0
  21. package/dist/bundle/chunks/chunk-LMNWTX2L.js +11 -0
  22. package/dist/bundle/chunks/chunk-LPXNMA2W.js +2 -0
  23. package/dist/bundle/chunks/chunk-LT2C56HV.js +130 -0
  24. package/dist/bundle/chunks/{chunk-6CYCI3EJ.js → chunk-LVVZS2NO.js} +1 -1
  25. package/dist/bundle/chunks/chunk-MF3VB62R.js +91 -0
  26. package/dist/bundle/chunks/chunk-NN4BEPYX.js +2 -0
  27. package/dist/bundle/chunks/{chunk-LD2P6SFZ.js → chunk-PMRZO46Y.js} +1 -1
  28. package/dist/bundle/chunks/chunk-R4VPBBDS.js +2 -0
  29. package/dist/bundle/chunks/chunk-RDZVAGPR.js +2 -0
  30. package/dist/bundle/chunks/chunk-TMTOQ7H7.js +2 -0
  31. package/dist/bundle/chunks/chunk-UKVNB6C4.js +2 -0
  32. package/dist/bundle/chunks/chunk-URBBMV3M.js +9 -0
  33. package/dist/bundle/chunks/chunk-WCGU75WO.js +11 -0
  34. package/dist/bundle/chunks/chunk-WCJNJQO5.js +9 -0
  35. package/dist/bundle/chunks/chunk-WDURT4ZM.js +2 -0
  36. package/dist/bundle/chunks/{cli-AOVD3SSZ.js → cli-M4YBZZ6Q.js} +4 -4
  37. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-MEZHQVNP.js +2 -0
  38. package/dist/bundle/chunks/codemode-worker.js +117 -13
  39. package/dist/bundle/chunks/easter-egg-3d-VFY3YRQR.js +2 -0
  40. package/dist/bundle/chunks/execute-FKI7Y4XR.js +499 -0
  41. package/dist/bundle/chunks/github-copilot.js +1 -1
  42. package/dist/bundle/chunks/{google-generative-ai-XMFHGQC5.js → google-generative-ai-D2VJQBTK.js} +1 -1
  43. package/dist/bundle/chunks/{google-vertex-4XRRNP74.js → google-vertex-SQG2BO6C.js} +1 -1
  44. package/dist/bundle/chunks/https-proxy-agent-LVOO5TPL.js +13 -0
  45. package/dist/bundle/chunks/image-resize-worker.js +1 -1
  46. package/dist/bundle/chunks/{jiti-loader-C3NU2SDH.js → jiti-loader-GL4HJFAD.js} +1 -1
  47. package/dist/bundle/chunks/{jiti-static-loader-E6ANQD5T.js → jiti-static-loader-2RCDI6B4.js} +1 -1
  48. package/dist/bundle/chunks/{lib-TEDK3E5I.js → lib-4AVRLBHM.js} +1 -1
  49. package/dist/bundle/chunks/{llama-cpp-classify-XT44PI3C.js → llama-cpp-classify-5YHLY3RC.js} +2 -2
  50. package/dist/bundle/chunks/mistral-conversations-BDARVJTT.js +5 -0
  51. package/dist/bundle/chunks/{multipart-parser-SQ6GDJL7.js → multipart-parser-FMGQ7342.js} +1 -1
  52. package/dist/bundle/chunks/{node-TWVVAGPO.js → node-AUOGOBCN.js} +1 -1
  53. package/dist/bundle/chunks/{node-N5BSDOA5.js → node-KCMANYC2.js} +1 -1
  54. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  55. package/dist/bundle/chunks/openai-codex-responses-CECGTDYD.js +10 -0
  56. package/dist/bundle/chunks/openai-codex.js +1 -1
  57. package/dist/bundle/chunks/openai-completions-UOA7MELD.js +7 -0
  58. package/dist/bundle/chunks/openai-decisions-HLM372N6.js +5 -0
  59. package/dist/bundle/chunks/openai-responses-TII7ZY5X.js +3 -0
  60. package/dist/bundle/chunks/{openrouter-images-ZVXWCSIM.js → openrouter-images-7T452AS5.js} +1 -1
  61. package/dist/bundle/chunks/{pi-messages-TM5SOOIW.js → pi-messages-2UDKLKOO.js} +1 -1
  62. package/dist/bundle/chunks/runtime-IKE5OQIW.js +2 -0
  63. package/dist/bundle/chunks/{src-UK77SYZE.js → src-QKGKDFSU.js} +1 -1
  64. package/dist/bundle/chunks/typesafe-system-one-KNCICMO5.js +2 -0
  65. package/dist/bundle/chunks/virtual-modules-TJPHLTRT.js +2 -0
  66. package/dist/bundle/cli-runtime.js +1 -1
  67. package/dist/bundle/index.js +1 -1
  68. package/dist/bundle/rpc-entry.js +1 -1
  69. package/dist/core/export-html/template.js +21 -16
  70. package/dist/modes/interactive/theme/dark.json +1 -1
  71. package/dist/modes/interactive/theme/light.json +1 -1
  72. package/dist/modes/interactive/theme/theme-schema.d.ts +28 -0
  73. package/dist/modes/interactive/theme/theme-schema.d.ts.map +1 -0
  74. package/dist/modes/interactive/theme/theme-schema.js +105 -0
  75. package/dist/modes/interactive/theme/theme-schema.js.map +1 -0
  76. package/dist/modes/interactive/theme/theme-tokens.d.ts +257 -0
  77. package/dist/modes/interactive/theme/theme-tokens.d.ts.map +1 -0
  78. package/dist/modes/interactive/theme/theme-tokens.js +94 -0
  79. package/dist/modes/interactive/theme/theme-tokens.js.map +1 -0
  80. package/dist/modes/interactive/theme/theme.d.ts +13 -16
  81. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  82. package/dist/modes/interactive/theme/theme.js +22 -29
  83. package/dist/modes/interactive/theme/theme.js.map +1 -1
  84. package/docs/cli-integration.md +1 -1
  85. package/docs/cli.md +22 -10
  86. package/docs/codemode.md +29 -6
  87. package/docs/compaction.md +5 -5
  88. package/docs/custom-provider.md +53 -1
  89. package/docs/docs.json +8 -0
  90. package/docs/environment-variables.md +3 -1
  91. package/docs/extensions.md +122 -13
  92. package/docs/json.md +3 -3
  93. package/docs/keybindings.md +5 -4
  94. package/docs/llama-cpp.md +9 -2
  95. package/docs/mcp.md +4 -2
  96. package/docs/message-types.md +22 -4
  97. package/docs/models-configuration.md +187 -0
  98. package/docs/models.md +18 -2
  99. package/docs/nvidia-rtx-llama-cpp.md +96 -0
  100. package/docs/providers.md +47 -0
  101. package/docs/sessions.md +1 -1
  102. package/docs/settings.md +9 -6
  103. package/docs/terminal-setup.md +14 -0
  104. package/docs/themes.md +4 -2
  105. package/docs/tui.md +71 -1
  106. package/docs/usage.md +1 -1
  107. package/examples/README.md +0 -3
  108. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  109. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  110. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  111. package/examples/extensions/dynamic-resources/dynamic.json +1 -1
  112. package/examples/extensions/gondolin/package-lock.json +2 -2
  113. package/examples/extensions/gondolin/package.json +1 -1
  114. package/examples/extensions/minimal-mode.ts +4 -5
  115. package/examples/extensions/overlay-test.ts +2 -2
  116. package/examples/extensions/plan-mode/index.ts +6 -2
  117. package/examples/extensions/sandbox/package-lock.json +2 -2
  118. package/examples/extensions/sandbox/package.json +1 -1
  119. package/examples/extensions/subagent/index.ts +4 -6
  120. package/examples/extensions/with-deps/package-lock.json +2 -2
  121. package/examples/extensions/with-deps/package.json +1 -1
  122. package/judge/dist/auth.js +91 -35
  123. package/judge/dist/chrome.js +2 -2
  124. package/judge/dist/import.js +852 -175
  125. package/judge/dist/setup.js +240 -153
  126. package/judge/manifest.json +2512 -546
  127. package/judge/mu/chunk-3NQ5BIBI.js +4773 -0
  128. package/judge/mu/chunk-SKGYWHW6.js +51 -0
  129. package/judge/mu/chunk-WQM4MV6L.js +58 -0
  130. package/judge/mu/cloud-code-V7FOGB4J.js +22802 -0
  131. package/judge/mu/dist-75PS4OC4.js +1283 -0
  132. package/judge/{dist/kyrn-judge.js → mu/index.js} +5365 -32809
  133. package/judge/mu/multipart-parser-ZDXVIOOP.js +372 -0
  134. package/judge/mu/src-TVVA5ZK2.js +1409 -0
  135. package/judge/themes/mu-dark.json +80 -0
  136. package/judge/themes/mu-light.json +80 -0
  137. package/kyrn/bin/kyrn-doctor +44 -19
  138. package/kyrn/bin/kyrn-judge-local +43 -14
  139. package/kyrn/bin/kyrn-ledger +16 -1
  140. package/kyrn/bin/mu.mjs +142 -61
  141. package/kyrn/local-judge/server.py +26 -14
  142. package/package.json +8 -6
  143. package/dist/bundle/chunks/anthropic-messages-MI4QHRXW.js +0 -6
  144. package/dist/bundle/chunks/azure-openai-responses-E3QGN4VN.js +0 -2
  145. package/dist/bundle/chunks/chunk-33KL6IIQ.js +0 -20
  146. package/dist/bundle/chunks/chunk-A3JYRWB6.js +0 -2
  147. package/dist/bundle/chunks/chunk-C47CLQZK.js +0 -2
  148. package/dist/bundle/chunks/chunk-HQHD6PZI.js +0 -2
  149. package/dist/bundle/chunks/chunk-KJUDFE6Y.js +0 -11
  150. package/dist/bundle/chunks/chunk-TE3GUV6H.js +0 -9
  151. package/dist/bundle/chunks/chunk-VIV3CWXG.js +0 -2
  152. package/dist/bundle/chunks/chunk-WE4MXUQS.js +0 -11
  153. package/dist/bundle/chunks/chunk-Y2PP32XV.js +0 -2
  154. package/dist/bundle/chunks/chunk-YLY6CKPK.js +0 -132
  155. package/dist/bundle/chunks/chunk-ZE5FMF3V.js +0 -99
  156. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-NM3JRRWQ.js +0 -2
  157. package/dist/bundle/chunks/easter-egg-3d-G2LUBEMZ.js +0 -2
  158. package/dist/bundle/chunks/execute-MZVUC6BB.js +0 -388
  159. package/dist/bundle/chunks/https-proxy-agent-2VXB7436.js +0 -13
  160. package/dist/bundle/chunks/mistral-conversations-Q22M3IBG.js +0 -5
  161. package/dist/bundle/chunks/openai-codex-responses-4MYQSO5E.js +0 -10
  162. package/dist/bundle/chunks/openai-completions-OSRCWAAA.js +0 -7
  163. package/dist/bundle/chunks/openai-responses-UHF3DHNG.js +0 -3
  164. package/dist/bundle/chunks/runtime-VJMMDLVH.js +0 -2
  165. package/dist/bundle/chunks/typesafe-system-one-PRR5K6CI.js +0 -2
  166. package/dist/bundle/chunks/virtual-modules-RJXJGCPI.js +0 -2
  167. package/dist/modes/interactive/theme/theme-json.d.ts +0 -85
  168. package/dist/modes/interactive/theme/theme-json.d.ts.map +0 -1
  169. package/dist/modes/interactive/theme/theme-json.js +0 -132
  170. package/dist/modes/interactive/theme/theme-json.js.map +0 -1
  171. package/dist/modes/interactive/theme/theme-schema.json +0 -361
  172. package/examples/plugins/pi-example-plugin/README.md +0 -38
  173. package/examples/plugins/pi-example-plugin/package.json +0 -10
  174. package/examples/plugins/pi-example-plugin/src/contract.ts +0 -13
  175. package/examples/plugins/pi-example-plugin/src/session.ts +0 -24
  176. package/examples/plugins/pi-example-plugin/src/tui.ts +0 -31
@@ -0,0 +1,2 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_windows=__commonJS({"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/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/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/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/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/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/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/shebang-regex/index.js"(exports,module){"use strict";module.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"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/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/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/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/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{accessSync,constants,existsSync,readFileSync,realpathSync as realpathSync2}from"fs";import{createRequire}from"module";import{homedir as homedir2}from"os";import{basename,delimiter,dirname,join as join2,resolve,sep as sep2,win32}from"path";import{fileURLToPath as fileURLToPath2}from"url";var import_cross_spawn=__toESM(require_cross_spawn(),1);import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";var EXIT_STDIO_GRACE_MS=100;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){return new Promise((resolve2,reject)=>{let settled=!1,exited=!1,exitCode=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=code=>{settled||(settled=!0,cleanup(),child.stdout?.destroy(),child.stderr?.destroy(),resolve2(code))},maybeFinalizeAfterExit=()=>{!exited||settled||stdoutEnded&&stderrEnded&&finalize(exitCode)},armIdleTimer=()=>{postExitTimer&&clearTimeout(postExitTimer),postExitTimer=setTimeout(()=>finalize(exitCode),EXIT_STDIO_GRACE_MS)},onData=()=>{exited&&!settled&&armIdleTimer()},onStdoutEnd=()=>{stdoutEnded=!0,maybeFinalizeAfterExit()},onStderrEnd=()=>{stderrEnded=!0,maybeFinalizeAfterExit()},onError=err=>{settled||(settled=!0,cleanup(),reject(err))},onExit=code=>{exited=!0,exitCode=code,maybeFinalizeAfterExit(),settled||armIdleTimer()},onClose=code=>{finalize(code)};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)})}import{realpathSync,statSync}from"node:fs";import{homedir}from"node:os";import{isAbsolute,join,resolve as nodeResolvePath,relative,sep}from"node:path";import{fileURLToPath}from"node:url";var UNICODE_SPACES=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;function canonicalizePath(path){try{return realpathSync(path)}catch{return path}}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}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("\\")?win32:{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=realpathSync2(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 getSelfUpdateUnavailableInstruction(packageName,npmCommand,updatePackageTarget=packageName){let method=detectInstallMethod(),target=normalizeSelfUpdatePackageTarget(updatePackageTarget);if(method==="bun-binary")return"Download from: https://github.com/earendil-works/pi/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}`:`This installation is not managed by a global ${method} install. Update it with the package manager, wrapper, or source checkout that provides it.`:`Update ${target.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`}function findNodePackageDir(startDir){let dir=startDir;for(;dir!==dirname(dir);){if(existsSync(join2(dir,"package.json"))){let parent=dirname(dir);return basename(dir)==="dist"&&existsSync(join2(parent,"package.json"))?parent:dir}dir=dirname(dir)}return startDir}function getPackageDir(){let envDir=process.env.PI_PACKAGE_DIR;return envDir?normalizePath(envDir):isBunBinary?dirname(process.execPath):findNodePackageDir(__dirname)}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 piConfigName=pkg.piConfig?.name,PACKAGE_NAME=pkg.name||"@earendil-works/pi-coding-agent",APP_NAME=piConfigName||"pi";function isAppExtension(extensionPath){let listed=process.env.PI_APP_EXTENSIONS;if(!listed)return!1;let target=resolve(extensionPath);return listed.split(delimiter).some(entry=>entry!==""&&resolve(entry)===target)}var APP_TITLE=piConfigName?APP_NAME:"\u03C0",CONFIG_DIR_NAME=pkg.piConfig?.configDir||".pi",VERSION=pkg.version||"0.0.0",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)}var DEFAULT_SHARE_VIEWER_URL="https://pi.dev/session/";function getShareViewerUrl(gistId){return`${process.env.PI_SHARE_VIEWER_URL||DEFAULT_SHARE_VIEWER_URL}#${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 getSessionsDir(){return join2(getAgentDir(),"sessions")}function getDebugLogPath(){return join2(getAgentDir(),`${APP_NAME}-debug.log`)}export{require_cross_spawn,spawnProcess,spawnProcessSync,waitForChildProcess,canonicalizePath,getFileRevision,isLocalPath,normalizePath,resolvePath,getCwdRelativePath,formatPathRelativeToCwdOrAbsolute,markPathIgnoredByCloudSync,splitBom,stripBom,isBunBinary,isBundledNode,detectInstallMethod,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,getPackageDir,getThemesDir,getExportTemplateDir,getReadmePath,getDocsPath,getExamplesPath,getChangelogPath,getBundledInteractiveAssetPath,getQuickJSWasmPath,getCodemodeWorkerSpecifier,detectInstallChange,PACKAGE_NAME,APP_NAME,isAppExtension,APP_TITLE,CONFIG_DIR_NAME,VERSION,ENV_AGENT_DIR,ENV_SESSION_DIR,expandTildePath,getShareViewerUrl,getAgentDir,getCustomThemesDir,getAuthPath,getSettingsPath,getBinDir,getSessionsDir,getDebugLogPath};
@@ -0,0 +1,11 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-R4VPBBDS.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{parseStreamingJson,parseToolCallArguments}from"./chunk-3V45WARH.js";import{calculateCost,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools}from"./chunk-WCGU75WO.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
+ `),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 convertResponsesMessages(model,context,allowedToolCallProviders,options){let normalizedContext=resolveTranscript(context,options?.supportsMidConvoSystemMessages),messages=[],normalizeIdPart=part=>{let sanitized=part.replace(/[^a-zA-Z0-9_-]/g,"_");return(sanitized.length>64?sanitized.slice(0,64):sanitized).replace(/_+$/,"")},buildForeignResponsesItemId=itemId=>{let normalized=`fc_${shortHash(itemId)}`;return normalized.length>64?normalized.slice(0,64):normalized},normalizeToolCallId=(id,_targetModel,source)=>{if(!allowedToolCallProviders.has(model.provider)||!id.includes("|"))return normalizeIdPart(id);let[callId,itemId]=id.split("|"),normalizedCallId=normalizeIdPart(callId),normalizedItemId=source.provider!==model.provider||source.api!==model.api?buildForeignResponsesItemId(itemId):normalizeIdPart(itemId);return normalizedItemId.startsWith("fc_")||(normalizedItemId=normalizeIdPart(`fc_${normalizedItemId}`)),`${normalizedCallId}|${normalizedItemId}`},transformedMessages=transformMessages(normalizedContext.messages,model,normalizeToolCallId),transcriptTools=resolveTranscriptTools(normalizedContext.messages,(options?.supportsAdditionalTools??!1)||(options?.supportsToolSearch??!1)),appendSystemToolAdditions=(message,seed)=>{let tools=transcriptTools.anchorsAdditions?message.toolsAdded??[]:[];if(tools.length===0)return;if(options?.supportsAdditionalTools){messages.push({type:"additional_tools",role:"developer",tools:convertResponsesTools(tools,options.toolOptions)});return}if(!options?.supportsToolSearch)return;let names=tools.map(tool=>tool.name),callId=`pi_tool_load_${shortHash(`${seed}:${names.join(",")}`)}`;messages.push({type:"tool_search_call",call_id:callId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}}),messages.push({type:"tool_search_output",call_id:callId,execution:"client",status:"completed",tools:convertResponsesTools(tools,{...options.toolOptions,toolSearchResult:!0})})},includeInitialSystemMessage=options?.includeSystemPrompt??!0,pushConfigurationUpdate=effort=>{messages.push({type:"configuration_update",reasoning:{effort}})},compat=model.compat,instructionRole=model.reasoning&&compat?.supportsDeveloperRole!==!1?"developer":"system",msgIndex=0,sourceIndex=0;for(let msg of transformedMessages){let isLeadingSystemMessage=sourceIndex++===0&&msg.role==="system";if(msg.role==="system"){if(isLeadingSystemMessage||appendSystemToolAdditions(msg,`system:${msgIndex}`),!isLeadingSystemMessage||includeInitialSystemMessage){let text=isLeadingSystemMessage?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&&messages.push({role:instructionRole,content:sanitizeSurrogates(text)})}}else if(msg.role==="user")if(typeof msg.content=="string")messages.push({role:"user",content:[{type:"input_text",text:sanitizeSurrogates(msg.content)}]});else{let content=msg.content.map(item=>item.type==="text"?{type:"input_text",text:sanitizeSurrogates(item.text)}:{type:"input_image",detail:"auto",image_url:`data:${item.mimeType};base64,${item.data}`});if(content.length===0)continue;messages.push({role:"user",content})}else if(msg.role==="assistant"){let output=[],assistantMsg=msg,isSameProviderAndApi=assistantMsg.provider===model.provider&&assistantMsg.api===model.api,isSameModel=isSameProviderAndApi&&assistantMsg.model===model.id,isDifferentModel=isSameProviderAndApi&&assistantMsg.model!==model.id,textBlockIndex=0;for(let block of msg.content)if(block.type==="thinking"){if(block.thinkingSignature){let reasoningItem=JSON.parse(block.thinkingSignature);output.push(reasoningItem)}}else if(block.type==="text"){let textBlock=block,parsedSignature=parseTextSignature(textBlock.textSignature),fallbackMessageId=textBlockIndex===0?`msg_pi_${msgIndex}`:`msg_pi_${msgIndex}_${textBlockIndex}`;textBlockIndex++;let msgId=parsedSignature?.id;msgId?msgId.length>64&&(msgId=`msg_${shortHash(msgId)}`):msgId=fallbackMessageId,output.push({type:"message",role:"assistant",content:[{type:"output_text",text:sanitizeSurrogates(textBlock.text),annotations:[]}],status:"completed",id:msgId,phase:parsedSignature?.phase})}else if(block.type==="toolCall"){let toolCall=block,[callId,itemIdRaw]=toolCall.id.split("|"),customInputProperty=options?.grammarToolInputProperties?.get(toolCall.name),itemId=itemIdRaw,itemIdPrefix=customInputProperty===void 0?"fc_":"ctc_";(isDifferentModel||!itemId?.startsWith(itemIdPrefix))&&(itemId=void 0),customInputProperty!==void 0?output.push({type:"custom_tool_call",id:itemId,call_id:callId,name:toolCall.name,input:sanitizeSurrogates(getGrammarToolInput(toolCall.name,toolCall.arguments,customInputProperty)),...isSameModel&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):output.push({type:"function_call",id:itemId,call_id:callId,name:toolCall.name,arguments:JSON.stringify(toolCall.arguments),...isSameModel&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}})}if(output.length===0)continue;options?.configurationUpdateEffort!==void 0&&isSameModel&&msg.providerThinkingLevel!==void 0&&pushConfigurationUpdate(msg.providerThinkingLevel),messages.push(...output)}else if(msg.role==="toolResult"){let[callId]=msg.toolCallId.split("|"),output=convertToolResultOutput(model,msg.content);options?.grammarToolInputProperties?.has(msg.toolName)?messages.push({type:"custom_tool_call_output",call_id:callId,output}):messages.push({type:"function_call_output",call_id:callId,output})}isLeadingSystemMessage||msgIndex++}return options?.configurationUpdateEffort!==void 0&&pushConfigurationUpdate(options.configurationUpdateEffort),messages}function convertResponsesTools(tools,options){let defaultStrict=options?.strict===void 0?!1:options.strict,supportsStrictMode=options?.supportsStrictMode??!0,supportsOpenAIGrammarTools=options?.supportsOpenAIGrammarTools??!1;return tools.map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);if(grammar)return{type:"custom",name:tool.name,description:tool.description,format:{type:"grammar",syntax:grammar.format,definition:grammar.definition},...options?.toolSearchResult?{defer_loading:!0}:{}};let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode)??defaultStrict,functionTool={type:"function",name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict===!0),...options?.toolSearchResult?{defer_loading:!0}:{}};return supportsStrictMode&&(functionTool.strict=strict),functionTool})}function getCustomToolCallInput(block){let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""}function appendCustomToolCallInput(block,nextInput,close){let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta}async function processResponsesStream(openaiStream,output,stream,model,options){let sawTerminalResponseEvent=!1,outputSlots=new Map,reasoningBlocksById=new Map,applyMessagePhaseStopReason=item=>{item.type==="message"&&item.phase==="final_answer"&&(output.stopReason="stop")},getSlot=(outputIndex,type)=>{let slot=outputSlots.get(outputIndex);return slot?.type===type?slot:void 0},pushToolCallDelta=(slot,delta)=>{delta!==void 0&&stream.push({type:"toolcall_delta",contentIndex:slot.contentIndex,delta,partial:output})},createSlot=(outputIndex,item)=>{if(item.type==="reasoning"){let block={type:"thinking",thinking:""};output.content.push(block);let slot={type:"thinking",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"thinking_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="message"){applyMessagePhaseStopReason(item);let block={type:"text",text:""};output.content.push(block);let slot={type:"text",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"text_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="function_call"){let block={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{},...item.namespace!==void 0?{namespace:item.namespace}:{},partialJson:item.arguments||""};output.content.push(block);let slot={type:"toolCall",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"toolcall_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="custom_tool_call"){let inputProperty=options?.grammarToolInputProperties?.get(item.name)??"input",input=item.input||"",block={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{[inputProperty]:input},...item.namespace!==void 0?{namespace:item.namespace}:{},customInput:{property:inputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}};output.content.push(block);let slot={type:"toolCall",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"toolcall_start",contentIndex:slot.contentIndex,partial:output}),slot}},getOrCreateSlot=(outputIndex,item)=>outputSlots.get(outputIndex)??createSlot(outputIndex,item),backfillReasoningSignatures=responseOutput=>{for(let item of responseOutput){if(item.type!=="reasoning"||!item.encrypted_content)continue;let block=reasoningBlocksById.get(item.id);if(!block?.thinkingSignature)continue;let storedItem=JSON.parse(block.thinkingSignature);storedItem.encrypted_content||(block.thinkingSignature=JSON.stringify({...storedItem,encrypted_content:item.encrypted_content}))}},finalizeResponse=response=>{if(sawTerminalResponseEvent=!0,backfillReasoningSignatures(response.output??[]),response?.id&&(output.responseId=response.id),response?.usage){let inputDetails=response.usage.input_tokens_details,cachedTokens=inputDetails?.cached_tokens||0,cacheWriteTokens=inputDetails?.cache_write_tokens||0;output.usage={input:Math.max(0,(response.usage.input_tokens||0)-cachedTokens-cacheWriteTokens),output:response.usage.output_tokens||0,cacheRead:cachedTokens,cacheWrite:cacheWriteTokens,reasoning:response.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:response.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(calculateCost(model,output.usage),options?.applyServiceTierPricing){let serviceTier=options.resolveServiceTier?options.resolveServiceTier(response?.service_tier,options.serviceTier):response?.service_tier??options.serviceTier;options.applyServiceTierPricing(output.usage,serviceTier)}let status=response?.status,incompleteDetails=response?.incomplete_details,incompleteReason=typeof incompleteDetails?.reason=="string"?incompleteDetails.reason:void 0;output.rawStopReason=incompleteReason?`${status}.${incompleteReason}`:status;let mappedStop=mapStopReason(status,incompleteReason);output.stopReason=mappedStop.stopReason,mappedStop.errorMessage===void 0?delete output.errorMessage:output.errorMessage=mappedStop.errorMessage,output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")};for await(let event of openaiStream)if(await options?.onProviderStreamEvent?.(event,model),event.type==="response.created")output.responseId=event.response.id;else if(event.type==="response.output_item.added")createSlot(event.output_index,event.item);else if(event.type==="response.reasoning_summary_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.reasoning_summary_part.done"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=`
4
+
5
+ `,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:`
6
+
7
+ `,partial:output})}else if(event.type==="response.reasoning_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.output_text.delta"){let slot=getSlot(event.output_index,"text");if(!slot)continue;slot.block.text+=event.delta,stream.push({type:"text_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.refusal.delta"){let slot=getSlot(event.output_index,"text");if(!slot)continue;slot.block.text+=event.delta,stream.push({type:"text_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.function_call_arguments.delta"){let slot=getSlot(event.output_index,"toolCall");if(!slot||slot.block.partialJson===void 0)continue;slot.block.partialJson+=event.delta,slot.block.arguments=parseStreamingJson(slot.block.partialJson),pushToolCallDelta(slot,event.delta)}else if(event.type==="response.function_call_arguments.done"){let slot=getSlot(event.output_index,"toolCall");if(!slot||slot.block.partialJson===void 0)continue;let previousPartialJson=slot.block.partialJson;if(slot.block.partialJson=event.arguments,slot.block.arguments=parseStreamingJson(slot.block.partialJson),event.arguments.startsWith(previousPartialJson)){let delta=event.arguments.slice(previousPartialJson.length);delta.length>0&&pushToolCallDelta(slot,delta)}}else if(event.type==="response.custom_tool_call_input.delta"){let slot=getSlot(event.output_index,"toolCall");if(!slot||!slot.block.customInput)continue;pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,getCustomToolCallInput(slot.block)+event.delta,!1))}else if(event.type==="response.custom_tool_call_input.done"){let slot=getSlot(event.output_index,"toolCall");if(!slot||!slot.block.customInput)continue;pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,event.input,!0))}else if(event.type==="response.output_item.done"){let item=event.item;applyMessagePhaseStopReason(item);let slot=getOrCreateSlot(event.output_index,item);if(item.type==="reasoning"&&slot?.type==="thinking"){let summaryText=item.summary?.map(s=>s.text).join(`
8
+
9
+ `)||"",contentText=item.content?.map(c=>c.text).join(`
10
+
11
+ `)||"";slot.block.thinking=summaryText||contentText||slot.block.thinking,slot.block.thinkingSignature=JSON.stringify(item),reasoningBlocksById.set(item.id,slot.block),stream.push({type:"thinking_end",contentIndex:slot.contentIndex,content:slot.block.thinking,partial:output}),outputSlots.delete(event.output_index)}else item.type==="message"&&slot?.type==="text"?(slot.block.text=item.content?.map(c=>c.type==="output_text"?c.text:c.refusal).join("")||"",slot.block.textSignature=encodeTextSignatureV1(item.id,item.phase??void 0),stream.push({type:"text_end",contentIndex:slot.contentIndex,content:slot.block.text,partial:output}),outputSlots.delete(event.output_index)):item.type==="function_call"&&slot?.type==="toolCall"&&slot.block.partialJson!==void 0?(Object.assign(slot.block,parseToolCallArguments(item.arguments||slot.block.partialJson)),item.namespace!==void 0&&(slot.block.namespace=item.namespace),delete slot.block.partialJson,stream.push({type:"toolcall_end",contentIndex:slot.contentIndex,toolCall:slot.block,partial:output}),outputSlots.delete(event.output_index)):item.type==="custom_tool_call"&&slot?.type==="toolCall"&&slot.block.customInput&&(pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,item.input??getCustomToolCallInput(slot.block),!0)),item.namespace!==void 0&&(slot.block.namespace=item.namespace),delete slot.block.customInput,stream.push({type:"toolcall_end",contentIndex:slot.contentIndex,toolCall:slot.block,partial:output}),outputSlots.delete(event.output_index))}else if(event.type==="response.completed"||event.type==="response.incomplete")finalizeResponse(event.response);else{if(event.type==="error")throw new Error(`Error Code ${event.code}: ${event.message}`||"Unknown error");if(event.type==="response.failed"){sawTerminalResponseEvent=!0,output.rawStopReason=event.response?.status;let error=event.response?.error,details=event.response?.incomplete_details,msg=error?`${error.code||"unknown"}: ${error.message||"no message"}`:details?.reason?`incomplete: ${details.reason}`:"Unknown error (no error details in response)";throw new Error(msg)}}if(!sawTerminalResponseEvent)throw new Error("OpenAI Responses stream ended before a terminal response event");if(output.stopReason==="toolUse")for(let block of output.content){if(block.type!=="toolCall")continue;let toolCall=block;if(toolCall.partialJson!==void 0||toolCall.customInput!==void 0)throw new Error(`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`)}}function mapStopReason(status,incompleteReason){if(!status)return{stopReason:"stop"};switch(status){case"completed":return{stopReason:"stop"};case"incomplete":return incompleteReason==="max_output_tokens"?{stopReason:"length"}:{stopReason:"error",errorMessage:incompleteReason?`Response incomplete: ${incompleteReason}`:"Response incomplete without a provider reason"};case"failed":case"cancelled":return{stopReason:"error"};case"in_progress":case"queued":return{stopReason:"stop"};default:{let _exhaustive=status;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}export{convertResponsesMessages,convertResponsesTools,processResponsesStream};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ var FifoQueue=class{incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(value){this.incoming.push(value)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},EventStream=class{queue=new FifoQueue;waiting=new FifoQueue;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(isComplete,extractResult){this.isComplete=isComplete,this.extractResult=extractResult,this.finalResultPromise=new Promise(resolve=>{this.resolveFinalResult=resolve})}push(event){if(this.done)return;this.isComplete(event)&&(this.done=!0,this.resolveFinalResult(this.extractResult(event)));let waiter=this.waiting.dequeue();waiter?waiter({value:event,done:!1}):this.queue.enqueue(event)}end(result){for(this.done=!0,result!==void 0&&this.resolveFinalResult(result);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let result=await new Promise(resolve=>this.waiting.enqueue(resolve));if(result.done)return;yield result.value}}}result(){return this.finalResultPromise}},AssistantMessageEventStream=class extends EventStream{#startedAt=Date.now();#startedAtMonotonic=performance.now();constructor(){super(event=>event.type==="done"||event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type for final result")})}push(event){event.type==="done"?this.#time(event.message):event.type==="error"&&this.#time(event.error),super.push(event)}end(result){result!==void 0&&this.#time(result),super.end(result)}#time(message){this.done||message.durationMs!==void 0||message.timestamp<this.#startedAt||(message.durationMs=Math.max(0,Math.round(performance.now()-this.#startedAtMonotonic)))}};function createAssistantMessageEventStream(){return new AssistantMessageEventStream}function formatThrownValue(value){return value instanceof Error?value.message||value.name:typeof value=="string"?value:String(value)}function extractDiagnosticError(error){if(!(error instanceof Error))return{name:"ThrownValue",message:formatThrownValue(error)};let code=error.code;return{name:error.name||void 0,message:error.message||error.name,stack:error.stack,code:typeof code=="string"||typeof code=="number"?code:void 0}}function createAssistantMessageDiagnostic(type,error,details){return{type,timestamp:Date.now(),error:extractDiagnosticError(error),details}}function appendAssistantMessageDiagnostic(message,diagnostic){message.diagnostics=[...message.diagnostics??[],diagnostic]}export{EventStream,AssistantMessageEventStream,createAssistantMessageEventStream,formatThrownValue,extractDiagnosticError,createAssistantMessageDiagnostic,appendAssistantMessageDiagnostic};