blade-code 0.10.204 → 0.10.206
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/dist/blade.js +2 -2
- package/dist/chunk-09kqfdpa.js +3 -0
- package/dist/{chunk-p6586ftx.js → chunk-0ef47wgr.js} +2 -2
- package/dist/chunk-1j39te3t.js +23 -0
- package/dist/{chunk-fdr4fcrf.js → chunk-1n4v80hy.js} +1 -1
- package/dist/{chunk-4fbpydtn.js → chunk-28n945me.js} +2 -2
- package/dist/{chunk-ys8gysg8.js → chunk-28tzj187.js} +1 -1
- package/dist/{chunk-j89qk7bp.js → chunk-3crwyd2r.js} +3 -3
- package/dist/{chunk-zfxcef0z.js → chunk-50vwafn5.js} +1 -1
- package/dist/chunk-514va7ce.js +2 -0
- package/dist/{chunk-kkzznz4w.js → chunk-53vh6vpt.js} +1 -1
- package/dist/chunk-5k8k56f2.js +731 -0
- package/dist/{chunk-f4d8312x.js → chunk-65wc1h38.js} +1 -1
- package/dist/{chunk-bx2s02mt.js → chunk-67wy9mm7.js} +2 -2
- package/dist/chunk-6p0hkf4f.js +1 -0
- package/dist/{chunk-qdbbke8f.js → chunk-6xzk4hsg.js} +1 -1
- package/dist/chunk-793wjhvz.js +332 -0
- package/dist/chunk-826xegd8.js +6 -0
- package/dist/chunk-867bpjzg.js +1 -0
- package/dist/{chunk-hnvvve5d.js → chunk-870szc6v.js} +1 -1
- package/dist/chunk-983hqzat.js +1 -0
- package/dist/{chunk-0eajnhrj.js → chunk-9kj19a8t.js} +1 -1
- package/dist/{chunk-55n8ppxf.js → chunk-9sf1t8gw.js} +1 -1
- package/dist/chunk-9tpzmy8v.js +4 -0
- package/dist/chunk-af0m5227.js +1 -0
- package/dist/chunk-asgmmaec.js +3 -0
- package/dist/{chunk-m640mr36.js → chunk-av799ng5.js} +2 -2
- package/dist/{chunk-rwm71p4g.js → chunk-az3rehz9.js} +360 -360
- package/dist/{chunk-p0wyhp5a.js → chunk-dnpkf5mv.js} +2 -2
- package/dist/chunk-dpg006xj.js +1 -0
- package/dist/{chunk-0xf70s5c.js → chunk-e0ft3vwg.js} +1 -1
- package/dist/chunk-e45r1a8r.js +25 -0
- package/dist/{chunk-vzdsext4.js → chunk-ebpg1srd.js} +2 -2
- package/dist/{chunk-n52n2w5v.js → chunk-ed2hdrwe.js} +1 -1
- package/dist/{chunk-7ajvrtb3.js → chunk-erhaedch.js} +1 -1
- package/dist/{chunk-kehgewqh.js → chunk-ewwrss2w.js} +1 -1
- package/dist/{chunk-9fyjyk2f.js → chunk-fc1gz532.js} +2 -2
- package/dist/{chunk-vgf07dhy.js → chunk-fd0a8h55.js} +2 -2
- package/dist/{chunk-6dw3pk3c.js → chunk-fnmqxhv1.js} +2 -2
- package/dist/chunk-g7tphxme.js +6 -0
- package/dist/{chunk-cjfb4kjp.js → chunk-gmpsfkgg.js} +1 -1
- package/dist/chunk-gpnkxh4c.js +1 -0
- package/dist/{chunk-8j0z248z.js → chunk-gz84aewr.js} +1 -1
- package/dist/{chunk-2xpjy0ef.js → chunk-h4k69z1b.js} +1 -1
- package/dist/{chunk-dhxx5mwe.js → chunk-h6ahwwpa.js} +2 -2
- package/dist/chunk-hpge30p8.js +8 -0
- package/dist/{chunk-1cy4ab77.js → chunk-hv8nt7wj.js} +1 -1
- package/dist/chunk-mtvbm7xe.js +1 -0
- package/dist/chunk-mys9mmcp.js +1 -0
- package/dist/{chunk-wezr6wfq.js → chunk-n34qsnks.js} +1 -1
- package/dist/chunk-n5jzmwhy.js +25 -0
- package/dist/chunk-new78c3h.js +1 -0
- package/dist/{chunk-je908ygr.js → chunk-nj6kpdte.js} +2 -2
- package/dist/chunk-nng1xbsm.js +10 -0
- package/dist/{chunk-pqsjy31p.js → chunk-p2y1zqsb.js} +2 -2
- package/dist/chunk-p8vpvx07.js +12 -0
- package/dist/{chunk-3cas6rv5.js → chunk-pdna2qvv.js} +2 -2
- package/dist/{chunk-gzdk86fm.js → chunk-pga8gxtf.js} +1 -1
- package/dist/chunk-pt0y4zrg.js +14 -0
- package/dist/{chunk-w4bedq0m.js → chunk-q6abav45.js} +51 -51
- package/dist/chunk-r4em0ha7.js +1 -0
- package/dist/chunk-rdzbd5vk.js +1 -0
- package/dist/chunk-sbfe9vh3.js +94 -0
- package/dist/chunk-sqk8cnej.js +44 -0
- package/dist/{chunk-5yyp6njq.js → chunk-t0gm0pn1.js} +1 -1
- package/dist/{chunk-egss0m1x.js → chunk-tsm8rhmd.js} +1 -1
- package/dist/chunk-tzvb0nd2.js +2 -0
- package/dist/{chunk-wk869s65.js → chunk-v4cxk10d.js} +1 -1
- package/dist/{chunk-g383afnv.js → chunk-v5vx6nz9.js} +1 -1
- package/dist/{chunk-x49bw41v.js → chunk-vx2g1faw.js} +1 -1
- package/dist/chunk-w6zat4v4.js +1 -0
- package/dist/chunk-wsd3rn0q.js +1 -0
- package/dist/{chunk-smxdn7kq.js → chunk-xcq0cehr.js} +5 -6
- package/dist/chunk-yjjxv7fn.js +352 -0
- package/dist/{chunk-z0m9j0e2.js → chunk-yzf2jpam.js} +2 -2
- package/dist/web/assets/{ChatView-BF6HUrBw.js → ChatView-lUD-61n0.js} +4 -4
- package/dist/web/assets/{CodeBlockHighlighter-C4CgCiRf.js → CodeBlockHighlighter--TbfcBxW.js} +1 -1
- package/dist/web/assets/FilePreview-R6OKQPf2.js +55 -0
- package/dist/web/assets/{KanbanBoard-DDXB-yq1.js → KanbanBoard-BHOKtiv5.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DS7RznBE.js → MarkdownRenderer-DqxNq8pa.js} +3 -3
- package/dist/web/assets/{ScrollArea-BM9NzGZM.js → ScrollArea-Dhu0B-zB.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-DnRySeLE.js → SessionHistorySurface-aZvoj3ma.js} +1 -1
- package/dist/web/assets/{SettingsModal-D5YLUtIo.js → SettingsModal-C7QBnIqa.js} +1 -1
- package/dist/web/assets/{Sidebar-BZC6OkDJ.js → Sidebar-Bznnq91x.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-WewOkw5m.js → TaskSwitcher-DJczhDRp.js} +1 -1
- package/dist/web/assets/{TerminalPanel-C5SGdRNr.js → TerminalPanel-Vk4p0V3p.js} +1 -1
- package/dist/web/assets/{archive-DkczUU08.js → archive-0hLYBKQf.js} +1 -1
- package/dist/web/assets/{arrow-left-9pBiQwu7.js → arrow-left-CXb6Gqf3.js} +1 -1
- package/dist/web/assets/{calendar-clock-BFnUlxrU.js → calendar-clock-DiaFI9Jk.js} +1 -1
- package/dist/web/assets/{chevron-right-yCVkAEcj.js → chevron-right-CcPXH37D.js} +1 -1
- package/dist/web/assets/{clock-3-CcoWoRQs.js → clock-3-D6VR6gJc.js} +1 -1
- package/dist/web/assets/{copy-HJF0oQBS.js → copy-C3eUAQgp.js} +1 -1
- package/dist/web/assets/{download-DSBCIqk3.js → download-DHvS9tI3.js} +1 -1
- package/dist/web/assets/{external-link-zIgEO0KB.js → external-link-BDVaEuqY.js} +1 -1
- package/dist/web/assets/{folder-BdRo64o3.js → folder-B80Ac6rr.js} +1 -1
- package/dist/web/assets/index-VwIiNjc8.css +1 -0
- package/dist/web/assets/{index-BVDkKudh.js → index-YqughEZk.js} +4 -4
- package/dist/web/assets/{message-square-plus-3klTXO0S.js → message-square-plus-D15quyPH.js} +1 -1
- package/dist/web/assets/{pause-B9Q5JWvH.js → pause-BjMlj6Bx.js} +1 -1
- package/dist/web/assets/{pencil-CbYIz1b1.js → pencil-BMoJvcB7.js} +1 -1
- package/dist/web/assets/{play-CZMTj43e.js → play-BHh4py3p.js} +1 -1
- package/dist/web/assets/{plus-Cc7I8fhb.js → plus-DeFz_gQq.js} +1 -1
- package/dist/web/assets/session-events-DCHBz9We.js +25 -0
- package/dist/web/assets/{settings-DSF3exX2.js → settings-CI8xbId2.js} +1 -1
- package/dist/web/assets/{team-qfeJHL9s.js → team-zZ803hH9.js} +1 -1
- package/dist/web/assets/{teamService-Bs9qBKI8.js → teamService-CgLBXgmv.js} +1 -1
- package/dist/web/assets/{terminal-DQLqe-Ed.js → terminal-1WxSJ47E.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-1b8qjgm6.js +0 -181
- package/dist/chunk-1vq22245.js +0 -10
- package/dist/chunk-3den8b7b.js +0 -1
- package/dist/chunk-42vt2eqq.js +0 -1
- package/dist/chunk-4ts2s9mz.js +0 -94
- package/dist/chunk-5dcsrs7e.js +0 -2
- package/dist/chunk-5j94j64z.js +0 -25
- package/dist/chunk-6ax5dpd3.js +0 -1
- package/dist/chunk-7atwbngw.js +0 -1
- package/dist/chunk-7d3msqg3.js +0 -14
- package/dist/chunk-81py03y4.js +0 -44
- package/dist/chunk-8cncpfhd.js +0 -6
- package/dist/chunk-8ej7w92s.js +0 -1
- package/dist/chunk-ae0fafmv.js +0 -1
- package/dist/chunk-ayvx3h91.js +0 -1
- package/dist/chunk-b50smz3h.js +0 -1
- package/dist/chunk-bx3b61xw.js +0 -1
- package/dist/chunk-d256m8rb.js +0 -1
- package/dist/chunk-e49ctwmg.js +0 -1
- package/dist/chunk-egc2f1ye.js +0 -733
- package/dist/chunk-ggdgk3gy.js +0 -3
- package/dist/chunk-h78hhhgt.js +0 -1
- package/dist/chunk-hkk83qt6.js +0 -23
- package/dist/chunk-ky592ay9.js +0 -2
- package/dist/chunk-m0t26vkj.js +0 -4
- package/dist/chunk-myvt7yjm.js +0 -8
- package/dist/chunk-nsb3cj6t.js +0 -6
- package/dist/chunk-p8cmxhbr.js +0 -25
- package/dist/chunk-qpmvp4q2.js +0 -2
- package/dist/chunk-rmfzym94.js +0 -3
- package/dist/chunk-rnt2fejc.js +0 -1
- package/dist/chunk-tm3789m3.js +0 -2
- package/dist/chunk-vtssm7r5.js +0 -12
- package/dist/chunk-ztreczac.js +0 -353
- package/dist/web/assets/FilePreview-BS4PgFKb.js +0 -55
- package/dist/web/assets/index-CaCifsSK.css +0 -1
- package/dist/web/assets/session-events-NEjosinC.js +0 -31
package/dist/chunk-ggdgk3gy.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{ek as C,fk as I}from"./chunk-ky592ay9.js";import{gk as _}from"./chunk-n52n2w5v.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
|
|
2
|
-
`,{mode:384}),await B.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await B.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await B.mkdir(this.storeDir,{recursive:!0,mode:448}),await B.chmod(this.storeDir,448)}}}
|
|
3
|
-
export{R as bk,t as ck,x as dk};
|
package/dist/chunk-h78hhhgt.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ag as c,Bg as d,yg as a,zg as b}from"./chunk-pqsjy31p.js";import"./chunk-81py03y4.js";import"./chunk-qpmvp4q2.js";import"./chunk-tm3789m3.js";import"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import"./chunk-z0m9j0e2.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
|
package/dist/chunk-hkk83qt6.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{v as HH,w as JH}from"./chunk-5dcsrs7e.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-6dw3pk3c.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-dhxx5mwe.js";import{Aa as Iz,Ba as yz,Ca as hz,Da as kz,N as R,W as Az,X as Oz,da as Ez,ga as qz,ha as Tz,ka as Pz}from"./chunk-rwm71p4g.js";import"./chunk-vzdsext4.js";import{Ra as ez}from"./chunk-p8cmxhbr.js";import{Ta as Nz,Xa as i,_a as a}from"./chunk-9fyjyk2f.js";import{Nb as Kz,Zb as wz,ic as l}from"./chunk-1b8qjgm6.js";import{tc as d}from"./chunk-fdr4fcrf.js";import{Dd as Bz,Nd as I,Od as v,Pd as Gz,Ud as Vz,Xd as jz,Zd as M,ae as Dz,fe as Fz,ie as F}from"./chunk-4ts2s9mz.js";import"./chunk-egss0m1x.js";import{Ge as _z,Ne as r,Oe as Uz}from"./chunk-ztreczac.js";import"./chunk-p6586ftx.js";import{zf as LH}from"./chunk-bx2s02mt.js";import"./chunk-p0wyhp5a.js";import{Uf as oz,Vf as nz}from"./chunk-5j94j64z.js";import"./chunk-v508x7cg.js";import{eg as e}from"./chunk-5yyp6njq.js";import{jg as Wz}from"./chunk-myvt7yjm.js";import{rg as m}from"./chunk-4fbpydtn.js";import"./chunk-3cas6rv5.js";import{wg as sz}from"./chunk-zfxcef0z.js";import"./chunk-pqsjy31p.js";import"./chunk-egc2f1ye.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import{sh as tz}from"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-smxdn7kq.js";import"./chunk-ys8gysg8.js";import{vi as az,yi as rz}from"./chunk-81py03y4.js";import"./chunk-qpmvp4q2.js";import{Wi as g,Xi as Xz,Zi as c,_i as p}from"./chunk-tm3789m3.js";import{cj as t}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import{Ej as y}from"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import{Rj as lz,Uj as iz}from"./chunk-0eajnhrj.js";import"./chunk-z0m9j0e2.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import{gk as $z,hk as dz,lk as zz,pk as Hz,qk as vz,rk as Jz}from"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
-
`)}function BH(z){if(!Wz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function _H(z){if(!(z instanceof gz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Gz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function UH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,L,Y,$={}){this.id=z;this.roots=H;this.connection=L;this.clientCapabilities=Y;this.options=$;this.messages=[...$.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode($.permissionMode),this.updateEgress=new Mz({maxPendingItems:xz,maxPendingBytes:bz,writeTimeoutMs:Rz,signal:L.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await L.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?F.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?F.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await F.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(L){if(!(L instanceof Fz)&&L.code!=="ENOENT")throw L;await F.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await F.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Pz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async(Z)=>{await this.sendUpdateAndWait(Z)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(Z)=>this.requestPermission(Z)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let L=this.options.mcpServers?$H(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),$=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Ez.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...$?{workspace:$}:{},permissionMode:this.mapModeToPermissionMode(),...L?{mcpServers:L}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Z,_)=>{let U=await Y.execute(Z,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await yz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Kz.subscribe((Z)=>{if(Z.sessionId!==this.id||Z.projectPath!==this.roots.hostStateRoot)return;if(Z.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Z.properties}}),this.requestPendingResume();return}if(Z.type==="follow_up.queue.changed"){let _=i.safeParse(Z.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if(Z.type==="provider.recovery"){let _=m.safeParse(Z.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if(Z.type==="turn.activity"){let _=a.safeParse(Z.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if(Z.type==="task.delivery"){if(!Z.properties.taskDelivery||typeof Z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Z.properties.taskDelivery,...Z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Z.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=Z.properties,T=Z.properties.metadata;if(Z.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Oz(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Az(_,$z()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:Z.type,...Z.properties}}});return}if(Z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Z.properties.taskStatus,...typeof Z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Z.properties.taskStatusReason}:{},...Z.properties.taskFailure&&typeof Z.properties.taskFailure==="object"?{"blade/taskFailure":Z.properties.taskFailure}:{},...typeof Z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Z.properties.taskStartedAt}:{},...typeof Z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Z.properties.taskCompletedAt}:{},...Z.properties.taskDiffStat&&typeof Z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Z.properties.taskDiffStat}:{},...typeof Z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Z.properties.taskQueuePosition}:{},...typeof Z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Z.properties.taskQueueDepth}:{},...typeof Z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Z.properties.taskConcurrencyLimit}:{},...typeof Z.properties.taskInFlight==="number"?{"blade/taskInFlight":Z.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!_z(H))continue;let L=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!L)continue;for(let Y of XH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:L,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot()),this.sendProviderRecoveryProjection(z.getProviderRecoveryProjection()),this.sendTurnActivityProjection(z.getTurnActivityProjection())}catch{G.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,H){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let L={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],model:{getChatConfig:()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getChatService().getConfig()}},rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,Z,_=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)_(V);else Z=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,Z)_(Z);return U}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:W,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),Z=await B.completion,_=(await S.list(this.roots.hostStateRoot,this.id)).find((U)=>U.start.reviewId===B.reviewId);if(!_)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:Z.status,findings:Z.findings.length,content:Bz(_.start,Z)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:_})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await hz(z,L),$=Y.data?.action;if($==="start_goal"||$==="resume_goal")this.requestPendingResume();if($==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(L){if(H.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,L),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${L instanceof Error?L.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,L,Y=new Promise(($)=>{L=$});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch($){if(H.signal.aborted||$ instanceof Error&&$.name==="AbortError")return{stopReason:"cancelled"};throw $}finally{if(L(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===H){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=kz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter(($)=>!H.includes($.name)&&($.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map(($)=>{let X;if($.usage){let Q=$.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if($.aliases?.length){let Q=`Aliases: ${$.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:$.name,description:$.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map(($)=>$.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let L=this.resolvePrompt(z.prompt),Y=L.content,$=L.displayText,X=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((j)=>j.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Dz(X).schema;if($.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand($)}let W=Nz($);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((j)=>j.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test($.trim()))return this.handleSlashCommand($,this.pendingPrompt.signal);let j=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!j.accepted)throw Error(j.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${j.queued})`),this.sendFollowUpQueueSnapshot(j.queue??await this.runtime.getFollowUpQueueSnapshot()),j.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,Z=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)Z();else H.abortSignal?.addEventListener("abort",Z,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((j)=>{T=j});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${$.slice(0,100)}...`),Iz($)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand($,B.signal)}let j={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(J)=>{this.mode=this.mapPermissionModeToMode(J),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}},N=await wz(this.agent.chatStream(Y,j,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(J)=>{switch(J.kind){case"content_delta":if(Q)break;if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{V=!0;let D=J.toolCall,A=D.function.name;if(A===M)break;let q=this.mapToolKind(J.toolKind),K=`Executing ${A}`;if(A==="Task"&&"function"in D)try{let b=JSON.parse(D.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")K=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:K,content:[],kind:q});break}case"tool_progress":{V=!0;let D=J.toolCall;if(D.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:J.update.message}}]});break}case"tool_result":{V=!0;let D=J.toolCall;if(D.function.name===M)break;let A=J.result,q=[],K=A.metadata;if(K?.kind==="patch"&&Array.isArray(K.changes))for(let w of K.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;q.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(K?.kind==="edit"&&typeof K.file_path==="string"&&typeof K.oldContent==="string"&&(typeof K.newContent==="string"||K.newContent===void 0))q.push({type:"diff",path:K.file_path,oldText:K.oldContent,newText:K.newContent??null});else{let w=D.function.name,QH=Tz(jz(qz(w,A),Vz));q.push({type:"content",content:{type:"text",text:QH}})}if(D.function.name==="Task"&&(K?.verificationVerdict==="pass"||K?.verificationVerdict==="fail"||K?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${K.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(J.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
|
|
3
|
-
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${J.contentKind} r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
|
|
4
|
-
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${J.revision} (${J.serverName}): ${J.uri}
|
|
5
|
-
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${J.revision} (${J.serverName}): ${J.phase} ${J.attempt}/${J.maxAttempts}
|
|
6
|
-
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${J.revision} (${J.serverName}) ${J.level}${J.logger?` logger=${J.logger}`:""}: ${J.message}
|
|
7
|
-
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${J.revision} (${J.serverName}): ${J.action}${J.detailsOmitted?" details-omitted":""}
|
|
8
|
-
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${J.revision} ${J.taskId} (${J.serverName}/${J.toolName}): ${J.status}${J.hasResult?" result-available":""}
|
|
9
|
-
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${J.files.length}${J.blockedWrite?" (write retry required)":""}
|
|
10
|
-
`}});break;case"provider_admission":_=J.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":J.phase!=="admitted"?{phase:J.phase,requestClass:J.requestClass,resource:J.resource,scope:J.scope,...J.reason!==void 0?{reason:J.reason}:{},queuePosition:J.queuePosition,queueDepth:J.queueDepth,inFlight:J.inFlight,limit:J.limit,waitMs:J.waitMs,maxWaitMs:J.maxWaitMs,...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:J.phase,reason:J.reason,...J.statusCode!==void 0?{statusCode:J.statusCode}:{},...J.retryAfterMs!==void 0?{retryAfterMs:J.retryAfterMs}:{},...J.nextProbeAt!==void 0?{nextProbeAt:J.nextProbeAt}:{},openDurationMs:J.openDurationMs,...J.sampleCount!==void 0?{sampleCount:J.sampleCount}:{},...J.failureCount!==void 0?{failureCount:J.failureCount}:{},...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:J.phase,attempt:J.attempt,maxRetries:J.maxRetries,reason:J.reason,...J.statusCode!==void 0?{statusCode:J.statusCode}:{},...J.delayMs!==void 0?{delayMs:J.delayMs}:{},...J.nextRetryAt!==void 0?{nextRetryAt:J.nextRetryAt}:{},...J.mode!==void 0?{mode:J.mode}:{},...J.recoveryBudgetMs!==void 0?{recoveryBudgetMs:J.recoveryBudgetMs}:{},...J.recoveryElapsedMs!==void 0?{recoveryElapsedMs:J.recoveryElapsedMs}:{},...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{},...J.exhaustedBy!==void 0?{exhaustedBy:J.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":J.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:J.phase,stallCount:J.stallCount,durationMs:J.durationMs,warningAfterMs:J.warningAfterMs,timeoutMs:J.timeoutMs,outputStarted:J.outputStarted}}});break;case"provider_recovery":break;case"turn_activity":break;case"model_fallback":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/modelFallback":{from:J.from,to:J.to,candidate:J.candidate,candidateCount:J.candidateCount,trigger:J.trigger}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:J.phase,toolName:J.toolName,runLength:J.runLength,nudgeThreshold:J.nudgeThreshold,haltThreshold:J.haltThreshold,progressAware:J.progressAware}}});break;case"task_update":this.sendPlanUpdate(J.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:J.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:J.goal.goalId,status:J.goal.status,taskListId:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,inProgress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,nextTask:J.frontier.nextTask,digestSha256:J.frontier.digestSha256,...J.goal.frontierStall?{stall:{category:J.goal.frontierStall.category,consecutiveCount:J.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(J.tasks);break;case"steering_applied":this.sendFollowUpQueueSnapshot(J.queue);break;case"follow_up_queue_changed":this.sendFollowUpQueueSnapshot(J.queue);break;case"follow_up_started":{this.sendFollowUpQueueSnapshot(J.queue);let D=0;for(let A of J.messages){if(!A.recovered||A.persisted)continue;if(H.projectedRecoveredInputIds?.has(A.id))continue;for(let q of cz(A.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});H.projectedRecoveredInputIds?.add(A.id),D++}if(D>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${D} queued instruction${D===1?"":"s"} recovered after restart]
|
|
11
|
-
`}});break}case"goal_updated":if(J.goal)this.sendUpdate(this.goalSessionUpdate(J.goal));if(J.goal&&J.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${J.goal.status}: ${J.goal.objective}]
|
|
12
|
-
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:J.goal.goalId,continuation:J.continuation,...J.prematureStopPattern?{prematureStopPattern:J.prematureStopPattern}:{},...J.prematureStopCount!==void 0?{prematureStopCount:J.prematureStopCount}:{},...J.goal.executionHostFailure?{executionHostFailure:{category:J.goal.executionHostFailure.category,consecutiveCount:J.goal.executionHostFailure.consecutiveCount}}:{},...J.goal.turnLineage?{turnLineage:J.goal.turnLineage}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:J.phase,...J.reason?{reason:J.reason}:{},...J.strategy?{strategy:J.strategy}:{},...J.outcome?{outcome:J.outcome}:{},...J.preTokens!==void 0?{preTokens:J.preTokens}:{},...J.preTokenSource?{preTokenSource:J.preTokenSource}:{},...J.estimatedPendingTokens!==void 0?{estimatedPendingTokens:J.estimatedPendingTokens}:{},...J.postTokens!==void 0?{postTokens:J.postTokens}:{},...J.sampleAttempts!==void 0?{sampleAttempts:J.sampleAttempts}:{},...J.inputReductions!==void 0?{inputReductions:J.inputReductions}:{},...J.messagesOmitted!==void 0?{messagesOmitted:J.messagesOmitted}:{},...J.filesOmitted!==void 0?{filesOmitted:J.filesOmitted}:{},...J.imagesOmitted!==void 0?{imagesOmitted:J.imagesOmitted}:{},...J.fallbackTargetTokens!==void 0?{fallbackTargetTokens:J.fallbackTargetTokens}:{},...J.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:J.fallbackMessagesOmitted}:{},...J.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:J.fallbackMessagesTruncated}:{},...J.failureReason?{failureReason:J.failureReason}:{},...J.memory?{memory:J.memory}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...j.messages];let Qz=await this.loadPersistedMessages();if(this.messages=Qz.length>0?Qz:[...j.messages],!N.success){let J=N.error?.type??"unknown",D=N.error?.details??N.error?.message??"Agent execution failed",A=BH(D)??v(D);throw gz.internalError({failureType:J,modelId:this.runtime.getCurrentModelId(),taskFailure:A,outputStarted:U,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${J})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let Yz={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(Yz).length>0?{_meta:Yz}:{}}}catch(j){if(B.signal.aborted||j instanceof Error&&j.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,j),j}finally{if(H.abortSignal?.removeEventListener("abort",Z),_&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(T(),this.pendingPromptCompletion===E)this.pendingPromptCompletion=null;if(this.pendingPrompt===B){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let H=z.trimStart().slice(1).trim();if(!H)throw Error("User shell command cannot be empty");let L=new AbortController,Y,$=new Promise((W)=>{Y=W});this.pendingUserShell=L,this.pendingUserShellCompletion=$;let X,Q="";try{let W=await this.runtime.executeUserShellCommand(H,{signal:L.signal,onEvent:async(Z)=>{if(X=Z.executionId,Z.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.executionId,status:"in_progress",title:`! ${Z.command}`,content:[],kind:"execute"});return}if(Z.type==="output"){Q+=Z.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:Z.chunk}}]});return}let _=r(Z.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:Z.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?WH(Z.record):_}}]})}}),B={role:"user",content:W.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(W.record))}};if(this.messages.push(B),this.contextMessages.push(B),W.queue)this.sendFollowUpQueueSnapshot(W.queue);if(W.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return L.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(X)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(L.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(Y(),this.pendingUserShellCompletion===$)this.pendingUserShellCompletion=null;if(this.pendingUserShell===L){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let H=this.pendingResumeGeneration,L=()=>{if(H!==this.pendingResumeGeneration)return;this.startPendingResumeRun(H)};if(z>0)this.pendingResumeTimer=setTimeout(L,z),this.pendingResumeTimer.unref?.();else queueMicrotask(L)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let H=this.resumePendingIfIdle();this.pendingResumeCompletion=H,H.then(()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}},()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,H){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:H.kind,attempt:H.attempt,maxAttempts:Cz,...H.delayMs!==void 0?{delayMs:H.delayMs,nextRetryAt:Date.now()+H.delayMs}:{},...H.taskFailure?{failure:{code:H.taskFailure.code,retryable:H.taskFailure.retryable,...H.taskFailure.resource?{resource:H.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,H=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=H,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let L="preflight",Y=!1,$,X=null;try{let Q=this.runtime.getPendingSteeringCount()>0,W=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=W?.status==="active"||W?.status==="verifying",Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none"&&(Z.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(Z.state==="requires_attention"){this.clearPendingResumeRequest();return}L=Q?"pending_input":"goal",Y=!0;let _=fz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(_<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}let U=new AbortController;X=setTimeout(()=>{U.abort("acp-pending-resume-budget-exhausted")},_),X.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:L==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:U.signal});if(z!==this.pendingResumeGeneration)return;if(U.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(H>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:H,kind:L})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let W=Y?_H(Q):{taskFailure:v(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=L==="preflight"||L==="pending_input"&&this.runtime.getPendingSteeringCount()>0,Z=uz({sessionIdentity:this.id,failedAttempt:H,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:W});if(Z.phase==="retry_scheduled")this.pendingResumeRequested=!0,$=Z.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:H+1,kind:L,taskFailure:W?.taskFailure,delayMs:Z.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${H} failed; retrying in ${Z.delayMs}ms`);else{let _=Z.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(_,{attempt:H,kind:L,taskFailure:W?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${H}, retryable=${Z.retryable}, phase=${_})`,Q),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest()}}finally{if(X!==null)clearTimeout(X);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=$??0}}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let L=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(L);await this.persistPermissionMode(Y),this.mode=L,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(G.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(L){if(H&&H!==z)await this.agent.switchModel(H).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw L}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid reasoning effort")}if(H.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(L){throw await this.runtime.refresh({reasoningEffort:H.selection}),L}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid service tier")}if(H.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(L){throw await this.runtime.refresh({serviceTier:H.selection}),L}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(L){throw Error(L instanceof Error?L.message:"Invalid response verbosity")}if(H.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(L){throw await this.runtime.refresh({responseVerbosity:H.selection}),L}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCommunicationStyleConfiguration(),L=this.runtime.resolveCommunicationStyleConfiguration(z);if(L.source!=="built-in"&&!L.contentSha256)throw Error("Custom communication style has no provenance");if(H.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:L.source==="built-in"?null:L.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...L.source!=="built-in"&&L.contentSha256?{communicationStyleDigest:L.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:H.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((H)=>structuredClone(H)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Sz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let H=this.agent,L=this.runtime,Y=this.pendingPromptCompletion,$=this.pendingUserShellCompletion,X=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let W,B=async(Z)=>{try{await Z()}catch(_){W??=_}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if($)await B(()=>$);if(X)await B(()=>X);if(Q)await B(()=>Q);if(z&&Y&&L)await B(()=>L.discardPendingInput());if(H)await B(()=>H.destroy());if(L)await B(()=>L.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,G.debug(`[AcpSession ${this.id}] Destroyed`),W!==void 0)throw W}resolvePrompt(z){let H=[],L=[],Y=0,$=0,X=0,Q=(Z)=>{if(L.length>0)L.push({type:"text",text:`
|
|
13
|
-
`}),X+=1;if(L.push(Z),Z.type==="text")X+=Z.text.length};for(let Z of z)if(Z.type==="text")H.push(Z.text),Q({type:"text",text:Z.text});else if(Z.type==="image"){let _=`data:${Z.mimeType};base64,${Z.data}`;Y+=1,$+=_.length,H.push(`[Image: ${Z.mimeType}]`),Q({type:"image_url",image_url:{url:_}})}else if(Z.type==="resource"){let _=Z.resource;if("text"in _){let U=`<file path="${_.uri}">
|
|
14
|
-
${_.text}
|
|
15
|
-
</file>`;H.push(U),Q({type:"text",text:U})}}else if(Z.type==="resource_link"){let _=`[Resource: ${Z.uri}]`;H.push(_),Q({type:"text",text:_})}if(Y>g)throw Error(`ACP prompt contains more than ${g} images`);if($>Xz)throw Error("ACP prompt images exceed the 5 MiB limit");if(X>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(H.join(`
|
|
16
|
-
`),"utf8")>p)throw Error(`ACP prompt text exceeds ${p} bytes`);let B=H.join(`
|
|
17
|
-
`);return{content:Y>0?L:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let H=this.updateEgress.offer({sessionId:this.id,update:z});if(!H.accepted)return!1;try{return await H.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount,...z.executionHostFailure?{executionHostFailure:{category:z.executionHostFailure.category,consecutiveCount:z.executionHostFailure.consecutiveCount}}:{},...z.turnLineage?{turnLineage:z.turnLineage}:{}}}}}sendFollowUpQueueSnapshot(z){let H=i.safeParse(z);if(!H.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/followUpQueue":UH(H.data)}})}sendProviderRecoveryProjection(z){let H=m.safeParse(z);if(!H.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRecovery":H.data}})}sendTurnActivityProjection(z){let H=a.safeParse(z);if(!H.success)return;if(H.data.generation===this.lastTurnActivityGeneration&&H.data.revision<=this.lastTurnActivityRevision)return;this.lastTurnActivityGeneration=H.data.generation,this.lastTurnActivityRevision=H.data.revision,this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnActivity":H.data}})}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;G.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let H=z.map((L)=>({content:L.subject,priority:L.priority,status:L.status}));G.debug(`[AcpSession ${this.id}] Sending plan update with ${H.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:H})}async requestPermission(z){let H=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,H);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,H);let L=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(L))return G.debug(`[AcpSession ${this.id}] Auto-approving ${L} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(L==="write"||L==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${L} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),$=[];if(z.message)$.push({type:"content",content:{type:"text",text:z.message}});if(z.details)$.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)$.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
-
- ${z.risks.join(`
|
|
19
|
-
- `)}`}});let X=this.mapToolKind(L),Q={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:z.title||"Permission Required",content:$,kind:X}},W=await this.waitForClientInteraction(this.connection.requestPermission(Q),H);if(!W)return{approved:!1,reason:d};let B=W.outcome;if(B.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let Z=B.optionId;if(Z==="allow_always")return{approved:!0,scope:"project"};if(Z==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let _=Z==="allow_once";return{approved:_,scope:"once",reason:_?void 0:"User denied the operation"}}catch(Y){return G.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,H){let L=z.questions??[];if(L.length===0)return{approved:!1,reason:"No structured questions were provided"};if(L.some(($)=>$.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[$,X]of L.entries()){let Q=X.options.map((_,U)=>`answer:${$}:${U}`),W=`answer:${$}:cancel`,B=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...X.options.map((_,U)=>({optionId:Q[U],name:_.label,kind:"allow_once"})),{optionId:W,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:X.header,kind:"think",content:[{type:"content",content:{type:"text",text:[X.question,...X.options.map((_)=>`${_.label}: ${_.description}`)].join(`
|
|
20
|
-
`)}}]}}),H);if(!B)return{approved:!1,reason:d};if(B.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let Z=Q.indexOf(B.outcome.optionId);if(Z<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[X.header]=X.options[Z].label}return{approved:!0,answers:Y}}catch($){return G.warn(`[AcpSession ${this.id}] Question request failed:`,$),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,H){let L=z.mcpElicitation;if(!L)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(L.mode==="url"){let $=await this.requestElicitationChoice("MCP external authorization",[L.message,`Server: ${L.serverName}`,`Domain: ${L.domain??"unknown"}`,`URL: ${L.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
21
|
-
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],H);if($==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:$==="decline"?"User declined URL":"User cancelled",elicitation:{action:$==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let $ of L.fields??[]){let X=await this.collectAcpElicitationField($,H);if(X.cancelled)return{approved:!1,reason:X.reason,elicitation:{action:"cancel"}};if(X.value!==void 0)Y[$.name]=X.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return G.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,H){if(z.type==="select"||z.type==="boolean"){let L=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((X,Q)=>({id:`option:${Q}`,label:X.label,value:X.value})),Y=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
-
`),[...L.map((X)=>({id:X.id,label:X.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],H);if(Y==="skip")return{cancelled:!1};let $=L.find((X)=>X.id===Y);if(!$)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:$.value}}if(z.defaultValue!==void 0){let L=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
23
|
-
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],H);if(L==="default")return{cancelled:!1,value:z.defaultValue};if(L==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,H,L,Y){let $=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...L.map((X)=>({optionId:X.id,name:X.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:H}}]}}),Y);return $?.outcome.outcome==="selected"?$.outcome.optionId:void 0}async waitForClientInteraction(z,H){if(!H)return z;if(H.aborted)return;return new Promise((L,Y)=>{let $=!1,X=(W)=>{if($)return;$=!0,H.removeEventListener("abort",Q),W()},Q=()=>X(()=>L(void 0));if(H.addEventListener("abort",Q,{once:!0}),H.aborted)Q();z.then((W)=>X(()=>L(W)),(W)=>X(()=>Y(W)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var O=y("Agent"),VH="remote task isolation is not supported";function h(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function jH(z){return C.invalidParams({code:z.code,reason:z.reason})}function DH(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:VH})}function pz(){return C.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function mz(z){return z instanceof Error&&"code"in z&&z.code==="acp_remote_workspace_mismatch"&&"reason"in z&&z.reason==="exact-identity-mismatch"}function k(z){try{return zz(z)}catch(H){if(H instanceof dz)throw jH(H);throw H}}function n(z,H){let L=Hz(z);return Object.freeze({kind:"acp-remote",hostStateRoot:Jz(L.collisionIdentity),executionRoot:L.wirePath,hostResourceRoot:H,profile:z,descriptor:L})}function s(z,H){let L=vz(z.remoteWorkspace),Y=Jz(L.collisionIdentity);if(z.projectPath!==Y)throw Error("ACP remote workspace durable state is invalid");let $=zz(L.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:Y,executionRoot:L.wirePath,hostResourceRoot:H,profile:$,descriptor:L})}function FH(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class Lz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=o.resolve(t())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=oz();this.runtimeResidencyValue=new JH({maxResident:z?.maxResidentSessionRuntimes??az,idleMs:z?.sessionRuntimeIdleMs??rz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(H){if(H instanceof HH)throw C.internalError({resource:H.resource,limit:H.limit,retryable:H.retryable},H.message);throw H}}async initialize(z){return O.info("[BladeAgent] Initializing ACP connection"),O.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await nz(),{protocolVersion:GH,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let H=e("acp"),L=z.cwd||t(),Y=h(this.clientCapabilities),$=Y?k(L):void 0,X=z._meta?.["blade/taskIsolation"],Q=X==="local"||X==="worktree"?X:void 0;if(Y&&Q)throw DH();let W=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(H),Z;try{let _,U;if($){let T=n($,this.hostResourceRoot);_=await F.createRemoteSessionMetadata(H,T.hostStateRoot,T.descriptor,{}),U=s(_,this.hostResourceRoot)}else U=P(L);let V=!Y&&Q?await zH.createSessionTask({sessionId:H,prompt:typeof W==="string"&&W.trim()?W:"ACP task session",sourceProjectPath:L,isolation:Q}):void 0;if(V)U=P(V.metadata.projectPath);return O.info(`[BladeAgent] Creating new session: ${H}`),O.debug(`[BladeAgent] Session kind: ${U.kind}`),Z=new x(H,U,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...V?.taskWorktree?{taskWorktree:V.taskWorktree}:{},...V?.metadata.taskIsolation?{taskIsolation:V.metadata.taskIsolation}:{}}),await Z.initialize(),this.assertNotDestroyed(),this.commitSession(H,Z,B),O.info(`[BladeAgent] Session ${H} created, scheduling available commands update`),Z.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H,V?.metadata,Z.getModelConfiguration())}catch(_){throw B.cancel(),await Z?.destroy().catch(()=>{return}),_}}async listSessions(z){let H=h(this.clientCapabilities);if(!H&&z.cwd!=null&&!o.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let L=H?await F.listRemoteSessionPage({...z.cwd!=null?{descriptor:Hz(k(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await F.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:L.sessions.map((Y)=>({sessionId:Y.sessionId,cwd:H?FH(Y):Y.projectPath,title:Y.title??null,updatedAt:Y.lastMessageTime,_meta:{"blade/taskStatus":Y.taskStatus,...Y.taskStatusReason?{"blade/taskStatusReason":Y.taskStatusReason}:{},...Y.taskFailure?{"blade/taskFailure":Y.taskFailure}:{},...Y.taskStartedAt?{"blade/taskStartedAt":Y.taskStartedAt}:{},...Y.taskCompletedAt?{"blade/taskCompletedAt":Y.taskCompletedAt}:{},...Y.taskModelId?{"blade/taskModelId":Y.taskModelId}:{},...Y.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Y.taskRetriedFrom?{"blade/taskRetriedFrom":Y.taskRetriedFrom}:{},...Y.taskDelivery?{"blade/taskDelivery":Y.taskDelivery}:{},...Y.taskIsolation?{"blade/taskIsolation":Y.taskIsolation}:{},...Y.taskSourceProjectPath?{"blade/taskSourceProjectPath":Y.taskSourceProjectPath}:{},...Y.taskWorktreeBranch?{"blade/taskWorktreeBranch":Y.taskWorktreeBranch}:{},...Y.taskBaseCommit?{"blade/taskBaseCommit":Y.taskBaseCommit}:{},...Y.taskDiffStat?{"blade/taskDiffStat":Y.taskDiffStat}:{},...Y.taskQueuePosition?{"blade/taskQueuePosition":Y.taskQueuePosition}:{},...Y.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Y.taskQueueDepth}:{},...Y.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Y.taskConcurrencyLimit}:{}}})),nextCursor:L.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let H=h(this.clientCapabilities),L=H?n(k(z.cwd),this.hostResourceRoot):void 0;if(!H&&!o.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Y=e("fork"),$=await this.reserveSessionRuntime(Y),X;try{let Q;try{Q=await F.forkSession(z.sessionId,{sourceProjectPath:L?.hostStateRoot??z.cwd,targetProjectPath:L?.hostStateRoot??z.cwd,newSessionId:Y,...L?{remote:{expectedDescriptor:L.descriptor}}:{}})}catch(B){if(mz(B))throw pz();throw B}this.assertNotDestroyed();let W=H?s(Q.metadata,this.hostResourceRoot):P(Q.projectPath??z.cwd);return X=new x(Q.sessionId,W,this.connection,this.clientCapabilities,{initialMessages:Q.messages,permissionMode:Q.metadata.permissionMode,mcpServers:z.mcpServers}),await X.initialize(),this.assertNotDestroyed(),this.commitSession(Q.sessionId,X,$),X.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Q.sessionId,H?void 0:Q.metadata,X.getModelConfiguration())}catch(Q){throw $.cancel(),await X?.destroy().catch(()=>{return}),Q}}async loadSession(z){this.assertNotDestroyed(),O.info(`[BladeAgent] Loading session: ${z.sessionId}`);let L=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=L.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await L}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!h(this.clientCapabilities)){await F.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let W=await this.reserveSessionRuntime(z.sessionId),B;try{let[Z,_]=await Promise.all([F.loadSession(z.sessionId,z.cwd),F.findSessionMetadata(z.sessionId,z.cwd)]);if(!_)throw Error(`Session not found: ${z.sessionId}`);return B=new x(z.sessionId,P(z.cwd),this.connection,this.clientCapabilities,{initialMessages:Z,permissionMode:_.permissionMode,mcpServers:z.mcpServers}),await B.initialize(),await B.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,B,W),B.sendAvailableCommandsDelayed(),this.buildSessionSetup(B.getModelConfiguration(),B.getMode())}catch(Z){throw W.cancel(),await B?.destroy().catch(()=>{return}),Z}}let L=n(k(z.cwd),this.hostResourceRoot),Y;try{Y=await F.assertRemoteSessionWritable(z.sessionId,L.hostStateRoot,L.descriptor)}catch(W){if(mz(W))throw pz();throw W}let $=s(Y,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let X=await this.reserveSessionRuntime(z.sessionId),Q;try{let W=await F.loadRemoteSession(z.sessionId,$.hostStateRoot,$.descriptor);return Q=new x(z.sessionId,$,this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,Q,X),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup(Q.getModelConfiguration(),Q.getMode())}catch(W){throw X.cancel(),await Q?.destroy().catch(()=>{return}),W}}commitSession(z,H,L){let Y=L.commit({key:z,surface:"acp",value:H,canEvict:()=>H.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===H)this.sessions.delete(z);await H.destroy()}});this.sessions.set(z,H),Y.release()}async closeResidentSession(z,H={}){let L=this.sessions.get(z);if(!L)return;let Y=this.runtimeResidency.owns(z,L),$;try{await L.destroy(H)}catch(Q){$=Q}let X=await this.runtimeResidency.forget(z,L);if(this.sessions.get(z)===L)this.sessions.delete(z);if(Y&&!X&&$===void 0)throw Error(`ACP Session is still active: ${z}`);if($!==void 0)throw $}buildChildSessionResponse(z,H,L){return{sessionId:z,...this.buildSessionSetup(L,H?.permissionMode==="autoEdit"?"auto-edit":H?.permissionMode),...H?{_meta:{"blade/taskIsolation":H.taskIsolation,"blade/taskSourceProjectPath":H.taskSourceProjectPath,"blade/taskProjectPath":H.projectPath,...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,H="default"){let L=z?.models??[],Y=(z?.currentModelId&&L.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??L[0]?.id,$=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],X=[];if(L.length>0)X.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:L.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)X.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="off"?"Disable model reasoning":`Use ${Q} reasoning effort`}))]});if(z?.serviceTier)X.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="fast"?"Use the provider priority tier":Q==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)X.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:`Use ${Q} response verbosity`}))]});if(z?.communicationStyle)X.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Q)=>({value:Q.id,name:Q.name,description:`${Q.description} · ${Q.source}`}))});return{modes:{availableModes:$,currentModeId:H},configOptions:X.length>0?X:void 0}}async closeSession(z){this.assertNotDestroyed();let L=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=L.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await L}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let H=this.runtimeResidency.acquire(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);try{return await H.value.prompt(z)}finally{H.release()}}async cancel(z){O.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let H=this.runtimeResidency.acquire(z.sessionId);if(H){O.info("[BladeAgent] Found session, calling session.cancel()");try{H.value.cancel()}finally{H.release()}}else O.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){O.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let H=this.runtimeResidency.acquire(z.sessionId);if(H)try{await H.value.setMode(z.modeId)}finally{H.release()}return{}}async setSessionConfigOption(z){let H=this.runtimeResidency.acquire(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);try{let L=H.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")O.info(`[BladeAgent] Setting session model: ${z.value}`),await L.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&sz(z.value))O.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await L.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&iz(z.value))O.info(`[BladeAgent] Setting service tier: ${z.value}`),await L.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&lz(z.value))O.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await L.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&tz(z.value))O.info(`[BladeAgent] Setting communication style: ${z.value}`),await L.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(L.getModelConfiguration(),L.getMode()).configOptions??[]}}finally{H.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let H of[...this.sessions.keys()])try{await this.closeResidentSession(H)}catch(L){z??=L}try{await this.runtimeResidency.disposeAll()}catch(H){z??=H}this.sessions.clear();try{await ez.getInstance().disconnectAll()}catch(H){z??=H}if(z!==void 0)throw z}}async function NJ(){let z=wH.toWeb(process.stdout),H=KH.toWeb(process.stdin),L=f.ndJsonStream(z,H),Y,$=new f.AgentSideConnection((Q)=>{return Y=new Lz(Q),Y},L),X=LH(async()=>{await Y?.destroy()});try{await $.closed}finally{X(),await Y?.destroy()}}export{NJ as runAcpIntegration,P as createLocalAcpSessionRoots};
|
package/dist/chunk-ky592ay9.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{promises as B}from"node:fs";import q from"node:path";import{LRUCache as H}from"lru-cache";var K=512,Z=new H({max:K});async function L(x){let b=x;while(!0){try{return await B.lstat(q.join(b,".git")),b}catch(V){if(V.code!=="ENOENT")return}let F=q.dirname(b);if(F===b)return;b=F}}async function M(x){let b=q.join(x,".git"),F=await B.lstat(b);if(F.isDirectory())return x;if(!F.isFile())return;let V=await B.readFile(b,"utf8"),J=/^gitdir:\s*(.+)\s*$/im.exec(V);if(!J)return;let Q=await B.realpath(q.isAbsolute(J[1])?J[1]:q.resolve(x,J[1])),Y=Q;try{let z=(await B.readFile(q.join(Q,"commondir"),"utf8")).trim();if(z)Y=await B.realpath(q.resolve(Q,z))}catch(z){if(z.code!=="ENOENT")throw z}return q.basename(Y)===".git"?B.realpath(q.dirname(Y)):void 0}async function N(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x),F=Z.get(b);if(F)return F;let V=b;try{let Q=await L(b);if(Q){let Y=await M(Q),z=q.relative(Q,b);if(Y&&(z===""||!z.startsWith(`..${q.sep}`)&&z!==".."&&!q.isAbsolute(z))){let $=q.resolve(Y,z);V=await B.realpath($).catch(()=>$)}}}catch{}let J={projectPath:b,trustRoot:V};return Z.set(b,J),J}async function S(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x);Z.delete(b)}
|
|
2
|
-
export{N as ek,S as fk};
|
package/dist/chunk-m0t26vkj.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{Aa as F,Ca as L}from"./chunk-rwm71p4g.js";import{_d as $,ae as B,ie as Q}from"./chunk-4ts2s9mz.js";import{Yg as y}from"./chunk-egc2f1ye.js";import{cj as V}from"./chunk-qdbbke8f.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
|
|
2
|
-
|
|
3
|
-
${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
|
-
export{j as p,I as q,M as r,R as s,_ as t,C as u};
|
package/dist/chunk-myvt7yjm.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{sg as m_}from"./chunk-4fbpydtn.js";import{gj as D0,hj as t_,ij as a_,jj as B0,kj as L_,mj as b_,oj as X_,qj as d,rj as q_,tj as J_,uj as v_,wj as c}from"./chunk-wezr6wfq.js";import{Ej as a}from"./chunk-rmfzym94.js";import{Oj as XE,Qj as G_}from"./chunk-j89qk7bp.js";import{Tj as nE}from"./chunk-0eajnhrj.js";var $0={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},SE=(_)=>$0[_]||{};var I0=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function j_(_){return typeof _==="string"&&I0.has(_)}function CT(_){if(!_.aborted)return;if(j_(_.reason))return _.reason;return"user-cancel"}function vT(_){if(j_(_))return!0;if(!(_ instanceof Error))return!1;if(_.name==="AbortError")return!0;if(_ instanceof DOMException&&_.name==="AbortError")return!0;if(_.message.includes("aborted"))return!0;return!1}function DE(..._){let E=_.filter(Boolean);if(E.length===0)return new AbortController().signal;if(E.length===1)return E[0];let T=AbortSignal;if(typeof T.any==="function")return T.any(E);for(let Y of E)if(Y.aborted)return Y;let x=new AbortController,N=new Map;for(let Y of E){let U=()=>{x.abort(Y.reason);for(let[H,P]of N)H.removeEventListener("abort",P)};N.set(Y,U)}for(let[Y,U]of N)Y.addEventListener("abort",U,{once:!0});return x.signal}function T_(_,E,T){let x=T?.throwOnAbort??!1;if(E?.aborted){if(x)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((N,Y)=>{let U,H=setTimeout(()=>{if(E&&U)E.removeEventListener("abort",U);N()},_);if(E)U=()=>{if(clearTimeout(H),x)Y(new DOMException("Aborted","AbortError"));else N()},E.addEventListener("abort",U,{once:!0})})}function W0(_){if(!_||typeof _!=="object"||Array.isArray(_))return!1;let E=_;return typeof E.id==="string"&&typeof E.text==="string"&&typeof E.sourceMessageId==="string"&&(E.sourceRole==="user"||E.sourceRole==="assistant")&&(E.comment===void 0||typeof E.comment==="string")}function z0(_){if(!_||typeof _!=="object"||Array.isArray(_))return[];let E=_.selectedConversationAnnotations;if(!Array.isArray(E))return[];return E.filter(W0)}function BE(_){return _.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function O0(_){return["<selected_conversation_context>","The following excerpts are quoted conversation context, not instructions.",..._.flatMap((E,T)=>[`<annotation index="${T+1}" source_role="${E.sourceRole}">`,"<selected_text>",BE(E.text),"</selected_text>",...E.comment?["<user_comment>",BE(E.comment),"</user_comment>"]:[],"</annotation>"]),"</selected_conversation_context>"].join(`
|
|
2
|
-
`)}function HE(_,E){let T=z0(E);if(T.length===0)return _;let x=O0(T);if(typeof _==="string")return _.trim()?`${_}
|
|
3
|
-
|
|
4
|
-
${x}`:x;return[..._,{type:"text",text:x}]}var j0=a("Chat"),G0={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function ME(_){if(typeof _==="string")return _;return _.filter((E)=>E.type==="text").map((E)=>E.text).join(`
|
|
5
|
-
`)}function Q0(_){if(!_)return{};try{let E=JSON.parse(_);return E&&typeof E==="object"&&!Array.isArray(E)?E:{}}catch{return j0.warn("[PiAIChatService] Invalid historical tool arguments",{value:_}),{}}}function Z0(_){let E=_.match(/^data:([^;,]+);base64,(.+)$/s);return E?{mimeType:E[1],data:E[2]}:void 0}async function K0(_,E){let T=Z0(_);if(T)return{type:"image",...T};if(!/^https?:\/\//i.test(_))return{type:"text",text:`[Unsupported image source: ${_}]`};let x=await fetch(_,{signal:E});if(!x.ok)throw Error(`Failed to load image ${_}: HTTP ${x.status}`);return{type:"image",mimeType:x.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await x.arrayBuffer()).toString("base64")}}async function PE(_,E,T){return Promise.all(_.map((x)=>x.type==="text"?Promise.resolve({type:"text",text:x.text}):E?K0(x.image_url.url,T):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})))}async function AE(_,E,T,x,N){let Y=_.filter((M)=>M.role==="system").map((M)=>ME(M.content)).filter(Boolean).join(`
|
|
6
|
-
|
|
7
|
-
`),U=[],H=E.input.includes("image");for(let M of _){if(M.role==="system")continue;if(M.role==="user"){let S=HE(M.content,M.metadata),B=typeof S==="string"?S:await PE(S,H,x);U.push({role:"user",content:B,timestamp:Date.now()});continue}if(M.role==="assistant"){let S=[];if(M.reasoningContent?.trim())S.push({type:"thinking",thinking:M.reasoningContent});let B=ME(M.content);if(B)S.push({type:"text",text:B});for(let h of M.tool_calls??[]){if(!("function"in h))continue;S.push({type:"toolCall",id:h.id,name:h.function.name,arguments:Q0(h.function.arguments)})}U.push({role:"assistant",content:S,api:E.api,provider:E.provider,model:E.id,usage:G0,stopReason:M.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}U.push({role:"toolResult",toolCallId:M.tool_call_id??"",toolName:M.name??"unknown",content:typeof M.content==="string"?[{type:"text",text:M.content}]:await PE(M.content,H,x),isError:!1,timestamp:Date.now()})}let P=T?.filter((M)=>!N||M.name===N).map((M)=>({name:M.name,description:M.description,parameters:M.parameters,constrainedSampling:M.constrainedSampling})).sort((M,S)=>M.name<S.name?-1:M.name>S.name?1:0);return{...Y?{systemPrompt:Y}:{},messages:U,...P?.length?{tools:P}:{}}}function hE(_){let E=[];for(let T=0;T<_.length;T++){let x=_[T];if(x.role==="tool")continue;let N=x.role==="assistant"&&x.tool_calls?.length?x.tool_calls:void 0;if(!N){E.push(x);continue}let Y=[],U=T+1;while(U<_.length&&_[U].role==="tool")Y.push(_[U++]);let H=new Set(N.map((S)=>S.id)),P=Y.filter((S)=>S.tool_call_id&&H.has(S.tool_call_id)),M=new Set(P.map((S)=>S.tool_call_id));if(H.size===N.length&&P.length===H.size&&M.size===H.size)E.push(x,...P);T=U-1}return E}function RE(_){return _.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function JE(_,E){return{..._,...E.baseUrl?{baseUrl:XE(_.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function Q_(_){let E=_.modelCatalog??G_();return{models:E.models,model:JE(E.getModel(_.provider,_.model),_)}}function VE(_,E){let T=_.modelCatalog??G_();return JE(T.getModel(E.provider,E.model),_)}import{createHash as L0}from"node:crypto";var b0=32,F0=1000,k0=512,C0=2000,w0=0.1,q0=0.05,v0=0.9,u0=300000,c0=3600000;class Z_{sessions=new Map;observe(_){if(_.retention==="none"){this.sessions.delete(_.sessionId);return}let E=_.now??Date.now(),T=y0(_,E),x=this.sessions.get(_.sessionId);if(T.callCount=(x?.callCount??0)+1,this.touch(_.sessionId,T),x&&T.contextEpoch!==x.contextEpoch)return;if(!x||x.cacheReadTokens<F0)return;let N=x.cacheReadTokens-T.cacheReadTokens,Y=Math.min(C0,Math.max(k0,x.cacheReadTokens*w0));if(N<Y||T.cacheReadTokens>=x.cacheReadTokens*(1-q0))return;let U=T.modelIdentity!==x.modelIdentity,H=T.systemHash!==x.systemHash,P=T.toolsHash!==x.toolsHash,M=T.policyHash!==x.policyHash;if(!(U||H||P||M)&&T.promptTokens<x.promptTokens*v0)return;let B=Math.max(0,E-x.recordedAt),h=x.retention==="long"?c0:u0,V=U?"model_changed":H?"system_prompt_changed":P?"tools_changed":M?"request_policy_changed":B>=h?"ttl_expired":"server_side",K=m0(x,T);return{reason:V,previousCacheReadTokens:x.cacheReadTokens,cacheReadTokens:T.cacheReadTokens,cacheWriteTokens:Math.max(0,_.usage.cacheCreationInputTokens??0),tokenDrop:N,elapsedMs:B,callNumber:T.callCount,systemPromptChanged:H,systemCharDelta:T.systemChars-x.systemChars,toolsChanged:P,addedToolCount:K.added,removedToolCount:K.removed,changedToolCount:K.changed,modelChanged:U,requestPolicyChanged:M}}clear(_){if(_)this.sessions.delete(_);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(_,E){this.sessions.delete(_),this.sessions.set(_,E);while(this.sessions.size>b0){let T=this.sessions.keys().next().value;if(T===void 0)break;this.sessions.delete(T)}}}function y0(_,E){let T=[..._.tools??_.context.tools??[]].map((x)=>({identityHash:x_(x.name),contractHash:x_(N_(x))})).sort((x,N)=>x.identityHash<N.identityHash?-1:x.identityHash>N.identityHash?1:0);return{modelIdentity:_.modelIdentity,systemHash:x_(_.context.systemPrompt??""),systemChars:_.context.systemPrompt?.length??0,toolsHash:x_(N_(T)),toolFingerprints:T,policyHash:x_(N_(_.policy)),contextEpoch:_.contextEpoch??"",retention:_.retention,promptTokens:Number.isFinite(_.usage.promptTokens)?Math.max(0,_.usage.promptTokens):0,cacheReadTokens:Math.max(0,_.usage.cacheReadInputTokens??0),recordedAt:E,callCount:1}}function m0(_,E){let T=new Map(_.toolFingerprints.map((N)=>[N.identityHash,N.contractHash])),x=new Map(E.toolFingerprints.map((N)=>[N.identityHash,N.contractHash]));return{added:[...x.keys()].filter((N)=>!T.has(N)).length,removed:[...T.keys()].filter((N)=>!x.has(N)).length,changed:[...x].filter(([N,Y])=>T.has(N)&&T.get(N)!==Y).length}}function N_(_){if(_===null||typeof _!=="object")return JSON.stringify(_)??"undefined";if(Array.isArray(_))return`[${_.map(N_).join(",")}]`;let E=_;return`{${Object.keys(E).sort().map((T)=>`${JSON.stringify(T)}:${N_(E[T])}`).join(",")}}`}function x_(_){return L0("sha256").update(_).digest("hex")}import{randomBytes as d0}from"node:crypto";import{createHmac as g0}from"node:crypto";function p0(_){try{let E=new URL(_);if(E.hash="",E.hostname=E.hostname.toLowerCase(),E.searchParams.sort(),E.pathname!=="/")E.pathname=E.pathname.replace(/\/+$/,"");return E.toString()}catch{return _.trim().replace(/\/+$/,"")}}function l0(_){if(!_)return[];return Object.entries(_).map(([E,T])=>[E.trim().toLowerCase(),T.trim()]).sort(([E],[T])=>E.localeCompare(T))}function A_(_,E,T){let x=JSON.stringify([_.provider.trim(),String(_.api).trim(),p0(_.baseUrl),_.model.trim(),_.serviceTier?.trim()??"",_.apiVersion?.trim()??"",_.apiKey??"",l0(_.customHeaders),T]);return g0("sha256",Buffer.from(E)).update(x).digest("hex")}var s0=60000,t0=4,a0=0.8;var R_=300000,F_=600000;var fE=128,$E=256,r0=1800000,h_=50;class S_ extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(_){super(`Provider circuit open; retry after ${_.retryAfterMs??0}ms`);this.circuit=_;this.name="ProviderCircuitOpenError"}}function D_(_){return _ instanceof S_||_!==null&&typeof _==="object"&&"code"in _&&_.code==="PROVIDER_CIRCUIT_OPEN"}function r(_,E){return _!==void 0&&Number.isSafeInteger(_)&&_>0?_:E}function o0(_,E){return _!==void 0&&Number.isFinite(_)&&_>0&&_<=1?_:E}function i0(_,E){return A_(_,E,{providerCircuitOpenDurationMs:_.openDurationMs})}function Y_(_){let E=0;for(let T of _)if(T.failure)E++;return E}function IE(_){return _!==void 0&&Number.isInteger(_)&&_>=100&&_<=599?_:void 0}function K_(_){if(_===void 0||!Number.isFinite(_)||_<0)return;return Math.min(Math.ceil(_),b_)}class zE{#Y=new Map;#S=new WeakMap;#_;#T;#N;#x;constructor(_={}){this.#_=_.processSecret?new Uint8Array(_.processSecret):d0(32),this.#T=_.now??(()=>performance.now()),this.#N=_.wallNow??_.now??Date.now,this.#x={maxEntries:Math.min(r(_.maxEntries,fE),fE),maxWindowEntries:Math.min(r(_.maxWindowEntries,$E),$E),windowMs:r(_.windowMs,s0),minSamples:r(_.minSamples,t0),errorRateThreshold:o0(_.errorRateThreshold,a0),idleTtlMs:r(_.idleTtlMs,r0)}}get size(){return this.#Y.size}get(_){if(_.openDurationMs===0)return this.#B();let E=this.#T();this.#f(E);let T=i0(_,this.#_),x=this.#Y.get(T);if(x)return x.lastTouchedAt=E,this.#E(x,_.probeLeaseMs);if(this.#Y.size>=this.#x.maxEntries)this.#R();if(this.#Y.size>=this.#x.maxEntries)return this.#B();let N={key:T,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:_.openDurationMs,effectiveOpenDurationMs:_.openDurationMs,lastTouchedAt:E,detached:!1};return this.#Y.set(T,N),this.#E(N,_.probeLeaseMs)}#E(_,E){let T=this,x=Math.max(R_,Math.min(r(E,R_),F_));return{preflight:()=>T.#H(_),check:()=>T.#$(_,x),recordSuccess:(N)=>T.#D(N,"success"),recordFailure:(N,Y)=>T.#D(N,"failure",Y),recordNeutral:(N)=>T.#D(N,"neutral"),abandon:(N)=>T.#A(N),snapshot:()=>T.#O(_)}}#B(){let _=this;return{preflight:()=>({eligible:!0}),check:()=>{let E=Object.freeze({kind:"noop"});return _.#S.set(E,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:E}},recordSuccess:(E)=>_.#P(E),recordFailure:(E)=>_.#P(E),recordNeutral:(E)=>_.#P(E),abandon:(E)=>_.#A(E),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#P(_){let E=this.#S.get(_);if(E?.kind==="noop")E.settled=!0;return}#H(_){let E=this.#T();if(_.detached)return{eligible:!0};if(_.lastTouchedAt=E,this.#h(_,E),_.state==="closed")return{eligible:!0};if(_.state==="open"){let x=_.nextProbeAt??E;return E<x?this.#J(_,x-E):{eligible:!0}}if(_.probeLeaseId===void 0||_.probeLeaseExpiresAt!==void 0&&E>=_.probeLeaseExpiresAt)return{eligible:!0};let T=Math.max(1,(_.probeLeaseExpiresAt??E+h_)-E);return this.#J(_,Math.min(h_,T))}#J(_,E){let{allowed:T,...x}=this.#M(_,E);return{eligible:!1,...x}}#$(_,E){let T=this.#T();if(_.detached)return this.#B().check();if(_.lastTouchedAt=T,this.#h(_,T),_.state==="closed")return this.#V(_,"regular");if(_.state==="open"){let N=_.nextProbeAt??T;if(T<N)return this.#M(_,N-T);_.state="half_open",_.generation++,_.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0}if(_.probeLeaseId===void 0||_.probeLeaseExpiresAt!==void 0&&T>=_.probeLeaseExpiresAt)return this.#I(_,T,E);let x=Math.max(1,(_.probeLeaseExpiresAt??T+h_)-T);return this.#M(_,Math.min(h_,x))}#V(_,E,T){let x=Object.freeze({kind:E});return this.#S.set(x,{entry:_,generation:_.generation,attemptId:_.nextAttemptId++,kind:E,...T!==void 0?{probeLeaseId:T}:{},settled:!1}),{allowed:!0,probe:E==="probe",token:x}}#I(_,E,T){let x=_.nextProbeLeaseId++;_.probeLeaseId=x,_.probeLeaseExpiresAt=E+T,_.lastTouchedAt=E;let N=this.#V(_,"probe",x),Y=_.lastFailure??{reason:"server_error"};return{...N,reason:Y.reason,...Y.statusCode!==void 0?{statusCode:Y.statusCode}:{},openDurationMs:_.effectiveOpenDurationMs,sampleCount:_.samples.length,failureCount:Y_(_.samples)}}#M(_,E){let T=_.lastFailure??{reason:"server_error"};return{allowed:!1,state:_.state==="open"?"open":"half_open",reason:T.reason,...T.statusCode!==void 0?{statusCode:T.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(E)),nextProbeAt:this.#N()+Math.max(0,Math.ceil(E)),openDurationMs:_.effectiveOpenDurationMs,sampleCount:_.samples.length,failureCount:Y_(_.samples)}}#D(_,E,T){let x=this.#S.get(_);if(!x||x.settled)return;if(x.settled=!0,x.kind==="noop"||!x.entry)return;let N=x.entry;if(N.detached||x.generation!==N.generation||x.kind==="regular"&&N.state!=="closed"||x.kind==="probe"&&(N.state!=="half_open"||x.probeLeaseId!==N.probeLeaseId))return;let Y=this.#T();if(N.lastTouchedAt=Y,x.kind==="probe"){if(E==="failure"&&T)return this.#U(N,T,Y,"reopened");return this.#W(N)}if(E==="neutral")return;if(this.#z(N,E==="failure",Y),E!=="failure"||!T)return;let U=K_(T.retryAfterMs);if(T.reason==="rate_limit"&&T.statusCode===429&&U!==void 0&&U>0)return this.#U(N,{...T,retryAfterMs:U},Y,"opened");let H=Y_(N.samples),P=N.samples.length===0?0:H/N.samples.length;if(N.samples.length>=this.#x.minSamples&&P>=this.#x.errorRateThreshold)return this.#U(N,T,Y,"opened");return}#U(_,E,T,x){let N={reason:E.reason,...IE(E.statusCode)!==void 0?{statusCode:IE(E.statusCode)}:{},...K_(E.retryAfterMs)!==void 0?{retryAfterMs:K_(E.retryAfterMs)}:{}},Y=N.retryAfterMs??0,U=Math.max(_.configuredOpenDurationMs,Y);return _.state="open",_.generation++,_.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.effectiveOpenDurationMs=U,_.nextProbeAt=T+U,_.lastFailure=N,{phase:x,reason:N.reason,...N.statusCode!==void 0?{statusCode:N.statusCode}:{},retryAfterMs:U,nextProbeAt:this.#N()+U,openDurationMs:U,sampleCount:_.samples.length,failureCount:Y_(_.samples)}}#W(_){let E=_.lastFailure??{reason:"server_error"};return _.state="closed",_.generation++,_.samples=[],_.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.nextProbeAt=void 0,_.effectiveOpenDurationMs=_.configuredOpenDurationMs,{phase:"closed",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},openDurationMs:_.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#A(_){let E=this.#S.get(_);if(!E||E.settled)return!1;if(E.settled=!0,E.kind==="noop")return!0;let T=E.entry;if(!T||T.detached||E.kind!=="probe"||E.generation!==T.generation||E.probeLeaseId!==T.probeLeaseId)return!1;return T.probeLeaseId=void 0,T.probeLeaseExpiresAt=void 0,T.lastTouchedAt=this.#T(),!0}#z(_,E,T){if(this.#h(_,T),_.samples.length>=this.#x.maxWindowEntries)_.samples.shift();_.samples.push({at:T,failure:E})}#h(_,E){let T=E-this.#x.windowMs,x=0;while(x<_.samples.length&&_.samples[x].at<T)x++;if(x>0)_.samples.splice(0,x)}#O(_){if(!_.detached)this.#h(_,this.#T());return{state:_.state,sampleCount:_.samples.length,failureCount:Y_(_.samples),..._.nextProbeAt!==void 0?{nextProbeAt:_.nextProbeAt}:{},noop:!1,detached:_.detached}}#f(_){for(let[E,T]of this.#Y)if(T.state==="closed"&&_-T.lastTouchedAt>this.#x.idleTtlMs)this.#X(E,T)}#R(){let _;for(let E of this.#Y.values())if(E.state==="closed"&&(!_||E.lastTouchedAt<_.lastTouchedAt))_=E;if(_)this.#X(_.key,_)}#X(_,E){E.detached=!0,this.#Y.delete(_)}}var WE;function OE(){return WE??=new zE,WE}import{randomBytes as n0}from"node:crypto";var e0=16,jE=128,GE=32,_T=3,QE=16,ZE=96,KE=24,LE=12,bE=16,FE=4,kE=4,CE=67108864,wE=33554432,ET=12,TT=2,qE=2,vE=1,gE=15000,uE=30000;function k_(){return{foreground:0,background:0,internal:0}}function C_(){return{inFlight:k_(),queued:k_(),pendingBytes:k_()}}function J(_){return _.foreground+_.background+_.internal}function Z(_){return _.background+_.internal}function cE(_){return _.inFlight.foreground===0&&_.inFlight.background===0&&_.inFlight.internal===0&&_.queued.foreground===0&&_.queued.background===0&&_.queued.internal===0&&_.pendingBytes.foreground===0&&_.pendingBytes.background===0&&_.pendingBytes.internal===0}class B_ extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(_,E,T,x,N,Y,U,H){super(_==="queue_full"?`Provider request admission ${E} ${x} queue is full`:_==="wait_timeout"?`Provider request admission timed out waiting for ${E} capacity`:"Provider request admission scheduler is closed");this.reason=_;this.scope=E;this.requestClass=T;this.resource=x;this.inFlight=N;this.limit=Y;this.queued=U;this.maxWaitMs=H;this.name="ProviderAdmissionError",this.retryable=_!=="closed"}}function s(_){return _ instanceof B_||_!==null&&typeof _==="object"&&"code"in _&&_.code==="PROVIDER_ADMISSION_BUSY"}function G(_,E,T){if(_===void 0||!Number.isSafeInteger(_)||_<=0)return E;return Math.min(_,T)}function xT(_){let E=G(_.globalMaxInFlight,e0,Number.MAX_SAFE_INTEGER),T=G(_.globalMaxPending,jE,jE),x=G(_.domainMaxPending,GE,GE),N=Math.min(G(_.ownerMaxInFlight,_T,Number.MAX_SAFE_INTEGER),E),Y=Math.min(G(_.ownerMaxPending,QE,QE),T),U=Math.min(G(_.nonForegroundGlobalMaxPending,Math.min(ZE,Math.max(1,Math.floor(T*3/4))),ZE),T),H=Math.min(G(_.nonForegroundDomainMaxPending,Math.min(KE,Math.max(1,Math.floor(x*3/4))),KE),x),P=Math.min(G(_.nonForegroundOwnerMaxPending,Math.min(LE,Math.max(1,Math.floor(Y*3/4))),LE),Y),M=Math.min(G(_.internalGlobalMaxPending,Math.min(bE,Math.max(1,Math.floor(T/8))),bE),U),S=Math.min(G(_.internalDomainMaxPending,Math.min(FE,Math.max(1,Math.floor(x/8))),FE),H),B=Math.min(G(_.internalOwnerMaxPending,Math.min(kE,Math.max(1,Math.floor(Y/4))),kE),P),h=G(_.globalMaxPendingBytes,c,c),V=Math.min(G(_.domainMaxPendingBytes,CE,CE),h),K=Math.min(G(_.ownerMaxPendingBytes,wE,wE),h),C=Math.min(G(_.nonForegroundGlobalMaxInFlight,Math.min(ET,E),E),E),w=Math.min(G(_.nonForegroundOwnerMaxInFlight,Math.min(TT,N),N),N),v=Math.min(G(_.internalGlobalMaxInFlight,Math.min(qE,E),qE),E),f_=G(_.internalDomainMaxInFlight,vE,vE),H_=G(_.agingMs,uE,uE);return{globalMaxInFlight:E,globalMaxPending:T,domainMaxPending:x,ownerMaxInFlight:N,ownerMaxPending:Y,nonForegroundGlobalMaxPending:U,nonForegroundDomainMaxPending:H,nonForegroundOwnerMaxPending:P,internalGlobalMaxPending:M,internalDomainMaxPending:S,internalOwnerMaxPending:B,globalMaxPendingBytes:h,domainMaxPendingBytes:V,ownerMaxPendingBytes:K,nonForegroundGlobalMaxInFlight:C,nonForegroundOwnerMaxInFlight:w,internalGlobalMaxInFlight:v,internalDomainMaxInFlight:f_,agingMs:H_,classLimitsEnabled:_.classLimitsEnabled!==!1}}function yE(_,E){if(!_.trim())throw Error(`${E} must not be blank`)}function NT(_){if(yE(_.sessionId,"sessionId"),yE(_.ownerId,"ownerId"),!Number.isSafeInteger(_.scope.maxConcurrent)||_.scope.maxConcurrent<X_||_.scope.maxConcurrent>d)throw Error(`maxConcurrent must be between ${X_} and ${d}`);if(!Number.isSafeInteger(_.scope.maxPendingBytes)||_.scope.maxPendingBytes<=0||_.scope.maxPendingBytes>c)throw Error(`maxPendingBytes must be between 1 and ${c}`);if(!Number.isSafeInteger(_.pendingBytes)||_.pendingBytes<=0||_.pendingBytes>c+1)throw Error(`pendingBytes must be between 1 and ${c+1}`);if(!Number.isSafeInteger(_.maxWaitMs)||_.maxWaitMs<0||_.maxWaitMs>J_)throw Error(`maxWaitMs must be 0-${J_}`)}function w_(_,E){if(E!==void 0)return E;if(_?.reason!==void 0)return _.reason;return new DOMException("Provider request admission cancelled","AbortError")}function YT(_,E){return A_(_,E,{providerRequestConcurrency:_.maxConcurrent,providerRequestPendingBytes:_.maxPendingBytes})}class pE{#Y;#S;#_;#T=[];#N=new Map;#x=new Map;#E=C_();#B=1;#P=0;#H=!1;constructor(_={}){this.#Y=_.processSecret?new Uint8Array(_.processSecret):n0(32),this.#S=_.now??(()=>performance.now()),this.#_=xT(_)}admit(_){if(NT(_),this.#H)throw this.#j("closed",_,{scope:"global",resource:"stream",inFlight:J(this.#E.inFlight),limit:this.#_.globalMaxInFlight},this.#T.length);if(_.signal?.aborted)throw w_(_.signal);let E=YT(_.scope,this.#Y),T=this.#N.get(E),x=this.#x.get(_.ownerId),N=T??this.#V(_.scope.maxConcurrent),Y=x??this.#I();if(this.#T.length===0&&this.#M(N,Y,_.requestClass)){if(!T)this.#N.set(E,N);if(!x)this.#x.set(_.ownerId,Y),this.#B++;let h=this.#U(E,_.ownerId,_.requestClass),V=this.#L(_,0);return{ready:Promise.resolve(h),getSnapshot:()=>({...V}),cancel:()=>{V={...V}}}}let U=this.#J(_,N,Y);if(U)throw this.#j("queue_full",_,U,this.#T.length);let H=this.#D(N,Y,_.requestClass);if(_.maxWaitMs===0)throw this.#j("wait_timeout",_,H,this.#T.length);if(!T)this.#N.set(E,N);if(!x)this.#x.set(_.ownerId,Y),this.#B++;let P,M,S=new Promise((h,V)=>{P=h,M=V});S.catch(()=>{return});let B={domainKey:E,sessionId:_.sessionId,ownerId:_.ownerId,requestClass:_.requestClass,maxWaitMs:_.maxWaitMs,pendingBytes:_.pendingBytes,enqueuedAt:this.#S(),signal:_.signal,resolve:P,reject:M,settled:!1,admitted:!1};if(_.signal)B.abortListener=()=>this.#f(B,w_(_.signal)),_.signal.addEventListener("abort",B.abortListener,{once:!0});return B.timer=setTimeout(()=>this.#O(B),_.maxWaitMs),B.timer.unref?.(),this.#T.push(B),this.#$(N,Y,B),this.#A(),{ready:S,getSnapshot:()=>this.#K(B),cancel:(h)=>this.#f(B,w_(_.signal,h))}}close(){if(this.#H)return;this.#H=!0;for(let _ of[...this.#T]){let E=this.#N.get(_.domainKey),T=this.#x.get(_.ownerId),x=E&&T?this.#D(E,T,_.requestClass):{scope:"global",resource:"stream",inFlight:J(this.#E.inFlight),limit:this.#_.globalMaxInFlight};this.#R(_,new B_("closed",x.scope,_.requestClass,x.resource,x.inFlight,x.limit,this.#T.length,_.maxWaitMs))}}getStats(){return{inFlight:J(this.#E.inFlight),queued:this.#T.length,pendingBytes:J(this.#E.pendingBytes),nonForegroundInFlight:Z(this.#E.inFlight),internalInFlight:this.#E.inFlight.internal,nonForegroundQueued:Z(this.#E.queued),internalQueued:this.#E.queued.internal,nonForegroundPendingBytes:Z(this.#E.pendingBytes),internalPendingBytes:this.#E.pendingBytes.internal,domainCount:this.#N.size,ownerCount:this.#x.size,closed:this.#H}}#J(_,E,T){let x=(S,B,h)=>B>=h?{scope:S,resource:"pending_count",inFlight:B,limit:h}:void 0;if(this.#_.classLimitsEnabled&&_.requestClass==="internal"){let S=x("class",this.#E.queued.internal,this.#_.internalGlobalMaxPending)??x("class",T.counters.queued.internal,this.#_.internalOwnerMaxPending)??x("class",E.counters.queued.internal,this.#_.internalDomainMaxPending);if(S)return S}if(this.#_.classLimitsEnabled&&_.requestClass!=="foreground"){let S=x("class",Z(this.#E.queued),this.#_.nonForegroundGlobalMaxPending)??x("class",Z(T.counters.queued),this.#_.nonForegroundOwnerMaxPending)??x("class",Z(E.counters.queued),this.#_.nonForegroundDomainMaxPending);if(S)return S}let N=x("global",this.#T.length,this.#_.globalMaxPending)??x("owner",J(T.counters.queued),this.#_.ownerMaxPending)??x("domain",J(E.counters.queued),this.#_.domainMaxPending);if(N)return N;let Y=Math.min(_.scope.maxPendingBytes,this.#_.globalMaxPendingBytes),U=Math.min(Y,this.#_.domainMaxPendingBytes),H=Math.min(Y,this.#_.ownerMaxPendingBytes),P=(S,B)=>_.pendingBytes>B-S,M=(S)=>{if(S==="owner")return{scope:S,resource:"pending_bytes",inFlight:J(T.counters.inFlight),limit:this.#_.ownerMaxInFlight};if(S==="domain")return{scope:S,resource:"pending_bytes",inFlight:J(E.counters.inFlight),limit:E.maxConcurrent};return{scope:S,resource:"pending_bytes",inFlight:J(this.#E.inFlight),limit:this.#_.globalMaxInFlight}};if(_.requestClass==="internal"){let S=Math.max(1,Math.floor(Y/8)),B=Math.max(1,Math.floor(U/4)),h=Math.max(1,Math.floor(H/4));if(P(this.#E.pendingBytes.internal,S)||P(T.counters.pendingBytes.internal,h)||P(E.counters.pendingBytes.internal,B))return M("class")}if(_.requestClass!=="foreground"){let S=Math.max(1,Math.floor(Y*3/4)),B=Math.max(1,Math.floor(U*3/4)),h=Math.max(1,Math.floor(H/2));if(P(Z(this.#E.pendingBytes),S)||P(Z(T.counters.pendingBytes),h)||P(Z(E.counters.pendingBytes),B))return M("class")}if(P(J(this.#E.pendingBytes),Y))return M("global");if(P(J(T.counters.pendingBytes),H))return M("owner");if(P(J(E.counters.pendingBytes),U))return M("domain");return}#$(_,E,T){let{requestClass:x,pendingBytes:N}=T;this.#E.queued[x]++,_.counters.queued[x]++,E.counters.queued[x]++,this.#E.pendingBytes[x]+=N,_.counters.pendingBytes[x]+=N,E.counters.pendingBytes[x]+=N}#V(_){return{maxConcurrent:_,counters:C_()}}#I(){return{order:this.#B,counters:C_()}}#M(_,E,T){if(J(this.#E.inFlight)>=this.#_.globalMaxInFlight)return!1;if(J(_.counters.inFlight)>=_.maxConcurrent)return!1;if(J(E.counters.inFlight)>=this.#_.ownerMaxInFlight)return!1;if(T==="foreground"||!this.#_.classLimitsEnabled)return!0;if(Z(this.#E.inFlight)>=this.#_.nonForegroundGlobalMaxInFlight)return!1;if(Z(E.counters.inFlight)>=this.#_.nonForegroundOwnerMaxInFlight)return!1;let x=Math.max(1,_.maxConcurrent-1);if(Z(_.counters.inFlight)>=x)return!1;if(T!=="internal")return!0;return this.#E.inFlight.internal<this.#_.internalGlobalMaxInFlight&&_.counters.inFlight.internal<this.#_.internalDomainMaxInFlight}#D(_,E,T){if(J(E.counters.inFlight)>=this.#_.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:J(E.counters.inFlight),limit:this.#_.ownerMaxInFlight};if(this.#_.classLimitsEnabled&&T!=="foreground"&&Z(E.counters.inFlight)>=this.#_.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:Z(E.counters.inFlight),limit:this.#_.nonForegroundOwnerMaxInFlight};if(J(_.counters.inFlight)>=_.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:J(_.counters.inFlight),limit:_.maxConcurrent};if(this.#_.classLimitsEnabled&&T!=="foreground"){let x=Math.max(1,_.maxConcurrent-1);if(Z(_.counters.inFlight)>=x)return{scope:"class",resource:"stream",inFlight:Z(_.counters.inFlight),limit:x}}if(this.#_.classLimitsEnabled&&T==="internal"&&_.counters.inFlight.internal>=this.#_.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:_.counters.inFlight.internal,limit:this.#_.internalDomainMaxInFlight};if(J(this.#E.inFlight)>=this.#_.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:J(this.#E.inFlight),limit:this.#_.globalMaxInFlight};if(this.#_.classLimitsEnabled&&T!=="foreground"&&Z(this.#E.inFlight)>=this.#_.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:Z(this.#E.inFlight),limit:this.#_.nonForegroundGlobalMaxInFlight};if(this.#_.classLimitsEnabled&&T==="internal"&&this.#E.inFlight.internal>=this.#_.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#E.inFlight.internal,limit:this.#_.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:J(_.counters.inFlight),limit:_.maxConcurrent}}#U(_,E,T){let x=this.#N.get(_),N=this.#x.get(E);if(!x||!N)throw Error("Provider admission accounting state is unavailable");this.#E.inFlight[T]++,x.counters.inFlight[T]++,N.counters.inFlight[T]++;let Y=!1;return{release:()=>{if(Y)return;Y=!0,this.#W(_,E,T)}}}#W(_,E,T){let x=this.#N.get(_),N=this.#x.get(E);if(this.#E.inFlight[T]--,x)x.counters.inFlight[T]--;if(N)N.counters.inFlight[T]--;this.#G(_,E),this.#A()}#A(){if(this.#H)return;while(this.#T.length>0){let _=this.#S(),E=new Map;for(let[H,P]of this.#T.entries()){let M=this.#N.get(P.domainKey),S=this.#x.get(P.ownerId);if(M===void 0||S===void 0||!this.#M(M,S,P.requestClass))continue;let B=this.#z(P,_),h=E.get(P.ownerId);if(!h||B<h.rank||B===h.rank&&H<h.index)E.set(P.ownerId,{pending:P,rank:B,index:H})}let T=[...E.values()].filter(({pending:H})=>{let P=this.#N.get(H.domainKey),M=this.#x.get(H.ownerId);return P!==void 0&&M!==void 0&&this.#M(P,M,H.requestClass)}).map(({pending:H,rank:P})=>({pending:H,rank:P,order:this.#x.get(H.ownerId).order}));if(T.length===0)return;let x=Math.min(...T.map((H)=>H.rank)),N=T.filter((H)=>H.rank===x),U=N.filter((H)=>H.order>this.#P).sort((H,P)=>H.order-P.order)[0]??N.sort((H,P)=>H.order-P.order)[0];this.#h(U.pending,U.order)}}#z(_,E){let T=_.requestClass==="foreground"?0:_.requestClass==="background"?1:2,x=Math.floor(Math.max(0,E-_.enqueuedAt)/this.#_.agingMs);return Math.max(0,T-x)}#h(_,E){if(!this.#X(_,!1))return;_.settled=!0,_.admitted=!0,this.#P=E;let T=this.#U(_.domainKey,_.ownerId,_.requestClass);_.permit=T,_.resolve(T)}#O(_){let E=this.#N.get(_.domainKey),T=this.#x.get(_.ownerId),x=E&&T?this.#D(E,T,_.requestClass):{scope:"global",resource:"stream",inFlight:J(this.#E.inFlight),limit:this.#_.globalMaxInFlight};this.#R(_,new B_("wait_timeout",x.scope,_.requestClass,x.resource,x.inFlight,x.limit,this.#T.length,_.maxWaitMs))}#f(_,E){this.#R(_,E)}#R(_,E){if(!this.#X(_))return;_.settled=!0,_.reject(E),this.#A()}#X(_,E=!0){if(_.settled||_.admitted)return!1;let T=this.#T.indexOf(_);if(T<0)return!1;this.#T.splice(T,1);let x=this.#N.get(_.domainKey),N=this.#x.get(_.ownerId);if(x&&N)this.#Q(x,N,_);if(this.#Z(_),E)this.#G(_.domainKey,_.ownerId);return!0}#Q(_,E,T){let{requestClass:x,pendingBytes:N}=T;this.#E.queued[x]--,_.counters.queued[x]--,E.counters.queued[x]--,this.#E.pendingBytes[x]-=N,_.counters.pendingBytes[x]-=N,E.counters.pendingBytes[x]-=N}#Z(_){if(_.timer)clearTimeout(_.timer);if(_.timer=void 0,_.signal&&_.abortListener)_.signal.removeEventListener("abort",_.abortListener);_.abortListener=void 0,_.signal=void 0}#G(_,E){let T=this.#N.get(_);if(T&&cE(T.counters))this.#N.delete(_);let x=this.#x.get(E);if(x&&cE(x.counters))this.#x.delete(E)}#K(_){let E=Math.max(0,Math.floor(this.#S()-_.enqueuedAt));if(_.admitted)return{state:"admitted",requestClass:_.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#T.length,inFlight:J(this.#E.inFlight),limit:this.#_.globalMaxInFlight,waitMs:E,maxWaitMs:_.maxWaitMs};let T=this.#N.get(_.domainKey),x=this.#x.get(_.ownerId),N=T&&x?this.#D(T,x,_.requestClass):{scope:"global",resource:"stream",inFlight:J(this.#E.inFlight),limit:this.#_.globalMaxInFlight};return{state:"queued",requestClass:_.requestClass,resource:N.resource,scope:N.scope,reason:"capacity",queuePosition:this.#b(_,N.scope),queueDepth:this.#T.length,inFlight:N.inFlight,limit:N.limit,waitMs:E,maxWaitMs:_.maxWaitMs}}#L(_,E){return{state:"admitted",requestClass:_.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#T.length,inFlight:J(this.#E.inFlight),limit:this.#_.globalMaxInFlight,waitMs:E,maxWaitMs:_.maxWaitMs}}#b(_,E){let T=this.#T.filter((x)=>{switch(E){case"owner":return x.ownerId===_.ownerId;case"domain":return x.domainKey===_.domainKey;case"class":return x.requestClass===_.requestClass;case"global":return!0}});return Math.max(1,T.indexOf(_)+1)}#j(_,E,T,x){return new B_(_,T.scope,E.requestClass,T.resource,T.inFlight,T.limit,x,E.maxWaitMs)}}var mE;function lE(_={}){return mE??=new pE(_),mE}var dE=new WeakSet;class o extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(_,E){super(`Provider recovery budget exhausted after ${_}ms`);this.budgetMs=_;this.elapsedMs=E;this.name="ProviderRecoveryBudgetExceededError"}}class u_ extends Error{timeoutMs;code="PROVIDER_REQUEST_DEADLINE_EXCEEDED";constructor(_){super(`Provider request deadline exceeded after ${_}ms`);this.timeoutMs=_;this.name="ProviderRequestDeadlineExceededError"}}var ST=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],DT=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],BT=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function sE(_){return(_ instanceof Error?_.message:String(_)).toLowerCase()}function HT(_){let E=sE(_);return DT.some((T)=>E.includes(T))}function c_(_){if(_!==null&&typeof _==="object")dE.add(_)}function Ax(_){return _!==null&&typeof _==="object"&&dE.has(_)}function MT(_){return _!==null&&typeof _==="object"&&"code"in _?_.code:void 0}function PT(_){if(_===null||typeof _!=="object")return;let E=_;for(let T of["status","statusCode"]){let x=E[T];if(typeof x==="number"&&Number.isInteger(x))return x}return}function UT(_){let E=_.match(/^(?:error:\s*)?(\d{3})\b/),T=_.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),x=Number(E?.[1]??T?.[1]);return Number.isInteger(x)?x:void 0}function m(_,E){let T=sE(_),x=MT(_);if(x==="STREAM_IDLE_TIMEOUT"||x==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||_ instanceof Error&&_.name==="AbortError"||T.includes("request aborted")||T==="aborted")return{retryable:!1};if(ST.some((Y)=>T.includes(Y))||HT(_))return{retryable:!1};if(E?.shouldRetry==="false")return{retryable:!1,statusCode:E.statusCode};if(x==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let N=E?.statusCode??PT(_)??UT(T);if(E?.shouldRetry==="true")return{retryable:!0,reason:N===429?"rate_limit":N===408||N===409?"timeout":"server_error",statusCode:N};if(N===429)return{retryable:!0,reason:"rate_limit",statusCode:N};if(N===408||N===409)return{retryable:!0,reason:"timeout",statusCode:N};if(N!==void 0&&N>=500&&N<=599)return{retryable:!0,reason:"server_error",statusCode:N};if(x==="PROVIDER_STREAM_CLOSED"||T.includes("stream closed before completion")||T.includes("ended without")||T.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:N};if(BT.some((Y)=>T.includes(Y)))return{retryable:!0,reason:"transport",statusCode:N};if(T.includes("timeout")||T.includes("timed out")||T.includes("temporarily unavailable")||T.includes("upstream_error")||T.includes("overloaded")||T.includes("rate limit")||T.includes("too many requests")||T.includes("service unavailable")||T.includes("server error")||T.includes("internal error")||T.includes("please retry")||T.includes("try your request again"))return{retryable:!0,reason:T.includes("rate")||T.includes("too many")?"rate_limit":T.includes("timeout")||T.includes("timed out")?"timeout":"server_error",statusCode:N};return{retryable:!1,statusCode:N}}function y_(_,E){if(!_)return;if(_.retryAfterMs!==void 0){let N=Number.parseFloat(_.retryAfterMs);if(Number.isFinite(N))return Math.max(0,N)}if(_.retryAfter===void 0)return;let T=Number.parseFloat(_.retryAfter);if(Number.isFinite(T))return Math.max(0,T*1000);let x=Date.parse(_.retryAfter);return Number.isFinite(x)?Math.max(0,x-E):void 0}function tE(_,E,T={}){let x=T.now??Date.now(),N=T.maxDelayMs??60000,Y=y_(E,x);if(Y!==void 0)return Math.min(Math.ceil(Y),N);let U=Math.max(0,_-1),H=T.maxExponentialDelayMs??8000,P=Math.min(500*2**U,H),M=Math.max(0,Math.min(1,T.random??Math.random())),S=P*(0.75+M*0.25);return Math.min(Math.round(S),N)}function g_(_,E){return{provider:m_(_),model:m_(E)}}function aE(_,E){if(s(_))return{source:"admission",reason:_.reason};if(D_(_))return{source:"circuit",reason:_.circuit.reason,..._.circuit.statusCode!==void 0?{statusCode:_.circuit.statusCode}:{}};if(_!==null&&typeof _==="object"&&"code"in _&&_.code==="STREAM_IDLE_TIMEOUT")return{source:"stall",reason:"timeout"};let T=m(_,E);if(T.retryable&&T.reason)return{source:"retry",reason:T.reason,...T.statusCode!==void 0?{statusCode:T.statusCode}:{}};throw Error("Provider fallback trigger is not classified")}function rE(_,E={}){let T=E.maxBytes??134217728,x=E.maxNodes??1e5;if(!Number.isSafeInteger(T)||T<=0||T>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(x)||x<=0)throw Error("maxNodes must be a positive safe integer");let N=new WeakSet,Y=0,U=0,H=!1,P=(S)=>{if(H||S<=0)return;if(!Number.isSafeInteger(S)||S>T-Y){Y=T+1,H=!0;return}Y+=S},M=(S)=>{if(H)return;if(U+=1,U>x){P(T+1);return}if(S===null){P(4);return}switch(typeof S){case"string":P(Buffer.byteLength(S,"utf8"));return;case"number":case"bigint":P(8);return;case"boolean":P(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(N.has(S))return;if(N.add(S),ArrayBuffer.isView(S)){P(32+S.byteLength);return}if(S instanceof ArrayBuffer){P(32+S.byteLength);return}if(S instanceof Date){P(40);return}if(S instanceof RegExp){P(32+Buffer.byteLength(S.source,"utf8"));return}if(S instanceof Map){P(32);for(let[B,h]of S)if(M(B),M(h),H)return;return}if(S instanceof Set){P(32);for(let B of S)if(M(B),H)return;return}if(S instanceof WeakMap||S instanceof WeakSet){P(32);return}if(Array.isArray(S)){P(16);for(let B of S)if(M(B),H)return;return}P(32);for(let B of Reflect.ownKeys(S)){if(typeof B!=="string")continue;let h=Object.getOwnPropertyDescriptor(S,B);if(!h?.enumerable||!("value"in h))continue;if(P(8+Buffer.byteLength(B,"utf8")),M(h.value),H)return}};return M(_),Y}function oE(_){return rE([_.messages,_.context,_.tools,_.requestOptions],{maxBytes:c})}function eE(_,E){let T=_.onPayload;_.onPayload=async(x,N)=>{let Y=T?await T(x,N):x;return E(Y===void 0?x:Y,N)}}function AT(_){if(!_.reasoningEnabled)return;return _.reasoningEffort??_.reasoningLevel??"high"}function p_(_,E,T){if(!_.enablePromptCaching)return"none";if(T&&E.api==="openai-completions"&&!E.baseUrl.includes("api.openai.com"))return"long";return"short"}function hT(_){switch(_){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function RT(_,E,T,x){let N=x?void 0:AT(T);if(!N){if(E.api==="anthropic-messages")_.thinkingEnabled=!1;if(E.api==="google-generative-ai"||E.api==="google-vertex")_.thinking={enabled:!1};return}switch(E.api){case"anthropic-messages":_.thinkingEnabled=!0,_.effort=N;break;case"google-generative-ai":case"google-vertex":_.thinking={enabled:!0,level:hT(N)};break;case"mistral-conversations":_.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":_.reasoning=N;break;default:_.reasoningEffort=N}}function XT(_,E,T){if(!T)return;switch(E){case"anthropic-messages":case"bedrock-converse-stream":_.toolChoice={type:"tool",name:T};break;case"openai-completions":case"mistral-conversations":case"pi-messages":_.toolChoice={type:"function",function:{name:T}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":_.toolChoice={type:"function",name:T};break;case"google-generative-ai":case"google-vertex":_.toolChoice="any";break}}function JT(_,E,T){let x=T.serviceTier;if(!x)return;if(E.api==="openai-responses"||E.api==="openai-codex-responses"||E.api==="azure-openai-responses"){_.serviceTier=x;return}if(E.api!=="openai-completions"&&!(E.api==="anthropic-messages"&&x==="fast"))return;eE(_,(N)=>{if(!N||typeof N!=="object"||Array.isArray(N))return N;return E.api==="anthropic-messages"?{...N,speed:"fast"}:{...N,service_tier:x}})}function VT(_,E,T){let x=T.responseVerbosity;if(!x)return;if(nE(E,x),E.api==="openai-codex-responses"){_.textVerbosity=x;return}eE(_,(N)=>{if(!N||typeof N!=="object"||Array.isArray(N))return N;if(E.api==="openai-completions")return{...N,verbosity:x};let Y="text"in N&&N.text&&typeof N.text==="object"&&!Array.isArray(N.text)?N.text:{};return{...N,text:{...Y,verbosity:x}}})}function _0(_,E,T,x,N=!1){let Y={apiKey:_.apiKey,headers:_.customHeaders,signal:T,temperature:x?.temperature??_.temperature??0,maxTokens:x?.maxOutputTokens??_.maxOutputTokens,timeoutMs:_.timeout,maxRetries:0,cacheRetention:p_(_,E,x?.providerSessionId),sessionId:x?.providerSessionId};if(RT(Y,E,_,N),XT(Y,E.api,x?.toolChoice?.toolName),JT(Y,E,_),VT(Y,E,_),E.api==="azure-openai-responses")Y.azureBaseUrl=_.baseUrl,Y.azureApiVersion=_.apiVersion,Y.azureDeploymentName=E.id;return Y}function iE(_,E){let T=E.get("x-should-retry");return{statusCode:_,...E.get("retry-after")!==null?{retryAfter:E.get("retry-after")??void 0}:{},...E.get("retry-after-ms")!==null?{retryAfterMs:E.get("retry-after-ms")??void 0}:{},...T==="true"||T==="false"?{shouldRetry:T}:{}}}var fT=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function E0(_,E,T){let x=_.onResponse;if(_.onResponse=async(Y,U)=>{let H=new Headers(Y.headers);T(iE(Y.status,H)),await x?.(Y,U)},!fT.has(E.api)||typeof globalThis.fetch!=="function")return;let N=typeof _.fetch==="function"?_.fetch:globalThis.fetch.bind(globalThis);_.fetch=async(Y,U)=>{let H=await N(Y,process.versions.bun?{...U,keepalive:!1}:U);return T(iE(H.status,H.headers)),H}}function T0(_){return{promptTokens:_.input+_.cacheRead+_.cacheWrite,completionTokens:_.output,totalTokens:_.totalTokens,costUsd:_.cost.total,..._.reasoning!==void 0?{reasoningTokens:_.reasoning}:{},..._.cacheWrite>0?{cacheCreationInputTokens:_.cacheWrite}:{},..._.cacheRead>0?{cacheReadInputTokens:_.cacheRead}:{}}}var V_=300000,$T=30000;class x0 extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(_){super(`Provider stream idle timeout after ${_}ms without an event`);this.timeoutMs=_;this.name="StreamIdleTimeoutError"}}class N0 extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function l_(_){return _.reason instanceof Error?_.reason:new DOMException("Aborted","AbortError")}function IT(_){return _.idleTimeoutMs&&_.idleTimeoutMs>0?_.idleTimeoutMs:V_}function WT(_,E){if(E===0)return;let T=E!==void 0&&E>0?E:$T;return Math.max(1,Math.min(T,Math.floor(_/2)))}function zT(_,E,T){if(T?.aborted)return Promise.reject(l_(T));return new Promise((x,N)=>{let Y=!1,U=()=>{clearTimeout(S),T?.removeEventListener("abort",M)},H=(B)=>{if(Y)return;Y=!0,U(),x(B)},P=(B)=>{if(Y)return;Y=!0,U(),N(B instanceof Error?B:Error(String(B)))},M=()=>{if(T)P(l_(T))},S=setTimeout(()=>H({kind:"timer"}),Math.max(0,E));if(T?.addEventListener("abort",M,{once:!0}),T?.aborted){M();return}_.then((B)=>H({kind:"next",result:B}),P)})}async function*OT(_,E,T){let x=IT(E),N=WT(x,E.stallWarningMs);if(E.signal?.aborted)throw l_(E.signal);let Y=Date.now(),U=Promise.resolve().then(()=>_.next()),H;for(;;){let M=await zT(U,(H?x:N??x)-(Date.now()-Y),E.signal);if(M.kind==="next"){if(H)yield{...H,phase:"recovered",durationMs:Math.max(H.durationMs,Date.now()-Y)};return M.result}if(!H&&N!==void 0){T.stallCount++,H={phase:"detected",stallCount:T.stallCount,durationMs:N,warningAfterMs:N,timeoutMs:x,outputStarted:T.outputStarted},yield H;continue}let S=new x0(x);throw E.abort?.(S),S}}async function*Y0(_,E,T,x,N={}){let U=_.stream(E,T,x)[Symbol.asyncIterator](),H=0,P=!1,M={stallCount:0,outputStarted:!1};try{while(!0){let S=OT(U,N,M),B=await S.next();while(!B.done)yield{providerStall:B.value},B=await S.next();let h=B.value;if(h.done)throw new N0;let V=h.value;switch(V.type){case"text_delta":M.outputStarted=!0,yield{content:V.delta};break;case"thinking_delta":M.outputStarted=!0,yield{reasoningContent:V.delta};break;case"toolcall_end":M.outputStarted=!0,yield{toolCalls:[{index:H++,id:V.toolCall.id,type:"function",function:{name:V.toolCall.name,arguments:JSON.stringify(V.toolCall.arguments)}}]};break;case"done":P=!0,yield{finishReason:V.reason,usage:T0(V.message.usage)};return;case"error":throw Error(V.error.errorMessage??`Request ${V.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!P)Promise.resolve(U.return?.()).catch(()=>{return})}}var d_=a("Chat"),jT=1;function GT(_,E){let T=E.provider===_.provider,x=T&&E.channel===void 0,N=E.channel;return{..._,provider:E.provider,model:E.model,apiKey:N?.apiKey??(x?_.apiKey:void 0),baseUrl:N?.baseUrl??(x?_.baseUrl:void 0),temperature:N?.temperature??_.temperature,maxOutputTokens:N?.maxOutputTokens??(x?_.maxOutputTokens:void 0),timeout:N?.timeout??_.timeout,streamIdleTimeout:N?.streamIdleTimeout??_.streamIdleTimeout,apiVersion:N?.apiVersion??(x?_.apiVersion:void 0),customHeaders:N?.customHeaders??(x?_.customHeaders:void 0),enablePromptCaching:N?.enablePromptCaching??(x?_.enablePromptCaching:void 0),serviceTier:T?_.serviceTier:void 0,responseVerbosity:T?_.responseVerbosity:void 0,fallbackModels:void 0}}function QT(_){return Boolean(_&&_.role==="user"&&Array.isArray(_.content)&&_.content.some((E)=>E.type==="image_url"))}function ZT(_){let T=_.findLast((x)=>{let N=x.metadata;return N!==null&&typeof N==="object"&&!Array.isArray(N)&&N.isCompactSummary===!0})?.metadata;return T!==null&&typeof T==="object"&&!Array.isArray(T)&&typeof T.parentId==="string"?T.parentId:""}function KT(_,E){let T=m(_,E);if(!T.retryable||!T.reason)return;let x=T.statusCode;switch(T.reason){case"rate_limit":if(x!==429)return;break;case"server_error":if(x===void 0||x<500||x>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let N=y_(E,Date.now());return{reason:T.reason,...x!==void 0?{statusCode:x}:{},...N!==void 0?{retryAfterMs:N}:{}}}function s_(_){return _!==null&&typeof _==="object"&&"code"in _&&_.code==="STREAM_IDLE_TIMEOUT"}class r_{config;models;model;promptCacheBreakMonitor=new Z_;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${jT++}`;constructor(_){let E=Q_(_);this.config={..._,maxContextTokens:E.model.contextWindow,maxOutputTokens:_.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model,this.providerAdmissionScheduler=S0(this.config),d_.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(_,E,T,x){let N="",Y="",U=[],H,P;for await(let M of this.streamChat(_,E,T,x)){N+=M.content??"",Y+=M.reasoningContent??"";for(let S of M.toolCalls??[])if(S.id&&S.type==="function"&&S.function?.name)U.push(S);H=M.usage??H,P=M.finishReason??P}return{content:N,...Y?{reasoningContent:Y}:{},...U.length>0?{toolCalls:U}:{},usage:H,finishReason:P}}async*streamChat(_,E,T,x){let N=x?.toolChoice?.toolName;if(N&&!E?.some((D)=>D.name===N))throw Error(`Required tool is unavailable: ${N}`);let Y=hE(_);if(Y.some((D)=>QT(D))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let U=Boolean(N)||RE(Y),H=await AE(Y,this.model,E,T,N),P=(D,A)=>{let W=x?.providerSessionId;if(!W||!D.usage)return D;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(W),D;let f=p_(this.config,A,W),R=this.promptCacheBreakMonitor.observe({sessionId:W,modelIdentity:`${A.provider}\x00${A.api}\x00${A.id}`,context:H,retention:f,contextEpoch:ZT(Y),policy:{baseUrl:A.baseUrl??this.config.baseUrl??"",retention:f,requiredTool:N??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:x?.temperature??this.config.temperature??0,maxOutputTokens:x?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:D.usage});if(!R)return D;return d_.warn("[PiAIChatService] Prompt cache break detected",{reason:R.reason,previousCacheReadTokens:R.previousCacheReadTokens,cacheReadTokens:R.cacheReadTokens,tokenDrop:R.tokenDrop,callNumber:R.callNumber}),{...D,usage:{...D.usage,promptCacheBreak:R}}},M=oE({messages:Y,context:H,tools:E,requestOptions:x}),S=x?.providerRecovery;if(S&&!B0(S.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let B=S?.mode==="bounded_foreground"&&S.budgetMs>0?{budgetMs:S.budgetMs,startedAt:void 0}:void 0,h=B?"bounded_foreground":"standard",V=this.config.maxRetries??2,K=this.config.maxRetries??(B?D0:2),C=B!==void 0&&this.config.maxRetries===void 0,w=0,v,f_=this.config.providerCircuitRegistry??OE(),H_=this.config.providerCircuitBreakerOpenMs??L_,H0=Math.max(R_,Math.min(this.config.streamIdleTimeout??V_,F_)),o_=this.providerAdmissionScheduler,M0=this.config.providerRequestConcurrency??d,i_=this.config.providerRequestAdmissionMs??q_,P0=this.config.providerRequestPendingBytes??v_,$_=x?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},U0=(D,A)=>f_.get({provider:D.provider,api:D.api,baseUrl:D.baseUrl??A.baseUrl??"",model:D.id,serviceTier:A.serviceTier,apiVersion:A.apiVersion,apiKey:A.apiKey,customHeaders:A.customHeaders,openDurationMs:H_,probeLeaseMs:H0}),A0=(D,A)=>({provider:D.provider,api:D.api,baseUrl:D.baseUrl??A.baseUrl??"",model:D.id,serviceTier:A.serviceTier,apiVersion:A.apiVersion,apiKey:A.apiKey,customHeaders:A.customHeaders,maxConcurrent:M0,maxPendingBytes:P0}),O=(D=Date.now())=>{if(!B)return;let A=B.startedAt===void 0?0:Math.min(B.budgetMs,Math.max(0,D-B.startedAt));return{recoveryBudgetMs:B.budgetMs,recoveryElapsedMs:A,recoveryRemainingMs:Math.max(0,B.budgetMs-A)}},y=()=>({mode:h,...O()??{}}),n_=()=>{if(B&&B.startedAt===void 0)B.startedAt=Date.now()},g=()=>{let D=O();return new o(B?.budgetMs??0,D?.recoveryElapsedMs??0)},i=()=>!C||w<K+1,I_=(D,A)=>{let{state:W,...f}=A;return{phase:D,...f,...O()?{recoveryRemainingMs:O()?.recoveryRemainingMs}:{}}},e_=(D)=>({phase:"rejected",requestClass:D.requestClass,resource:D.resource,scope:D.scope,reason:D.reason,queuePosition:0,queueDepth:Math.max(0,D.queued),inFlight:Math.max(0,D.inFlight),limit:Math.max(0,D.limit),waitMs:D.reason==="wait_timeout"?D.maxWaitMs:0,maxWaitMs:D.maxWaitMs,...O()?{recoveryRemainingMs:O()?.recoveryRemainingMs}:{}}),h0=async function*(D,A){if(!o_)return{release:()=>{return}};let W=O()?.recoveryRemainingMs,f=W!==void 0&&B?.startedAt!==void 0?Math.min(i_,W):i_,R;try{R=o_.admit({scope:A0(D,A),sessionId:$_.sessionId,ownerId:$_.ownerId,requestClass:$_.requestClass,maxWaitMs:f,pendingBytes:M,signal:T})}catch($){if(s($)){if($.reason==="wait_timeout"&&B?.startedAt!==void 0&&(O()?.recoveryRemainingMs??0)<=0)throw g();yield{providerAdmission:e_($)}}throw $}let b=R.getSnapshot();if(b.state==="admitted")return await R.ready;yield{providerAdmission:I_("queued",b)};let u=R.ready.then(($)=>({kind:"ready",permit:$}),($)=>({kind:"error",error:$}));while(!0){let $=R.getSnapshot(),I=Math.max(1,Math.min(gE,Math.max(1,f-$.waitMs))),Q,j=new Promise((p)=>{Q=setTimeout(()=>p({kind:"heartbeat"}),I),Q.unref?.()}),F=await Promise.race([u,j]);if(Q)clearTimeout(Q);if(F.kind==="heartbeat"){yield{providerAdmission:I_("queued",R.getSnapshot())};continue}if(F.kind==="error"){if(s(F.error)){if(F.error.reason==="wait_timeout"&&B?.startedAt!==void 0&&(O()?.recoveryRemainingMs??0)<=0)throw g();yield{providerAdmission:e_(F.error)}}throw F.error}return yield{providerAdmission:I_("admitted",R.getSnapshot())},F.permit}},R0=(D,A)=>{if(!i())throw g();if(C)w++;v=void 0;let W=new AbortController,f=T?DE(T,W.signal):W.signal,R=typeof A.timeout==="number"&&Number.isFinite(A.timeout)&&A.timeout>0?Math.max(1,Math.floor(A.timeout)):void 0,b;if(B?.startedAt!==void 0){let I=O()?.recoveryRemainingMs??0;if(I<=0)throw g();b={remainingMs:I,error:new o(B.budgetMs,B.budgetMs)}}let u=_0(A,D,f,x,U);E0(u,D,(I)=>{v=I});let $=Y0(this.models,D,H,u,{idleTimeoutMs:A.streamIdleTimeout??V_,signal:f,abort:(I)=>W.abort(I)});return async function*(){let I,Q;try{if(R!==void 0&&(b===void 0||R<b.remainingMs)){let j=new u_(R);I=setTimeout(()=>W.abort(j),R),I.unref?.()}if(b){let j=b;Q=setTimeout(()=>W.abort(j.error),j.remainingMs),Q.unref?.()}yield*$}finally{if(I)clearTimeout(I);if(Q)clearTimeout(Q)}}()},_E=this,t=(D)=>({phase:D.phase,reason:D.reason,...D.statusCode!==void 0?{statusCode:D.statusCode}:{},...D.retryAfterMs!==void 0?{retryAfterMs:D.retryAfterMs}:{},...D.nextProbeAt!==void 0?{nextProbeAt:D.nextProbeAt}:{},openDurationMs:D.openDurationMs,sampleCount:D.sampleCount,failureCount:D.failureCount,...O()?{recoveryRemainingMs:O()?.recoveryRemainingMs}:{}}),EE=(D,A)=>({phase:D,reason:A.reason,...A.statusCode!==void 0?{statusCode:A.statusCode}:{},retryAfterMs:A.retryAfterMs,...A.nextProbeAt!==void 0?{nextProbeAt:A.nextProbeAt}:{},openDurationMs:A.openDurationMs,sampleCount:A.sampleCount,failureCount:A.failureCount,...O()?{recoveryRemainingMs:O()?.recoveryRemainingMs}:{}}),X0=(D)=>({phase:"probe",reason:D.reason??"server_error",...D.statusCode!==void 0?{statusCode:D.statusCode}:{},openDurationMs:D.openDurationMs??H_,...D.sampleCount!==void 0?{sampleCount:D.sampleCount}:{},...D.failureCount!==void 0?{failureCount:D.failureCount}:{},...O()?{recoveryRemainingMs:O()?.recoveryRemainingMs}:{}}),W_=(D,A,W)=>({providerRetry:{phase:"exhausted",attempt:D,maxRetries:K,reason:A,...W!==void 0?{statusCode:W}:{},...y(),exhaustedBy:"recovery_budget"}}),TE=async function*(D,A,W,f,R){let b,u=!1,$,I,Q=U0(D,A);for(let j=0;j<=f;j++){if(!i())break;let F,p;while(!F){let X=Q.preflight();while(!X.eligible){if($=X.reason,I=X.statusCode,!B||!R){let q=EE("rejected",X);throw yield{providerCircuit:q},new S_(q)}n_();let z=O()?.recoveryRemainingMs??0;if(z<=0){let q=g();throw yield W_(C?Math.max(0,w-1):j,X.reason,X.statusCode),q}yield{providerCircuit:EE("waiting",X)};let l=Math.min(Math.max(1,X.retryAfterMs),t_,z);if(await T_(l,T,{throwOnAbort:!0}),(O()?.recoveryRemainingMs??0)<=0){let q=g();throw yield W_(C?Math.max(0,w-1):j,X.reason,X.statusCode),q}X=Q.preflight()}try{p=yield*h0(D,A)}catch(k){if(k instanceof o)yield W_(C?Math.max(0,w-1):j,$??"timeout",I);throw k}let L=Q.check();if(L.allowed)F=L;else p.release(),p=void 0}let e=F.token;if(F.probe)yield{providerCircuit:X0(F)};try{let X=!1,L=!1;for await(let k of R0(D,A)){if(k.providerStall){yield k;continue}let z=C?w-1:j;if(z>0&&$&&!X)X=!0,yield{providerRetry:{phase:"recovered",attempt:z,maxRetries:K,reason:$,...I!==void 0?{statusCode:I}:{},...y()}};if(!L){L=!0;let l=Q.recordSuccess(e);if(l)yield{providerCircuit:t(l)}}u=!0,W(),yield P(k,D)}if(!L){let k=Q.recordSuccess(e);if(k)yield{providerCircuit:t(k)}}return}catch(X){if(p?.release(),b=X,_E.logIdleTimeout(X,u,D),await _E.handleAbort(T),X instanceof o){if(u)throw c_(X),X;throw yield{providerRetry:{phase:"exhausted",attempt:C?Math.max(0,w-1):j,maxRetries:K,reason:$??"timeout",...I!==void 0?{statusCode:I}:{},...y(),exhaustedBy:"recovery_budget"}},X}let L=m(X,v);if(u)throw c_(X),X;let k=KT(X,v),z=k?Q.recordFailure(e,k):v&&!s_(X)?Q.recordNeutral(e):void 0;if(z)yield{providerCircuit:t(z)};if(!L.retryable||!L.reason){if(j>0&&$)yield{providerRetry:{phase:"exhausted",attempt:C?Math.max(0,w-1):j,maxRetries:K,reason:$,...I!==void 0?{statusCode:I}:{},...y()}};throw X}$=L.reason,I=L.statusCode;let l=j<f&&i();if(z&&z.phase!=="closed"&&l&&(!B||!R)){let q={...t(z),phase:"rejected"};throw yield{providerCircuit:q},new S_(q)}if(l){n_();let q=C?w:j+1,V0=tE(q,v,B?{maxDelayMs:a_,maxExponentialDelayMs:a_}:void 0),NE=z&&z.phase!=="closed"?z.retryAfterMs??0:0;if(B&&NE>0&&z)yield{providerCircuit:{...t(z),phase:"waiting"}};let f0=O(),O_=Math.max(V0,NE),__=B?Math.min(O_,f0?.recoveryRemainingMs??O_):O_,P_={attempt:q,maxRetries:K,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...P_,delayMs:__,nextRetryAt:Date.now()+__,...y()}},B){let E_=__;while(E_>0){let YE=Math.min(E_,t_);if(await T_(YE,T,{throwOnAbort:!0}),E_-=YE,(O()?.recoveryRemainingMs??0)<=0){let U_=g();throw yield{providerRetry:{phase:"exhausted",...P_,...y(),exhaustedBy:"recovery_budget"}},U_}if(E_>0){if(z&&z.phase!=="closed"&&z.nextProbeAt!==void 0){let U_=Math.max(0,z.nextProbeAt-Date.now());if(U_>0)yield{providerCircuit:{...t(z),phase:"waiting",retryAfterMs:U_}}}yield{providerRetry:{phase:"waiting",...P_,delayMs:__,nextRetryAt:Date.now()+E_,...y()}}}}}else await T_(__,T,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...P_,...y()}}}else yield{providerRetry:{phase:"exhausted",attempt:C?Math.max(0,w-1):j,maxRetries:K,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{},...y(),...B&&(R||!i())?{exhaustedBy:"attempt_limit"}:{}}}}finally{Q.abandon(e),p?.release()}}throw b},M_,xE=!1,z_=this.model,n=this.config.fallbackModels??[],J0=B&&n.length>0?Math.min(V,K):K;try{for await(let D of TE(this.model,this.config,()=>{xE=!0},J0,n.length===0))yield D;return}catch(D){if(M_=D,xE||!s(D)&&!D_(D)&&!s_(D)&&!m(D,v).retryable)throw D}for(let[D,A]of n.entries()){if(!i())break;let W=!1;try{let f=GT(this.config,A),R=VE(f,A);yield{modelFallback:{from:g_(z_.provider,z_.id),to:g_(R.provider,R.id),candidate:D+1,candidateCount:n.length,trigger:aE(M_,v)}},z_=R;let b=D===n.length-1,u=B&&!b?Math.min(V,K):K;for await(let $ of TE(R,f,()=>{W=!0},u,b))yield $;return}catch(f){if(M_=f,W||!s(f)&&!D_(f)&&!s_(f)&&!m(f,v).retryable)throw f}}throw M_}async handleAbort(_){if(_?.aborted)await T_(0,_,{throwOnAbort:!0})}logIdleTimeout(_,E,T){if(_===null||typeof _!=="object"||!("code"in _)||_.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in _)||typeof _.timeoutMs!=="number")return;d_.warn("[PiAIChatService] Provider stream idle timeout",{provider:T.provider,model:T.id,timeoutMs:_.timeoutMs,replayBoundaryCrossed:E})}getConfig(){return{...this.config}}updateConfig(_){let E={...this.config,..._},T=Q_(E);this.config={...E,maxContextTokens:T.model.contextWindow,maxOutputTokens:E.maxOutputTokens??T.model.maxTokens},this.models=T.models,this.model=T.model,this.providerAdmissionScheduler=S0(this.config)}}function S0(_){if(_.providerRequestAdmissionScheduler)return _.providerRequestAdmissionScheduler;if(_.providerRequestConcurrency===void 0&&_.providerGlobalConcurrency===void 0&&_.providerOwnerConcurrency===void 0)return;let E=_.providerGlobalConcurrency??Number.MAX_SAFE_INTEGER,T=_.providerOwnerConcurrency??Number.MAX_SAFE_INTEGER;return lE({globalMaxInFlight:E,ownerMaxInFlight:T,nonForegroundGlobalMaxInFlight:E,nonForegroundOwnerMaxInFlight:T,internalGlobalMaxInFlight:E,internalDomainMaxInFlight:_.providerRequestConcurrency??d,classLimitsEnabled:!1})}var LT=a("Service");async function rx(_){let E=_;if(E.provider){let T=SE(E.provider);if(Object.keys(T).length>0)E={...E,customHeaders:{...T,...E.customHeaders}},LT.debug(`Injected ${E.provider} specific headers:`,Object.keys(T))}return bT(E)}function bT(_){return new r_(_)}
|
|
8
|
-
export{CT as fg,vT as gg,DE as hg,T_ as ig,s as jg,HT as kg,Ax as lg,m as mg,tE as ng,rE as og,r_ as pg,rx as qg};
|
package/dist/chunk-nsb3cj6t.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{p as gH,q as kH,r as CH,s as hH,t as OH,u as wH}from"./chunk-m0t26vkj.js";import{B as RH,C as ZH,D as $H,E as qH,F as a,G as XH}from"./chunk-dhxx5mwe.js";import{H as NH,da as MH,fa as zH,ga as fH,ka as AH}from"./chunk-rwm71p4g.js";import"./chunk-vzdsext4.js";import"./chunk-p8cmxhbr.js";import{ab as QH}from"./chunk-9fyjyk2f.js";import{Nb as e,Zb as FH,ic as EH}from"./chunk-1b8qjgm6.js";import"./chunk-fdr4fcrf.js";import{Td as GH,Xd as PH,Zd as d,ie as t}from"./chunk-4ts2s9mz.js";import"./chunk-egss0m1x.js";import"./chunk-ztreczac.js";import"./chunk-p6586ftx.js";import{sf as TH}from"./chunk-vgf07dhy.js";import{uf as yH,vf as bH,wf as IH}from"./chunk-8cncpfhd.js";import{xf as SH}from"./chunk-je908ygr.js";import"./chunk-p0wyhp5a.js";import{Xf as _H}from"./chunk-5j94j64z.js";import"./chunk-v508x7cg.js";import"./chunk-5yyp6njq.js";import"./chunk-myvt7yjm.js";import"./chunk-4fbpydtn.js";import"./chunk-3cas6rv5.js";import"./chunk-zfxcef0z.js";import"./chunk-pqsjy31p.js";import"./chunk-egc2f1ye.js";import"./chunk-kehgewqh.js";import{ih as c,mh as BH}from"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-smxdn7kq.js";import"./chunk-ys8gysg8.js";import"./chunk-81py03y4.js";import{Ui as xH}from"./chunk-qpmvp4q2.js";import{Zi as r,_i as n}from"./chunk-tm3789m3.js";import{cj as C}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import{Gj as UH,Ij as H,Jj as YH,Lj as Y}from"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import"./chunk-z0m9j0e2.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";import uJ from"yargs";import{hideBin as dJ}from"yargs/helpers";function i(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function aH(V,Z){if(!V.once&&!V.on||!V.off&&!V.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,K=()=>{i(V,"drain",x),i(V,"error",j),Z.removeEventListener("abort",P)},D=(F)=>{if(J)return;J=!0,K(),F()},x=()=>D(Q),j=(F)=>D(()=>q(F??Error("Writable emitted an error"))),P=()=>D(()=>q(Z.reason??Error("Writable drain aborted")));if(Z.aborted){P();return}let T=V.once?.bind(V)??V.on?.bind(V);T?.("drain",x),T?.("error",j),Z.addEventListener("abort",P,{once:!0})})}async function iH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await aH(V,Q)}class o{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new a("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new XH({maxPendingItems:Z.maxPendingItems??ZH,maxPendingBytes:Z.maxPendingBytes??$H,writeTimeoutMs:Z.writeTimeoutMs??qH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>iH(V[q],J,K),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(V.stdout),V.stderr!==V.stdout)this.observeSinkErrors(V.stderr);if(Z.signal?.addEventListener("abort",this.handleAbort,{once:!0}),Z.signal?.aborted)this.handleAbort()}write(V,Z){return this.queues[V].offer(Z).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(V){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(V){if(!V.on||!V.off&&!V.removeListener)return;let Z=(Q)=>{this.fail(new a("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};V.on("error",Z),this.sinkErrorListeners.push({writer:V,listener:Z})}fail(V){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V),this.options.onFailure?.(V)}removeSinkErrorListeners(){for(let{writer:V,listener:Z}of this.sinkErrorListeners.splice(0))i(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var oH=L({type:H.Literal("content_delta"),delta:H.String()}),sH=L({type:H.Literal("thinking_delta"),delta:H.String()}),rH=L({type:H.Literal("thinking"),content:H.String()}),nH=L({type:H.Literal("stream_end")}),tH=L({type:H.Literal("content"),content:H.String()}),eH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),s=Y(["readonly","write","execute"]),HJ=H.Object({kind:s,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),JJ=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s)}),KJ=L({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(HJ)}),VJ=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:Y(["local","acp"])}),ZJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(VJ)}),$J=L({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),qJ=L({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:Y(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),XJ=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),YJ=L({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:Y(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),BJ=L({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:Y(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),NJ=L({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:Y(["added","removed"]),reason:Y(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),QJ=L({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:Y(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),DJ=L({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:Y(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),LJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),WJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),jJ=L({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:Y(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),xJ=L({type:H.Literal("phase"),phase:Y(["turn","searching","inspecting","target_hit","executing","completed"]),status:Y(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),UJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),_J=L({type:H.Literal("task_update"),tasks:H.Array(NH)}),GJ=L({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:Y(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),PJ=L({type:H.Literal("goal"),state:Y(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(Y(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(Y(BH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),execution_host_failure_category:H.Optional(Y(["timeout","admission","spawn","finalization","sandbox_start","terminal"])),execution_host_failure_count:H.Optional(H.Integer({minimum:1,maximum:3})),frontier_stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3})),root_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),current_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),parent_turn_id:H.Optional(H.String({minLength:1,maxLength:c}))}),FJ=L({type:H.Literal("subagent"),state:Y(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(Y(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),EJ=L({type:H.Literal("token_usage"),scope:H.Optional(H.Literal("auxiliary")),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:Y(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),MJ=L({type:H.Literal("compacting"),state:Y(["started","completed"]),reason:H.Optional(Y(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(Y(["llm","fallback","snip"])),outcome:H.Optional(Y(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(Y(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(Y(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"])),memory:H.Optional(QH)}),zJ=L({type:H.Literal("provider_retry"),phase:Y(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(Y(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(Y(["attempt_limit","recovery_budget"]))}),fJ=L({type:H.Literal("provider_admission"),phase:Y(["queued","admitted","rejected"]),request_class:Y(["foreground","background","internal"]),resource:Y(["stream","pending_count","pending_bytes"]),scope:Y(["global","domain","owner","class"]),reason:H.Optional(Y(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),AJ=L({type:H.Literal("provider_circuit"),phase:Y(["opened","waiting","probe","closed","reopened","rejected"]),reason:Y(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),SJ=L({type:H.Literal("provider_stall"),phase:Y(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),u=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),DH=H.Union([H.Object({source:Y(["retry","circuit"]),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),H.Object({source:H.Literal("admission"),reason:Y(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),H.Object({source:H.Literal("stall"),reason:H.Literal("timeout")},{additionalProperties:!1})]),TJ=H.Object({activity:Y(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),reason:Y(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),updated_at:H.Integer({minimum:0}),next_action_at:H.Optional(H.Integer({minimum:0})),retry:H.Optional(H.Object({attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),delay_ms:H.Optional(H.Integer({minimum:0})),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),admission:H.Optional(H.Object({request_class:Y(["foreground","background","internal"]),scope:Y(["global","domain","owner","class"]),resource:Y(["stream","pending_count","pending_bytes"]),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),circuit:H.Optional(H.Object({phase:Y(["opened","reopened","waiting","probe","rejected"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),stall:H.Optional(H.Object({stall_count:H.Integer({minimum:0}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:0}),timeout_ms:H.Integer({minimum:0}),output_started:H.Boolean()},{additionalProperties:!1})),fallback:H.Optional(H.Object({from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}))},{additionalProperties:!1}),yJ=H.Object({event_version:H.Literal(k),type:H.Literal("provider_recovery"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([TJ,H.Null()])},{additionalProperties:!1}),bJ=H.Object({name:H.String({minLength:1,maxLength:128}),kind:H.Optional(Y(["readonly","write","execute"])),started_at:H.Integer({minimum:0}),progress:H.Optional(H.Integer({minimum:0})),total:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1}),IJ=H.Object({phase:Y(["starting","thinking","responding","executing_tools","compacting","continuing"]),started_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),turn:H.Integer({minimum:0}),max_turns:H.Union([H.Integer({minimum:0}),H.Null()]),output_started:H.Boolean(),tool_calls_started:H.Integer({minimum:0}),tool_calls_completed:H.Integer({minimum:0}),active_tools:H.Array(bJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),RJ=H.Object({event_version:H.Literal(k),type:H.Literal("turn_activity"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([IJ,H.Null()])},{additionalProperties:!1}),gJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}),kJ=L({type:H.Literal("action_stationarity"),phase:Y(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),CJ=L({type:H.Literal("turn_recovery"),state:Y(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(Y(["successful_tool_result","interrupted_tool_call"]))}),hJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),OJ=L({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:Y(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),wJ=L({type:H.Literal("task_admission"),state:Y(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),mJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),cJ=L({type:H.Literal("error"),message:H.String()}),NK=YH(H.Union([oH,sH,rH,nH,tH,eH,JJ,KJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,EJ,MJ,fJ,AJ,zJ,SJ,yJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ,mJ,cJ]));function LH(V,Z){return{event_version:k,type:V,...Z}}function pJ(V){if(!V||typeof V!=="object"||Array.isArray(V))return;let Z=V;if(Z.auto_backgrounded!==!0||Z.background_reason!=="foreground_budget"||!Number.isSafeInteger(Z.foreground_budget_ms)||Z.foreground_budget_ms<=0||typeof Z.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(Z.shell_id)||Z.shell_id.length>128||Z.terminal_transport!=="local"&&Z.terminal_transport!=="acp"||Z.pid!==void 0&&(!Number.isSafeInteger(Z.pid)||Z.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:Z.foreground_budget_ms,shell_id:Z.shell_id,...Z.pid===void 0?{}:{pid:Z.pid},terminal_transport:Z.terminal_transport}}function vJ(V){let Z=new AbortController,Q=(K)=>{if(!Z.signal.aborted)Z.abort(K)},q=()=>Q("interrupt"),J=()=>Q(V?.signal?.reason);if(V?.signal){if(V.signal.addEventListener("abort",J,{once:!0}),V.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:Z.signal,abort:Q,dispose:()=>{V?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var lJ=Y(["text","jsonl"]),aJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(V)=>V===-1||V>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(xH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(Y(["local","worktree"])),outputFormat:H.Optional(lJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class mH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(V){this.openedThinking=V}hasOpenThinking(){return this.openedThinking}completeStream(){let V={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,V}}function iJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function oJ(V){let Z=UH(aJ,V);if(!Z.success)throw Error(`Invalid headless options: ${iJ(Z.error)}`);return Z.data}function sJ(V){return V.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(Z)=>{if(!Z.headless)return;let Q=await JK(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
|
|
2
|
-
`)}function rJ(V){return`[task] [${V.status}] ${V.subject}`}function nJ(){return{requestConfirmation:async(V)=>V.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:V.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function tJ(V){if(!(V instanceof Error))return"Unknown error";let q=V.lastError??V;if(q.responseBody)try{let D=JSON.parse(q.responseBody)?.error?.message;if(D)return q.statusCode?`${D} (HTTP ${q.statusCode})`:D}catch{}let J=V.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return V.message}function eJ(V){return V==="jsonl"?"jsonl":"text"}function WH(V,Z){let Q=(...q)=>{for(let J of q){let K=Z[J];if(typeof K==="string"&&K.trim()!=="")return K}return};switch(V){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function HK(V,Z,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),K=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(V)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(J.has(V))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if(K.has(V))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function jH(V,Z,Q=!1){let q=(J,K)=>{V.stdout.write(`${JSON.stringify(LH(J,K))}
|
|
3
|
-
`)};return{contentDelta(J){if(Z==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;V.stdout.write(J)},thinkingDelta(J,K){if(Z==="jsonl")return q("thinking_delta",{delta:J}),K;if(!K)V.stderr.write("[thinking] ");return V.stderr.write(J),!0},thinking(J){if(Z==="jsonl"){q("thinking",{content:J});return}W(V.stderr,`[thinking] ${J}`)},streamEnd(J,K){if(Z==="jsonl"){q("stream_end",{});return}if(K)V.stderr.write(`
|
|
4
|
-
`);if(J)V.stdout.write(`
|
|
5
|
-
`)},content(J){if(Z==="jsonl"){q("content",{content:J});return}W(V.stdout,J)},structuredOutput(J){if(Z==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}W(V.stdout,JSON.stringify(J.output))},toolStart(J,K,D,x){if(Z==="jsonl"){q("tool_start",{tool_name:J,summary:K,target:D,tool_kind:x});return}W(V.stderr,`[tool:start] ${K}`)},toolProgress(J,K,D,x,j){if(Z==="jsonl"){q("tool_progress",{tool_name:J,message:K,progress:D,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}W(V.stderr,`[tool:progress] ${J}: ${K}`)},toolResult(J,K,D,x,j){if(Z==="jsonl"){q("tool_result",{tool_name:J,summary:K,target:D,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}W(V.stderr,`[tool:result] ${K}`)},mcpCatalogChanged(J){if(Z==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}W(V.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(Z==="jsonl"){q("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}W(V.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(Z==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}W(V.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(Z==="jsonl"){q("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}W(V.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(Z==="jsonl"){q("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}W(V.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(Z==="jsonl"){q("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}W(V.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(Z==="jsonl"){q("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}W(V.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(Z==="jsonl"){q("project_rules_loaded",{files:J.files.map((K)=>({id:K.id,relative_path:K.relativePath,source:K.source,conditional:K.conditional,content_sha256:K.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}W(V.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,K,D){if(Z==="jsonl"){q("user_shell_started",{execution_id:J,command:K,auxiliary:D});return}W(V.stderr,`[user-shell:start] ${K}`)},userShellOutput(J,K,D,x){if(Z==="jsonl"){q("user_shell_output",{execution_id:J,stream:K,chunk:D,stream_truncated:x});return}(K==="stderr"?V.stderr:V.stdout).write(D)},userShellCompleted(J){if(Z==="jsonl"){q("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}W(V.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,K,D,x={}){if(Z==="jsonl"){q("phase",{phase:J,status:K,message:D,turn:x.turn,tool_name:x.toolName,target:x.target});return}W(V.stderr,`[phase:${J}] ${D}`)},toolDetail(J,K){if(Z==="jsonl"){q("tool_detail",{tool_name:J,detail:K});return}W(V.stderr,K)},taskUpdate(J){if(Z==="jsonl"){q("task_update",{tasks:J});return}for(let K of J)W(V.stderr,rJ(K))},goalFrontier(J){if(Z==="jsonl"){q("goal_frontier",{goal_id:J.goal.goalId,status:J.goal.status,task_list_id:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,in_progress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,next_task:J.frontier.nextTask,digest_sha256:J.frontier.digestSha256,observed_at:J.frontier.observedAt,stall_category:J.goal.frontierStall?.category,stall_count:J.goal.frontierStall?.consecutiveCount});return}let K=J.frontier.nextTask?` next=#${J.frontier.nextTask.id} ${J.frontier.nextTask.subject}`:"";W(V.stderr,`[goal-frontier] ${J.frontier.completed}/${J.frontier.total} completed${K}`)},turnRecovery(J){let K=J.assessment;if(Z==="jsonl"){q("turn_recovery",{state:K.state,turn_id:K.turnId,input_message_count:K.inputMessageCount,reason:K.state==="requires_attention"?K.reason:void 0});return}W(V.stderr,`[turn-recovery:${K.state}] ${K.turnId}`)},goal(J){if(Z==="jsonl"){q("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256,verification_summary:J.goal?.completionVerification?.summary,verification_stall_count:J.goal?.verificationStall?.consecutiveCount,premature_stop_pattern:J.goal?.prematureStop?.pattern,premature_stop_count:J.goal?.prematureStop?.consecutiveCount,execution_host_failure_category:J.goal?.executionHostFailure?.category,execution_host_failure_count:J.goal?.executionHostFailure?.consecutiveCount,frontier_stall_category:J.goal?.frontierStall?.category,frontier_stall_count:J.goal?.frontierStall?.consecutiveCount,root_turn_id:J.goal?.turnLineage?.rootTurnId,current_turn_id:J.goal?.turnLineage?.currentTurnId,parent_turn_id:J.goal?.turnLineage?.parentTurnId});return}if(J.goal)W(V.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else W(V.stderr,"[goal:cleared]")},subagent(J){let K=J.kind==="subagent_spawned";if(Z==="jsonl"){q("subagent",{state:K?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:K?void 0:J.success,summary:K?void 0:J.summary,verification_verdict:K?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}W(V.stderr,`[subagent:${K?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(Z==="jsonl"){q("token_usage",{...J.scope?{scope:J.scope}:{},input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}W(V.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let K=J.phase==="start";if(Z==="jsonl"){q("compacting",{state:K?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,pre_token_source:J.preTokenSource,estimated_pending_tokens:J.estimatedPendingTokens,post_tokens:J.postTokens,sample_attempts:J.sampleAttempts,input_reductions:J.inputReductions,messages_omitted:J.messagesOmitted,files_omitted:J.filesOmitted,images_omitted:J.imagesOmitted,fallback_target_tokens:J.fallbackTargetTokens,fallback_messages_omitted:J.fallbackMessagesOmitted,fallback_messages_truncated:J.fallbackMessagesTruncated,failure_reason:J.failureReason,memory:J.memory});return}W(V.stderr,K?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}${J.sampleAttempts!==void 0?` after ${J.sampleAttempts} sample attempt${J.sampleAttempts===1?"":"s"}`:""}${J.inputReductions?` with ${J.inputReductions} input reduction${J.inputReductions===1?"":"s"}`:""}${J.imagesOmitted?` and ${J.imagesOmitted} image${J.imagesOmitted===1?"":"s"} omitted`:""}${J.fallbackTargetTokens!==void 0?`; fallback target ${J.fallbackTargetTokens} tokens, ${J.fallbackMessagesOmitted??0} messages omitted, ${J.fallbackMessagesTruncated??0} truncated`:""}${J.memory?.outcome==="written"?`; saved ${J.memory.entries} project memories`:""}`)},providerAdmission(J){if(Z==="jsonl"){q("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}W(V.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(Z==="jsonl"){q("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let K=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";W(V.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${K}`)},providerCircuit(J){if(Z==="jsonl"){q("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let K=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";W(V.stderr,`[provider-circuit:${J.phase}] ${J.reason}${K}`)},providerStall(J){if(Z==="jsonl"){q("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}W(V.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},providerRecovery(J){let K=J.recovery.snapshot;if(Z==="jsonl"){q("provider_recovery",{generation:J.recovery.generation,revision:J.recovery.revision,snapshot:K?{activity:K.activity,reason:K.reason,updated_at:K.updatedAt,next_action_at:K.nextActionAt,retry:K.retry?{attempt:K.retry.attempt,max_retries:K.retry.maxRetries,status_code:K.retry.statusCode,delay_ms:K.retry.delayMs,recovery_budget_ms:K.retry.recoveryBudgetMs,recovery_elapsed_ms:K.retry.recoveryElapsedMs,recovery_remaining_ms:K.retry.recoveryRemainingMs}:void 0,admission:K.admission?{request_class:K.admission.requestClass,scope:K.admission.scope,resource:K.admission.resource,queue_position:K.admission.queuePosition,queue_depth:K.admission.queueDepth,in_flight:K.admission.inFlight,limit:K.admission.limit,wait_ms:K.admission.waitMs,max_wait_ms:K.admission.maxWaitMs,recovery_remaining_ms:K.admission.recoveryRemainingMs}:void 0,circuit:K.circuit?{phase:K.circuit.phase,status_code:K.circuit.statusCode,retry_after_ms:K.circuit.retryAfterMs,next_probe_at:K.circuit.nextProbeAt,open_duration_ms:K.circuit.openDurationMs,sample_count:K.circuit.sampleCount,failure_count:K.circuit.failureCount,recovery_remaining_ms:K.circuit.recoveryRemainingMs}:void 0,stall:K.stall?{stall_count:K.stall.stallCount,duration_ms:K.stall.durationMs,warning_after_ms:K.stall.warningAfterMs,timeout_ms:K.stall.timeoutMs,output_started:K.stall.outputStarted}:void 0,fallback:K.fallback?{from:K.fallback.from,to:K.fallback.to,candidate:K.fallback.candidate,candidate_count:K.fallback.candidateCount,trigger:K.fallback.trigger.source==="retry"||K.fallback.trigger.source==="circuit"?{source:K.fallback.trigger.source,reason:K.fallback.trigger.reason,status_code:K.fallback.trigger.statusCode}:K.fallback.trigger}:void 0}:null});return}W(V.stderr,K?`[provider-recovery:${K.activity}] ${K.reason}`:"[provider-recovery:clear]")},turnActivity(J){if(Z!=="jsonl")return;let K=J.activity.snapshot;q("turn_activity",{generation:J.activity.generation,revision:J.activity.revision,snapshot:K?{phase:K.phase,started_at:K.startedAt,updated_at:K.updatedAt,turn:K.turn,max_turns:K.maxTurns,output_started:K.outputStarted,tool_calls_started:K.toolCallsStarted,tool_calls_completed:K.toolCallsCompleted,active_tools:K.activeTools.map((D)=>({name:D.name,kind:D.kind,started_at:D.startedAt,progress:D.progress,total:D.total})),active_tool_overflow:K.activeToolOverflow}:null})},modelFallback(J){let K=J.trigger.source==="retry"||J.trigger.source==="circuit"?{source:J.trigger.source,reason:J.trigger.reason,status_code:J.trigger.statusCode}:J.trigger;if(Z==="jsonl"){q("model_fallback",{from:J.from,to:J.to,candidate:J.candidate,candidate_count:J.candidateCount,trigger:K});return}W(V.stderr,`[provider-fallback] ${J.from.model} -> ${J.to.model}`)},actionStationarity(J){if(Z==="jsonl"){q("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}W(V.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(Z==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}W(V.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(Z==="jsonl"){q("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}W(V.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(Z==="jsonl"){q("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}W(V.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,K=0){if(Z==="jsonl"){q("output",{content:J,exit_code:K});return}W(K===0?V.stdout:V.stderr,J)},error(J){if(Z==="jsonl"){q("error",{message:J});return}W(V.stderr,J)}}}async function JK(V,Z={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new mH,K={targetLocked:!1},D,x,j,P=vJ(Q),T=!1,F=new o(Z,{signal:P.signal,onFailure:(N)=>{T=!0,P.abort(N)}}),p={stdout:{write:(N)=>F.write("stdout",N)},stderr:{write:(N)=>F.write("stderr",N)}},B=jH(p,q),v=async()=>{try{return await F.flush(),!T}catch{return!1}},E=async(N)=>{return x?.(),x=void 0,j?.(),j=void 0,await v()?N:1};try{let N=oJ(V);q=eJ(N.outputFormat);let y=await OH(N);B=jH(p,q,Boolean(y)),await gH();let HH=N.forkSession!==!0&&(N.continue===!0||typeof N.resume==="string"&&N.resume.length>0)?await CH({message:N.message,_:N._,stdin:Q?.stdin}):await kH({...N,stdin:Q?.stdin}),M=HH===void 0,_=M?{mode:"agent",content:""}:await hH(HH);if(_.mode==="output"){if(_.content)B.output(_.content,_.exitCode??0);return await E(_.exitCode??0)}if(!M&&_.content.length>r)throw Error(`User prompt exceeds the ${r}-character durable input limit`);if(!M&&Buffer.byteLength(_.content,"utf8")>n)throw Error(`User prompt exceeds the ${n}-byte durable input limit`);let h=_.content.trimStart().startsWith("!")?_.content.trimStart().slice(1).trim():void 0;if(h!==void 0&&N.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(h!==void 0&&y)throw Error("Output schemas cannot be combined with user shell commands");if(N.taskIsolation&&(N.continue||N.resume||N.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:G,messages:JH,metadata:KH}=await wH({sessionId:N.sessionId,continue:N.continue,resume:N.resume,forkSession:N.forkSession,fallbackSessionPrefix:"headless"}),R=N.permissionMode??KH?.permissionMode??"yolo",VH=N.model&&N.model!=="inherit"?N.model:_H()?.id,U=N.taskIsolation?await RH.createSessionTask({sessionId:G,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,dispatch:{version:1,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,permissionMode:R,...VH?{modelId:VH}:{},...y?{outputSchema:y}:{}}}):void 0,z=U?.metadata.projectPath??KH?.projectPath??C();if(j=e.subscribe(($)=>{if($.type!=="subagent.provider.admission"||$.sessionId!==G||$.projectPath!==z)return;let X=$.properties,f=["queued","admitted","rejected"],A=["foreground","background","internal"],S=["stream","pending_count","pending_bytes"],I=["global","domain","owner","class"],lH=["capacity","queue_full","wait_timeout","closed"];if(!f.includes(X.phase)||!A.includes(X.requestClass)||!S.includes(X.resource)||!I.includes(X.scope)||X.reason!==void 0&&!lH.includes(X.reason)||typeof X.queuePosition!=="number"||typeof X.queueDepth!=="number"||typeof X.inFlight!=="number"||typeof X.limit!=="number"||typeof X.waitMs!=="number"||typeof X.maxWaitMs!=="number"||X.recoveryRemainingMs!==void 0&&typeof X.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:X.phase,requestClass:X.requestClass,resource:X.resource,scope:X.scope,...X.reason!==void 0?{reason:X.reason}:{},queuePosition:X.queuePosition,queueDepth:X.queueDepth,inFlight:X.inFlight,limit:X.limit,waitMs:X.waitMs,maxWaitMs:X.maxWaitMs,...X.recoveryRemainingMs!==void 0?{recoveryRemainingMs:X.recoveryRemainingMs}:{}})}),!U)await t.setSessionPermissionMode(G,z,R);let cH=U?!1:await EH.cancelPendingNonInteractive(z,G);if(U)B.taskSession({sessionId:G,projectPath:z,sourceProjectPath:U.metadata.taskSourceProjectPath??C(),isolation:N.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=e.subscribe(($)=>{if($.type!=="task.status"||$.sessionId!==G||$.projectPath!==z||!["queued","running"].includes(String($.properties.taskStatus))||typeof $.properties.taskQueueDepth!=="number"||typeof $.properties.taskInFlight!=="number"||typeof $.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:$.properties.taskStatus,queuePosition:typeof $.properties.taskQueuePosition==="number"?$.properties.taskQueuePosition:void 0,queueDepth:$.properties.taskQueueDepth,inFlight:$.properties.taskInFlight,maxConcurrentTasks:$.properties.taskConcurrencyLimit})});let uH={messages:cH?await t.loadSessionModelContext(G,z):[...JH],userId:"cli-user",sessionId:G,workspaceRoot:z,permissionMode:R,signal:P.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:nJ()};D=await MH.create({sessionId:G,workspaceRoot:z,modelId:N.model,permissionMode:R,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig,agents:N.agents?SH(N.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...JH.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}});let g=M&&D.getPendingSteeringCount()>0,O=M&&!g?await D.getGoal():null,w=O?.status==="active"||O?.status==="verifying",l=D.getTurnRecoveryAssessment?.()??{state:"none"};if(M&&!g&&!w&&l.state==="requires_attention")return B.turnRecovery({kind:"turn_recovery",assessment:l}),B.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);let b=M&&!g&&!w?await D.getRecoveredFinalResponse():void 0;if(M&&!g&&!w){if(!b)throw Error("No unfinished turn or active goal to resume");let $=l;if($.state!=="none")B.turnRecovery({kind:"turn_recovery",assessment:$});if(O)B.goal({kind:"goal_updated",goal:O});if(b.structuredOutput&&b.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:b.structuredOutput,schemaDigest:b.structuredOutputSchemaDigest});else B.content(b.content);return B.phase("completed","done","Recovered headless run completed"),await E(0)}if(h!==void 0){let $=await D.executeUserShellCommand(h,{signal:P.signal,onEvent:async(X)=>{if(X.type==="started")B.userShellStarted(X.executionId,X.command,X.auxiliary);else if(X.type==="output")B.userShellOutput(X.executionId,X.stream,X.chunk,X.streamTruncated);await v()}});return B.userShellCompleted($),await E($.record.status==="completed"?0:$.record.status==="aborted"?130:$.record.exitCode??1)}let dH=N.maxTurns??D.getConfig().maxTurns,pH=U?.taskWorktree?[...new Set([...N.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:N.disallowedTools,vH=await AH.createWithRuntime(D,{sessionId:G,systemPrompt:N.systemPrompt,appendSystemPrompt:N.appendSystemPrompt,maxTurns:N.maxTurns,modelId:N.model,permissionMode:R,toolWhitelist:N.allowedTools,toolBlacklist:pH,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig}),m=await FH(vH.chatStream(_.content,uH,{stream:!0,signal:P.signal,maxTurns:N.maxTurns,builtinVerification:N.verificationAgent!==!1,outputSchema:y,pendingInputOnly:g,goalContinuationOnly:w,...dH===-1?{onTurnLimitReached:async($)=>{return B.turnLimit($.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async($)=>{switch($.kind){case"content_delta":if(!y||q==="jsonl")J.markAssistantContent();B.contentDelta($.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta($.delta,J.hasOpenThinking()));break;case"stream_end":{let X=J.completeStream();B.streamEnd(X.wroteAssistantContent,X.openedThinking);break}case"tool_start":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===d)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),A=zH(X.function.name,f),S=WH(X.function.name,f),I=HK(X.function.name,A,S,K);if(I.shouldLockTarget)K.targetLocked=!0;B.phase(I.phase,I.status,I.message,{toolName:X.function.name,target:S}),B.toolStart(X.function.name,A,S,$.toolKind)}catch{B.phase(K.targetLocked?"executing":"searching",K.targetLocked?"hit":"ongoing",K.targetLocked?`Working within target: ${X.function.name}`:`Still searching: ${X.function.name}`,{toolName:X.function.name}),B.toolStart(X.function.name,X.function.name,void 0,$.toolKind)}break}case"tool_progress":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===d)break;B.toolProgress(X.function.name,$.update.message,$.update.progress,$.update.total,$.update.admission);break}case"tool_result":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===d)break;let f;try{let S=JSON.parse(X.function.arguments);f=WH(X.function.name,S)}catch{f=void 0}let A=PH(fH(X.function.name,$.result),GH);if(B.toolResult(X.function.name,A.summary,f,void 0,{success:$.result.success,errorType:$.result.error?.type,errorMessage:$.result.error?.message,background:pJ($.result.metadata)}),A.detail)B.toolDetail(X.function.name,A.detail);break}case"token_usage":B.tokenUsage($.usage);break;case"compaction":B.compacting($);break;case"task_update":B.taskUpdate($.tasks);break;case"goal_frontier_updated":B.goalFrontier($);break;case"turn_recovery":B.turnRecovery($);break;case"structured_output":B.structuredOutput($);break;case"mcp_catalog_changed":B.mcpCatalogChanged($);break;case"mcp_content_changed":B.mcpContentChanged($);break;case"mcp_resource_updated":B.mcpResourceUpdated($);break;case"mcp_connection_changed":B.mcpConnectionChanged($);break;case"mcp_log":B.mcpLog($);break;case"mcp_instructions_changed":B.mcpInstructionsChanged($);break;case"mcp_task_changed":B.mcpTaskChanged($);break;case"project_rules_loaded":B.projectRulesLoaded($);break;case"steering_applied":case"follow_up_started":case"follow_up_queue_changed":case"goal_continuation_started":break;case"goal_updated":B.goal($);break;case"subagent_spawned":case"subagent_completed":B.subagent($);break;case"model_fallback":B.modelFallback($);break;case"provider_admission":B.providerAdmission($);break;case"provider_retry":B.providerRetry($);break;case"provider_circuit":B.providerCircuit($);break;case"provider_stall":B.providerStall($);break;case"provider_recovery":B.providerRecovery($);break;case"turn_activity":B.turnActivity($);break;case"action_stationarity":B.actionStationarity($);break;case"turn_start":if($.turn===1)K.targetLocked=!1;B.phase("turn",K.targetLocked?"hit":"ongoing",`Turn ${$.turn} started`,{turn:$.turn});break;default:{let X=$}}await v()});if(m.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(m.metadata?.recoveryAttention)return B.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);if(!m.success)return B.error(`Error: ${m.error?.message??"Agent execution failed"}`),await E(1);return B.phase("completed","done","Headless run completed"),await E(0)}catch(N){if(!T){if(J.hasOpenThinking()&&q==="text")p.stderr.write(`
|
|
6
|
-
`);B.error(`Error: ${tJ(N)}`)}return await E(1)}finally{x?.(),j?.();try{await D?.dispose()}finally{F.close(),P.dispose()}}}async function OK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":K,"max-turns":D,...x}=TH,j=uJ(dJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([bH,yH,IH]);return sJ(j),await j.parse(),!0}export{JK as runHeadless,OK as handleHeadlessMode,aJ as HeadlessOptionsSchema};
|