@code-yeongyu/senpi 2026.9.18 → 2026.9.19-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +117 -0
- package/dist/bundle/chunks/{anthropic-messages-ZEJ3DPCP.js → anthropic-messages-WZCFP6BT.js} +1 -1
- package/dist/bundle/chunks/{app-server-command-ELSORC4D.js → app-server-command-QBJ4GPN7.js} +1 -1
- package/dist/bundle/chunks/bun-extension-importer-JQZRPNJH.js +10 -0
- package/dist/bundle/chunks/{chunk-Y6HDGVS5.js → chunk-34GCWLNV.js} +1 -1
- package/dist/bundle/chunks/{chunk-XJUVWITG.js → chunk-3FRTRCR6.js} +1 -1
- package/dist/bundle/chunks/chunk-5E5TLB76.js +8 -0
- package/dist/bundle/chunks/{chunk-AH72FRZ2.js → chunk-EHSDTQ6I.js} +13 -13
- package/dist/bundle/chunks/{chunk-VRAYXSST.js → chunk-FDLVINNY.js} +2 -2
- package/dist/bundle/chunks/{chunk-QNZ24YOQ.js → chunk-HGAX6JZ7.js} +3 -1
- package/dist/bundle/chunks/{chunk-QGBRSL64.js → chunk-HSH674C6.js} +1 -1
- package/dist/bundle/chunks/chunk-IUZUN32Z.js +13 -0
- package/dist/bundle/chunks/chunk-IXAUDPOK.js +2 -0
- package/dist/bundle/chunks/{chunk-NLOZDJQX.js → chunk-LF3XTYYF.js} +3 -3
- package/dist/bundle/chunks/{chunk-ANTGWIGI.js → chunk-MUC3MZTV.js} +1 -1
- package/dist/bundle/chunks/chunk-NQAVM5XL.js +2 -0
- package/dist/bundle/chunks/chunk-P7PWCGLJ.js +5 -0
- package/dist/bundle/chunks/{chunk-4C7LNOHI.js → chunk-PLZK7ABD.js} +1 -1
- package/dist/bundle/chunks/{chunk-CKNRCW35.js → chunk-RLRLQRI2.js} +1 -1
- package/dist/bundle/chunks/{chunk-7FXIHFZU.js → chunk-UAYBYTFN.js} +1 -1
- package/dist/bundle/chunks/{chunk-7A47FVQC.js → chunk-W4SRGDQ4.js} +3 -6
- package/dist/bundle/chunks/{chunk-QROWINIH.js → chunk-XK24AFYU.js} +1 -1
- package/dist/bundle/chunks/cli-main-MLJ2H637.js +3 -0
- package/dist/bundle/chunks/cursor-agent.js +38 -0
- package/dist/bundle/chunks/cursor.js +2 -0
- package/dist/bundle/chunks/devin-agent.js +5 -0
- package/dist/bundle/chunks/devin.js +75 -0
- package/dist/bundle/chunks/{help-fast-path-WQCATMI4.js → help-fast-path-RQDCLDQT.js} +1 -1
- package/dist/bundle/chunks/host-command-3LS772D5.js +2 -0
- package/dist/bundle/chunks/{host-lifecycle-EAXSS3F2.js → host-lifecycle-TA5XGUW5.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +20 -0
- package/dist/bundle/chunks/interactive-host-runtime-AITXUDCT.js +4 -0
- package/dist/bundle/chunks/interactive-mode-7C75IXNF.js +2 -0
- package/dist/bundle/chunks/{multi-session-host-OK6WMHB4.js → multi-session-host-2YCJKQOL.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-2RS3VSPV.js → openai-completions-TOWYKX2U.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-C2K4YRGI.js → package-manager-cli-4ANSELYT.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-536AQTIS.js → rotation-stream-KDLA7K6X.js} +1 -1
- package/dist/bundle/chunks/rpc-mode-OPFQIWFP.js +2 -0
- package/dist/bundle/chunks/{session-picker-BUHK3FCS.js → session-picker-DXCITGLS.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +359 -346
- package/dist/bundle/chunks/{state-store-OYDXEIXU.js → state-store-HBBOD7I5.js} +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +2 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/deferred-commands.d.ts +7 -0
- package/dist/cli/deferred-commands.d.ts.map +1 -1
- package/dist/cli/deferred-commands.js +12 -0
- package/dist/cli/deferred-commands.js.map +1 -1
- package/dist/cli/host-command.d.ts +21 -0
- package/dist/cli/host-command.d.ts.map +1 -0
- package/dist/cli/host-command.js +148 -0
- package/dist/cli/host-command.js.map +1 -0
- package/dist/core/agent-session.d.ts +4 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +57 -33
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.js +2 -17
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-8.d.ts +3 -0
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-8.d.ts.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-8.js +5 -0
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-8.js.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.d.ts +3 -0
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.d.ts.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.js +28 -0
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.js.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/presets.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/presets.js +21 -1
- package/dist/core/extensions/builtin/prompt-preset/presets.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.js +1 -0
- package/dist/core/extensions/builtin/prompt-preset/settings.js.map +1 -1
- package/dist/core/extensions/bun-extension-importer.d.ts.map +1 -1
- package/dist/core/extensions/bun-extension-importer.js +31 -5
- package/dist/core/extensions/bun-extension-importer.js.map +1 -1
- package/dist/core/extensions/bun-extension-registry.d.ts +9 -0
- package/dist/core/extensions/bun-extension-registry.d.ts.map +1 -1
- package/dist/core/extensions/bun-extension-registry.js +72 -16
- package/dist/core/extensions/bun-extension-registry.js.map +1 -1
- package/dist/core/extensions/extension-runtime-module.d.ts +5 -0
- package/dist/core/extensions/extension-runtime-module.d.ts.map +1 -0
- package/dist/core/extensions/extension-runtime-module.js +6 -0
- package/dist/core/extensions/extension-runtime-module.js.map +1 -0
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -0
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +7 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/index.d.ts +3 -0
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js +5 -0
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/rpc/host-daemon-env.d.ts +18 -0
- package/dist/modes/rpc/host-daemon-env.d.ts.map +1 -0
- package/dist/modes/rpc/host-daemon-env.js +95 -0
- package/dist/modes/rpc/host-daemon-env.js.map +1 -0
- package/dist/modes/rpc/host-decision.d.ts +1 -1
- package/dist/modes/rpc/host-decision.d.ts.map +1 -1
- package/dist/modes/rpc/host-decision.js +2 -0
- package/dist/modes/rpc/host-decision.js.map +1 -1
- package/dist/modes/rpc/host-ensure.js +8 -1
- package/dist/modes/rpc/host-ensure.js.map +1 -1
- package/dist/modes/rpc/host-launch-spec.d.ts +43 -0
- package/dist/modes/rpc/host-launch-spec.d.ts.map +1 -0
- package/dist/modes/rpc/host-launch-spec.js +183 -0
- package/dist/modes/rpc/host-launch-spec.js.map +1 -0
- package/dist/modes/rpc/host-launch.d.ts +3 -1
- package/dist/modes/rpc/host-launch.d.ts.map +1 -1
- package/dist/modes/rpc/host-launch.js +24 -5
- package/dist/modes/rpc/host-launch.js.map +1 -1
- package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
- package/dist/modes/rpc/host-lifecycle.js +36 -2
- package/dist/modes/rpc/host-lifecycle.js.map +1 -1
- package/dist/modes/rpc/host-probe.d.ts +7 -0
- package/dist/modes/rpc/host-probe.d.ts.map +1 -1
- package/dist/modes/rpc/host-probe.js +15 -4
- package/dist/modes/rpc/host-probe.js.map +1 -1
- package/dist/modes/rpc/host-process-metrics.d.ts +10 -0
- package/dist/modes/rpc/host-process-metrics.d.ts.map +1 -0
- package/dist/modes/rpc/host-process-metrics.js +83 -0
- package/dist/modes/rpc/host-process-metrics.js.map +1 -0
- package/dist/modes/rpc/host-runner.d.ts +38 -0
- package/dist/modes/rpc/host-runner.d.ts.map +1 -0
- package/dist/modes/rpc/host-runner.js +195 -0
- package/dist/modes/rpc/host-runner.js.map +1 -0
- package/dist/modes/rpc/host-status.d.ts +58 -0
- package/dist/modes/rpc/host-status.d.ts.map +1 -0
- package/dist/modes/rpc/host-status.js +117 -0
- package/dist/modes/rpc/host-status.js.map +1 -0
- package/docs/extensions.md +35 -0
- package/docs/providers.md +30 -0
- package/docs/rpc.md +177 -15
- package/docs/settings.md +1 -1
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +84 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/README.md +9 -0
- package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts +2 -2
- package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/models.generated.js +2 -2
- package/node_modules/@earendil-works/pi-ai/dist/models.generated.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/all.d.ts +150 -7
- package/node_modules/@earendil-works/pi-ai/dist/providers/all.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/all.js +17 -3
- package/node_modules/@earendil-works/pi-ai/dist/providers/all.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.d.ts +13 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.js +55 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai.d.ts +11 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai.js +94 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.d.ts +4 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.js +6 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/bai.json +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/venice.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.models.d.ts +142 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.models.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.models.js +156 -3
- package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.models.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
- package/dist/bundle/chunks/bun-extension-importer-SW7XGNSG.js +0 -10
- package/dist/bundle/chunks/chunk-AGXZF7RF.js +0 -2
- package/dist/bundle/chunks/chunk-F5JZNLDE.js +0 -8
- package/dist/bundle/chunks/cli-main-4TWJXJKM.js +0 -3
- package/dist/bundle/chunks/interactive-host-runtime-EDXG6A5L.js +0 -4
- package/dist/bundle/chunks/interactive-mode-PD7S7KFZ.js +0 -2
- package/dist/bundle/chunks/rpc-mode-TIJFUWXS.js +0 -2
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/kimi-coding.json +0 -1
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
3
|
+
var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function(){try{return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e){throw mod=0,e}};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod));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(stat2,path,options){return!stat2.isSymbolicLink()&&!stat2.isFile()?!1:checkPathExt(path,options)}function isexe(path,options,cb){fs.stat(path,function(er,stat2){cb(er,er?!1:checkStat(stat2,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,stat2){cb(er,er?!1:checkStat(stat2,options))})}function sync(path,options){return checkStat(fs.statSync(path),options)}function checkStat(stat2,options){return stat2.isFile()&&checkMode(stat2,options)}function checkMode(stat2,options){var mod=stat2.mode,uid=stat2.uid,gid=stat2.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(resolve3,reject){isexe(path,options||{},function(er,is){er?reject(er):resolve3(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((resolve3,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve3(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;resolve3(subStep(p,i,0))}),subStep=(p,i,ii)=>new Promise((resolve3,reject)=>{if(ii===pathExt.length)return resolve3(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 resolve3(p+ext);return resolve3(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 parse2(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=parse2}});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"),parse2=require_parse(),enoent=require_enoent();function spawn2(command,args,options){let parsed=parse2(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=parse2(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=spawn2;module.exports.spawn=spawn2;module.exports.sync=spawnSync;module.exports._parse=parse2;module.exports._enoent=enoent}});import{spawn}from"node:child_process";import{randomUUID as randomUUID2}from"node:crypto";import{existsSync as existsSync2,readFileSync as readFileSync2,realpathSync as realpathSync2,writeSync}from"node:fs";import{access,chmod as chmod2,mkdir as mkdir3,readFile as readFile4,rename as rename3,rm as rm2,unlink as unlink2,writeFile as writeFile4}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{tmpdir}from"node:os";import{dirname as dirname5,extname,join as join5,resolve as resolve2}from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";import{accessSync,constants,existsSync,readFileSync,realpathSync}from"fs";import{homedir as homedir2}from"os";import{basename,dirname as dirname2,join as join3,resolve,sep as sep2,win32}from"path";import{fileURLToPath as fileURLToPath2}from"url";var BUN_LAUNCHER_REPAIR_SOURCE=`
|
|
4
|
+
import { renameSync, writeFileSync } from "node:fs";
|
|
5
|
+
const [launcher, entrypoint] = process.argv.slice(1);
|
|
6
|
+
if (!launcher || !entrypoint) throw new Error("Missing Bun launcher repair path");
|
|
7
|
+
const quote = (value) => "'" + value.replaceAll("'", "'\\"'\\"'") + "'";
|
|
8
|
+
const temporary = launcher + "." + process.pid + ".tmp";
|
|
9
|
+
writeFileSync(temporary, "#!/bin/sh\\nexec " + quote(process.execPath) + " " + quote(entrypoint) + " \\"$@\\"\\n", { mode: 0o755 });
|
|
10
|
+
renameSync(temporary, launcher);
|
|
11
|
+
`.trim();var BRAND_ENV_VAR="SENPI_BRAND";function readChangelog(source){let value=source.changelog;if(typeof value!="object"||value===null||Array.isArray(value))return;let changelog=value,path=readString(changelog,"path");if(!path?.startsWith("/")||path.includes("\0"))return;let version=readString(changelog,"version");return{path,...version?{version}:{}}}function readUpdateChannel(source){let update=source.update;if(typeof update!="object"||update===null||Array.isArray(update))return;let channel=update,packageName=readString(channel,"packageName"),command=readString(channel,"command");if(!(!packageName||!command))return{packageName,distTag:readString(channel,"distTag")||"latest",command,changelogUrl:readString(channel,"changelogUrl")}}function isSafeConfigDirName(value){return value!=="."&&value!==".."&&!/[\\/]/.test(value)}function readString(source,key){let value=source[key];return typeof value=="string"&&value.trim()?value.trim():void 0}function parseBrandProfile(raw){if(!raw?.trim())return;let parsed;try{parsed=JSON.parse(raw)}catch{process.stderr.write(`warning: ignoring malformed ${BRAND_ENV_VAR} (expected JSON)
|
|
12
|
+
`);return}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){process.stderr.write(`warning: ignoring malformed ${BRAND_ENV_VAR} (expected a JSON object)
|
|
13
|
+
`);return}let source=parsed,name=readString(source,"name");if(!name){process.stderr.write(`warning: ignoring ${BRAND_ENV_VAR} without a "name"
|
|
14
|
+
`);return}let configDir=readString(source,"configDir")||`.${name}`;if(!isSafeConfigDirName(configDir)){process.stderr.write(`warning: ignoring ${BRAND_ENV_VAR} with an unsafe "configDir"
|
|
15
|
+
`);return}let changelog=readChangelog(source);return{name,command:readString(source,"command"),displayVersion:readString(source,"displayVersion"),configDir,flatLayout:source.flatLayout===!0,envPrefix:(readString(source,"envPrefix")||name).toUpperCase(),userAgent:readString(source,"userAgent")||name,originator:readString(source,"originator"),update:readUpdateChannel(source),...changelog?{changelog}:{}}}function consumeBrandProfile(env=process.env){return parseBrandProfile(env[BRAND_ENV_VAR])}var LEGACY_ENV_PREFIXES=["SENPI","PI"],cachedProfile,profileResolved=!1;function brandProfile(){return profileResolved||(cachedProfile=consumeBrandProfile(),profileResolved=!0),cachedProfile}function brandEnvNames(suffix,profile=brandProfile()){let prefixes=[profile?.envPrefix,...LEGACY_ENV_PREFIXES].filter(prefix=>typeof prefix=="string"&&prefix.length>0);return[...new Set(prefixes)].map(prefix=>`${prefix}_${suffix}`)}function envValue(suffix,env=process.env){for(let name of brandEnvNames(suffix)){let value=env[name];if(value!==void 0)return value}}import{lstatSync}from"node:fs";import{dirname,join,normalize}from"node:path";var MAX_PARENT_CONFIG_SEARCH_DEPTH=100;function isDirectory(path){try{return lstatSync(path).isDirectory()}catch{return!1}}function isFile(path){try{return lstatSync(path).isFile()}catch{return!1}}function findNearestParentConfigDir(cwd,homeDir,configDirName,requiredChildDir,requiredChildFile){let normalizedHomeDir=normalize(homeDir),currentDir=normalize(cwd);for(let depth=0;depth<=MAX_PARENT_CONFIG_SEARCH_DEPTH;depth+=1){if(currentDir===normalizedHomeDir)return;let configDir=join(currentDir,configDirName),hasRequiredChild=requiredChildFile?isFile(join(configDir,requiredChildFile)):!requiredChildDir||isDirectory(join(configDir,requiredChildDir));if(isDirectory(configDir)&&hasRequiredChild)return configDir;let parentDir=dirname(currentDir);if(parentDir===currentDir)return;currentDir=parentDir}}var import_cross_spawn=__toESM(require_cross_spawn(),1);import{homedir}from"node:os";import{isAbsolute,join as join2,resolve as nodeResolvePath,parse,relative,sep}from"node:path";import{fileURLToPath}from"node:url";var UNICODE_SPACES=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;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 join2(home,normalized.slice(2))}return/^file:\/\//.test(normalized)?fileURLToPath(normalized):normalized}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=dirname2(__filename),isBunBinary=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),isBunRuntime=!!process.versions.bun,isBundledNode=!0;function findNodePackageDir(startDir){let dir=startDir;for(;dir!==dirname2(dir);){if(existsSync(join3(dir,"package.json"))){let parent=dirname2(dir);return basename(dir)==="dist"&&existsSync(join3(parent,"package.json"))?parent:dir}dir=dirname2(dir)}return startDir}function getPackageDir(){let envDir=envValue("PACKAGE_DIR");return envDir?normalizePath(envDir):isBunBinary?dirname2(process.execPath):findNodePackageDir(__dirname)}function getPackageJsonPath(){return join3(getPackageDir(),"package.json")}var pkg={};try{pkg=JSON.parse(stripBom(readFileSync(getPackageJsonPath(),"utf-8")))}catch(e){if(e.code!=="ENOENT")throw e}var piConfigName=pkg.piConfig?.name,BRAND=brandProfile(),PACKAGE_NAME=pkg.name||"@earendil-works/pi-coding-agent",APP_NAME=BRAND?.name||piConfigName||"pi",APP_COMMAND=BRAND?.command??APP_NAME,APP_TITLE=BRAND?.name||(piConfigName?APP_NAME:"\u03C0"),CONFIG_DIR_NAME=BRAND?.configDir||pkg.piConfig?.configDir||".pi",CONFIG_FLAT_LAYOUT=BRAND?.flatLayout===!0,VERSION=pkg.version||"0.0.0",DISPLAY_VERSION=BRAND?.displayVersion||VERSION,ENV_PREFIX=BRAND?.envPrefix||APP_NAME.toUpperCase(),ENV_AGENT_DIR=`${ENV_PREFIX}_CODING_AGENT_DIR`,ENV_SESSION_DIR=`${ENV_PREFIX}_CODING_AGENT_SESSION_DIR`;var FLAT_LAYOUT_SENTINEL="settings.json";function resolveAgentDir(cwd,homeDir,envDir){if(envDir)return normalizePath(envDir,{homeDir});if(CONFIG_FLAT_LAYOUT)return findNearestParentConfigDir(cwd,homeDir,CONFIG_DIR_NAME,void 0,FLAT_LAYOUT_SENTINEL)??join3(homeDir,CONFIG_DIR_NAME);let projectConfigDir=findNearestParentConfigDir(cwd,homeDir,CONFIG_DIR_NAME,"agent");return projectConfigDir?join3(projectConfigDir,"agent"):join3(homeDir,CONFIG_DIR_NAME,"agent")}function getAgentDir(){return resolveAgentDir(process.cwd(),homedir2(),envValue("CODING_AGENT_DIR"))}import{execFile}from"node:child_process";function parseDaemonPidFile(text){let parsed;try{parsed=JSON.parse(text)}catch(error){if(error instanceof SyntaxError)return;throw error}let unguarded=parsed!==null&&isRecord(parsed)&&parsed.processStartTime===null;if(!(!isRecord(parsed)||typeof parsed.pid!="number"||!unguarded&&typeof parsed.processStartTime!="string")&&!(!Number.isInteger(parsed.pid)||parsed.pid<=0)){if(unguarded)return{pid:parsed.pid,processStartTime:null};if(!(typeof parsed.processStartTime!="string"||parsed.processStartTime.trim()===""))return{pid:parsed.pid,processStartTime:parsed.processStartTime}}}async function readProcessIdentity(pid,platform=process.platform,timeoutMs,isLive=processIsLive){let command=platform==="win32"?{executable:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`$process = Get-CimInstance Win32_Process -Filter "ProcessId=${String(pid)}" -ErrorAction Stop; if ($null -eq $process) { Write-Output '__SENPI_ABSENT__'; exit 0 }; $process.CreationDate.ToFileTimeUtc().ToString("D", [Globalization.CultureInfo]::InvariantCulture)`]}:{executable:"ps",args:["-o","lstart=","-p",String(pid)]};return new Promise(resolve3=>{let effectiveTimeoutMs=timeoutMs??(platform==="win32"?1e3:void 0);execFile(command.executable,command.args,{windowsHide:!0,...effectiveTimeoutMs===void 0?{}:{timeout:effectiveTimeoutMs}},(error,stdout)=>{if(error){let code="code"in error?error.code:void 0;if(platform!=="win32"&&code===1||!isLive(pid)){resolve3({kind:"absent"});return}resolve3({kind:"error",error});return}let output=stdout.trim();if(output==="__SENPI_ABSENT__")return resolve3({kind:"absent"});if(!output||platform==="win32"&&!/^\d+$/.test(output))return resolve3({kind:"error",error:new Error("invalid process identity output")});resolve3({kind:"present",identity:output})}).once("error",error=>resolve3({kind:"error",error}))})}async function readProcessStartTime(pid,platform=process.platform,timeoutMs){return readProcessIdentity(pid,platform,timeoutMs).then(result=>{if(result.kind==="error")throw result.error;return result.kind==="present"?result.identity:void 0})}function processIsLive(pid){try{return process.kill(pid,0),!0}catch(error){if(isNodeErrorCode(error,"ESRCH"))return!1;if(isNodeErrorCode(error,"EPERM"))return!0;throw error}}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNodeErrorCode(error,code){return error instanceof Error&&"code"in error&&error.code===code}import{createHash}from"node:crypto";import{basename as basename2,join as join4,win32 as win322}from"node:path";var HOST_DAEMON_DIR_ENV="SENPI_RPC_HOST_DAEMON_DIR";function daemonDirectoryName(socket,platform=process.platform){let canonical=platform==="win32"?win322.normalize(socket).toLowerCase():socket;return createHash("sha256").update(canonical,"utf8").digest("hex").slice(0,16)}function createHostDaemonPaths(target){let flatDir=join4(target.agentDir??getAgentDir(),"rpc-host-daemon"),dir=join4(flatDir,daemonDirectoryName(target.socket));return{flatDir,layoutMarker:join4(flatDir,"layout.json"),legacyPidFile:join4(flatDir,"host.pid"),dir,pointerFile:join4(dir,"host.pid"),lockFile:join4(dir,"daemon.lock"),settingsFile:join4(dir,"settings.json"),stderrLog:join4(dir,"stderr.log"),generationsDir:join4(dir,"generations"),reservationsDir:join4(dir,"reservations")}}function generationPaths(paths,instanceId){let dir=join4(paths.generationsDir,instanceId);return{dir,relativeDir:`generations/${instanceId}`,pidFile:join4(dir,"host.pid"),settingsFile:join4(dir,"settings.json"),scratchDir:join4(dir,"scratch")}}import{rename,rm}from"node:fs/promises";var CALVER=/^(\d+)\.(\d+)\.(\d+)(?:-(\d+))?/;function engineBuildIdentityFrom(build){let match=CALVER.exec(build.version),epoch=Number.isSafeInteger(build.epoch)&&build.epoch!==void 0&&build.epoch>0?build.epoch:0,sha7=build.sha7??"";return{text:epoch===0?build.version:`${build.version}+${epoch}${sha7===""?"":`.${sha7}`}`,ordinal:[match?Number(match[1]):0,match?Number(match[2]):0,match?Number(match[3]):0,match?.[4]?Number(match[4]):0,epoch],scheme:epoch===0?"nodef":"epoch"}}var BUILT=engineBuildIdentityFrom({version:VERSION,epoch:typeof SENPI_BUILD_EPOCH=="number"?SENPI_BUILD_EPOCH:0,sha7:typeof SENPI_BUILD_SHA7=="string"?SENPI_BUILD_SHA7:""});import{readFile,writeFile}from"node:fs/promises";async function readFileOrUndefined(path){try{return await readFile(path,"utf8")}catch(error){if(isNodeErrorCode2(error,"ENOENT")||isNodeErrorCode2(error,"ENOTDIR"))return;throw error}}function parseJson(text){if(text!==void 0)try{let parsed=JSON.parse(text);return isRecord2(parsed)?parsed:void 0}catch{return}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNodeErrorCode2(error,code){return error instanceof Error&&"code"in error&&error.code===code}async function releaseGeneration(paths,owner){let generation=generationPaths(paths,owner.instanceId),record=parseDaemonPidFile(await readFileOrUndefined(generation.pidFile)??"");if(record!==void 0&&record.pid!==owner.pid)return;parseJson(await readFileOrUndefined(paths.pointerFile))?.instance_id===owner.instanceId&&(await rm(paths.pointerFile,{force:!0}),await rm(paths.settingsFile,{force:!0})),await rm(generation.dir,{recursive:!0,force:!0})}var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID";var HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";import{StringDecoder}from"node:string_decoder";var MAX_RPC_LINE_CHARACTERS=16*1024*1024;function attachJsonlLineReader(stream,onLine,options={}){let decoder=new StringDecoder("utf8"),maxLineLength=options.maxLineLength??Number.POSITIVE_INFINITY;if(!(maxLineLength>0))throw new Error("maxLineLength must be greater than zero.");let buffer="",discardingOversizedLine=!1,consume=text=>{let offset=0;for(;offset<text.length;){if(discardingOversizedLine){let newlineIndex2=text.indexOf(`
|
|
16
|
+
`,offset);if(newlineIndex2===-1)return;discardingOversizedLine=!1,offset=newlineIndex2+1;continue}let newlineIndex=text.indexOf(`
|
|
17
|
+
`,offset);if(newlineIndex===-1){let remainder=text.slice(offset);buffer.length+remainder.length>maxLineLength?(buffer="",discardingOversizedLine=!0,options.onOversizedLine?.()):buffer+=remainder;return}let segment=text.slice(offset,newlineIndex);if(buffer.length+segment.length>maxLineLength)options.onOversizedLine?.();else{let line=buffer+segment;onLine(line.endsWith("\r")?line.slice(0,-1):line)}buffer="",offset=newlineIndex+1}},onData=chunk=>{consume(typeof chunk=="string"?chunk:decoder.write(chunk))},onEnd=()=>{consume(decoder.end()),!discardingOversizedLine&&buffer.length>0&&onLine(buffer.endsWith("\r")?buffer.slice(0,-1):buffer),buffer="",discardingOversizedLine=!1};return stream.on("data",onData),stream.on("end",onEnd),()=>{stream.off("data",onData),stream.off("end",onEnd)}}import{createHash as createHash2,randomUUID}from"node:crypto";var HOST_INSTANCE_ID_ENV="SENPI_RPC_HOST_INSTANCE_ID",INSTANCE_ID=resolveInstanceId(process.env[HOST_INSTANCE_ID_ENV]);function resolveInstanceId(value){return value!==void 0&&value.trim()!==""?value:randomUUID()}import{mkdir,readFile as readFile2,rename as rename2,stat,unlink,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname3}from"node:path";var PUBLIC_SOCKET_IDENTITY_FILE="public-socket.owner";var MAX_SOCKET_PATH_BYTES=103;function sameSocketIdentity(a,b){return a.dev===b.dev&&a.ino===b.ino}async function statSocketIdentity(socketPath){try{let{dev,ino}=await stat(socketPath);return{dev,ino}}catch(cause){if(isNodeErrorCode3(cause,"ENOENT"))return;throw cause}}async function writeSocketIdentityFile(path,identity){await mkdir(dirname3(path),{recursive:!0,mode:448});let tmpPath=`${path}.${process.pid}.tmp`;await writeFile2(tmpPath,`${JSON.stringify(identity)}
|
|
18
|
+
`,{mode:384}),await rename2(tmpPath,path)}async function unlinkOwnedSocket(socketPath,identity,log){if(process.platform==="win32"||socketPath.startsWith("\0"))return;let current;try{current=await statSocketIdentity(socketPath)}catch(cause){log(`socket ${socketPath} ownership could not be verified (${errorMessage(cause)}); leaving it`);return}if(current!==void 0){if(identity===void 0){log(`socket path ${socketPath} ownership unknown; leaving it`);return}if(!sameSocketIdentity(current,identity)){log(`socket path ${socketPath} now owned by another host; leaving it`);return}try{await unlink(socketPath)}catch(cause){isNodeErrorCode3(cause,"ENOENT")||log(`socket ${socketPath} removal failed (${errorMessage(cause)})`)}}}async function shieldSocketDuringClose(socketPath,close){if(process.platform==="win32"||socketPath.startsWith("\0"))return close();let shieldPath=`${socketPath}.shield-${process.pid}`,shielded=!1;try{await statSocketIdentity(socketPath)!==void 0&&(await rename2(socketPath,shieldPath),shielded=!0)}catch{}try{await close()}finally{if(shielded)try{await rename2(shieldPath,socketPath)}catch{}}}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode3(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}import{createHash as createHash3,randomBytes,timingSafeEqual}from"node:crypto";import{chmod,mkdir as mkdir2,readFile as readFile3,writeFile as writeFile3}from"node:fs/promises";import{dirname as dirname4,win32 as win323}from"node:path";var WINDOWS_PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",SOCKET_SECRET_BYTES=32,SOCKET_SECRET_SUFFIX=".secret",SOCKET_SECRET_FILE_ENV="SENPI_RPC_SOCKET_SECRET_FILE",SOCKET_HANDSHAKE_TIMEOUT_MS=2e3;function socketSecretPath(logicalPath){if(logicalPath.toLowerCase().startsWith("\\\\.\\pipe\\"))throw new Error(`Windows RPC named-pipe addresses need a logical filesystem path for their secret: ${logicalPath}`);return`${logicalPath}${SOCKET_SECRET_SUFFIX}`}async function ensureSocketSecret(path){try{let existing=await readFile3(path);if(existing.length===SOCKET_SECRET_BYTES)return existing}catch(error){if(!isNodeErrorCode4(error,"ENOENT"))throw error}return createSocketSecret(path)}async function createSocketSecret(path){await mkdir2(dirname4(path),{recursive:!0});let secret=randomBytes(SOCKET_SECRET_BYTES);return await writeFile3(path,secret,{mode:384}),await chmod(path,384),secret}function resolveSocketTransportAddress(socketPath,platform,secret){if(platform!=="win32"||socketPath.toLowerCase().startsWith("\\\\.\\pipe\\"))return socketPath;if(!/^[a-zA-Z]:[\\/]/.test(socketPath)&&!/^\\\\[^/]/.test(socketPath))throw new Error(`Windows RPC socket path must be drive-qualified or UNC: ${socketPath}`);let canonical=win323.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret??[])]),name=createHash3("sha256").update(identity).digest("hex").slice(0,32);return`${WINDOWS_PIPE_PREFIX}${name}`}function authenticateSocket(socket,secret,onAuthenticated){let received=Buffer.alloc(0),finish=()=>{clearTimeout(timer),socket.off("data",onData),socket.off("error",onError)},onError=()=>{finish(),socket.destroy()},timer=setTimeout(()=>{finish(),socket.destroy()},SOCKET_HANDSHAKE_TIMEOUT_MS),onData=chunk=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(finish(),!timingSafeEqual(received.subarray(0,secret.length),Buffer.from(secret))){socket.destroy();return}let remainder=received.subarray(secret.length);remainder.length>0&&socket.unshift(remainder),onAuthenticated()};socket.on("data",onData),socket.once("error",onError),socket.once("close",finish)}function sendSocketHandshake(socket,secret){socket.write(Buffer.from(secret))}function isNodeErrorCode4(error,code){return error instanceof Error&&"code"in error&&error.code===code}var HOST_COLD_START_ENV="SENPI_RPC_HOST_COLD_START",HOST_IDLE_EXIT_MS_ENV="SENPI_RPC_HOST_IDLE_EXIT_MS",DEFAULT_HOST_IDLE_EXIT_MS=15*6e4,CHILD_STOP_TIMEOUT_MS=5e3,WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS=2e3,CHILD_WATCH_FD=3;async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join5(baseDir,`internal-${randomUUID2()}`);return await mkdir3(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID2()}`,dir:dir2,secretPath:join5(dir2,"secret")}}let dir=join5(tmpdir(),`senpi-rpc-host-internal-${randomUUID2().slice(0,8)}`);return await mkdir3(dir,{recursive:!1,mode:448}),await writeFile4(join5(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join5(dir,"host.sock"),dir,secretPath:join5(dir,".secret")}}function parseColdStart(value){return value==="transient"||value==="persistent"?value:void 0}function parseIdleExitMs(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}function resolveHostPolicy(settings,env){let record=isRecord3(settings)?settings:{},coldStart=parseColdStart(env[HOST_COLD_START_ENV])??parseColdStart(asOptionalString(record.coldStart))??"transient",idleExitMs=parseIdleExitMs(env[HOST_IDLE_EXIT_MS_ENV])??parseIdleExitMs(asOptionalString(record.idleExitMs))??DEFAULT_HOST_IDLE_EXIT_MS;return{coldStart,idleExitMs}}function classifyChildExit(code,signal){return code===0&&signal===null?{reason:"rpc host exited on its own idle policy",exitCode:0}:{reason:`rpc host process exited unexpectedly (${code??signal})`,exitCode:1}}var IdleExitDecider=class{constructor(idleExitMs,now=Date.now){this.idleExitMs=idleExitMs,this.now=now}update(activity){return activity.connections>0||activity.activeTurns>0?(this.idleSince=void 0,"active"):this.idleExitMs===Number.POSITIVE_INFINITY?"idle":this.idleSince===void 0?(this.idleSince=this.now(),"idle"):this.now()-this.idleSince>=this.idleExitMs?"exit":"idle"}},INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,bindSocket,replaceIdentity;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}hostArgs.push(arg)}return socket===void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,bindSocket,replaceIdentity}}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function resolveCliMainPath(){let modulePath=fileURLToPath3(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve2(dirname5(modulePath),"..","..",`cli-main${extension}`);return existsSync2(unbundled)?unbundled:resolveDeclaredCliEntry(modulePath)??unbundled}function resolveDeclaredCliEntry(modulePath){let dir=dirname5(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve2(dir,"package.json");if(existsSync2(manifestPath)){try{let declared=JSON.parse(readFileSync2(manifestPath,"utf8")).bin,candidates=typeof declared=="string"?[declared]:Object.values(declared??{});for(let candidate of candidates){let entry=resolve2(dir,candidate);if(existsSync2(entry))return entry}}catch{}return}let parent=dirname5(dir);if(parent===dir)return;dir=parent}}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...process.execArgv,resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}async function runHostSupervisor(launch){let paths=createHostDaemonPaths({socket:launch.socket,agentDir:launch.agentDir??getAgentDir()}),told=process.env[HOST_INSTANCE_ID_ENV],instanceId=told!==void 0&&told.trim()!==""?told:randomUUID2(),generation=generationPaths(paths,instanceId),policy=resolveHostPolicy(await readSettingsFile(paths.settingsFile),process.env),publicSocket=launch.socket,bindSocket=launch.bindSocket??publicSocket,successor=launch.bindSocket!==void 0,publicSecret=process.platform==="win32"?await ensurePublicSocketSecret(publicSocket):void 0,internal=await createInternalSocketPath(paths.dir),internalSocket=internal.socket,internalSecretPath=internal.secretPath??socketSecretPath(internalSocket),internalSecret=process.platform==="win32"?await createSocketSecret(internalSecretPath):void 0,clientSockets=new Set,busySessions=new Map,observerHealthy=!1,observerReconnectTimer,childExitWatchTimer,shuttingDown=!1,draining=!1,shutdownPromise,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),child=spawn(childLaunch.command,childLaunch.args,{env:{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:paths.dir,[HOST_INSTANCE_ID_ENV]:instanceId,[HOST_WATCH_FD_ENV]:String(CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},...internalSecret?{[SOCKET_SECRET_FILE_ENV]:internalSecretPath}:{},[HOST_CLEANUP_PATHS_ENV]:[...successor?[]:[paths.pointerFile,generation.pidFile,paths.settingsFile],...process.platform==="win32"?[publicSocket]:[]].join(`
|
|
19
|
+
`),...process.platform==="win32"?{}:{[HOST_PUBLIC_SOCKET_ENV]:publicSocket}},shell:childLaunch.shell,stdio:["ignore","ignore","inherit","pipe"],windowsHide:!0});child.stdio[CHILD_WATCH_FD]?.on("error",()=>{}),child.once("exit",(code,signal)=>{if(shuttingDown)return;let{reason,exitCode}=classifyChildExit(code,signal);shutdown(reason,exitCode)});let server=createServer(client=>{let accept=()=>{if(shuttingDown||draining){client.destroy();return}let internal2=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,internalSecret));internalSecret&&sendSocketHandshake(internal2,internalSecret),clientSockets.add(client),decider.update(currentActivity());let detach=()=>{clientSockets.delete(client),decider.update(currentActivity()),internal2.destroy(),client.destroy()};client.pipe(internal2),internal2.pipe(client),client.once("close",detach),client.once("error",detach),internal2.once("close",detach),internal2.once("error",detach)};publicSecret?authenticateSocket(client,publicSecret,accept):accept()});server.once("error",cause=>{shuttingDown||shutdown(`public socket listener failed: ${errorMessage2(cause)}`,1)});let decider=new IdleExitDecider(policy.coldStart==="persistent"?Number.POSITIVE_INFINITY:policy.idleExitMs),tickIntervalMs=Math.max(20,Math.min(1e3,policy.idleExitMs/4)),ticker=setInterval(()=>{decider.update(currentActivity())==="exit"&&shutdown("idle",0)},tickIntervalMs);function currentActivity(){return{connections:clientSockets.size,activeTurns:observerHealthy?countBusySessions():1}}function countBusySessions(){let busy=0;for(let count of busySessions.values())count>0&&busy++;return busy}function observeHostEvent(line){let event;try{event=JSON.parse(line)}catch{return}if(typeof event!="object"||event===null)return;let{type,sessionId}=event;if(typeof sessionId=="string"){if(type==="agent_start")busySessions.set(sessionId,(busySessions.get(sessionId)??0)+1);else if(type==="agent_settled")busySessions.set(sessionId,Math.max(0,(busySessions.get(sessionId)??1)-1));else return;decider.update(currentActivity())}}async function shutdown(reason,exitCode){return shutdownPromise??=performShutdown(reason,exitCode),shutdownPromise}async function performShutdown(reason,exitCode){shuttingDown&&process.exit(exitCode),shuttingDown=!0,clearInterval(ticker),childExitWatchTimer&&clearInterval(childExitWatchTimer);let hardExit=process.platform==="win32"?setTimeout(()=>process.exit(exitCode),WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS):void 0;try{writeStderrLine(`senpi rpc host supervisor: ${reason} shutdown`);for(let client of clientSockets)client.destroy();draining||await shieldSocketDuringClose(publicSocket,()=>closeServer(server)),internal.dir&&await rm2(internal.dir,{recursive:!0,force:!0}),await stopChild(child),observer?.destroy(),publicSocketOwned&&process.platform!=="win32"&&await unlinkOwnedSocket(publicSocket,publicSocketIdentity,supervisorLog),await releaseGeneration(paths,{instanceId,pid:process.pid})}finally{hardExit&&clearTimeout(hardExit),process.exit(exitCode)}}let observer,publicSocketOwned=!1,publicSocketIdentity;function supervisorLog(message){writeStderrLine(`senpi rpc host supervisor: ${message}`)}function drainForHandoff(){if(!(draining||shuttingDown)&&(draining=!0,supervisorLog("draining into the next generation"),child.pid!==void 0&&child.exitCode===null&&child.signalCode===null))try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage2(cause)}`)}}registerSupervisorSignals(shutdown,drainForHandoff);try{await waitForListener(internalSocket,3e4,internalSecret),await connectObserver(),await prepareSocketPath(bindSocket),await listen(server,bindSocket,publicSecret),publicSocketOwned=!0,successor&&await adoptPublicSocket(bindSocket,publicSocket,launch.replaceIdentity),publicSocketIdentity=await statSocketIdentity(publicSocket),publicSocketIdentity&&internal.dir&&await writeSocketIdentityFile(join5(internal.dir,PUBLIC_SOCKET_IDENTITY_FILE),publicSocketIdentity)}catch(cause){await shutdown(`startup failed: ${errorMessage2(cause)}`,1)}async function connectObserver(){let secret=internalSecret,next=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,secret));secret&&sendSocketHandshake(next,secret),await waitForConnect(next,5e3),observer=next,observerHealthy=!0,attachJsonlLineReader(next,observeHostEvent,{maxLineLength:MAX_RPC_LINE_CHARACTERS});let lost=()=>{observer!==next||shuttingDown||(observerHealthy=!1,observer=void 0,observerReconnectTimer===void 0&&(observerReconnectTimer=setTimeout(()=>{observerReconnectTimer=void 0,connectObserver().catch(()=>lost())},250),observerReconnectTimer.unref?.()))};next.once("close",lost),next.once("error",lost)}if(process.platform==="win32"&&child.pid!==void 0){let childStartTime=await readProcessStartTime(child.pid,process.platform,1e3).catch(()=>{}),missingIdentityChecks=0,checkingChildIdentity=!1;childExitWatchTimer=setInterval(()=>{shuttingDown||checkingChildIdentity||child.exitCode!==null||child.signalCode!==null||(checkingChildIdentity=!0,readProcessStartTime(child.pid,process.platform,1e3).then(currentStartTime=>{currentStartTime===void 0&&!processIsLive(child.pid)?missingIdentityChecks++:currentStartTime!==void 0&&(missingIdentityChecks=0),(childStartTime!==void 0&¤tStartTime!==void 0&¤tStartTime!==childStartTime||missingIdentityChecks>=2)&&shutdown("rpc host child exit observed by identity watchdog",0)}).catch(()=>{}).finally(()=>{checkingChildIdentity=!1}))},500),childExitWatchTimer.unref?.()}writeStderrLine(`senpi rpc host ready on unix://${publicSocket} (coldStart=${policy.coldStart}, idleExitMs=${policy.coldStart==="persistent"?"never":String(policy.idleExitMs)})`),await new Promise(()=>{})}function registerSupervisorSignals(shutdown,drain){for(let signal of process.platform==="win32"?["SIGTERM"]:["SIGTERM","SIGHUP"])process.on(signal,()=>{shutdown(`signal:${signal}`,signal==="SIGHUP"?129:143)});process.platform!=="win32"&&process.on("SIGUSR1",drain)}async function adoptPublicSocket(bindSocket,publicSocket,expected){if(expected===void 0)throw new Error(`${publicSocket}: a generation launch must name the entry it replaces`);let current=await statSocketIdentity(publicSocket);if(current===void 0||current.dev!==expected.dev||current.ino!==expected.ino)throw new Error(`${publicSocket}: owned by another socket entry now; refusing to replace it`);await rename3(bindSocket,publicSocket)}async function ensurePublicSocketSecret(publicSocket){let secretPath=socketSecretPath(publicSocket);try{return await ensureSocketSecret(secretPath)}catch(cause){throw new Error(`senpi rpc host supervisor: cannot provision public socket secret ${secretPath}`,{cause})}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile4(settingsFile,"utf8"))}catch{return}}async function stopChild(child){if(!(child.exitCode!==null||child.signalCode!==null)){try{child.kill("SIGTERM")}catch{return}if(!await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS)){try{child.kill("SIGKILL")}catch{return}await waitForChildExit(child,2e3)}}}function waitForChildExit(child,timeoutMs){return child.exitCode!==null||child.signalCode!==null?Promise.resolve(!0):new Promise(resolve3=>{let timer=setTimeout(()=>{child.off("exit",onExit),resolve3(!1)},timeoutMs),onExit=()=>{clearTimeout(timer),resolve3(!0)};child.once("exit",onExit)})}async function waitForListener(socketPath,timeoutMs,secret){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){if(await canConnect(socketPath,secret))return;await delay(50)}throw new Error(`${socketPath}: host did not start listening within ${timeoutMs}ms`)}function canConnect(socketPath,secret){return new Promise(resolve3=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret));secret&&sendSocketHandshake(socket,secret);let settle=value=>{socket.destroy(),resolve3(value)};socket.once("connect",()=>settle(!0)),socket.once("error",()=>settle(!1))})}function waitForConnect(socket,timeoutMs){return new Promise((resolve3,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve3()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}async function prepareSocketPath(socketPath){if(process.platform!=="win32"){if(Buffer.byteLength(socketPath)>MAX_SOCKET_PATH_BYTES)throw new Error(`${socketPath}: socket path is ${Buffer.byteLength(socketPath)} bytes, over the ${MAX_SOCKET_PATH_BYTES}-byte limit.`);await mkdir3(dirname5(socketPath),{recursive:!0,mode:448});try{await access(socketPath)}catch(cause){if(isNodeErrorCode5(cause,"ENOENT"))return;throw cause}if(await canConnect(socketPath))throw new Error(`${socketPath}: address already in use by a live server.`);await unlink2(socketPath)}}function listen(server,socketPath,secret){return new Promise((resolve3,reject)=>{server.once("error",reject),server.listen({path:resolveSocketTransportAddress(socketPath,process.platform,secret),readableAll:!1,writableAll:!1},async()=>{server.off("error",reject);try{process.platform!=="win32"&&!socketPath.startsWith("\0")&&await chmod2(socketPath,384),resolve3()}catch(cause){reject(cause)}})})}function closeServer(server){return new Promise(resolve3=>{server.close(()=>resolve3())})}function writeStderrLine(text){try{writeSync(2,`${text}
|
|
20
|
+
`)}catch{}}function delay(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function errorMessage2(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode5(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function asOptionalString(value){return typeof value=="string"?value:typeof value=="number"?String(value):void 0}function isEntryScript(){let entry=process.argv[1];if(!entry)return!1;try{return fileURLToPath3(import.meta.url)===realpathSync2(entry)}catch{return!1}}if(!isBundledNode&&isEntryScript()){let launch=parseSupervisorArgs(process.argv.slice(2));launch||(writeStderrLine("usage: host-lifecycle.ts --socket <path> [host cli args...]"),process.exit(2)),runHostSupervisor(launch)}export{DEFAULT_HOST_IDLE_EXIT_MS,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,INTERNAL_SUPERVISOR_FLAG,IdleExitDecider,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseColdStart,parseIdleExitMs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,resolveHostPolicy,runHostSupervisor,spawnableChildLaunch};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{RpcClient,SessionManager,executeBashWithOperations,isTransportGoneError}from"./chunk-W4SRGDQ4.js";import{SettingsManager}from"./chunk-PLZK7ABD.js";import{ensureHost}from"./chunk-P7PWCGLJ.js";import{QUESTION_CAPABILITY,RENDERED_COMPONENTS_CAPABILITY}from"./chunk-U6Z6OBX4.js";import"./chunk-LF3XTYYF.js";import"./chunk-HSH674C6.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-7X72IACK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-U7RQY7MH.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{randomUUID}from"node:crypto";import{rm}from"node:fs/promises";var HOST_CLIENT_CAPABILITIES=[RENDERED_COMPONENTS_CAPABILITY,QUESTION_CAPABILITY],INTERACTIVE_HOST_FALLBACK_WARNING="Warning: shared interactive host unavailable; continuing locally",INTERACTIVE_HOST_RECONNECTING_WARNING="Warning: shared interactive host connection lost; reconnecting";async function createInteractiveHostRuntime(localRuntime,options){let sessionPath=localRuntime.session.sessionFile;if(!sessionPath)return localRuntime;let startHost=options.ensureHost??(hostOptions=>ensureHost(hostOptions)),remoteSession,remoteRuntime,reconnecting,disconnectQueued=!1,disposed=!1,fallbackWarned=!1,reconnectWarningShown=!1,warnReconnect=cause=>{reconnectWarningShown||(reconnectWarningShown=!0,options.onWarning?.({type:"interactive_host_action_failed",message:INTERACTIVE_HOST_RECONNECTING_WARNING,cause}))},warnFallback=cause=>{fallbackWarned||(fallbackWarned=!0,options.onWarning?.({type:"interactive_host_fallback",message:INTERACTIVE_HOST_FALLBACK_WARNING,cause}))},scheduleReconnect=()=>{},client=new RpcClient({socketPath:options.socket,onDisconnect:()=>{disconnectQueued=!0,scheduleReconnect()}});scheduleReconnect=()=>{!remoteSession||reconnecting||disposed||remoteRuntime?.isFallback||(remoteRuntime?.enterReconnecting(),reconnecting=(async()=>{let cause;for(let attempt=0;attempt<3;attempt++){if(disposed)return;disconnectQueued=!1;try{if(await startHost({socket:options.socket,agentDir:options.agentDir}),disposed||(await client.start(),disposed)||(await client.openSession({sessionPath,cwd:localRuntime.cwd}),disposed)||(remoteRuntime&&await remoteRuntime.reRegisterClientInfo(),disposed)||(await remoteSession.refresh(),disposed))return;fallbackWarned=!1,reconnectWarningShown=!1,remoteRuntime?.enterConnected();return}catch(error){if(cause=error,await client.stop().catch(()=>{}),disposed)return}}disposed||(await remoteRuntime?.enterFallback(),warnFallback(cause))})().finally(()=>{reconnecting=void 0,disconnectQueued&&!disposed&&!remoteRuntime?.isFallback&&scheduleReconnect()}))};try{await startHost({socket:options.socket,agentDir:options.agentDir}),await client.start(),await client.setClientInfo(80,[...HOST_CLIENT_CAPABILITIES]);let startupEvents=[],stopBuffering=client.onEvent(event=>startupEvents.push(event)),opened=await client.openSession({sessionPath,cwd:localRuntime.cwd,provider:localRuntime.session.model?.provider,modelId:localRuntime.session.model?.id,thinkingLevel:localRuntime.session.thinkingLevel});return remoteSession=createRemoteSessionProxy(localRuntime.session,localRuntime.services.agentDir,client,opened.state,options.onWarning,cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},startupEvents.filter(event=>!("sessionId"in event)||event.sessionId===opened.sessionId)),stopBuffering(),opened.state.isBashRunning&&!opened.attached&&await client.abortBash().catch(()=>{}),opened.attached&&await remoteSession.refresh(),remoteRuntime=new RemoteInteractiveRuntime(localRuntime,remoteSession,client,{onTransportGone:cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},get reconnecting(){return reconnecting},dispose:()=>{disposed=!0}}),remoteRuntime}catch(cause){return await client.stop().catch(()=>{}),warnFallback(cause),localRuntime}}var RemoteInteractiveRuntime=class{#local;#remoteSession;#client;#lifecycle;#onTransportGone;#rebindSession;#beforeSessionInvalidate;#state="connected";#fallbackHandoff;get isReconnecting(){return this.#state==="reconnecting"}get isFallback(){return this.#state==="fallback"}constructor(local,remoteSession,client,lifecycle){this.#local=local,this.#remoteSession=remoteSession,this.#client=client,this.#lifecycle=lifecycle,this.#onTransportGone=lifecycle?.onTransportGone??(()=>{})}async#call(call){try{return await call()}catch(error){if(isTransportGoneError(error))return this.#onTransportGone(error),{cancelled:!0};throw error}}enterConnected(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="connected")}enterReconnecting(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="reconnecting")}async enterFallback(){if(this.#state==="disposed"||this.#state==="fallback")return;this.#state="fallback",this.#beforeSessionInvalidate?.();let rebind=this.#rebindSession?.();rebind&&(this.#fallbackHandoff=rebind.catch(error=>{this.#onTransportGone(error)}),await this.#fallbackHandoff)}get session(){return this.#state==="fallback"||this.#state==="disposed"?this.#local.session:this.#remoteSession.session}get services(){return this.#local.services}get cwd(){return this.session.sessionManager.getCwd()}get diagnostics(){return this.#local.diagnostics}get modelFallbackMessage(){return this.#local.modelFallbackMessage}get launchProfile(){return this.#local.launchProfile}setBeforeSessionInvalidate(callback){this.#beforeSessionInvalidate=callback,this.#local.setBeforeSessionInvalidate(callback)}setRebindSession(callback){this.#rebindSession=callback,this.#local.setRebindSession(callback),callback&&this.#state==="fallback"&&!this.#fallbackHandoff&&(this.#fallbackHandoff=callback().catch(error=>{this.#onTransportGone(error)}))}setHostUiHandler(callback){this.#remoteSession.setHostUiHandler(callback)}sendHostUiProgress(record){this.#client.sendExtensionUIProgress(record).catch(()=>{})}#clientInfoSent=!1;#lastClientWidth=80;setClientInfo(width){this.#lastClientWidth=width;let capabilities=this.#clientInfoSent?void 0:[...HOST_CLIENT_CAPABILITIES];this.#clientInfoSent=!0,this.#client.setClientInfo(width,capabilities).catch(()=>{})}async reRegisterClientInfo(){await this.#client.setClientInfo(this.#lastClientWidth,[...HOST_CLIENT_CAPABILITIES])}async dispose(){if(this.#state==="disposed")return;this.#state="disposed",this.#lifecycle?.dispose(),await this.#lifecycle?.reconnecting?.catch(()=>{}),await this.#fallbackHandoff?.catch(()=>{});let errors=[];for(let cleanup of[()=>this.#remoteSession.abortLocalBash(),()=>this.#client.closeSession(),()=>this.#client.stop(),()=>this.#local.dispose()])try{await cleanup()}catch(error){errors.push(error)}if(errors.length>0)throw errors[0]}async newSession(options){return this.#state==="fallback"?this.#local.newSession(options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.newSession(options?.parentSession));if(!result.cancelled){if(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),options?.setup){let capture=SessionManager.inMemory(this.#remoteSession.session.sessionManager.getCwd());await options.setup(capture);for(let entry of capture.getEntries())await this.#client.appendSessionEntry(entry);await this.#remoteSession.refresh()}await this.#rebindSession?.(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())}return result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async switchSession(sessionPath,options){return this.#state==="fallback"?this.#local.switchSession(sessionPath,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.switchSession(sessionPath,options?.cwdOverride===void 0?void 0:{cwdOverride:options.cwdOverride}));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),await this.#rebindSession?.(),options?.projectTrustContextFactory?.(this.#remoteSession.session.sessionManager.getCwd()),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async fork(entryId,options){return this.#state==="fallback"?this.#local.fork(entryId,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.fork(entryId,options));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),{cancelled:result.cancelled,selectedText:result.text}}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async importFromJsonl(inputPath,cwdOverride){return this.#state==="fallback"?this.#local.importFromJsonl(inputPath,cwdOverride):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.importJsonl(inputPath,cwdOverride));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind()),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async#refreshAndRebind(){await this.#remoteSession.refresh(),await this.#rebindSession?.()}};function createRemoteSessionProxy(local,agentDir,client,initialState,onWarning,onTransportGone,startupEvents=[]){let reportActionFailure=action=>error=>{isTransportGoneError(error)?onTransportGone?.(error):onWarning?.({type:"interactive_host_action_failed",message:`Warning: shared interactive host ${action} failed: ${error instanceof Error?error.message:String(error)}`,cause:error})},transportCall=async(action,call,cancelledValue)=>{try{return await call()}catch(error){if(!isTransportGoneError(error))throw error;return reportActionFailure(action)(error),cancelledValue}},state={...initialState},waitForBashCallbacks=async(promises,allowAbandonment)=>{if(promises.size===0)return!0;let settled=Promise.allSettled([...promises]).then(()=>!0),timeout,bounded=new Promise(resolve=>{timeout=setTimeout(resolve,allowAbandonment?100:5e3,!1),timeout.unref?.()});try{return await Promise.race([settled,bounded])}finally{timeout&&clearTimeout(timeout)}},executionNamespace=randomUUID(),cleanupRemoteBashOutput=async path=>{let cleanupTimeout;try{await Promise.race([client.cleanupBashOutput(path),new Promise((_,reject)=>{cleanupTimeout=setTimeout(()=>reject(new Error("RPC cleanup timed out")),1e3)})]);return}catch(transportError){try{await rm(path,{force:!0});return}catch(localError){onWarning?.({type:"interactive_host_action_failed",message:`Warning: failed to clean up shared bash output spill: ${localError instanceof Error?localError.message:String(localError)}`,cause:new AggregateError([transportError,localError])})}}finally{cleanupTimeout&&clearTimeout(cleanupTimeout)}},nextBashExecutionId=0,bashExecutions=new Map,hostUiHandler,pendingUiRequests=[],localBashAbortController,localBashRunning=!1,hostBashRunning=initialState.isBashRunning,nextQueuedInputOrder=Math.max(0,...initialState.ordered.map(item=>item.enqueueOrder)),sessionManager=local.sessionManager,settingsManager=SettingsManager.create(initialState.cwd,agentDir,{projectTrusted:initialState.projectTrusted}),updateBashState=()=>{state={...state,isBashRunning:localBashRunning||hostBashRunning}},remoteSessionManager=new Proxy({},{get(_target,property,_receiver){if(property==="appendLabelChange")return(entryId,label)=>{client.setLabel(entryId,label).catch(reportActionFailure("appendLabelChange"))};if(property==="getCwd")return()=>state.cwd;if(property==="getSessionName")return()=>state.sessionName;if(property==="getUsageTotals")return()=>state.usageTotals;let value=Reflect.get(sessionManager,property,sessionManager);return typeof value=="function"?value.bind(sessionManager):value}}),streamingAssistant,mirroredCurrentAssistantUsage=!1,localReplacementDepth=0,listeners=new Set,handleWireEvent=wireEvent=>{if(wireEvent.type==="extension_ui_request"){let request=wireEvent;hostUiHandler?Promise.resolve(hostUiHandler(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response")):pendingUiRequests.push(request);return}if(wireEvent.type==="session_replaced"){localReplacementDepth===0&&refresh().catch(reportActionFailure("session refresh after replacement"));return}if(wireEvent.type==="agent_settled"&&(state={...state,isStreaming:!1,retryAttempt:0}),wireEvent.type==="bash_start"&&(hostBashRunning=!0,updateBashState()),wireEvent.type==="bash_end"&&(hostBashRunning=!1,updateBashState()),wireEvent.type==="bash_execution_update"&&wireEvent.id){let execution=bashExecutions.get(wireEvent.id);if(execution?.chunk&&!execution.hasError)try{let callbackPromise=Promise.resolve(execution.chunk(wireEvent.delta)).catch(error=>{throw execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{})),error});execution.promises.add(callbackPromise),callbackPromise.catch(()=>{}).finally(()=>execution.promises.delete(callbackPromise))}catch(error){execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{}))}}if(wireEvent.type==="agent_start"&&(state={...state,isStreaming:!0}),wireEvent.type==="compaction_start"&&(state={...state,isCompacting:!0}),wireEvent.type==="compaction_end"&&(state={...state,isCompacting:!1}),wireEvent.type==="auto_retry_start"&&(state={...state,retryAttempt:wireEvent.attempt}),wireEvent.type==="auto_retry_end"&&(state={...state,retryAttempt:0}),wireEvent.type==="queue_update"&&(nextQueuedInputOrder=Math.max(nextQueuedInputOrder,...wireEvent.ordered.map(item=>item.enqueueOrder)),state={...state,steering:[...wireEvent.steering],followUp:[...wireEvent.followUp],ordered:[...wireEvent.ordered],pendingMessageCount:wireEvent.steering.length+wireEvent.followUp.length}),wireEvent.type==="model_changed"&&(state={...state,model:wireEvent.model,thinkingLevel:wireEvent.thinkingLevel}),wireEvent.type==="thinking_level_changed"&&(state={...state,thinkingLevel:wireEvent.level}),wireEvent.type==="service_tier_changed"&&(state={...state,serviceTier:wireEvent.tier,fastMode:wireEvent.fastMode}),wireEvent.type==="session_settings_changed"&&(state={...state,steeringMode:wireEvent.steeringMode,followUpMode:wireEvent.followUpMode,autoCompactionEnabled:wireEvent.autoCompactionEnabled}),wireEvent.type==="entry_appended")try{sessionManager.appendEntry(wireEvent.entry),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}if(wireEvent.type==="session_info_changed"&&(state={...state,sessionName:wireEvent.name}),wireEvent.type==="message_start"&&(wireEvent.message.role==="assistant"&&(streamingAssistant=structuredClone(wireEvent.message),mirroredCurrentAssistantUsage=!1),local.agent.state.messages.push(structuredClone(wireEvent.message))),wireEvent.type==="message_end"){if(wireEvent.message.role==="assistant"){streamingAssistant=structuredClone(wireEvent.message);let usage=wireEvent.message.usage;if(usage&&!mirroredCurrentAssistantUsage){mirroredCurrentAssistantUsage=!0;let latestPromptTokens=usage.input+usage.cacheRead+usage.cacheWrite,contextWindow=state.model?.contextWindow??0,contextTokens=usage.input+usage.cacheRead+usage.cacheWrite;state={...state,contextUsage:contextWindow>0?{tokens:contextTokens,contextWindow,percent:contextTokens/contextWindow*100}:void 0,usageTotals:{...state.usageTotals,input:state.usageTotals.input+usage.input,output:state.usageTotals.output+usage.output,cacheRead:state.usageTotals.cacheRead+usage.cacheRead,cacheWrite:state.usageTotals.cacheWrite+usage.cacheWrite,cost:state.usageTotals.cost+(usage.cost?.total??0),latestCacheHitRate:latestPromptTokens>0?usage.cacheRead/latestPromptTokens*100:void 0}}}}let messages=local.agent.state.messages;messages.at(-1)?.role===wireEvent.message.role&&(messages[messages.length-1]=structuredClone(wireEvent.message))}if(wireEvent.type==="compaction_end"&&wireEvent.accepted&&!wireEvent.aborted)try{local.sessionManager.reloadFromDisk?.(),sessionManager!==local.sessionManager&&sessionManager.reloadFromDisk?.(),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}let event=hydrateMessageUpdate(wireEvent,streamingAssistant);for(let listener of listeners)listener(event)};client.onEvent(handleWireEvent);for(let event of startupEvents)handleWireEvent(event);let performRefresh=async()=>{let idsAtRefreshStart=new Set(sessionManager.getEntries().map(entry=>entry.id)),nextState=await transportCall("refresh",()=>client.getState());if(!nextState)return;state={...nextState},nextQueuedInputOrder=Math.max(0,...nextState.ordered.map(item=>item.enqueueOrder));let messages;if(settingsManager=SettingsManager.create(nextState.cwd,agentDir,{projectTrusted:nextState.projectTrusted}),nextState.sessionFile){sessionManager.getSessionFile()===nextState.sessionFile?sessionManager.reloadFromDisk?.():sessionManager=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);let authoritative=nextState.entries;if(authoritative?.length){let mirror=sessionManager.getEntries();if(!(mirror.length===authoritative.length&&mirror.every((entry,index)=>entry.id===authoritative[index]?.id))){let rebuilt=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);for(let entry of authoritative)rebuilt.appendEntry(entry);let authoritativeIds=new Set(authoritative.map(entry=>entry.id));for(let entry of mirror)!idsAtRefreshStart.has(entry.id)&&!authoritativeIds.has(entry.id)&&rebuilt.appendEntry(entry);sessionManager=rebuilt}}messages=sessionManager.buildSessionContext().messages}else messages=await transportCall("refresh",()=>client.getMessages(),[]);local.agent.state.messages.splice(0,local.agent.state.messages.length,...structuredClone(messages)),streamingAssistant=void 0},refreshChain=Promise.resolve(),refresh=()=>{let next=refreshChain.then(performRefresh,performRefresh);return refreshChain=next.then(()=>{},()=>{}),next};return{session:new Proxy(local,{get(target,property,receiver){if(property==="prompt")return async(message,options)=>{try{await client.prompt(message,{...options?.images?{images:options.images}:{},...options?.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options?.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options?.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options?.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{},...options?.promptDisposition?{promptDisposition:options.promptDisposition}:{},...options?.preflightResult?{preflightResult:options.preflightResult}:{}})}catch(error){if(!isTransportGoneError(error))throw error;reportActionFailure("prompt")(error)}};if(property==="abort")return()=>client.abort();if(property==="abortCompaction")return()=>{client.abortCompaction().catch(reportActionFailure("abortCompaction"))};if(property==="steer")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,steering:[...state.steering,message],ordered:[...state.ordered,{text:message,mode:"steer",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("steer",()=>client.steer(message,images,{...recovery,enqueueOrder}))};if(property==="followUp")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,followUp:[...state.followUp,message],ordered:[...state.ordered,{text:message,mode:"followUp",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("followUp",()=>client.followUp(message,images,{...recovery,enqueueOrder}))};if(property==="waitForIdle")return()=>client.waitForIdle();if(property==="getLastAssistantText")return()=>target.getLastAssistantText();if(property==="setModel"||property==="setSessionModel")return async model=>{let next=await transportCall("setModel",()=>client.setModel(model.provider,model.id),void 0);return next?{systemPromptName:next.systemPromptName,model:next}:void 0};if(property==="setSessionThinkingLevel")return level=>{client.setThinkingLevel(level,{scope:"turn"}).catch(reportActionFailure("setSessionThinkingLevel"))};if(property==="setSessionFastMode")return enabled=>{client.setFastMode(enabled).catch(reportActionFailure("setSessionFastMode"))};if(property==="abortRetry")return()=>{client.abortRetry().catch(reportActionFailure("abortRetry"))};if(property==="setAutoRetryEnabled")return enabled=>{client.setAutoRetry(enabled).catch(reportActionFailure("setAutoRetryEnabled"))};if(property==="reserveQueuedInputOrder")return()=>++nextQueuedInputOrder;if(property==="setFavoriteModels")return models=>{state={...state,favoriteModels:[...models]},client.setFavoriteModels(models).catch(reportActionFailure("setFavoriteModels"))};if(property==="setScopedModels")return models=>{state={...state,scopedModels:[...models]},client.setScopedModels(models).catch(reportActionFailure("setScopedModels"))};if(property==="cycleModel")return direction=>transportCall("cycleModel",()=>client.cycleModel(direction),void 0);if(property==="setThinkingLevel")return level=>{client.setThinkingLevel(level).catch(reportActionFailure("setThinkingLevel"))};if(property==="cycleThinkingLevel")return()=>transportCall("cycleThinkingLevel",()=>client.cycleThinkingLevel(),void 0).then(result=>result?.level);if(property==="getAvailableThinkingLevels")return()=>transportCall("getAvailableThinkingLevels",()=>client.getAvailableThinkingLevels(),[]);if(property==="setSteeringMode")return mode=>{client.setSteeringMode(mode).catch(reportActionFailure("setSteeringMode"))};if(property==="setFollowUpMode")return mode=>{client.setFollowUpMode(mode).catch(reportActionFailure("setFollowUpMode"))};if(property==="compact")return instructions=>transportCall("compact",()=>client.compact(instructions));if(property==="setAutoCompactionEnabled")return enabled=>{client.setAutoCompaction(enabled).catch(reportActionFailure("setAutoCompaction"))};if(property==="executeBash")return async(command,onChunk,options)=>{if(options?.operations&&typeof options.operations.exec=="function"){let abortController=new AbortController;localBashAbortController=abortController,localBashRunning=!0,updateBashState();let sessionAtStart=state.sessionId,prefix=settingsManager.getShellCommandPrefix(),resolvedCommand=prefix?`${prefix}
|
|
3
|
+
${command}`:command;try{let result=await executeBashWithOperations(resolvedCommand,state.cwd,options.operations,{onChunk,signal:abortController.signal});return state.sessionId===sessionAtStart&&await transportCall("recordBashResult",()=>client.recordBashResult(command,result,options.excludeFromContext)),result}finally{localBashAbortController=void 0,localBashRunning=!1,updateBashState()}}let executionId=`bash-${executionNamespace}-${++nextBashExecutionId}`,execution={chunk:onChunk,promises:new Set,error:void 0,hasError:!1};bashExecutions.set(executionId,execution);try{let result=await transportCall("bash",()=>client.bash(command,{excludeFromContext:options?.excludeFromContext,executionId,operations:options?.operations}),{output:"",exitCode:void 0,cancelled:!0,truncated:!1});if(!await waitForBashCallbacks(execution.promises,!1))throw result.fullOutputPath&&await cleanupRemoteBashOutput(result.fullOutputPath),new Error("Bash output callback did not settle within 5000ms");if(execution.hasError)throw result.fullOutputPath&&await cleanupRemoteBashOutput(result.fullOutputPath),execution.error;return result}finally{bashExecutions.delete(executionId)}};if(property==="abortBash")return()=>{localBashAbortController?localBashAbortController.abort():client.abortBash().catch(reportActionFailure("abortBash"))};if(property==="getContextUsage")return()=>state.contextUsage;if(property==="getSessionStats")return()=>transportCall("getSessionStats",()=>client.getSessionStats(),local.getSessionStats());if(property==="exportToHtml")return(outputPath,options)=>transportCall("exportToHtml",()=>client.exportHtml(outputPath,options?.themeName)).then(result=>result?.path);if(property==="setSessionName")return name=>client.setSessionName(name).catch(reportActionFailure("setSessionName"));if(property==="navigateTree")return async(targetId,options)=>{let result=await transportCall("navigateTree",()=>client.navigateTree(targetId,options),{cancelled:!0});return result.cancelled||await refresh(),result};if(property==="editAssistantMessage")return async(entryId,text,options)=>{let result=await client.editAssistantMessage(entryId,text,{expectedLeafId:options?.expectedLeafId,summarize:options?.summarize,customInstructions:options?.customInstructions});return result.outcome==="unchanged"?{cancelled:!1,unchanged:!0}:result.outcome==="cancelled"?{cancelled:!0,aborted:result.aborted}:(await refresh(),{cancelled:!1,entryId:result.entry.id})};if(property==="getUserMessagesForForking")return()=>transportCall("getUserMessagesForForking",()=>client.getForkMessages(),[]);if(property==="subscribe")return listener=>{listeners.add(listener);let localUnsubscribe=target.subscribe(listener);return()=>{listeners.delete(listener),localUnsubscribe()}};if(property==="isStreaming")return state.isStreaming;if(property==="isIdle")return!state.isStreaming;if(property==="isCompacting")return state.isCompacting;if(property==="pendingMessageCount")return state.pendingMessageCount;if(property==="getSteeringMessages")return()=>state.steering;if(property==="getFollowUpMessages")return()=>state.followUp;if(property==="clearQueue")return options=>{let result={steering:[...state.steering],followUp:[...state.followUp],ordered:[...state.ordered]};return Object.defineProperty(result,"ordered",{value:result.ordered,enumerable:!1}),client.clearQueue(options).catch(reportActionFailure("clearQueue")),result};if(property==="abortBranchSummary")return()=>{client.abortBranchSummary().catch(reportActionFailure("abortBranchSummary"))};if(property==="recordBashResult")return(command,result,options)=>{client.recordBashResult(command,result,options?.excludeFromContext).catch(reportActionFailure("recordBashResult"))};if(property!=="set_label"){if(property==="retryAttempt")return state.retryAttempt;if(property==="isBashRunning")return state.isBashRunning;if(property==="reload")return _options=>transportCall("reload",()=>client.reload(),{cancelled:!0});if(property==="checkReloadVeto")return()=>transportCall("checkReloadVeto",()=>client.checkReloadVeto(),{cancelled:!0});if(property==="exportToJsonl")return outputPath=>transportCall("exportToJsonl",()=>client.exportJsonl(outputPath)).then(result=>result?.path);if(property==="state"){let localState=target.state;return{...localState,model:state.model??localState.model,thinkingLevel:state.thinkingLevel,isStreaming:state.isStreaming,isCompacting:state.isCompacting}}return property==="sessionFile"?state.sessionFile:property==="sessionId"?state.sessionId:property==="sessionName"?state.sessionName:property==="serviceTier"?state.serviceTier:property==="steeringMode"?state.steeringMode:property==="followUpMode"?state.followUpMode:property==="autoCompactionEnabled"?state.autoCompactionEnabled:property==="isFastModeActive"?()=>state.fastMode:property==="sessionManager"?remoteSessionManager:property==="settingsManager"?settingsManager:property==="messages"?target.messages:property==="favoriteModels"?state.favoriteModels:property==="scopedModels"?state.scopedModels:property==="model"?state.model??target.model:property==="thinkingLevel"?state.thinkingLevel:Reflect.get(target,property,receiver)}}}),setHostUiHandler:callback=>{if(hostUiHandler=callback,callback)for(let request of pendingUiRequests.splice(0))Promise.resolve(callback(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response"))},refresh,aroundLocalReplacement:async body=>{localReplacementDepth++;try{return await body()}finally{localReplacementDepth--}},abortLocalBash:()=>localBashAbortController?.abort(),createReplacedSessionContext:()=>{let context=local.createReplacedSessionContext();return Object.defineProperty(context,"cwd",{value:state.cwd}),Object.defineProperty(context,"sessionManager",{value:remoteSessionManager}),context.sendMessage=(message,options)=>transportCall("sendMessage",()=>client.sendCustomMessage(message,{triggerTurn:options?.triggerTurn,deliverAs:options?.deliverAs})),context.sendUserMessage=(content,options)=>{if(typeof content=="string")return transportCall("sendUserMessage",()=>client.prompt(content,{streamingBehavior:options?.deliverAs,expandPromptTemplates:options?.expandPromptTemplates}));let text=content.filter(part=>part.type==="text").map(part=>part.text).join(`
|
|
4
|
+
`),images=content.filter(part=>part.type==="image");return transportCall("sendUserMessage",()=>client.prompt(text,{images,streamingBehavior:options?.deliverAs,expandPromptTemplates:options?.expandPromptTemplates}))},context}}}function hydrateMessageUpdate(event,streamingAssistant){if(event.type!=="message_update"||!streamingAssistant)return event;let update=event.assistantMessageEvent;if(update.type!=="text_delta"&&update.type!=="thinking_delta"&&update.type!=="toolcall_delta")return event;let content=streamingAssistant.content[update.contentIndex];if(update.type==="text_delta"&&content?.type==="text"&&(content.text+=update.delta),update.type==="thinking_delta"&&content?.type==="thinking"&&(content.thinking+=update.delta),update.type==="toolcall_delta"&&content?.type==="toolCall"){let raw=JSON.stringify(content.arguments)+update.delta;try{let parsed=JSON.parse(raw);typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed)&&(content.arguments=parsed)}catch{}}return streamingAssistant.usage=event.usage,{type:"message_update",message:structuredClone(streamingAssistant),assistantMessageEvent:{...update,partial:structuredClone(streamingAssistant)}}}function isInteractiveHostEvent(event){return typeof event=="object"&&event!==null&&"type"in event}export{INTERACTIVE_HOST_FALLBACK_WARNING,INTERACTIVE_HOST_RECONNECTING_WARNING,RemoteInteractiveRuntime,createInteractiveHostRuntime,createRemoteSessionProxy,isInteractiveHostEvent};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-EHSDTQ6I.js";import"./chunk-3FRTRCR6.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import"./chunk-W4SRGDQ4.js";import"./chunk-GFUZPFHN.js";import{isApiKeyLoginProvider}from"./chunk-5E5TLB76.js";import"./chunk-RLRLQRI2.js";import"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-IUZUN32Z.js";import"./chunk-P7PWCGLJ.js";import"./chunk-U6Z6OBX4.js";import"./chunk-LF3XTYYF.js";import"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator};
|
package/dist/bundle/chunks/{multi-session-host-OK6WMHB4.js → multi-session-host-2YCJKQOL.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,ProviderScope,bindToProviderScope,createAgentSessionRuntime,runWithProviderScope}from"./chunk-
|
|
2
|
+
import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,ProviderScope,bindToProviderScope,createAgentSessionRuntime,runWithProviderScope}from"./chunk-EHSDTQ6I.js";import"./chunk-3FRTRCR6.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import{SessionManager}from"./chunk-W4SRGDQ4.js";import"./chunk-GFUZPFHN.js";import{RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_UNKNOWN_SESSION,SessionEventWriter,buildRpcSessionState,createRpcConnectionHandler,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError}from"./chunk-5E5TLB76.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-RLRLQRI2.js";import"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-IUZUN32Z.js";import{GENERATION_HANDOFF_CAPABILITY}from"./chunk-P7PWCGLJ.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,parseClientCapabilities}from"./chunk-U6Z6OBX4.js";import{HOST_DAEMON_DIR_ENV,PUBLIC_SOCKET_IDENTITY_FILE,SOCKET_SECRET_FILE_ENV,armHostWatchdog,authenticateSocket,createHostDaemonPaths,ensureSocketSecret,parseIdleExitMs,processIsLive,readHostWatchdogConfigFromBrandEnv,readProcessStartTime,readSocketIdentityFile,resolveSocketTransportAddress,shieldSocketDuringClose,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-LF3XTYYF.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,hostInstanceId,protocolIdentity}from"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import{killTrackedDetachedChildren}from"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import{VERSION,envValue,isBunBinary}from"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{access,chmod,mkdir as mkdir2,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{dirname as dirname2,join as join2}from"node:path";import{readdirSync,readFileSync}from"node:fs";var P_PID=1,WNOHANG=1,WEXITED=4,WNOWAIT={darwin:32,linux:16777216},SI_PID_OFFSET={darwin:12,linux:16},MAX_TRACKED_CHILDREN=4096;function supportedPlatform(platform){return platform==="darwin"||platform==="linux"?platform:void 0}async function loadChildReaperSyscalls(platform=process.platform){let supported=supportedPlatform(platform);if(supported===void 0||typeof globalThis.Bun>"u")return;let{dlopen,FFIType,ptr}=await import("bun:ffi"),wait=dlopen(supported==="darwin"?"libSystem.B.dylib":"libc.so.6",{waitid:{args:[FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32},waitpid:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),info=new Uint8Array(512),infoView=new DataView(info.buffer),status=new Int32Array(1),peekOptions=WEXITED|WNOHANG|WNOWAIT[supported],siPidOffset=SI_PID_OFFSET[supported];return{listDirectChildren:supported==="darwin"?darwinChildren(dlopen,FFIType,ptr):linuxChildren,isWaitable(pid){return info.fill(0),wait.symbols.waitid(P_PID,pid,ptr(info),peekOptions)===0&&infoView.getInt32(siPidOffset,!0)===pid},reapExited(pid){if(pid<=0)throw new Error(`child reaper refuses to wait on pid ${pid}`);return wait.symbols.waitpid(pid,ptr(status),WNOHANG)===pid},describe:supported==="darwin"?darwinName(dlopen,FFIType,ptr):linuxName}}function darwinChildren(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_listchildpids:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),pids=new Int32Array(MAX_TRACKED_CHILDREN);return()=>{let found=libproc.symbols.proc_listchildpids(process.pid,ptr(pids),pids.byteLength);return found<=0?[]:Array.from(pids.subarray(0,Math.min(found,pids.length)))}}function darwinName(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_name:{args:[FFIType.i32,FFIType.ptr,FFIType.u32],returns:FFIType.i32}}),name=new Uint8Array(256),decoder=new TextDecoder;return pid=>{name.fill(0);let written=libproc.symbols.proc_name(pid,ptr(name),name.length);return written<=0?"":decoder.decode(name.subarray(0,written))}}function linuxChildren(){let children=[];for(let entry of readdirSync("/proc")){let pid=Number(entry);if(!(!Number.isInteger(pid)||pid<=0)&&(parentOf(pid)===process.pid&&children.push(pid),children.length>=MAX_TRACKED_CHILDREN))break}return children}function linuxStat(pid){try{return readFileSync(`/proc/${pid}/stat`,"utf8")}catch{return}}function parentOf(pid){let stat=linuxStat(pid),tail=stat?.slice(stat.lastIndexOf(")")+2).split(" ");return tail===void 0?void 0:Number(tail[1])}function linuxName(pid){let stat=linuxStat(pid),open=stat?.indexOf("(")??-1,close=stat?.lastIndexOf(")")??-1;return stat===void 0||open===-1||close<=open?"":stat.slice(open+1,close)}var CHILD_REAPER_ENV="SENPI_RPC_HOST_REAPER",CHILD_REAPER_MIN_WAITABLE_MS_ENV="SENPI_RPC_HOST_REAPER_MIN_WAITABLE_MS",MIN_WAITABLE_FLOOR_MS=5e3,DEFAULT_MIN_WAITABLE_MS=3e4,TICK_MS=1e3,WARN_INTERVAL_MS=5*6e4,WARN_AT_WAITING=10,TOP_NAMES=3;function resolveChildReaperConfig(env){let override=Number(env[CHILD_REAPER_MIN_WAITABLE_MS_ENV]);return{enabled:env[CHILD_REAPER_ENV]!=="0",tickMs:TICK_MS,minWaitableMs:Number.isFinite(override)&&override>0?clampWindow(override):DEFAULT_MIN_WAITABLE_MS}}function clampWindow(milliseconds){return Math.max(MIN_WAITABLE_FLOOR_MS,milliseconds)}function createChildReaper(options){let now=options.now??Date.now,minWaitableMs=clampWindow(options.minWaitableMs??DEFAULT_MIN_WAITABLE_MS),tracked=new Map,lastWarnAt,report=(waiting,reaped)=>{options.log===void 0||reaped.length===0&&waiting.length<WARN_AT_WAITING||lastWarnAt!==void 0&&now()-lastWarnAt<WARN_INTERVAL_MS||(lastWarnAt=now(),options.log(`child reaper: reaped=${reaped.length} waiting=${waiting.length} top=${topNames(waiting,reaped)}`))};return{tick(){let children=options.syscalls.listDirectChildren(),present=new Set(children);for(let pid of[...tracked.keys()])present.has(pid)||tracked.delete(pid);let reaped=[];for(let pid of children){let child=tracked.get(pid)??{name:options.syscalls.describe(pid)||"unknown",waitableSince:void 0};if(tracked.set(pid,child),!options.syscalls.isWaitable(pid)){child.waitableSince=void 0;continue}if(child.waitableSince===void 0){child.waitableSince=now();continue}now()-child.waitableSince<minWaitableMs||options.syscalls.reapExited(pid)&&(tracked.delete(pid),reaped.push(child.name))}report(waitingNames(tracked),reaped)},get waitingPids(){return[...tracked].filter(([,child])=>child.waitableSince!==void 0).map(([pid])=>pid)}}}function waitingNames(tracked){return[...tracked.values()].filter(child=>child.waitableSince!==void 0).map(child=>child.name)}function topNames(waiting,reaped){let counts=new Map;for(let name of[...waiting,...reaped])counts.set(name,(counts.get(name)??0)+1);return[...counts].sort(([,left],[,right])=>right-left).slice(0,TOP_NAMES).map(([name,count])=>`${name} x${count}`).join(", ")}async function startHostChildReaper(log){let config=resolveChildReaperConfig(process.env);if(!config.enabled)return()=>{};let syscalls=await loadChildReaperSyscalls();if(syscalls===void 0)return log(`child reaper unavailable under ${runtimeName()}: children orphaned by a terminated worker thread stay as zombies until this host exits`),()=>{};let reaper=createChildReaper({syscalls,minWaitableMs:config.minWaitableMs,log}),timer=setInterval(()=>reaper.tick(),config.tickMs);return timer.unref(),()=>clearInterval(timer)}function runtimeName(){return typeof globalThis.Bun>"u"?"Node":`Bun on ${process.platform}`}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??4096}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),3e4),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let rssMb=Math.round(this.readRssBytes()/1048576);if(rssMb<=this.warnMb){if(!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();this.emit({type:"host_memory_pressure",rssMb,sessions});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<3e5||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: rssMb=${rssMb} sessions=${sessions} (idle parking halved)
|
|
3
3
|
`))}};import{createHash}from"node:crypto";import{mkdir,readFile,rename,rm,writeFile}from"node:fs/promises";import{join}from"node:path";var SESSION_PATH_RETRY_AFTER_MS=2e3;function reservationFile(dir,sessionPath){return join(dir,`${createHash("sha256").update(sessionPath,"utf8").digest("hex").slice(0,16)}.json`)}function createEndpointReservations(host){let told=process.env[HOST_DAEMON_DIR_ENV],dir=told!==void 0&&told.trim()!==""?told:host.socket===void 0?void 0:createHostDaemonPaths({socket:host.socket,agentDir:host.agentDir}).dir;if(dir!==void 0)return createSessionPathReservations({dir:join(dir,"reservations"),instanceId:host.instanceId,...host.onFailure?{onFailure:host.onFailure}:{}})}function createSessionPathReservations(options){let pid=options.pid??process.pid,startTime=readProcessStartTime(pid).then(value=>value??null,()=>null),held=new Set,report=message=>options.onFailure?.(message);return{async claim(sessionPath){let file=reservationFile(options.dir,sessionPath),existing=await readOwner(file);if(existing&&existing.pid!==pid&&await ownerIsLive(existing))return existing;let owner={instanceId:options.instanceId,pid,processStartTime:await startTime,sessionPath};try{await mkdir(options.dir,{recursive:!0,mode:448});let staging=`${file}.${pid}.tmp`;await writeFile(staging,`${JSON.stringify(owner)}
|
|
4
4
|
`,{mode:384}),await rename(staging,file),held.add(sessionPath)}catch(cause){report(`session path reservation for ${sessionPath} could not be written (${errorMessage(cause)})`)}},release(sessionPath){held.delete(sessionPath)&&rm(reservationFile(options.dir,sessionPath),{force:!0}).catch(cause=>{report(`session path reservation for ${sessionPath} could not be removed (${errorMessage(cause)})`)})}}}async function readOwner(file){let parsed;try{parsed=JSON.parse(await readFile(file,"utf8"))}catch{return}if(typeof parsed!="object"||parsed===null)return;let{instanceId,pid,processStartTime,sessionPath}=parsed;if(!(typeof instanceId!="string"||typeof pid!="number"||typeof sessionPath!="string"))return{instanceId,pid,processStartTime:typeof processStartTime=="string"?processStartTime:null,sessionPath}}async function ownerIsLive(owner){if(!processIsLive(owner.pid))return!1;if(owner.processStartTime===null)return!0;let current=await readProcessStartTime(owner.pid).catch(()=>{});return current===void 0||current===owner.processStartTime}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}import{AsyncLocalStorage}from"node:async_hooks";var attributionStore=new AsyncLocalStorage,sequence=0,openActivities=new Map,lastFinished;function runWithSessionAttribution(attribution,task){let mark=++sequence;openActivities.set(mark,attribution);let finish=()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution})},awaited=!1;try{let result=attributionStore.run(attribution,task);return isPromiseLike(result)&&(awaited=!0,Promise.resolve(result).then(finish,finish)),result}finally{awaited||finish()}}function isPromiseLike(value){return typeof value=="object"&&value!==null&&"then"in value&&typeof value.then=="function"}function openSessionAttributionSpan(attribution){let ambient=attributionStore.getStore(),merged={sessionId:attribution.sessionId??ambient?.sessionId,tool:attribution.tool},mark=++sequence;return openActivities.set(mark,merged),()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution:merged})}}function sessionActivityMark(){return sequence}function sessionActivitySince(mark){if(lastFinished!==void 0&&lastFinished.sequence>mark)return lastFinished.attribution;let newest;for(let attribution of openActivities.values())newest=attribution;return newest}function toolRecord(record){if(!(!("type"in record)||typeof record.type!="string"))return{type:record.type,toolCallId:"toolCallId"in record&&typeof record.toolCallId=="string"?record.toolCallId:void 0,toolName:"toolName"in record&&typeof record.toolName=="string"?record.toolName:void 0}}function createToolAttributionSpans(sessionId){let spans=new Map,closeAll=()=>{for(let close of spans.values())close();spans.clear()};return{closeAll,observe:record=>{let parsed=toolRecord(record);if(parsed!==void 0){if(parsed.type==="tool_execution_start"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.set(parsed.toolCallId,openSessionAttributionSpan({sessionId,tool:parsed.toolName}));return}if(parsed.type==="tool_execution_end"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.delete(parsed.toolCallId);return}(parsed.type==="agent_settled"||parsed.type==="agent_idle")&&closeAll()}}}}var LOOP_LAG_WARN_MS_ENV="SENPI_RPC_LOOP_LAG_WARN_MS",LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_WARN_MS=500,DEFAULT_LOOP_LAG_ERROR_MS=5e3,LOOP_LAG_TICK_MS=200,LOOP_LAG_WARN_INTERVAL_MS=1e4;function describeAttribution(attribution){return attribution?.sessionId===void 0&&attribution?.tool===void 0?"no attributed session":`sessionId=${attribution.sessionId??"unknown"}${attribution.tool?` tool=${attribution.tool}`:""}`}var LoopLagWatchdog=class{constructor(options){this.activityMark=0;let env=options.env??process.env;this.emit=options.emit,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.warnMs=parseIdleExitMs(env[LOOP_LAG_WARN_MS_ENV])??DEFAULT_LOOP_LAG_WARN_MS,this.errorMs=parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}start(){this.timer===void 0&&(this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark(),this.timer=setInterval(()=>this.tick(),LOOP_LAG_TICK_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0,this.expectedTickAt=void 0)}tick(){let now=this.now(),expectedAt=this.expectedTickAt??now,previousMark=this.activityMark;this.expectedTickAt=now+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let driftMs=Math.round(now-expectedAt);if(driftMs<=this.warnMs)return;let attribution=sessionActivitySince(previousMark);driftMs>this.errorMs&&this.emit({type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool}),!(this.lastWarnAt!==void 0&&now-this.lastWarnAt<LOOP_LAG_WARN_INTERVAL_MS)&&(this.lastWarnAt=now,this.log(`senpi rpc host stall: event loop blocked ${driftMs}ms (${describeAttribution(attribution)})
|
|
5
5
|
`))}};async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecords=chunk=>{for(let line of chunk.split(`
|
package/dist/bundle/chunks/{openai-completions-2RS3VSPV.js → openai-completions-TOWYKX2U.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{isForcedToolChoiceUnsupportedError,normalizeToolParametersForMoonshot,normalizeToolParametersForOpenAICompat,omitToolChoiceParam}from"./chunk-AGXZF7RF.js";import{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PUWVIQW6.js";import{clampOpenAIPromptCacheKey}from"./chunk-MUYK27UR.js";import{OpenAI}from"./chunk-CD2HJK4C.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI,clampThinkingBudgetToAnswerRoom,thinkingBudgetForLevel}from"./chunk-POMPEGWQ.js";import{retryProviderStreamRequest}from"./chunk-ZTVQY5V6.js";import{getOpenAICompletionsCompat}from"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import{getProviderEnvValue}from"./chunk-V55B77HQ.js";import{parseStreamingJson}from"./chunk-FC7R7NOV.js";import{formatProviderError,normalizeProviderError}from"./chunk-PRC5XIIH.js";import{appendGrammarToolInputJsonDelta,calculateCost,clampThinkingLevel,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,inferOpenAIThinkingLevelMap,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,supportsMax,supportsXhigh,transformMessages}from"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-BQVVQ2LQ.js";import"./chunk-VR4X5O2Z.js";var KIMI_K3_THINKING_LEVEL_MAP={off:null,minimal:null,low:"low",medium:null,high:"high",xhigh:null,max:"max"},DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"max",max:"max"},OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},MIMO_THINKING_LEVEL_MAP={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"high",max:null},OLLAMA_THINKING_LEVEL_MAP={off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:"high"};function getThinkingLevelMap(model,compat){let inferred=inferOpenAIThinkingLevelMap(model);if(inferred!==void 0)return inferred;let id=model.id.toLowerCase(),isKimiK3=id==="k3"||id.startsWith("k3-")||/(?:^|[/:-])kimi-k3(?:$|[/.:_-])/.test(id),isDeepSeek=id.includes("deepseek"),isMiMo=/\bmimo\b/.test(id),isGlm5x=/(?:^|[/:-])glm-5\.[23](?:$|[/.:_-])/.test(id);if(model.provider==="ollama")return OLLAMA_THINKING_LEVEL_MAP;if(isKimiK3)return KIMI_K3_THINKING_LEVEL_MAP;if(compat.thinkingFormat==="openrouter"&&isDeepSeek)return OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP;if((compat.thinkingFormat==="openai"||compat.thinkingFormat==="openrouter")&&isMiMo)return MIMO_THINKING_LEVEL_MAP;if(isDeepSeek)return DEEPSEEK_THINKING_LEVEL_MAP;if(isGlm5x)return compat.thinkingFormat==="zai"?DEEPSEEK_THINKING_LEVEL_MAP:compat.thinkingFormat==="openrouter"?{xhigh:"xhigh"}:{max:"max"}}function resolveReasoningEffort(thinkingLevelMap,effort){let mapped=thinkingLevelMap?.[effort];return mapped===void 0?effort:typeof mapped=="string"?mapped:void 0}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function getDeferredToolNames(messages){let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);return names}function getToolsByName(tools,names){if(!tools)return[];let toolsByName=new Map(tools.map(tool=>[tool.name,tool]));return Array.from(names).map(name=>toolsByName.get(name)).filter(tool=>tool!==void 0)}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isRecord(value){return typeof value=="object"&&value!==null}function getOpenRouterRawMetadata(error){if(!isRecord(error)||!isRecord(error.error)||!isRecord(error.error.metadata))return;let rawMetadata=error.error.metadata.raw;return typeof rawMetadata=="string"?rawMetadata:void 0}function isForcedOpenAICompletionsToolChoice(toolChoice){return toolChoice!==void 0&&toolChoice!=="auto"&&toolChoice!=="none"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let clientAuth=resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers),compat=getOpenAICompletionsCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,context,clientAuth.apiKey,clientAuth.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,context,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams),params=normalizeRequestToolSchemas(params,compat);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},createChatCompletion=client.chat.completions.create.bind(client.chat.completions),createStream=body=>createChatCompletion(body,requestOptions).withResponse(),createRequest=async()=>{try{return await createStream(params)}catch(error){if(isForcedToolChoiceUnsupportedError(error,isForcedOpenAICompletionsToolChoice(params.tool_choice)))return params=omitToolChoiceParam(params),createStream(params);throw error}},{stream:openaiStream}=await retryProviderStreamRequest(async()=>{let{data,response}=await createRequest();return await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),{stream:data,metadata:response}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,activeBlock=null,deferMixedEvents=!1,hasFinishReason=!1,deferredTextDeltas=[],deferredThinkingDeltas=[],deferredToolCallDeltas=new Map,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},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},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else block.arguments=parseStreamingJson(block.partialArgs);delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},finishActiveBlock=()=>{activeBlock&&(finishBlock(activeBlock),activeBlock=null)},ensureTextBlock=()=>(textBlock||(deferMixedEvents||(finishActiveBlock(),thinkingBlock=null),textBlock={type:"text",text:""},blocks.push(textBlock),deferMixedEvents||(activeBlock=textBlock,stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output}))),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(deferMixedEvents||(finishActiveBlock(),textBlock=null),thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),deferMixedEvents||(activeBlock=thinkingBlock,stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output}))),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){deferMixedEvents||(finishActiveBlock(),textBlock=null,thinkingBlock=null);let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),deferMixedEvents||(activeBlock=block,stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output}))}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block},flushDeferredBlocks=()=>{for(let block of blocks){let contentIndex=getContentIndex(block);if(block.type==="text"){stream2.push({type:"text_start",contentIndex,partial:output});for(let delta of deferredTextDeltas)stream2.push({type:"text_delta",contentIndex,delta,partial:output})}else if(block.type==="thinking"){stream2.push({type:"thinking_start",contentIndex,partial:output});for(let delta of deferredThinkingDeltas)stream2.push({type:"thinking_delta",contentIndex,delta,partial:output})}else{stream2.push({type:"toolcall_start",contentIndex,partial:output});for(let delta of deferredToolCallDeltas.get(block)??[])stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}finishBlock(block)}};for await(let chunk of openaiStream){if(!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(!choice)continue;let choiceUsage=choice.usage;if(!chunk.usage&&choiceUsage&&(output.usage=parseChunkUsage(choiceUsage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){let contentDelta=typeof choice.delta.content=="string"&&choice.delta.content.length>0?choice.delta.content:null,reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(blocks.length===0&&contentDelta&&foundReasoningField&&(deferMixedEvents=!0),contentDelta){let block=ensureTextBlock();block.text+=contentDelta,deferMixedEvents?deferredTextDeltas.push(contentDelta):stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:contentDelta,partial:output})}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,deferMixedEvents?deferredThinkingDeltas.push(delta):stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}if(deferMixedEvents){let deltas=deferredToolCallDeltas.get(block)??[];deltas.push(delta),deferredToolCallDeltas.set(block,deltas)}else stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails){if(!isOpenAIReasoningDetail(detail))continue;let block=ensureThinkingBlock(""),preservedDetails=parseOpenAIReasoningDetails(block.thinkingSignature)??[];appendOpenAIReasoningDetail(preservedDetails,detail),block.thinkingSignature=JSON.stringify(preservedDetails)}}}if(deferMixedEvents?flushDeferredBlocks():finishActiveBlock(),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=getOpenRouterRawMetadata(error);rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
2
|
+
import{isForcedToolChoiceUnsupportedError,omitToolChoiceParam}from"./chunk-NQAVM5XL.js";import{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PUWVIQW6.js";import{clampOpenAIPromptCacheKey}from"./chunk-MUYK27UR.js";import{OpenAI}from"./chunk-CD2HJK4C.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI,clampThinkingBudgetToAnswerRoom,thinkingBudgetForLevel}from"./chunk-POMPEGWQ.js";import{retryProviderStreamRequest}from"./chunk-ZTVQY5V6.js";import{normalizeToolParametersForMoonshot,normalizeToolParametersForOpenAICompat}from"./chunk-IXAUDPOK.js";import{getOpenAICompletionsCompat}from"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import{getProviderEnvValue}from"./chunk-V55B77HQ.js";import{parseStreamingJson}from"./chunk-FC7R7NOV.js";import{formatProviderError,normalizeProviderError}from"./chunk-PRC5XIIH.js";import{appendGrammarToolInputJsonDelta,calculateCost,clampThinkingLevel,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,inferOpenAIThinkingLevelMap,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,supportsMax,supportsXhigh,transformMessages}from"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-BQVVQ2LQ.js";import"./chunk-VR4X5O2Z.js";var KIMI_K3_THINKING_LEVEL_MAP={off:null,minimal:null,low:"low",medium:null,high:"high",xhigh:null,max:"max"},DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"max",max:"max"},OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},MIMO_THINKING_LEVEL_MAP={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"high",max:null},OLLAMA_THINKING_LEVEL_MAP={off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:"high"};function getThinkingLevelMap(model,compat){let inferred=inferOpenAIThinkingLevelMap(model);if(inferred!==void 0)return inferred;let id=model.id.toLowerCase(),isKimiK3=id==="k3"||id.startsWith("k3-")||/(?:^|[/:-])kimi-k3(?:$|[/.:_-])/.test(id),isDeepSeek=id.includes("deepseek"),isMiMo=/\bmimo\b/.test(id),isGlm5x=/(?:^|[/:-])glm-5\.[23](?:$|[/.:_-])/.test(id);if(model.provider==="ollama")return OLLAMA_THINKING_LEVEL_MAP;if(isKimiK3)return KIMI_K3_THINKING_LEVEL_MAP;if(compat.thinkingFormat==="openrouter"&&isDeepSeek)return OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP;if((compat.thinkingFormat==="openai"||compat.thinkingFormat==="openrouter")&&isMiMo)return MIMO_THINKING_LEVEL_MAP;if(isDeepSeek)return DEEPSEEK_THINKING_LEVEL_MAP;if(isGlm5x)return compat.thinkingFormat==="zai"?DEEPSEEK_THINKING_LEVEL_MAP:compat.thinkingFormat==="openrouter"?{xhigh:"xhigh"}:{max:"max"}}function resolveReasoningEffort(thinkingLevelMap,effort){let mapped=thinkingLevelMap?.[effort];return mapped===void 0?effort:typeof mapped=="string"?mapped:void 0}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function getDeferredToolNames(messages){let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);return names}function getToolsByName(tools,names){if(!tools)return[];let toolsByName=new Map(tools.map(tool=>[tool.name,tool]));return Array.from(names).map(name=>toolsByName.get(name)).filter(tool=>tool!==void 0)}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isRecord(value){return typeof value=="object"&&value!==null}function getOpenRouterRawMetadata(error){if(!isRecord(error)||!isRecord(error.error)||!isRecord(error.error.metadata))return;let rawMetadata=error.error.metadata.raw;return typeof rawMetadata=="string"?rawMetadata:void 0}function isForcedOpenAICompletionsToolChoice(toolChoice){return toolChoice!==void 0&&toolChoice!=="auto"&&toolChoice!=="none"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let clientAuth=resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers),compat=getOpenAICompletionsCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,context,clientAuth.apiKey,clientAuth.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,context,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams),params=normalizeRequestToolSchemas(params,compat);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},createChatCompletion=client.chat.completions.create.bind(client.chat.completions),createStream=body=>createChatCompletion(body,requestOptions).withResponse(),createRequest=async()=>{try{return await createStream(params)}catch(error){if(isForcedToolChoiceUnsupportedError(error,isForcedOpenAICompletionsToolChoice(params.tool_choice)))return params=omitToolChoiceParam(params),createStream(params);throw error}},{stream:openaiStream}=await retryProviderStreamRequest(async()=>{let{data,response}=await createRequest();return await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),{stream:data,metadata:response}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,activeBlock=null,deferMixedEvents=!1,hasFinishReason=!1,deferredTextDeltas=[],deferredThinkingDeltas=[],deferredToolCallDeltas=new Map,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},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},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else block.arguments=parseStreamingJson(block.partialArgs);delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},finishActiveBlock=()=>{activeBlock&&(finishBlock(activeBlock),activeBlock=null)},ensureTextBlock=()=>(textBlock||(deferMixedEvents||(finishActiveBlock(),thinkingBlock=null),textBlock={type:"text",text:""},blocks.push(textBlock),deferMixedEvents||(activeBlock=textBlock,stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output}))),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(deferMixedEvents||(finishActiveBlock(),textBlock=null),thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),deferMixedEvents||(activeBlock=thinkingBlock,stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output}))),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){deferMixedEvents||(finishActiveBlock(),textBlock=null,thinkingBlock=null);let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),deferMixedEvents||(activeBlock=block,stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output}))}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block},flushDeferredBlocks=()=>{for(let block of blocks){let contentIndex=getContentIndex(block);if(block.type==="text"){stream2.push({type:"text_start",contentIndex,partial:output});for(let delta of deferredTextDeltas)stream2.push({type:"text_delta",contentIndex,delta,partial:output})}else if(block.type==="thinking"){stream2.push({type:"thinking_start",contentIndex,partial:output});for(let delta of deferredThinkingDeltas)stream2.push({type:"thinking_delta",contentIndex,delta,partial:output})}else{stream2.push({type:"toolcall_start",contentIndex,partial:output});for(let delta of deferredToolCallDeltas.get(block)??[])stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}finishBlock(block)}};for await(let chunk of openaiStream){if(!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(!choice)continue;let choiceUsage=choice.usage;if(!chunk.usage&&choiceUsage&&(output.usage=parseChunkUsage(choiceUsage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){let contentDelta=typeof choice.delta.content=="string"&&choice.delta.content.length>0?choice.delta.content:null,reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(blocks.length===0&&contentDelta&&foundReasoningField&&(deferMixedEvents=!0),contentDelta){let block=ensureTextBlock();block.text+=contentDelta,deferMixedEvents?deferredTextDeltas.push(contentDelta):stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:contentDelta,partial:output})}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,deferMixedEvents?deferredThinkingDeltas.push(delta):stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}if(deferMixedEvents){let deltas=deferredToolCallDeltas.get(block)??[];deltas.push(delta),deferredToolCallDeltas.set(block,deltas)}else stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails){if(!isOpenAIReasoningDetail(detail))continue;let block=ensureThinkingBlock(""),preservedDetails=parseOpenAIReasoningDetails(block.thinkingSignature)??[];appendOpenAIReasoningDetail(preservedDetails,detail),block.thinkingSignature=JSON.stringify(preservedDetails)}}}if(deferMixedEvents?flushDeferredBlocks():finishActiveBlock(),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=getOpenRouterRawMetadata(error);rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
3
3
|
${rawMetadata}`),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice??options?.toolChoice},compat=getOpenAICompletionsCompat(model),thinkingLevelMap=getThinkingLevelMap(model,compat),thinkingModel=thinkingLevelMap===model.thinkingLevelMap?model:{...model,thinkingLevelMap},clampedReasoning=options?.reasoning?clampThinkingLevel(thinkingModel,options.reasoning):model.id.includes("gpt-6-astra")?"off":void 0,normalizedReasoning=clampedReasoning==="off"&&model.id.includes("gpt-6-astra")?"low":clampedReasoning,reasoningEffort=normalizedReasoning==="off"?void 0:normalizedReasoning==="max"&&supportsMax(thinkingModel)?"max":clampMaxForOpenAI(normalizedReasoning,supportsXhigh(thinkingModel));return stream(model,context,{...base,reasoningEffort,thinkingBudgets:options?.thinkingBudgets})};function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId,compat=getOpenAICompletionsCompat(model)){let headers={"User-Agent":getPiUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&compat.sendSessionAffinityHeaders&&(compat.sessionAffinityFormat==="openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId,headers["x-session-affinity"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat=getOpenAICompletionsCompat(model),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,compat.supportsOpenAIGrammarTools)){let messages=convertMessages(model,context,compat,{preserveThinking:options?.reasoningEffort!==void 0,grammarToolInputProperties}),cacheControl=getCompatCacheControl(compat,cacheRetention),thinkingLevelMap=getThinkingLevelMap(model,compat),params={model:model.id,messages,stream:!0,prompt_cache_key:model.baseUrl.includes("api.openai.com")&&cacheRetention!=="none"||cacheRetention==="long"&&compat.supportsLongCacheRetention||compat.supportsPromptCacheKey&&cacheRetention!=="none"?clampOpenAIPromptCacheKey(options?.sessionId):void 0,prompt_cache_retention:cacheRetention==="long"&&compat.supportsLongCacheRetention?"24h":void 0,session_id:compat.sendSessionAffinityHeaders&&compat.sessionAffinityFormat==="openrouter"&&cacheRetention!=="none"?options?.sessionId:void 0};compat.supportsUsageInStreaming!==!1&&(params.stream_options={include_usage:!0}),compat.supportsStore&&(params.store=!1),options?.maxTokens&&(compat.maxTokensField==="max_tokens"?params.max_tokens=options.maxTokens:params.max_completion_tokens=options.maxTokens),options?.temperature!==void 0&&(params.temperature=options.temperature);let deferredToolNames=compat.deferredToolsMode==="kimi"?getDeferredToolNames(context.messages):new Set,activeTools=context.tools?.filter(tool=>!deferredToolNames.has(tool.name));activeTools&&activeTools.length>0?(params.tools=convertTools(activeTools,compat),compat.zaiToolStream&&(params.tool_stream=!0)):hasToolHistory(context.messages)&&(params.tools=[]),cacheControl&&applyAnthropicCacheControl(messages,params.tools,cacheControl),options?.toolChoice&&(params.tool_choice=options.toolChoice),compat.vllmPriority!==void 0&&(params.priority=compat.vllmPriority);let thinkingTokenBudgetField=resolveThinkingTokenBudgetField(compat),thinkingBudget=resolveClampedThinkingBudget(model,options,params);if(compat.thinkingFormat==="zai"&&model.reasoning){let isGlm53=/(?:^|[/:-])glm-5\.3(?:-(?:flash|highspeed))?(?:$|[/.:_])/.test(model.id.toLowerCase()),zaiParams=params;if(zaiParams.thinking=options?.reasoningEffort||isGlm53?{type:"enabled",clear_thinking:!1}:{type:"disabled"},options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(zaiParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen"&&model.reasoning){if(params.enable_thinking=!!options?.reasoningEffort,options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen-chat-template"&&model.reasoning)params.chat_template_kwargs={enable_thinking:!!options?.reasoningEffort,preserve_thinking:!0};else if(compat.thinkingFormat==="chat-template"&&model.reasoning){let chatTemplateKwargs=buildChatTemplateValues(model,options,compat,compat.chatTemplateKwargs,thinkingBudget);chatTemplateKwargs&&(params.chat_template_kwargs=chatTemplateKwargs)}else if(compat.thinkingFormat==="baseten"&&model.reasoning){let basetenParams=params,chatTemplateArgs=buildChatTemplateValues(model,options,compat,compat.chatTemplateArgs??{},thinkingBudget);if(chatTemplateArgs&&(basetenParams.chat_template_args=chatTemplateArgs),compat.supportsReasoningEffort){let requestedEffort=options?.reasoningEffort,mappedEffort=requestedEffort?thinkingLevelMap?.[requestedEffort]:thinkingLevelMap?.off,effort=mappedEffort===void 0?requestedEffort:mappedEffort;typeof effort=="string"&&(basetenParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="deepseek"&&model.reasoning)if(options?.reasoningEffort){if(params.thinking={type:"enabled"},compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.reasoning_effort=effort)}}else compat.supportsDisabledThinking!==!1&&thinkingLevelMap?.off!==null&&(params.thinking={type:"disabled"});else if(compat.thinkingFormat==="openrouter"&&model.reasoning){let openRouterParams=params;if(options?.reasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(openRouterParams.reasoning={effort})}else thinkingLevelMap?.off!==null&&(openRouterParams.reasoning={effort:thinkingLevelMap?.off??"none"})}else if(compat.thinkingFormat==="ant-ling"&&model.reasoning&&options?.reasoningEffort){let effort=thinkingLevelMap?.[options.reasoningEffort];typeof effort=="string"&&(params.reasoning={effort})}else if(compat.thinkingFormat==="together"&&model.reasoning){let togetherParams=params;if(togetherParams.reasoning={enabled:!!options?.reasoningEffort},options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(togetherParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="string-thinking"&&model.reasoning)if(options?.reasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.thinking=effort)}else thinkingLevelMap?.off!==null&&(params.thinking=thinkingLevelMap?.off??"none");else if(options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.reasoning_effort=effort)}else if(!options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort){let offValue=thinkingLevelMap?.off;typeof offValue=="string"&&(params.reasoning_effort=offValue)}if(thinkingTokenBudgetField&&thinkingBudget!==void 0&&Object.assign(params,{[thinkingTokenBudgetField]:thinkingBudget}),model.compat?.openRouterRouting&&(params.provider=model.compat.openRouterRouting),model.compat?.veniceParameters&&(params.venice_parameters=model.compat.veniceParameters),model.compat?.vercelGatewayRouting){let routing=model.compat.vercelGatewayRouting;if(routing.only||routing.order){let gatewayOptions={};routing.only&&(gatewayOptions.only=routing.only),routing.order&&(gatewayOptions.order=routing.order),params.providerOptions={gateway:gatewayOptions}}}return applyExtraBody(params,options?.extraBody,OPENAI_COMPLETIONS_RESERVED_BODY_KEYS),options?.samplingParams&&Object.assign(params,options.samplingParams),params}function resolveThinkingTokenBudgetField(compat){if(compat.thinkingTokenBudgetField)return compat.thinkingTokenBudgetField;if(compat.supportsThinkingTokenBudget)return"thinking_token_budget"}function resolveClampedThinkingBudget(model,options,params){if(!options?.reasoningEffort||!model.reasoning)return;let ceiling=params.max_tokens??params.max_completion_tokens??model.maxTokens,budget=clampThinkingBudgetToAnswerRoom(thinkingBudgetForLevel(options.reasoningEffort,options.thinkingBudgets),ceiling);return budget>0?budget:void 0}function buildChatTemplateValues(model,options,compat,values,thinkingBudget){let resolvedValues={};for(let[key,value]of Object.entries(values)){let resolved=resolveChatTemplateKwargValue(model,options,compat,value,thinkingBudget);resolved!==void 0&&(resolvedValues[key]=resolved)}return Object.keys(resolvedValues).length>0?resolvedValues:void 0}function resolveChatTemplateKwargValue(model,options,compat,value,thinkingBudget){if(typeof value!="object"||value===null)return value;let reasoningEffort=options?.reasoningEffort;if(!reasoningEffort&&value.omitWhenOff)return;if(value.$var==="thinking.enabled")return!!reasoningEffort;if(value.$var==="thinking.budget")return thinkingBudget;let thinkingLevelMap=getThinkingLevelMap(model,compat),mappedValue=reasoningEffort?thinkingLevelMap?.[reasoningEffort]:thinkingLevelMap?.off;return mappedValue===void 0?reasoningEffort:typeof mappedValue=="string"?mappedValue:void 0}function getCompatCacheControl(compat,cacheRetention){if(compat.cacheControlFormat!=="anthropic"||cacheRetention==="none")return;let ttl=cacheRetention==="long"&&compat.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...ttl?{ttl}:{}}}function applyAnthropicCacheControl(messages,tools,cacheControl){addCacheControlToSystemPrompt(messages,cacheControl),addCacheControlToLastTool(tools,cacheControl),addCacheControlToLastConversationMessage(messages,cacheControl)}function addCacheControlToSystemPrompt(messages,cacheControl){for(let message of messages)if(message.role==="system"||message.role==="developer"){addCacheControlToInstructionMessage(message,cacheControl);return}}function addCacheControlToLastConversationMessage(messages,cacheControl){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if((message.role==="user"||message.role==="assistant"||message.role==="tool")&&addCacheControlToMessage(message,cacheControl))return}}function addCacheControlToLastTool(tools,cacheControl){if(!tools||tools.length===0)return;let lastTool=tools[tools.length-1];lastTool.cache_control=cacheControl}function addCacheControlToInstructionMessage(message,cacheControl){return addCacheControlToTextContent(message,cacheControl)}function addCacheControlToMessage(message,cacheControl){return message.role==="user"||message.role==="assistant"||message.role==="tool"?addCacheControlToTextContent(message,cacheControl):!1}function addCacheControlToTextContent(message,cacheControl){let content=message.content;if(typeof content=="string")return content.length===0?!1:(message.content=[{type:"text",text:content,cache_control:cacheControl}],!0);if(!Array.isArray(content))return!1;for(let i=content.length-1;i>=0;i--){let part=content[i];if(part?.type==="text"){let textPart=part;return textPart.cache_control=cacheControl,!0}}return!1}function convertMessages(model,context,compat,options={}){let params=[],normalizeToolCallId=id=>{if(id.includes("|")){let separatorIndex=id.indexOf("|"),callId=id.slice(0,separatorIndex).replace(/[^a-zA-Z0-9_-]/g,"_"),itemId=id.slice(separatorIndex+1).replace(/[^a-zA-Z0-9_-]/g,"_"),combinedId=itemId.length>0?`${callId}_${itemId}`:callId;if(combinedId.length<=40)return combinedId;let hash2=shortHash(id).slice(0,8);return`${callId.slice(0,Math.max(1,40-hash2.length-1))}_${hash2}`}let sanitizedId=id.replace(/[^a-zA-Z0-9_-]/g,"_")||"tool_call";if(sanitizedId===id&&sanitizedId.length<=40)return id;let hash=shortHash(id).slice(0,8);return`${sanitizedId.slice(0,Math.max(1,40-hash.length-1))}_${hash}`},transformedMessages=transformMessages(context.messages,model,id=>normalizeToolCallId(id),{preserveThinking:options.preserveThinking,normalizeSameModelToolCallIds:!0});if(context.systemPrompt){let role=model.reasoning&&compat.supportsDeveloperRole?"developer":"system";params.push({role,content:sanitizeSurrogates(context.systemPrompt)})}let lastRole=null;for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(compat.requiresAssistantAfterToolResult&&lastRole==="toolResult"&&msg.role==="user"&¶ms.push({role:"assistant",content:"I have processed the tool results."}),msg.role==="user")if(typeof msg.content=="string")params.push({role:"user",content:sanitizeSurrogates(msg.content)});else{let content=msg.content.map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",image_url:{url:`data:${item.mimeType};base64,${item.data}`}});if(content.length===0)continue;params.push({role:"user",content})}else if(msg.role==="assistant"){let assistantMsg={role:"assistant",content:compat.requiresAssistantAfterToolResult?"":null},assistantTextParts=msg.content.filter(isTextContentBlock).filter(block=>block.text.trim().length>0).map(block=>({type:"text",text:sanitizeSurrogates(block.text)})),assistantText=assistantTextParts.map(part=>part.text).join(""),thinkingBlocks=msg.content.filter(isThinkingContentBlock),toolCalls=msg.content.filter(isToolCallBlock),signedReasoningDetails=thinkingBlocks.map(block=>parseOpenAIReasoningDetails(block.thinkingSignature)).find(details=>details!==void 0),legacyReasoningDetails=toolCalls.map(toolCall=>parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature)).filter(detail=>detail!==void 0),preservedReasoningDetails=signedReasoningDetails??(legacyReasoningDetails.length>0?legacyReasoningDetails:void 0),nonEmptyThinkingBlocks=thinkingBlocks.filter(block=>block.thinking.trim().length>0);if(nonEmptyThinkingBlocks.length>0)if(compat.requiresThinkingAsText){let thinkingText=nonEmptyThinkingBlocks.map(block=>sanitizeSurrogates(block.thinking)).join(`
|
|
4
4
|
|
|
5
5
|
`);assistantMsg.content=[{type:"text",text:thinkingText},...assistantTextParts]}else{assistantText.length>0&&(assistantMsg.content=assistantText);let signature=nonEmptyThinkingBlocks[0].thinkingSignature;model.provider==="opencode-go"&&signature==="reasoning"&&(signature="reasoning_content"),signature&&signature.length>0&&Object.assign(assistantMsg,{[signature]:nonEmptyThinkingBlocks.map(block=>block.thinking).join(`
|
package/dist/bundle/chunks/{package-manager-cli-C2K4YRGI.js → package-manager-cli-4ANSELYT.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{DefaultResourceLoader,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-
|
|
2
|
+
import{DefaultResourceLoader,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-EHSDTQ6I.js";import{DefaultPackageManager,DynamicBorder,appendHiddenTuiStdout,keyHint,rawKeyHint}from"./chunk-3FRTRCR6.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import"./chunk-W4SRGDQ4.js";import"./chunk-GFUZPFHN.js";import"./chunk-5E5TLB76.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-RLRLQRI2.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-YRN3PCTM.js";import{SettingsManager}from"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-IUZUN32Z.js";import"./chunk-P7PWCGLJ.js";import"./chunk-U6Z6OBX4.js";import"./chunk-LF3XTYYF.js";import"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import{killProcessTree}from"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import{source_default}from"./chunk-26UBFF6N.js";import{require_proper_lockfile}from"./chunk-3P23SBT3.js";import{APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import{__toESM}from"./chunk-VR4X5O2Z.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
|
|
3
3
|
`)}return hash.digest("hex")}import{spawn}from"node:child_process";import{closeSync,mkdirSync,openSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{fileURLToPath}from"node:url";function omoLocalUpdateWorkerLogPath(agentDir){return join2(agentDir,"omo-local-update","worker.log")}function workerCommandArgs(force){let updateArgs=["update","--omo-local-update-worker",...force?["--force"]:[]];if(detectInstallMethod()==="bun-binary")return updateArgs;let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",cliMainPath=resolve(dirname(modulePath),"..",`cli-main${extension}`);return[...process.execArgv,cliMainPath,...updateArgs]}var defaultSpawnWorker=request=>{let logPath=omoLocalUpdateWorkerLogPath(request.agentDir);try{mkdirSync(dirname(logPath),{recursive:!0});let logFd=openSync(logPath,"w");try{let child=spawn(process.execPath,workerCommandArgs(request.force),{detached:!0,env:process.env,stdio:["ignore",logFd,logFd]});return child.unref(),{ok:!0,pid:child.pid,logPath}}finally{closeSync(logFd)}}catch(error){return{ok:!1,message:error instanceof Error?error.message:String(error)}}};async function defaultRun(command,args,options){let child=spawnProcess(command,args,{cwd:options.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env,...options.env},detached:process.platform!=="win32",windowsHide:!0}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()});let abort=new AbortController,timedOut=!1,pid=child.pid,timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,pid!==void 0&&killProcessTree(pid),abort.abort()},options.timeoutMs);try{return{code:await waitForChildProcess(child,{signal:abort.signal}),stdout,stderr,timedOut}}finally{timer!==void 0&&clearTimeout(timer)}}function isKillSwitched(env){return env.SENPI_OMO_LOCAL_UPDATE==="0"}function defaultReadJson(path){try{return JSON.parse(readFileSync(path,"utf-8"))}catch{return}}function packageNameOf(json){if(typeof json!="object"||json===null)return;let name=json.name;return typeof name=="string"?name:void 0}function homeDir(){return process.env.HOME||homedir()}async function detectOmoLocalInstall(options){let readJson=options.readJson??defaultReadJson,exists=options.exists??existsSync2;if(options.packages)for(let entry of options.packages){let source=typeof entry=="string"?entry:entry.source;if(!isLocalPath(source))continue;let pluginPath=resolvePath(source,options.agentDir,{homeDir:homeDir(),trim:!0});if(packageNameOf(readJson(join3(pluginPath,"package.json")))!=="@code-yeongyu/omo-senpi")continue;let repoRoot=resolve2(pluginPath,"..","..",".."),omoSenpiPkgPath=join3(repoRoot,"packages","omo-senpi","package.json"),senpiTaskPkgPath=join3(repoRoot,"packages","senpi-task","package.json");if(!exists(omoSenpiPkgPath)||packageNameOf(readJson(omoSenpiPkgPath))!=="@oh-my-opencode/omo-senpi"||!exists(senpiTaskPkgPath)||packageNameOf(readJson(senpiTaskPkgPath))!=="@oh-my-opencode/senpi-task")continue;let topLevel;try{let result=await options.run("git",["-C",repoRoot,"rev-parse","--show-toplevel"],{});if(result.code!==0)continue;topLevel=result.stdout.trim()}catch{continue}if(!(topLevel===""||canonicalizePath(topLevel)!==canonicalizePath(repoRoot)))return{pluginPath,repoRoot}}}function omoLocalUpdateStampPath(agentDir){return join3(agentDir,"omo-local-update-state.json")}function readStamp(agentDir){let json=defaultReadJson(omoLocalUpdateStampPath(agentDir));if(typeof json!="object"||json===null)return;let candidate=json;if(typeof candidate.repoRoot!="string"||typeof candidate.sha!="string"||typeof candidate.omoSenpiTree!="string"||typeof candidate.senpiTaskTree!="string"||typeof candidate.buildInputsHash!="string"||typeof candidate.installedAt!="string"||!Array.isArray(candidate.artifacts))return;let artifacts=[];for(let artifact of candidate.artifacts){if(typeof artifact!="string")return;artifacts.push(artifact)}return{repoRoot:candidate.repoRoot,sha:candidate.sha,omoSenpiTree:candidate.omoSenpiTree,senpiTaskTree:candidate.senpiTaskTree,buildInputsHash:candidate.buildInputsHash,installedAt:candidate.installedAt,artifacts}}function writeStamp(agentDir,stamp){mkdirSync2(agentDir,{recursive:!0}),writeFileSync(omoLocalUpdateStampPath(agentDir),`${JSON.stringify(stamp,null,2)}
|
|
4
4
|
`,"utf-8")}function shouldSkipUpdate(options){if(options.force)return!1;let stamp=options.stamp;return!stamp||stamp.repoRoot!==options.repoRoot||stamp.sha!==options.remoteSha&&stamp.buildInputsHash!==options.remoteBuildInputsHash||stamp.artifacts.length===0?!1:options.stampArtifactsExist}var OmoLocalStepError=class extends Error{constructor(stage,message,output){super(message),this.name="OmoLocalStepError",this.stage=stage,this.output=output}};function firstErrorLine(result){for(let text of[result.stderr,result.stdout])for(let line of text.split(`
|
|
5
5
|
`)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}async function computeRemoteState(options){let{repoRoot,run}=options,git=(args,timeoutMs)=>run("git",args,{cwd:repoRoot,timeoutMs}),requireOk=async(args,timeoutMs)=>{let result=await git(args,timeoutMs);if(result.timedOut)throw new OmoLocalStepError("fetch",`git ${args.join(" ")} timed out`);if(result.code!==0)throw new OmoLocalStepError("fetch",`git ${args.join(" ")}: ${firstErrorLine(result)}`,`${result.stdout}${result.stderr}`);return result.stdout.trim()};await requireOk(["fetch","origin","dev"],12e4);let sha=await requireOk(["rev-parse","origin/dev"]);if(sha==="")throw new OmoLocalStepError("fetch","git rev-parse origin/dev: empty output");let subject=await requireOk(["log","-1","--format=%s","origin/dev"]),omoSenpiTree=await requireOk(["rev-parse","origin/dev:packages/omo-senpi"]),senpiTaskTree=await requireOk(["rev-parse","origin/dev:packages/senpi-task"]),buildInputsHash=computeBuildInputsHashFromLsTree(await requireOk(["ls-tree","-z","origin/dev"]));return{sha,subject,omoSenpiTree,senpiTaskTree,buildInputsHash}}function omoLocalUpdateLockPath(agentDir){return join3(agentDir,"omo-local-update.lock")}function omoLocalUpdateBuildWorktreePath(agentDir){return join3(agentDir,"omo-local-update","build-worktree")}function readLockFile(path){try{let json=JSON.parse(readFileSync(path,"utf-8"));return typeof json.pid!="number"||typeof json.nonce!="string"?void 0:{pid:json.pid,nonce:json.nonce}}catch{return}}function pidIsAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function acquireOmoLocalLock(agentDir,log){mkdirSync2(agentDir,{recursive:!0});let path=omoLocalUpdateLockPath(agentDir),lock={path,pid:process.pid,nonce:randomUUID()},payload=JSON.stringify({pid:lock.pid,nonce:lock.nonce,startedAt:new Date().toISOString()}),tryCreate=()=>{try{return writeFileSync(path,payload,{flag:"wx"}),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}},reportBusy=()=>{let existing2=readLockFile(path);log(source_default.dim(`OMO local plugin update already running (pid ${existing2?.pid??"unknown"}); skipping.`))};if(tryCreate())return lock;let existing=readLockFile(path);if(existing!==void 0&&pidIsAlive(existing.pid))return reportBusy();try{rmSync(path)}catch{}return tryCreate()?lock:reportBusy()}function releaseOmoLocalLock(lock){try{let existing=readLockFile(lock.path);existing!==void 0&&existing.pid===lock.pid&&existing.nonce===lock.nonce&&rmSync(lock.path)}catch{}}var OmoLocalBunMissingError=class extends Error{constructor(){super("bun not found on PATH"),this.name="OmoLocalBunMissingError"}};async function runBunStep(stage,args,worktree,run,timeoutMs){let result;try{result=await run("bun",args,{cwd:worktree,timeoutMs})}catch(error){throw error.code==="ENOENT"?new OmoLocalBunMissingError:new OmoLocalStepError(stage,`bun ${args.join(" ")} failed to start: ${error instanceof Error?error.message:String(error)}`)}let output=`${result.stdout}${result.stderr}`;if(result.timedOut)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} timed out after ${Math.round(timeoutMs/1e3)}s`,output);if(result.code!==0)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} exited with code ${result.code??"unknown"}`,output)}async function ensureBuildWorktree(options){let{worktree,repoRoot,sha,run}=options;if(existsSync2(worktree)){let commonDir=await run("git",["-C",worktree,"rev-parse","--git-common-dir"],{});if(commonDir.code===0&&commonDir.stdout.trim()!==""&&canonicalizePath(resolve2(worktree,commonDir.stdout.trim()))===canonicalizePath(join3(repoRoot,".git"))){let checkout=await run("git",["-C",worktree,"checkout","--detach","--force",sha],{});if(checkout.code!==0)throw new OmoLocalStepError("worktree",`git checkout --detach --force: ${firstErrorLine(checkout)}`,`${checkout.stdout}${checkout.stderr}`);return}((await run("git",["-C",repoRoot,"worktree","remove","--force",worktree],{})).code!==0||existsSync2(worktree))&&rmSync(worktree,{recursive:!0,force:!0})}mkdirSync2(dirname2(worktree),{recursive:!0});let add=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(add.code===0)return;await run("git",["-C",repoRoot,"worktree","prune"],{});let retry=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(retry.code!==0)throw new OmoLocalStepError("worktree",`git worktree add: ${firstErrorLine(retry)}`,`${add.stdout}${add.stderr}${retry.stdout}${retry.stderr}`)}var defaultFsSeam={cpSync:(source,destination)=>{cpSync(source,destination,{recursive:!0})},renameSync:(oldPath,newPath)=>{renameSync(oldPath,newPath)},rmSync:path=>{rmSync(path,{recursive:!0,force:!0})}},swapCounter=0;function swapPluginDir(options){let seam=options.fs??defaultFsSeam;swapCounter+=1;let tag=`${Date.now()}-${process.pid}-${swapCounter}`,staging=`${options.pluginPath}.staging-${tag}`,prev=`${options.pluginPath}.prev-${tag}`;seam.cpSync(options.sourceDir,staging),seam.renameSync(options.pluginPath,prev);try{seam.renameSync(staging,options.pluginPath)}catch(error){throw seam.renameSync(prev,options.pluginPath),seam.rmSync(staging),error}seam.rmSync(prev)}function firstLine(text){for(let line of text.split(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{classifyCredentialFailure,rendezvousOrder,resolveConfigValue,runCredentialFailover}from"./chunk-
|
|
2
|
+
import{classifyCredentialFailure,rendezvousOrder,resolveConfigValue,runCredentialFailover}from"./chunk-XK24AFYU.js";import{discoverEnvSlots}from"./chunk-MUC3MZTV.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import{acquireHalfOpenLease}from"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import{listSlots}from"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-U7RQY7MH.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{createHash,randomUUID}from"node:crypto";var sha256SlotHasher=input=>createHash("sha256").update(input).digest().readBigUInt64BE(0);function overlayState(slot,state){return state?{...slot,...state.blockedUntil===void 0?{}:{blockedUntil:state.blockedUntil},...state.blockReason===void 0?{}:{blockReason:state.blockReason},...state.failureCount===void 0?{}:{failureCount:state.failureCount},...state.lease===void 0?{}:{lease:state.lease}}:slot}async function listRotationSlots(sources,options={}){let acquireLeases=options.acquireLeases!==!1,{providerId,credential,env,repository}=sources,policySlots=[];for(let[name,ref]of Object.entries(sources.policy?.slots??{})){let envVarName=ref.env??`models.json:${name}`,key=ref.env!==void 0?env(ref.env):ref.value!==void 0?await resolveConfigValue(ref.value,{}):void 0;key&&policySlots.push({name,envVarName,key,source:"env"})}if(credential){let state=await repository.listSlots(providerId,"stored"),slots=[];for(let slot of listSlots(credential)){let persisted=state[slot.name],storedRevision=await repository.storedCredentialRevision(providerId,slot.name,{key:slot.key,access:slot.access,refresh:slot.refresh}),applicable=persisted?.credentialRevision===storedRevision?persisted:void 0;if(acquireLeases&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=(sources.now??Date.now)()){if(!await acquireHalfOpenLease(repository,providerId,"stored",slot.name,{now:(sources.now??Date.now)()}))continue;let leasedState=(await repository.listSlots(providerId,"stored"))[slot.name];slots.push(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},leasedState?.credentialRevision===storedRevision?leasedState:void 0));continue}slots.push(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},applicable))}if(policySlots.length===0)return slots;let namedSources={...sources,credential:void 0,policy:{...sources.policy,slots:{}}},namedSlots=await listEnvRotationSlots(namedSources,policySlots,acquireLeases);return[...slots,...namedSlots]}let envSlots=[...discoverEnvSlots(providerId,env),...policySlots];return listEnvRotationSlots(sources,envSlots,acquireLeases)}async function listEnvRotationSlots(sources,envSlots,acquireLeases=!0){if(envSlots.length===0)return[];let{providerId,repository}=sources,state=await repository.listSlots(providerId,"env"),slots=[];for(let slot of envSlots){let persisted=state[slot.name],revision=await repository.envCredentialRevision(slot.envVarName,slot.key),applicable=persisted?.credentialRevision===revision?persisted:void 0;if(acquireLeases&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=(sources.now??Date.now)()){if(!await acquireHalfOpenLease(repository,providerId,"env",slot.name,{now:(sources.now??Date.now)()}))continue;applicable=(await repository.listSlots(providerId,"env"))[slot.name]}slots.push(overlayState({name:slot.name,lane:"env",envKey:slot.key,envVarName:slot.envVarName},applicable))}return slots}function blockPatch(block,current,now,credentialRevision,policy){let base={failureCount:(current?.failureCount??0)+1,...credentialRevision===void 0?{}:{credentialRevision},...current?.lastSuccessAt===void 0?{}:{lastSuccessAt:current.lastSuccessAt}};return block.reason==="rate_limit"?{...base,blockedUntil:now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs),blockReason:"rate_limit"}:{...base,blockReason:block.reason}}function errorFromEvent(event){if(event.type!=="error")return;let message=event.error.errorMessage??"provider stream error";return new Error(message)}function streamWithCredentialRotation(options){let{sources,runAttempt}=options,hasher=options.hasher??sha256SlotHasher,affinityKey=options.affinityKey??randomUUID(),useAffinity=sources.policy?.affinity!==!1,now=sources.now??Date.now;return runCredentialFailover({listSlots:()=>listRotationSlots(sources),select:candidates=>{let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let winner=(useAffinity?rendezvousOrder(affinityKey,candidates,hasher):candidates)[0];if(!winner)throw new Error("credential rotation selected from an empty candidate set");return winner},runAttempt,isCommittedOutput:event=>event.type!=="start",errorFromEvent,classify:(error,context)=>classifyCredentialFailure(error,{...context,cooldownBaseMs:sources.policy?.cooldownBaseMs,cooldownCapMs:sources.policy?.cooldownCapMs}),onSuccess:async slot=>{await sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>current?{...current,lastSuccessAt:now(),lease:void 0,blockedUntil:void 0,blockReason:void 0}:void 0)},persistBlock:async(slot,block)=>{let revision=slot.lane==="env"&&slot.envVarName!==void 0&&slot.envKey!==void 0?await sources.repository.envCredentialRevision(slot.envVarName,slot.envKey):slot.storedRevision;await sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>blockPatch(block,current,now(),revision,sources.policy))},now})}export{listRotationSlots,sha256SlotHasher,streamWithCredentialRotation};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{runRpcMode}from"./chunk-5E5TLB76.js";import"./chunk-RLRLQRI2.js";import"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-U6Z6OBX4.js";import"./chunk-HSH674C6.js";import"./chunk-HB35RBP4.js";import"./chunk-MUC3MZTV.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-U7RQY7MH.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";export{runRpcMode};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{SessionSelectorComponent,createStartupTui,startStartupTui}from"./chunk-
|
|
2
|
+
import{SessionSelectorComponent,createStartupTui,startStartupTui}from"./chunk-3FRTRCR6.js";import{KeybindingsManager}from"./chunk-3Q4WGKFA.js";import"./chunk-RLRLQRI2.js";import{setKeybindings}from"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-7X72IACK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-I7YUNMWH.js";import"./chunk-U7RQY7MH.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";async function selectSession(currentSessionsLoader,allSessionsLoader,settingsManager){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let keybindings=KeybindingsManager.create();setKeybindings(keybindings);let resolved=!1,selector=new SessionSelectorComponent(currentSessionsLoader,allSessionsLoader,path=>{resolved||(resolved=!0,ui.stop(),resolve(path))},()=>{resolved||(resolved=!0,ui.stop(),resolve(null))},()=>{ui.stop(),process.exit(0)},()=>ui.requestRender(),{showRenameHint:!1,keybindings});ui.addChild(selector),ui.setFocus(selector.getSessionList()),startStartupTui(ui,settingsManager)})}export{selectSession};
|