blade-code 0.10.99 → 0.10.100
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-a42rvwg4.js → chunk-1nwc2wt6.js} +1 -1
- package/dist/{chunk-mq4x8zhq.js → chunk-2s86w4yb.js} +2 -2
- package/dist/{chunk-gmnv1jme.js → chunk-3ktsyk2g.js} +1 -1
- package/dist/{chunk-x5j6nexe.js → chunk-6hr7mv7f.js} +1 -1
- package/dist/{chunk-qwjfxvda.js → chunk-6jhndjnq.js} +1 -1
- package/dist/{chunk-ga15nptz.js → chunk-6p9p71qm.js} +1 -1
- package/dist/{chunk-et6pvc3y.js → chunk-6rd8x9j0.js} +1 -1
- package/dist/{chunk-5tq3s9h5.js → chunk-73t5j9dn.js} +1 -1
- package/dist/{chunk-spdrxj5e.js → chunk-8wzn2p00.js} +1 -1
- package/dist/{chunk-2jffgzdf.js → chunk-8zm5r6g8.js} +1 -1
- package/dist/{chunk-71jnx206.js → chunk-ara0zd89.js} +1 -1
- package/dist/{chunk-vd6kmnc7.js → chunk-axycs651.js} +1 -1
- package/dist/{chunk-6yz49rz2.js → chunk-c3yd59qh.js} +1 -1
- package/dist/{chunk-d7j7z8hy.js → chunk-cc74b8qp.js} +9 -1
- package/dist/{chunk-9z0yx0bn.js → chunk-dfxfcsm1.js} +1 -1
- package/dist/{chunk-fqwq3626.js → chunk-gcnke6s4.js} +1 -1
- package/dist/{chunk-r22mdmtr.js → chunk-gkdynynx.js} +1 -1
- package/dist/{chunk-gwj637ey.js → chunk-gr6e2vsy.js} +1 -1
- package/dist/{chunk-3ghvdscg.js → chunk-hx3c0qn6.js} +1 -1
- package/dist/{chunk-ap8539bw.js → chunk-hx55j0d0.js} +3 -3
- package/dist/{chunk-45sgvghd.js → chunk-jac8cc04.js} +1 -1
- package/dist/{chunk-akfez2cs.js → chunk-njctfzqw.js} +1 -1
- package/dist/{chunk-cc3d4nne.js → chunk-p4h3p1at.js} +1 -1
- package/dist/{chunk-p7zvg7e3.js → chunk-pzp42zf0.js} +1 -1
- package/dist/{chunk-qdgwprcv.js → chunk-q1cc7kwn.js} +1 -1
- package/dist/{chunk-1gjn9bp7.js → chunk-qc4fe1j6.js} +1 -1
- package/dist/{chunk-bdbyy2ah.js → chunk-rmhgyrgh.js} +1 -1
- package/dist/{chunk-xg959k9w.js → chunk-s15phq98.js} +1 -1
- package/dist/{chunk-6vcy0nq7.js → chunk-sgzqcr55.js} +1 -1
- package/dist/chunk-t29x8420.js +1 -0
- package/dist/chunk-tagtjbw9.js +2 -0
- package/dist/{chunk-xz5ar75z.js → chunk-tsthz2ex.js} +1 -1
- package/dist/{chunk-12vzyc3x.js → chunk-ttg3xrsc.js} +1 -1
- package/dist/{chunk-1pscfw5q.js → chunk-v9pcf4w4.js} +1 -1
- package/dist/chunk-vgevdm8b.js +1 -0
- package/dist/{chunk-hyk4fw18.js → chunk-x677fstt.js} +1 -1
- package/dist/{chunk-pmb5kr86.js → chunk-y7bsjbsa.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-c2s9rgyj.js +0 -1
- package/dist/chunk-hcz98dbj.js +0 -1
- package/dist/chunk-mhfwp1f0.js +0 -2
|
@@ -25,7 +25,7 @@ import{sg as YO}from"./chunk-c6tq09mt.js";import{Bh as S,Eh as y,zh as qO}from".
|
|
|
25
25
|
`):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
|
|
26
26
|
`):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
|
|
27
27
|
`):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
|
|
28
|
-
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-
|
|
28
|
+
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-dfxfcsm1.js"),{createChatServiceAsync:W}=await import("./chunk-p7t010gq.js"),{resolveModelConfig:J}=await import("./chunk-n4cw6vt1.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-6rd8x9j0.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
|
|
29
29
|
|
|
30
30
|
`+`## 评估指令
|
|
31
31
|
${O.prompt}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Xf as b1,Yf as L0,Zf as z1,cg as N0}from"./chunk-fvfc95g3.js";import{hg as jO,ig as wO}from"./chunk-qcy79mva.js";import{lg as A1}from"./chunk-p0rvgzpx.js";import{mg as b0,og as J0}from"./chunk-
|
|
1
|
+
import{Xf as b1,Yf as L0,Zf as z1,cg as N0}from"./chunk-fvfc95g3.js";import{hg as jO,ig as wO}from"./chunk-qcy79mva.js";import{lg as A1}from"./chunk-p0rvgzpx.js";import{mg as b0,og as J0}from"./chunk-c3yd59qh.js";import{qh as S0,rh as GO,vh as I0}from"./chunk-gcnke6s4.js";import{Bh as L,Eh as c1,zh as u}from"./chunk-czcxx8tb.js";import{Nh as M}from"./chunk-9sx3vsyj.js";import{ni as k,oi as S}from"./chunk-d8wzc602.js";import{Bi as u0}from"./chunk-tagtjbw9.js";import{Ii as N}from"./chunk-cp7xsjj2.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
|
|
2
2
|
${J.map((K)=>`- ${K}`).join(`
|
|
3
3
|
`)}`:""].filter(Boolean).join(`
|
|
4
4
|
|
|
@@ -28,6 +28,14 @@ current workspace provides direct evidence for every explicit requirement.
|
|
|
28
28
|
contradiction, failed check, defect, or missing required artifact.
|
|
29
29
|
8. SAFE FEEDBACK. Keep summary and findings concise, use workspace-relative
|
|
30
30
|
file locations, and never include credentials or secret values.
|
|
31
|
+
9. HOST CONTROL PLANE. This reserved verifier runs only after the host durably
|
|
32
|
+
accepts the parent Agent's UpdateGoal complete call. During verification, the
|
|
33
|
+
Goal intentionally remains status=verifying with
|
|
34
|
+
completionVerification.status=pending. Treat that state as an awaiting
|
|
35
|
+
verdict, never as evidence that UpdateGoal was omitted. Do not require
|
|
36
|
+
status=complete or a PASS verdict before issuing your own verdict because
|
|
37
|
+
only your PASS permits the host to commit them. This proves only the
|
|
38
|
+
completion-candidate control action, not the requested deliverables.
|
|
31
39
|
|
|
32
40
|
## Verdict
|
|
33
41
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$e as q,Le as a,Me as b,Ne as c,Oe as d,Pe as e,Qe as f,Re as g,Se as h,Te as i,Ue as j,Ve as k,We as l,Xe as m,Ye as n,Ze as o,_e as p}from"./chunk-
|
|
1
|
+
import{$e as q,Le as a,Me as b,Ne as c,Oe as d,Pe as e,Qe as f,Re as g,Se as h,Te as i,Ue as j,Ve as k,We as l,Xe as m,Ye as n,Ze as o,_e as p}from"./chunk-v9pcf4w4.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-gcnke6s4.js";import"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import"./chunk-maebpz1j.js";import"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import"./chunk-k7vv9vne.js";import"./chunk-tagtjbw9.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{yh as Y}from"./chunk-f9asjkfz.js";import{Ah as F,Bh as o,zh as on}from"./chunk-czcxx8tb.js";import{Fh as ct,Gh as bt}from"./chunk-maebpz1j.js";import{Nh as x}from"./chunk-9sx3vsyj.js";import{$h as Bt,Oh as Jn,Ph as Xt,Qh as pt,Uh as gt,Vh as kn,Wh as it,Xh as Rt,Yh as Ct,Zh as un,_h as zt,ai as On,bi as Kt,ci as Ut,di as jn,ei as Ht,fi as Yt,gi as qt,hi as Vt,ii as Qt,ji as Gt}from"./chunk-70hwyc2w.js";import{ni as fn}from"./chunk-d8wzc602.js";import{qi as $t,ti as J}from"./chunk-425p4nwx.js";import{Bi as Pn,Ci as Ln}from"./chunk-
|
|
1
|
+
import{yh as Y}from"./chunk-f9asjkfz.js";import{Ah as F,Bh as o,zh as on}from"./chunk-czcxx8tb.js";import{Fh as ct,Gh as bt}from"./chunk-maebpz1j.js";import{Nh as x}from"./chunk-9sx3vsyj.js";import{$h as Bt,Oh as Jn,Ph as Xt,Qh as pt,Uh as gt,Vh as kn,Wh as it,Xh as Rt,Yh as Ct,Zh as un,_h as zt,ai as On,bi as Kt,ci as Ut,di as jn,ei as Ht,fi as Yt,gi as qt,hi as Vt,ii as Qt,ji as Gt}from"./chunk-70hwyc2w.js";import{ni as fn}from"./chunk-d8wzc602.js";import{qi as $t,ti as J}from"./chunk-425p4nwx.js";import{Bi as Pn,Ci as Ln}from"./chunk-tagtjbw9.js";import{Ii as h}from"./chunk-cp7xsjj2.js";import{Ti as Tn}from"./chunk-q3vza5gt.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function k(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Wt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await L.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=j.join(this.stateRoot,".oauth-credentials.lock"),t=Jt(),M=Date.now()+jt;while(Date.now()<M)try{let e=await L.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(_){if(!H(_,"ENOENT"))throw _}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await L.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!tM(M.pid))await L.unlink(n)}}var bn="127.0.0.1",wn=7777,xn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{vh as F}from"./chunk-
|
|
1
|
+
import{vh as F}from"./chunk-gcnke6s4.js";import{si as D,ti as E}from"./chunk-425p4nwx.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 sf,Q as tf,T as uf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ai as a,Bi as b,Ci as c,Di as d,Ei as e,Fi as f}from"./chunk-
|
|
1
|
+
import{Ai as a,Bi as b,Ci as c,Di as d,Ei as e,Fi as f}from"./chunk-tagtjbw9.js";import"./chunk-w9xfks7f.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-
|
|
1
|
+
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-jac8cc04.js";import{U as M,aa as y}from"./chunk-hx55j0d0.js";import"./chunk-0zhdjaen.js";import"./chunk-rmhgyrgh.js";import"./chunk-hz5rsfxv.js";import{Db as h,Mb as A}from"./chunk-2s86w4yb.js";import"./chunk-8hprmrd5.js";import{Cd as w,Qd as U}from"./chunk-6hr7mv7f.js";import"./chunk-s0tq8gyx.js";import"./chunk-h8qjkxee.js";import{oe as C}from"./chunk-qc4fe1j6.js";import{qe as I,re as S,se as v}from"./chunk-8zm5r6g8.js";import{te as O}from"./chunk-10taec1j.js";import"./chunk-rej5bbbs.js";import{Qe as P}from"./chunk-v9pcf4w4.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-3awjdsef.js";import"./chunk-53xtssbf.js";import"./chunk-2hb222re.js";import"./chunk-gkdynynx.js";import"./chunk-cc74b8qp.js";import"./chunk-fvfc95g3.js";import"./chunk-qcy79mva.js";import"./chunk-p0rvgzpx.js";import"./chunk-c3yd59qh.js";import"./chunk-c6tq09mt.js";import"./chunk-gcnke6s4.js";import{xh as F}from"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import"./chunk-maebpz1j.js";import{Nh as z}from"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import"./chunk-k7vv9vne.js";import"./chunk-tagtjbw9.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
2
|
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
3
|
`);else j.io.stdout.write(`${j.response}
|
|
4
4
|
`)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.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(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{wa as qZ}from"./chunk-0zhdjaen.js";import{Aa as i0,Fa as TY,Ga as V7,Ha as l0,za as C}from"./chunk-
|
|
1
|
+
import{wa as qZ}from"./chunk-0zhdjaen.js";import{Aa as i0,Fa as TY,Ga as V7,Ha as l0,za as C}from"./chunk-rmhgyrgh.js";import{Ia as s4,Ka as DQ,Ma as FQ,Na as YZ,db as _Q}from"./chunk-hz5rsfxv.js";import{Ab as e6,Cb as N9,Db as z$,Jb as L4,Kb as OY,Lb as hJ,Nb as P2,Ob as YY,Tb as A7,Wb as C7,eb as y$,fb as k1,gb as c3,hb as K1,ib as f3,jb as i3,kb as k3,lb as n3,mb as r3,nb as u7,rb as U0,tb as x6,wb as s6,yb as X5,zb as t6}from"./chunk-2s86w4yb.js";import{Ac as Q1,Ad as eJ,Bc as j1,Bd as $Y,Cc as X2,Dc as A1,Ec as C1,Ed as CY,Fc as Z6,Gc as M1,Hc as J6,Ic as Y6,Id as j7,Jc as D$,Kc as Q6,Lc as SZ,Mc as H2,Nc as W6,Nd as ZY,Oc as U6,Od as JY,Pc as X6,Qc as V6,Qd as s,Rc as kZ,Sc as vZ,Uc as yZ,ac as sZ,bc as D0,cc as t1,dc as t$,ec as a2,fc as VZ,gc as a6,hc as o6,ic as y3,jc as I3,kc as tJ,lc as _Z,ld as B4,mc as Y1,nc as DZ,nd as N0,oc as d4,od as U$,pc as S$,qc as k$,rc as w2,sc as V2,tc as K2,uc as e2,vc as $6,wc as W2,xc as NZ,xd as wZ,yc as U2,yd as r0,zc as m4,zd as v1}from"./chunk-6hr7mv7f.js";import{Rd as m,Sd as c7,Td as l7,Ud as S9,Wd as y1}from"./chunk-s0tq8gyx.js";import{Xd as LQ,_d as OQ,he as bQ,ne as NQ}from"./chunk-h8qjkxee.js";import{ye as q9,ze as F9}from"./chunk-rej5bbbs.js";import{$e as T1,Le as $4,Me as z0,Ne as y,Qe as _0,Re as h6,Se as I1,Te as m$,Ue as _5,Ve as W1,We as N7}from"./chunk-v9pcf4w4.js";import{af as B1}from"./chunk-dg0d3303.js";import{ef as z5,ff as E7,gf as O7,lf as GY,mf as g6}from"./chunk-3awjdsef.js";import{of as k0,pf as s$}from"./chunk-53xtssbf.js";import{qf as NY}from"./chunk-2hb222re.js";import{sf as nJ,tf as rJ,uf as aJ}from"./chunk-gkdynynx.js";import{Af as r6,Bf as r$,Cf as o7,Ef as q$,Ff as X$,Gf as Y$,Hf as a4,If as P1,Jf as _4,Kf as q1,Lf as L1,Mf as sJ,Qf as I5,Sf as v0,Tf as G$,Vf as u6,Wf as QY,vf as c6,wf as l6,xf as i6,zf as n6}from"./chunk-cc74b8qp.js";import{$f as M6,Yf as c$,_f as H$,ag as uZ,bg as dZ,cg as z2,dg as mZ,eg as pZ,fg as K6}from"./chunk-fvfc95g3.js";import{gg as dY,ig as oJ,jg as G4,kg as L9}from"./chunk-qcy79mva.js";import{mg as s5,og as P0}from"./chunk-c3yd59qh.js";import{pg as d2,qg as XZ,rg as m2,sg as b1}from"./chunk-c6tq09mt.js";import{Bg as i5,Gg as RY,Kg as Q9,Mg as pJ,Og as m3,Pg as p3,Vg as z1,Yg as S3,gh as K7,hh as H7,ih as z7,jh as G7,kh as D5,lh as B7,mh as d$,nh as D7,oh as F7,ph as _7,rh as rZ,th as UY,ug as J9,uh as iJ,vh as X0,zg as Y9}from"./chunk-gcnke6s4.js";import{yh as v$}from"./chunk-f9asjkfz.js";import{Ah as l4,Bh as z,Ch as ZJ,Dh as T,Eh as x,zh as w6}from"./chunk-czcxx8tb.js";import{Gh as IJ,Ih as xJ}from"./chunk-maebpz1j.js";import{Lh as B6,Nh as M}from"./chunk-9sx3vsyj.js";import{ni as o}from"./chunk-d8wzc602.js";import{si as cJ,ti as lJ}from"./chunk-425p4nwx.js";import{ui as pY,xi as gY}from"./chunk-k7vv9vne.js";import{Bi as nY}from"./chunk-tagtjbw9.js";import{Hi as WY,Ii as u0}from"./chunk-cp7xsjj2.js";import{Mi as r2,Oi as g$,Qi as mJ,Ri as gZ,Ti as J0}from"./chunk-q3vza5gt.js";import{Vi as a0}from"./chunk-w9xfks7f.js";import{randomUUID as k4}from"crypto";import{randomUUID as dQ}from"node:crypto";var IQ=String.raw`
|
|
2
2
|
const { spawn } = require('node:child_process');
|
|
3
3
|
const [ownerPidValue, command, ...args] = process.argv.slice(1);
|
|
4
4
|
const ownerPid = Number(ownerPidValue);
|
|
@@ -843,7 +843,7 @@ ${a}
|
|
|
843
843
|
</approved-plan>
|
|
844
844
|
|
|
845
845
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof _==="string")n0=_+w0;else n0=[..._,{type:"text",text:w0}]}v=yield*this.runLoop(n0,L,{...I,inputMessageId:void 0})}if(!this.sessionRuntime||!S)return v;let k=await this.sessionRuntime.recordGoalProgress({tokens:v.metadata?.tokensUsed??0,elapsedMs:v.metadata?.duration??0,prematureStopPattern:v.success?d3(v.finalMessage):void 0});if(k)yield{kind:"goal_updated",goal:k};if(!v.success||L.signal?.aborted){if(k=await this.sessionRuntime.pauseActiveGoal(L.signal?.aborted?"goal paused after user cancellation":v.error?.message??"goal paused after turn failure"),k)yield{kind:"goal_updated",goal:k}}if(v.success&&!L.signal?.aborted&&R<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(S,L.signal);let d=v.success&&!L.signal?.aborted&&R<20,Z0=uV(v);if(j=await this.sessionRuntime.finishTurn(S,{continuePending:d,...Z0?{acknowledgeInput:!0}:{},outcome:v.success&&!L.signal?.aborted?{status:"completed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}:{status:"aborted",cause:L.signal?.aborted?"cancelled":"failed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}}),j){R++,q=!0,E=!1,N=null,_="",f=void 0,A="",b=void 0,O=g(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:p()};continue}if(!v.success||L.signal?.aborted)return v;if(k=await this.sessionRuntime.getGoal(),!k||k.status!=="active"&&k.status!=="verifying")return v;if(N=await this.sessionRuntime.beginGoalContinuation(),!N)return v;j=await this.sessionRuntime.beginTurn("goal"),q=!1,E=!0,_=N8(N),f=void 0,O=void 0,yield{kind:"goal_continuation_started",goal:N,continuation:N.continuationCount,...N.prematureStop?{prematureStopPattern:N.prematureStop.pattern,prematureStopCount:N.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:N}}}finally{if(this.sessionRuntime&&j)await this.sessionRuntime.finishTurn(j)}}let B=typeof w==="string"?w:w.filter((_)=>_.type==="text").map((_)=>_.text).join(`
|
|
846
|
-
`),F={id:this.generateTaskId(),type:"simple",prompt:B};return{success:!0,finalMessage:(await this.executeTask(F)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-akfez2cs.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){r.debug("Processing Plan mode message...");let{prompt:Y}=await I$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:P2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),Q;if(typeof $==="string")Q=D2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:D2(U.text)}:X)}else Q=[{type:"text",text:D2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){r.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await I$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:P2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return C7(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,X={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],w=A7(Y,X);if(w)V.push(w);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,r.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);r.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);r.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){r.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){r.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await I$({projectPath:this.sessionRuntime?.workspaceRoot??M(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),r.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await d6({sessionId:"default",configDir:J0(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});r.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;r.debug(`Builtin tools registered: ${Z} tools`),r.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw r.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await D6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){r.debug("No MCP servers configured");return}let Z=l0.createIsolated({artifactWriter:new B2(`legacy-${gV()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{r.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),r.debug(`MCP server "${W}" connected`)}catch(X){r.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(O2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)r.debug(`Registered ${Y.tools.length} MCP tools`),r.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){r.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await v0(M());if(this.agentResources=u6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)r.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else r.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;r.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return r.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)r.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
846
|
+
`),F={id:this.generateTaskId(),type:"simple",prompt:B};return{success:!0,finalMessage:(await this.executeTask(F)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-njctfzqw.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){r.debug("Processing Plan mode message...");let{prompt:Y}=await I$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:P2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),Q;if(typeof $==="string")Q=D2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:D2(U.text)}:X)}else Q=[{type:"text",text:D2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){r.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await I$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:P2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return C7(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,X={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],w=A7(Y,X);if(w)V.push(w);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,r.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);r.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);r.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){r.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){r.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await I$({projectPath:this.sessionRuntime?.workspaceRoot??M(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),r.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await d6({sessionId:"default",configDir:J0(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});r.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;r.debug(`Builtin tools registered: ${Z} tools`),r.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw r.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await D6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){r.debug("No MCP servers configured");return}let Z=l0.createIsolated({artifactWriter:new B2(`legacy-${gV()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{r.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),r.debug(`MCP server "${W}" connected`)}catch(X){r.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(O2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)r.debug(`Registered ${Y.tools.length} MCP tools`),r.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){r.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await v0(M());if(this.agentResources=u6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)r.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else r.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;r.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return r.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)r.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
847
847
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;r.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return r.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let W=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${W?` range="${W}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
|
|
848
848
|
|
|
849
849
|
<system-reminder>
|
|
@@ -1654,7 +1654,7 @@ ${J}
|
|
|
1654
1654
|
`)),{success:!0,message:"Schedules listed",content:V.join(`
|
|
1655
1655
|
`)}}case"create":{let X=qG(W);if("error"in X)return Y.sendMessage(`创建失败:${X.error}`),{success:!1,error:X.error};let V={prompt:X.prompt,projectPath:U,trigger:X.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let w=await $.create(V),K=w.nextRunAt?new Date(w.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${w.id}\`
|
|
1656
1656
|
${YZ(w.trigger)} · 下次运行: ${K}`),{success:!0,message:`Schedule ${w.id} created`}}catch(w){let K=w instanceof Error?w.message:String(w);return Y.sendMessage(`创建失败:${K}`),{success:!1,error:K}}}case"remove":case"rm":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(X);return Y.sendMessage(V?`[OK] 已删除 \`${X}\``:`未找到 \`${X}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let X=W[0];if(!X)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(X,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${X}\``:`未找到 \`${X}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await LG(X),Y.sendMessage(`[OK] 已触发 \`${X}\``),{success:!0,message:"Schedule triggered"}}catch(V){let w=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${w}`),{success:!1,error:w}}}default:return Y.sendMessage(`未知子命令: ${Q}
|
|
1657
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var qQ=OG();import*as a1 from"node:fs/promises";import*as o1 from"node:path";async function EQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??r2(Q??M());if(!W){let G=await bG($,Q??M(),J,Y);if(G)return G}let X;try{X=(await a1.readdir(U)).filter((B)=>B.endsWith(".jsonl")&&!B.startsWith("agent_")).map((B)=>o1.join(U,B))}catch{return[]}let w=(await Promise.all(X.map(async(G)=>{try{let B=await a1.stat(G);return{path:G,mtime:B.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,B)=>B.mtime-G.mtime).map((G)=>G.path),K=[],H=Y?$:$.toLowerCase();for(let G of w){if(K.length>=J)break;let B=o1.basename(G,".jsonl"),F=await NG(G,H,Y,B);if(K.push(...F),K.length>=J){K.length=J;break}}return K}async function bG($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-5dkzqgxa.js"),W=await bQ();if(!W)return null;let{SessionService:U}=await import("./chunk-
|
|
1657
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var qQ=OG();import*as a1 from"node:fs/promises";import*as o1 from"node:path";async function EQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??r2(Q??M());if(!W){let G=await bG($,Q??M(),J,Y);if(G)return G}let X;try{X=(await a1.readdir(U)).filter((B)=>B.endsWith(".jsonl")&&!B.startsWith("agent_")).map((B)=>o1.join(U,B))}catch{return[]}let w=(await Promise.all(X.map(async(G)=>{try{let B=await a1.stat(G);return{path:G,mtime:B.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,B)=>B.mtime-G.mtime).map((G)=>G.path),K=[],H=Y?$:$.toLowerCase();for(let G of w){if(K.length>=J)break;let B=o1.basename(G,".jsonl"),F=await NG(G,H,Y,B);if(K.push(...F),K.length>=J){K.length=J;break}}return K}async function bG($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-5dkzqgxa.js"),W=await bQ();if(!W)return null;let{SessionService:U}=await import("./chunk-3ktsyk2g.js");await Q(W,U.projectionDeriverForSearch());let X=o1.resolve(Z),V=NQ(W,$,X,J*4),w=Y?$:$.toLowerCase(),K=[];for(let H of V){if(H.role!=="user"&&H.role!=="assistant")continue;let G=QZ(H.text,w,Y,H.session_id,H.role,H.timestamp??void 0,0);if(G)K.push(G);if(K.length>=J)break}return K}catch{return null}}async function NG($,Z,J,Y){try{let Q=await a1.readFile($,"utf8"),U=Q.split(`
|
|
1658
1658
|
`).flatMap((H,G)=>{if(!H.trim())return[];try{return[{event:JSON.parse(H),index:G}]}catch{return[]}});if(!U.some(({event:H})=>H.type==="session_created"))return EG(U,Z,J,Y);let V=new Map(U.flatMap(({event:H,index:G})=>typeof H.id==="string"?[[H.id,G+1]]:[])),w=LQ(OQ(Q,$)),K=new Map;for(let H of w){if(H.type==="message_created"&&(H.data.role==="user"||H.data.role==="assistant"))K.set(H.data.messageId,{role:H.data.role,content:[],timestamp:H.timestamp,lineNumber:V.get(H.id)??0});if(H.type==="part_created"&&H.data.partType==="text"){let G=K.get(H.data.messageId),B=H.data.payload.text;if(G&&typeof B==="string")G.content.push(B)}}return[...K.values()].flatMap((H)=>{let G=QZ(H.content.join(" "),Z,J,Y,H.role,H.timestamp,H.lineNumber);return G?[G]:[]})}catch{return[]}}function EG($,Z,J,Y){return $.flatMap(({event:Q,index:W})=>{if(Q.type!=="message")return[];let U=Q.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let X=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((w)=>typeof w==="object"&&w!==null&&w.type==="text"&&typeof w.text==="string").map((w)=>w.text).join(" "):"",V=QZ(X,Z,J,Y,U.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,W+1);return V?[V]:[]})}function QZ($,Z,J,Y,Q,W,U){if(!$)return;let X=J?$:$.toLowerCase();if(!X.includes(Z))return;let V=X.indexOf(Z),w=Math.max(0,V-80),K=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(w>0?"...":"")+$.slice(w,K).replace(/\n/g," ")+(K<$.length?"...":""),timestamp:W,lineNumber:U}}function jQ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1659
1659
|
`];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1660
1660
|
`)}var jG={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=u(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await EQ(Y,{maxResults:15,projectPath:Z.cwd}),W=jQ(Q);return J.sendMessage(W),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let W=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${W}`),{success:!1,error:W}}}},AQ=jG;var AG={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await G$(J,async(Y)=>{await Y.skills.refresh(),L1(J),await q1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return y().addAssistantMessage(Y),{success:!1,error:Y}}}},CQ=AG;import CG from"node:path";function M4($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function MQ($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function PQ($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function MG($,Z){let J=u(Z),Y=$[0],Q=e.getInstance(),W=V0.getInstance(),U=Z.sessionId??"",X=Z.sessionId?{sessionId:Z.sessionId,projectPath:CG.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let B=$[1],F=$.slice(2).join(" ").trim();if(!B||!F)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let D=await Z.subagents.resume(B,F),_=`Resumed \`${B}\` as \`${D.session.id}\` (depth ${D.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:B,subagent:D.session}}}if(Y==="clean"){let B=W.cleanupExpiredSessionsForParent(X??U,0);return J.sendMessage(`已清理 ${B} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${B} agent sessions`}}let V=[`**后台任务列表**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{qa as F,sa as L}from"./chunk-
|
|
1
|
+
import{qa as F,sa as L}from"./chunk-hx55j0d0.js";import{Gd as $,Id as B,Qd as Q}from"./chunk-6hr7mv7f.js";import{Sf as y}from"./chunk-cc74b8qp.js";import{Nh as V}from"./chunk-9sx3vsyj.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
|
|
2
2
|
|
|
3
3
|
${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{j as m,I as n,M as o,R as p,_ as q,C as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Bb as d,Cb as e,Db as f,Eb as g,Fb as h,Gb as i,Hb as j,Ib as k,Pb as l,Qb as m,Rb as n,Sb as o,Ub as p,Vb as q,Wb as r,ub as a,vb as b,xb as c}from"./chunk-
|
|
1
|
+
import{Bb as d,Cb as e,Db as f,Eb as g,Fb as h,Gb as i,Hb as j,Ib as k,Pb as l,Qb as m,Rb as n,Sb as o,Ub as p,Vb as q,Wb as r,ub as a,vb as b,xb as c}from"./chunk-2s86w4yb.js";import"./chunk-8hprmrd5.js";import"./chunk-6hr7mv7f.js";import"./chunk-s0tq8gyx.js";import"./chunk-h8qjkxee.js";import"./chunk-dg0d3303.js";import"./chunk-3awjdsef.js";import"./chunk-2hb222re.js";import"./chunk-fvfc95g3.js";import"./chunk-qcy79mva.js";import"./chunk-c3yd59qh.js";import"./chunk-c6tq09mt.js";import"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import"./chunk-maebpz1j.js";import"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import"./chunk-k7vv9vne.js";import"./chunk-tagtjbw9.js";import"./chunk-2va6ex5v.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{s as cz,t as pz}from"./chunk-
|
|
1
|
+
import{s as cz,t as pz}from"./chunk-6p9p71qm.js";import{u as S}from"./chunk-1nwc2wt6.js";import{A as Nz,v as gz,w as wz,x as Dz,y as _z,z as Az}from"./chunk-sgzqcr55.js";import{G as E,P as Bz,Q as Gz,U as Uz,X as jz,Y as Vz,aa as Kz,qa as Oz,ra as qz,sa as Pz,ta as Rz}from"./chunk-hx55j0d0.js";import"./chunk-0zhdjaen.js";import{Ha as uz}from"./chunk-rmhgyrgh.js";import{Ja as Fz}from"./chunk-hz5rsfxv.js";import{Db as Yz,Mb as Lz,rb as Xz}from"./chunk-2s86w4yb.js";import{Xb as g}from"./chunk-8hprmrd5.js";import{Cd as p,Dd as $z,Fd as h,Id as Wz,Nd as P,Qd as j,ad as zz,kd as y,ld as c,md as Hz,rd as Jz,ud as Qz,wd as Zz}from"./chunk-6hr7mv7f.js";import"./chunk-s0tq8gyx.js";import"./chunk-h8qjkxee.js";import{ve as mz}from"./chunk-ttg3xrsc.js";import"./chunk-rej5bbbs.js";import{Qe as kz,Re as Iz}from"./chunk-v9pcf4w4.js";import"./chunk-v508x7cg.js";import{af as m}from"./chunk-dg0d3303.js";import{ff as e}from"./chunk-3awjdsef.js";import"./chunk-53xtssbf.js";import{qf as Cz}from"./chunk-2hb222re.js";import"./chunk-gkdynynx.js";import"./chunk-cc74b8qp.js";import"./chunk-fvfc95g3.js";import{gg as fz}from"./chunk-qcy79mva.js";import"./chunk-p0rvgzpx.js";import"./chunk-c3yd59qh.js";import"./chunk-c6tq09mt.js";import{_g as yz,bh as Mz}from"./chunk-gcnke6s4.js";import"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import{Fh as C,Gh as t,Ih as f,Jh as u}from"./chunk-maebpz1j.js";import{Nh as bz}from"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import{ni as M}from"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import{ui as hz,xi as Sz}from"./chunk-k7vv9vne.js";import"./chunk-tagtjbw9.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import{Ti as s}from"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";import{Readable as JH,Writable as QH}from"node:stream";import*as k from"@agentclientprotocol/sdk";import Ez from"node:path";import{PROTOCOL_VERSION as zH,RequestError as HH}from"@agentclientprotocol/sdk";import{createHash as lz}from"node:crypto";import{RequestError as Tz}from"@agentclientprotocol/sdk";import{nanoid as I}from"nanoid";var U=M("Agent"),i=4,iz=1000,a=4000,r=120000,o=0.2;function n(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function az(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:n(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:n("headers"in z?z.headers:void 0)};return null}function rz(z){let J={};for(let H of z){let W=az(H);if(W)J[H.name]=W}return J}function xz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function oz(z){let J=$z(z.metadata);return J?[{type:"text",text:p(J)}]:xz(z.content)}function nz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function sz(z){if(!e(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...y("capacity"),resource:z.resource}}function tz(z,J){let H=Math.max(0,J-1),W=Math.min(iz*2**H,a),$=lz("sha256").update(`${z}\x00${J}`).digest().readUInt32BE(0)/4294967295,Z=1-o+2*o*$;return Math.min(a,Math.max(0,Math.round(W*Z)))}function ez(z){if(!(z instanceof Tz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Hz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}class b{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,H,W,X={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=W;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new Nz({maxPendingItems:wz,maxPendingBytes:Dz,writeTimeoutMs:_z,signal:H.signal,sizeOf:($)=>Buffer.byteLength(JSON.stringify($)),write:async($)=>{await H.sessionUpdate($)},onFailure:($)=>this.handleUpdateEgressFailure($)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([j.loadSession(this.id,this.cwd),j.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await j.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Kz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(U.debug(`[AcpSession ${this.id}] Initializing...`),await j.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),E.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async($)=>{await this.sendUpdateAndWait($)}),U.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Lz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:($)=>this.requestPermission($)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?rz(this.options.mcpServers):void 0,H=E.getInstance().getTerminalService(this.id);if(this.runtime=await Uz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,Z)=>{let Y=await H.execute($,{cwd:Z.cwd,env:Z.env,timeout:Z.timeoutMs,signal:Z.signal,allowLocalFallback:!1,onOutput:(F)=>Z.onOutput?.("stdout",F)});return{exitCode:Y.exitCode,stdout:Y.stdout,stderr:Y.stderr,...Y.error?{error:Y.error}:{},timedOut:Y.failureKind==="timeout",aborted:Y.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await S.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await qz(this.cwd),U.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Xz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:Z,messageId:Y,content:F}=$.properties,L=$.properties.metadata;if($.type==="team.message.received"&&typeof Z==="string"&&typeof Y==="string"&&typeof F==="string"&&Gz(L,{messageId:Y,teamName:Z}))(async()=>{let B=await this.runtime?.enqueueSteering(F,{allowBeforeTurn:!0,messageId:Y,origin:"team_message",metadata:L});if(!B?.accepted)return;if(await new Bz(Z,s()).markDelivered([Y]),B.delivery==="next_turn")this.requestPendingResume()})().catch((B)=>{U.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,B)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let X=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||X?.status==="active"||X?.status==="verifying")this.requestPendingResume({defer:this.options.initialMessages!==void 0})}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Zz(J))continue;let H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let W of oz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:W}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);U.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{U.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let Y=await this.runtime.rewindSession(Z);return this.messages=[...Y.messages],this.contextMessages=await this.loadModelContextOr(Y.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),Y}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Z)=>{if(await this.setServiceTier(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Z)=>{if(await this.setResponseVerbosity(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Z)=>{if(await this.setCommunicationStyle(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,L,B=(D)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:D.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:D.result?.message||D.result?.error||`Subagent ${D.status}`}}]})},G=this.runtime.resumeSubagent({agentId:Z,prompt:Y,onCompleted:(D)=>{if(F)B(D);else L=D}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,L)B(L);return G}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,Y,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,Y,F)},complete:async(Z,Y,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,Y,F)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,Y)},getLogs:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,Y)},setLoggingLevel:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,Y)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Z,{signal:Y})}},codeReview:{run:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await S.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:Y,onEvent:(G)=>{if(G.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.toolCall.id,status:"in_progress",title:`Review: ${G.toolCall.function.name}`,content:[],kind:this.mapToolKind(G.toolKind)});else if(G.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.toolCall.id,status:G.result.success?"completed":"failed",content:[]})}}),L=await F.completion,B=(await S.list(this.cwd,this.id)).find((G)=>G.start.reviewId===F.reviewId);if(!B)throw Error(`Review not found: ${F.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:F.reviewId,status:L.status,findings:L.findings.length,content:zz(B.start,L)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,Y,F)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:B})},sendToolResult:(Z,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},W=await Pz(z,H),X=W.data?.action;if(X==="start_goal"||X==="resume_goal")this.requestPendingResume();if(X==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages],this.contextMessages=await this.loadModelContextOr(W.data.messages);if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages){this.contextMessages=[...W.data.compactedMessages];let Z=await j.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let $=W.content||W.message;if($)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return await this.flushUpdates(),{stopReason:W.success?"end_turn":"cancelled"}}catch(H){if(J.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};return U.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,H,W=new Promise((X)=>{H=X});this.pendingSideConversation=J,this.pendingSideConversationCompletion=W;try{return await this.handleSlashCommand(z,J.signal)}catch(X){if(J.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw X}finally{if(H(),this.pendingSideConversationCompletion===W)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Rz(this.cwd,this.runtime?.getAgentResources()),J=["model","permissions","theme","config","exit","ide"],W=z.filter((X)=>!J.includes(X.name)&&(X.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((X)=>{let $;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)$=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;$=$?`${$} | ${Z}`:Z}return{name:X.name,description:X.description,input:$?{hint:$}:void 0}});U.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),U.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(z){U.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(E.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),W=H.content,X=H.displayText,$=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((K)=>K.outputSchema)?.outputSchema:void 0),Z;if($!==void 0)Z=Wz($).schema;if(X.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let Y=Fz(X);if(Y){if(Z)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(W)&&W.some((K)=>K.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(Y.question?`/btw ${Y.question}`:"/btw")}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(X.trim()))return this.handleSlashCommand(X,this.pendingPrompt.signal);let K=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!K.accepted)throw Error(K.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(U.debug(`[AcpSession ${this.id}] Queued steering for active turn (${K.queued})`),K.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let F=new AbortController,L=()=>{F.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let B=!1,G=!1,D=!1,R,T=new Promise((K)=>{R=K});this.pendingPrompt=F,this.pendingPromptCompletion=T;try{if(U.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),Oz(X)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,F.signal)}let K={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Q)=>{this.mode=this.mapPermissionModeToMode(Q),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Q)=>{return this.requestPermission(Q)}}},A=await Yz(this.agent.chatStream(W,K,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async(Q)=>{switch(Q.kind){case"content_delta":if(Z)break;if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q.delta}});break;case"thinking_delta":if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Q.delta}});break;case"tool_start":{D=!0;let V=Q.toolCall,N=V.function.name;if(N===h)break;let q=this.mapToolKind(Q.toolKind),w=`Executing ${N}`;if(N==="Task"&&"function"in V)try{let x=JSON.parse(V.function.arguments),_=x.resume_from??x.resume;if(typeof _==="string")w=`Resuming ${String(x.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:q});break}case"tool_progress":{D=!0;let V=Q.toolCall;if(V.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Q.update.message}}]});break}case"tool_result":{D=!0;let V=Q.toolCall;if(V.function.name===h)break;let N=Q.result,q=[],w=N.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let _ of w.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;q.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))q.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let _=V.function.name,vz=Vz(Qz(jz(_,N),Jz));q.push({type:"content",content:{type:"text",text:vz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let x=N.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:x,content:q});break}case"structured_output":G=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Q.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Q.contentKind} r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Q.revision} (${Q.serverName}): ${Q.uri}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{qe as a,re as b,se as c}from"./chunk-
|
|
1
|
+
import{qe as a,re as b,se as c}from"./chunk-8zm5r6g8.js";import"./chunk-10taec1j.js";import"./chunk-v9pcf4w4.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-p0rvgzpx.js";import"./chunk-gcnke6s4.js";import"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import"./chunk-maebpz1j.js";import"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import"./chunk-k7vv9vne.js";import"./chunk-tagtjbw9.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as o}from"./chunk-
|
|
1
|
+
import{h as o}from"./chunk-ara0zd89.js";import"./chunk-tagtjbw9.js";import"./chunk-w9xfks7f.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Bi as d,Di as h}from"./chunk-
|
|
1
|
+
import{Bi as d,Di as h}from"./chunk-tagtjbw9.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as oe,w as pe};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Xb as Xt,Yb as En,Zb as yn,_b as bn}from"./chunk-8hprmrd5.js";import{og as Bt}from"./chunk-
|
|
1
|
+
import{Xb as Xt,Yb as En,Zb as yn,_b as bn}from"./chunk-8hprmrd5.js";import{og as Bt}from"./chunk-c3yd59qh.js";import{Ag as mt,Cg as rn,Dg as Tn,Eg as B,Fg as dn,Gg as on,Hg as pn,Ig as lt,Jg as un,Kg as cn,Lg as Mn,Ng as S,Qg as wn,Rg as Gt,Sg as Ut,Tg as h,Ug as Ht,tg as xt,ug as vi,vg as sn,wg as zt,xg as U,yg as en,zg as gt}from"./chunk-gcnke6s4.js";import{Bh as x,zh as X}from"./chunk-czcxx8tb.js";import{Nh as It}from"./chunk-9sx3vsyj.js";import{Bi as tn,Ci as nn}from"./chunk-tagtjbw9.js";import{Vi as ns}from"./chunk-w9xfks7f.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(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 An(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||`验证失败:${hn(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:An(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;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}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 jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!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 +1 @@
|
|
|
1
|
-
import{Nf as a,Of as b,Pf as c,Qf as d,Rf as e,Sf as f,Tf as g,Uf as h,Vf as i,Wf as j}from"./chunk-
|
|
1
|
+
import{Nf as a,Of as b,Pf as c,Qf as d,Rf as e,Sf as f,Tf as g,Uf as h,Vf as i,Wf as j}from"./chunk-cc74b8qp.js";import"./chunk-fvfc95g3.js";import"./chunk-qcy79mva.js";import"./chunk-p0rvgzpx.js";import"./chunk-c3yd59qh.js";import"./chunk-c6tq09mt.js";import"./chunk-gcnke6s4.js";import"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import"./chunk-maebpz1j.js";import"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import"./chunk-k7vv9vne.js";import"./chunk-tagtjbw9.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{O as I}from"./chunk-
|
|
1
|
+
import{O as I}from"./chunk-hx55j0d0.js";import{Qd as M}from"./chunk-6hr7mv7f.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
|
|
2
2
|
export{C as v,$ as w,V as x,x as y,i as z,K as A};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as a,i as b,j as c,k as d,l as e}from"./chunk-ara0zd89.js";import"./chunk-tagtjbw9.js";import"./chunk-w9xfks7f.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.100",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
|
|
2
|
+
export{y as Ai,p as Bi,v as Ci,g as Di,f as Ei,w as Fi};
|