blade-code 0.10.91 → 0.10.92
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-6wbhsgqd.js → chunk-0ayxntzc.js} +2 -2
- package/dist/{chunk-y7dtdwqx.js → chunk-0eqk29xr.js} +2 -2
- package/dist/{chunk-xrpmfq5d.js → chunk-1tjm9zdt.js} +1 -1
- package/dist/chunk-1ydbdbfj.js +1 -0
- package/dist/chunk-27y5dt0f.js +10 -0
- package/dist/chunk-2rpcwgr9.js +1 -0
- package/dist/chunk-30pq99z7.js +1 -0
- package/dist/{chunk-vxa67kca.js → chunk-339r521e.js} +3 -3
- package/dist/{chunk-j0rkfsdy.js → chunk-36dhm0fm.js} +2 -2
- package/dist/{chunk-47xjtzq5.js → chunk-3qtmrh3z.js} +1 -1
- package/dist/{chunk-tc1001nx.js → chunk-4cvmfne8.js} +1 -1
- package/dist/{chunk-r2nzt9jm.js → chunk-4jbpvete.js} +2 -2
- package/dist/chunk-54qgtz5s.js +1 -0
- package/dist/{chunk-7mj87nb9.js → chunk-602decf8.js} +3 -3
- package/dist/{chunk-ckqz2btx.js → chunk-74yge4ka.js} +1 -1
- package/dist/chunk-78agjkm5.js +1 -0
- package/dist/{chunk-45a1tsk1.js → chunk-7dqh8bqm.js} +1 -1
- package/dist/{chunk-xxk5d2v6.js → chunk-7k5v52ct.js} +1 -1
- package/dist/{chunk-yr16h4mj.js → chunk-7tda8v4p.js} +2 -2
- package/dist/{chunk-f7p7tzx2.js → chunk-8eh0vp98.js} +2 -2
- package/dist/{chunk-sa259vbs.js → chunk-8hry1mq6.js} +2 -2
- package/dist/{chunk-rj49h1x1.js → chunk-9318pj5k.js} +1 -1
- package/dist/{chunk-rm8w0qg7.js → chunk-am66822r.js} +1 -1
- package/dist/{chunk-j6tp0ny9.js → chunk-cadgtmrr.js} +2 -2
- package/dist/{chunk-qn8jacbk.js → chunk-cx7g79et.js} +1 -1
- package/dist/chunk-d45gd36e.js +1 -0
- package/dist/chunk-d83bfr0b.js +2 -0
- package/dist/{chunk-8mee32xq.js → chunk-dd99sgf8.js} +1 -1
- package/dist/{chunk-x4zy3sez.js → chunk-dj0jfyms.js} +288 -288
- package/dist/{chunk-7r2p609r.js → chunk-dq5ry3nq.js} +1 -1
- package/dist/{chunk-27h9k89q.js → chunk-dwttn5xg.js} +1 -1
- package/dist/{chunk-mh92e9gy.js → chunk-epmxrw4f.js} +1 -1
- package/dist/{chunk-e6gfpm6b.js → chunk-fthm9y4q.js} +1 -1
- package/dist/{chunk-xhhgpbzs.js → chunk-gbsxnvgg.js} +1 -1
- package/dist/chunk-gf2vdsx3.js +1 -0
- package/dist/{chunk-hkh2nsam.js → chunk-h4j0nve8.js} +2 -2
- package/dist/{chunk-hjkz6k6v.js → chunk-h6fcb6ky.js} +1 -1
- package/dist/{chunk-33g68zy1.js → chunk-hrfh7wck.js} +1 -1
- package/dist/chunk-jgd76jdj.js +1 -0
- package/dist/chunk-jqky08cw.js +1 -0
- package/dist/{chunk-c0ecz59a.js → chunk-k8h7k11c.js} +1 -1
- package/dist/{chunk-s8hdg5y9.js → chunk-kp40bxpa.js} +2 -2
- package/dist/{chunk-50zkdamf.js → chunk-myzmv0ns.js} +2 -2
- package/dist/{chunk-7a8j14gg.js → chunk-n4gtzx4x.js} +1 -1
- package/dist/{chunk-1mb2y0e0.js → chunk-na1cney5.js} +2 -2
- package/dist/{chunk-m5hnyxf3.js → chunk-nh45xp7r.js} +1 -1
- package/dist/{chunk-11ajd6hj.js → chunk-nje776xv.js} +2 -2
- package/dist/{chunk-k38mgpj8.js → chunk-p8hgymk2.js} +1 -1
- package/dist/{chunk-1g5s5vf3.js → chunk-qa4efys0.js} +1 -1
- package/dist/{chunk-ff38sxd0.js → chunk-qxm67agj.js} +2 -2
- package/dist/{chunk-cwtj154q.js → chunk-qy68f2g6.js} +1 -1
- package/dist/{chunk-q15sm6vj.js → chunk-rsh4rw9k.js} +1 -1
- package/dist/chunk-rtdvy14c.js +1 -0
- package/dist/{chunk-vyk5nxsz.js → chunk-rxbxvq67.js} +2 -2
- package/dist/{chunk-bvp5wpz8.js → chunk-rzja9zza.js} +2 -2
- package/dist/{chunk-ne5w9ds8.js → chunk-t48zm299.js} +1 -1
- package/dist/{chunk-61sg8p2c.js → chunk-t5hfc8xq.js} +1 -1
- package/dist/{chunk-anpph83s.js → chunk-va1exak5.js} +1 -1
- package/dist/chunk-vy4dz3yz.js +1 -0
- package/dist/{chunk-4vng4fc2.js → chunk-w4e6xp05.js} +2 -2
- package/dist/{chunk-rxjyc6ff.js → chunk-w63dfcx5.js} +2 -2
- package/dist/{chunk-x079eg84.js → chunk-wbfa6xce.js} +2 -2
- package/dist/chunk-wm02k4gq.js +1 -0
- package/dist/chunk-xdvk6frk.js +1 -0
- package/dist/chunk-xphk45bp.js +1 -0
- package/dist/{chunk-7avnhnjn.js → chunk-ya5p7mx7.js} +1 -1
- package/dist/{chunk-d83meq4k.js → chunk-yjh47zv6.js} +1 -1
- package/dist/{chunk-zg73wrze.js → chunk-ysephh7s.js} +1 -1
- package/dist/{chunk-pxah309m.js → chunk-z24ha5jk.js} +2 -2
- package/dist/{chunk-ebxt5bv1.js → chunk-z5rtzcm4.js} +2 -2
- package/dist/chunk-z5xtgfja.js +8 -0
- package/dist/{chunk-q8jfwyr4.js → chunk-z6xfknxe.js} +1 -1
- package/dist/{chunk-3aejg2jy.js → chunk-zj4kfyer.js} +1 -1
- package/dist/{chunk-dm1knbf8.js → chunk-ztp2ff01.js} +2 -2
- package/dist/web/assets/ChatView-D-UBHYgT.js +58 -0
- package/dist/web/assets/{CodeBlockHighlighter-BR4c98oZ.js → CodeBlockHighlighter-CjP3le5E.js} +2 -2
- package/dist/web/assets/FilePreview-DRJTAYmL.js +54 -0
- package/dist/web/assets/KanbanBoard-CRu-0zva.js +16 -0
- package/dist/web/assets/{MarkdownRenderer-BVPIxk31.js → MarkdownRenderer-fbB4bMCw.js} +12 -12
- package/dist/web/assets/{SettingsModal-CuUrUdWR.js → SettingsModal-RAG8JMXx.js} +22 -2
- package/dist/web/assets/TaskSwitcher-DC-7RPBv.js +26 -0
- package/dist/web/assets/TerminalPanel-CCB3heKF.js +6 -0
- package/dist/web/assets/arrow-left-Dwndq437.js +6 -0
- package/dist/web/assets/calendar-clock-CNd8rd6n.js +6 -0
- package/dist/web/assets/chevrons-up-down-DGxAunkR.js +11 -0
- package/dist/web/assets/clock-3-BEqhPeh5.js +6 -0
- package/dist/web/assets/external-link-ClLpF7at.js +11 -0
- package/dist/web/assets/folder-B5LF32bS.js +11 -0
- package/dist/web/assets/index-BgdiwWDg.js +271 -0
- package/dist/web/assets/index-C8M-7zAh.css +1 -0
- package/dist/web/assets/pause-B39o8olb.js +6 -0
- package/dist/web/assets/play-Bmh7JaqQ.js +6 -0
- package/dist/web/assets/teamService-4Cn4uKC9.js +1 -0
- package/dist/web/index.html +2 -3
- package/package.json +1 -1
- package/dist/chunk-12e2yj9p.js +0 -2
- package/dist/chunk-1gnq2qz3.js +0 -1
- package/dist/chunk-3xpgkrnw.js +0 -1
- package/dist/chunk-7zjzykx2.js +0 -8
- package/dist/chunk-85s1nyaz.js +0 -1
- package/dist/chunk-8zvjcxze.js +0 -1
- package/dist/chunk-a1hvqk3r.js +0 -1
- package/dist/chunk-aj647rtw.js +0 -1
- package/dist/chunk-hj41cbd6.js +0 -1
- package/dist/chunk-kbgsbq7k.js +0 -1
- package/dist/chunk-kq9xrrhg.js +0 -1
- package/dist/chunk-nvakshbb.js +0 -1
- package/dist/chunk-qsxt9ejm.js +0 -1
- package/dist/chunk-s1xrzd14.js +0 -1
- package/dist/chunk-scdfsyfc.js +0 -10
- package/dist/chunk-tja1sejx.js +0 -1
- package/dist/chunk-vs5bmzj8.js +0 -1
- package/dist/web/assets/ChatView-juDcmnHV.js +0 -18
- package/dist/web/assets/FilePreview-DKgh-Chb.js +0 -8
- package/dist/web/assets/KanbanBoard-CQU0UQP8.js +0 -1
- package/dist/web/assets/TaskSwitcher-DB7by2ch.js +0 -1
- package/dist/web/assets/TerminalPanel-BN9ftZUH.js +0 -1
- package/dist/web/assets/index-BdnOTMNi.css +0 -1
- package/dist/web/assets/index-ebnhtfFC.js +0 -11
- package/dist/web/assets/teamService-CFKFv0qS.js +0 -1
- package/dist/web/assets/vendor-icons-CX5BfgqQ.js +0 -431
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ng as YO}from"./chunk-74yge4ka.js";import{uh as qO,wh as S,zh as y}from"./chunk-7dqh8bqm.js";import{Ih as P}from"./chunk-qa4efys0.js";import{ii as XO}from"./chunk-h4j0nve8.js";import{Ei as n}from"./chunk-dd99sgf8.js";import{Oi as r}from"./chunk-na1cney5.js";import{Qi as w}from"./chunk-nh45xp7r.js";var b;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(b||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import C from"node:path";import{LRUCache as fO}from"lru-cache";import{nanoid as R}from"nanoid";var N={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import DO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import k from"node:path";import{Mutex as SO}from"async-mutex";import GO from"write-file-atomic";var h=1,VO=1048576,LO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function zO(O){let q={};for(let Q of Object.values(b)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(b))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(zO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new SO;filePath;constructor(O=k.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let W;try{W=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let J=W.projects[Z];if(!J)return{...X,state:"untrusted"};return{...X,state:J.digest===$?"trusted":"modified",trustedDigest:J.digest,trustedAt:J.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:h,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>VO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==h)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!k.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!LO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:h,projects:Z}}async writeStore(O){let q=k.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await GO(this.filePath,`${JSON.stringify(O,null,2)}
|
|
2
2
|
`,{mode:384}),await j.chmod(this.filePath,384)}}class T extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function e(O,q={}){let Q;try{Q=new URL(O)}catch{throw new T(`Invalid URL: ${O}`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw new T(`Only http/https supported, got: ${Q.protocol}`);let Z=Q.hostname.toLowerCase();if(BO(Z,q.allowedHosts))return;if(Q.protocol==="http:"&&!q.allowHttp)throw new T(`HTTP (non-TLS) blocked for ${Z}; use https:// or add to allowedHosts`);if(AO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(PO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function BO(O,q){if(!q||q.length===0)return!1;return q.some((Q)=>{let Z=Q.toLowerCase();if(Z===O)return!0;if(Z.startsWith("*.")){let Y=Z.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function AO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function PO(O){let q=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!q)return!1;let[Q,Z]=q.slice(1).map(Number);if(Q===10)return!0;if(Q===172&&Z>=16&&Z<=31)return!0;if(Q===192&&Z===168)return!0;if(Q===169&&Z===254)return!0;return!1}function OO(O){if(!O)return{};let q={};for(let[Q,Z]of Object.entries(O))q[Q]=Z.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,$)=>{return process.env[$]??`\${${$}}`});return q}var UO=S.Object({hookEventName:S.Literal("PreToolUse"),permissionDecision:S.Optional(S.Enum(m)),permissionDecisionReason:S.Optional(S.String()),updatedInput:S.Optional(S.Record(S.String(),S.Unknown()))}),_O=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),KO=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),bO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),NO=S.Object({hookEventName:S.Literal("PermissionRequest"),permissionDecision:S.Optional(y(["approve","deny","ask"])),permissionDecisionReason:S.Optional(S.String())}),QO=S.Record(S.String(),S.Union([S.String(),S.Number(),S.Boolean(),S.Array(S.String(),{maxItems:100})]),{maxProperties:32}),MO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),wO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),CO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),EO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),jO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([UO,_O,KO,bO,NO,MO,TO,wO,CO,EO])),suppressOutput:S.Optional(S.Boolean())});function ZO(O){return qO(jO,O)}class p{parse(O,q,Q){if(O.timedOut){let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let Z=this.tryParseJSON(O.stdout);if(Z){let Y=ZO(Z);if(!Y.success){let X="error"in Y?Y.error.message:"Unknown validation error",W=Q?.failureBehavior||"ignore",J=`Invalid hook output JSON: ${X}`;if(W==="deny")return{success:!1,blocking:!0,error:J,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(W==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${J}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:J,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let $=Y.data;if($.decision?.behavior==="block")return{success:!1,blocking:!0,error:$.systemMessage||"Hook blocked execution",output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};if($.decision?.behavior==="async")return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}return this.parseByExitCode(O,q,Q)}parseByExitCode(O,q,Q){let Z=O.exitCode;switch(Z){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 124:{let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}default:{let Y=Q?.failureBehavior||"ignore",$=O.stderr||O.stdout||`Hook failed with exit code ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${$}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}}}tryParseJSON(O){try{let q=O.trim();if(!q)return null;let Q=q.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Q)return null;return JSON.parse(Q[1])}catch{return null}}}class u{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let q=this.maxSize-this.content.length;this.content+=O.substring(0,q)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class l{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,q,Q,Z){let Y=JSON.stringify(q);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let $=this.createSafeEnv(q,Q.environment),{child:X,processTree:W}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),J=new u(this.MAX_STDOUT_SIZE),G=new u(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{J.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await W.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,F)=>{let z=!1,V=!1,B,U=()=>{return B??=W.terminate(),B},K=null,H=()=>{if(K&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",K),K=null},I=setTimeout(()=>{z=!0,U()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(I),H(),z)await U();L({stdout:J.getContent(),stderr:G.getContent(),exitCode:z?124:f??1,timedOut:z})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(I),H(),F(f)}),Q.abortSignal){if(K=()=>{if(V)return;V=!0,clearTimeout(I),H(),U().then(()=>{L({stdout:J.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",K),Q.abortSignal.aborted)K()}})}createSafeEnv(O,q={}){return{...q,PATH:q.PATH??process.env.PATH??"",HOME:q.HOME??process.env.HOME??"",USER:q.USER??process.env.USER??"",SHELL:q.SHELL??process.env.SHELL??"/bin/sh",BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:""}}}var $O=XO("Execution"),yO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',Elicitation:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',ElicitationResult:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class x{processExecutor=new l;outputParser=new p;chatServiceCache=new Map;sessionModelResources=new Map;sessionEnvironments=new Map;trustWarnings=new Set;bindSessionModelResources(O,q,Q){for(let Z of q)this.sessionModelResources.set(this.sessionResourceKey(O,Z),Q),this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q.config.env)}bindSessionEnvironment(O,q,Q){for(let Z of q)this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q)}async unbindSessionModelResources(O,q){for(let Q of q){let Z=this.sessionResourceKey(O,Q);this.sessionModelResources.delete(Z),this.sessionEnvironments.delete(Z);let Y=`${Z}\x00`;for(let[$,X]of this.chatServiceCache){if(!$.startsWith(Y))continue;this.chatServiceCache.delete($),await X.dispose?.()}}}async executePreToolHooks(O,q,Q){if(O.length===0)return{decision:"allow"};let Z="tool_input"in q?q.tool_input:{},Y=[];for(let $ of O)try{let X={...q,...Z&&{tool_input:Z}},W=await this.executeHook($,X,Q);if(!W.success){if(W.blocking)return{decision:"deny",reason:W.error};if(W.needsConfirmation)return{decision:"ask",reason:W.warning||W.error};if(W.warning)Y.push(W.warning);continue}let J=W.output?.hookSpecificOutput;if(J&&"permissionDecision"in J){switch(J.permissionDecision){case"deny":return{decision:"deny",reason:J.permissionDecisionReason};case"ask":return{decision:"ask",reason:J.permissionDecisionReason};case"allow":break}if("updatedInput"in J&&J.updatedInput)Z={...Z,...J.updatedInput}}}catch(X){let W=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${W}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:W};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${W}. Continue?`}}return{decision:"allow",modifiedInput:Z,warning:Y.length>0?Y.join(`
|
|
3
3
|
`):void 0}}async executePostToolHooks(O,q,Q){if(O.length===0)return{};let Z=Q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,q,Q,Z),$=[],X=void 0,W=[];for(let J of Y){if(!J.success&&J.warning){W.push(J.warning);continue}let G=J.output?.hookSpecificOutput;if(G&&"additionalContext"in G){if(G.additionalContext)$.push(G.additionalContext);if("updatedOutput"in G&&G.updatedOutput!==void 0)X=G.updatedOutput}}return{additionalContext:$.length>0?$.join(`
|
|
4
4
|
|
|
@@ -25,7 +25,7 @@ import{lg as YO}from"./chunk-ckqz2btx.js";import{sh as qO,uh as S,xh 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-wm02k4gq.js"),{createChatServiceAsync:W}=await import("./chunk-gf2vdsx3.js"),{resolveModelConfig:J}=await import("./chunk-54qgtz5s.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-jgd76jdj.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}
|
|
@@ -42,4 +42,4 @@ ${O.prompt}
|
|
|
42
42
|
`+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
|
|
43
43
|
`+`- 如果没有发现问题,使用 "approve"
|
|
44
44
|
`+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(O){let q=O.trim(),Q=q.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(Q)return Q[1].trim();return q}async executeHooksConcurrently(O,q,Q,Z){let Y=[],$=new Set;for(let X of O){if($.size>=Z)await Promise.race($);let W=this.executeHook(X,q,Q).catch((G)=>({success:!1,blocking:!1,error:G instanceof Error?G.message:String(G),hook:X})),J=W.then(()=>{$.delete(J)}).catch(()=>{$.delete(J)});$.add(J),Y.push(W)}return Promise.all(Y)}}async function HO(O,q){let Q=O.body?.getReader();if(!Q)return"";let Z=new TextDecoder,Y=0,$="";while(!0){let{value:X,done:W}=await Q.read();if(W)break;if(Y+=X.byteLength,Y>q){try{Q.cancel()}catch{}$+=Z.decode(X.slice(0,q-(Y-X.byteLength)));break}$+=Z.decode(X,{stream:!0})}return $+=Z.decode(),$}import a from"picomatch";var IO=/^([A-Za-z0-9_|]+)\((.+)\)$/;class i{matches(O,q){if(!O)return!0;if(O.tools&&q.toolName){if(!this.matchTools(O.tools,q))return!1}if(O.paths){let Q=q.filePaths??(q.filePath?[q.filePath]:[]);if(Q.length===0||!Q.some((Z)=>this.matchPaths(O.paths,Z)))return!1}if(O.commands&&q.command){if(!this.matchCommands(O.commands,q.command))return!1}return!0}matchTools(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchToolWithParams(Q,q));return this.matchToolWithParams(O,q)}matchPaths(O,q){if(Array.isArray(O))return O.some((Z)=>{return a(Z)(q)});return a(O)(q)}matchCommands(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchPattern(q,Q));return this.matchPattern(q,O)}matchToolWithParams(O,q){let{toolName:Q,command:Z,filePath:Y}=q,$=IO.exec(O);if(!$)return this.matchPattern(Q,O);let[,X,W]=$;if(!this.matchPattern(Q,X))return!1;let J=this.getArgValues(Q,Z,q.filePaths??(Y?[Y]:[]));if(J.length===0)return!1;return J.some((G)=>this.matchGlobOrPattern(G,W))}getArgValues(O,q,Q=[]){if(O==="Bash"||O==="BashTool")return q?[q]:[];if(["Read","Edit","Write","ApplyPatch","Glob","Grep"].includes(O))return Q;return q?[q]:Q}matchGlobOrPattern(O,q){if(/[*?[\]{}!]/.test(q))try{return a(q,{bash:!0,dot:!0})(O)}catch{}if(q.endsWith("*")){let Q=q.slice(0,-1);return O.startsWith(Q)}return O===q}matchPattern(O,q){if(q==="*")return!0;if(!q.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(q))return O===q;if(q.includes("|"))return q.split("|").map((Z)=>Z.trim()).includes(O);try{return new RegExp(q).test(O)}catch{return O===q}}}var WO=64;class _{static instance=null;config=N;executor=new x;guard=new d;matcher=new i;processDisabled=!1;disabledSessions=new Set;sessionStateAliases=new Map;projectConfigs=new fO({max:WO});sessionConfigs=new Map;managedFunctionMatchers={};constructor(){}static getInstance(){if(!_.instance)_.instance=new _;return _.instance}bindSessionModelResources(O,q,Q){this.executor.bindSessionModelResources(O,q,Q)}bindSessionEnvironment(O,q,Q){this.executor.bindSessionEnvironment(O,q,Q)}bindSessionConfig(O,q,Q){let Z=this.sessionConfigKey(O,q[0]??P()),Y=this.disabledSessions.has(Z);for(let $ of q){let X=this.sessionConfigKey(O,$);if(Y||=this.disabledSessions.has(X),this.sessionStateAliases.set(X,Z),this.sessionConfigs.set(X,this.snapshotConfig(Q)),X!==Z)this.disabledSessions.delete(X)}if(Y)this.disabledSessions.add(Z)}async unbindSessionModelResources(O,q){let Q=`${O}\x00`;for(let Z of this.sessionConfigs.keys()){if(!Z.startsWith(Q))continue;this.sessionConfigs.delete(Z)}for(let Z of this.sessionStateAliases.keys()){if(!Z.startsWith(Q))continue;this.sessionStateAliases.delete(Z)}for(let Z of this.disabledSessions){if(!Z.startsWith(Q))continue;this.disabledSessions.delete(Z)}await this.executor.unbindSessionModelResources(O,q)}static resetInstance(){_.instance?.cleanup(),_.instance=null}loadConfig(O,q=P()){let Q=E(N,O),Z=c();Q=E(Q,Z),this.storeProjectConfig(q,Q)}isEnabled(O=P(),q){if(!(q?this.getExecutionConfig(q,O):this.getConfig(O)).enabled)return!1;if(this.processDisabled)return!1;if(q&&this.disabledSessions.has(this.sessionStateKey(q,O)))return!1;return!0}disable(){this.processDisabled=!0,console.log("[HookManager] Hooks disabled for this process")}enable(){this.processDisabled=!1,console.log("[HookManager] Hooks enabled for this process")}disableSession(O,q){this.disabledSessions.add(this.sessionStateKey(O,q))}enableSession(O,q){this.disabledSessions.delete(this.sessionStateKey(O,q))}isSessionEnabled(O,q){return this.isEnabled(q,O)}isSessionPaused(O,q){return this.disabledSessions.has(this.sessionStateKey(O,q))}getConfig(O=P()){let q=C.resolve(O),Q=this.projectConfigs.get(q);if(Q)return Q;if(q===C.resolve(P()))return this.config;return{...N,enabled:!1}}getExecutionConfig(O,q){return this.sessionConfigs.get(this.sessionConfigKey(O,q))??this.getConfig(q)}isExecutionEnabled(O,q,Q){return O.enabled===!0&&!this.processDisabled&&!this.disabledSessions.has(this.sessionStateKey(q,Q))}sessionStateKey(O,q){let Q=this.sessionConfigKey(O,q);return this.sessionStateAliases.get(Q)??Q}sessionConfigKey(O,q){return`${O}\x00${C.resolve(q)}`}snapshotConfig(O){let q=E(N,O);for(let Q of Object.values(b))q[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((Y)=>({...Y}))}));return q}storeProjectConfig(O,q){let Q=C.resolve(O);if(Q===C.resolve(P())){this.config=q,this.projectConfigs.delete(Q);return}this.projectConfigs.set(Q,q)}inheritProjectConfig(O,q,Q){let Z=Q?this.getExecutionConfig(Q,O):this.getConfig(O);if(this.storeProjectConfig(q,this.snapshotConfig(Z)),!Q)return;let Y=this.sessionConfigKey(Q,O),$=this.sessionConfigKey(Q,q),X=this.sessionStateAliases.get(Y)??Y,W=this.disabledSessions.has(X)||this.disabledSessions.has($);if(this.sessionConfigs.set($,this.snapshotConfig(Z)),this.sessionStateAliases.set($,X),$!==X)this.disabledSessions.delete($);if(W)this.disabledSessions.add(X)}getResidencyStats(){return{projectCapacity:WO,projectConfigs:this.projectConfigs.size,sessionConfigs:this.sessionConfigs.size,sessionAliases:this.sessionStateAliases.size}}getTrustStatus(O=P()){return A.getInstance().getStatus(O,this.getConfig(O))}trustProject(O=P(),q){return A.getInstance().trust(O,this.getConfig(O),q)}revokeProjectTrust(O=P()){return A.getInstance().revoke(O,this.getConfig(O))}registerFunction(O,q,Q,Z){let Y={type:"function",handler:Q,timeout:Z?.timeout},$={name:Z?.name??`inline-${O}-${Date.now()}`,matcher:q,hooks:[Y]};if(Z?.projectDir){let W=C.resolve(Z.projectDir),J=this.getConfig(W),G=J[O]??[];return J[O]=[...G,$],this.storeProjectConfig(W,J),()=>{let L=J[O];if(!L)return;J[O]=L.filter((F)=>F!==$)}}let X=this.managedFunctionMatchers[O]??[];return this.managedFunctionMatchers[O]=[...X,$],()=>{let W=this.managedFunctionMatchers[O]??[];this.managedFunctionMatchers[O]=W.filter((J)=>J!==$)}}async reloadConfig(O=P()){let q=await import("node:fs/promises"),Q=await import("node:path");try{let Z=Q.join(O,".blade","settings.local.json"),Y=await q.readFile(Z,"utf-8"),$=JSON.parse(Y);if($.hooks)this.loadConfig($.hooks,O)}catch{}}async executePreToolHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"allow"};if(Z.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(q,"PreToolUse"))return{decision:"allow"};let $={hook_event_name:"PreToolUse",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"allow"};let W={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{let J=await this.executor.executePreToolHooks(X,$,W);if(this.guard.markExecuted(q,"PreToolUse"),Z.permissionMode==="yolo"){if(J.decision==="deny")return J;return{decision:"allow",modifiedInput:J.modifiedInput,warning:J.warning,reason:J.reason}}return J}catch(J){return console.error("[HookManager] Error executing PreToolUse hooks:",J),{decision:"allow",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executePostToolHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(q,"PostToolUse"))return{};let X={hook_event_name:"PostToolUse",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,tool_response:Z,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(W.length===0)return{};let J={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{let G=await this.executor.executePostToolHooks(W,X,J);return this.guard.markExecuted(q,"PostToolUse"),G}catch(G){return console.error("[HookManager] Error executing PostToolUse hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}finally{this.guard.cleanup(q)}}async executeStopHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{shouldStop:!0};let Q={hook_event_name:"Stop",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},Z=this.getMatchingHooks("Stop",{},q);if(Z.length===0)return{shouldStop:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing Stop hooks:",$),{shouldStop:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSubagentStopHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{shouldStop:!0};let Z={hook_event_name:"SubagentStop",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,agent_type:O,task_description:q.taskDescription,success:q.success,result_summary:q.resultSummary,error:q.error},Y=this.getMatchingHooks("SubagentStop",{},Q);if(Y.length===0)return{shouldStop:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing SubagentStop hooks:",X),{shouldStop:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePermissionRequestHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"ask"};let $={hook_event_name:"PermissionRequest",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"ask"};let W={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,W)}catch(J){return console.error("[HookManager] Error executing PermissionRequest hooks:",J),{decision:"ask",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeUserPromptSubmitHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{proceed:!0};let Z={hook_event_name:"UserPromptSubmit",hook_execution_id:R(),timestamp:new Date().toISOString(),user_prompt:O,has_images:q.hasImages,image_count:q.imageCount,project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{},Q);if(Y.length===0)return{proceed:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",X),{proceed:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeSessionStartHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{proceed:!0};let Q={hook_event_name:"SessionStart",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},Z=this.getMatchingHooks("SessionStart",{},q);if(Z.length===0)return{proceed:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing SessionStart hooks:",$),{proceed:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSessionEndHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"SessionEnd",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,reason:O},Y=this.getMatchingHooks("SessionEnd",{},Q);if(Y.length===0)return{};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,Z,$),{}}catch(X){return console.error("[HookManager] Error executing SessionEnd hooks:",X),{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolUseFailureHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};let X={hook_event_name:"PostToolUseFailure",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,error:Z,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(W.length===0)return{};let J={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(W,X,J)}catch(G){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeNotificationHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{suppress:!1,message:q};let Y={hook_event_name:"Notification",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,notification_type:O,title:Q.title,message:q},$=this.getMatchingHooks("Notification",{},Z);if($.length===0)return{suppress:!1,message:q};let X={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeNotificationHooks($,Y,X)}catch(W){return console.error("[HookManager] Error executing Notification hooks:",W),{suppress:!1,message:q,warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeElicitationHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"Elicitation",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,server_name:O.serverName,mode:O.mode,message:O.message,requested_schema:O.requestedSchema,url:O.url,elicitation_id:O.elicitationId};return this.executeElicitationHookChain("Elicitation",Z,q,Q)}async executeElicitationResultHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{};let Y={hook_event_name:"ElicitationResult",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,server_name:O.serverName,mode:O.mode,elicitation_id:O.elicitationId,action:q.action,content:q.content};return this.executeElicitationHookChain("ElicitationResult",Y,Q,Z)}async executeElicitationHookChain(O,q,Q,Z){let Y=this.getMatchingHooks(O,{},Z);if(Y.length===0)return{};let $={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeElicitationHooks(Y,q,$)}catch(X){return{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeCompactionHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{blockCompaction:!1};let Z={hook_event_name:"Compaction",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,trigger:O,messages_before:q.messagesBefore,tokens_before:q.tokensBefore},Y=this.getMatchingHooks("Compaction",{},Q);if(Y.length===0)return{blockCompaction:!1};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeCompactionHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing Compaction hooks:",X),{blockCompaction:!1,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}getMatchingHooks(O,q,Q){let Z=[...Q[O]??[],...this.managedFunctionMatchers[O]??[]],Y=[];for(let $ of Z)if(this.matcher.matches($.matcher,q))Y.push(...$.hooks);return Y}extractFilePaths(O){let q=[],Q=["file_path","path","filePath","source","target"];for(let Z of Q){let Y=O[Z];if(typeof Y==="string")q.push(Y)}if(typeof O.patch==="string"){for(let Z of O.patch.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm))if(Z[1])q.push(Z[1]);for(let Z of O.patch.matchAll(/^\*\*\* Move to: (.+)$/gm))if(Z[1])q.push(Z[1])}return[...new Set(q)]}extractCommand(O,q){if(O==="Bash"||O==="BashTool"){let Q=q.command;if(typeof Q==="string")return Q}return}cleanup(){this.guard.cleanupAll(),this.config=N,this.processDisabled=!1,this.disabledSessions.clear(),this.sessionStateAliases.clear(),this.projectConfigs.clear(),this.sessionConfigs.clear(),this.managedFunctionMatchers={}}}
|
|
45
|
-
export{b as
|
|
45
|
+
export{b as hg,o as ig,_ as jg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
|
|
2
|
-
export{G as
|
|
2
|
+
export{G as kg,F as lg,R as mg,v as ng};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ai as f,vi as a,wi as b,xi as c,yi as d,zi as e}from"./chunk-myzmv0ns.js";import"./chunk-nh45xp7r.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
|
|
2
|
-
export{a as
|
|
2
|
+
export{a as uh,f as vh,l as wh,x as xh,b as yh,V as zh};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{oi as o}from"./chunk-w63dfcx5.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
|
|
2
2
|
export{e,i as f};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Sf as b1,Tf as L0,Uf as z1,Zf as N0}from"./chunk-yjh47zv6.js";import{cg as jO,dg as wO}from"./chunk-rsh4rw9k.js";import{gg as A1}from"./chunk-4cvmfne8.js";import{hg as b0,jg as J0}from"./chunk-602decf8.js";import{lh as S0,mh as GO,qh as I0}from"./chunk-z24ha5jk.js";import{uh as u,wh as L,zh as c1}from"./chunk-7dqh8bqm.js";import{Ih as M}from"./chunk-qa4efys0.js";import{ii as k,ji as S}from"./chunk-h4j0nve8.js";import{wi as u0}from"./chunk-myzmv0ns.js";import{Di as N}from"./chunk-rzja9zza.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
|
|
2
2
|
${J.map((K)=>`- ${K}`).join(`
|
|
3
3
|
`)}`:""].filter(Boolean).join(`
|
|
4
4
|
|
|
@@ -722,4 +722,4 @@ ${Z.join(`
|
|
|
722
722
|
</${Q}>`:"";return{content:K,files:[...O],references:O.map(O4),triggerPaths:[...$],contentBytes:Buffer.byteLength(K,"utf8"),provenanceSha256:w0(O.map((q)=>`${q.id}:${q.contentSha256}`).join(`
|
|
723
723
|
`))}}function AO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let K=O[J];if(!K)continue;let q=Buffer.byteLength(K.content,"utf8");if(q>Q)continue;Z.push(K),Q-=q}return Z.reverse()}class m{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=K1(O),this.definitions=Object.freeze([...$].sort(L1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=w0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
|
|
724
724
|
`))}static empty(O){return new m(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new m(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=c$){if(this.definitions.length===0)return q0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&G1(J.scopeDirectory,Q));return q0(AO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=l$){if(this.definitions.length===0)return q0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),K=[...new Set($.map((G)=>W1(z.relative(this.projectRoot,K1(G)))).filter(Y1))].sort(),q=new Map;for(let G of K)for(let Y of this.definitions){if(Q.has(Y.id))continue;if(!G1(Y.scopeDirectory,G))continue;if(Y.conditional){let X=z.posix.relative(Y.scopeDirectory||".",G);if(!Y.patterns?.some((U)=>xO(U,{dot:!0})(X)))continue}else if(G1(Y.scopeDirectory,J))continue;q.set(Y.id,Y)}let W=AO([...q.values()].sort(L1),Z);return q0(W,K,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return q0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(L1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=W1(z.relative(this.projectRoot,K1(O)));if($&&!Y1($))throw Error("Project instruction source is outside the catalog root");return $}}async function $4(O,$){let Q=await d.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>zO)throw Error(`Project rule exceeds ${zO} bytes`);let Z=await d.realpath($),J=W1(z.relative(O,Z));if(!Y1(J))throw Error("Project rule escapes its repository root");let K=await d.readFile(Z,"utf8");if(TO(K))throw Error("Project rule contains hidden control characters");let q=u$(K),W=q.content.trim();if(!W)throw Error("Project rule content must not be empty");let G=r$(q.data.paths),Y=e$(J),X=w0(JSON.stringify({relativePath:J,patterns:G??[],content:W}));return{id:`${Y.source}:${w0(J).slice(0,20)}`,relativePath:J,source:Y.source,kind:Y.kind,scopeDirectory:Y.scopeDirectory,priority:Y.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:W,contentSha256:X}}async function _O(O,$){let Q=t$(O);if(!$.projectTrusted)return m.empty(Q);let Z=await d.realpath(Q),J=g$.stream([...o$],{cwd:Z,absolute:!0,dot:!0,deep:s$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...a$]}),K=[];for await(let Y of J)if(K.push(Y.toString()),K.length>SO)throw Error(`Project rule catalog exceeds ${SO} files`);K.sort();let q=new Set(K.filter((Y)=>z.basename(Y)==="AGENTS.override.md").map((Y)=>z.dirname(Y))),W=[],G=0;for(let Y of K){if(z.basename(Y)==="AGENTS.md"&&q.has(z.dirname(Y)))continue;try{let X=await $4(Z,Y);if(G+=Buffer.byteLength(X.content,"utf8"),G>MO)throw Error(`Project rule catalog exceeds ${MO} bytes`);W.push(X)}catch(X){i$.warn(`[ProjectRules] Ignoring rule: ${X instanceof Error?X.message:String(X)}`)}}return new m(Z,W)}var DO=32,D0=64;class CO extends Error{capacity=D0;constructor(){super(`Workspace agent resource capacity is full (${D0})`);this.name="WorkspaceAgentResourceCapacityError"}}var x=new Map,X1=0,NO=[];async function Q4(O){let $=await N.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await q1(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function Z4(O){let $={...O};for(let Q of Object.values(b0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function J5(O){NO=[...new Set(O.map(($)=>H1.resolve($)))]}function EO(O,$){YO(O,$.plugins),C.releaseInstance(O,$.subagents),P.releaseInstance({cwd:O},$.skills),T.releaseInstance(O,$.commands),D.releaseInstance(O,$.plugins)}function vO(O){EO(O.workspaceRoot,O)}function K0(){while(x.size>DO){let O=!1;for(let[$,Q]of x){if(!Q.resources||Q.users>0)continue;if(x.get($)!==Q)continue;x.delete($),vO(Q.resources),O=!0;break}if(!O)return}}function J4(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),K0()}).unref?.()}async function q4(O,$){let Q=await N.getInstance().getStatus(O),Z=o(O),J=g({cwd:O}),K=T.getInstance(O),q=Q0(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),K.isInitialized()?void 0:K.initialize(O),q.isInitialized()?void 0:q.initialize(O,[...$.cliPluginDirs??NO])]),A0(O),await Z1(O);let W=await q1(O,{projectTrusted:Q.state==="trusted",plugins:q.getActive()}),G=await _O(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:K,plugins:q,communicationStyles:W,projectRules:G}}catch(W){throw EO(O,{subagents:Z,skills:J,commands:K,plugins:q}),W}}function K4(O,$){let Q={generation:X1,users:0};return Q.promise=q4(O,$).then((Z)=>{if(Q.generation!==X1||x.get(O)!==Q)return vO(Z),Z;return Q.resources=Z,K0(),Z},(Z)=>{if(x.get(O)===Q)x.delete(O);throw Z}),x.set(O,Q),Q}async function RO(O,$){let Q=H1.resolve(O),Z=x.get(Q);if(!Z){if(K0(),x.size>=D0)throw new CO;Z=K4(Q,$)}else x.delete(Q),x.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(K){throw Z.users=Math.max(0,Z.users-1),K0(),K}return{entry:Z,resources:J}}async function yO(O,$){if(!$)return;A0(O.workspaceRoot),await Z1(O.workspaceRoot),await Q4(O)}async function q5(O,$={}){let Q=await RO(O,$);try{return await yO(Q.resources,$.reconcilePlugins),Q.resources}finally{J4(Q.entry)}}async function K5(O,$,Q={}){let Z=await RO(O,Q);try{return await yO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),K0()}}function G5(){let O=0,$=0;for(let Q of x.values()){if(Q.resources)O++;$+=Q.users}return{capacity:DO,activeCapacity:D0,entries:x.size,initialized:O,inFlight:x.size-O,activeUsers:$}}function L5(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:H1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??wO.snapshot(),projectRules:O.projectRules?.snapshot()??m.empty($),hooks:Z4("hooks"in O&&O.hooks?O.hooks:J0.getInstance().getConfig($))}}function W5(){X1++;for(let[O,$]of x)if($.resources)A0(O);x.clear(),C.resetInstances(),P.resetInstance(),T.resetInstance(),D.resetInstance()}
|
|
725
|
-
export{Y4 as
|
|
725
|
+
export{Y4 as qf,X4 as rf,H4 as sf,M1 as tf,B4 as uf,S4 as vf,o as wf,y4 as xf,w1 as yf,g as zf,T as Af,r0 as Bf,M0 as Cf,D as Df,Q0 as Ef,Z1 as Ff,A0 as Gf,m as Hf,DO as If,D0 as Jf,CO as Kf,Q4 as Lf,J5 as Mf,q5 as Nf,K5 as Of,G5 as Pf,L5 as Qf,W5 as Rf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{uh as Q,vh as X,wh as U,xh as Z}from"./chunk-45a1tsk1.js";import{Bh as d,yh as N,zh as h}from"./chunk-12e2yj9p.js";import{gi as a}from"./chunk-hkh2nsam.js";import{Mi as i}from"./chunk-1mb2y0e0.js";var b=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],T={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},E=new Map;function D($,J,K){let B=new Set;for(let W of $.split(",")){let[Y,O]=W.split("/"),V=O?Number.parseInt(O,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${$}"`);let j=J,H=K;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[k,r]=Y.split("-");j=Number.parseInt(k,10),H=Number.parseInt(r,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<J||H>K||j>H)throw Error(`Invalid cron range "${Y}" in field "${$}"`);for(let k=j;k<=H;k+=V)B.add(k)}return B}function R($){let J=$.trim().split(/\s+/);if(J.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${J.length}`);let[K,B,W,Y,O]=J,V=D(O,b[4].min,b[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(K,b[0].min,b[0].max),hours:D(B,b[1].min,b[1].max),daysOfMonth:D(W,b[2].min,b[2].max),months:D(Y,b[3].min,b[3].max),daysOfWeek:j,domRestricted:W.trim()!=="*",dowRestricted:O.trim()!=="*"}}function y($,J){if(!J)return{minute:$.getMinutes(),hour:$.getHours(),dayOfMonth:$.getDate(),month:$.getMonth()+1,dayOfWeek:$.getDay()};let K=E.get(J);if(!K)K=new Intl.DateTimeFormat("en-US",{timeZone:J,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),E.set(J,K);let B=Object.fromEntries(K.formatToParts($).filter((W)=>W.type!=="literal").map((W)=>[W.type,W.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:T[B.weekday]??-1}}function p($,J,K){let B=y(J,K);if(!$.minutes.has(B.minute))return!1;if(!$.hours.has(B.hour))return!1;if(!$.months.has(B.month))return!1;let W=$.daysOfMonth.has(B.dayOfMonth),Y=$.daysOfWeek.has(B.dayOfWeek);if($.domRestricted&&$.dowRestricted)return W||Y;if($.domRestricted)return W;if($.dowRestricted)return Y;return!0}function e($,J,K){let B=R($),W=new Date(J.getTime());W.setSeconds(0,0),W.setMinutes(W.getMinutes()+1);let Y=new Date(J.getTime());Y.setFullYear(Y.getFullYear()+4);while(W.getTime()<=Y.getTime()){if(p(B,W,K))return new Date(W.getTime());W.setMinutes(W.getMinutes()+1)}return null}var S={s:1000,m:60000,h:3600000,d:86400000};function F1($){let K=$.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!K)return null;let B=Number.parseInt(K[1],10);if(!Number.isInteger(B)||B<=0)return null;let W=K[2]||"m";return B*S[W]}function Q1($){for(let J of["d","h","m","s"]){let K=S[J];if($%K===0)return`${$/K}${J}`}return`${Math.round($/1000)}s`}function F($,J,K){switch($.kind){case"cron":{if(!$.cron)return null;try{return e($.cron,J,$.timezone)}catch{return null}}case"interval":{if(!$.intervalMs||$.intervalMs<=0)return null;let W=new Date((K??J).getTime()+$.intervalMs);return W.getTime()<=J.getTime()?new Date(J.getTime()+1000):W}case"once":{if(!$.runAt)return null;let B=new Date($.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>J.getTime()?B:null}default:return null}}function z($){switch($.kind){case"cron":if(!$.cron)return"cron trigger requires a cron expression";try{if(R($.cron),$.timezone)new Intl.DateTimeFormat("en-US",{timeZone:$.timezone}).format();return null}catch(J){return J instanceof Error?J.message:"invalid cron expression"}case"interval":if(!$.intervalMs||$.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!$.runAt)return"once trigger requires runAt timestamp";let J=new Date($.runAt);if(Number.isNaN(J.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function z1($){switch($.kind){case"cron":return`cron: ${$.cron??"?"}`;case"interval":return`every ${$.intervalMs?Q1($.intervalMs):"?"}`;case"once":return`once at ${$.runAt??"?"}`;default:return"unknown"}}import{mkdir as P1,readFile as I1}from"node:fs/promises";import t from"node:path";import{nanoid as L1}from"nanoid";import D1 from"write-file-atomic";var l=16384;function v1($){let J=/^\s*\/btw(?:\s+([\s\S]*))?\s*$/iu.exec($);if(!J)return;return{question:(J[1]??"").trim()}}var w=X(Z(["default","autoEdit","yolo","plan"]));var v=X(Z(["user","assistant","system","tool"])),$1=X(Q.Union([Q.Object({type:Q.Literal("text"),text:Q.String()}),Q.Object({type:Q.Literal("image_url"),image_url:Q.Object({url:Q.String()})})])),m=Q.Union([Q.String(),Q.Array($1)]),R1=X(Q.Object({id:Q.String(),role:v,content:m,timestamp:Q.Number(),metadata:Q.Optional(Q.Record(Q.String(),Q.Unknown())),thinkingContent:Q.Optional(Q.String()),tool_call_id:Q.Optional(Q.String()),name:Q.Optional(Q.String()),tool_calls:Q.Optional(Q.Unknown())})),J1=X(Z(["queued","running","completed","failed","cancelled","interrupted"])),A=X(Z(["local","worktree"])),x=X(Z(["high","medium","low"])),C=X(Z(["feature","bug","maintenance","research"])),X1=X(Z(["applied","discarded","conflicted"])),Z1=X(Q.Object({status:X1,updatedAt:Q.String(),sourceCommit:Q.Optional(Q.String()),changedFiles:Q.Optional(Q.Integer({minimum:0})),message:Q.Optional(Q.String())})),B1=X(Q.Object({changedFiles:Q.Integer({minimum:0}),additions:Q.Integer({minimum:0}),deletions:Q.Integer({minimum:0}),commits:Q.Integer({minimum:0})})),K1=X(Q.Object({path:Q.String({minLength:1}),patch:Q.String({maxLength:2097152}),additions:Q.Integer({minimum:0}),deletions:Q.Integer({minimum:0}),binary:Q.Boolean(),truncated:Q.Boolean()})),S1=X(Q.Object({sessionId:Q.String(),projectPath:Q.String(),baseCommit:Q.String(),files:Q.Array(K1,{maxItems:100}),truncated:Q.Boolean()})),W1=Q.Union([Q.String(),Q.Number(),Q.Boolean(),Q.Array(Q.String())]),Y1=X(Q.Object({name:Q.String(),type:Z(["string","number","integer","boolean","select","multi-select"]),title:Q.String(),description:Q.Optional(Q.String()),required:Q.Boolean(),defaultValue:Q.Optional(W1),options:Q.Optional(Q.Array(Q.Object({value:Q.String(),label:Q.String()}))),format:Q.Optional(Z(["date","uri","email","date-time"])),minimum:Q.Optional(Q.Number()),maximum:Q.Optional(Q.Number()),minLength:Q.Optional(Q.Number()),maxLength:Q.Optional(Q.Number()),minItems:Q.Optional(Q.Number()),maxItems:Q.Optional(Q.Number())})),l1=X(Q.Object({serverName:Q.String(),mode:Z(["form","url"]),message:Q.String(),fields:Q.Optional(Q.Array(Y1)),requestedSchema:Q.Optional(Q.Record(Q.String(),Q.Unknown())),url:Q.Optional(Q.String()),domain:Q.Optional(Q.String()),elicitationId:Q.Optional(Q.String())})),H1=X(Q.Object({type:Z(["permission","question","elicitation"]),requestId:Q.String()})),j1=X(Q.Object({code:Z(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","capacity","runtime"]),message:Q.String({minLength:1,maxLength:500}),retryable:Q.Boolean(),resource:Q.Optional(Z(["pending_count","pending_bytes","resident_runtimes"]))})),M=X(Z(["auto","off","minimal","low","medium","high","xhigh","max"])),P=X(Z(["auto","standard","fast","flex"])),I=X(Z(["auto","low","medium","high"])),G=X(Q.Union([Z(["auto","pragmatic","friendly","explanatory"]),Q.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),_=X(Q.Object({sessionId:Q.String(),projectPath:Q.String(),title:Q.Optional(Q.String()),gitBranch:Q.Optional(Q.String()),rootId:Q.String(),parentId:Q.Optional(Q.String()),relationType:Q.Optional(Z(["subagent","fork"])),resumedFrom:Q.Optional(Q.String()),rootAgentId:Q.Optional(Q.String()),resumeDepth:Q.Optional(Q.Integer({minimum:0})),taskStatus:U(J1,"completed"),taskStatusReason:Q.Optional(Q.String()),taskFailure:Q.Optional(j1),taskStartedAt:Q.Optional(Q.String()),taskCompletedAt:Q.Optional(Q.String()),taskPromptSummary:Q.Optional(Q.String()),taskPriority:Q.Optional(x),taskKind:Q.Optional(C),taskDueAt:Q.Optional(Q.String()),taskModelId:Q.Optional(Q.String()),selectedModelId:Q.Optional(Q.String()),permissionMode:Q.Optional(w),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),communicationStyleDigest:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:Q.Optional(Q.Boolean()),taskRetriedFrom:Q.Optional(Q.Object({sessionId:Q.String(),projectPath:Q.String()})),taskDelivery:Q.Optional(Z1),taskIsolation:Q.Optional(A),taskSourceProjectPath:Q.Optional(Q.String()),taskWorktreePath:Q.Optional(Q.String()),taskWorktreeBranch:Q.Optional(Q.String()),taskBaseCommit:Q.Optional(Q.String()),taskDiffStat:Q.Optional(B1),taskQueuePosition:Q.Optional(Q.Integer({minimum:1})),taskQueueDepth:Q.Optional(Q.Integer({minimum:0})),taskConcurrencyLimit:Q.Optional(Q.Integer({minimum:1})),archivedAt:Q.Optional(Q.String()),archivedBySessionId:Q.Optional(Q.String()),pendingInteraction:Q.Optional(H1),messageCount:Q.Number(),firstMessageTime:Q.String(),lastMessageTime:Q.String(),hasErrors:Q.Boolean()})),u1=X(Q.Object({sessions:Q.Array(_),nextCursor:Q.Optional(Q.String())})),h1=X(Q.Object({session:_,archivedSessionIds:Q.Array(Q.String())})),d1=X(Q.Object({session:_,restoredSessionIds:Q.Array(Q.String())})),m1=X(Q.Object({version:Q.Literal(1),sessionId:Q.String(),goalId:Q.String(),objective:Q.String(),status:Z(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:Q.Optional(Q.Number()),tokensUsed:Q.Number(),timeUsedSeconds:Q.Number(),continuationCount:Q.Number(),statusReason:Q.Optional(Q.String()),completionVerification:Q.Optional(Q.Object({attempt:Q.Integer({minimum:1}),status:Z(["pending","pass","fail","partial"]),requestedAt:Q.String(),completedAt:Q.Optional(Q.String()),verifierSessionId:Q.Optional(Q.String()),summary:Q.Optional(Q.String()),evidenceSha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))})),prematureStop:Q.Optional(Q.Object({pattern:Q.Unsafe({type:"string"}),consecutiveCount:Q.Integer({minimum:1}),detectedAt:Q.String()})),verificationStall:Q.Optional(Q.Unsafe({type:"object"})),createdAt:Q.String(),updatedAt:Q.String()})),c=X(Q.Object({role:v,content:m,metadata:Q.Optional(Q.Unknown()),reasoningContent:Q.Optional(Q.String()),thinkingContent:Q.Optional(Q.String()),tool_call_id:Q.Optional(Q.String()),name:Q.Optional(Q.String()),tool_calls:Q.Optional(Q.Unknown())})),c1=X(Q.Object({session:_,messages:Q.Array(c)})),n=X(Z(["conversation","code","both"])),U1=X(Q.Object({messageId:Q.String(),preview:Q.String(),createdAt:Q.String(),fileCount:Q.Integer({minimum:0})})),n1=X(Q.Object({targetMessageId:Q.String({minLength:1}),mode:U(n,"conversation")})),g1=X(Q.Object({checkpoint:U1,mode:n,removedTurns:Q.Integer({minimum:1}),restoredFiles:Q.Array(Q.String()),messages:Q.Array(c)})),k1=Z(["running","completed","failed","cancelled"]),u=X(Q.Object({id:Q.String(),subagentType:Q.String(),description:Q.String(),status:k1,background:Q.Boolean(),rootAgentId:Q.String(),resumedFrom:Q.Optional(Q.String()),resumeDepth:Q.Integer({minimum:0}),createdAt:Q.Number(),lastActiveAt:Q.Number(),completedAt:Q.Optional(Q.Number()),restartRecovery:Q.Optional(Q.Object({outcome:Z(["completed","interrupted","failed"]),recoveredAt:Q.Number()})),result:Q.Optional(Q.Object({success:Q.Boolean(),message:Q.String(),error:Q.Optional(Q.String()),verificationCommands:Q.Optional(Q.Array(Q.String())),verificationVerdict:Q.Optional(Z(["pass","fail","partial"])),modifiedFiles:Q.Optional(Q.Array(Q.String()))})),stats:Q.Optional(Q.Object({tokens:Q.Optional(Q.Number()),toolCalls:Q.Optional(Q.Number()),duration:Q.Optional(Q.Number())}))})),o1=X(Q.Object({prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"})})),s1=X(Q.Object({source:u,session:u})),i1=X(Q.Object({sessionId:Q.String(),projectPath:Q.String()})),a1=X(Q.Object({path:Q.String(),name:Q.String(),gitBranch:Q.Optional(Q.String()),available:Q.Boolean(),isCurrent:Q.Boolean(),boundAt:Q.String()})),t1=X(Q.Union([Q.Object({cancelled:Q.Literal(!0)}),Q.Object({cancelled:Q.Literal(!1),path:Q.String({minLength:1})})])),r1=X(Q.Object({type:Q.String(),seq:Q.Optional(Q.Number()),properties:Q.Record(Q.String(),Q.Unknown())})),g=Q.Object({type:Z(["file","image","url"]),path:Q.Optional(Q.String()),url:Q.Optional(Q.String()),content:Q.Optional(Q.String({maxLength:h})),mimeType:Q.Optional(Q.String()),name:Q.Optional(Q.String())}),o=Q.Record(Q.String(),Q.Unknown()),T1=X(Q.Object({prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:Q.Optional(Q.String({minLength:1,maxLength:200})),taskPriority:U(x,"medium"),taskKind:U(C,"feature"),taskDueAt:Q.Optional(Q.String({minLength:1,maxLength:64})),projectPath:Q.Optional(Q.String()),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default"),attachments:Q.Optional(Q.Array(g,{maxItems:N})),outputSchema:Q.Optional(o)})),y1=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),taskPriority:Q.Optional(x),taskKind:Q.Optional(C),taskDueAt:Q.Optional(Q.Union([Q.String({minLength:1,maxLength:64}),Q.Null()]))})),p1=X(Q.Object({session:_,runId:Q.String(),messageId:Q.String(),status:Z(["queued","running"]),queuePosition:Q.Optional(Q.Integer({minimum:1})),queueDepth:Q.Optional(Q.Integer({minimum:0})),maxConcurrentTasks:Q.Optional(Q.Integer({minimum:1}))})),e1=X(Q.Object({action:Z(["apply","discard"])})),q=X(Q.Object({kind:Z(["cron","interval","once"]),cron:Q.Optional(Q.String({minLength:1,maxLength:120})),intervalMs:Q.Optional(Q.Integer({minimum:60000})),runAt:Q.Optional(Q.String({minLength:1,maxLength:40})),timezone:Q.Optional(Q.String({minLength:1,maxLength:80}))})),O1=X(Q.Object({modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default")})),f=X(Q.Object({id:Q.String(),title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:Q.String({minLength:1}),trigger:q,dispatch:O1,enabled:Q.Boolean(),createdAt:Q.String(),updatedAt:Q.String(),nextRunAt:Q.Union([Q.String(),Q.Null()]),expiresAt:Q.Union([Q.String(),Q.Null()]),lastRunAt:Q.Optional(Q.String()),lastRunSessionId:Q.Optional(Q.String()),lastStatus:Q.Optional(Z(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:Q.Optional(Q.String()),runCount:Q.Integer({minimum:0})})),QQ=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:Q.String({minLength:1}),trigger:q,modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default"),enabled:U(Q.Boolean(),!0)})),$Q=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.Optional(Q.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:Q.Optional(q),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:Q.Optional(A),permissionMode:Q.Optional(w),enabled:Q.Optional(Q.Boolean())})),JQ=X(Q.Object({schedules:Q.Array(f)})),XQ=X(Q.Object({content:Q.String({maxLength:d}),projectPath:Q.Optional(Q.String()),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),permissionMode:Q.Optional(w),attachments:Q.Optional(Q.Array(g,{maxItems:N})),outputSchema:Q.Optional(o)})),V1=Z(["completed","failed","aborted","timed_out","spawn_error"]),b1=X(Q.Object({version:Q.Literal(1),command:Q.String(),status:V1,exitCode:Q.Union([Q.Integer(),Q.Null()]),durationMs:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),stdoutOmittedBytes:Q.Integer({minimum:0}),stderrOmittedBytes:Q.Integer({minimum:0}),binaryOutput:Q.Boolean(),truncated:Q.Boolean()})),ZQ=X(Q.Object({command:Q.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:Q.Optional(Q.String())})),BQ=X(Q.Object({executionId:Q.String(),messageId:Q.String(),record:b1,auxiliary:Q.Boolean(),delivery:Q.Optional(Z(["current_turn","next_turn"])),queued:Q.Optional(Q.Integer({minimum:0}))})),KQ=X(Q.Object({question:Q.String({minLength:1,maxLength:l,pattern:"^(?![\\s\\S]*\\x00)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:Q.Optional(Q.String())})),WQ=X(Q.Object({response:Q.String({minLength:1}),durationMs:Q.Number({minimum:0}),modelId:Q.Optional(Q.String()),usage:Q.Optional(Q.Object({promptTokens:Q.Number({minimum:0}),completionTokens:Q.Number({minimum:0}),totalTokens:Q.Number({minimum:0}),reasoningTokens:Q.Optional(Q.Number({minimum:0})),cacheCreationInputTokens:Q.Optional(Q.Number({minimum:0})),cacheReadInputTokens:Q.Optional(Q.Number({minimum:0})),costUsd:Q.Optional(Q.Number({minimum:0}))}))})),YQ=X(Q.Object({projectPath:Q.String(),kind:Z(["uncommitted","base","commit"]),ref:Q.Optional(Q.String({maxLength:200})),instructions:Q.Optional(Q.String({maxLength:4000})),modelId:Q.Optional(Q.String({minLength:1,maxLength:200}))})),HQ=X(Q.Object({reviewId:Q.String(),status:Q.Literal("running")})),jQ=X(Q.Object({messageId:Q.String(),role:v,content:Q.String(),timestamp:Q.String()})),UQ=X(Q.Object({approved:Q.Boolean(),remember:Q.Optional(Q.Boolean()),scope:Q.Optional(Z(["once","session","project"])),targetMode:Q.Optional(w),feedback:Q.Optional(Q.String()),answers:Q.Optional(Q.Record(Q.String(),Q.Union([Q.String(),Q.Array(Q.String())]))),elicitation:Q.Optional(Q.Object({action:Z(["accept","decline","cancel"]),content:Q.Optional(Q.Record(Q.String(),Q.Union([Q.String({maxLength:4000}),Q.Number(),Q.Boolean(),Q.Array(Q.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),G1=X(Q.Object({id:G,name:Q.String({minLength:1,maxLength:80}),description:Q.String({minLength:1,maxLength:256}),source:Z(["built-in","user","project","plugin"]),contentSha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))})),kQ=X(Q.Object({id:Q.String(),displayName:Q.Optional(Q.String()),provider:Q.String(),model:Q.String(),contextWindow:Q.Optional(Q.Number()),maxTokens:Q.Optional(Q.Number()),reasoning:Q.Optional(Q.Boolean()),supportedReasoningEfforts:Q.Optional(Q.Array(Z(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:Q.Optional(Q.Array(Z(["standard","fast","flex"]))),supportedResponseVerbosities:Q.Optional(Q.Array(Z(["low","medium","high"]))),communicationStyles:Q.Optional(Q.Array(G1,{maxItems:36})),input:Q.Optional(Q.Array(Z(["text","image"]))),overrides:Q.Optional(Q.Object({baseUrl:Q.Optional(Q.String()),temperature:Q.Optional(Q.Number()),maxOutputTokens:Q.Optional(Q.Number()),timeout:Q.Optional(Q.Number()),streamIdleTimeout:Q.Optional(Q.Number({minimum:1000}))}))})),OQ=X(Z(["vs-dark","vs-light","hc-black"])),w1=X(Z(["light","dark","system"])),M1=X(Q.Object({language:Q.String(),codeTheme:Q.String(),uiTheme:w1,autoSaveSessions:Q.Boolean(),notifyBuild:Q.Boolean(),notifyErrors:Q.Boolean(),notifySounds:Q.Boolean(),privacyTelemetry:Q.Boolean(),privacyCrash:Q.Boolean(),agentTeamsEnabled:Q.Boolean(),communicationStyle:Q.Optional(G)})),VQ=X(Q.Partial(M1));var s=a("Service"),A1=1;function _1(){return t.join(i(),"schedules.json")}class L{filePath;static instance;static getInstance(){if(!L.instance)L.instance=new L;return L.instance}writeChain=Promise.resolve();constructor($=_1()){this.filePath=$}async readFile(){try{let $=await I1(this.filePath,"utf-8"),J=JSON.parse($);if(!J||!Array.isArray(J.schedules))return[];let K=[],B=0;for(let W of J.schedules){let Y=f.safeParse(W);if(Y.success)K.push(Y.data);else B+=1}if(B>0)s.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return K}catch($){let J=$;if(J.code!=="ENOENT")s.warn("[ScheduleStore] Failed to read schedules; treating as empty:",J);return[]}}async writeFile($){await P1(t.dirname(this.filePath),{recursive:!0,mode:493});let J={version:A1,schedules:$};await D1(this.filePath,JSON.stringify(J,null,2),{mode:384})}serializeWrite($){let J=this.writeChain.then($,$);return this.writeChain=J.then(()=>{return},()=>{return}),J}async list(){return this.readFile()}async get($){return(await this.readFile()).find((K)=>K.id===$)}async create($){return this.serializeWrite(async()=>{let J=$.trigger.kind==="cron"&&!$.trigger.timezone?{...$.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:$.trigger,K=z(J);if(K)throw Error(K);let B=new Date;if(J.kind==="once"&&new Date(J.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let W=B.toISOString(),Y=F(J,B),O={id:L1(10),title:$.title,prompt:$.prompt,projectPath:$.projectPath,trigger:J,dispatch:{modelId:$.modelId,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,isolation:$.isolation??"worktree",permissionMode:$.permissionMode??"default"},enabled:$.enabled??!0,createdAt:W,updatedAt:W,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(O),await this.writeFile(V),O})}async update($,J){return this.serializeWrite(async()=>{let K=await this.readFile(),B=K.findIndex((H)=>H.id===$);if(B===-1)return;let W=K[B];if(J.trigger){let H=J.trigger.kind==="cron"&&!J.trigger.timezone?{...J.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:J.trigger,k=z(H);if(k)throw Error(k);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");J={...J,trigger:H}}let Y={...W,...J,dispatch:J.dispatch?{...W.dispatch,...J.dispatch}:W.dispatch,updatedAt:new Date().toISOString()},O=!W.enabled,V=Y.enabled,j=J.trigger!==void 0;if((j||O&&V)&&J.nextRunAt===void 0){let H=new Date,k=F(Y.trigger,H);if(Y.nextRunAt=k?k.toISOString():null,j)Y.expiresAt=null}return K[B]=Y,await this.writeFile(K),Y})}async remove($){return this.serializeWrite(async()=>{let J=await this.readFile(),K=J.filter((B)=>B.id!==$);if(K.length===J.length)return!1;return await this.writeFile(K),!0})}async setEnabled($,J){return this.update($,{enabled:J})}}var NQ=L.getInstance();
|
|
2
|
-
export{l as
|
|
1
|
+
import{wh as Q,xh as X,yh as U,zh as Z}from"./chunk-7dqh8bqm.js";import{Ah as N,Bh as h,Dh as d}from"./chunk-d83bfr0b.js";import{ii as a}from"./chunk-h4j0nve8.js";import{Oi as i}from"./chunk-na1cney5.js";var b=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],T={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},E=new Map;function D($,J,K){let B=new Set;for(let W of $.split(",")){let[Y,O]=W.split("/"),V=O?Number.parseInt(O,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${$}"`);let j=J,H=K;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[k,r]=Y.split("-");j=Number.parseInt(k,10),H=Number.parseInt(r,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<J||H>K||j>H)throw Error(`Invalid cron range "${Y}" in field "${$}"`);for(let k=j;k<=H;k+=V)B.add(k)}return B}function R($){let J=$.trim().split(/\s+/);if(J.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${J.length}`);let[K,B,W,Y,O]=J,V=D(O,b[4].min,b[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(K,b[0].min,b[0].max),hours:D(B,b[1].min,b[1].max),daysOfMonth:D(W,b[2].min,b[2].max),months:D(Y,b[3].min,b[3].max),daysOfWeek:j,domRestricted:W.trim()!=="*",dowRestricted:O.trim()!=="*"}}function y($,J){if(!J)return{minute:$.getMinutes(),hour:$.getHours(),dayOfMonth:$.getDate(),month:$.getMonth()+1,dayOfWeek:$.getDay()};let K=E.get(J);if(!K)K=new Intl.DateTimeFormat("en-US",{timeZone:J,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),E.set(J,K);let B=Object.fromEntries(K.formatToParts($).filter((W)=>W.type!=="literal").map((W)=>[W.type,W.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:T[B.weekday]??-1}}function p($,J,K){let B=y(J,K);if(!$.minutes.has(B.minute))return!1;if(!$.hours.has(B.hour))return!1;if(!$.months.has(B.month))return!1;let W=$.daysOfMonth.has(B.dayOfMonth),Y=$.daysOfWeek.has(B.dayOfWeek);if($.domRestricted&&$.dowRestricted)return W||Y;if($.domRestricted)return W;if($.dowRestricted)return Y;return!0}function e($,J,K){let B=R($),W=new Date(J.getTime());W.setSeconds(0,0),W.setMinutes(W.getMinutes()+1);let Y=new Date(J.getTime());Y.setFullYear(Y.getFullYear()+4);while(W.getTime()<=Y.getTime()){if(p(B,W,K))return new Date(W.getTime());W.setMinutes(W.getMinutes()+1)}return null}var S={s:1000,m:60000,h:3600000,d:86400000};function F1($){let K=$.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!K)return null;let B=Number.parseInt(K[1],10);if(!Number.isInteger(B)||B<=0)return null;let W=K[2]||"m";return B*S[W]}function Q1($){for(let J of["d","h","m","s"]){let K=S[J];if($%K===0)return`${$/K}${J}`}return`${Math.round($/1000)}s`}function F($,J,K){switch($.kind){case"cron":{if(!$.cron)return null;try{return e($.cron,J,$.timezone)}catch{return null}}case"interval":{if(!$.intervalMs||$.intervalMs<=0)return null;let W=new Date((K??J).getTime()+$.intervalMs);return W.getTime()<=J.getTime()?new Date(J.getTime()+1000):W}case"once":{if(!$.runAt)return null;let B=new Date($.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>J.getTime()?B:null}default:return null}}function z($){switch($.kind){case"cron":if(!$.cron)return"cron trigger requires a cron expression";try{if(R($.cron),$.timezone)new Intl.DateTimeFormat("en-US",{timeZone:$.timezone}).format();return null}catch(J){return J instanceof Error?J.message:"invalid cron expression"}case"interval":if(!$.intervalMs||$.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!$.runAt)return"once trigger requires runAt timestamp";let J=new Date($.runAt);if(Number.isNaN(J.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function z1($){switch($.kind){case"cron":return`cron: ${$.cron??"?"}`;case"interval":return`every ${$.intervalMs?Q1($.intervalMs):"?"}`;case"once":return`once at ${$.runAt??"?"}`;default:return"unknown"}}import{mkdir as P1,readFile as I1}from"node:fs/promises";import t from"node:path";import{nanoid as L1}from"nanoid";import D1 from"write-file-atomic";var l=16384;function v1($){let J=/^\s*\/btw(?:\s+([\s\S]*))?\s*$/iu.exec($);if(!J)return;return{question:(J[1]??"").trim()}}var w=X(Z(["default","autoEdit","yolo","plan"]));var v=X(Z(["user","assistant","system","tool"])),$1=X(Q.Union([Q.Object({type:Q.Literal("text"),text:Q.String()}),Q.Object({type:Q.Literal("image_url"),image_url:Q.Object({url:Q.String()})})])),m=Q.Union([Q.String(),Q.Array($1)]),R1=X(Q.Object({id:Q.String(),role:v,content:m,timestamp:Q.Number(),metadata:Q.Optional(Q.Record(Q.String(),Q.Unknown())),thinkingContent:Q.Optional(Q.String()),tool_call_id:Q.Optional(Q.String()),name:Q.Optional(Q.String()),tool_calls:Q.Optional(Q.Unknown())})),J1=X(Z(["queued","running","completed","failed","cancelled","interrupted"])),A=X(Z(["local","worktree"])),x=X(Z(["high","medium","low"])),C=X(Z(["feature","bug","maintenance","research"])),X1=X(Z(["applied","discarded","conflicted"])),Z1=X(Q.Object({status:X1,updatedAt:Q.String(),sourceCommit:Q.Optional(Q.String()),changedFiles:Q.Optional(Q.Integer({minimum:0})),message:Q.Optional(Q.String())})),B1=X(Q.Object({changedFiles:Q.Integer({minimum:0}),additions:Q.Integer({minimum:0}),deletions:Q.Integer({minimum:0}),commits:Q.Integer({minimum:0})})),K1=X(Q.Object({path:Q.String({minLength:1}),patch:Q.String({maxLength:2097152}),additions:Q.Integer({minimum:0}),deletions:Q.Integer({minimum:0}),binary:Q.Boolean(),truncated:Q.Boolean()})),S1=X(Q.Object({sessionId:Q.String(),projectPath:Q.String(),baseCommit:Q.String(),files:Q.Array(K1,{maxItems:100}),truncated:Q.Boolean()})),W1=Q.Union([Q.String(),Q.Number(),Q.Boolean(),Q.Array(Q.String())]),Y1=X(Q.Object({name:Q.String(),type:Z(["string","number","integer","boolean","select","multi-select"]),title:Q.String(),description:Q.Optional(Q.String()),required:Q.Boolean(),defaultValue:Q.Optional(W1),options:Q.Optional(Q.Array(Q.Object({value:Q.String(),label:Q.String()}))),format:Q.Optional(Z(["date","uri","email","date-time"])),minimum:Q.Optional(Q.Number()),maximum:Q.Optional(Q.Number()),minLength:Q.Optional(Q.Number()),maxLength:Q.Optional(Q.Number()),minItems:Q.Optional(Q.Number()),maxItems:Q.Optional(Q.Number())})),l1=X(Q.Object({serverName:Q.String(),mode:Z(["form","url"]),message:Q.String(),fields:Q.Optional(Q.Array(Y1)),requestedSchema:Q.Optional(Q.Record(Q.String(),Q.Unknown())),url:Q.Optional(Q.String()),domain:Q.Optional(Q.String()),elicitationId:Q.Optional(Q.String())})),H1=X(Q.Object({type:Z(["permission","question","elicitation"]),requestId:Q.String()})),j1=X(Q.Object({code:Z(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","capacity","runtime"]),message:Q.String({minLength:1,maxLength:500}),retryable:Q.Boolean(),resource:Q.Optional(Z(["pending_count","pending_bytes","resident_runtimes"]))})),M=X(Z(["auto","off","minimal","low","medium","high","xhigh","max"])),P=X(Z(["auto","standard","fast","flex"])),I=X(Z(["auto","low","medium","high"])),G=X(Q.Union([Z(["auto","pragmatic","friendly","explanatory"]),Q.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),_=X(Q.Object({sessionId:Q.String(),projectPath:Q.String(),title:Q.Optional(Q.String()),gitBranch:Q.Optional(Q.String()),rootId:Q.String(),parentId:Q.Optional(Q.String()),relationType:Q.Optional(Z(["subagent","fork"])),resumedFrom:Q.Optional(Q.String()),rootAgentId:Q.Optional(Q.String()),resumeDepth:Q.Optional(Q.Integer({minimum:0})),taskStatus:U(J1,"completed"),taskStatusReason:Q.Optional(Q.String()),taskFailure:Q.Optional(j1),taskStartedAt:Q.Optional(Q.String()),taskCompletedAt:Q.Optional(Q.String()),taskPromptSummary:Q.Optional(Q.String()),taskPriority:Q.Optional(x),taskKind:Q.Optional(C),taskDueAt:Q.Optional(Q.String()),taskModelId:Q.Optional(Q.String()),selectedModelId:Q.Optional(Q.String()),permissionMode:Q.Optional(w),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),communicationStyleDigest:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:Q.Optional(Q.Boolean()),taskRetriedFrom:Q.Optional(Q.Object({sessionId:Q.String(),projectPath:Q.String()})),taskDelivery:Q.Optional(Z1),taskIsolation:Q.Optional(A),taskSourceProjectPath:Q.Optional(Q.String()),taskWorktreePath:Q.Optional(Q.String()),taskWorktreeBranch:Q.Optional(Q.String()),taskBaseCommit:Q.Optional(Q.String()),taskDiffStat:Q.Optional(B1),taskQueuePosition:Q.Optional(Q.Integer({minimum:1})),taskQueueDepth:Q.Optional(Q.Integer({minimum:0})),taskConcurrencyLimit:Q.Optional(Q.Integer({minimum:1})),archivedAt:Q.Optional(Q.String()),archivedBySessionId:Q.Optional(Q.String()),pendingInteraction:Q.Optional(H1),messageCount:Q.Number(),firstMessageTime:Q.String(),lastMessageTime:Q.String(),hasErrors:Q.Boolean()})),u1=X(Q.Object({sessions:Q.Array(_),nextCursor:Q.Optional(Q.String())})),h1=X(Q.Object({session:_,archivedSessionIds:Q.Array(Q.String())})),d1=X(Q.Object({session:_,restoredSessionIds:Q.Array(Q.String())})),m1=X(Q.Object({version:Q.Literal(1),sessionId:Q.String(),goalId:Q.String(),objective:Q.String(),status:Z(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:Q.Optional(Q.Number()),tokensUsed:Q.Number(),timeUsedSeconds:Q.Number(),continuationCount:Q.Number(),statusReason:Q.Optional(Q.String()),completionVerification:Q.Optional(Q.Object({attempt:Q.Integer({minimum:1}),status:Z(["pending","pass","fail","partial"]),requestedAt:Q.String(),completedAt:Q.Optional(Q.String()),verifierSessionId:Q.Optional(Q.String()),summary:Q.Optional(Q.String()),evidenceSha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))})),prematureStop:Q.Optional(Q.Object({pattern:Q.Unsafe({type:"string"}),consecutiveCount:Q.Integer({minimum:1}),detectedAt:Q.String()})),verificationStall:Q.Optional(Q.Unsafe({type:"object"})),createdAt:Q.String(),updatedAt:Q.String()})),c=X(Q.Object({role:v,content:m,metadata:Q.Optional(Q.Unknown()),reasoningContent:Q.Optional(Q.String()),thinkingContent:Q.Optional(Q.String()),tool_call_id:Q.Optional(Q.String()),name:Q.Optional(Q.String()),tool_calls:Q.Optional(Q.Unknown())})),c1=X(Q.Object({session:_,messages:Q.Array(c)})),n=X(Z(["conversation","code","both"])),U1=X(Q.Object({messageId:Q.String(),preview:Q.String(),createdAt:Q.String(),fileCount:Q.Integer({minimum:0})})),n1=X(Q.Object({targetMessageId:Q.String({minLength:1}),mode:U(n,"conversation")})),g1=X(Q.Object({checkpoint:U1,mode:n,removedTurns:Q.Integer({minimum:1}),restoredFiles:Q.Array(Q.String()),messages:Q.Array(c)})),k1=Z(["running","completed","failed","cancelled"]),u=X(Q.Object({id:Q.String(),subagentType:Q.String(),description:Q.String(),status:k1,background:Q.Boolean(),rootAgentId:Q.String(),resumedFrom:Q.Optional(Q.String()),resumeDepth:Q.Integer({minimum:0}),createdAt:Q.Number(),lastActiveAt:Q.Number(),completedAt:Q.Optional(Q.Number()),restartRecovery:Q.Optional(Q.Object({outcome:Z(["completed","interrupted","failed"]),recoveredAt:Q.Number()})),result:Q.Optional(Q.Object({success:Q.Boolean(),message:Q.String(),error:Q.Optional(Q.String()),verificationCommands:Q.Optional(Q.Array(Q.String())),verificationVerdict:Q.Optional(Z(["pass","fail","partial"])),modifiedFiles:Q.Optional(Q.Array(Q.String()))})),stats:Q.Optional(Q.Object({tokens:Q.Optional(Q.Number()),toolCalls:Q.Optional(Q.Number()),duration:Q.Optional(Q.Number())}))})),o1=X(Q.Object({prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"})})),s1=X(Q.Object({source:u,session:u})),i1=X(Q.Object({sessionId:Q.String(),projectPath:Q.String()})),a1=X(Q.Object({path:Q.String(),name:Q.String(),gitBranch:Q.Optional(Q.String()),available:Q.Boolean(),isCurrent:Q.Boolean(),boundAt:Q.String()})),t1=X(Q.Union([Q.Object({cancelled:Q.Literal(!0)}),Q.Object({cancelled:Q.Literal(!1),path:Q.String({minLength:1})})])),r1=X(Q.Object({type:Q.String(),seq:Q.Optional(Q.Number()),properties:Q.Record(Q.String(),Q.Unknown())})),g=Q.Object({type:Z(["file","image","url"]),path:Q.Optional(Q.String()),url:Q.Optional(Q.String()),content:Q.Optional(Q.String({maxLength:h})),mimeType:Q.Optional(Q.String()),name:Q.Optional(Q.String())}),o=Q.Record(Q.String(),Q.Unknown()),T1=X(Q.Object({prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:Q.Optional(Q.String({minLength:1,maxLength:200})),taskPriority:U(x,"medium"),taskKind:U(C,"feature"),taskDueAt:Q.Optional(Q.String({minLength:1,maxLength:64})),projectPath:Q.Optional(Q.String()),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default"),attachments:Q.Optional(Q.Array(g,{maxItems:N})),outputSchema:Q.Optional(o)})),y1=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),taskPriority:Q.Optional(x),taskKind:Q.Optional(C),taskDueAt:Q.Optional(Q.Union([Q.String({minLength:1,maxLength:64}),Q.Null()]))})),p1=X(Q.Object({session:_,runId:Q.String(),messageId:Q.String(),status:Z(["queued","running"]),queuePosition:Q.Optional(Q.Integer({minimum:1})),queueDepth:Q.Optional(Q.Integer({minimum:0})),maxConcurrentTasks:Q.Optional(Q.Integer({minimum:1}))})),e1=X(Q.Object({action:Z(["apply","discard"])})),q=X(Q.Object({kind:Z(["cron","interval","once"]),cron:Q.Optional(Q.String({minLength:1,maxLength:120})),intervalMs:Q.Optional(Q.Integer({minimum:60000})),runAt:Q.Optional(Q.String({minLength:1,maxLength:40})),timezone:Q.Optional(Q.String({minLength:1,maxLength:80}))})),O1=X(Q.Object({modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default")})),f=X(Q.Object({id:Q.String(),title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:Q.String({minLength:1}),trigger:q,dispatch:O1,enabled:Q.Boolean(),createdAt:Q.String(),updatedAt:Q.String(),nextRunAt:Q.Union([Q.String(),Q.Null()]),expiresAt:Q.Union([Q.String(),Q.Null()]),lastRunAt:Q.Optional(Q.String()),lastRunSessionId:Q.Optional(Q.String()),lastStatus:Q.Optional(Z(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:Q.Optional(Q.String()),runCount:Q.Integer({minimum:0})})),QQ=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:Q.String({minLength:1}),trigger:q,modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default"),enabled:U(Q.Boolean(),!0)})),$Q=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.Optional(Q.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:Q.Optional(q),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:Q.Optional(A),permissionMode:Q.Optional(w),enabled:Q.Optional(Q.Boolean())})),JQ=X(Q.Object({schedules:Q.Array(f)})),XQ=X(Q.Object({content:Q.String({maxLength:d}),projectPath:Q.Optional(Q.String()),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),permissionMode:Q.Optional(w),attachments:Q.Optional(Q.Array(g,{maxItems:N})),outputSchema:Q.Optional(o)})),V1=Z(["completed","failed","aborted","timed_out","spawn_error"]),b1=X(Q.Object({version:Q.Literal(1),command:Q.String(),status:V1,exitCode:Q.Union([Q.Integer(),Q.Null()]),durationMs:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),stdoutOmittedBytes:Q.Integer({minimum:0}),stderrOmittedBytes:Q.Integer({minimum:0}),binaryOutput:Q.Boolean(),truncated:Q.Boolean()})),ZQ=X(Q.Object({command:Q.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:Q.Optional(Q.String())})),BQ=X(Q.Object({executionId:Q.String(),messageId:Q.String(),record:b1,auxiliary:Q.Boolean(),delivery:Q.Optional(Z(["current_turn","next_turn"])),queued:Q.Optional(Q.Integer({minimum:0}))})),KQ=X(Q.Object({question:Q.String({minLength:1,maxLength:l,pattern:"^(?![\\s\\S]*\\x00)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:Q.Optional(Q.String())})),WQ=X(Q.Object({response:Q.String({minLength:1}),durationMs:Q.Number({minimum:0}),modelId:Q.Optional(Q.String()),usage:Q.Optional(Q.Object({promptTokens:Q.Number({minimum:0}),completionTokens:Q.Number({minimum:0}),totalTokens:Q.Number({minimum:0}),reasoningTokens:Q.Optional(Q.Number({minimum:0})),cacheCreationInputTokens:Q.Optional(Q.Number({minimum:0})),cacheReadInputTokens:Q.Optional(Q.Number({minimum:0})),costUsd:Q.Optional(Q.Number({minimum:0}))}))})),YQ=X(Q.Object({projectPath:Q.String(),kind:Z(["uncommitted","base","commit"]),ref:Q.Optional(Q.String({maxLength:200})),instructions:Q.Optional(Q.String({maxLength:4000})),modelId:Q.Optional(Q.String({minLength:1,maxLength:200}))})),HQ=X(Q.Object({reviewId:Q.String(),status:Q.Literal("running")})),jQ=X(Q.Object({messageId:Q.String(),role:v,content:Q.String(),timestamp:Q.String()})),UQ=X(Q.Object({approved:Q.Boolean(),remember:Q.Optional(Q.Boolean()),scope:Q.Optional(Z(["once","session","project"])),targetMode:Q.Optional(w),feedback:Q.Optional(Q.String()),answers:Q.Optional(Q.Record(Q.String(),Q.Union([Q.String(),Q.Array(Q.String())]))),elicitation:Q.Optional(Q.Object({action:Z(["accept","decline","cancel"]),content:Q.Optional(Q.Record(Q.String(),Q.Union([Q.String({maxLength:4000}),Q.Number(),Q.Boolean(),Q.Array(Q.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),G1=X(Q.Object({id:G,name:Q.String({minLength:1,maxLength:80}),description:Q.String({minLength:1,maxLength:256}),source:Z(["built-in","user","project","plugin"]),contentSha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))})),kQ=X(Q.Object({id:Q.String(),displayName:Q.Optional(Q.String()),provider:Q.String(),model:Q.String(),contextWindow:Q.Optional(Q.Number()),maxTokens:Q.Optional(Q.Number()),reasoning:Q.Optional(Q.Boolean()),supportedReasoningEfforts:Q.Optional(Q.Array(Z(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:Q.Optional(Q.Array(Z(["standard","fast","flex"]))),supportedResponseVerbosities:Q.Optional(Q.Array(Z(["low","medium","high"]))),communicationStyles:Q.Optional(Q.Array(G1,{maxItems:36})),input:Q.Optional(Q.Array(Z(["text","image"]))),overrides:Q.Optional(Q.Object({baseUrl:Q.Optional(Q.String()),temperature:Q.Optional(Q.Number()),maxOutputTokens:Q.Optional(Q.Number()),timeout:Q.Optional(Q.Number()),streamIdleTimeout:Q.Optional(Q.Number({minimum:1000}))}))})),OQ=X(Z(["vs-dark","vs-light","hc-black"])),w1=X(Z(["light","dark","system"])),M1=X(Q.Object({language:Q.String(),codeTheme:Q.String(),uiTheme:w1,autoSaveSessions:Q.Boolean(),notifyBuild:Q.Boolean(),notifyErrors:Q.Boolean(),notifySounds:Q.Boolean(),privacyTelemetry:Q.Boolean(),privacyCrash:Q.Boolean(),agentTeamsEnabled:Q.Boolean(),communicationStyle:Q.Optional(G)})),VQ=X(Q.Partial(M1));var s=a("Service"),A1=1;function _1(){return t.join(i(),"schedules.json")}class L{filePath;static instance;static getInstance(){if(!L.instance)L.instance=new L;return L.instance}writeChain=Promise.resolve();constructor($=_1()){this.filePath=$}async readFile(){try{let $=await I1(this.filePath,"utf-8"),J=JSON.parse($);if(!J||!Array.isArray(J.schedules))return[];let K=[],B=0;for(let W of J.schedules){let Y=f.safeParse(W);if(Y.success)K.push(Y.data);else B+=1}if(B>0)s.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return K}catch($){let J=$;if(J.code!=="ENOENT")s.warn("[ScheduleStore] Failed to read schedules; treating as empty:",J);return[]}}async writeFile($){await P1(t.dirname(this.filePath),{recursive:!0,mode:493});let J={version:A1,schedules:$};await D1(this.filePath,JSON.stringify(J,null,2),{mode:384})}serializeWrite($){let J=this.writeChain.then($,$);return this.writeChain=J.then(()=>{return},()=>{return}),J}async list(){return this.readFile()}async get($){return(await this.readFile()).find((K)=>K.id===$)}async create($){return this.serializeWrite(async()=>{let J=$.trigger.kind==="cron"&&!$.trigger.timezone?{...$.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:$.trigger,K=z(J);if(K)throw Error(K);let B=new Date;if(J.kind==="once"&&new Date(J.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let W=B.toISOString(),Y=F(J,B),O={id:L1(10),title:$.title,prompt:$.prompt,projectPath:$.projectPath,trigger:J,dispatch:{modelId:$.modelId,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,isolation:$.isolation??"worktree",permissionMode:$.permissionMode??"default"},enabled:$.enabled??!0,createdAt:W,updatedAt:W,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(O),await this.writeFile(V),O})}async update($,J){return this.serializeWrite(async()=>{let K=await this.readFile(),B=K.findIndex((H)=>H.id===$);if(B===-1)return;let W=K[B];if(J.trigger){let H=J.trigger.kind==="cron"&&!J.trigger.timezone?{...J.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:J.trigger,k=z(H);if(k)throw Error(k);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");J={...J,trigger:H}}let Y={...W,...J,dispatch:J.dispatch?{...W.dispatch,...J.dispatch}:W.dispatch,updatedAt:new Date().toISOString()},O=!W.enabled,V=Y.enabled,j=J.trigger!==void 0;if((j||O&&V)&&J.nextRunAt===void 0){let H=new Date,k=F(Y.trigger,H);if(Y.nextRunAt=k?k.toISOString():null,j)Y.expiresAt=null}return K[B]=Y,await this.writeFile(K),Y})}async remove($){return this.serializeWrite(async()=>{let J=await this.readFile(),K=J.filter((B)=>B.id!==$);if(K.length===J.length)return!1;return await this.writeFile(K),!0})}async setEnabled($,J){return this.update($,{enabled:J})}}var NQ=L.getInstance();
|
|
2
|
+
export{l as Ha,v1 as Ia,F1 as Ja,F as Ka,z as La,z1 as Ma,S1 as Na,_ as Oa,n1 as Pa,o1 as Qa,T1 as Ra,y1 as Sa,p1 as Ta,e1 as Ua,f as Va,QQ as Wa,$Q as Xa,JQ as Ya,XQ as Za,ZQ as _a,KQ as $a,YQ as ab,L as bb,NQ as cb};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{oe as s}from"./chunk-wbfa6xce.js";import{He as o}from"./chunk-0ayxntzc.js";import{Rg as y,Sg as D,Ug as N,Wg as j,Xg as F,Zg as R,bh as E,ch as _,dh as f,eh as C,gh as S,hh as m,lh as c,qh as l,rh as n}from"./chunk-z24ha5jk.js";import{sh as Y}from"./chunk-t48zm299.js";import{uh as x,wh as k,zh as Z}from"./chunk-7dqh8bqm.js";import{Gh as X}from"./chunk-qa4efys0.js";import{$h as O,Kh as h,Lh as A,Rh as P,Sh as T,Uh as $,Vh as U,Wh as G,Yh as L,Zh as M,ai as I}from"./chunk-hrfh7wck.js";import{ii as d}from"./chunk-h4j0nve8.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
|
|
2
2
|
[FAIL] 配置初始化失败
|
|
3
3
|
`),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
|
|
4
4
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
|
5
5
|
`),process.exit(1)}};function r(q){if(q.continue&&q.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(q.forkSession&&!q.continue&&!q.resume)throw Error("--fork-session requires --resume or --continue");if(q.sessionId&&(q.continue||q.resume)&&!q.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var Ak=(q)=>{if(q.jsonSchema&&q.outputSchema)throw Error("--json-schema cannot be combined with --output-schema");if((q.jsonSchema||q.outputSchema)&&!q.print&&!q.headless)throw Error("--json-schema and --output-schema can only be used with --print or --headless");if(q.outputFormat&&q.outputFormat!=="text"&&!q.print&&!q.headless)throw Error("--output-format can only be used with --print or --headless");if(q.headless&&q.outputFormat&&!["text","jsonl"].includes(q.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${q.outputFormat}". Use --print for json|stream-json support.`);if(q.print&&q.outputFormat&&!["text","json","stream-json"].includes(q.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${q.outputFormat}". Use --headless for jsonl support.`);if(q.inputFormat==="stream-json"&&q.print)Q.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
|
|
6
|
-
export{Dk as
|
|
6
|
+
export{Dk as le,hk as me,Ak as ne};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ni as $,Oi as F}from"./chunk-na1cney5.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
|
|
2
2
|
`,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
|
|
3
3
|
export{_ as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ja as V,La as W,Ma as O,cb as J}from"./chunk-8eh0vp98.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Ih as Q}from"./chunk-qa4efys0.js";import"./chunk-h4j0nve8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{H as
|
|
1
|
+
import{qh as F}from"./chunk-z24ha5jk.js";import{ni as D,oi as E}from"./chunk-w63dfcx5.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
|
|
2
|
+
export{H as nf,Q as of,T as pf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{$g as H,ah as I}from"./chunk-z24ha5jk.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as s,K as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Bi as a,Ci as b,Di as c}from"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{promises as B}from"node:fs";import q from"node:path";import{LRUCache as H}from"lru-cache";var K=512,Z=new H({max:K});async function L(x){let b=x;while(!0){try{return await B.lstat(q.join(b,".git")),b}catch(V){if(V.code!=="ENOENT")return}let F=q.dirname(b);if(F===b)return;b=F}}async function M(x){let b=q.join(x,".git"),F=await B.lstat(b);if(F.isDirectory())return x;if(!F.isFile())return;let V=await B.readFile(b,"utf8"),J=/^gitdir:\s*(.+)\s*$/im.exec(V);if(!J)return;let Q=await B.realpath(q.isAbsolute(J[1])?J[1]:q.resolve(x,J[1])),Y=Q;try{let z=(await B.readFile(q.join(Q,"commondir"),"utf8")).trim();if(z)Y=await B.realpath(q.resolve(Q,z))}catch(z){if(z.code!=="ENOENT")throw z}return q.basename(Y)===".git"?B.realpath(q.dirname(Y)):void 0}async function N(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x),F=Z.get(b);if(F)return F;let V=b;try{let Q=await L(b);if(Q){let Y=await M(Q),z=q.relative(Q,b);if(Y&&(z===""||!z.startsWith(`..${q.sep}`)&&z!==".."&&!q.isAbsolute(z))){let $=q.resolve(Y,z);V=await B.realpath($).catch(()=>$)}}}catch{}let J={projectPath:b,trustRoot:V};return Z.set(b,J),J}async function S(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x);Z.delete(b)}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as Ei,S as Fi};
|