blade-code 0.10.109 → 0.10.111
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-z38a3vvk.js → chunk-1n23f3qb.js} +1 -1
- package/dist/{chunk-qxa90mwt.js → chunk-2hmc9pr9.js} +1 -1
- package/dist/{chunk-pa8pkt00.js → chunk-32zgv9dx.js} +1 -1
- package/dist/{chunk-e2mcqkgv.js → chunk-3y8qp69k.js} +1 -1
- package/dist/{chunk-m3w413zt.js → chunk-4je46cyf.js} +3 -3
- package/dist/{chunk-f8f96dca.js → chunk-4k61tkpp.js} +1 -1
- package/dist/{chunk-m8k3j75k.js → chunk-50prvxfw.js} +1 -1
- package/dist/{chunk-dzsjjhqy.js → chunk-541h9the.js} +1 -1
- package/dist/chunk-6pp5945x.js +1 -0
- package/dist/{chunk-jdx7c2pd.js → chunk-8pr55zfw.js} +1 -1
- package/dist/{chunk-k359hejz.js → chunk-agpbarbx.js} +1 -1
- package/dist/{chunk-21z1cm7p.js → chunk-ahjh8y56.js} +1 -1
- package/dist/{chunk-kdrn84pk.js → chunk-bq9cg7pa.js} +1 -1
- package/dist/chunk-ceaee099.js +1 -0
- package/dist/{chunk-rqmaqthv.js → chunk-cv20apqr.js} +1 -1
- package/dist/{chunk-aydxzp31.js → chunk-d7ytnvqy.js} +1 -1
- package/dist/{chunk-kckkqtyj.js → chunk-e99c1t8e.js} +1 -1
- package/dist/{chunk-jvedgz9x.js → chunk-ep657gs0.js} +1 -1
- package/dist/{chunk-7wnx6fq5.js → chunk-exv2prhq.js} +1 -1
- package/dist/{chunk-9metwvwb.js → chunk-fymsjr4x.js} +1 -1
- package/dist/{chunk-nshgwxk5.js → chunk-g4ftk610.js} +1 -1
- package/dist/{chunk-18metkce.js → chunk-gner6fka.js} +1 -1
- package/dist/{chunk-nehwxpq2.js → chunk-h25qd3d7.js} +1 -1
- package/dist/{chunk-ta43te9m.js → chunk-j7bdnptp.js} +1 -1
- package/dist/{chunk-ynjqrans.js → chunk-k7980hzm.js} +2 -2
- package/dist/{chunk-gbbtksvv.js → chunk-kx05z7sx.js} +1 -1
- package/dist/{chunk-hwzwjfvc.js → chunk-s6xw42mr.js} +1 -1
- package/dist/{chunk-2cdys9m5.js → chunk-snj119c2.js} +1 -1
- package/dist/{chunk-y5fet3r6.js → chunk-t30jd4wg.js} +1 -1
- package/dist/{chunk-gc3qqxhf.js → chunk-tk7yfgay.js} +1 -1
- package/dist/{chunk-dx95g6sa.js → chunk-vvhnv7ng.js} +1 -1
- package/dist/{chunk-q0x3jwz1.js → chunk-wkvh3xrp.js} +1 -1
- package/dist/{chunk-5yvqbshs.js → chunk-xgbnb37n.js} +1 -1
- package/dist/{chunk-zjgfvqjk.js → chunk-z1da8k2d.js} +1 -1
- package/dist/{chunk-88rbkzqr.js → chunk-zgw04ttb.js} +1 -1
- package/dist/{chunk-mvr12g3x.js → chunk-zh2vrkyt.js} +1 -1
- package/dist/{chunk-2jhj3462.js → chunk-zkrtn8b1.js} +1 -1
- package/dist/web/assets/{ChatView-p9tMKcFw.js → ChatView-DCHnicTP.js} +11 -11
- package/dist/web/assets/{CodeBlockHighlighter-DD7FIfcr.js → CodeBlockHighlighter-0VOa5Mes.js} +1 -1
- package/dist/web/assets/{FilePreview-DDpZFwlq.js → FilePreview-C_3KHzzj.js} +1 -1
- package/dist/web/assets/{KanbanBoard-1Bkr6fIi.js → KanbanBoard-D_NTkUnD.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-hkB9aVVA.js → MarkdownRenderer-3g4TPTeI.js} +3 -3
- package/dist/web/assets/{SettingsModal-KpvOJhBi.js → SettingsModal-3GMy6V-E.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-2FU_n9lh.js → TaskSwitcher-eCdxu5Eo.js} +1 -1
- package/dist/web/assets/{TerminalPanel-C-LpIqOw.js → TerminalPanel-9q9Trmv9.js} +1 -1
- package/dist/web/assets/{arrow-left-Bf8UJl0b.js → arrow-left-03GxbYI7.js} +1 -1
- package/dist/web/assets/{calendar-clock-BTAxrL8A.js → calendar-clock-8W4ostX1.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-CTzVylwH.js → chevrons-up-down-BboZzEAk.js} +1 -1
- package/dist/web/assets/{clock-3-Cm6_vdYx.js → clock-3-aXgeptZP.js} +1 -1
- package/dist/web/assets/{external-link-DJln2WFN.js → external-link-UkIIC2ds.js} +1 -1
- package/dist/web/assets/{folder-BXj3pohP.js → folder-BOCc5dv2.js} +1 -1
- package/dist/web/assets/{index-DQL9otjm.js → index-DaiT-mmo.js} +15 -15
- package/dist/web/assets/{pause-W092j5bW.js → pause-DVIT6IIr.js} +1 -1
- package/dist/web/assets/{play-OpsbZ_PE.js → play-DsdF5dji.js} +1 -1
- package/dist/web/assets/session-events-CWzF04l4.js +22 -0
- package/dist/web/assets/{teamService-Aj-8ajEO.js → teamService-BliaDj1Z.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-9xa0mdxg.js +0 -1
- package/dist/chunk-cdtwwc9v.js +0 -1
- package/dist/web/assets/session-events-BuugneNw.js +0 -22
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$d as F$,_d as n,ae as h_,be as D$,ce as j,de as c_,ee as f$,fe as n_,ge as z$,he as l_,ie as p_,ke as d0,ne as i_,oe as x$}from"./chunk-qdv0n8yt.js";import{tf as D0}from"./chunk-hv6hrsnk.js";import{lg as f0}from"./chunk-9g64g1np.js";import{xg as a1}from"./chunk-eyb9psbc.js";import{Kh as K$,Lh as M$,Mh as B0,Nh as g0,Oh as W0}from"./chunk-p3m1jyg5.js";import{Sh as B1}from"./chunk-ecd727xh.js";import{si as h0}from"./chunk-dvv28pkc.js";import{Ci as F0,zi as M0}from"./chunk-z52s82k7.js";import{Gi as a}from"./chunk-
|
|
1
|
+
import{$d as F$,_d as n,ae as h_,be as D$,ce as j,de as c_,ee as f$,fe as n_,ge as z$,he as l_,ie as p_,ke as d0,ne as i_,oe as x$}from"./chunk-qdv0n8yt.js";import{tf as D0}from"./chunk-hv6hrsnk.js";import{lg as f0}from"./chunk-9g64g1np.js";import{xg as a1}from"./chunk-eyb9psbc.js";import{Kh as K$,Lh as M$,Mh as B0,Nh as g0,Oh as W0}from"./chunk-p3m1jyg5.js";import{Sh as B1}from"./chunk-ecd727xh.js";import{si as h0}from"./chunk-dvv28pkc.js";import{Ci as F0,zi as M0}from"./chunk-z52s82k7.js";import{Gi as a}from"./chunk-s6xw42mr.js";import{Qi as q$,Ri as Q0,Si as A$,Ti as x,Ui as u,Wi as A0,Xi as t,Yi as k}from"./chunk-rkdxqx8m.js";import{readdir as v_,readFile as T0,rm as G0,stat as o0}from"node:fs/promises";import*as Y from"node:path";import{nanoid as P}from"nanoid";import{createHash as u$,randomUUID as h$}from"node:crypto";import*as h from"node:fs/promises";import*as b0 from"node:path";import{execFileSync as j$}from"node:child_process";import{createHash as y$}from"node:crypto";import{readFileSync as I$}from"node:fs";var m$=/^[a-f0-9]{64}$/;function O1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&m$.test($.fingerprint)}var T1={readFile:(_)=>I$(_,"utf8"),execFile:(_,$)=>j$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},v$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function X_(_,$){return{platform:_,fingerprint:y$("sha256").update(`${_}\x00${$}`).digest("hex")}}function P$(_,$){let R=$.readFile(`/proc/${_}/stat`).trim(),O=R.lastIndexOf(")");if(O<0)throw Error("Invalid /proc process stat");let T=R.slice(O+2).split(/\s+/)[19];if(!T||!/^\d+$/.test(T))throw Error("Missing process start ticks");return T}function x0(_,$=process.platform,R=T1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return X_($,P$(_,R));if($==="darwin"){let O=R.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return O?X_($,O):void 0}if($==="win32"){let O=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,X=R.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",O]).trim();return X?X_($,X):void 0}}catch{return}return}function X1(_,$){return x0(_,$.platform)?.fingerprint===$.fingerprint}function j2(_,$,R=T1,O=v$){if(!Number.isInteger(_)||_<=1)return!1;let X=x0(_,$.platform,R);if(X)return X.fingerprint===$.fingerprint;return!O(_)}var C1=1;function c$(_,$){let R=u$("sha256").update($).digest("hex");return b0.join(Q0(_),".locks",`${R}.lock`)}function w0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function L_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==C1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!O1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function L1(_){let $=await L_(_);if($)return $;return await new Promise((R)=>setTimeout(R,10)),L_(_)}function n$(_){try{return process.kill(_,0),!0}catch($){return w0($,"EPERM")}}async function W1(_,$){let R;try{return R=await h.open(_,"wx",384),await R.writeFile(`${JSON.stringify($)}
|
|
2
2
|
`,"utf8"),!0}catch(O){if(w0(O,"EEXIST"))return!1;if(R)await h.unlink(_).catch(()=>{return});throw O}finally{await R?.close().catch(()=>{return})}}class d extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class o{filePath;record;released=!1;constructor(_,$){this.filePath=_;this.record=$}static async acquire(_,$=B1()){let R=c$($,_),O={version:C1,sessionId:_,ownerId:h$(),pid:process.pid,processIdentity:x0(process.pid),acquiredAt:new Date().toISOString()};if(await h.mkdir(b0.dirname(R),{recursive:!0,mode:448}),await W1(R,O))return new o(R,O);let X=await L1(R);if(X&&n$(X.pid)&&(!X.processIdentity||X1(X.pid,X.processIdentity)))throw new d(X.pid);if(await h.unlink(R).catch((T)=>{if(!w0(T,"ENOENT"))throw T}),await W1(R,O))return new o(R,O);throw new d((await L1(R))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await L_(this.filePath))?.ownerId!==this.record.ownerId)return;await h.unlink(this.filePath).catch(($)=>{if(!w0($,"ENOENT"))throw $})}}import{createHash as k0}from"node:crypto";import{constants as s,promises as c}from"node:fs";import i from"node:path";import{Mutex as l$}from"async-mutex";var G1=128,V1=67108864,p$=24576,E1=65536,B_=1,H1=/^[a-f0-9]{64}$/,i$=/^[a-f0-9]{64}\.txt$/,U1=64,d$=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),j0=`
|
|
3
3
|
|
|
4
4
|
...[middle omitted; read the private prompt artifact for the complete request]...
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$b as En,_b as Xt,ac as yn,bc as bn}from"./chunk-cnhw5mqv.js";import{tg as Bt}from"./chunk-
|
|
1
|
+
import{$b as En,_b as Xt,ac as yn,bc as bn}from"./chunk-cnhw5mqv.js";import{tg as Bt}from"./chunk-zh2vrkyt.js";import{Ag as sn,Bg as zt,Cg as U,Dg as en,Eg as gt,Fg as mt,Hg as rn,Ig as Tn,Jg as B,Kg as dn,Lg as on,Mg as pn,Ng as lt,Og as un,Pg as cn,Qg as Mn,Sg as S,Vg as wn,Wg as Gt,Xg as Ut,Yg as h,Zg as Ht,yg as xt,zg as vi}from"./chunk-zkrtn8b1.js";import{Eh as X,Gh as x}from"./chunk-6k5k40p8.js";import{Sh as It}from"./chunk-ecd727xh.js";import{Gi as tn,Hi as nn}from"./chunk-s6xw42mr.js";import{_i as ns}from"./chunk-tf7ezqew.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{$e as n,Oe as a,Pe as b,Qe as c,Re as d,Se as e,Te as f,Ue as g,Ve as h,We as i,Xe as j,Ye as k,Ze as l,_e as m,af as o,bf as p,cf as q}from"./chunk-
|
|
1
|
+
import{$e as n,Oe as a,Pe as b,Qe as c,Re as d,Se as e,Te as f,Ue as g,Ve as h,We as i,Xe as j,Ye as k,Ze as l,_e as m,af as o,bf as p,cf as q}from"./chunk-3y8qp69k.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-zkrtn8b1.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-s6xw42mr.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.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{Z as P}from"./chunk-
|
|
1
|
+
import{Z as P}from"./chunk-4je46cyf.js";import{wb as K}from"./chunk-exv2prhq.js";import{Td as B,ad as G,bd as N,cd as S,dd as O,ed as s}from"./chunk-tk7yfgay.js";import{ce as j}from"./chunk-qdv0n8yt.js";import{df as q}from"./chunk-pshyn3yy.js";import{Bf as v}from"./chunk-g4ftk610.js";import{Ui as z}from"./chunk-rkdxqx8m.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
|
|
2
2
|
`)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
|
|
3
3
|
`).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
|
|
4
4
|
`)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{pd as C}from"./chunk-
|
|
1
|
+
import{pd as C}from"./chunk-tk7yfgay.js";import{jh as F,kh as L}from"./chunk-zkrtn8b1.js";import{Mutex as G}from"async-mutex";class $ extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(j){super("Session runtime capacity is full");this.limit=j;this.name="SessionRuntimeCapacityError"}}class X extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class W extends Error{constructor(j){super(`Session runtime residency already owns key: ${j}`);this.name="SessionRuntimeResidencyConflictError"}}class U{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new G;nextGeneration=1;closed=!1;constructor(j){if(!F(j.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!L(j.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=j.maxResident,this.idleMs=j.idleMs,this.now=j.now??Date.now}acquire(j){let q=this.residents.get(j);if(!q||q.poisoned)return;return q.pins++,q.lastUsedAt=this.now(),this.createLease(q)}owns(j,q){let z=this.residents.get(j);return Boolean(z&&(q===void 0||z.value===q))}async reserve(j,q){if(!j.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new X;if(this.residents.has(j)||this.reservations.has(j))throw new W(j);while(this.retainedCount()>=this.maxResident){if(!q.allowEviction)throw new $(this.maxResident);let H=this.oldestEvictableWebResident();if(!H)throw new $(this.maxResident);await this.disposeResident(H,!0)}let z={generation:this.allocateGeneration(),surface:q.surface};return this.reservations.set(j,z),this.createReservation(j,z)})}async remove(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q)return!1;if(z.pins>0)return!1;return await this.disposeResident(z,!0),!0})}async forget(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q||z.pins>0)return!1;return this.residents.delete(j),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let j=0;while(!0){let q=this.oldestIdleWebResident();if(!q)return j;await this.disposeResident(q,!0),j++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let j;for(let q of[...this.residents.values()])try{await this.disposeResident(q,!1)}catch(z){j??=z}if(this.residents.clear(),j!==void 0)throw j})}getStats(){let j=0;for(let q of this.residents.values())if(q.pins>0)j++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:j,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let j=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,j}createReservation(j,q){let z=!1;return{commit:(H)=>{if(z)throw new W(j);if(H.key!==j||H.surface!==q.surface||this.reservations.get(j)!==q||this.closed)throw this.reservations.delete(j),z=!0,this.closed?new X:new W(j);this.reservations.delete(j);let J={...H,generation:q.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(j,J),z=!0,this.createLease(J)},cancel:()=>{if(z)return;if(this.reservations.get(j)===q)this.reservations.delete(j);z=!0}}}createLease(j){let q=!1;return{value:j.value,release:()=>{if(q)return;q=!0;let z=this.residents.get(j.key);if(z!==j||z.generation!==j.generation)return;z.pins=Math.max(0,z.pins-1),z.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((j)=>this.canEvict(j))}oldestIdleWebResident(){let j=this.now();return this.sortedWebResidents().find((q)=>j-q.lastUsedAt>=this.idleMs&&this.canEvict(q))}sortedWebResidents(){return[...this.residents.values()].filter((j)=>j.surface==="web").sort((j,q)=>j.lastUsedAt-q.lastUsedAt||j.generation-q.generation)}canEvict(j){if(j.pins>0||j.poisoned)return!1;try{return j.canEvict()}catch{return!1}}async disposeResident(j,q){if(this.residents.get(j.key)!==j)return;this.residents.delete(j.key);try{await j.dispose()}catch(z){if(q&&!this.closed&&!this.residents.has(j.key))j.lastUsedAt=this.now(),j.poisoned=!0,this.residents.set(j.key,j);throw z}}}import{createHash as B}from"node:crypto";var P=4,b=1000,Y=4000,D=120000,O=0.2;function w(j){try{return C(j)&&j.retryable}catch{return!1}}function N(j,q){let z=Number.isSafeInteger(q)&&q>0?q:1,H=z-1,J=Math.min(b*2**H,Y),K=B("sha256").update(`${j}\x00${z}`).digest().readUInt32BE(0)/4294967295,Q=1-O+2*O*K;return Math.min(Y,Math.max(0,Math.round(J*Q)))}function _(j){let q=N(j.sessionIdentity,j.failedAttempt),z=j.evidence,H=j.workStillPending===!0&&z!==void 0&&w(z.taskFailure)&&z.outputStarted===!1&&z.toolExecutionStarted===!1&&Number.isInteger(z.toolCallsCount)&&z.toolCallsCount===0,J=Number.isSafeInteger(j.failedAttempt)&&j.failedAttempt>0&&j.failedAttempt<P,Z=j.now??Date.now(),K=Z-j.recoveryStartedAt,Q=Number.isFinite(Z)&&Number.isFinite(j.recoveryStartedAt)&&Number.isFinite(K)&&K>=0&&K+q<=D;return{phase:H?J&&Q?"retry_scheduled":"exhausted":"failed",delayMs:q,retryable:H,withinAttemptBudget:J,withinTimeBudget:Q}}
|
|
2
2
|
export{$ as s,U as t,P as u,D as v,_ as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Qf as a,Rf as b,Sf as c,Tf as d,Uf as e,Vf as f,Wf as g,Xf as h,Yf as i,Zf as j}from"./chunk-
|
|
1
|
+
import{Qf as a,Rf as b,Sf as c,Tf as d,Uf as e,Vf as f,Wf as g,Xf as h,Yf as i,Zf as j}from"./chunk-g4ftk610.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-zh2vrkyt.js";import"./chunk-eyb9psbc.js";import"./chunk-zkrtn8b1.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-s6xw42mr.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.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};
|
|
@@ -25,7 +25,7 @@ import{xg as YO}from"./chunk-eyb9psbc.js";import{Eh as qO,Gh as S,Jh as y}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-wkvh3xrp.js"),{createChatServiceAsync:W}=await import("./chunk-wyw17nfy.js"),{resolveModelConfig:J}=await import("./chunk-25ps9fxw.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-32zgv9dx.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{Dh as Y}from"./chunk-4w4wjm49.js";import{Eh as on,Fh as F,Gh as o}from"./chunk-6k5k40p8.js";import{Kh as ct,Lh as bt}from"./chunk-p3m1jyg5.js";import{Sh as x}from"./chunk-ecd727xh.js";import{$h as it,Th as Jn,Uh as Xt,Vh as pt,Zh as gt,_h as kn,ai as Rt,bi as Ct,ci as un,di as zt,ei as Bt,fi as On,gi as Kt,hi as Ut,ii as jn,ji as Ht,ki as Yt,li as qt,mi as Vt,ni as Qt,oi as Gt}from"./chunk-x05zyqzf.js";import{si as fn}from"./chunk-dvv28pkc.js";import{vi as $t,yi as J}from"./chunk-dgf2xzzd.js";import{Gi as Pn,Hi as Ln}from"./chunk-
|
|
1
|
+
import{Dh as Y}from"./chunk-4w4wjm49.js";import{Eh as on,Fh as F,Gh as o}from"./chunk-6k5k40p8.js";import{Kh as ct,Lh as bt}from"./chunk-p3m1jyg5.js";import{Sh as x}from"./chunk-ecd727xh.js";import{$h as it,Th as Jn,Uh as Xt,Vh as pt,Zh as gt,_h as kn,ai as Rt,bi as Ct,ci as un,di as zt,ei as Bt,fi as On,gi as Kt,hi as Ut,ii as jn,ji as Ht,ki as Yt,li as qt,mi as Vt,ni as Qt,oi as Gt}from"./chunk-x05zyqzf.js";import{si as fn}from"./chunk-dvv28pkc.js";import{vi as $t,yi as J}from"./chunk-dgf2xzzd.js";import{Gi as Pn,Hi as Ln}from"./chunk-s6xw42mr.js";import{Ni as h}from"./chunk-vbwvsgs1.js";import{Yi as Tn}from"./chunk-rkdxqx8m.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">
|