blade-code 0.10.19 → 0.10.21
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-1wz10w2m.js → chunk-033vmd74.js} +1 -1
- package/dist/{chunk-y72p0x68.js → chunk-0et4h9p3.js} +1 -1
- package/dist/chunk-0qayfsc9.js +2 -0
- package/dist/{chunk-5ra89kse.js → chunk-17jpjcvb.js} +2 -2
- package/dist/{chunk-zek2ec3c.js → chunk-1p5822w7.js} +1 -1
- package/dist/{chunk-qkrssft1.js → chunk-1y52h772.js} +1 -1
- package/dist/{chunk-zgt1jpgg.js → chunk-2wp6h1p8.js} +1 -1
- package/dist/{chunk-d9k98jy2.js → chunk-2ygqbd1z.js} +1 -1
- package/dist/chunk-303cba4k.js +1 -0
- package/dist/{chunk-3gra6n0k.js → chunk-4tkn9bky.js} +1 -1
- package/dist/{chunk-qwxqfb9z.js → chunk-4v8nxcxp.js} +1 -1
- package/dist/{chunk-y5fk4fx5.js → chunk-4ypy5bk8.js} +1 -1
- package/dist/chunk-51vnya3v.js +1 -0
- package/dist/{chunk-6pa6c2n0.js → chunk-5hhfv1w1.js} +1 -1
- package/dist/{chunk-k3nkcaap.js → chunk-65kbckpt.js} +1 -1
- package/dist/{chunk-c6rff43d.js → chunk-6f3rp67k.js} +1 -1
- package/dist/chunk-6v4dwkw7.js +1 -0
- package/dist/chunk-72ztan96.js +200 -0
- package/dist/{chunk-07mstszb.js → chunk-73jh6fz9.js} +2 -2
- package/dist/{chunk-6207mbmr.js → chunk-77z6x1zb.js} +2 -2
- package/dist/{chunk-zt5wq0qj.js → chunk-7mpa4esh.js} +1 -1
- package/dist/chunk-7p4qvftj.js +1 -0
- package/dist/chunk-9snsxf18.js +1 -0
- package/dist/{chunk-yqfqj7mh.js → chunk-9wqr1sbq.js} +1 -1
- package/dist/{chunk-t8g4288j.js → chunk-a1ztrwjb.js} +1 -1
- package/dist/{chunk-kbpc97n3.js → chunk-afhdpen9.js} +1 -1
- package/dist/{chunk-y2g5a5bp.js → chunk-ah8hky46.js} +1 -1
- package/dist/{chunk-36626eyr.js → chunk-bdn1tkyz.js} +1 -1
- package/dist/{chunk-ddqwtw3z.js → chunk-bjf7ecgy.js} +1 -1
- package/dist/chunk-c23c1vn6.js +1 -0
- package/dist/chunk-cb0rb9ss.js +1 -0
- package/dist/{chunk-aem57a6n.js → chunk-cysaxtfp.js} +1 -1
- package/dist/{chunk-prgh321y.js → chunk-dbb20rxh.js} +1 -1
- package/dist/{chunk-t3b689pm.js → chunk-e9xv0yyr.js} +1 -1
- package/dist/{chunk-6r0nj7ay.js → chunk-edphxwj1.js} +1 -1
- package/dist/chunk-efkqwhff.js +1 -0
- package/dist/{chunk-6g5k5de1.js → chunk-fasxw5bb.js} +1 -1
- package/dist/{chunk-yp02wzek.js → chunk-g7p165yz.js} +1 -1
- package/dist/{chunk-1n60pgsq.js → chunk-jahf977w.js} +2 -2
- package/dist/{chunk-fvj1mzgs.js → chunk-jdsr22s2.js} +1 -1
- package/dist/{chunk-zdkc4kj1.js → chunk-jhzk287k.js} +1 -1
- package/dist/chunk-jyeas4p9.js +2 -0
- package/dist/{chunk-wt7gy9bm.js → chunk-k106g2p6.js} +1 -1
- package/dist/{chunk-yxmy7g38.js → chunk-kfqj54ax.js} +1 -1
- package/dist/{chunk-yvf4nmds.js → chunk-kmeccj99.js} +2 -2
- package/dist/{chunk-qt114yth.js → chunk-ktbe458z.js} +1 -1
- package/dist/{chunk-et9k9pac.js → chunk-mvc0tad6.js} +2 -2
- package/dist/{chunk-amzz0mk6.js → chunk-ns5015tn.js} +1 -1
- package/dist/{chunk-5a8tqdrk.js → chunk-pmw9pn3v.js} +1 -1
- package/dist/{chunk-29axr7g4.js → chunk-q4fjec99.js} +1 -1
- package/dist/{chunk-96h588rd.js → chunk-r561wfcz.js} +1 -1
- package/dist/chunk-r73fanrm.js +1 -0
- package/dist/{chunk-hmvyreyx.js → chunk-ryhk5qmv.js} +339 -318
- package/dist/{chunk-xet98pc1.js → chunk-sj2w24fe.js} +1 -1
- package/dist/chunk-smh39yy2.js +1 -0
- package/dist/{chunk-8rzwyknk.js → chunk-vprpk6q1.js} +1 -1
- package/dist/{chunk-ks6by04t.js → chunk-vzgy95tp.js} +1 -1
- package/dist/{chunk-jpwfq49n.js → chunk-w5m418w5.js} +2 -2
- package/dist/chunk-w9tnd1q2.js +1 -0
- package/dist/{chunk-fa6313dv.js → chunk-wc1ee4tc.js} +1 -1
- package/dist/{chunk-8mafna0v.js → chunk-whftbz4b.js} +1 -1
- package/dist/{chunk-cyda7gnb.js → chunk-wxqkpvqw.js} +2 -2
- package/dist/{chunk-entmz5b1.js → chunk-y68sxcgk.js} +1 -1
- package/dist/chunk-zz9rax72.js +1 -0
- package/package.json +1 -1
- package/dist/chunk-1ydqqzp1.js +0 -1
- package/dist/chunk-2gj76ba1.js +0 -1
- package/dist/chunk-30e3v8cw.js +0 -1
- package/dist/chunk-3qhqbj09.js +0 -2
- package/dist/chunk-4svjvyyd.js +0 -1
- package/dist/chunk-87vsgqvy.js +0 -1
- package/dist/chunk-88639hse.js +0 -1
- package/dist/chunk-8zywzb9j.js +0 -1
- package/dist/chunk-bcxbrbvd.js +0 -1
- package/dist/chunk-ctkxf0y7.js +0 -200
- package/dist/chunk-kgypdjdw.js +0 -1
- package/dist/chunk-mg421b17.js +0 -1
- package/dist/chunk-q3c07kb4.js +0 -2
- package/dist/chunk-tcnnh890.js +0 -1
- package/dist/chunk-ycwrykxe.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-
|
|
2
|
-
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-
|
|
1
|
+
import"./chunk-5hhfv1w1.js";import"./chunk-77z6x1zb.js";import{Xe as Q}from"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as L}from"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import{Rf as F}from"./chunk-fasxw5bb.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
|
|
2
|
+
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-0et4h9p3.js"),{SessionService:B}=await import("./chunk-smh39yy2.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
|
|
3
3
|
`);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
|
|
4
4
|
Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Pf as j}from"./chunk-kmeccj99.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
|
|
2
2
|
`)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
|
|
3
|
-
export{m as
|
|
3
|
+
export{m as ge,I as he,M as ie,V as je,h as ke};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ea as J,la as V,na as W,oa as O}from"./chunk-
|
|
1
|
+
import{Ea as J,la as V,na as W,oa as O}from"./chunk-ktbe458z.js";import"./chunk-77z6x1zb.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as Q}from"./chunk-dbb20rxh.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{wc as a,xc as b,yc as c}from"./chunk-2wp6h1p8.js";import"./chunk-k106g2p6.js";import"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-2c3zavy2.js";import"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ff as a}from"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";export{a as WorkspaceTrustService};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as tf,p as uf,u as vf,S as wf,c as xf,l as yf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{G as P}from"./chunk-
|
|
1
|
+
import{G as P}from"./chunk-ryhk5qmv.js";import{gb as K}from"./chunk-72ztan96.js";import{Eb as G,Fb as N,Gb as S,Hb as O,Ib as s,bc as B}from"./chunk-1p5822w7.js";import{gc as j}from"./chunk-vprpk6q1.js";import{hd as q}from"./chunk-yz2bsntj.js";import{zd as v}from"./chunk-g7p165yz.js";import{Lf as z}from"./chunk-kmeccj99.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
|
|
2
2
|
`)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
|
|
3
3
|
`).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
|
|
4
4
|
`)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{td as B}from"./chunk-5chec8rs.js";import{
|
|
1
|
+
import{td as B}from"./chunk-5chec8rs.js";import{sf as Y}from"./chunk-w5m418w5.js";import{vf as Z,yf as $}from"./chunk-9wqr1sbq.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
|
|
2
2
|
export{K as pd,O as qd,E as rd};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var r;((t)=>{t.DEFAULT="default";t.AUTO_EDIT="autoEdit";t.YOLO="yolo";t.PLAN="plan"})(r||={});var N=100;function _(n){return Number.isInteger(n)&&n>=-1&&n<=100}function u(){return"-1, 0, or an integer from 1 to 100"}
|
|
2
|
-
export{r as
|
|
2
|
+
export{r as Ze,N as _e,_ as $e,u as af};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as R,n as I,o as C,p as v,q as S}from"./chunk-
|
|
1
|
+
import{m as R,n as I,o as C,p as v,q as S}from"./chunk-ns5015tn.js";import{F as y,L as w}from"./chunk-ryhk5qmv.js";import"./chunk-4tkn9bky.js";import"./chunk-ktbe458z.js";import{Va as x,hb as U}from"./chunk-72ztan96.js";import"./chunk-095x2ykj.js";import{Qb as k,bc as b}from"./chunk-1p5822w7.js";import"./chunk-vprpk6q1.js";import{uc as P}from"./chunk-q4fjec99.js";import{wc as h,xc as O,yc as M}from"./chunk-2wp6h1p8.js";import{zc as z}from"./chunk-k106g2p6.js";import"./chunk-65kbckpt.js";import{Wc as N}from"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-sj2w24fe.js";import"./chunk-afhdpen9.js";import"./chunk-5chec8rs.js";import"./chunk-4ypy5bk8.js";import"./chunk-g7p165yz.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import{Ze as D}from"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as E}from"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import g from"yargs";import{hideBin as c}from"yargs/helpers";var m=new Set(Object.values(D));function d(j){if(j&&m.has(j))return j;return}function l(j){return j.command("* [message]","Print response and exit (useful for pipes)",(q)=>q.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(q)=>{if(!q.p)return;let B=await u(q);process.exit(B)})}async function u(j,q=process){let B;try{await R();let T=await I({message:j.message,_:j._,defaultMessage:"Hello"}),J=await C(T);if(J.mode==="output"){if(J.content)q.stdout.write(`${J.content}
|
|
2
2
|
`);return J.exitCode??0}let K=J.content,X=await v(j),Y=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(Y!==void 0&&X)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:G,messages:F,metadata:V}=await S({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),W=V?.projectPath??E(),Z=d(j.permissionMode)??V?.permissionMode??N()?.permissionMode??"default";await b.setSessionPermissionMode(G,W,Z);let _=await U.cancelPendingNonInteractive(W,G)?await b.loadSessionModelContext(G,W):F;if(B=await y.create({sessionId:G,workspaceRoot:W,modelId:j.model,permissionMode:Z,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?z(j.agents):void 0,..._.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}}),Y!==void 0){let H=await B.executeUserShellCommand(Y);if(j.outputFormat==="json")q.stdout.write(`${JSON.stringify(H,null,2)}
|
|
3
3
|
`);else if(j.outputFormat==="stream-json")q.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:H.executionId,record:H.record})}
|
|
4
4
|
`);else q.stdout.write(`${k(H.record)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ka as H}from"./chunk-
|
|
1
|
+
import{ka as H}from"./chunk-4tkn9bky.js";import"./chunk-095x2ykj.js";import{$c as $,fd as T}from"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as k}from"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ud as a,vd as b,wd as c}from"./chunk-4ypy5bk8.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{uc as a,vc as b}from"./chunk-q4fjec99.js";import"./chunk-wxqkpvqw.js";import"./chunk-fasxw5bb.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as Q,g as R,h as T,i as W}from"./chunk-
|
|
1
|
+
import{f as Q,g as R,h as T,i as W}from"./chunk-pmw9pn3v.js";import"./chunk-jhzk287k.js";import"./chunk-wc1ee4tc.js";import"./chunk-a1ztrwjb.js";import"./chunk-4v8nxcxp.js";import"./chunk-ryhk5qmv.js";import"./chunk-4tkn9bky.js";import"./chunk-ktbe458z.js";import"./chunk-72ztan96.js";import"./chunk-095x2ykj.js";import"./chunk-1p5822w7.js";import"./chunk-vprpk6q1.js";import"./chunk-65kbckpt.js";import{Xc as M}from"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-sj2w24fe.js";import"./chunk-afhdpen9.js";import"./chunk-5chec8rs.js";import"./chunk-4ypy5bk8.js";import"./chunk-g7p165yz.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import{Af as J}from"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import b from"chalk";import H from"open";var $=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as kf,D as lf,P as mf,V as nf};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{l as i}from"./chunk-
|
|
1
|
+
import{l as i}from"./chunk-wc1ee4tc.js";import{nf as s}from"./chunk-dbb20rxh.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
|
|
2
2
|
${e.path}`}).join(`
|
|
3
3
|
`)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Sc as W}from"./chunk-
|
|
1
|
+
import{Sc as W}from"./chunk-whftbz4b.js";import{de as X}from"./chunk-17jpjcvb.js";import{he as Q,je as U}from"./chunk-77z6x1zb.js";import{nf as V}from"./chunk-dbb20rxh.js";function _(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=U("Service");function $(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class F{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!F.instance)F.instance=new F;return F.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await Q()}catch(z){}try{let z=X.getInstance(),J=W(),N=J.session?.sessionId||"unknown",O=J.session?.workspaceRoot||V();if(z.isEnabled(O,N)){let Z=J.config?.config?.permissionMode||"default";await z.executeSessionEndHooks($(b),{projectDir:O,sessionId:N,permissionMode:Z})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,Y=new Promise((z,J)=>{setTimeout(()=>{J(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,Y])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{_(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var K=()=>{return F.getInstance()},P=(b)=>{return K().registerCleanup(b)},L=()=>{K().initialize()},k=(b=0)=>{K().shutdown("normal",b)};
|
|
4
4
|
export{K as Ac,P as Bc,L as Cc,k as Dc};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{od as a}from"./chunk-sj2w24fe.js";import"./chunk-77z6x1zb.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";export{a as createChatServiceAsync};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as a}from"node:module";var c=a(import.meta.url);
|
|
2
|
-
export{c as
|
|
2
|
+
export{c as Rf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Sd as L1,Td as Z0,Ud as G1}from"./chunk-r1jxbx1h.js";import{Yd as $O,Zd as HO}from"./chunk-6sb7cg95.js";import{ae as Y1}from"./chunk-2c3zavy2.js";import{be as B0,de as M0}from"./chunk-
|
|
1
|
+
import{Sd as L1,Td as Z0,Ud as G1}from"./chunk-r1jxbx1h.js";import{Yd as $O,Zd as HO}from"./chunk-6sb7cg95.js";import{ae as Y1}from"./chunk-2c3zavy2.js";import{be as B0,de as M0}from"./chunk-17jpjcvb.js";import{je as h,ke as z}from"./chunk-77z6x1zb.js";import{Ne as V0,Oe as o1,Xe as j0}from"./chunk-mvc0tad6.js";import{bf as u,df as W,gf as R1}from"./chunk-r561wfcz.js";import{nf as b}from"./chunk-dbb20rxh.js";import{Af as d0}from"./chunk-wxqkpvqw.js";import{Ff as T}from"./chunk-jahf977w.js";import J1 from"node:path";import L$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import jO from"yaml";var g$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function u$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
|
|
2
2
|
|
|
3
3
|
You are a fresh, independent, adversarial verifier. The parent Agent has claimed
|
|
4
4
|
that a persisted goal is complete. Your job is to refute that claim unless the
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Gf as y}from"./chunk-1y52h772.js";import{Pf as b}from"./chunk-kmeccj99.js";import{createHash as N}from"node:crypto";import{constants as v,promises as d}from"node:fs";import W from"node:os";import a from"node:path";import{Mutex as A}from"async-mutex";import O from"write-file-atomic";var w=1,x=65536,T=1048576,m=100;function p(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function k(e,t=2048){return e.length<=t?e:`${e.slice(0,t-1)}…`}function S(e){if(typeof e!=="string"||!e.trim())return;try{let t=new URL(e);return k(`${t.origin}${t.pathname}`)}catch{return k(e)}}function D(e){return Array.isArray(e)?e.filter((t)=>typeof t==="string"):[]}function R(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.type==="string"?r.type:"unknown",n=typeof r.command==="string"?r.command:void 0,o=D(r.args),c=i==="stdio"?k([n,...o].filter(Boolean).join(" ")):S(r.url);return{kind:"mcp",name:`${t} (${i})`,...c?{target:c}:{}}})}function F(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.command==="string"?k(r.command):void 0,n=p(r.extensionToLanguage)?Object.keys(r.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${t} (${n})`,...i?{target:i}:{}}})}function j(e){if(!Array.isArray(e))return[];return e.slice(0,m).flatMap((t)=>{if(!p(t))return[];let s=typeof t.id==="string"?t.id:"unnamed",r=typeof t.provider==="string"?t.provider:"unknown",i=typeof t.model==="string"?t.model:"unknown",n=p(t.overrides)?t.overrides:{},o=S(n.baseUrl);return[{kind:"model",name:`${s}: ${r}/${i}`,...o?{target:o}:{}}]})}function $(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.wireApi==="string"?r.wireApi:"unknown",n=S(r.baseUrl);return{kind:"model",name:`${t} (${i})`,...n?{target:n}:{}}})}function P(e){if(!p(e))return[];let t=[];for(let s of["allow","ask","deny"])for(let r of D(e[s]).slice(0,m))t.push({kind:"permission",name:`${s}: ${k(r,512)}`});return t}function C(e){let t=[...R(e.mcpServers),...F(e.lspServers),...j(e.models),...$(e.modelProviders),...P(e.permissions)];if(p(e.env))for(let s of Object.keys(e.env).slice(0,m))t.push({kind:"environment",name:s});if(typeof e.permissionMode==="string")t.push({kind:"permission",name:`permissionMode: ${e.permissionMode}`});return t}function I(e){return e!=="hooks"&&e!=="disableAllHooks"}function M(e){return N("sha256").update(e).digest("hex")}function L(e,t){let s=a.relative(e,t);return s===""||!s.startsWith(`..${a.sep}`)&&s!==".."&&!a.isAbsolute(s)}class h{storeDir;static instance=null;mutex=new A;statusCache=new Map;constructor(e=a.join(b(),"workspace-trust")){this.storeDir=e}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}static resetInstance(){h.instance=null}async getStatus(e){let t=await y(e),s;try{s=await this.discoverSensitiveSources(t.projectPath)}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:0,sources:[],decision:"undecided",error:u instanceof Error?u.message:"Workspace trust review failed"};return this.cacheStatus(e,g),g}if(s.length===0){let u={...t,state:"not_required",trusted:!0,sensitiveSources:0,sources:s,decision:"undecided"};return this.cacheStatus(e,u),u}let r;try{r=await this.readDecisions()}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:s.length,sources:s,decision:"undecided",error:u instanceof Error?u.message:"Workspace trust store is unavailable"};return this.cacheStatus(e,g),g}let i=r.filter((u)=>L(u.path,t.trustRoot)),n=Math.max(-1,...i.map((u)=>u.path.split(a.sep).length)),o=i.filter((u)=>u.path.split(a.sep).length===n),c=o.length>0&&o.every((u)=>u.trusted),f=o[0],l=f?.path===t.trustRoot,E={...t,state:c?"trusted":"untrusted",trusted:c,sensitiveSources:s.length,sources:s,decision:f?l?f.trusted?"trusted":"untrusted":"inherited":"undecided",...f?.decidedAt?{decidedAt:f.decidedAt}:{},...!l&&f?.path?{inheritedFrom:f.path}:{}};return this.cacheStatus(e,E),E}cacheStatus(e,t){this.statusCache.set(a.resolve(e),t),this.statusCache.set(t.projectPath,t)}getCachedStatus(e){return this.statusCache.get(a.resolve(e))}isTrustedCached(e){return this.getCachedStatus(e)?.state==="trusted"}async trust(e){return this.recordDecision(e,!0)}async revoke(e){return this.recordDecision(e,!1)}async recordDecision(e,t){return this.mutex.runExclusive(async()=>{let s=await y(e);await this.assertSafeTrustRoot(s);let r={version:w,path:s.trustRoot,trusted:t,decidedAt:new Date().toISOString()};return await this.writeDecision(r),this.statusCache.clear(),this.getStatus(e)})}async assertSafeTrustRoot(e){let t=a.parse(e.trustRoot).root,s=await d.realpath(W.homedir()).catch(()=>a.resolve(W.homedir()));if(!a.isAbsolute(e.trustRoot)||e.trustRoot===t||e.trustRoot===s)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(e){let t=[],s=await this.reviewPackageScripts(e);if(s)t.push(s);for(let[r,i]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let n=await this.reviewConfigFile(e,r,i);if(n)t.push(n)}for(let r of[".blade/plugins",".claude/plugins"]){let i=await this.reviewResourceDirectory(e,r,"plugins","plugin");if(i)t.push(i)}for(let r of[".blade/commands",".claude/commands"]){let i=await this.reviewResourceDirectory(e,r,"commands","command");if(i)t.push(i)}for(let[r,i,n]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let o=await this.reviewResourceDirectory(e,r,i,n);if(o)t.push(o)}for(let r of["CLAUDE.md","AGENTS.md","BLADE.md"]){let i=await this.reviewInstructionFile(e,r);if(i)t.push(i)}return t}async reviewPackageScripts(e){let t=a.join(e,"package.json"),s;try{s=await d.stat(t)}catch(o){if(o.code==="ENOENT")return;throw o}if(!s.isFile())return;if(s.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let r;try{r=JSON.parse(await d.readFile(t,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!p(r)||!p(r.scripts))return;let i=r.scripts,n=Object.keys(i).filter((o)=>typeof i[o]==="string").sort().slice(0,m);if(n.length===0)return;return{path:"package.json",kind:"package",keys:n,effects:n.map((o)=>({kind:"command",name:`package script: ${o}`}))}}async reviewInstructionFile(e,t){try{if(!(await d.stat(a.join(e,t))).isFile())return}catch(s){if(s.code==="ENOENT")return;throw s}return{path:t,kind:"instructions",keys:[t],effects:[{kind:"instruction",name:t}]}}async reviewConfigFile(e,t,s){let r=a.join(e,t),i;try{i=await d.stat(r)}catch(l){if(l.code==="ENOENT")return;throw l}if(!i.isFile())return;if(i.size>T)throw Error(`${t} exceeds the 1 MiB workspace review limit`);let n;try{n=JSON.parse(await d.readFile(r,"utf8"))}catch{return{path:t,kind:s,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!p(n))return{path:t,kind:s,keys:[],effects:[],warning:"Configuration root is not an object"};let o=Object.keys(n).filter(I).sort();if(o.length===0)return;let c=C(n),f=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let l of o)if(!f.has(l))c.push({kind:"configuration",name:l});return{path:t,kind:s,keys:o,effects:c}}async reviewResourceDirectory(e,t,s,r){let i=a.join(e,t),n;try{n=await d.readdir(i,{withFileTypes:!0})}catch(c){if(c.code==="ENOENT")return;throw c}let o=n.filter((c)=>s==="plugins"||s==="skills"?c.isDirectory()||c.isSymbolicLink():c.isFile()||c.isDirectory()||c.isSymbolicLink()).slice(0,m);if(o.length===0)return;return{path:t,kind:s,keys:o.map((c)=>c.name),effects:o.map((c)=>({kind:r,name:c.name}))}}async readDecisions(){let e;try{e=await d.lstat(this.storeDir)}catch(r){if(r.code==="ENOENT")return[];throw r}if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let t=await d.readdir(this.storeDir,{withFileTypes:!0}),s=[];for(let r of t){if(!r.name.endsWith(".json"))continue;if(!r.isFile())throw Error("Workspace trust store entries must be regular files");s.push(await this.readDecision(a.join(this.storeDir,r.name)))}return s}async readDecision(e){let t;try{t=await d.open(e,v.O_RDONLY|v.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let s=await t.stat();if(!s.isFile()||s.size>x)throw Error("Workspace trust decision is invalid");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let r=JSON.parse(await t.readFile("utf8"));if(!p(r)||r.version!==w||typeof r.path!=="string"||!a.isAbsolute(r.path)||typeof r.trusted!=="boolean"||typeof r.decidedAt!=="string"||!Number.isFinite(Date.parse(r.decidedAt))||Object.keys(r).some((i)=>i!=="version"&&i!=="path"&&i!=="trusted"&&i!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:w,path:r.path,trusted:r.trusted,decidedAt:r.decidedAt}}finally{await t.close()}}async writeDecision(e){await this.ensureStoreDirectoryForWrite();let t=a.join(this.storeDir,`${M(e.path)}.json`);try{let s=await d.lstat(t);if(!s.isFile()||s.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(s){if(s.code!=="ENOENT")throw s}await O(t,`${JSON.stringify(e,null,2)}
|
|
2
2
|
`,{mode:384}),await d.chmod(t,384)}async ensureStoreDirectoryForWrite(){try{let e=await d.lstat(this.storeDir);if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(e){if(e.code!=="ENOENT")throw e;await d.mkdir(this.storeDir,{recursive:!0,mode:448}),await d.chmod(this.storeDir,448)}}}
|
|
3
|
-
export{h as
|
|
3
|
+
export{h as Ff};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
1
|
+
import{a as o}from"./chunk-2ygqbd1z.js";import"./chunk-fasxw5bb.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{sf as o}from"./chunk-w5m418w5.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
|
|
2
2
|
export{e as j,i as k};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{spawn as b}from"node:child_process";var I=500;function X(j){return new Promise((q)=>setTimeout(q,j))}function Y(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function x(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=b("taskkill",z,{stdio:"ignore",windowsHide:!0}),J=!1,K=(H)=>{if(J)return;J=!0,y(H)};B.once("error",()=>K(!1)),B.once("close",(H)=>K(H===0))})}async function N(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??I,B=q.killProcess??process.kill.bind(process),J=q.taskkill??x,K=q.wait??X,H=q.validatePidOwnership??(()=>!0);if(!H())return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let Q=await J(j,!1);if(await K(z),!H())return{success:Q,alreadyExited:!1,forced:!1};let V=await J(j,!0);return{success:Q||V,alreadyExited:!Q&&!V,forced:V}}let W=(Q,V)=>{try{return B(Q,V)}catch(G){return Y(G)==="ESRCH"}},Z=W(-j,"SIGTERM")||W(j,"SIGTERM");if(await K(z),!H())return{success:Z,alreadyExited:!1,forced:!1};let $=W(-j,"SIGKILL")||W(j,"SIGKILL");return{success:Z||$,alreadyExited:!1,forced:$}}class D{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??I,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??x,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(Y(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Y(q)==="ESRCH"}}}function U(j,q,y={},z={}){let B=b(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new D(B,z)}}
|
|
2
|
+
export{N as ee,U as fe};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ae as W}from"./chunk-2c3zavy2.js";import{
|
|
1
|
+
import{ae as W}from"./chunk-2c3zavy2.js";import{_e as V}from"./chunk-ah8hky46.js";import{bf as F,df as k,gf as H}from"./chunk-r561wfcz.js";var $=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),Q=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),b=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(Q),disallowedTools:k.Optional(Q),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(H(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1,maximum:V})),isolation:k.Optional(H(["none","worktree"]))},{additionalProperties:!1});function O(Y){let w;try{w=JSON.parse(Y)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let I=Object.entries(w);if(I.length>64)throw Error("--agents supports at most 64 definitions");return I.map(([z,Z])=>{if(!F($,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let K=F(b,Z);if(!K.success)throw Error(`Invalid --agents definition for "${z}"`);let q=K.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:W(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
|
|
2
2
|
export{O as zc};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as E}from"./chunk-
|
|
1
|
+
import{r as E}from"./chunk-a1ztrwjb.js";import{s as YJ}from"./chunk-4v8nxcxp.js";import{$ as o,F as m,I as d,J as l,L as i,Z as r,_ as a,aa as n,v as A}from"./chunk-ryhk5qmv.js";import{ka as WJ}from"./chunk-4tkn9bky.js";import"./chunk-ktbe458z.js";import{Va as c,Ya as p,hb as v}from"./chunk-72ztan96.js";import{sb as T}from"./chunk-095x2ykj.js";import{Hb as f,Qb as M,Rb as u,Tb as R,Wb as g,_b as N,bc as D}from"./chunk-1p5822w7.js";import"./chunk-vprpk6q1.js";import"./chunk-65kbckpt.js";import"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import{hd as ZJ}from"./chunk-yz2bsntj.js";import"./chunk-sj2w24fe.js";import"./chunk-afhdpen9.js";import{sd as $J}from"./chunk-5chec8rs.js";import"./chunk-4ypy5bk8.js";import"./chunk-g7p165yz.js";import"./chunk-r1jxbx1h.js";import{Xd as zJ}from"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import{je as b}from"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import{hf as I,if as S,jf as y}from"./chunk-0qayfsc9.js";import{nf as e}from"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import{tf as JJ,wf as QJ}from"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import{Readable as VJ,Writable as wJ}from"node:stream";import*as x from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as BJ}from"@agentclientprotocol/sdk";import s from"node:path";import{RequestError as GJ}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var j=b("Agent");function C(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function XJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:C(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:C("headers"in J?J.headers:void 0)};return null}function jJ(J){let Z={};for(let Q of J){let Y=XJ(Q);if(Y)Z[Q.name]=Y}return Z}function t(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function DJ(J){let Z=u(J.metadata);return Z?[{type:"text",text:M(Z)}]:t(J.content)}function LJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}class O{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;contextMessages;mode;constructor(J,Z,Q,Y,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode)}async refreshPersistedMessages(){let[J,Z]=await Promise.all([D.loadSession(this.id,this.cwd),D.loadSessionModelContext(this.id,this.cwd)]);if(J.length>0)this.messages=J;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(J){let Z=await D.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...J]}mapPermissionModeToMode(J){switch(J){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return i.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(j.debug(`[AcpSession ${this.id}] Initializing...`),await D.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),A.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),j.debug(`[AcpSession ${this.id}] ACP service context initialized`),await v.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?jJ(this.options.mcpServers):void 0,Q=A.getInstance().getTerminalService(this.id);if(this.runtime=await m.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(z,$)=>{let F=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(G)=>$.onOutput?.("stdout",G)});return{exitCode:F.exitCode,stdout:F.stdout,stderr:F.stderr,...F.error?{error:F.error}:{},timedOut:F.error==="Command timed out",aborted:F.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await a(this.cwd),j.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=p.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of DJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);j.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{j.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await this.runtime.rewindSession($);return this.messages=[...F.messages],this.contextMessages=await this.loadModelContextOr(F.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),F}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async($)=>{if(await this.setReasoningEffort($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async($)=>{if(await this.setServiceTier($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async($)=>{if(await this.setResponseVerbosity($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async($)=>{if(await this.setCommunicationStyle($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=!1,X,L=(W)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.id,status:W.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:W.result?.message||W.result?.error||`Subagent ${W.status}`}}]})},B=this.runtime.resumeSubagent({agentId:$,prompt:F,onCompleted:(W)=>{if(G)L(W);else X=W}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.session.id,status:"in_progress",title:`Resuming ${B.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${B.source.id} at depth ${B.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),G=!0,X)L(X);return B}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs($)},getPrompt:async($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,F,G)},complete:async($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,F,G)},listTasks:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks($)},getTask:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask($)},cancelTask:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,F)},getLogs:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,F)},setLoggingLevel:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,F)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:F,onEvent:(B)=>{if(B.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.toolCall.id,status:"in_progress",title:`Review: ${B.toolCall.function.name}`,content:[],kind:this.mapToolKind(B.toolKind)});else if(B.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.toolCall.id,status:B.result.success?"completed":"failed",content:[]})}}),X=await G.completion,L=(await E.list(this.cwd,this.id)).find((B)=>B.start.reviewId===G.reviewId);if(!L)throw Error(`Review not found: ${G.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:G.reviewId,status:X.status,findings:X.findings.length,content:f(L.start,X)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,F,G)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(G);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(F,null,2)}}],kind:L})},sendToolResult:($,F)=>{if(F.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:F.summary}})}}},Y=await o(J,Q),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let $=await D.loadSession(this.id,this.cwd);if($.length>0)this.messages=$}let z=Y.content||Y.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return{stopReason:Y.success?"end_turn":"cancelled"}}catch(Q){return j.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=n(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});j.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),j.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){j.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(A.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((G)=>G.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=g(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let G=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!G.accepted)throw Error(G.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(j.debug(`[AcpSession ${this.id}] Queued steering for active turn (${G.queued})`),G.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let F=new AbortController;this.pendingPrompt=F;try{if(j.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),r(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,F.signal)}let G={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(W)=>{this.mode=this.mapPermissionModeToMode(W),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}},X=await c(this.agent.chatStream(Y,G,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(W)=>{switch(W.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let w=W.toolCall,_=w.function.name;if(_===R)break;let q=this.mapToolKind(W.toolKind),V=`Executing ${_}`;if(_==="Task"&&"function"in w)try{let P=JSON.parse(w.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")V=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:q});break}case"tool_progress":{let w=W.toolCall;if(w.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let w=W.toolCall;if(w.function.name===R)break;let _=W.result,q=[],V=_.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let K of V.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;q.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))q.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let K=w.function.name,HJ=l(d(K,_));q.push({type:"content",content:{type:"text",text:HJ}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let P=_.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:P,content:q});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(W.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{M as
|
|
1
|
+
import{Rf as F}from"./chunk-fasxw5bb.js";import{execSync as G}from"node:child_process";import*as C from"node:os";import*as v from"node:path";function H(k){return v.resolve(k).replace(/[/\\]/g,"-").replace(/:/g,"_")}function M(k){let q=k.replace(/_/g,":");if(q.startsWith("-"))q="/"+q.slice(1);return q.replace(/-/g,"/")}function z(k){let q=H(k);return v.join(E(),"projects",q)}function J(k){return typeof k==="string"&&k!=="."&&k!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(k)}function A(k){if(!J(k))throw Error(`Invalid session ID: ${k}`)}function N(k,q){return A(q),v.join(z(k),`${q}.jsonl`)}function O(k,q){return A(q),v.join(z(k),`${q}.inbox.json`)}function Q(k,q){return A(q),v.join(z(k),`${q}.goal.json`)}function T(k){try{return G("git rev-parse --abbrev-ref HEAD",{cwd:k,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E(){return process.env.BLADE_STORAGE_ROOT||v.join(C.homedir(),".blade")}async function U(){let{readdir:k}=await import("node:fs/promises");try{let q=v.join(E(),"projects");return(await k(q,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}
|
|
2
|
+
export{M as Hf,z as If,J as Jf,A as Kf,N as Lf,O as Mf,Q as Nf,T as Of,E as Pf,U as Qf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ie as o}from"./chunk-6207mbmr.js";import{cf as J,df as $,ef as O,ff as W}from"./chunk-96h588rd.js";import{gf as v,hf as S,if as l}from"./chunk-3qhqbj09.js";import{Of as n}from"./chunk-yvf4nmds.js";var G=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],a={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},f=new Map;function D(Q,Z,K){let B=new Set;for(let X of Q.split(",")){let[Y,k]=X.split("/"),V=k?Number.parseInt(k,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=K;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[U,i]=Y.split("-");j=Number.parseInt(U,10),H=Number.parseInt(i,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>K||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let U=j;U<=H;U+=V)B.add(U)}return B}function C(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[K,B,X,Y,k]=Z,V=D(k,G[4].min,G[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(K,G[0].min,G[0].max),hours:D(B,G[1].min,G[1].max),daysOfMonth:D(X,G[2].min,G[2].max),months:D(Y,G[3].min,G[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:k.trim()!=="*"}}function t(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let K=f.get(Z);if(!K)K=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),f.set(Z,K);let B=Object.fromEntries(K.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:a[B.weekday]??-1}}function r(Q,Z,K){let B=t(Z,K);if(!Q.minutes.has(B.minute))return!1;if(!Q.hours.has(B.hour))return!1;if(!Q.months.has(B.month))return!1;let X=Q.daysOfMonth.has(B.dayOfMonth),Y=Q.daysOfWeek.has(B.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function T(Q,Z,K){let B=C(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(r(B,X,K))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var E={s:1000,m:60000,h:3600000,d:86400000};function DJ(Q){let K=Q.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 X=K[2]||"m";return B*E[X]}function y(Q){for(let Z of["d","h","m","s"]){let K=E[Z];if(Q%K===0)return`${Q/K}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,K){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return T(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((K??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let B=new Date(Q.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>Z.getTime()?B:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(C(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function FJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?y(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as bJ,readFile as wJ}from"node:fs/promises";import s from"node:path";import{nanoid as LJ}from"nanoid";import PJ from"write-file-atomic";var w=$(W(["default","autoEdit","yolo","plan"]));var N=$(W(["user","assistant","system","tool"])),p=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),h=J.Union([J.String(),J.Array(p)]),NJ=$(J.Object({id:J.String(),role:N,content:h,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),e=$(W(["queued","running","completed","failed","cancelled","interrupted"])),F=$(W(["local","worktree"])),JJ=$(W(["applied","discarded","conflicted"])),QJ=$(J.Object({status:JJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),ZJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),$J=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),qJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array($J,{maxItems:100}),truncated:J.Boolean()})),BJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),KJ=$(J.Object({name:J.String(),type:W(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(BJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(W(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),xJ=$(J.Object({serverName:J.String(),mode:W(["form","url"]),message:J.String(),fields:J.Optional(J.Array(KJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),WJ=$(J.Object({type:W(["permission","question","elicitation"]),requestId:J.String()})),XJ=$(J.Object({code:W(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean()})),L=$(W(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(W(["auto","standard","fast","flex"])),M=$(W(["auto","low","medium","high"])),b=$(J.Union([W(["auto","pragmatic","friendly","explanatory"]),J.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})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(W(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:O(e,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(XJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional(QJ),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(ZJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(WJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),fJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),CJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),EJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),RJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:W(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),completionVerification:J.Optional(J.Object({attempt:J.Integer({minimum:1}),status:W(["pending","pass","fail","partial"]),requestedAt:J.String(),completedAt:J.Optional(J.String()),verifierSessionId:J.Optional(J.String()),summary:J.Optional(J.String()),evidenceSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),createdAt:J.String(),updatedAt:J.String()})),u=$(J.Object({role:N,content:h,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),SJ=$(J.Object({session:z,messages:J.Array(u)})),d=$(W(["conversation","code","both"])),YJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),lJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:O(d,"conversation")})),hJ=$(J.Object({checkpoint:YJ,mode:d,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(u)})),HJ=W(["running","completed","failed","cancelled"]),R=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:HJ,rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(W(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),uJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),dJ=$(J.Object({source:R,session:R})),mJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),cJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),gJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),nJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),m=J.Object({type:W(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:S})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),c=J.Record(J.String(),J.Unknown()),oJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),sJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:W(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),iJ=$(J.Object({action:W(["apply","discard"])})),q=$(J.Object({kind:W(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),jJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default")})),x=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,dispatch:jJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(W(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),enabled:O(J.Boolean(),!0)})),tJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(q),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),rJ=$(J.Object({schedules:J.Array(x)})),TJ=$(J.Object({content:J.String({maxLength:l}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),UJ=W(["completed","failed","aborted","timed_out","spawn_error"]),kJ=$(J.Object({version:J.Literal(1),command:J.String(),status:UJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),yJ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),pJ=$(J.Object({executionId:J.String(),messageId:J.String(),record:kJ,auxiliary:J.Boolean(),delivery:J.Optional(W(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),eJ=$(J.Object({projectPath:J.String(),kind:W(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),JQ=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),QQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),ZQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(W(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:W(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),VJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:W(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),$Q=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(W(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(W(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(W(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(VJ,{maxItems:36})),input:J.Optional(J.Array(W(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),BQ=$(W(["vs-dark","vs-light","hc-black"])),GJ=$(W(["light","dark","system"])),OJ=$(J.Object({language:J.String(),theme:J.String(),uiTheme:GJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),KQ=$(J.Partial(OJ));var g=o("Service"),MJ=1;function IJ(){return s.join(n(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=IJ()){this.filePath=Q}async readFile(){try{let Q=await wJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let K=[],B=0;for(let X of Z.schedules){let Y=x.safeParse(X);if(Y.success)K.push(Y.data);else B+=1}if(B>0)g.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return K}catch(Q){let Z=Q;if(Z.code!=="ENOENT")g.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await bJ(s.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:MJ,schedules:Q};await PJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((K)=>K.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,K=_(Z);if(K)throw Error(K);let B=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let X=B.toISOString(),Y=A(Z,B),k={id:LJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(k),await this.writeFile(V),k})}async update(Q,Z){return this.serializeWrite(async()=>{let K=await this.readFile(),B=K.findIndex((H)=>H.id===Q);if(B===-1)return;let X=K[B];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,U=_(H);if(U)throw Error(U);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},k=!X.enabled,V=Y.enabled,j=Z.trigger!==void 0;if((j||k&&V)&&Z.nextRunAt===void 0){let H=new Date,U=A(Y.trigger,H);if(Y.nextRunAt=U?U.toISOString():null,j)Y.expiresAt=null}return K[B]=Y,await this.writeFile(K),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),K=Z.filter((B)=>B.id!==Q);if(K.length===Z.length)return!1;return await this.writeFile(K),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var LQ=I.getInstance();
|
|
1
|
+
import{je as o}from"./chunk-77z6x1zb.js";import{df as J,ef as $,ff as O,gf as W}from"./chunk-r561wfcz.js";import{hf as v,if as S,jf as l}from"./chunk-0qayfsc9.js";import{Pf as n}from"./chunk-kmeccj99.js";var G=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],a={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},f=new Map;function D(Q,Z,K){let B=new Set;for(let X of Q.split(",")){let[Y,k]=X.split("/"),V=k?Number.parseInt(k,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=K;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[U,i]=Y.split("-");j=Number.parseInt(U,10),H=Number.parseInt(i,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>K||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let U=j;U<=H;U+=V)B.add(U)}return B}function C(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[K,B,X,Y,k]=Z,V=D(k,G[4].min,G[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(K,G[0].min,G[0].max),hours:D(B,G[1].min,G[1].max),daysOfMonth:D(X,G[2].min,G[2].max),months:D(Y,G[3].min,G[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:k.trim()!=="*"}}function t(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let K=f.get(Z);if(!K)K=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),f.set(Z,K);let B=Object.fromEntries(K.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:a[B.weekday]??-1}}function r(Q,Z,K){let B=t(Z,K);if(!Q.minutes.has(B.minute))return!1;if(!Q.hours.has(B.hour))return!1;if(!Q.months.has(B.month))return!1;let X=Q.daysOfMonth.has(B.dayOfMonth),Y=Q.daysOfWeek.has(B.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function T(Q,Z,K){let B=C(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(r(B,X,K))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var E={s:1000,m:60000,h:3600000,d:86400000};function DJ(Q){let K=Q.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 X=K[2]||"m";return B*E[X]}function y(Q){for(let Z of["d","h","m","s"]){let K=E[Z];if(Q%K===0)return`${Q/K}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,K){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return T(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((K??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let B=new Date(Q.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>Z.getTime()?B:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(C(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function FJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?y(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as bJ,readFile as wJ}from"node:fs/promises";import s from"node:path";import{nanoid as LJ}from"nanoid";import PJ from"write-file-atomic";var w=$(W(["default","autoEdit","yolo","plan"]));var N=$(W(["user","assistant","system","tool"])),p=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),h=J.Union([J.String(),J.Array(p)]),NJ=$(J.Object({id:J.String(),role:N,content:h,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),e=$(W(["queued","running","completed","failed","cancelled","interrupted"])),F=$(W(["local","worktree"])),JJ=$(W(["applied","discarded","conflicted"])),QJ=$(J.Object({status:JJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),ZJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),$J=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),qJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array($J,{maxItems:100}),truncated:J.Boolean()})),BJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),KJ=$(J.Object({name:J.String(),type:W(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(BJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(W(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),xJ=$(J.Object({serverName:J.String(),mode:W(["form","url"]),message:J.String(),fields:J.Optional(J.Array(KJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),WJ=$(J.Object({type:W(["permission","question","elicitation"]),requestId:J.String()})),XJ=$(J.Object({code:W(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean()})),L=$(W(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(W(["auto","standard","fast","flex"])),M=$(W(["auto","low","medium","high"])),b=$(J.Union([W(["auto","pragmatic","friendly","explanatory"]),J.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})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(W(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:O(e,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(XJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional(QJ),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(ZJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(WJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),fJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),CJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),EJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),RJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:W(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),completionVerification:J.Optional(J.Object({attempt:J.Integer({minimum:1}),status:W(["pending","pass","fail","partial"]),requestedAt:J.String(),completedAt:J.Optional(J.String()),verifierSessionId:J.Optional(J.String()),summary:J.Optional(J.String()),evidenceSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),createdAt:J.String(),updatedAt:J.String()})),u=$(J.Object({role:N,content:h,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),SJ=$(J.Object({session:z,messages:J.Array(u)})),d=$(W(["conversation","code","both"])),YJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),lJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:O(d,"conversation")})),hJ=$(J.Object({checkpoint:YJ,mode:d,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(u)})),HJ=W(["running","completed","failed","cancelled"]),R=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:HJ,rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(W(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),uJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),dJ=$(J.Object({source:R,session:R})),mJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),cJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),gJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),nJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),m=J.Object({type:W(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:S})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),c=J.Record(J.String(),J.Unknown()),oJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),sJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:W(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),iJ=$(J.Object({action:W(["apply","discard"])})),q=$(J.Object({kind:W(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),jJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default")})),x=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,dispatch:jJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(W(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),enabled:O(J.Boolean(),!0)})),tJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(q),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),rJ=$(J.Object({schedules:J.Array(x)})),TJ=$(J.Object({content:J.String({maxLength:l}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),UJ=W(["completed","failed","aborted","timed_out","spawn_error"]),kJ=$(J.Object({version:J.Literal(1),command:J.String(),status:UJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),yJ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),pJ=$(J.Object({executionId:J.String(),messageId:J.String(),record:kJ,auxiliary:J.Boolean(),delivery:J.Optional(W(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),eJ=$(J.Object({projectPath:J.String(),kind:W(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),JQ=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),QQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),ZQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(W(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:W(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),VJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:W(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),$Q=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(W(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(W(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(W(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(VJ,{maxItems:36})),input:J.Optional(J.Array(W(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),BQ=$(W(["vs-dark","vs-light","hc-black"])),GJ=$(W(["light","dark","system"])),OJ=$(J.Object({language:J.String(),theme:J.String(),uiTheme:GJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),KQ=$(J.Partial(OJ));var g=o("Service"),MJ=1;function IJ(){return s.join(n(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=IJ()){this.filePath=Q}async readFile(){try{let Q=await wJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let K=[],B=0;for(let X of Z.schedules){let Y=x.safeParse(X);if(Y.success)K.push(Y.data);else B+=1}if(B>0)g.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return K}catch(Q){let Z=Q;if(Z.code!=="ENOENT")g.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await bJ(s.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:MJ,schedules:Q};await PJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((K)=>K.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,K=_(Z);if(K)throw Error(K);let B=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let X=B.toISOString(),Y=A(Z,B),k={id:LJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(k),await this.writeFile(V),k})}async update(Q,Z){return this.serializeWrite(async()=>{let K=await this.readFile(),B=K.findIndex((H)=>H.id===Q);if(B===-1)return;let X=K[B];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,U=_(H);if(U)throw Error(U);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},k=!X.enabled,V=Y.enabled,j=Z.trigger!==void 0;if((j||k&&V)&&Z.nextRunAt===void 0){let H=new Date,U=A(Y.trigger,H);if(Y.nextRunAt=U?U.toISOString():null,j)Y.expiresAt=null}return K[B]=Y,await this.writeFile(K),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),K=Z.filter((B)=>B.id!==Q);if(K.length===Z.length)return!1;return await this.writeFile(K),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var LQ=I.getInstance();
|
|
2
2
|
export{DJ as la,A as ma,_ as na,FJ as oa,qJ as pa,z as qa,lJ as ra,uJ as sa,oJ as ta,sJ as ua,iJ as va,x as wa,aJ as xa,tJ as ya,rJ as za,TJ as Aa,yJ as Ba,eJ as Ca,I as Da,LQ as Ea};
|