blade-code 0.11.8 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-74vmjngm.js → chunk-0vet7np5.js} +1 -1
  3. package/dist/{chunk-j5e589we.js → chunk-113t7z1d.js} +1 -1
  4. package/dist/{chunk-926rkw87.js → chunk-123x4vv0.js} +1 -1
  5. package/dist/{chunk-2fj047zf.js → chunk-1j3y40wn.js} +1 -1
  6. package/dist/{chunk-hdy7b6zw.js → chunk-3ce55d11.js} +1 -1
  7. package/dist/{chunk-34y4z9ns.js → chunk-54mb3ar4.js} +1 -1
  8. package/dist/{chunk-0e9nrf53.js → chunk-58t96cyv.js} +1 -1
  9. package/dist/{chunk-1gr9vqy1.js → chunk-5tf0hs46.js} +1 -1
  10. package/dist/{chunk-7876fd4b.js → chunk-75an4n90.js} +1 -1
  11. package/dist/{chunk-ayqqhefz.js → chunk-7bvtz3mm.js} +1 -1
  12. package/dist/{chunk-de3wa8nq.js → chunk-7me3rm8n.js} +1 -1
  13. package/dist/{chunk-np5t59fa.js → chunk-8cr35jh6.js} +1 -1
  14. package/dist/{chunk-53twn9t2.js → chunk-8fasjabf.js} +1 -1
  15. package/dist/{chunk-vjvw3v6b.js → chunk-8hke5rc9.js} +1 -1
  16. package/dist/{chunk-m8sttgjc.js → chunk-8httqk7j.js} +1 -1
  17. package/dist/{chunk-3t655nhk.js → chunk-8tjh8nzm.js} +1 -1
  18. package/dist/{chunk-e613h191.js → chunk-8wk4q3bz.js} +363 -363
  19. package/dist/{chunk-8r8fp09p.js → chunk-am63xh9m.js} +1 -1
  20. package/dist/{chunk-1crgzzz7.js → chunk-bckm03fv.js} +53 -53
  21. package/dist/{chunk-erget6wk.js → chunk-d40j41s5.js} +1 -1
  22. package/dist/{chunk-14jd0cj6.js → chunk-geakn1sr.js} +1 -1
  23. package/dist/{chunk-s7jd42xp.js → chunk-j5nz7kb4.js} +1 -1
  24. package/dist/chunk-j63n860q.js +1 -0
  25. package/dist/{chunk-rwtsvy5y.js → chunk-jgmaytrk.js} +1 -1
  26. package/dist/{chunk-rcfef8qj.js → chunk-k5595spk.js} +1 -1
  27. package/dist/{chunk-dgypy6yt.js → chunk-k6knawfb.js} +9 -9
  28. package/dist/{chunk-b0smnpzh.js → chunk-katmqxmn.js} +1 -1
  29. package/dist/{chunk-rh1q6srx.js → chunk-kn7jya27.js} +1 -1
  30. package/dist/chunk-mnm8epn5.js +2 -0
  31. package/dist/{chunk-547g7bq5.js → chunk-mvyrhqrm.js} +2 -2
  32. package/dist/{chunk-22py5y1p.js → chunk-pt4reckf.js} +1 -1
  33. package/dist/chunk-se9tcqqv.js +1 -0
  34. package/dist/{chunk-re6hbrmb.js → chunk-t5hhrj1g.js} +1 -1
  35. package/dist/{chunk-5q2gp1bb.js → chunk-vh5za5en.js} +1 -1
  36. package/dist/{chunk-mmwqe49e.js → chunk-vhc0z5k0.js} +1 -1
  37. package/dist/{chunk-3m8949fr.js → chunk-vkabej0v.js} +1 -1
  38. package/dist/{chunk-29t2wbwt.js → chunk-yzw0e9a5.js} +1 -1
  39. package/dist/{chunk-nr5s7qtp.js → chunk-z7f2a75f.js} +1 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-c1331rdc.js +0 -2
  42. package/dist/chunk-jbp9wt3f.js +0 -1
  43. package/dist/chunk-kz842bqy.js +0 -1
@@ -1,2 +1,2 @@
1
- import{M as N,ka as _,la as z}from"./chunk-e613h191.js";import{$d as R,Xc as I,Zd as g,cd as x,dd as X,ed as B,fd as V,gd as b,wd as A}from"./chunk-ayqqhefz.js";import{Di as M,Ei as O}from"./chunk-nr5s7qtp.js";import{Mutex as j}from"async-mutex";class C extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(q){super("Session runtime capacity is full");this.limit=q;this.name="SessionRuntimeCapacityError"}}class W extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class Y extends Error{constructor(q){super(`Session runtime residency already owns key: ${q}`);this.name="SessionRuntimeResidencyConflictError"}}class k{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new j;nextGeneration=1;closed=!1;constructor(q){if(!M(q.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!O(q.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=q.maxResident,this.idleMs=q.idleMs,this.now=q.now??Date.now}acquire(q){let $=this.residents.get(q);if(!$||$.poisoned)return;return $.pins++,$.lastUsedAt=this.now(),this.createLease($)}owns(q,$){let Q=this.residents.get(q);return Boolean(Q&&($===void 0||Q.value===$))}async reserve(q,$){if(!q.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new W;if(this.residents.has(q)||this.reservations.has(q))throw new Y(q);while(this.retainedCount()>=this.maxResident){if(!$.allowEviction)throw new C(this.maxResident);let P=this.oldestEvictableWebResident();if(!P)throw new C(this.maxResident);await this.disposeResident(P,!0)}let Q={generation:this.allocateGeneration(),surface:$.surface};return this.reservations.set(q,Q),this.createReservation(q,Q)})}async remove(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$)return!1;if(Q.pins>0)return!1;return await this.disposeResident(Q,!0),!0})}async forget(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$||Q.pins>0)return!1;return this.residents.delete(q),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let q=0;while(!0){let $=this.oldestIdleWebResident();if(!$)return q;await this.disposeResident($,!0),q++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let q;for(let $ of[...this.residents.values()])try{await this.disposeResident($,!1)}catch(Q){q??=Q}if(this.residents.clear(),q!==void 0)throw q})}getStats(){let q=0;for(let $ of this.residents.values())if($.pins>0)q++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:q,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let q=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,q}createReservation(q,$){let Q=!1;return{commit:(P)=>{if(Q)throw new Y(q);if(P.key!==q||P.surface!==$.surface||this.reservations.get(q)!==$||this.closed)throw this.reservations.delete(q),Q=!0,this.closed?new W:new Y(q);this.reservations.delete(q);let L={...P,generation:$.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(q,L),Q=!0,this.createLease(L)},cancel:()=>{if(Q)return;if(this.reservations.get(q)===$)this.reservations.delete(q);Q=!0}}}createLease(q){let $=!1;return{value:q.value,release:()=>{if($)return;$=!0;let Q=this.residents.get(q.key);if(Q!==q||Q.generation!==q.generation)return;Q.pins=Math.max(0,Q.pins-1),Q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((q)=>this.canEvict(q))}oldestIdleWebResident(){let q=this.now();return this.sortedWebResidents().find(($)=>q-$.lastUsedAt>=this.idleMs&&this.canEvict($))}sortedWebResidents(){return[...this.residents.values()].filter((q)=>q.surface==="web").sort((q,$)=>q.lastUsedAt-$.lastUsedAt||q.generation-$.generation)}canEvict(q){if(q.pins>0||q.poisoned)return!1;try{return q.canEvict()}catch{return!1}}async disposeResident(q,$){if(this.residents.get(q.key)!==q)return;this.residents.delete(q.key);try{await q.dispose()}catch(Q){if($&&!this.closed&&!this.residents.has(q.key))q.lastUsedAt=this.now(),q.poisoned=!0,this.residents.set(q.key,q);throw Q}}}function f(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q,{code:Q,kind:P,limit:L,reason:D,scope:J}=$;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||D!=="queue_full"&&D!=="wait_timeout"&&D!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(L)||L<=0||P!==void 0&&P!=="readonly"&&P!=="write"&&P!=="execute")return;return{code:Q,reason:D,scope:J,retryable:$.retryable,...P===void 0?{}:{kind:P},limit:L}}function T(q,$){if(!$||typeof $!=="object")return $;let Q={...$},P=f(Q.tool_admission);if(P)Q.tool_admission=P;else delete Q.tool_admission;if(N(q)){let J=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},h={},G=(Z,F,K)=>{let H=J[Z];if(typeof H==="string"&&Buffer.byteLength(H)<=F&&(!K||K.test(H)))h[Z]=H};if(G("action",64),G("status",16,/^(?:ok|warning|error)$/),G("pageId",V,/^browser_page_[a-f0-9-]+$/),G("snapshotId",V,/^browser_snapshot_[a-f0-9-]+$/),G("origin",X),G("candidateOrigin",X),G("url",x),G("title",B),G("errorCode",64,/^browser_[a-z_]+$/),typeof J.truncated==="boolean")h.truncated=J.truncated;if(typeof J.actionApplied==="boolean"||J.actionApplied==="unknown")h.actionApplied=J.actionApplied;if(typeof J.sideEffectsUncertain==="boolean")h.sideEffectsUncertain=J.sideEffectsUncertain;if(typeof J.diagnosticCount==="number"&&Number.isSafeInteger(J.diagnosticCount)&&J.diagnosticCount>=0&&J.diagnosticCount<=I)h.diagnosticCount=J.diagnosticCount;if(J.interaction&&typeof J.interaction==="object"&&!Array.isArray(J.interaction)){let Z=J.interaction,F=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof Z.action==="string"&&F.has(Z.action)){let K={action:Z.action};if(typeof Z.ref==="string"&&Buffer.byteLength(Z.ref)<=b&&/^[a-z][a-z0-9]*$/.test(Z.ref))K.ref=Z.ref;let H=(U,E,S)=>typeof U==="number"&&Number.isFinite(U)&&U>=E&&U<=S;if(Z.viewport&&typeof Z.viewport==="object"&&!Array.isArray(Z.viewport)){let U=Z.viewport;if(H(U.width,1,16384)&&H(U.height,1,16384))K.viewport={width:U.width,height:U.height}}if(Z.targetBox&&typeof Z.targetBox==="object"&&!Array.isArray(Z.targetBox)){let U=Z.targetBox;if(H(U.x,-16384,32768)&&H(U.y,-16384,32768)&&H(U.width,0,16384)&&H(U.height,0,16384))K.targetBox={x:U.x,y:U.y,width:U.width,height:U.height}}h.interaction=K}}if(J.artifact&&typeof J.artifact==="object"&&!Array.isArray(J.artifact)){let Z=J.artifact;if(typeof Z.id==="string"&&/^[a-f0-9]{64}$/.test(Z.id)&&Z.sha256===Z.id&&Z.kind==="image"&&Z.mimeType==="image/png"&&typeof Z.size==="number"&&Number.isSafeInteger(Z.size)&&Z.size>=0&&Z.size<=A&&Z.persisted===!0)h.artifact={id:Z.id,sha256:Z.sha256,kind:Z.kind,mimeType:Z.mimeType,size:Z.size,persisted:!0,...typeof Z.path==="string"&&Buffer.byteLength(Z.path)<=8192?{path:Z.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:h,...P?{tool_admission:P}:{}}}if(q==="Bash"){let J={},h=["message","signal","status","summary"],G=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],Z=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let K of h){let H=Q[K];if(typeof H==="string")J[K]=H.slice(0,8192)}for(let K of G){let H=Q[K];if(typeof H==="boolean")J[K]=H}for(let K of Z){let H=Q[K];if(typeof H==="number"&&Number.isSafeInteger(H)&&H>=0)J[K]=H}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))J.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")J.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")J.background_reason=Q.background_reason;for(let K of["bash_id","shell_id"]){let H=Q[K];if(typeof H==="string"&&H.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(H))J[K]=H}if(P)J.tool_admission=P;let F=Q.background_shell_admission;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F;if(K.code==="background_shell_busy"&&(K.scope==="session"||K.scope==="global")&&K.retryable===!0&&Number.isSafeInteger(K.limit)&&K.limit>0)J.background_shell_admission={code:K.code,scope:K.scope,retryable:K.retryable,limit:K.limit}}return J}let L=200000,D=(J,h)=>typeof J==="number"&&Number.isSafeInteger(J)&&J>=0&&J<=h?J:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>L)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>L)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let J=Q.mcpResult,h=Array.isArray(J.artifacts)?J.artifacts.slice(0,64).flatMap((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return[];let Z=G,F=new Set(["text","image","audio","resource"]);if(typeof Z.id!=="string"||!/^[a-f0-9]{64}$/.test(Z.id)||typeof Z.sha256!=="string"||Z.sha256!==Z.id||typeof Z.kind!=="string"||!F.has(Z.kind)||D(Z.size,67108864)!==Z.size||typeof Z.persisted!=="boolean")return[];return[{id:Z.id.slice(0,128),sha256:Z.sha256.slice(0,128),kind:Z.kind,size:Z.size,persisted:Z.persisted,...typeof Z.mimeType==="string"?{mimeType:Z.mimeType.slice(0,256)}:{},...typeof Z.sourceUri==="string"?{sourceUri:Z.sourceUri.slice(0,8192)}:{},...typeof Z.path==="string"?{path:Z.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:J.isError===!0,contentCount:D(J.contentCount,64),textBytes:D(J.textBytes,4194304),structuredBytes:D(J.structuredBytes,4194304),artifactCount:D(J.artifactCount,64),truncated:J.truncated===!0,binaryOmitted:J.binaryOmitted===!0,artifacts:h}}else delete Q.mcpResult;return Q}var y=(q,$)=>Object.fromEntries($.map((Q)=>[String(Q),q[Q]])),w=(q,$,Q,P=!1)=>({type:$,messageScoped:P,properties:y(q,Q)});function m(q){switch(q.kind){case"tool_start":if(!("function"in q.toolCall))return;return{type:"tool.start",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,arguments:q.toolCall.function.arguments,toolKind:q.toolKind}};case"tool_progress":if(!("function"in q.toolCall))return;return{type:"tool.progress",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,...q.update}};case"tool_result":{if(!("function"in q.toolCall))return;let $=q.toolCall.function.name;return{type:"tool.result",messageScoped:!0,toolName:$,properties:{toolName:$,toolCallId:q.toolCall.id,success:q.result.success,summary:q.result.metadata?.summary,output:z(R(_($,q.result),g)),metadata:T($,q.result.metadata)}}}case"provider_admission":return w(q,"provider.admission",["phase","requestClass","resource","scope","reason","queuePosition","queueDepth","inFlight","limit","waitMs","maxWaitMs","recoveryRemainingMs"]);case"provider_circuit":return w(q,"provider.circuit",["phase","reason","statusCode","retryAfterMs","nextProbeAt","openDurationMs","sampleCount","failureCount","recoveryRemainingMs"]);case"provider_retry":return w(q,"provider.retry",["phase","attempt","maxRetries","reason","statusCode","delayMs","nextRetryAt","mode","recoveryBudgetMs","recoveryElapsedMs","recoveryRemainingMs","exhaustedBy"]);case"provider_stall":return w(q,"provider.stall",["phase","stallCount","durationMs","warningAfterMs","timeoutMs","outputStarted"]);case"action_stationarity":return w(q,"action.stationarity",["phase","toolName","runLength","nudgeThreshold","haltThreshold","progressAware"]);case"mcp_catalog_changed":return w(q,"mcp.catalog.changed",["revision","serverName","added","removed","updated"],!0);case"mcp_content_changed":return w(q,"mcp.content.changed",["revision","serverName","contentKind","added","removed","updated"],!0);case"mcp_resource_updated":return w(q,"mcp.resource.updated",["revision","serverName","uri"],!0);case"mcp_connection_changed":return w(q,"mcp.connection.changed",["revision","serverName","phase","reason","attempt","maxAttempts","nextRetryAt","error"],!0);case"mcp_log":return w(q,"mcp.log",["revision","serverName","level","logger","message","projectedBytes","dataSha256","truncated","detailsOmitted","timestamp","synthetic"],!0);case"mcp_instructions_changed":return w(q,"mcp.instructions.changed",["revision","serverName","action","reason","text","sourceBytes","projectedBytes","sha256","truncated","detailsOmitted"],!0);case"mcp_task_changed":return w(q,"mcp.task.changed",["revision","taskId","serverName","toolName","status","statusMessage","createdAt","updatedAt","completedAt","hasResult","error"],!0);case"project_rules_loaded":return w(q,"project.rules.loaded",["files","triggerPaths","blockedWrite"],!0);default:return}}function a(q,$={}){let Q=m(q);if(!Q||!$.omitUndefined)return Q;return{...Q,properties:Object.fromEntries(Object.entries(Q.properties).filter(([,P])=>P!==void 0))}}
1
+ import{M as N,ka as _,la as z}from"./chunk-8wk4q3bz.js";import{$d as R,Xc as I,Zd as g,cd as x,dd as X,ed as B,fd as V,gd as b,wd as A}from"./chunk-7bvtz3mm.js";import{Di as M,Ei as O}from"./chunk-z7f2a75f.js";import{Mutex as j}from"async-mutex";class C extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(q){super("Session runtime capacity is full");this.limit=q;this.name="SessionRuntimeCapacityError"}}class W extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class Y extends Error{constructor(q){super(`Session runtime residency already owns key: ${q}`);this.name="SessionRuntimeResidencyConflictError"}}class k{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new j;nextGeneration=1;closed=!1;constructor(q){if(!M(q.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!O(q.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=q.maxResident,this.idleMs=q.idleMs,this.now=q.now??Date.now}acquire(q){let $=this.residents.get(q);if(!$||$.poisoned)return;return $.pins++,$.lastUsedAt=this.now(),this.createLease($)}owns(q,$){let Q=this.residents.get(q);return Boolean(Q&&($===void 0||Q.value===$))}async reserve(q,$){if(!q.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new W;if(this.residents.has(q)||this.reservations.has(q))throw new Y(q);while(this.retainedCount()>=this.maxResident){if(!$.allowEviction)throw new C(this.maxResident);let P=this.oldestEvictableWebResident();if(!P)throw new C(this.maxResident);await this.disposeResident(P,!0)}let Q={generation:this.allocateGeneration(),surface:$.surface};return this.reservations.set(q,Q),this.createReservation(q,Q)})}async remove(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$)return!1;if(Q.pins>0)return!1;return await this.disposeResident(Q,!0),!0})}async forget(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$||Q.pins>0)return!1;return this.residents.delete(q),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let q=0;while(!0){let $=this.oldestIdleWebResident();if(!$)return q;await this.disposeResident($,!0),q++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let q;for(let $ of[...this.residents.values()])try{await this.disposeResident($,!1)}catch(Q){q??=Q}if(this.residents.clear(),q!==void 0)throw q})}getStats(){let q=0;for(let $ of this.residents.values())if($.pins>0)q++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:q,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let q=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,q}createReservation(q,$){let Q=!1;return{commit:(P)=>{if(Q)throw new Y(q);if(P.key!==q||P.surface!==$.surface||this.reservations.get(q)!==$||this.closed)throw this.reservations.delete(q),Q=!0,this.closed?new W:new Y(q);this.reservations.delete(q);let L={...P,generation:$.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(q,L),Q=!0,this.createLease(L)},cancel:()=>{if(Q)return;if(this.reservations.get(q)===$)this.reservations.delete(q);Q=!0}}}createLease(q){let $=!1;return{value:q.value,release:()=>{if($)return;$=!0;let Q=this.residents.get(q.key);if(Q!==q||Q.generation!==q.generation)return;Q.pins=Math.max(0,Q.pins-1),Q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((q)=>this.canEvict(q))}oldestIdleWebResident(){let q=this.now();return this.sortedWebResidents().find(($)=>q-$.lastUsedAt>=this.idleMs&&this.canEvict($))}sortedWebResidents(){return[...this.residents.values()].filter((q)=>q.surface==="web").sort((q,$)=>q.lastUsedAt-$.lastUsedAt||q.generation-$.generation)}canEvict(q){if(q.pins>0||q.poisoned)return!1;try{return q.canEvict()}catch{return!1}}async disposeResident(q,$){if(this.residents.get(q.key)!==q)return;this.residents.delete(q.key);try{await q.dispose()}catch(Q){if($&&!this.closed&&!this.residents.has(q.key))q.lastUsedAt=this.now(),q.poisoned=!0,this.residents.set(q.key,q);throw Q}}}function f(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q,{code:Q,kind:P,limit:L,reason:D,scope:J}=$;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||D!=="queue_full"&&D!=="wait_timeout"&&D!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(L)||L<=0||P!==void 0&&P!=="readonly"&&P!=="write"&&P!=="execute")return;return{code:Q,reason:D,scope:J,retryable:$.retryable,...P===void 0?{}:{kind:P},limit:L}}function T(q,$){if(!$||typeof $!=="object")return $;let Q={...$},P=f(Q.tool_admission);if(P)Q.tool_admission=P;else delete Q.tool_admission;if(N(q)){let J=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},h={},G=(Z,F,K)=>{let H=J[Z];if(typeof H==="string"&&Buffer.byteLength(H)<=F&&(!K||K.test(H)))h[Z]=H};if(G("action",64),G("status",16,/^(?:ok|warning|error)$/),G("pageId",V,/^browser_page_[a-f0-9-]+$/),G("snapshotId",V,/^browser_snapshot_[a-f0-9-]+$/),G("origin",X),G("candidateOrigin",X),G("url",x),G("title",B),G("errorCode",64,/^browser_[a-z_]+$/),typeof J.truncated==="boolean")h.truncated=J.truncated;if(typeof J.actionApplied==="boolean"||J.actionApplied==="unknown")h.actionApplied=J.actionApplied;if(typeof J.sideEffectsUncertain==="boolean")h.sideEffectsUncertain=J.sideEffectsUncertain;if(typeof J.diagnosticCount==="number"&&Number.isSafeInteger(J.diagnosticCount)&&J.diagnosticCount>=0&&J.diagnosticCount<=I)h.diagnosticCount=J.diagnosticCount;if(J.interaction&&typeof J.interaction==="object"&&!Array.isArray(J.interaction)){let Z=J.interaction,F=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof Z.action==="string"&&F.has(Z.action)){let K={action:Z.action};if(typeof Z.ref==="string"&&Buffer.byteLength(Z.ref)<=b&&/^[a-z][a-z0-9]*$/.test(Z.ref))K.ref=Z.ref;let H=(U,E,S)=>typeof U==="number"&&Number.isFinite(U)&&U>=E&&U<=S;if(Z.viewport&&typeof Z.viewport==="object"&&!Array.isArray(Z.viewport)){let U=Z.viewport;if(H(U.width,1,16384)&&H(U.height,1,16384))K.viewport={width:U.width,height:U.height}}if(Z.targetBox&&typeof Z.targetBox==="object"&&!Array.isArray(Z.targetBox)){let U=Z.targetBox;if(H(U.x,-16384,32768)&&H(U.y,-16384,32768)&&H(U.width,0,16384)&&H(U.height,0,16384))K.targetBox={x:U.x,y:U.y,width:U.width,height:U.height}}h.interaction=K}}if(J.artifact&&typeof J.artifact==="object"&&!Array.isArray(J.artifact)){let Z=J.artifact;if(typeof Z.id==="string"&&/^[a-f0-9]{64}$/.test(Z.id)&&Z.sha256===Z.id&&Z.kind==="image"&&Z.mimeType==="image/png"&&typeof Z.size==="number"&&Number.isSafeInteger(Z.size)&&Z.size>=0&&Z.size<=A&&Z.persisted===!0)h.artifact={id:Z.id,sha256:Z.sha256,kind:Z.kind,mimeType:Z.mimeType,size:Z.size,persisted:!0,...typeof Z.path==="string"&&Buffer.byteLength(Z.path)<=8192?{path:Z.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:h,...P?{tool_admission:P}:{}}}if(q==="Bash"){let J={},h=["message","signal","status","summary"],G=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],Z=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let K of h){let H=Q[K];if(typeof H==="string")J[K]=H.slice(0,8192)}for(let K of G){let H=Q[K];if(typeof H==="boolean")J[K]=H}for(let K of Z){let H=Q[K];if(typeof H==="number"&&Number.isSafeInteger(H)&&H>=0)J[K]=H}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))J.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")J.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")J.background_reason=Q.background_reason;for(let K of["bash_id","shell_id"]){let H=Q[K];if(typeof H==="string"&&H.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(H))J[K]=H}if(P)J.tool_admission=P;let F=Q.background_shell_admission;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F;if(K.code==="background_shell_busy"&&(K.scope==="session"||K.scope==="global")&&K.retryable===!0&&Number.isSafeInteger(K.limit)&&K.limit>0)J.background_shell_admission={code:K.code,scope:K.scope,retryable:K.retryable,limit:K.limit}}return J}let L=200000,D=(J,h)=>typeof J==="number"&&Number.isSafeInteger(J)&&J>=0&&J<=h?J:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>L)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>L)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let J=Q.mcpResult,h=Array.isArray(J.artifacts)?J.artifacts.slice(0,64).flatMap((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return[];let Z=G,F=new Set(["text","image","audio","resource"]);if(typeof Z.id!=="string"||!/^[a-f0-9]{64}$/.test(Z.id)||typeof Z.sha256!=="string"||Z.sha256!==Z.id||typeof Z.kind!=="string"||!F.has(Z.kind)||D(Z.size,67108864)!==Z.size||typeof Z.persisted!=="boolean")return[];return[{id:Z.id.slice(0,128),sha256:Z.sha256.slice(0,128),kind:Z.kind,size:Z.size,persisted:Z.persisted,...typeof Z.mimeType==="string"?{mimeType:Z.mimeType.slice(0,256)}:{},...typeof Z.sourceUri==="string"?{sourceUri:Z.sourceUri.slice(0,8192)}:{},...typeof Z.path==="string"?{path:Z.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:J.isError===!0,contentCount:D(J.contentCount,64),textBytes:D(J.textBytes,4194304),structuredBytes:D(J.structuredBytes,4194304),artifactCount:D(J.artifactCount,64),truncated:J.truncated===!0,binaryOmitted:J.binaryOmitted===!0,artifacts:h}}else delete Q.mcpResult;return Q}var y=(q,$)=>Object.fromEntries($.map((Q)=>[String(Q),q[Q]])),w=(q,$,Q,P=!1)=>({type:$,messageScoped:P,properties:y(q,Q)});function m(q){switch(q.kind){case"tool_start":if(!("function"in q.toolCall))return;return{type:"tool.start",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,arguments:q.toolCall.function.arguments,toolKind:q.toolKind}};case"tool_progress":if(!("function"in q.toolCall))return;return{type:"tool.progress",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,...q.update}};case"tool_result":{if(!("function"in q.toolCall))return;let $=q.toolCall.function.name;return{type:"tool.result",messageScoped:!0,toolName:$,properties:{toolName:$,toolCallId:q.toolCall.id,success:q.result.success,summary:q.result.metadata?.summary,output:z(R(_($,q.result),g)),metadata:T($,q.result.metadata)}}}case"provider_admission":return w(q,"provider.admission",["phase","requestClass","resource","scope","reason","queuePosition","queueDepth","inFlight","limit","waitMs","maxWaitMs","recoveryRemainingMs"]);case"provider_circuit":return w(q,"provider.circuit",["phase","reason","statusCode","retryAfterMs","nextProbeAt","openDurationMs","sampleCount","failureCount","recoveryRemainingMs"]);case"provider_retry":return w(q,"provider.retry",["phase","attempt","maxRetries","reason","statusCode","delayMs","nextRetryAt","mode","recoveryBudgetMs","recoveryElapsedMs","recoveryRemainingMs","exhaustedBy"]);case"provider_stall":return w(q,"provider.stall",["phase","stallCount","durationMs","warningAfterMs","timeoutMs","outputStarted"]);case"action_stationarity":return w(q,"action.stationarity",["phase","toolName","runLength","nudgeThreshold","haltThreshold","progressAware"]);case"mcp_catalog_changed":return w(q,"mcp.catalog.changed",["revision","serverName","added","removed","updated"],!0);case"mcp_content_changed":return w(q,"mcp.content.changed",["revision","serverName","contentKind","added","removed","updated"],!0);case"mcp_resource_updated":return w(q,"mcp.resource.updated",["revision","serverName","uri"],!0);case"mcp_connection_changed":return w(q,"mcp.connection.changed",["revision","serverName","phase","reason","attempt","maxAttempts","nextRetryAt","error"],!0);case"mcp_log":return w(q,"mcp.log",["revision","serverName","level","logger","message","projectedBytes","dataSha256","truncated","detailsOmitted","timestamp","synthetic"],!0);case"mcp_instructions_changed":return w(q,"mcp.instructions.changed",["revision","serverName","action","reason","text","sourceBytes","projectedBytes","sha256","truncated","detailsOmitted"],!0);case"mcp_task_changed":return w(q,"mcp.task.changed",["revision","taskId","serverName","toolName","status","statusMessage","createdAt","updatedAt","completedAt","hasResult","error"],!0);case"project_rules_loaded":return w(q,"project.rules.loaded",["files","triggerPaths","blockedWrite"],!0);default:return}}function a(q,$={}){let Q=m(q);if(!Q||!$.omitUndefined)return Q;return{...Q,properties:Object.fromEntries(Object.entries(Q.properties).filter(([,P])=>P!==void 0))}}
2
2
  export{C as w,k as x,T as y,a as z};
@@ -24,7 +24,7 @@ import{Eh as YO}from"./chunk-ys8gysg8.js";import{Zi as P}from"./chunk-b22ab7yw.j
24
24
  `):void 0,warning:Z.length>0?Z.join(`
25
25
  `):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(`
26
26
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
27
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await B.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((R)=>setTimeout(R,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 R=V.name==="AbortError"||V.code==="ABORT_ERR";if(R&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(R){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-s7jd42xp.js"),{createChatServiceAsync:W}=await import("./chunk-gwf872nm.js"),{resolveModelConfig:J}=await import("./chunk-eb10zapp.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-rcfef8qj.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((R)=>R.id===O):F.config.models.find((R)=>R.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} 事件中被触发。
27
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await B.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((R)=>setTimeout(R,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 R=V.name==="AbortError"||V.code==="ABORT_ERR";if(R&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(R){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-j5nz7kb4.js"),{createChatServiceAsync:W}=await import("./chunk-gwf872nm.js"),{resolveModelConfig:J}=await import("./chunk-eb10zapp.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-k5595spk.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((R)=>R.id===O):F.config.models.find((R)=>R.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} 事件中被触发。
28
28
 
29
29
  `+`## 评估指令
30
30
  ${O.prompt}
@@ -1,4 +1,4 @@
1
- import{Ea as I,Ga as K}from"./chunk-e613h191.js";import{de as l,fe as V,ne as q}from"./chunk-ayqqhefz.js";import{Yg as z}from"./chunk-34y4z9ns.js";import{Zi as x}from"./chunk-b22ab7yw.js";async function J(){await z(x())}async function N(y){let R=y.message||y._?.[0];if(typeof R==="string"&&R.trim())return R;let G=y.stdin??process.stdin;if(!G.isTTY){let b=[];for await(let F of G)b.push(F);return Buffer.concat(b).toString("utf-8").trim()}if(y.defaultMessage!==void 0)return y.defaultMessage;throw Error("No input provided")}async function W(y){let R=y.message||y._?.[0];if(typeof R==="string"&&R.trim())return R;let G=y.stdin??process.stdin;if(G.isTTY)return;let b=[];for await(let O of G)b.push(Buffer.isBuffer(O)?O:Buffer.from(O));return Buffer.concat(b).toString("utf-8").trim()||void 0}async function X(y){if(!I(y))return{mode:"agent",content:y};let R=await K(y,{cwd:x(),surface:"headless",workspaceRoot:x()});if(!R.success)return{mode:"output",content:`Error: ${R.error||"未知错误"}`,exitCode:1};let G=R.data;if(G?.action==="invoke_skill"){let{skillName:b,skillArgs:F}=G;return{mode:"agent",content:F?`Please use the "${b}" skill to help me with: ${F}`:`Please use the "${b}" skill.`}}if(G?.action==="invoke_custom_command"||G?.action==="invoke_plugin_command"){let b=G.processedContent;return{mode:"agent",content:`# Custom Command: /${G.commandName}
1
+ import{Ea as I,Ga as K}from"./chunk-8wk4q3bz.js";import{de as l,fe as V,ne as q}from"./chunk-7bvtz3mm.js";import{Yg as z}from"./chunk-54mb3ar4.js";import{Zi as x}from"./chunk-b22ab7yw.js";async function J(){await z(x())}async function N(y){let R=y.message||y._?.[0];if(typeof R==="string"&&R.trim())return R;let G=y.stdin??process.stdin;if(!G.isTTY){let b=[];for await(let F of G)b.push(F);return Buffer.concat(b).toString("utf-8").trim()}if(y.defaultMessage!==void 0)return y.defaultMessage;throw Error("No input provided")}async function W(y){let R=y.message||y._?.[0];if(typeof R==="string"&&R.trim())return R;let G=y.stdin??process.stdin;if(G.isTTY)return;let b=[];for await(let O of G)b.push(Buffer.isBuffer(O)?O:Buffer.from(O));return Buffer.concat(b).toString("utf-8").trim()||void 0}async function X(y){if(!I(y))return{mode:"agent",content:y};let R=await K(y,{cwd:x(),surface:"headless",workspaceRoot:x()});if(!R.success)return{mode:"output",content:`Error: ${R.error||"未知错误"}`,exitCode:1};let G=R.data;if(G?.action==="invoke_skill"){let{skillName:b,skillArgs:F}=G;return{mode:"agent",content:F?`Please use the "${b}" skill to help me with: ${F}`:`Please use the "${b}" skill.`}}if(G?.action==="invoke_custom_command"||G?.action==="invoke_plugin_command"){let b=G.processedContent;return{mode:"agent",content:`# Custom Command: /${G.commandName}
2
2
 
3
3
  ${b}`}}return{mode:"output",content:R.content||R.message||"",exitCode:0}}async function m(y,R){let G=R&&y.getPendingSteeringCount()>0,b=R&&!G?await y.getGoal():null,F=b?.status==="active"||b?.status==="verifying",O=R&&!G&&!F,v=y.getTurnRecoveryAssessment?.()??{state:"none"},Z=O&&v.state!=="requires_attention"?await y.getRecoveredFinalResponse():void 0;return{pendingInputOnly:G,resumedGoal:b,goalContinuationOnly:F,finalRecovery:O,recoveryAssessment:v,recoveredFinalResponse:Z}}import{readFile as $,stat as L}from"node:fs/promises";import f from"node:path";function Q(y,R){let G;try{G=JSON.parse(y)}catch(b){throw Error(`Invalid JSON output schema from ${R}`,{cause:b})}return V(G).schema}async function _(y){if(y.jsonSchema!==void 0&&y.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(y.jsonSchema!==void 0)return Q(y.jsonSchema,"--json-schema");if(y.outputSchema===void 0)return;let R=f.resolve(y.outputSchema),G=await L(R);if(!G.isFile())throw Error(`Output schema path is not a regular file: ${R}`);if(G.size>l)throw Error(`Output schema exceeds ${l} bytes: ${R}`);return Q(await $(R,"utf8"),R)}function j(y){if(!(y instanceof Error))return!1;return y.message.includes("未找到会话")||y.message.includes("ENOENT")||y.message.includes("no such file")}async function A(y){try{return await q.loadSessionModelContext(y,x())}catch(R){if(j(R))return null;throw R}}async function C(y){if(y.resume===!0||y.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof y.resume==="string"&&y.resume.length>0){if(y.forkSession){let b=x(),F=await q.forkSession(y.resume,{newSessionId:y.sessionId,sourceProjectPath:b,targetProjectPath:b});return{...F,messages:await q.loadSessionModelContext(F.sessionId,b)}}let[R,G]=await Promise.all([q.loadSessionModelContext(y.resume),q.findSessionMetadata(y.resume)]);return{sessionId:y.resume,messages:R,metadata:G}}if(y.continue){let R=y.forkSession?await q.listSessions({cwd:x()}):await q.listSessions();if(R.length>0){let G=R[0].sessionId;if(y.forkSession){let b=x(),F=await q.forkSession(G,{newSessionId:y.sessionId,sourceProjectPath:b,targetProjectPath:b});return{...F,messages:await q.loadSessionModelContext(F.sessionId,b)}}return{sessionId:G,messages:await q.loadSessionModelContext(G),metadata:R[0]}}if(y.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(y.sessionId){let R=await A(y.sessionId);return{sessionId:y.sessionId,messages:R??[],...R?{metadata:await q.findSessionMetadata(y.sessionId,x())}:{}}}return{sessionId:`${y.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{J as p,N as q,W as r,X as s,m as t,_ as u,C as v};
@@ -1,4 +1,4 @@
1
- import{Zi as i}from"./chunk-b22ab7yw.js";import{$i as Kn,_i as rn,aj as Hn,ej as Yn,fj as _n,gj as Fn,hj as Vn,ij as qn,jj as ct,kj as Jn,lj as Qn,mj as Mn,nj as jn,oj as Wn,pj as Sn,qj as Zn,rj as kn,sj as ln,tj as yn,uj as vn,vj as te}from"./chunk-amabfzc8.js";import{wj as Pn,xj as xn}from"./chunk-m2x6pb4f.js";import{Ej as Ut,Gj as Lt,Hj as St,Ij as m}from"./chunk-saz6mwpq.js";import{Nj as Gn,Qj as tt}from"./chunk-xhwdac1j.js";import{Xj as xt,Yj as Bt}from"./chunk-c1331rdc.js";import{ck as b}from"./chunk-asgmmaec.js";import{dk as It}from"./chunk-ed2hdrwe.js";var nt;((r)=>{r.DEFAULT="default";r.AUTO_EDIT="autoEdit";r.YOLO="yolo";r.PLAN="plan"})(nt||={});var ne=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function ee(t){return t==="127.0.0.1"||t==="[::1]"||t.toLowerCase()==="localhost"}function $(t,n="MCP OAuth URL"){let e=new URL(t);if(e.username||e.password)throw Error(`${n} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ee(e.hostname)))throw Error(`${n} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var K=async(t,n)=>{$(t,"MCP OAuth request URL");let e=await fetch(t,{...n,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function et(t){let n=t.oauth;if(!n)return;let e=n;for(let s of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[s]!==void 0)throw Error(`MCP OAuth "${s}" is not supported; use standards-based discovery`);if(n.enabled!==!0)return{enabled:!1};if(t.type!=="http"&&t.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!t.url)throw Error("MCP OAuth requires an MCP server URL");if($(t.url,"MCP OAuth server URL"),Object.keys(t.headers??{}).find((s)=>s.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=n.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=n.scopes?.map((s)=>s.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((s)=>!s||s.length>128||!ne.test(s)))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 M=n.callbackPort;if(M!==void 0&&(!Number.isInteger(M)||M<1024||M>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},...M!==void 0?{callbackPort:M}:{}}}import{randomUUID as Et}from"node:crypto";import ge from"node:http";import{auth as wt}from"@modelcontextprotocol/sdk/client/auth.js";import ce from"open";import{createHash as _e,randomUUID as Me}from"node:crypto";import{constants as rt,promises as I}from"node:fs";import _t from"node:path";import Se from"write-file-atomic";import{Mutex as re}from"async-mutex";class U{entries=new Map;async runExclusive(t,n){let e=this.entries.get(t);if(!e)e={mutex:new re,operations:0},this.entries.set(t,e);e.operations++;try{return await e.mutex.runExclusive(n)}finally{if(e.operations--,e.operations===0&&this.entries.get(t)===e)this.entries.delete(t)}}getStats(){let t=0;for(let n of this.entries.values())t+=n.operations;return{keys:this.entries.size,operations:t}}}var bt=1,se=1048576,Ee=5000,ue=50,oe=/^[a-f0-9]{64}$/,me=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Te=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ae=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),dt=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(me),tokens:m.Optional(Te),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(ae),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),it=m.Object({version:m.Literal(bt),credentials:m.Record(m.String(),dt)},{additionalProperties:!1});function H(t,n){return t instanceof Error&&"code"in t&&t.code===n}function Ae(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(n){return H(n,"EPERM")}}function Mt(t){return structuredClone(t)}function ht(t){if(Object.keys(t.credentials).some((n)=>!oe.test(n)))throw Error("MCP OAuth credential store contains an invalid identity")}function Y(t){let n=new URL(t);return n.hash="",n.toString()}function st(t,n,e=[]){return _e("sha256").update(JSON.stringify({serverUrl:Y(t),clientId:n?.trim()||null,scopes:[...e].sort()})).digest("hex")}class N{static locks=new U;stateRoot;tokenFilePath;constructor(t=It()){this.stateRoot=_t.join(t,"mcp"),this.tokenFilePath=_t.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[t];return e?Mt(e):null})}async updateCredential(t,n){return this.runMutation(async(e)=>{let _=e.credentials[t],r=await n(_?Mt(_):null);if(r)e.credentials[t]=St(dt,r);else delete e.credentials[t];return r?Mt(e.credentials[t]):null})}async deleteCredential(t){await this.updateCredential(t,()=>null)}async listCredentialIds(){return N.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let n=await this.acquireStoreLock();try{let e=await this.readStore(),_=await t(e);return await this.writeStore(e),_}finally{await n()}})}async ensureStateRoot(){await I.mkdir(this.stateRoot,{recursive:!0,mode:448});let t=await I.lstat(this.stateRoot);if(!t.isDirectory()||t.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((t.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let t=await I.lstat(this.tokenFilePath);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((t.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(t.size>se)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let n=JSON.parse(await I.readFile(this.tokenFilePath,"utf8")),e=Lt(it,n);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return ht(e.data),e.data}catch(t){if(H(t,"ENOENT"))return{version:bt,credentials:{}};throw t}}async writeStore(t){await this.ensureStateRoot();let n=St(it,t);ht(n),await Se(this.tokenFilePath,`${JSON.stringify(n,null,2)}
1
+ import{Zi as i}from"./chunk-b22ab7yw.js";import{$i as Kn,_i as rn,aj as Hn,ej as Yn,fj as _n,gj as Fn,hj as Vn,ij as qn,jj as ct,kj as Jn,lj as Qn,mj as Mn,nj as jn,oj as Wn,pj as Sn,qj as Zn,rj as kn,sj as ln,tj as yn,uj as vn,vj as te}from"./chunk-amabfzc8.js";import{wj as Pn,xj as xn}from"./chunk-m2x6pb4f.js";import{Ej as Ut,Gj as Lt,Hj as St,Ij as m}from"./chunk-saz6mwpq.js";import{Nj as Gn,Qj as tt}from"./chunk-xhwdac1j.js";import{Xj as xt,Yj as Bt}from"./chunk-mnm8epn5.js";import{ck as b}from"./chunk-asgmmaec.js";import{dk as It}from"./chunk-ed2hdrwe.js";var nt;((r)=>{r.DEFAULT="default";r.AUTO_EDIT="autoEdit";r.YOLO="yolo";r.PLAN="plan"})(nt||={});var ne=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function ee(t){return t==="127.0.0.1"||t==="[::1]"||t.toLowerCase()==="localhost"}function $(t,n="MCP OAuth URL"){let e=new URL(t);if(e.username||e.password)throw Error(`${n} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ee(e.hostname)))throw Error(`${n} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var K=async(t,n)=>{$(t,"MCP OAuth request URL");let e=await fetch(t,{...n,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function et(t){let n=t.oauth;if(!n)return;let e=n;for(let s of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[s]!==void 0)throw Error(`MCP OAuth "${s}" is not supported; use standards-based discovery`);if(n.enabled!==!0)return{enabled:!1};if(t.type!=="http"&&t.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!t.url)throw Error("MCP OAuth requires an MCP server URL");if($(t.url,"MCP OAuth server URL"),Object.keys(t.headers??{}).find((s)=>s.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=n.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=n.scopes?.map((s)=>s.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((s)=>!s||s.length>128||!ne.test(s)))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 M=n.callbackPort;if(M!==void 0&&(!Number.isInteger(M)||M<1024||M>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},...M!==void 0?{callbackPort:M}:{}}}import{randomUUID as Et}from"node:crypto";import ge from"node:http";import{auth as wt}from"@modelcontextprotocol/sdk/client/auth.js";import ce from"open";import{createHash as _e,randomUUID as Me}from"node:crypto";import{constants as rt,promises as I}from"node:fs";import _t from"node:path";import Se from"write-file-atomic";import{Mutex as re}from"async-mutex";class U{entries=new Map;async runExclusive(t,n){let e=this.entries.get(t);if(!e)e={mutex:new re,operations:0},this.entries.set(t,e);e.operations++;try{return await e.mutex.runExclusive(n)}finally{if(e.operations--,e.operations===0&&this.entries.get(t)===e)this.entries.delete(t)}}getStats(){let t=0;for(let n of this.entries.values())t+=n.operations;return{keys:this.entries.size,operations:t}}}var bt=1,se=1048576,Ee=5000,ue=50,oe=/^[a-f0-9]{64}$/,me=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Te=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ae=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),dt=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(me),tokens:m.Optional(Te),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(ae),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),it=m.Object({version:m.Literal(bt),credentials:m.Record(m.String(),dt)},{additionalProperties:!1});function H(t,n){return t instanceof Error&&"code"in t&&t.code===n}function Ae(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(n){return H(n,"EPERM")}}function Mt(t){return structuredClone(t)}function ht(t){if(Object.keys(t.credentials).some((n)=>!oe.test(n)))throw Error("MCP OAuth credential store contains an invalid identity")}function Y(t){let n=new URL(t);return n.hash="",n.toString()}function st(t,n,e=[]){return _e("sha256").update(JSON.stringify({serverUrl:Y(t),clientId:n?.trim()||null,scopes:[...e].sort()})).digest("hex")}class N{static locks=new U;stateRoot;tokenFilePath;constructor(t=It()){this.stateRoot=_t.join(t,"mcp"),this.tokenFilePath=_t.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[t];return e?Mt(e):null})}async updateCredential(t,n){return this.runMutation(async(e)=>{let _=e.credentials[t],r=await n(_?Mt(_):null);if(r)e.credentials[t]=St(dt,r);else delete e.credentials[t];return r?Mt(e.credentials[t]):null})}async deleteCredential(t){await this.updateCredential(t,()=>null)}async listCredentialIds(){return N.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let n=await this.acquireStoreLock();try{let e=await this.readStore(),_=await t(e);return await this.writeStore(e),_}finally{await n()}})}async ensureStateRoot(){await I.mkdir(this.stateRoot,{recursive:!0,mode:448});let t=await I.lstat(this.stateRoot);if(!t.isDirectory()||t.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((t.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let t=await I.lstat(this.tokenFilePath);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((t.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(t.size>se)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let n=JSON.parse(await I.readFile(this.tokenFilePath,"utf8")),e=Lt(it,n);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return ht(e.data),e.data}catch(t){if(H(t,"ENOENT"))return{version:bt,credentials:{}};throw t}}async writeStore(t){await this.ensureStateRoot();let n=St(it,t);ht(n),await Se(this.tokenFilePath,`${JSON.stringify(n,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await I.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let t=_t.join(this.stateRoot,".oauth-credentials.lock"),n=Me(),e=Date.now()+Ee;while(Date.now()<e)try{let _=await I.open(t,rt.O_CREAT|rt.O_EXCL|rt.O_WRONLY,384);return await _.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:n,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await _.close(),async()=>{try{if(JSON.parse(await I.readFile(t,"utf8")).token===n)await I.unlink(t)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(_){if(!H(_,"EEXIST"))throw _;await this.removeDeadLock(t),await new Promise((r)=>setTimeout(r,ue))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(t){let n=await I.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&n.uid!==process.getuid()||(n.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await I.readFile(t,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!Ae(e.pid))await I.unlink(t)}}var Nt="127.0.0.1",ft=7777,Pt="/oauth/callback",ie=300000;class ut extends Error{constructor(t){super(`MCP server "${t}" requires OAuth authorization; run "blade mcp login ${t}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Ct extends Error{constructor(t){super(`MCP OAuth credentials are unavailable in this runtime for server "${t}"`);this.name="McpOAuthUnavailableError"}}function he(t){let n=t?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.11.8",
3
+ "version": "0.11.10",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1,2 +0,0 @@
1
- import{readFileSync as c}from"node:fs";import{dirname as n,join as l}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.11.8",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":"node scripts/test.js all","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",prepack:"node scripts/download-ripgrep.js && 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.86.1","@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:"^6.0.0",diff:"^8.0.4","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.16",open:"^10.1.2",pathe:"^2.0.3",picomatch:"^4.0.5",playwright:"1.63.0","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:"^8.10.2","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","wrap-ansi":"^9.0.2","write-file-atomic":"^7.0.1",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":"^5.0.1",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^5.0.1"}};var s;function i(){if(s)return s;let r=n(a(import.meta.url));for(let o=0;o<5;o++){try{let t=JSON.parse(c(l(r,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}r=n(r)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function d(){return i().version}function y(){return i().name}function v(){return i().description}function w(){return`v${d()} © 2025 Blade Code`}
2
- export{d as Xj,y as Yj,v as Zj,w as _j};
@@ -1 +0,0 @@
1
- import{k as a,l as b,m as c,n as d,o as e}from"./chunk-b0smnpzh.js";import"./chunk-c1331rdc.js";import"./chunk-gmpsfkgg.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +0,0 @@
1
- import{xf as a,yf as b}from"./chunk-re6hbrmb.js";import"./chunk-c1331rdc.js";import"./chunk-gmpsfkgg.js";export{a as globalOptions,b as cliConfig};