blade-code 0.10.14 → 0.10.15
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-wj4cjb73.js → chunk-09k2b1tw.js} +1 -1
- package/dist/{chunk-0hbvc51n.js → chunk-0z7rg4f3.js} +1 -1
- package/dist/{chunk-sntbbkbf.js → chunk-1amhvwmj.js} +2 -2
- package/dist/chunk-1c9rkm57.js +1 -0
- package/dist/{chunk-r6bha0vm.js → chunk-25abj6rx.js} +1 -1
- package/dist/{chunk-xk7svrdb.js → chunk-2cqsqrxx.js} +1 -1
- package/dist/{chunk-m088381q.js → chunk-3m8pschr.js} +1 -1
- package/dist/{chunk-avsv4e5g.js → chunk-5psydp1v.js} +1 -1
- package/dist/{chunk-hpbyvwhm.js → chunk-5tpjb8yn.js} +1 -1
- package/dist/{chunk-snv4bpbv.js → chunk-5wecprcp.js} +1 -1
- package/dist/chunk-67vf8r5v.js +6 -0
- package/dist/{chunk-3be2feze.js → chunk-6y9w5296.js} +1 -1
- package/dist/{chunk-hrmfhv8k.js → chunk-7bq9p4ab.js} +1 -1
- package/dist/{chunk-se1tfys3.js → chunk-7x5cqfy7.js} +1 -1
- package/dist/{chunk-wznyzdtg.js → chunk-a170cgzr.js} +1 -1
- package/dist/{chunk-321n9hem.js → chunk-afxpp33r.js} +1 -1
- package/dist/{chunk-j7k5x43d.js → chunk-agdamn30.js} +1 -1
- package/dist/{chunk-kesgbws4.js → chunk-csn0epd2.js} +1 -1
- package/dist/chunk-d7976m5f.js +5 -0
- package/dist/{chunk-8y2zs0p0.js → chunk-eav8jpk1.js} +2 -2
- package/dist/{chunk-8zr7h97n.js → chunk-ee7an1kq.js} +1 -1
- package/dist/{chunk-9ajyeqa7.js → chunk-jjy8sg10.js} +1 -1
- package/dist/{chunk-mcqe9km3.js → chunk-k47f7zqm.js} +1 -1
- package/dist/{chunk-2z6261pz.js → chunk-m4f213hk.js} +1 -1
- package/dist/{chunk-4rn3r12e.js → chunk-mc29y7tj.js} +2 -2
- package/dist/{chunk-3jnhd81j.js → chunk-n72www7h.js} +3 -3
- package/dist/{chunk-cyhmfcqq.js → chunk-nfqsnkbt.js} +47 -47
- package/dist/{chunk-zvt8ngpt.js → chunk-ng8a4btc.js} +1 -1
- package/dist/{chunk-m2b2w90y.js → chunk-qpd1jmm4.js} +1 -1
- package/dist/{chunk-e0y9nb0a.js → chunk-t6cmqsdj.js} +1 -1
- package/dist/{chunk-k5fw5abr.js → chunk-wz3z8908.js} +1 -1
- package/dist/{chunk-rbph12qe.js → chunk-x1qw695m.js} +3 -3
- package/dist/{chunk-pt0en61h.js → chunk-zmg66vp7.js} +1 -1
- package/dist/{chunk-2cgcht30.js → chunk-zn2cec1d.js} +1 -1
- package/dist/{chunk-xq403rac.js → chunk-zn7c21zj.js} +3 -3
- package/dist/web/assets/{ChatView-CxSysoN5.js → ChatView-rHWZ9qCy.js} +5 -5
- package/dist/web/assets/{CodeBlockHighlighter-a5UaDQQg.js → CodeBlockHighlighter-KpN8jpS4.js} +1 -1
- package/dist/web/assets/{FilePreview-CvGTS9CJ.js → FilePreview-BbEcYewq.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-D50Cw9OM.js → MarkdownRenderer-Cpqkv5Ml.js} +3 -3
- package/dist/web/assets/{SettingsModal-DtREOjs-.js → SettingsModal-D6NZP8vM.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BlMvq8mt.js → TaskSwitcher-cT1qKR6s.js} +1 -1
- package/dist/web/assets/{TerminalPanel-B8LccKzq.js → TerminalPanel-0MehdzKr.js} +1 -1
- package/dist/web/assets/index-BYd4kNGp.js +11 -0
- package/dist/web/assets/{session-events-_Kir2HH_.js → session-events-BH7O5JJl.js} +5 -5
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-99tdg2ny.js +0 -1
- package/dist/chunk-g3w00xb7.js +0 -5
- package/dist/chunk-qb076ca2.js +0 -6
- package/dist/web/assets/index-CQP8XT9a.js +0 -11
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ac as u,bc as qq,cc as e0,dc as Gq,ec as v,fc as $$,gc as Lq,hc as q$,ic as G$,jc as L$,lc as f0,oc as Z$,pc as Zq}from"./chunk-4hawehmd.js";import{od as K0}from"./chunk-8j01ssaf.js";import{Td as B0}from"./chunk-heqs3xan.js";import{ae as I$}from"./chunk-7wjy6kgt.js";import{ee as U0}from"./chunk-4dq9y7zn.js";import{cf as e$,df as $q}from"./chunk-f4z3gkbs.js";import{if as H$}from"./chunk-5s123nbs.js";import{of as V0,rf as x0}from"./chunk-dsj62dcg.js";import{vf as l}from"./chunk-
|
|
1
|
+
import{ac as u,bc as qq,cc as e0,dc as Gq,ec as v,fc as $$,gc as Lq,hc as q$,ic as G$,jc as L$,lc as f0,oc as Z$,pc as Zq}from"./chunk-4hawehmd.js";import{od as K0}from"./chunk-8j01ssaf.js";import{Td as B0}from"./chunk-heqs3xan.js";import{ae as I$}from"./chunk-7wjy6kgt.js";import{ee as U0}from"./chunk-4dq9y7zn.js";import{cf as e$,df as $q}from"./chunk-f4z3gkbs.js";import{if as H$}from"./chunk-5s123nbs.js";import{of as V0,rf as x0}from"./chunk-dsj62dcg.js";import{vf as l}from"./chunk-7x5cqfy7.js";import{Cf as s$,Df as H0,Ff as f,Gf as m,If as s0,Jf as c,Kf as J0}from"./chunk-363pgv1e.js";import{readdir as l$,readFile as e,rm as R0,stat as oq}from"node:fs/promises";import*as F from"node:path";import{nanoid as S}from"nanoid";import{createHash as Kq,randomUUID as Bq}from"node:crypto";import*as I from"node:fs/promises";import*as X0 from"node:path";var X$=1;function Yq($,q){let G=Kq("sha256").update(q).digest("hex");return X0.join(H0($),".locks",`${G}.lock`)}function F0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function S0($){try{let q=JSON.parse(await I.readFile($,"utf8"));if(q.version!==X$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function N$($){let q=await S0($);if(q)return q;return await new Promise((G)=>setTimeout(G,10)),S0($)}function Nq($){try{return process.kill($,0),!0}catch(q){return F0(q,"EPERM")}}async function F$($,q){let G;try{return G=await I.open($,"wx",384),await G.writeFile(`${JSON.stringify(q)}
|
|
2
2
|
`,"utf8"),!0}catch(L){if(F0(L,"EEXIST"))return!1;if(G)await I.unlink($).catch(()=>{return});throw L}finally{await G?.close().catch(()=>{return})}}class n extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class i{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=H$()){let G=Yq(q,$),L={version:X$,sessionId:$,ownerId:Bq(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await I.mkdir(X0.dirname(G),{recursive:!0,mode:448}),await F$(G,L))return new i(G,L);let J=await N$(G);if(J&&Nq(J.pid))throw new n(J.pid);if(await I.unlink(G).catch((Z)=>{if(!F0(Z,"ENOENT"))throw Z}),await F$(G,L))return new i(G,L);throw new n((await N$(G))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await S0(this.filePath))?.ownerId!==this.record.ownerId)return;await I.unlink(this.filePath).catch((q)=>{if(!F0(q,"ENOENT"))throw q})}}function Fq($,q){for(let G of $){if(G.type!=="part_created"||G.data.partType!=="tool_result")continue;let L=G.data.payload;if(!L||typeof L!=="object"||Array.isArray(L))continue;let J=L;if(J.toolCallId===q||G.data.partId===q||G.data.messageId===q)return J}return}function W$($){let q=u($),G=new Map;for(let L of q){if(L.type==="interaction_requested"){G.set(L.data.requestId,{request:L.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(L.type==="interaction_responded"){let J=G.get(L.data.requestId);if(J)J.response=L.data;continue}if(L.type==="interaction_recovered"){let J=G.get(L.data.requestId);if(J)J.recovery=L.data}}for(let L of G.values()){let J=Fq(q,L.request.toolCallId);L.hasToolResult=J!==void 0;let Z=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;L.hasRecoveryToolResult=Z?.interactionRecovery===!0&&Z.requestId===L.request.requestId}return[...G.values()]}function T$($){return W$($).reverse().find((q)=>!q.response&&!q.recovery)}function z1($){let q=new Map;for(let G of W$($))q.set(G.request.toolCallId,G);return[...q.values()].filter((G)=>G.response&&!G.recovery&&(!G.hasToolResult||G.hasRecoveryToolResult))}function U$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function W0($){let q=new Map,G=[];for(let L of $){if(L.type==="review_started"){if(!q.has(L.data.reviewId))G.push(L.data.reviewId),q.set(L.data.reviewId,{start:L.data});continue}if(L.type!=="review_completed")continue;let J=q.get(L.data.reviewId);if(J&&J.completion===void 0)J.completion=L.data}return G.map((L)=>q.get(L)).filter((L)=>L!==void 0)}function _1($){return W0($).reverse().find((q)=>q.completion===void 0)}function m0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function O$($,q){let G=["## Code Review","",`Target: ${$.target.label}`,`Status: ${m0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)G.push("","No actionable findings.");else{G.push("","### Findings");for(let[L,J]of q.findings.entries()){let Z=J.codeLocation.lineStart===J.codeLocation.lineEnd?`${J.codeLocation.lineStart}`:`${J.codeLocation.lineStart}-${J.codeLocation.lineEnd}`;G.push("",`${L+1}. ${J.title}`,` ${J.codeLocation.path}:L${Z} · confidence ${J.confidenceScore.toFixed(2)}`,` ${J.body}`)}}if(q.error)G.push("",`Error: ${q.error}`);return G.join(`
|
|
3
3
|
`)}function C$($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((G)=>({title:G.title,body:G.body,priority:G.priority,confidenceScore:G.confidenceScore,codeLocation:{...G.codeLocation}})),...q.error?{error:q.error}:{}}}var I0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function Hq($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function Xq($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";return"runtime"}function Wq($){return{code:$,...I0[$]}}function v0($){return Wq(Xq(Hq($)))}function P0($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in I0))return!1;let G=I0[q.code];return q.message===G.message&&q.retryable===G.retryable}import{promises as G0,realpathSync as Uq}from"node:fs";import T0 from"node:path";import*as o from"fs/promises";import*as O from"path";var z$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class u0{static normalize($,q){let G=O.isAbsolute($)?$:O.resolve(q,$),L=O.normalize(G),J=O.normalize(q);if(!this.isWithinWorkspace(L,J))throw new d(`Path outside workspace: ${$} (resolved to ${L}, workspace: ${J})`,"PATH_OUTSIDE_WORKSPACE");return L}static checkRestricted($){let q=$.split(O.sep);for(let G of z$)if(q.includes(G))throw new d(`Access denied: "${G}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let G=this.normalize($,q);this.checkRestricted(G);try{await o.access(G)}catch(L){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return G}static async resolveSymlink($,q){try{let G=await o.realpath($),L=await o.realpath(q);if(!this.isWithinWorkspace(G,L))throw new d(`Symlink points outside workspace: ${$} -> ${G}`,"SYMLINK_OUTSIDE_WORKSPACE");return G}catch(G){if(G instanceof d)throw G;return $}}static getRelativePath($,q){return O.relative(q,$)}static isWithinWorkspace($,q){let G=O.resolve($),L=O.resolve(q),J=O.relative(L,G);return J===""||J!==".."&&!J.startsWith(`..${O.sep}`)&&!O.isAbsolute(J)}static async isWithinWorkspaceResolved($,q){let G=O.resolve(q),L=O.isAbsolute($)?O.resolve($):O.resolve(G,$);if(!this.isWithinWorkspace(L,G))return!1;let J;try{J=await o.realpath(G)}catch{return!1}let Z=L;while(!0){try{let V=await o.realpath(Z);return this.isWithinWorkspace(V,J)}catch(V){let B=V.code;if(B!=="ENOENT"&&B!=="ENOTDIR")return!1}let Q=O.dirname(Z);if(Q===Z)return!1;Z=Q}}static isRestricted($){let q=$.split(O.sep);return z$.some((G)=>q.includes(G))}}var L0=U0("Tool");class h{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}async recordFileRead($,q){try{let G=await G0.stat($),L={filePath:T0.resolve($),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(L),await this.recordAliases($,L.filePath),L0.debug(`记录文件读取: ${$}`)}catch(G){L0.warn(`记录文件读取失败: ${$}`,G)}}async recordFileEdit($,q,G="edit"){try{let L=await G0.stat($),J={filePath:T0.resolve($),accessTime:Date.now(),mtime:L.mtimeMs,sessionId:q,lastOperation:G};this.setRecord(J),await this.recordAliases($,J.filePath),L0.debug(`记录文件${G==="edit"?"编辑":"写入"}: ${$}`)}catch(L){L0.warn(`记录文件${G==="edit"?"编辑":"写入"}失败: ${$}`,L)}}hasFileBeenRead($,q){let G=this.accessedFiles.get(this.resolveTrackedPath($));if(!G)return!1;return q?G.has(q):G.size>0}async checkFileModification($,q){let G=this.getFileRecord($,q);if(!G)return{modified:!1,message:"文件未被跟踪"};try{let L=await G0.stat($);if(Math.abs(L.mtimeMs-G.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(G.accessTime).toISOString()}, 当前修改时间: ${L.mtime.toISOString()})`};return{modified:!1}}catch(L){let J=L;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification($,q){let G=this.getFileRecord($,q);if(!G)return{isExternal:!1,message:"文件未被跟踪"};try{let L=await G0.stat($);if(L.mtimeMs-G.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(G.accessTime).toISOString()} (${G.lastOperation}) 之后被外部程序修改(当前修改时间: ${L.mtime.toISOString()})`};return{isExternal:!1}}catch(L){let J=L;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return L0.warn(`检查文件外部修改失败: ${$}`,L),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord($,q){let G=this.accessedFiles.get(this.resolveTrackedPath($));if(!G)return;if(q)return G.get(q);return[...G.values()].sort((L,J)=>J.accessTime-L.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let G=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(G),this.removeAliases(G);return}let L=this.accessedFiles.get(G);if(L?.delete(q),L?.size===0)this.accessedFiles.delete(G),this.removeAliases(G)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[G,L]of this.accessedFiles.entries()){if(q&&!u0.isWithinWorkspace(G,q))continue;if(L.delete($),L.size===0)this.accessedFiles.delete(G),this.removeAliases(G)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){h.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(T0.resolve($),q);let G=await G0.realpath($).catch(()=>{return});if(G)this.pathAliases.set(G,q)}resolveTrackedPath($){let q=T0.resolve($);if(this.accessedFiles.has(q))return q;let G=this.pathAliases.get(q);if(G)return G;try{let L=Uq.native(q);return this.pathAliases.get(L)??L}catch{return q}}removeAliases($){for(let[q,G]of this.pathAliases)if(G===$)this.pathAliases.delete(q)}}import*as Z0 from"node:crypto";import{promises as X}from"node:fs";import*as T from"node:path";import h0 from"write-file-atomic";var D$="missing";class O0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(f($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!T.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?T.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=J0();this.snapshotDir=T.join(q,"file-history",this.sessionId),this.manifestPath=T.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await X.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=J0(),q=await X.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),G=Z0.createHash("sha256").update(q).digest("hex").slice(0,24),L=T.join($,"file-history",this.sessionId),J=T.join($,"file-history","workspaces",G,this.sessionId),Z=T.join(J,"manifest.json");try{await X.access(Z)}catch{await this.migrateLegacySnapshotDir(L,J,q)}this.snapshotDir=J,this.manifestPath=Z}async migrateLegacySnapshotDir($,q,G){let L;try{L=JSON.parse(await X.readFile(T.join($,"manifest.json"),"utf8"))}catch{return}if(L.schemaVersion!==1||!Array.isArray(L.snapshots)||!L.snapshots.every((J)=>this.isWithinWorkspace(J.filePath,G)))return;await X.mkdir(T.dirname(q),{recursive:!0,mode:493});try{await X.rename($,q)}catch(J){let Z=J.code;if(Z!=="ENOENT"&&Z!=="EEXIST"&&Z!=="ENOTEMPTY")throw J}}isWithinWorkspace($,q){if(!T.isAbsolute($))return!1;let G=T.relative(q,T.resolve($));return G===""||G!==".."&&!G.startsWith(`..${T.sep}`)&&!T.isAbsolute(G)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let G=await this.resolveFileIdentity($),L=!0;try{await X.access(G)}catch{L=!1}let J=this.trackedFileBackups.get(G),Z=J?J.version+1:1,Q=this.generateFileHash(G,Z),V=this.getSnapshotPath(Q,Z),B=new Date;if(L){let K=await X.readFile(G);await X.writeFile(V,K)}let x={backupFileName:Q,version:Z,backupTime:B};return this.trackedFileBackups.set(G,x),this.snapshots.push({messageId:q,backupFileName:Q,timestamp:B,filePath:G,version:Z,existedBefore:L}),await this.cleanupOldSnapshots(G),await this.persistManifest(),x}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let G=await this.resolveFileIdentity($),L=this.snapshots.find((J)=>J.filePath===G&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!L)throw Error(`未找到待完成的快照: ${G}`);L.postEditHash=await this.hashFile(G),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let G=await this.resolveFileIdentity($),L=this.snapshots.find((J)=>J.filePath===G&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!L)return;this.removeSnapshot(L),await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),G=this.snapshots.slice().reverse().find((Z)=>Z.filePath===q&&Z.postEditHash!==void 0);if(!G?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==G.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let J=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let Z=await X.readFile(J);await X.mkdir(T.dirname(q),{recursive:!0}),await X.writeFile(q,Z)}else await X.rm(q,{force:!0});return this.removeSnapshot(G),await X.rm(J,{force:!0}),await this.persistManifest(),G}async restoreSnapshot($,q){let G=await this.resolveFileIdentity($),L=this.snapshots.slice().reverse().find((Z)=>Z.messageId===q&&Z.filePath===G);if(!L)throw Error(`未找到快照: messageId=${q}, filePath=${G}`);let J=this.getSnapshotPath(L.backupFileName,L.version);if(L.existedBefore){let Z=await X.readFile(J);await X.mkdir(T.dirname(G),{recursive:!0}),await X.writeFile(G,Z)}else await X.rm(G,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((G)=>G.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((G)=>G.filePath),snapshotCount:q.reduce((G,L)=>G+L.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let G=new Map;for(let J of q){let Z,Q=!0;try{Z=await X.readFile(J.filePath)}catch(B){if(B.code!=="ENOENT")throw B;Q=!1}if((Z?Z0.createHash("sha256").update(Z).digest("hex"):D$)!==J.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${J.filePath}`);if(G.set(J.filePath,{existed:Q,content:Z}),J.target.existedBefore)await X.access(this.getSnapshotPath(J.target.backupFileName,J.target.version))}let L=[...this.snapshots];try{for(let Z of q)if(Z.target.existedBefore){let Q=await X.readFile(this.getSnapshotPath(Z.target.backupFileName,Z.target.version));await X.mkdir(T.dirname(Z.filePath),{recursive:!0}),await h0(Z.filePath,Q)}else await X.rm(Z.filePath,{force:!0});let J=new Set(q.flatMap((Z)=>Z.selected));this.snapshots=this.snapshots.filter((Z)=>!J.has(Z)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...J].map((Z)=>X.rm(this.getSnapshotPath(Z.backupFileName,Z.version),{force:!0}).catch(()=>{return})))}catch(J){this.snapshots=L,this.rebuildTrackedFileBackups();let Z=[];for(let[Q,V]of G)try{if(V.existed&&V.content)await h0(Q,V.content);else await X.rm(Q,{force:!0})}catch(B){Z.push(B)}if(Z.length>0)throw AggregateError([J,...Z],"快照回退失败且无法完整恢复回退前状态");throw J}return{files:q.map((J)=>J.filePath),snapshotCount:q.reduce((J,Z)=>J+Z.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),G=new Set(q.flatMap((J)=>J.selected));if(G.size===0)return{files:[],snapshotCount:0};let L=[...this.snapshots];this.snapshots=this.snapshots.filter((J)=>!G.has(J)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(J){throw this.snapshots=L,this.rebuildTrackedFileBackups(),J}return await Promise.all([...G].map((J)=>X.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return}))),{files:q.map((J)=>J.filePath),snapshotCount:G.size}}buildRewindPlan($){let q=new Set($),G=this.snapshots.filter((Z)=>Z.postEditHash!==void 0),L=G.filter((Z)=>q.has(Z.messageId));return[...new Set(L.map((Z)=>Z.filePath))].sort().map((Z)=>{let Q=G.filter((K)=>K.filePath===Z),V=Q.filter((K)=>q.has(K.messageId)),B=Q.indexOf(V[0]),x=Q.slice(B);if(x.length!==V.length||x.some((K)=>!q.has(K.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${Z}`);return{filePath:Z,selected:V,target:V[0],latest:V.at(-1)}})}async loadManifest(){try{let $=await X.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(G)=>({...G,filePath:await this.resolveFileIdentity(G.filePath),timestamp:new Date(G.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await X.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await h0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let G=this.snapshots.filter((L)=>L.filePath===$).slice(0,-this.maxSnapshots);for(let L of G)await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),this.removeSnapshot(L)}async cleanup($=0){let q=this.snapshots.slice().sort((L,J)=>J.timestamp.getTime()-L.timestamp.getTime()),G=new Set(q.slice(0,$));for(let L of this.snapshots)if(!G.has(L))await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return T.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=T.resolve($),G=[],L=q;while(!0){try{let Z=await X.realpath(L);return T.join(Z,...G.reverse())}catch(Z){let Q=Z.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")throw Z}let J=T.dirname(L);if(J===L)return q;G.push(T.basename(L)),L=J}}async hashFile($){try{let q=await X.readFile($);return Z0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return D$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let G=Z0.createHash("md5");return G.update(`${$}:${q}`),G.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}import{createHash as Oq}from"node:crypto";import Cq from"ajv";var E$="StructuredOutput",_$=65536,R$=131072,v1=2,f$=20,M$=1000,A$=200;function r($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function b$($,q){if(!r($))throw Error(`${q} must be a JSON object`);let G;try{G=JSON.stringify($)}catch(J){throw Error(`${q} must be JSON-serializable`,{cause:J})}if(G===void 0)throw Error(`${q} must be JSON-serializable`);let L=JSON.parse(G);if(!r(L))throw Error(`${q} must be a JSON object`);return L}function zq($){let q=0,G=0,L=(J,Z)=>{if(q++,q>M$)throw Error(`Output schema exceeds the ${M$} node complexity limit`);if(Z>f$)throw Error(`Output schema exceeds the ${f$} level depth limit`);if(Array.isArray(J)){for(let Q of J)L(Q,Z+1);return}if(!r(J))return;if("$ref"in J){let Q=J.$ref;if(typeof Q!=="string"||!(Q==="#"||Q.startsWith("#/$defs/")||Q.startsWith("#/definitions/")))throw Error("Output schema only supports self-contained local $ref values")}if("properties"in J&&r(J.properties)){if(G+=Object.keys(J.properties).length,G>A$)throw Error(`Output schema exceeds the ${A$} property limit`)}for(let Q of Object.values(J))L(Q,Z+1)};L($,0)}function Dq($){if(!$||$.length===0)return"Structured output does not match the requested schema";return $.slice(0,8).map((q)=>{return`${q.instancePath||"root"}: ${q.message??q.keyword}`}).join("; ")}function _q($){let q=new Cq({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return q.compile($)}catch(G){throw Error(`Invalid output schema: ${G instanceof Error?G.message:String(G)}`)}}function k$($){let q=b$($,"Output schema"),G=JSON.stringify(q);if(Buffer.byteLength(G)>_$)throw Error(`Output schema exceeds ${_$} bytes`);if(q.type!=="object")throw Error('Output schema root type must be "object"');zq(q);let J=_q(q),Z=Oq("sha256").update(G).digest("hex");return{schema:q,schemaDigest:Z,declaration:{name:E$,description:"Submit the final response as an object matching the requested JSON Schema. Call this exactly once after all requested work and verification are complete.",parameters:q,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(Q){let V;try{V=b$(Q,"Structured output")}catch(x){return{success:!1,message:x instanceof Error?x.message:String(x)}}let B=JSON.stringify(V);if(Buffer.byteLength(B)>R$)return{success:!1,message:`Structured output exceeds ${R$} bytes`};if(!J(V))return{success:!1,message:Dq(J.errors)};return{success:!0,output:V}}}}function w$($,q){if(!r($))return;let G=r($.structuredOutput)?$.structuredOutput:$;if(G.schemaDigest!==q.schemaDigest||!("output"in G))return;let L=q.validate(G.output);return L.success?L.output:void 0}function P1($,q){for(let G=$.length-1;G>=0;G--){let L=$[G];if(!L)continue;if(L.role==="user")return;if(L.role==="assistant"){let Q=w$(L.metadata,q);if(Q)return{output:Q,completed:!0};continue}if(L.role!=="tool"||L.name!==E$)continue;let J=r(L.metadata)?L.metadata:void 0,Z=w$(J?.metadata,q);if(Z)return{output:Z,completed:!1}}return}import{createHash as mq}from"node:crypto";import u$ from"node:path";import{StringDecoder as Aq}from"node:string_decoder";function Rq($,q){let G=q;while(G<$.length&&($[G]&192)===128)G+=1;return G}class c0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?Buffer.from($):Buffer.from($);if(q.length===0)return;this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),omittedBytes:this.omittedBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}trimToLimit(){while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let q=this.retainedBytes-this.maxBytes;if($.length<=q){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length;continue}let G=Rq($,q);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G}}}var C0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},a={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},g$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},fq={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},Mq=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:C0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:C0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:a,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:g$},{pattern:/^git\s+(status|branch|remote)/i,config:a},{pattern:/^git\s+(log|diff|show)/i,config:g$},{pattern:/^(ls|dir|tree)\s+/i,config:a,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:a,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:a,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:C0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:C0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:a,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:a,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class l0{static getConfigForCommand($){for(let{pattern:q,config:G,summaryTemplate:L}of Mq)if(q.test($))return{config:G,summaryTemplate:L};return{config:fq}}static truncate($,q){let{config:G,summaryTemplate:L}=this.getConfigForCommand(q);return this.truncateWithConfig($,G,L)}static truncateWithConfig($,q,G){let L=$.length,J=$.split(`
|
|
4
4
|
`),Z=J.length;if(Z<=q.maxLines&&L<=q.maxChars)return{content:$,truncated:!1,originalLines:Z,originalChars:L};let Q=J.slice(0,q.keepHead),V=J.slice(-q.keepTail),B=Z-q.keepHead-q.keepTail,x=Q.join(`
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{ee as R}from"./chunk-4dq9y7zn.js";import{lf as z,nf as _}from"./chunk-s5666ta0.js";import{qf as X}from"./chunk-dsj62dcg.js";var oe={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},N=(e)=>oe[e]||{};var ne=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function A(e){return typeof e==="string"&&ne.has(e)}function Oe(e){if(!e.aborted)return;if(A(e.reason))return e.reason;return"user-cancel"}function Ne(e){if(A(e))return!0;if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e.message.includes("aborted"))return!0;return!1}function U(...e){let t=e.filter(Boolean);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];let o=AbortSignal;if(typeof o.any==="function")return o.any(t);for(let i of t)if(i.aborted)return i;let r=new AbortController,n=new Map;for(let i of t){let a=()=>{r.abort(i.reason);for(let[u,s]of n)u.removeEventListener("abort",s)};n.set(i,a)}for(let[i,a]of n)i.addEventListener("abort",a,{once:!0});return r.signal}function P(e,t,o){let r=o?.throwOnAbort??!1;if(t?.aborted){if(r)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((n,i)=>{let a,u=setTimeout(()=>{if(t&&a)t.removeEventListener("abort",a);n()},e);if(t)a=()=>{if(clearTimeout(u),r)i(new DOMException("Aborted","AbortError"));else n()},t.addEventListener("abort",a,{once:!0})})}var re=R("Chat"),ie={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function E(e){if(typeof e==="string")return e;return e.filter((t)=>t.type==="text").map((t)=>t.text).join(`
|
|
2
|
+
`)}function se(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return re.warn("[PiAIChatService] Invalid historical tool arguments",{value:e}),{}}}function ae(e){let t=e.match(/^data:([^;,]+);base64,(.+)$/s);return t?{mimeType:t[1],data:t[2]}:void 0}async function ue(e,t){let o=ae(e);if(o)return{type:"image",...o};if(!/^https?:\/\//i.test(e))return{type:"text",text:`[Unsupported image source: ${e}]`};let r=await fetch(e,{signal:t});if(!r.ok)throw Error(`Failed to load image ${e}: HTTP ${r.status}`);return{type:"image",mimeType:r.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await r.arrayBuffer()).toString("base64")}}async function j(e,t,o,r,n){let i=e.filter((s)=>s.role==="system").map((s)=>E(s.content)).filter(Boolean).join(`
|
|
3
|
+
|
|
4
|
+
`),a=[];for(let s of e){if(s.role==="system")continue;if(s.role==="user"){let c=t.input.includes("image"),d=typeof s.content==="string"?s.content:await Promise.all(s.content.map((l)=>l.type==="text"?Promise.resolve({type:"text",text:l.text}):c?ue(l.image_url.url,r):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));a.push({role:"user",content:d,timestamp:Date.now()});continue}if(s.role==="assistant"){let c=[];if(s.reasoningContent?.trim())c.push({type:"thinking",thinking:s.reasoningContent});let d=E(s.content);if(d)c.push({type:"text",text:d});for(let l of s.tool_calls??[]){if(!("function"in l))continue;c.push({type:"toolCall",id:l.id,name:l.function.name,arguments:se(l.function.arguments)})}a.push({role:"assistant",content:c,api:t.api,provider:t.provider,model:t.id,usage:ie,stopReason:s.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}a.push({role:"toolResult",toolCallId:s.tool_call_id??"",toolName:s.name??"unknown",content:[{type:"text",text:E(s.content)}],isError:!1,timestamp:Date.now()})}let u=o?.filter((s)=>!n||s.name===n).map((s)=>({name:s.name,description:s.description,parameters:s.parameters,constrainedSampling:s.constrainedSampling}));return{...i?{systemPrompt:i}:{},messages:a,...u?.length?{tools:u}:{}}}function F(e){let t=[];for(let o=0;o<e.length;o++){let r=e[o];if(r.role==="tool")continue;let n=r.role==="assistant"&&r.tool_calls?.length?r.tool_calls:void 0;if(!n){t.push(r);continue}let i=[],a=o+1;while(a<e.length&&e[a].role==="tool")i.push(e[a++]);let u=new Set(n.map((d)=>d.id)),s=i.filter((d)=>d.tool_call_id&&u.has(d.tool_call_id)),c=new Set(s.map((d)=>d.tool_call_id));if(u.size===n.length&&s.length===u.size&&c.size===u.size)t.push(r,...s);o=a-1}return t}function q(e){return e.some((t)=>t.role==="assistant"&&Boolean(t.tool_calls?.length)&&!t.reasoningContent?.trim())}function B(e,t){return{...e,...t.baseUrl?{baseUrl:z(e.api,t.baseUrl)}:{},...t.maxOutputTokens?{maxTokens:t.maxOutputTokens}:{}}}function S(e){let t=e.modelCatalog??_();return{models:t.models,model:B(t.getModel(e.provider,e.model),e)}}function V(e,t){let o=e.modelCatalog??_();return B(o.getModel(t.provider,t.model),e)}var de=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],ce=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],le=["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 me(e){return(e instanceof Error?e.message:String(e)).toLowerCase()}function pe(e){return e!==null&&typeof e==="object"&&"code"in e?e.code:void 0}function fe(e){if(e===null||typeof e!=="object")return;let t=e;for(let o of["status","statusCode"]){let r=t[o];if(typeof r==="number"&&Number.isInteger(r))return r}return}function he(e){let t=e.match(/^(?:error:\s*)?(\d{3})\b/),o=e.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),r=Number(t?.[1]??o?.[1]);return Number.isInteger(r)?r:void 0}function T(e,t){let o=me(e),r=pe(e);if(r==="STREAM_IDLE_TIMEOUT"||e instanceof Error&&e.name==="AbortError"||o.includes("request aborted")||o==="aborted")return{retryable:!1};if(de.some((i)=>o.includes(i))||ce.some((i)=>o.includes(i)))return{retryable:!1};if(t?.shouldRetry==="false")return{retryable:!1,statusCode:t.statusCode};let n=t?.statusCode??fe(e)??he(o);if(t?.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(r==="PROVIDER_STREAM_CLOSED"||o.includes("stream closed before completion")||o.includes("ended without")||o.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:n};if(le.some((i)=>o.includes(i)))return{retryable:!0,reason:"transport",statusCode:n};if(o.includes("timeout")||o.includes("timed out")||o.includes("temporarily unavailable")||o.includes("upstream_error")||o.includes("overloaded")||o.includes("rate limit")||o.includes("too many requests")||o.includes("service unavailable")||o.includes("server error")||o.includes("internal error")||o.includes("please retry")||o.includes("try your request again"))return{retryable:!0,reason:o.includes("rate")||o.includes("too many")?"rate_limit":o.includes("timeout")||o.includes("timed out")?"timeout":"server_error",statusCode:n};return{retryable:!1,statusCode:n}}function ye(e,t){if(!e)return;if(e.retryAfterMs!==void 0){let n=Number.parseFloat(e.retryAfterMs);if(Number.isFinite(n))return Math.max(0,n)}if(e.retryAfter===void 0)return;let o=Number.parseFloat(e.retryAfter);if(Number.isFinite(o))return Math.max(0,o*1000);let r=Date.parse(e.retryAfter);return Number.isFinite(r)?Math.max(0,r-t):void 0}function Y(e,t,o={}){let r=o.now??Date.now(),n=o.maxDelayMs??60000,i=ye(t,r);if(i!==void 0)return Math.min(Math.ceil(i),n);let a=Math.max(0,e-1),u=Math.min(500*2**a,8000),s=Math.max(0,Math.min(1,o.random??Math.random())),c=u*(0.75+s*0.25);return Math.min(Math.round(c),n)}function G(e,t){let o=e.onPayload;e.onPayload=async(r,n)=>{let i=o?await o(r,n):r;return t(i===void 0?r:i,n)}}function ge(e){if(!e.reasoningEnabled)return;return e.reasoningEffort??e.reasoningLevel??"high"}function Ce(e){switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function Me(e,t,o,r){let n=r?void 0:ge(o);if(!n){if(t.api==="anthropic-messages")e.thinkingEnabled=!1;if(t.api==="google-generative-ai"||t.api==="google-vertex")e.thinking={enabled:!1};return}switch(t.api){case"anthropic-messages":e.thinkingEnabled=!0,e.effort=n;break;case"google-generative-ai":case"google-vertex":e.thinking={enabled:!0,level:Ce(n)};break;case"mistral-conversations":e.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":e.reasoning=n;break;default:e.reasoningEffort=n}}function be(e,t,o){if(!o)return;switch(t){case"anthropic-messages":case"bedrock-converse-stream":e.toolChoice={type:"tool",name:o};break;case"openai-completions":case"mistral-conversations":case"pi-messages":e.toolChoice={type:"function",function:{name:o}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":e.toolChoice={type:"function",name:o};break;case"google-generative-ai":case"google-vertex":e.toolChoice="any";break}}function Re(e,t,o){let r=o.serviceTier;if(!r)return;if(t.api==="openai-responses"||t.api==="openai-codex-responses"||t.api==="azure-openai-responses"){e.serviceTier=r;return}if(t.api!=="openai-completions"&&!(t.api==="anthropic-messages"&&r==="fast"))return;G(e,(n)=>{if(!n||typeof n!=="object"||Array.isArray(n))return n;return t.api==="anthropic-messages"?{...n,speed:"fast"}:{...n,service_tier:r}})}function xe(e,t,o){let r=o.responseVerbosity;if(!r)return;if(X(t,r),t.api==="openai-codex-responses"){e.textVerbosity=r;return}G(e,(n)=>{if(!n||typeof n!=="object"||Array.isArray(n))return n;if(t.api==="openai-completions")return{...n,verbosity:r};let i="text"in n&&n.text&&typeof n.text==="object"&&!Array.isArray(n.text)?n.text:{};return{...n,text:{...i,verbosity:r}}})}function $(e,t,o,r,n=!1){let i={apiKey:e.apiKey,headers:e.customHeaders,signal:o,temperature:r?.temperature??e.temperature??0,maxTokens:r?.maxOutputTokens??e.maxOutputTokens,timeoutMs:e.timeout,maxRetries:0,cacheRetention:e.enablePromptCaching?"short":"none"};if(Me(i,t,e,n),be(i,t.api,r?.toolChoice?.toolName),Re(i,t,e),xe(i,t,e),t.api==="azure-openai-responses")i.azureBaseUrl=e.baseUrl,i.azureApiVersion=e.apiVersion,i.azureDeploymentName=t.id;return i}function H(e,t){let o=t.get("x-should-retry");return{statusCode:e,...t.get("retry-after")!==null?{retryAfter:t.get("retry-after")??void 0}:{},...t.get("retry-after-ms")!==null?{retryAfterMs:t.get("retry-after-ms")??void 0}:{},...o==="true"||o==="false"?{shouldRetry:o}:{}}}var ve=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function K(e,t,o){let r=e.onResponse;if(e.onResponse=async(i,a)=>{let u=new Headers(i.headers);o(H(i.status,u)),await r?.(i,a)},!ve.has(t.api)||typeof globalThis.fetch!=="function")return;let n=typeof e.fetch==="function"?e.fetch:globalThis.fetch.bind(globalThis);e.fetch=async(i,a)=>{let u=await n(i,a);return o(H(u.status,u.headers)),u}}function J(e){return{promptTokens:e.input+e.cacheRead+e.cacheWrite,completionTokens:e.output,totalTokens:e.totalTokens,costUsd:e.cost.total,...e.reasoning!==void 0?{reasoningTokens:e.reasoning}:{},...e.cacheWrite>0?{cacheCreationInputTokens:e.cacheWrite}:{},...e.cacheRead>0?{cacheReadInputTokens:e.cacheRead}:{}}}var O=300000,Te=30000;class Z extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(e){super(`Provider stream idle timeout after ${e}ms without an event`);this.timeoutMs=e;this.name="StreamIdleTimeoutError"}}class Q extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function I(e){return e.reason instanceof Error?e.reason:new DOMException("Aborted","AbortError")}function ke(e){return e.idleTimeoutMs&&e.idleTimeoutMs>0?e.idleTimeoutMs:O}function we(e,t){if(t===0)return;let o=t!==void 0&&t>0?t:Te;return Math.max(1,Math.min(o,Math.floor(e/2)))}function Ae(e,t,o){if(o?.aborted)return Promise.reject(I(o));return new Promise((r,n)=>{let i=!1,a=()=>{clearTimeout(d),o?.removeEventListener("abort",c)},u=(l)=>{if(i)return;i=!0,a(),r(l)},s=(l)=>{if(i)return;i=!0,a(),n(l instanceof Error?l:Error(String(l)))},c=()=>{if(o)s(I(o))},d=setTimeout(()=>u({kind:"timer"}),Math.max(0,t));if(o?.addEventListener("abort",c,{once:!0}),o?.aborted){c();return}e.then((l)=>u({kind:"next",result:l}),s)})}async function*Pe(e,t,o){let r=ke(t),n=we(r,t.stallWarningMs);if(t.signal?.aborted)throw I(t.signal);let i=Date.now(),a=Promise.resolve().then(()=>e.next()),u;for(;;){let c=await Ae(a,(u?r:n??r)-(Date.now()-i),t.signal);if(c.kind==="next"){if(u)yield{...u,phase:"recovered",durationMs:Math.max(u.durationMs,Date.now()-i)};return c.result}if(!u&&n!==void 0){o.stallCount++,u={phase:"detected",stallCount:o.stallCount,durationMs:n,warningAfterMs:n,timeoutMs:r,outputStarted:o.outputStarted},yield u;continue}let d=new Z(r);throw t.abort?.(d),d}}async function*ee(e,t,o,r,n={}){let a=e.stream(t,o,r)[Symbol.asyncIterator](),u=0,s=!1,c={stallCount:0,outputStarted:!1};try{while(!0){let d=Pe(a,n,c),l=await d.next();while(!l.done)yield{providerStall:l.value},l=await d.next();let x=l.value;if(x.done)throw new Q;let f=x.value;switch(f.type){case"text_delta":c.outputStarted=!0,yield{content:f.delta};break;case"thinking_delta":c.outputStarted=!0,yield{reasoningContent:f.delta};break;case"toolcall_end":c.outputStarted=!0,yield{toolCalls:[{index:u++,id:f.toolCall.id,type:"function",function:{name:f.toolCall.name,arguments:JSON.stringify(f.toolCall.arguments)}}]};break;case"done":s=!0,yield{finishReason:f.reason,usage:J(f.message.usage)};return;case"error":throw Error(f.error.errorMessage??`Request ${f.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!s)Promise.resolve(a.return?.()).catch(()=>{return})}}var te=R("Chat");function Ee(e){return Boolean(e&&e.role==="user"&&Array.isArray(e.content)&&e.content.some((t)=>t.type==="image_url"))}class D{config;models;model;constructor(e){let t=S(e);this.config={...e,maxContextTokens:t.model.contextWindow,maxOutputTokens:e.maxOutputTokens??t.model.maxTokens},this.models=t.models,this.model=t.model,te.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(e,t,o,r){let n="",i="",a=[],u,s;for await(let c of this.streamChat(e,t,o,r)){n+=c.content??"",i+=c.reasoningContent??"";for(let d of c.toolCalls??[])if(d.id&&d.type==="function"&&d.function?.name)a.push(d);u=c.usage??u,s=c.finishReason??s}return{content:n,...i?{reasoningContent:i}:{},...a.length>0?{toolCalls:a}:{},usage:u,finishReason:s}}async*streamChat(e,t,o,r){let n=r?.toolChoice?.toolName;if(n&&!t?.some((m)=>m.name===n))throw Error(`Required tool is unavailable: ${n}`);let i=F(e);if(i.some((m)=>Ee(m))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let a=Boolean(n)||q(i),u=await j(i,this.model,t,o,n),s,c=(m)=>{s=void 0;let C=new AbortController,h=o?U(o,C.signal):C.signal,M=$(this.config,m,h,r,a);return K(M,m,(y)=>{s=y}),ee(this.models,m,u,M,{idleTimeoutMs:this.config.streamIdleTimeout??O,signal:h,abort:(y)=>C.abort(y)})},d=this.config.maxRetries??2,l=this,x=async function*(m,C){let h,M=!1,y,v;for(let g=0;g<=d;g++)try{let b=!1;for await(let p of c(m)){if(p.providerStall){yield p;continue}if(g>0&&y&&!b)b=!0,yield{providerRetry:{phase:"recovered",attempt:g,maxRetries:d,reason:y,...v!==void 0?{statusCode:v}:{}}};M=!0,C(),yield p}return}catch(b){h=b,l.logIdleTimeout(b,M,m),await l.handleAbort(o);let p=T(b,s);if(M)throw b;if(!p.retryable||!p.reason){if(g>0&&y)yield{providerRetry:{phase:"exhausted",attempt:g,maxRetries:d,reason:y,...v!==void 0?{statusCode:v}:{}}};throw b}if(y=p.reason,v=p.statusCode,g<d){let k=g+1,w=Y(k,s);yield{providerRetry:{phase:"scheduled",attempt:k,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{},delayMs:w,nextRetryAt:Date.now()+w}},await P(w,o,{throwOnAbort:!0}),yield{providerRetry:{phase:"attempt",attempt:k,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{}}}}else yield{providerRetry:{phase:"exhausted",attempt:g,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{}}}}throw h},f,L=!1;try{for await(let m of x(this.model,()=>{L=!0}))yield m;return}catch(m){if(f=m,L||!T(m,s).retryable)throw m}for(let m of this.config.fallbackModels??[]){yield{modelFallback:!0};let C=!1;try{let h=V(this.config,m);for await(let M of x(h,()=>{C=!0}))yield M;return}catch(h){if(f=h,C||!T(h,s).retryable)throw h}}throw f}async handleAbort(e){if(e?.aborted)await P(0,e,{throwOnAbort:!0})}logIdleTimeout(e,t,o){if(e===null||typeof e!=="object"||!("code"in e)||e.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in e)||typeof e.timeoutMs!=="number")return;te.warn("[PiAIChatService] Provider stream idle timeout",{provider:o.provider,model:o.id,timeoutMs:e.timeoutMs,replayBoundaryCrossed:t})}getConfig(){return{...this.config}}updateConfig(e){let t={...this.config,...e},o=S(t);this.config={...t,maxContextTokens:o.model.contextWindow,maxOutputTokens:t.maxOutputTokens??o.model.maxTokens},this.models=o.models,this.model=o.model}}var _e=R("Service");async function ut(e){let t=e;if(t.provider){let o=N(t.provider);if(Object.keys(o).length>0)t={...t,customHeaders:{...o,...t.customHeaders}},_e.debug(`Injected ${t.provider} specific headers:`,Object.keys(o))}return Se(t)}function Se(e){return new D(e)}
|
|
5
|
+
export{Oe as gd,Ne as hd,U as id,D as jd,ut as kd};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-vmq248m7.js";import"./chunk-4dq9y7zn.js";import{Se as Q}from"./chunk-
|
|
2
|
-
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-h6w3ggx9.js"),{SessionService:B}=await import("./chunk-
|
|
1
|
+
import"./chunk-vmq248m7.js";import"./chunk-4dq9y7zn.js";import{Se as Q}from"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as L}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import{Mf as F}from"./chunk-g11hq0e5.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
|
|
2
|
+
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-h6w3ggx9.js"),{SessionService:B}=await import("./chunk-25abj6rx.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
|
|
3
3
|
`);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
|
|
4
4
|
Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{rb as jt,sb as Xt,tb as bn,ub as Tn,vb as fn}from"./chunk-095x2ykj.js";import{$d as Ut}from"./chunk-
|
|
1
|
+
import{rb as jt,sb as Xt,tb as bn,ub as Tn,vb as fn}from"./chunk-095x2ykj.js";import{$d as Ut}from"./chunk-ng8a4btc.js";import{Ae as S,De as yn,Ee as Ht,Fe as Bt,Ge as R,He as qt,ge as xt,he as tn,ie as en,je as zt,ke as B,le as rn,me as gt,ne as mt,pe as dn,qe as En,re as U,se as on,te as pn,ue as cn,ve as lt,we as un,xe as Mn,ye as wn}from"./chunk-7bq9p4ab.js";import{Ye as X,_e as x}from"./chunk-kvx3sb3z.js";import{if as vt}from"./chunk-5s123nbs.js";import{vf as nn,wf as sn}from"./chunk-7x5cqfy7.js";import{Mf as ss}from"./chunk-g11hq0e5.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as R,n as I,o as C,p as v,q as S}from"./chunk-
|
|
1
|
+
import{m as R,n as I,o as C,p as v,q as S}from"./chunk-2cqsqrxx.js";import{F as y,L as w}from"./chunk-x1qw695m.js";import"./chunk-ee7an1kq.js";import"./chunk-p4zt7ts9.js";import{Va as x,hb as U}from"./chunk-mc29y7tj.js";import"./chunk-095x2ykj.js";import{$b as b,Tb as k}from"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import{sc as P}from"./chunk-0z7rg4f3.js";import{uc as h,vc as O,wc as M}from"./chunk-5wecprcp.js";import{xc as z}from"./chunk-632rgzcf.js";import"./chunk-ktf3bpmw.js";import{Uc as N}from"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-d7976m5f.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-m4f213hk.js";import"./chunk-agdamn30.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import{Ue as D}from"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as E}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import g from"yargs";import{hideBin as c}from"yargs/helpers";var m=new Set(Object.values(D));function d(j){if(j&&m.has(j))return j;return}function l(j){return j.command("* [message]","Print response and exit (useful for pipes)",(q)=>q.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).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("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(q)=>{if(!q.p)return;let B=await u(q);process.exit(B)})}async function u(j,q=process){let B;try{await R();let T=await I({message:j.message,_:j._,defaultMessage:"Hello"}),J=await C(T);if(J.mode==="output"){if(J.content)q.stdout.write(`${J.content}
|
|
2
2
|
`);return J.exitCode??0}let K=J.content,X=await v(j),Y=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(Y!==void 0&&X)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:G,messages:F,metadata:V}=await S({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),W=V?.projectPath??E(),Z=d(j.permissionMode)??V?.permissionMode??N()?.permissionMode??"default";await b.setSessionPermissionMode(G,W,Z);let _=await U.cancelPendingNonInteractive(W,G)?await b.loadSession(G,W):F;if(B=await y.create({sessionId:G,workspaceRoot:W,modelId:j.model,permissionMode:Z,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?z(j.agents):void 0,..._.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}}),Y!==void 0){let H=await B.executeUserShellCommand(Y);if(j.outputFormat==="json")q.stdout.write(`${JSON.stringify(H,null,2)}
|
|
3
3
|
`);else if(j.outputFormat==="stream-json")q.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:H.executionId,record:H.record})}
|
|
4
4
|
`);else q.stdout.write(`${k(H.record)}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{C as o}from"./chunk-
|
|
1
|
+
import{C as o}from"./chunk-x1qw695m.js";import{$b as i}from"./chunk-csn0epd2.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
|
|
2
2
|
export{m as s};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Se as F}from"./chunk-
|
|
1
|
+
import{Se as F}from"./chunk-7bq9p4ab.js";import{mf as D,nf as E}from"./chunk-s5666ta0.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
|
|
2
2
|
export{H as qd,Q as rd,T as sd};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{wb as NZ}from"./chunk-095x2ykj.js";import{$b as S$,Ab as I$,Bb as p$,Ib as R1,Kb as j2,Mb as o$,Nb as g0,Ob as a$,xb as T2}from"./chunk-kesgbws4.js";import{ac as E2,dc as d1,ec as V2}from"./chunk-4hawehmd.js";import{fd as EZ}from"./chunk-ybvdac8k.js";import{gd as bZ,hd as R2,id as UZ,kd as v1}from"./chunk-g3w00xb7.js";import{Od as _2,Pd as U2,Sd as _Z}from"./chunk-9tnaads5.js";import{$d as l2}from"./chunk-zvt8ngpt.js";import{ee as B2}from"./chunk-4dq9y7zn.js";import{Ve as PZ}from"./chunk-3aqdjrtm.js";import{if as u}from"./chunk-5s123nbs.js";import{vf as i1}from"./chunk-se1tfys3.js";import{Df as r2,Ff as A1,Gf as J2,Hf as p0,Jf as c1,Lf as l1}from"./chunk-363pgv1e.js";import{Mf as l5}from"./chunk-g11hq0e5.js";function V0($){return $.role==="system"&&Array.isArray($.content)}function A0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class k0{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,Z){this.context=$;let W=$.messages.find(V0);if(this._contextualSystemMessages=$.messages.filter(A0),W)this.systemMessages=[W,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((J)=>!V0(J)&&!A0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!A0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(V0);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!V0(Z)&&!A0(Z))}removeMessages($){this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function B1($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function V1($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function D1($,Z,W){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:W?$.consecutiveContinuations+1:0}}import f2 from"node:path";var hZ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),IZ=/^(LD_.+|DYLD_.+|PATH)$/,j1=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function D0($){let Z=$;while(!0){let W=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!W)break;let J=W[1],K=W[2],Y=J.match(j1);if(!Y)break;let X=Y[1];if(!hZ.has(X))break;Z=K}return Z}function s6($){let Z=$;while(!0){let W=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!W)break;let J=W[1],K=W[2],Y=J.match(j1);if(!Y)break;let X=Y[1];if(IZ.test(X))break;Z=K}return Z}var pZ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function P$($){let Z=$,W=!0;while(W){W=!1;for(let J of pZ){let K=Z.match(J);if(K){Z=Z.slice(K[0].length),W=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),W=!0}return Z}function S0($){let Z=[],W="",J=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){W+=z,Y=!1;continue}if(z==="\\"&&!J){W+=z,Y=!0;continue}if(z==="'"&&!K){J=!J,W+=z;continue}if(z==='"'&&!J){K=!K,W+=z;continue}if(J||K){W+=z;continue}if(z==="|"){if(X+1<$.length&&$[X+1]==="|"){if(W.trim())Z.push(W.trim());W="",X++;continue}return null}if(z===">"||z==="<")return null;if(z==="&"&&X+1<$.length&&$[X+1]==="&"){if(W.trim())Z.push(W.trim());W="",X++;continue}if(z==="&")return null;if(z===";"){if(W.trim())Z.push(W.trim());W="";continue}W+=z}if(W.trim())Z.push(W.trim());return Z.length>0?Z:null}function w1($){let Z=!1,W=!1,J=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(J){J=!1;continue}if(Y==="\\"&&!Z){J=!0;continue}if(Y==="'"&&!W){Z=!Z;continue}if(Y==='"'&&!Z){W=!W;continue}if(Z)continue;if(Y==="$"){let X=$[K+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(Y==="`")return!0;if(W)continue;if(Y==="|")return!0;if(Y===">"||Y==="<")return!0;if(Y==="{"){let X=$.slice(K);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function j0($){let Z=[],W="",J=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){W+=z,Y=!1;continue}if(z==="\\"&&!J){if(Y=!0,K){let Q=$[X+1];if(Q&&'$`"\\'.includes(Q))continue;W+=z,Y=!1}continue}if(z==="'"&&!K){J=!J;continue}if(z==='"'&&!J){K=!K;continue}if(!J&&!K&&/[ \t]/.test(z)){if(W)Z.push(W),W="";continue}W+=z}if(W)Z.push(W);return Z}var gZ=new Set(["npm","pnpm","yarn","bun"]),q1=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),mZ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function dZ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function uZ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function cZ($,Z,W){if(!W||Z.length!==2)return;let J=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!J)return;let K=j0(J[1]??"");if(K.length!==2||K[0]!=="cd")return;let Y=K[1];if(!Y||Y==="-")return;let X=f2.isAbsolute(Y)?f2.resolve(Y):f2.resolve(W,Y);if(!T2.isWithinWorkspace(X,W))return;return J[2]?.trim()||void 0}function c2($,Z){let W=D0(uZ($)),J=S0(W);if(!J||w1(W)||/[\r\n]/.test(W))return!1;let K=J.length===1?J[0]:cZ(W,J,Z);if(!K)return!1;let Y=j0(K);if(Y.length===0||Y.some((V)=>[...mZ].some((j)=>V===j||V.startsWith(`${j}=`))))return!1;let[X,z,Q]=Y;if(gZ.has(X??""))return dZ(z==="run"?Q:z)||z==="--test";if((X==="npx"||X==="bunx")&&q1.has(z??""))return!0;if(q1.has(X??""))return!0;if(X==="node"&&z==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(z??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(z??"")}function W7($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!f2.isAbsolute($);let W=f2.isAbsolute($)?f2.resolve($):f2.resolve(Z,$);return T2.isWithinWorkspace(W,Z)}var E$=B2("Agent"),lZ=3;function b$($,Z,W){if($!=="length")return{action:"none"};if(Z>=lZ)return{action:"truncated"};if(B1(W)==="stop")return E$.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var iZ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],rZ=/```[\s\S]{50,}```/,G1="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",nZ=2;function _$($,Z,W=!0){if(!$||Z>=nZ)return{action:"none"};if(!W&&rZ.test($))return{action:"retry",prompt:G1};let J=$.slice(-200),K=J.match(/```/g);if(K&&K.length%2!==0)return{action:"none"};if(iZ.some((X)=>X.test(J)))return{action:"retry",prompt:G1};return{action:"none"}}var oZ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],U1={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},aZ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},sZ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",tZ="Required verification did not run successfully before the retry limit.",eZ=3;function F1($,Z,W,J){if(!W.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof W.metadata?.command==="string"&&W.metadata.exit_code===0&&c2(W.metadata.command,J)){$.add(W.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let K=W.metadata?.verificationCommands;if(!Array.isArray(K))return;for(let Y of K)if(typeof Y==="string"&&c2(Y,J))$.add(Y)}function N$($,Z,W){if(!$||!oZ.some((Q)=>Q.test($)))return{action:"none"};let J=Object.keys(U1).filter((Q)=>U1[Q].test($)),K=[...Z],Y=J.filter((Q)=>!K.some((V)=>aZ[Q].test(V)));if(J.length>0?Y.length===0:K.some((Q)=>c2(Q)))return{action:"none"};if(W>=eZ)return{action:"fail",message:tZ};let z=J.length>1&&Y.length>0?` Missing successful verification categories: ${Y.join(", ")}.`:"";return{action:"retry",prompt:`${sZ}${z}`}}var $5=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],L1=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function y1($){return typeof $==="string"&&L1.some((Z)=>Z.test($))}var Z5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],W5=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function J5($){if(typeof $!=="string")return;if(W5.some((Z)=>Z.test($)))return"multiple-allowed";return Z5.some((Z)=>Z.test($))?"required":void 0}function f0($){for(let Z of $){let W=J5(Z);if(W!==void 0)return W==="required"}return!1}var K5="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",Y5="Required delegation did not complete before the retry limit.",X5=3;function P1($,Z,W){let J=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),K=f0(J),Y=!1;if(!K)for(let X of J){if(L1.some((z)=>z.test(X)))break;if($5.some((z)=>z.test(X))){Y=!0;break}}if(J.length===0||!K&&!Y||Z.has("Task"))return{action:"none"};if(W>=X5)return{action:"fail",message:Y5};return{action:"retry",prompt:K5}}var z5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function E1($){return H5.reduce((Z,W)=>Z.replace(W," "),$)}function T0($){if(typeof $!=="string")return!1;let Z=E1($);return z5.some((W)=>W.test(Z))}var B5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",V5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",D5="Required worktree lifecycle did not complete before the retry limit.",j5=3;function b1($,Z,W){if(!$)return{action:"none"};let J=E1($);if(!T0(J))return{action:"none"};let K=Q5.some((X)=>X.test(J));if(Z.has("TaskWorktree"))return{action:"none"};let Y=!Z.has("EnterWorktree")?"EnterWorktree":K&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!Y)return{action:"none"};if(W>=j5)return{action:"fail",message:D5};return{action:"retry",tool:Y,prompt:Y==="EnterWorktree"?B5:V5}}var O1=30000;async function A$($){try{let W=l2.getInstance().executeStopHooks({projectDir:$.workspaceRoot??u(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),J,K=new Promise((Y)=>{J=setTimeout(()=>Y("timeout"),O1)});try{let Y=await Promise.race([W,K]);if(Y==="timeout")return E$.warn(`[Loop] Stop hook 超时 (${O1}ms),按 shouldStop: true 处理`),{action:"stop"};let X=Y;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return E$.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function w5($,Z){let W;while(!(W=await $.next()).done)if(Z)await Z(W.value);return W.value}var q5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let W=Z.text;return typeof W==="string"?W:""}return""}).join(" ");return""}function U5($){let Z=$;for(let Q of q5)Z=Z.replace(Q," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let W=Z.replace(/\s+/g," ").trim();if(!W)return"";let J=W.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),K=J&&J[1].length>=6?J[1]:W;if(K=K.trim().replace(/[\s.。!!??,,;;::-]+$/,""),K.length<=60)return K;let Y=K.slice(0,60),X=Y.lastIndexOf(" ");return`${(X>36?Y.slice(0,X):Y).trimEnd()}…`}function _1($){return U5(G5($))}import{EventEmitter as O5}from"events";import N1 from"node:path";function k$($){if(A1($.sessionId),!N1.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:N1.resolve($.projectPath)}}function w7($){let Z=k$($);return JSON.stringify([Z.projectPath,Z.sessionId])}class i2 extends O5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!i2.instance)i2.instance=new i2;return i2.instance}publish($,Z,W,J){let K=k$($);this.emit("event",{sessionId:K.sessionId,projectPath:K.projectPath,type:Z,...J!==void 0?{seq:J}:{},properties:W})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var w0=i2.getInstance();var y2=B2("Agent"),M0=new Set;async function F5($,Z){let W=$.sessionId;if(!W||$.subagentInfo)return;if(M0.has(W))return;if(M0.size>=5000)M0.clear();M0.add(W);try{let J=$.workspaceRoot,K=await S$.findSessionMetadata(W,J);if(!K)return;if(K.title&&K.title.trim())return;let Y=_1(Z);if(!Y)return;await S$.updateSessionMetadata(W,K.projectPath,{title:Y}),w0.publish({sessionId:W,projectPath:K.projectPath},"session.updated",{title:Y})}catch(J){y2.debug?.("[Loop] 自动生成会话标题失败:",J)}}var x$=`<turn_aborted>
|
|
1
|
+
import{wb as NZ}from"./chunk-095x2ykj.js";import{$b as S$,Ab as I$,Bb as p$,Ib as R1,Kb as j2,Mb as o$,Nb as g0,Ob as a$,xb as T2}from"./chunk-csn0epd2.js";import{ac as E2,dc as d1,ec as V2}from"./chunk-4hawehmd.js";import{fd as EZ}from"./chunk-ybvdac8k.js";import{gd as bZ,hd as R2,id as UZ,kd as v1}from"./chunk-d7976m5f.js";import{Od as _2,Pd as U2,Sd as _Z}from"./chunk-9tnaads5.js";import{$d as l2}from"./chunk-ng8a4btc.js";import{ee as B2}from"./chunk-4dq9y7zn.js";import{Ve as PZ}from"./chunk-3aqdjrtm.js";import{if as u}from"./chunk-5s123nbs.js";import{vf as i1}from"./chunk-7x5cqfy7.js";import{Df as r2,Ff as A1,Gf as J2,Hf as p0,Jf as c1,Lf as l1}from"./chunk-363pgv1e.js";import{Mf as l5}from"./chunk-g11hq0e5.js";function V0($){return $.role==="system"&&Array.isArray($.content)}function A0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class k0{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,Z){this.context=$;let W=$.messages.find(V0);if(this._contextualSystemMessages=$.messages.filter(A0),W)this.systemMessages=[W,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((J)=>!V0(J)&&!A0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!A0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(V0);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!V0(Z)&&!A0(Z))}removeMessages($){this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function B1($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function V1($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function D1($,Z,W){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:W?$.consecutiveContinuations+1:0}}import f2 from"node:path";var hZ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),IZ=/^(LD_.+|DYLD_.+|PATH)$/,j1=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function D0($){let Z=$;while(!0){let W=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!W)break;let J=W[1],K=W[2],Y=J.match(j1);if(!Y)break;let X=Y[1];if(!hZ.has(X))break;Z=K}return Z}function s6($){let Z=$;while(!0){let W=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!W)break;let J=W[1],K=W[2],Y=J.match(j1);if(!Y)break;let X=Y[1];if(IZ.test(X))break;Z=K}return Z}var pZ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function P$($){let Z=$,W=!0;while(W){W=!1;for(let J of pZ){let K=Z.match(J);if(K){Z=Z.slice(K[0].length),W=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),W=!0}return Z}function S0($){let Z=[],W="",J=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){W+=z,Y=!1;continue}if(z==="\\"&&!J){W+=z,Y=!0;continue}if(z==="'"&&!K){J=!J,W+=z;continue}if(z==='"'&&!J){K=!K,W+=z;continue}if(J||K){W+=z;continue}if(z==="|"){if(X+1<$.length&&$[X+1]==="|"){if(W.trim())Z.push(W.trim());W="",X++;continue}return null}if(z===">"||z==="<")return null;if(z==="&"&&X+1<$.length&&$[X+1]==="&"){if(W.trim())Z.push(W.trim());W="",X++;continue}if(z==="&")return null;if(z===";"){if(W.trim())Z.push(W.trim());W="";continue}W+=z}if(W.trim())Z.push(W.trim());return Z.length>0?Z:null}function w1($){let Z=!1,W=!1,J=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(J){J=!1;continue}if(Y==="\\"&&!Z){J=!0;continue}if(Y==="'"&&!W){Z=!Z;continue}if(Y==='"'&&!Z){W=!W;continue}if(Z)continue;if(Y==="$"){let X=$[K+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(Y==="`")return!0;if(W)continue;if(Y==="|")return!0;if(Y===">"||Y==="<")return!0;if(Y==="{"){let X=$.slice(K);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function j0($){let Z=[],W="",J=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){W+=z,Y=!1;continue}if(z==="\\"&&!J){if(Y=!0,K){let Q=$[X+1];if(Q&&'$`"\\'.includes(Q))continue;W+=z,Y=!1}continue}if(z==="'"&&!K){J=!J;continue}if(z==='"'&&!J){K=!K;continue}if(!J&&!K&&/[ \t]/.test(z)){if(W)Z.push(W),W="";continue}W+=z}if(W)Z.push(W);return Z}var gZ=new Set(["npm","pnpm","yarn","bun"]),q1=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),mZ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function dZ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function uZ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function cZ($,Z,W){if(!W||Z.length!==2)return;let J=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!J)return;let K=j0(J[1]??"");if(K.length!==2||K[0]!=="cd")return;let Y=K[1];if(!Y||Y==="-")return;let X=f2.isAbsolute(Y)?f2.resolve(Y):f2.resolve(W,Y);if(!T2.isWithinWorkspace(X,W))return;return J[2]?.trim()||void 0}function c2($,Z){let W=D0(uZ($)),J=S0(W);if(!J||w1(W)||/[\r\n]/.test(W))return!1;let K=J.length===1?J[0]:cZ(W,J,Z);if(!K)return!1;let Y=j0(K);if(Y.length===0||Y.some((V)=>[...mZ].some((j)=>V===j||V.startsWith(`${j}=`))))return!1;let[X,z,Q]=Y;if(gZ.has(X??""))return dZ(z==="run"?Q:z)||z==="--test";if((X==="npx"||X==="bunx")&&q1.has(z??""))return!0;if(q1.has(X??""))return!0;if(X==="node"&&z==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(z??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(z??"")}function W7($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!f2.isAbsolute($);let W=f2.isAbsolute($)?f2.resolve($):f2.resolve(Z,$);return T2.isWithinWorkspace(W,Z)}var E$=B2("Agent"),lZ=3;function b$($,Z,W){if($!=="length")return{action:"none"};if(Z>=lZ)return{action:"truncated"};if(B1(W)==="stop")return E$.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var iZ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],rZ=/```[\s\S]{50,}```/,G1="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",nZ=2;function _$($,Z,W=!0){if(!$||Z>=nZ)return{action:"none"};if(!W&&rZ.test($))return{action:"retry",prompt:G1};let J=$.slice(-200),K=J.match(/```/g);if(K&&K.length%2!==0)return{action:"none"};if(iZ.some((X)=>X.test(J)))return{action:"retry",prompt:G1};return{action:"none"}}var oZ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],U1={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},aZ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},sZ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",tZ="Required verification did not run successfully before the retry limit.",eZ=3;function F1($,Z,W,J){if(!W.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof W.metadata?.command==="string"&&W.metadata.exit_code===0&&c2(W.metadata.command,J)){$.add(W.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let K=W.metadata?.verificationCommands;if(!Array.isArray(K))return;for(let Y of K)if(typeof Y==="string"&&c2(Y,J))$.add(Y)}function N$($,Z,W){if(!$||!oZ.some((Q)=>Q.test($)))return{action:"none"};let J=Object.keys(U1).filter((Q)=>U1[Q].test($)),K=[...Z],Y=J.filter((Q)=>!K.some((V)=>aZ[Q].test(V)));if(J.length>0?Y.length===0:K.some((Q)=>c2(Q)))return{action:"none"};if(W>=eZ)return{action:"fail",message:tZ};let z=J.length>1&&Y.length>0?` Missing successful verification categories: ${Y.join(", ")}.`:"";return{action:"retry",prompt:`${sZ}${z}`}}var $5=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],L1=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function y1($){return typeof $==="string"&&L1.some((Z)=>Z.test($))}var Z5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],W5=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function J5($){if(typeof $!=="string")return;if(W5.some((Z)=>Z.test($)))return"multiple-allowed";return Z5.some((Z)=>Z.test($))?"required":void 0}function f0($){for(let Z of $){let W=J5(Z);if(W!==void 0)return W==="required"}return!1}var K5="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",Y5="Required delegation did not complete before the retry limit.",X5=3;function P1($,Z,W){let J=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),K=f0(J),Y=!1;if(!K)for(let X of J){if(L1.some((z)=>z.test(X)))break;if($5.some((z)=>z.test(X))){Y=!0;break}}if(J.length===0||!K&&!Y||Z.has("Task"))return{action:"none"};if(W>=X5)return{action:"fail",message:Y5};return{action:"retry",prompt:K5}}var z5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function E1($){return H5.reduce((Z,W)=>Z.replace(W," "),$)}function T0($){if(typeof $!=="string")return!1;let Z=E1($);return z5.some((W)=>W.test(Z))}var B5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",V5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",D5="Required worktree lifecycle did not complete before the retry limit.",j5=3;function b1($,Z,W){if(!$)return{action:"none"};let J=E1($);if(!T0(J))return{action:"none"};let K=Q5.some((X)=>X.test(J));if(Z.has("TaskWorktree"))return{action:"none"};let Y=!Z.has("EnterWorktree")?"EnterWorktree":K&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!Y)return{action:"none"};if(W>=j5)return{action:"fail",message:D5};return{action:"retry",tool:Y,prompt:Y==="EnterWorktree"?B5:V5}}var O1=30000;async function A$($){try{let W=l2.getInstance().executeStopHooks({projectDir:$.workspaceRoot??u(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),J,K=new Promise((Y)=>{J=setTimeout(()=>Y("timeout"),O1)});try{let Y=await Promise.race([W,K]);if(Y==="timeout")return E$.warn(`[Loop] Stop hook 超时 (${O1}ms),按 shouldStop: true 处理`),{action:"stop"};let X=Y;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return E$.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function w5($,Z){let W;while(!(W=await $.next()).done)if(Z)await Z(W.value);return W.value}var q5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let W=Z.text;return typeof W==="string"?W:""}return""}).join(" ");return""}function U5($){let Z=$;for(let Q of q5)Z=Z.replace(Q," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let W=Z.replace(/\s+/g," ").trim();if(!W)return"";let J=W.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),K=J&&J[1].length>=6?J[1]:W;if(K=K.trim().replace(/[\s.。!!??,,;;::-]+$/,""),K.length<=60)return K;let Y=K.slice(0,60),X=Y.lastIndexOf(" ");return`${(X>36?Y.slice(0,X):Y).trimEnd()}…`}function _1($){return U5(G5($))}import{EventEmitter as O5}from"events";import N1 from"node:path";function k$($){if(A1($.sessionId),!N1.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:N1.resolve($.projectPath)}}function w7($){let Z=k$($);return JSON.stringify([Z.projectPath,Z.sessionId])}class i2 extends O5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!i2.instance)i2.instance=new i2;return i2.instance}publish($,Z,W,J){let K=k$($);this.emit("event",{sessionId:K.sessionId,projectPath:K.projectPath,type:Z,...J!==void 0?{seq:J}:{},properties:W})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var w0=i2.getInstance();var y2=B2("Agent"),M0=new Set;async function F5($,Z){let W=$.sessionId;if(!W||$.subagentInfo)return;if(M0.has(W))return;if(M0.size>=5000)M0.clear();M0.add(W);try{let J=$.workspaceRoot,K=await S$.findSessionMetadata(W,J);if(!K)return;if(K.title&&K.title.trim())return;let Y=_1(Z);if(!Y)return;await S$.updateSessionMetadata(W,K.projectPath,{title:Y}),w0.publish({sessionId:W,projectPath:K.projectPath},"session.updated",{title:Y})}catch(J){y2.debug?.("[Loop] 自动生成会话标题失败:",J)}}var x$=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`;function M2($){return $.executionEngine?.getContextManager()}async function Z2($,Z,W,J=null,K){try{let Y=M2($),X=typeof W==="string"?W.trim()!=="":W.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(Y&&Z.sessionId&&X){let z=await Y.saveMessage(Z.sessionId,"user",W,J,K,Z.subagentInfo);return F5(Z,W),z}}catch(Y){y2.warn("[Loop] 保存用户消息失败:",Y)}return null}async function M($,Z,W,J,K,Y){try{let X=M2($);if(X&&Z.sessionId&&(W.trim()||K?.trim()))return await X.saveMessage(Z.sessionId,"assistant",W,J,Y,Z.subagentInfo,K)}catch(X){y2.warn("[Loop] 保存助手消息失败:",X)}return null}async function k1($,Z,W){try{let J=M2($);if(J&&Z.sessionId)return await J.saveMessage(Z.sessionId,"system",x$,W,void 0,Z.subagentInfo)}catch(J){y2.warn("[Loop] 保存中断边界失败:",J)}return null}async function S1($,Z,W,J,K){try{let Y=M2($);if(!Y||!Z.sessionId||W.length===0)return null;return await Y.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${W.length}" />`,K,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(W.map((X)=>({...X})))),triggerPaths:[...J]},Z.subagentInfo)}catch(Y){y2.warn("[Loop] 保存 contextual project rules provenance 失败:",Y)}return null}async function f$($,Z,W,J,K){try{let Y=M2($);if(Y&&Z.sessionId)return await Y.saveToolUse(Z.sessionId,W,J,K,Z.subagentInfo)}catch(Y){y2.warn("[Loop] 保存工具调用失败:",Y)}return null}async function v0($,Z,W,J,K,Y,X,z,Q){try{let V=M2($);if(V&&Z.sessionId)return await V.saveToolResult(Z.sessionId,W,J,K,Y,X,Z.subagentInfo,z,Q)}catch(V){y2.warn("[Loop] 保存工具结果失败:",V)}return null}async function R0($,Z,W,J){try{let K=M2($);if(K&&Z.sessionId)return await K.saveCompaction(Z.sessionId,W,J,null)}catch(K){y2.warn("[Loop] 保存压缩数据失败:",K)}return null}import{createHash as S6}from"node:crypto";import{promises as S5}from"node:fs";import x5 from"node:path";import{nanoid as P2}from"nanoid";import*as g from"node:fs/promises";import*as v2 from"node:path";var x1={enabled:!0,maxIndexLines:200};var L5="memory",f1="MEMORY.md";class T${memoryDir;config;initialized=!1;constructor($,Z,W){if(W)this.memoryDir=W;else{let J=r2($);this.memoryDir=v2.join(J,L5)}this.config={...x1,...Z}}async initialize(){if(this.initialized)return;await g.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=v2.join(this.memoryDir,f1);try{let Z=await g.readFile($,"utf-8");if(!Z.trim())return null;let W=Z.split(`
|
|
4
4
|
`),K=W.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -140,7 +140,7 @@ When facing complex multi-step tasks:
|
|
|
140
140
|
3. If a step fails, diagnose the root cause rather than repeating the same approach.
|
|
141
141
|
4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
|
|
142
142
|
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function N2($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function yZ($){let Z=$.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let W=JSON.parse(Z);if(typeof W==="object"&&W!==null&&!Array.isArray(W))return W;return null}catch{return null}}function t0($){let Z=yZ($);if(Z)return Z;try{let W=JSON.parse($);return typeof W==="string"?yZ(W):null}catch{return null}}function C6($){let Z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0;if(Z?.contextualProjectRules!==!0)return[];if(!Array.isArray(Z.ruleReferences))throw Error("Invalid contextual project rule provenance");return Z.ruleReferences.map((W)=>{if(!W||typeof W!=="object"||Array.isArray(W))throw Error("Invalid contextual project rule reference");let J=W;if(typeof J.id!=="string"||typeof J.relativePath!=="string"||!["project","local"].includes(String(J.source))||typeof J.contentSha256!=="string"||!/^[a-f0-9]{64}$/u.test(J.contentSha256))throw Error("Invalid contextual project rule reference");return{id:J.id,relativePath:J.relativePath,source:J.source,contentSha256:J.contentSha256}})}function O0($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function h6($){let Z=new Set,W=!1;for(let J of $){if(J.role==="assistant"){if(J.tool_calls&&J.tool_calls.length>0){for(let Y of J.tool_calls)if("function"in Y&&Y.function.name==="Task")Z.add(Y.id)}else if(W)W=!1;continue}if(J.role!=="tool"||J.name!=="Task"||!J.tool_call_id||!Z.has(J.tool_call_id)||typeof J.metadata!=="object"||J.metadata===null||Array.isArray(J.metadata))continue;let K=J.metadata;if(K.toolCallId===J.tool_call_id&&K.toolName==="Task"&&K.error===null)W=!0}return W}function I6($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let z=JSON.parse(J.responseBody)?.error?.message;if(z){let Q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${z}${Q}`}}catch{}let K=$.message,Y=K.match(/Last error:\s*(.+)$/);if(Y)return Y[1];return K}function p6($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((W)=>$.message.toLowerCase().includes(W.toLowerCase()))}function g6($,Z){if(!Z)return"Tool execution failed (no details).";let W=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")W.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")W.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")W.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let J=Z.message??"";if(J.includes("ENOENT")||J.includes("no such file"))W.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(J.includes("EACCES")||J.includes("permission"))W.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(J.includes("not found in file")||J.includes("old_string"))W.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${$} with the exact text.`);else if(J.includes("ENOTDIR"))W.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return W.join(`
|
|
143
|
-
`)}function m6($){if(!($ instanceof Error))return!1;let Z=$.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||$.status===413}function d6($,Z){let W=Z,J=W.index??0;if(!$.has(J))$.set(J,{id:W.id||"",name:W.function?.name||"",arguments:""});let K=$.get(J);if(W.id&&!K.id)K.id=W.id;if(W.function?.name&&!K.name)K.name=W.function.name;if(W.function?.arguments)K.arguments+=W.function.arguments}function u6($){if($.size===0)return;return Array.from($.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*c6($,Z,W,J,K,Y){let X="",z="",Q,V,j=new Map;try{let q=$.chatService.streamChat(Z,W,J,K),O=0;for await(let D of q){if(J?.aborted)break;if(D.providerRetry){yield{kind:"provider_retry",...D.providerRetry};continue}if(O++,D.modelFallback){Y?.discard(),X="",z="",Q=void 0,V=void 0,j.clear(),O=0,yield{kind:"model_fallback"};continue}if(D.content)X+=D.content,yield{kind:"content_delta",delta:D.content};if(D.reasoningContent)z+=D.reasoningContent,yield{kind:"thinking_delta",delta:D.reasoningContent};if(D.usage)Q=D.usage;if(D.toolCalls){for(let T of D.toolCalls)if(d6(j,T),Y){let k=T.index??0,N=j.get(k);if(N&&N.id&&N.name)try{let w2=t0(N.arguments);if(w2===null)continue;let t={id:N.id,type:"function",function:{name:N.name,arguments:N.arguments}},C=$.toolExecutor.getRegistry().get(N.name)?.kind;if(Y.addTool(t,w2)==="prelaunched")yield{kind:"tool_start",toolCall:t,toolKind:C}}catch{}}}if(D.finishReason){V=D.finishReason;break}}if(O===0&&!J?.aborted&&X.length===0&&j.size===0)return I.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),Y?.discard(),{...await $.chatService.chat(Z,W,J,K),_nonStreamingFallback:!0};return{content:X,reasoningContent:z||void 0,toolCalls:u6(j),usage:Q,finishReason:V}}catch(q){if(p6(q))return I.warn("[Loop] 流式请求失败,降级到非流式模式"),Y?.discard(),{...await $.chatService.chat(Z,W,J,K),_nonStreamingFallback:!0};throw q}}async function*AZ($,Z,W,J,K,Y,X,z){if(J===void 0)return I.debug(`[Loop] [轮次 ${W}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let Q=C1(Z.messages,Y);if(Q)Z.messages=Q.messages,I.debug(`[Loop] [轮次 ${W}] MicroCompact: 清理 ${Q.snippedCount} 轮旧工具结果(缓存已过期)`);let V=G0(Z.messages),j=!1;if(V.snippedCount>0)j=!0,I.debug(`[Loop] [轮次 ${W}] Snip 压缩: 移除 ${V.snippedCount} 轮旧工具调用,释放约 ${V.estimatedTokensFreed} tokens`);let q=$.chatService.getConfig(),O=q.model,D=q.maxContextTokens??0,T=q.maxOutputTokens??$.config.maxOutputTokens??Math.min(Math.max(Math.floor(D*x6),f6),T6),d=D-T,k=Math.floor(d*0.8);if(I.debug(`[Loop] [轮次 ${W}] 压缩检查:`,{promptTokens:J,maxContextTokens:D,maxOutputTokens:T,availableForInput:d,threshold:k,shouldCompact:J>=k}),J<k){if(j)Z.messages=V.messages;return j?"snipped":"none"}let N=z?.lastCompactionTurn===void 0?void 0:W-z.lastCompactionTurn,w2=N!==void 0&&N<=M6,t=Math.floor(d*v6);if(w2&&J<t){if(j)Z.messages=V.messages;return I.debug(`[Loop] [轮次 ${W}] 跳过连续 LLM 压缩,距离上次压缩 ${N} 轮`),j?"snipped":"none"}I.debug(W===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${W}] 触发循环内自动压缩`),yield{kind:"compaction",phase:"start"};try{let G=j?V.messages:Z.messages,C=await n2.compact(G,{trigger:"auto",modelName:O,modelProvider:q.provider,maxContextTokens:D,apiKey:q.apiKey,baseURL:q.baseUrl,actualPreTokens:J,signal:K,activeTask:X,workspaceRoot:Z.workspaceRoot||u(),sessionId:Z.sessionId});if(C.usage)yield{kind:"token_usage",usage:s0(C.usage,D)};if(Z.messages=C.compactedMessages,z)z.lastCompactionTurn=W;if(C.success)I.debug(`[Loop] [轮次 ${W}] 压缩完成: ${C.preTokens} -> ${C.postTokens} tokens`);else I.warn(`[Loop] [轮次 ${W}] 压缩使用降级策略: ${C.preTokens} -> ${C.postTokens} tokens`);return await R0($,Z,C.summary,{trigger:"auto",preTokens:C.preTokens,postTokens:C.postTokens,filesIncluded:C.filesIncluded}),"compacted"}catch(G){if(R2(G))return I.debug(`[Loop] [轮次 ${W}] 压缩被中止`),"none";if(j)Z.messages=V.messages;return I.error(`[Loop] [轮次 ${W}] 压缩失败,继续执行`,G),j?"snipped":"none"}finally{yield{kind:"compaction",phase:"end"}}}function l6($,Z,W,J){let K=J?bZ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(K==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-W,abortReason:K}}}async function*i6($,Z,W,J,K){let Y=Date.now(),X=0,z=[],Q=null,V=!1,j=(q,O,D)=>{return V=!0,l6(q,O,Y,D)};try{let q=$.toolExecutor.getRegistry(),O=W.permissionMode,D=J?.outputSchema?g0(J.outputSchema):void 0,T=()=>{let L=$.applySkillToolRestrictions(q.getFunctionDeclarationsByMode(O));if(!D)return L;return[...L.filter((y)=>y.name!==j2),D.declaration]},d=t1(),k=KZ(),N=K;if(typeof q.getDeferredToolsListing==="function"){let L=q.getDeferredToolsListing();if(L&&N)N=`${N}
|
|
143
|
+
`)}function m6($){if(!($ instanceof Error))return!1;let Z=$.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||$.status===413}function d6($,Z){let W=Z,J=W.index??0;if(!$.has(J))$.set(J,{id:W.id||"",name:W.function?.name||"",arguments:""});let K=$.get(J);if(W.id&&!K.id)K.id=W.id;if(W.function?.name&&!K.name)K.name=W.function.name;if(W.function?.arguments)K.arguments+=W.function.arguments}function u6($){if($.size===0)return;return Array.from($.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*c6($,Z,W,J,K,Y){let X="",z="",Q,V,j=new Map;try{let q=$.chatService.streamChat(Z,W,J,K),O=0;for await(let D of q){if(J?.aborted)break;if(D.providerRetry){yield{kind:"provider_retry",...D.providerRetry};continue}if(D.providerStall){yield{kind:"provider_stall",...D.providerStall};continue}if(O++,D.modelFallback){Y?.discard(),X="",z="",Q=void 0,V=void 0,j.clear(),O=0,yield{kind:"model_fallback"};continue}if(D.content)X+=D.content,yield{kind:"content_delta",delta:D.content};if(D.reasoningContent)z+=D.reasoningContent,yield{kind:"thinking_delta",delta:D.reasoningContent};if(D.usage)Q=D.usage;if(D.toolCalls){for(let T of D.toolCalls)if(d6(j,T),Y){let k=T.index??0,N=j.get(k);if(N&&N.id&&N.name)try{let w2=t0(N.arguments);if(w2===null)continue;let t={id:N.id,type:"function",function:{name:N.name,arguments:N.arguments}},C=$.toolExecutor.getRegistry().get(N.name)?.kind;if(Y.addTool(t,w2)==="prelaunched")yield{kind:"tool_start",toolCall:t,toolKind:C}}catch{}}}if(D.finishReason){V=D.finishReason;break}}if(O===0&&!J?.aborted&&X.length===0&&j.size===0)return I.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),Y?.discard(),{...await $.chatService.chat(Z,W,J,K),_nonStreamingFallback:!0};return{content:X,reasoningContent:z||void 0,toolCalls:u6(j),usage:Q,finishReason:V}}catch(q){if(p6(q))return I.warn("[Loop] 流式请求失败,降级到非流式模式"),Y?.discard(),{...await $.chatService.chat(Z,W,J,K),_nonStreamingFallback:!0};throw q}}async function*AZ($,Z,W,J,K,Y,X,z){if(J===void 0)return I.debug(`[Loop] [轮次 ${W}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let Q=C1(Z.messages,Y);if(Q)Z.messages=Q.messages,I.debug(`[Loop] [轮次 ${W}] MicroCompact: 清理 ${Q.snippedCount} 轮旧工具结果(缓存已过期)`);let V=G0(Z.messages),j=!1;if(V.snippedCount>0)j=!0,I.debug(`[Loop] [轮次 ${W}] Snip 压缩: 移除 ${V.snippedCount} 轮旧工具调用,释放约 ${V.estimatedTokensFreed} tokens`);let q=$.chatService.getConfig(),O=q.model,D=q.maxContextTokens??0,T=q.maxOutputTokens??$.config.maxOutputTokens??Math.min(Math.max(Math.floor(D*x6),f6),T6),d=D-T,k=Math.floor(d*0.8);if(I.debug(`[Loop] [轮次 ${W}] 压缩检查:`,{promptTokens:J,maxContextTokens:D,maxOutputTokens:T,availableForInput:d,threshold:k,shouldCompact:J>=k}),J<k){if(j)Z.messages=V.messages;return j?"snipped":"none"}let N=z?.lastCompactionTurn===void 0?void 0:W-z.lastCompactionTurn,w2=N!==void 0&&N<=M6,t=Math.floor(d*v6);if(w2&&J<t){if(j)Z.messages=V.messages;return I.debug(`[Loop] [轮次 ${W}] 跳过连续 LLM 压缩,距离上次压缩 ${N} 轮`),j?"snipped":"none"}I.debug(W===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${W}] 触发循环内自动压缩`),yield{kind:"compaction",phase:"start"};try{let G=j?V.messages:Z.messages,C=await n2.compact(G,{trigger:"auto",modelName:O,modelProvider:q.provider,maxContextTokens:D,apiKey:q.apiKey,baseURL:q.baseUrl,actualPreTokens:J,signal:K,activeTask:X,workspaceRoot:Z.workspaceRoot||u(),sessionId:Z.sessionId});if(C.usage)yield{kind:"token_usage",usage:s0(C.usage,D)};if(Z.messages=C.compactedMessages,z)z.lastCompactionTurn=W;if(C.success)I.debug(`[Loop] [轮次 ${W}] 压缩完成: ${C.preTokens} -> ${C.postTokens} tokens`);else I.warn(`[Loop] [轮次 ${W}] 压缩使用降级策略: ${C.preTokens} -> ${C.postTokens} tokens`);return await R0($,Z,C.summary,{trigger:"auto",preTokens:C.preTokens,postTokens:C.postTokens,filesIncluded:C.filesIncluded}),"compacted"}catch(G){if(R2(G))return I.debug(`[Loop] [轮次 ${W}] 压缩被中止`),"none";if(j)Z.messages=V.messages;return I.error(`[Loop] [轮次 ${W}] 压缩失败,继续执行`,G),j?"snipped":"none"}finally{yield{kind:"compaction",phase:"end"}}}function l6($,Z,W,J){let K=J?bZ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(K==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-W,abortReason:K}}}async function*i6($,Z,W,J,K){let Y=Date.now(),X=0,z=[],Q=null,V=!1,j=(q,O,D)=>{return V=!0,l6(q,O,Y,D)};try{let q=$.toolExecutor.getRegistry(),O=W.permissionMode,D=J?.outputSchema?g0(J.outputSchema):void 0,T=()=>{let L=$.applySkillToolRestrictions(q.getFunctionDeclarationsByMode(O));if(!D)return L;return[...L.filter((y)=>y.name!==j2),D.declaration]},d=t1(),k=KZ(),N=K;if(typeof q.getDeferredToolsListing==="function"){let L=q.getDeferredToolsListing();if(L&&N)N=`${N}
|
|
144
144
|
|
|
145
145
|
${L}`}if(N)N+=R6;if(D)N=`${N??""}
|
|
146
146
|
|