blade-code 0.10.24 → 0.10.26
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-01n8k1jj.js +1 -0
- package/dist/{chunk-1gkpjhts.js → chunk-0q4jbbm5.js} +1 -1
- package/dist/{chunk-9c3jjbgd.js → chunk-1g5h4zv6.js} +1 -1
- package/dist/{chunk-xzdpdwhz.js → chunk-1hzj6s0f.js} +2 -2
- package/dist/chunk-1mh2285d.js +200 -0
- package/dist/{chunk-26zhy301.js → chunk-20kg90zt.js} +2 -2
- package/dist/{chunk-18n15nn8.js → chunk-35d5gdgw.js} +1 -1
- package/dist/{chunk-f8zz4se0.js → chunk-46yg6dfr.js} +2 -2
- package/dist/{chunk-f4ksxskk.js → chunk-4aem0m2n.js} +1 -1
- package/dist/chunk-58tpe6nx.js +44 -0
- package/dist/{chunk-phzy5kqq.js → chunk-58yqrbey.js} +1 -1
- package/dist/{chunk-5xph8r1k.js → chunk-5mtryjjc.js} +1 -1
- package/dist/chunk-5yr2c8gz.js +25 -0
- package/dist/chunk-6axhk4r7.js +2 -0
- package/dist/chunk-6k74z0eb.js +2 -0
- package/dist/{chunk-yac1ga9w.js → chunk-6srz3q5d.js} +1 -1
- package/dist/{chunk-d2kzet1k.js → chunk-7jv8thn1.js} +2 -2
- package/dist/{chunk-3fkj59nv.js → chunk-89gswfb2.js} +1 -1
- package/dist/{chunk-w56y2pvk.js → chunk-8htfb5zn.js} +2 -2
- package/dist/{chunk-hpmxmkzc.js → chunk-9ka0bdry.js} +1 -1
- package/dist/{chunk-m13jrgp9.js → chunk-a4cyec1y.js} +2 -2
- package/dist/chunk-aa28p37g.js +2 -0
- package/dist/chunk-acf5v2fv.js +2 -0
- package/dist/chunk-b5fegjt7.js +6 -0
- package/dist/chunk-bbjtt28z.js +1 -0
- package/dist/{chunk-6vfe3409.js → chunk-ct2x59pr.js} +1 -1
- package/dist/chunk-d9jz1edf.js +100 -0
- package/dist/chunk-dxgzyy09.js +1 -0
- package/dist/{chunk-j8ggq1z4.js → chunk-ebffhjma.js} +2 -2
- package/dist/{chunk-bp886b8j.js → chunk-edyxa2jw.js} +1 -1
- package/dist/{chunk-k2b95m2p.js → chunk-eqa706gn.js} +2 -2
- package/dist/chunk-f88wkyfm.js +1 -0
- package/dist/{chunk-aw8s1sej.js → chunk-fbc5zfq7.js} +1 -1
- package/dist/chunk-fkwqgqsw.js +1 -0
- package/dist/{chunk-m27w377p.js → chunk-fnt1z0y8.js} +1 -1
- package/dist/chunk-gahvpbbs.js +1 -0
- package/dist/{chunk-57q5wn4g.js → chunk-gn37wxwg.js} +1 -1
- package/dist/chunk-h2npwqz9.js +10 -0
- package/dist/{chunk-c674mmtj.js → chunk-jt55ct49.js} +2 -2
- package/dist/{chunk-xjqcc0nt.js → chunk-k99rbzqw.js} +1 -1
- package/dist/{chunk-wjqctwyr.js → chunk-kskg7crs.js} +26 -41
- package/dist/{chunk-p1dp2xgq.js → chunk-kvd5nexw.js} +1 -1
- package/dist/chunk-kwe0a3xw.js +1 -0
- package/dist/chunk-m7x4ya6m.js +1 -0
- package/dist/chunk-mqsxghqb.js +1 -0
- package/dist/chunk-nar8qz5t.js +1 -0
- package/dist/{chunk-5sw8j9ae.js → chunk-nt6xmzk0.js} +1 -1
- package/dist/chunk-p6nhdbdw.js +116 -0
- package/dist/{chunk-67ekta7b.js → chunk-pja0tttq.js} +1 -1
- package/dist/{chunk-my2jwz6y.js → chunk-px3t1rxa.js} +2 -2
- package/dist/chunk-pyfag66h.js +1 -0
- package/dist/chunk-q1papzdc.js +1 -0
- package/dist/{chunk-pccn8ndq.js → chunk-r46ws0q8.js} +2 -2
- package/dist/{chunk-bw7vknjr.js → chunk-rgafk34p.js} +1 -1
- package/dist/chunk-rth3jfdq.js +2 -0
- package/dist/{chunk-nqpcwa0k.js → chunk-rtktz9v1.js} +233 -231
- package/dist/{chunk-s14wmzm3.js → chunk-s1khjfye.js} +2 -2
- package/dist/{chunk-vns8g2rv.js → chunk-sprjrvn6.js} +1 -1
- package/dist/chunk-ss449b56.js +1 -0
- package/dist/{chunk-yaxapgbm.js → chunk-tg1mf1tf.js} +1 -1
- package/dist/{chunk-x6tns9d8.js → chunk-tnrrnzzv.js} +1 -1
- package/dist/chunk-v508x7cg.js +0 -0
- package/dist/chunk-vc2c8wkx.js +2 -0
- package/dist/chunk-vp50e95n.js +3 -0
- package/dist/chunk-wg8p9g0z.js +1 -0
- package/dist/chunk-xkb48pvz.js +1 -0
- package/dist/{chunk-t327cwnb.js → chunk-xp44jtsd.js} +1 -1
- package/dist/chunk-y2en7qvs.js +6 -0
- package/dist/{chunk-86zsjamb.js → chunk-zs9mwd17.js} +3 -3
- package/dist/web/assets/{ChatView-CCxjYDmJ.js → ChatView-Crna6-ID.js} +2 -2
- package/dist/web/assets/{CodeBlockHighlighter-D9MqsrZP.js → CodeBlockHighlighter-coWjWCyT.js} +1 -1
- package/dist/web/assets/{FilePreview-Cn5HOlPw.js → FilePreview-BKcCbpvz.js} +2 -2
- package/dist/web/assets/{MarkdownRenderer-ALTOCdfi.js → MarkdownRenderer-BqV1nvf1.js} +3 -3
- package/dist/web/assets/{SettingsModal-Dk69F1bS.js → SettingsModal-BOMswk9P.js} +2 -2
- package/dist/web/assets/{TaskSwitcher-DRZZocE1.js → TaskSwitcher-BEW2DhW3.js} +1 -1
- package/dist/web/assets/{TerminalPanel-ByAqKZ47.js → TerminalPanel-BXzypTz6.js} +1 -1
- package/dist/web/assets/index-DqXKkjcp.js +11 -0
- package/dist/web/index.html +1 -1
- package/package.json +2 -1
- package/dist/chunk-014rwj5b.js +0 -1
- package/dist/chunk-0568ndm9.js +0 -200
- package/dist/chunk-1pkca2km.js +0 -3
- package/dist/chunk-2wpnzjme.js +0 -1
- package/dist/chunk-3ak60ndt.js +0 -1
- package/dist/chunk-3qmwt188.js +0 -100
- package/dist/chunk-4a02yjg9.js +0 -2
- package/dist/chunk-6pb6zs96.js +0 -2
- package/dist/chunk-7dqc10sc.js +0 -1
- package/dist/chunk-ag07wwer.js +0 -2
- package/dist/chunk-bpz0g8ej.js +0 -2
- package/dist/chunk-bvwq5wth.js +0 -6
- package/dist/chunk-c29y2s8g.js +0 -2
- package/dist/chunk-d70mtcp4.js +0 -1
- package/dist/chunk-e71qm105.js +0 -1
- package/dist/chunk-edqtngzr.js +0 -44
- package/dist/chunk-f0mt91sr.js +0 -1
- package/dist/chunk-gwe547ww.js +0 -1
- package/dist/chunk-m486vmtn.js +0 -1
- package/dist/chunk-n00mknme.js +0 -25
- package/dist/chunk-n54tp9wr.js +0 -1
- package/dist/chunk-pq7tk058.js +0 -6
- package/dist/chunk-q5sewfn5.js +0 -1
- package/dist/chunk-qg87zezq.js +0 -1
- package/dist/chunk-r14bz8va.js +0 -1
- package/dist/chunk-rtkhyp1g.js +0 -1
- package/dist/chunk-s4mqw4wa.js +0 -116
- package/dist/chunk-sgnjekfb.js +0 -1
- package/dist/chunk-tetxqw28.js +0 -1
- package/dist/chunk-vmzf4nvh.js +0 -2
- package/dist/chunk-zm3zn23k.js +0 -10
- package/dist/web/assets/index-CRCirUK7.js +0 -11
|
@@ -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 of,D as pf,P as qf,V as rf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{If as a,Jf as b,Kf as c,Lf as d,Mf as e,Nf as f}from"./chunk-acf5v2fv.js";import"./chunk-sprjrvn6.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as o}from"./chunk-aa28p37g.js";import"./chunk-acf5v2fv.js";import"./chunk-sprjrvn6.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Of as a}from"./chunk-r46ws0q8.js";import"./chunk-tnrrnzzv.js";import"./chunk-s1khjfye.js";import"./chunk-sprjrvn6.js";export{a as WorkspaceTrustService};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{vd as a,wd as b,xd as c}from"./chunk-1hzj6s0f.js";import"./chunk-fnt1z0y8.js";import"./chunk-jt55ct49.js";import"./chunk-0q4jbbm5.js";import"./chunk-s1khjfye.js";import"./chunk-sprjrvn6.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import{vf as i}from"./chunk-8htfb5zn.js";import{Qf as o,Sf as C,Uf as L,Yf as j,Zf as n}from"./chunk-s1khjfye.js";import{_f as I}from"./chunk-sprjrvn6.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
|
|
2
|
+
`),W=!_.endsWith(`
|
|
3
|
+
`),$=[];for(let[H,k]of R.entries())try{let M=V_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E=await V.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map(x).join(`
|
|
4
|
+
`)}
|
|
5
|
+
`;return await E.appendFile(R+H,"utf8"),await E.sync(),$}finally{await E.close()}})}async createExclusive(_){if(_.length===0)throw Error("Cannot create an empty session transcript");await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E;try{E=await V.open(this.filePath,"wx",384);let W=`${Y.stampSeq(_,[]).map(x).join(`
|
|
6
|
+
`)}
|
|
7
|
+
`;await E.writeFile(W,"utf-8"),await E.sync()}catch(R){if(E)await E.close(),E=void 0,await V.unlink(this.filePath).catch(()=>{return});throw R}finally{await E?.close()}}async readAll(){if(!f.existsSync(this.filePath))return[];let _=await V.readFile(this.filePath,"utf-8");return z(_,this.filePath)}async readStream(_){return new Promise((E,R)=>{if(!f.existsSync(this.filePath)){E();return}let W=M_(this.filePath,"utf-8"),$=Q_({input:W,crlfDelay:Number.POSITIVE_INFINITY}),H=0;$.on("line",async(k)=>{let M=k.trim();if(M.length===0)return;try{let X=JSON.parse(M);if(H+=1,typeof X.seq!=="number")X.seq=H;await _(X)}catch(X){console.warn(`[JSONLStore] 解析 JSON 行失败: ${M}`,X)}}),$.on("close",()=>E()),$.on("error",R),W.on("error",R)})}async filter(_){let E=[];return await this.readStream((R)=>{if(_(R))E.push(R)}),E}async readLast(_){return(await this.readAll()).slice(-_)}async readFromSeq(_){return(await this.readAll()).filter((R)=>(R.seq??0)>=_)}async getStats(){try{if(!f.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let _=await V.stat(this.filePath),R=(await V.readFile(this.filePath,"utf-8")).split(`
|
|
8
|
+
`).filter((W)=>W.trim().length>0).length;return{exists:!0,size:_.size,lineCount:R}}catch(_){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,_),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await V.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await V.unlink(this.filePath),!0}catch(_){if(_.code==="ENOENT")return!1;throw _}})}catch(_){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,_),_}}async deleteValidated(_){return this.enqueue(async()=>{let E;try{E=await V.open(this.filePath,"r")}catch(W){if(W.code==="ENOENT")return!1;throw W}let R;try{R=z(await E.readFile("utf8"),"session transcript")}finally{await E.close()}if(!_(R))return!1;try{return await V.unlink(this.filePath),!0}catch(W){if(W.code==="ENOENT")return!1;throw W}})}async appendValidated(_){return this.appendValidatedAsync(async(E)=>_(E))}async appendValidatedBatch(_){return this.appendValidatedBatchAsync(async(E)=>_(E))}async appendValidatedBatchAsync(_){return this.enqueue(async()=>{let E=await V.open(this.filePath,"r+");try{let{entries:R,separator:W,size:$}=await this.readCommittedState(E,"session transcript"),H=await _(R);if(H.length===0)return[];let k=Y.stampSeq(H,R),M=`${k.map(x).join(`
|
|
9
|
+
`)}
|
|
10
|
+
`;return await E.write(W+M,$,"utf8"),await E.sync(),k}finally{await E.close()}})}async appendValidatedAsync(_){return this.enqueue(async()=>{let E=await V.open(this.filePath,"r+");try{let{entries:R,separator:W,size:$}=await this.readCommittedState(E,"session transcript"),H=await _(R),[k]=Y.stampSeq([H],R),M=`${W}${x(k)}
|
|
11
|
+
`;return await E.write(M,$,"utf8"),await E.sync(),k}finally{await E.close()}})}getFilePath(){return this.filePath}async enqueue(_){let R=(Y.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(_),W=R.then(()=>{return},()=>{return});Y.appendQueues.set(this.filePath,W);try{return await R}finally{if(Y.appendQueues.get(this.filePath)===W)Y.appendQueues.delete(this.filePath)}}async readCommittedState(_,E=this.filePath){let R=await this.repairIncompleteTail(_),W=await _.readFile("utf8"),$=z(W,E),{size:H}=await _.stat();return{entries:$,separator:R,size:H}}async readTailSeq(_){let{size:E}=await _.stat();if(E===0)return 0;let R=Math.max(0,E-m),W=Buffer.allocUnsafe(E-R);await _.read(W,0,W.length,R);let $=W.toString("utf8").split(`
|
|
12
|
+
`);for(let k=$.length-1;k>=0;k--){let M=$[k].trim();if(!M)continue;if(k===0&&R>0)break;try{let X=JSON.parse(M).seq;if(typeof X==="number")return X}catch{}break}let H=await _.readFile("utf8");return Y.maxSeq(z(H,this.filePath))}async repairIncompleteTail(_){let{size:E}=await _.stat();if(E===0)return"";let R=Buffer.allocUnsafe(1);if(await _.read(R,0,1,E-1),R[0]===10)return"";let W=await this.findTailStart(_,E),$=Buffer.allocUnsafe(E-W);await _.read($,0,$.length,W);try{return JSON.parse($.toString("utf8").trim()),`
|
|
13
|
+
`}catch{return await _.truncate(W),""}}async findTailStart(_,E){let R=E;while(R>0){let W=Math.max(0,R-m),$=Buffer.allocUnsafe(R-W);await _.read($,0,$.length,W);let H=$.lastIndexOf(10);if(H>=0)return W+H+1;R=W}return 0}}function X_(){return typeof globalThis.Bun<"u"}function Y_(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.prepare(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>_.pragma(E,{simple:!0}),close:()=>_.close()}}function G_(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.query(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>{let R=_.query(`PRAGMA ${E}`).get();if(!R)return;let W=Object.values(R);return W.length===1?W[0]:R},close:()=>_.close()}}var T_=["PRAGMA journal_mode=WAL;","PRAGMA busy_timeout=5000;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
|
|
14
|
+
`);async function h(_){try{let E;if(X_()){let{Database:W}=await import("bun:sqlite");E=G_(new W(_))}else{let $=(await import("better-sqlite3")).default;E=Y_(new $(_))}return E.exec(T_),E}catch{return null}}function b(_){let E=Number(_.pragma("user_version")??0);if(E===3)return;if(E>0&&E!==3)_.exec(`
|
|
15
|
+
DROP TABLE IF EXISTS parts_fts;
|
|
16
|
+
DROP TABLE IF EXISTS parts;
|
|
17
|
+
DROP TABLE IF EXISTS sessions;
|
|
18
|
+
DROP TABLE IF EXISTS projection_state;
|
|
19
|
+
`);_.exec(`
|
|
20
|
+
CREATE TABLE IF NOT EXISTS projection_state (
|
|
21
|
+
project_path TEXT NOT NULL,
|
|
22
|
+
session_id TEXT NOT NULL,
|
|
23
|
+
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
24
|
+
file_size INTEGER NOT NULL DEFAULT 0,
|
|
25
|
+
mtime_ms INTEGER NOT NULL DEFAULT 0,
|
|
26
|
+
PRIMARY KEY (project_path, session_id)
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
30
|
+
project_path TEXT NOT NULL,
|
|
31
|
+
session_id TEXT NOT NULL,
|
|
32
|
+
root_id TEXT,
|
|
33
|
+
parent_id TEXT,
|
|
34
|
+
relation_type TEXT,
|
|
35
|
+
title TEXT,
|
|
36
|
+
agent_type TEXT,
|
|
37
|
+
model TEXT,
|
|
38
|
+
task_status TEXT,
|
|
39
|
+
archived_at TEXT,
|
|
40
|
+
last_message_time TEXT,
|
|
41
|
+
project_sort_key TEXT NOT NULL,
|
|
42
|
+
session_sort_key TEXT NOT NULL,
|
|
43
|
+
first_message_time TEXT,
|
|
44
|
+
message_count INTEGER NOT NULL DEFAULT 0,
|
|
45
|
+
has_errors INTEGER NOT NULL DEFAULT 0,
|
|
46
|
+
is_subagent INTEGER NOT NULL DEFAULT 0,
|
|
47
|
+
-- 完整 StoredSessionMetadata JSON,读回时直接反序列化,保证与 JSONL 路径一致。
|
|
48
|
+
metadata_json TEXT NOT NULL,
|
|
49
|
+
PRIMARY KEY (project_path, session_id)
|
|
50
|
+
);
|
|
51
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_catalog ON sessions(
|
|
52
|
+
last_message_time DESC,
|
|
53
|
+
project_sort_key ASC,
|
|
54
|
+
session_sort_key ASC
|
|
55
|
+
);
|
|
56
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_archived ON sessions(
|
|
57
|
+
archived_at,
|
|
58
|
+
project_path,
|
|
59
|
+
parent_id
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
CREATE TABLE IF NOT EXISTS parts (
|
|
63
|
+
project_path TEXT NOT NULL,
|
|
64
|
+
session_id TEXT NOT NULL,
|
|
65
|
+
part_id TEXT NOT NULL,
|
|
66
|
+
message_id TEXT,
|
|
67
|
+
part_type TEXT,
|
|
68
|
+
role TEXT,
|
|
69
|
+
seq INTEGER,
|
|
70
|
+
timestamp TEXT,
|
|
71
|
+
text TEXT,
|
|
72
|
+
PRIMARY KEY (project_path, session_id, part_id)
|
|
73
|
+
);
|
|
74
|
+
CREATE INDEX IF NOT EXISTS idx_parts_session ON parts(project_path, session_id);
|
|
75
|
+
|
|
76
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
77
|
+
text,
|
|
78
|
+
project_path UNINDEXED,
|
|
79
|
+
session_id UNINDEXED,
|
|
80
|
+
part_id UNINDEXED,
|
|
81
|
+
role UNINDEXED,
|
|
82
|
+
timestamp UNINDEXED,
|
|
83
|
+
seq UNINDEXED,
|
|
84
|
+
tokenize = 'unicode61'
|
|
85
|
+
);
|
|
86
|
+
`),_.exec("PRAGMA user_version=3;")}var Z_=i("Service"),D;function r(){return B.join(j(),"index.db")}async function K_(){let _=r();if(D&&D.path===_)return D.db;let E=(async()=>{let R=await h(_);if(!R)return null;try{return b(R),R}catch{return null}})();return D={path:_,db:E},E}function U_(){D=void 0}function g_(_){if(_&&typeof _==="object"){let E=_.text;if(typeof E==="string")return E}return null}function F_(_,E,R,W){_.prepare("DELETE FROM parts WHERE project_path=? AND session_id=?").run(E,R),_.prepare("DELETE FROM parts_fts WHERE project_path=? AND session_id=?").run(E,R);let $=new Map;for(let M of W)if(M.type==="message_created")$.set(M.data.messageId,M.data.role);let H=_.prepare(`INSERT OR REPLACE INTO parts
|
|
87
|
+
(project_path, session_id, part_id, message_id, part_type, role, seq, timestamp, text)
|
|
88
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),k=_.prepare(`INSERT INTO parts_fts (text, project_path, session_id, part_id, role, timestamp, seq)
|
|
89
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let M of W){if(M.type!=="part_created"&&M.type!=="part_updated")continue;if(M.data.partType!=="text")continue;let X=g_(M.data.payload);if(X===null)continue;let G=$.get(M.data.messageId)??"assistant",g=M.seq??0;if(H.run(E,R,M.data.partId,M.data.messageId,M.data.partType,G,g,M.timestamp,X),G==="user"||G==="assistant")k.run(X,E,R,M.data.partId,G,M.timestamp,g)}}function D_(_,E){_.prepare(`INSERT INTO sessions
|
|
90
|
+
(project_path, session_id, root_id, parent_id, relation_type, title,
|
|
91
|
+
agent_type, model, task_status, archived_at, last_message_time, project_sort_key,
|
|
92
|
+
session_sort_key, first_message_time, message_count, has_errors,
|
|
93
|
+
is_subagent, metadata_json)
|
|
94
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
95
|
+
ON CONFLICT(project_path, session_id) DO UPDATE SET
|
|
96
|
+
root_id=excluded.root_id, parent_id=excluded.parent_id,
|
|
97
|
+
relation_type=excluded.relation_type, title=excluded.title,
|
|
98
|
+
agent_type=excluded.agent_type, model=excluded.model,
|
|
99
|
+
task_status=excluded.task_status, archived_at=excluded.archived_at,
|
|
100
|
+
last_message_time=excluded.last_message_time,
|
|
101
|
+
project_sort_key=excluded.project_sort_key,
|
|
102
|
+
session_sort_key=excluded.session_sort_key,
|
|
103
|
+
first_message_time=excluded.first_message_time, message_count=excluded.message_count,
|
|
104
|
+
has_errors=excluded.has_errors, is_subagent=excluded.is_subagent,
|
|
105
|
+
metadata_json=excluded.metadata_json`).run(E.projectPath,E.sessionId,E.rootId,E.parentId??null,E.relationType??null,E.title??null,E.agentType??null,E.model??null,E.taskStatus,E.archivedAt??null,E.lastMessageTime,y(E.projectPath),y(E.sessionId),E.firstMessageTime,E.messageCount,E.hasErrors?1:0,E.relationType==="subagent"?1:0,JSON.stringify(E))}function a(_,E,R){for(let W of["sessions","parts","parts_fts"])_.prepare(`DELETE FROM ${W} WHERE project_path=? AND session_id=?`).run(E,R)}function v(_,E,R){a(_,E,R),_.prepare("DELETE FROM projection_state WHERE project_path=? AND session_id=?").run(E,R)}function N(_,E,R,W,$,H){_.prepare(`INSERT INTO projection_state
|
|
106
|
+
(project_path, session_id, last_seq, file_size, mtime_ms)
|
|
107
|
+
VALUES (?, ?, ?, ?, ?)
|
|
108
|
+
ON CONFLICT(project_path, session_id) DO UPDATE SET
|
|
109
|
+
last_seq=excluded.last_seq, file_size=excluded.file_size,
|
|
110
|
+
mtime_ms=excluded.mtime_ms`).run(E,R,W,$,H)}async function B_(_,E,R,W,$=L(R,E)){let H;try{let Q=await d($);H={size:Q.size,mtimeMs:Q.mtimeMs}}catch{return _.transaction(()=>v(_,R,E)),!0}let k=_.prepare("SELECT last_seq, file_size, mtime_ms FROM projection_state WHERE project_path=? AND session_id=?").get(R,E);if(k&&k.file_size===H.size&&k.mtime_ms===Math.floor(H.mtimeMs))return!1;let X=await new Y($).readAll(),G=X.reduce((Q,Z)=>typeof Z.seq==="number"&&Z.seq>Q?Z.seq:Q,0),g=w(X),T=W(X,E,R);if(X.length===0||!T)return _.transaction(()=>{a(_,R,E),N(_,R,E,G,H.size,Math.floor(H.mtimeMs))}),!0;let F=_.prepare("SELECT last_message_time FROM sessions WHERE project_path=? AND session_id=?").get(T.projectPath,T.sessionId),A=B.resolve($)===B.resolve(L(T.projectPath,T.sessionId));if(F&&!A&&typeof F.last_message_time==="string"&&F.last_message_time>T.lastMessageTime)return N(_,R,E,G,H.size,Math.floor(H.mtimeMs)),!0;return _.transaction(()=>{D_(_,T),F_(_,T.projectPath,T.sessionId,g),N(_,R,E,G,H.size,Math.floor(H.mtimeMs))}),!0}var l=new WeakMap;async function A_(_,E,R=0){let W=l.get(_)??{};if(l.set(_,W),W.inFlight)return W.inFlight;if(R>0&&W.lastCompletedAt!==void 0&&Date.now()-W.lastCompletedAt<=R)return;let $=C_(_,E);W.inFlight=$;try{await $,W.lastCompletedAt=Date.now()}finally{if(W.inFlight===$)W.inFlight=void 0}}async function C_(_,E){let{readdir:R}=await import("node:fs/promises"),W=await n(),$=new Set,k=(await Promise.all(W.map(async(Q)=>{let Z=o(Q),K=B.join(j(),"projects",Q);try{return(await R(K)).flatMap((q)=>{if(!q.endsWith(".jsonl"))return[];let p=q.slice(0,-6);if(!C(p))return[];return[{filePath:B.join(K,q),projectPath:Z,sessionId:p}]})}catch{return[]}}))).flat();for(let Q of k)$.add(`${Q.projectPath}\x00${Q.sessionId}`);let M=_.prepare(`SELECT project_path, session_id, last_seq, file_size, mtime_ms
|
|
111
|
+
FROM projection_state`).all(),X=new Map(M.map((Q)=>[`${Q.project_path}\x00${Q.session_id}`,Q])),G=[],g=Math.min(128,k.length),T=0;await Promise.all(Array.from({length:g},async()=>{while(T<k.length){let Q=k[T++];if(!Q)continue;try{let Z=await d(Q.filePath),K=X.get(`${Q.projectPath}\x00${Q.sessionId}`);if(K&&K.file_size===Z.size&&K.mtime_ms===Math.floor(Z.mtimeMs))continue}catch{}G.push(Q)}}));let F=Math.min(32,G.length),A=0;await Promise.all(Array.from({length:F},async()=>{while(A<G.length){let Q=G[A++];if(!Q)continue;try{await B_(_,Q.sessionId,Q.projectPath,E,Q.filePath)}catch(Z){if(Z.code!=="ENOENT")Z_.warn(`[SessionService] Skipping invalid session transcript: ${Q.sessionId}`)}}}));for(let Q of M)if(!$.has(`${Q.project_path}\x00${Q.session_id}`))_.transaction(()=>v(_,Q.project_path,Q.session_id))}function n_(_,E,R){_.transaction(()=>v(_,R,E))}async function i_(_){let{rm:E}=await import("node:fs/promises");U_();let R=r();for(let H of["","-wal","-shm"])await E(`${R}${H}`,{force:!0}).catch(()=>{return});let W=await K_();if(!W)return null;return await A_(W,_),W.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function d_(_,E,R,W){let $=E.replace(/["*]/g," ").trim().split(/\s+/)[0];if(!$)return[];let H=`"${$}"*`,k=R?`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
112
|
+
WHERE parts_fts MATCH ? AND project_path = ?
|
|
113
|
+
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
114
|
+
WHERE parts_fts MATCH ?
|
|
115
|
+
ORDER BY timestamp DESC LIMIT ?`,M=_.prepare(k);return R?M.all(H,R,W):M.all(H,W)}
|
|
116
|
+
export{w as jc,q_ as kc,y_ as lc,z as mc,Y as nc,y as oc,$_ as pc,z_ as qc,k_ as rc,f_ as sc,r as tc,K_ as uc,U_ as vc,B_ as wc,A_ as xc,n_ as yc,i_ as zc,d_ as Ac};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{l as i}from"./chunk-
|
|
1
|
+
import{l as i}from"./chunk-edyxa2jw.js";import{rf as s}from"./chunk-kvd5nexw.js";import"./chunk-s1khjfye.js";import"./chunk-sprjrvn6.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{
|
|
1
|
+
import{Zc as W}from"./chunk-5yr2c8gz.js";import{le as X}from"./chunk-zs9mwd17.js";import{rf as V}from"./chunk-kvd5nexw.js";import{tf as Q,vf as U}from"./chunk-8htfb5zn.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
|
-
export{K as
|
|
4
|
+
export{K as Hc,P as Ic,L as Jc,k as Kc};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as y,g as A,h as C,i as D}from"./chunk-vp50e95n.js";import"./chunk-gn37wxwg.js";import"./chunk-edyxa2jw.js";import"./chunk-1g5h4zv6.js";import"./chunk-58yqrbey.js";import"./chunk-rtktz9v1.js";import"./chunk-tg1mf1tf.js";import"./chunk-89gswfb2.js";import"./chunk-1mh2285d.js";import"./chunk-4dnvydyv.js";import"./chunk-d9jz1edf.js";import"./chunk-p6nhdbdw.js";import"./chunk-ebffhjma.js";import{cd as q}from"./chunk-5yr2c8gz.js";import"./chunk-v508x7cg.js";import"./chunk-k99rbzqw.js";import"./chunk-46yg6dfr.js";import"./chunk-1hzj6s0f.js";import"./chunk-fnt1z0y8.js";import"./chunk-7jv8thn1.js";import"./chunk-kskg7crs.js";import"./chunk-5mtryjjc.js";import"./chunk-nt6xmzk0.js";import"./chunk-35d5gdgw.js";import"./chunk-zs9mwd17.js";import"./chunk-rth3jfdq.js";import"./chunk-58tpe6nx.js";import"./chunk-6axhk4r7.js";import"./chunk-9ka0bdry.js";import"./chunk-vc2c8wkx.js";import"./chunk-kvd5nexw.js";import"./chunk-8htfb5zn.js";import"./chunk-jt55ct49.js";import"./chunk-0q4jbbm5.js";import"./chunk-acf5v2fv.js";import"./chunk-r46ws0q8.js";import"./chunk-tnrrnzzv.js";import"./chunk-s1khjfye.js";import"./chunk-sprjrvn6.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Bc as a,Cc as b}from"./chunk-eqa706gn.js";import"./chunk-acf5v2fv.js";import"./chunk-sprjrvn6.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Pf as y}from"./chunk-tnrrnzzv.js";import{Yf as b}from"./chunk-s1khjfye.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 Of};
|
|
@@ -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-89gswfb2.js";import"./chunk-9ka0bdry.js";import"./chunk-vc2c8wkx.js";import{rf as Q}from"./chunk-kvd5nexw.js";import"./chunk-8htfb5zn.js";import"./chunk-s1khjfye.js";import"./chunk-sprjrvn6.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,2 @@
|
|
|
1
|
+
import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
|
|
2
|
+
export{G as me,F as ne,R as oe,v as pe};
|