blade-code 0.10.23 → 0.10.25
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-0qayfsc9.js +2 -0
- package/dist/{chunk-rxfmqnf7.js → chunk-0t0dsepx.js} +1 -1
- package/dist/{chunk-46nbyp0r.js → chunk-10yas08a.js} +360 -359
- package/dist/{chunk-2kpynwxa.js → chunk-15edqtyv.js} +1 -1
- package/dist/chunk-37bxrzq5.js +1 -0
- package/dist/chunk-38pr3rjg.js +1 -0
- package/dist/chunk-3mgfa96q.js +1 -0
- package/dist/chunk-4vwyhhjt.js +6 -0
- package/dist/chunk-565weg3f.js +44 -0
- package/dist/chunk-584eewzf.js +1 -0
- package/dist/chunk-58wxa5cj.js +2 -0
- package/dist/{chunk-kky5ydtw.js → chunk-5dr18jzd.js} +1 -1
- package/dist/{chunk-3d2f82yb.js → chunk-5k02rk0f.js} +2 -2
- package/dist/{chunk-33wheqb0.js → chunk-5tb28pxt.js} +1 -1
- package/dist/{chunk-tw0eh910.js → chunk-65pe5x3a.js} +1 -1
- package/dist/chunk-6pb6zs96.js +2 -0
- package/dist/{chunk-698qsvyb.js → chunk-6vhc5gdf.js} +2 -2
- package/dist/{chunk-ksm02qjh.js → chunk-763aam58.js} +1 -1
- package/dist/chunk-7cgbnp1m.js +1 -0
- package/dist/{chunk-8472vz3s.js → chunk-7tea6e9y.js} +2 -2
- package/dist/{chunk-c7zk9zj2.js → chunk-86g3xxx7.js} +1 -1
- package/dist/chunk-9e244cxx.js +1 -0
- package/dist/chunk-9gtc0kd2.js +2 -0
- package/dist/{chunk-f9tahtz6.js → chunk-9tp00s2z.js} +1 -1
- package/dist/{chunk-0affe05f.js → chunk-a0ga35qv.js} +43 -43
- package/dist/{chunk-djh79rde.js → chunk-awwe1rqb.js} +2 -2
- package/dist/chunk-axrwmx6e.js +1 -0
- package/dist/{chunk-70jrd752.js → chunk-b22x3h7k.js} +1 -1
- package/dist/{chunk-afk22y4r.js → chunk-bt6xqnbx.js} +1 -1
- package/dist/chunk-d6qktf17.js +1 -0
- package/dist/{chunk-kvd5nexw.js → chunk-dbb20rxh.js} +1 -1
- package/dist/{chunk-yqk501wp.js → chunk-eeet612j.js} +1 -1
- package/dist/chunk-eh8gdgfb.js +1 -0
- package/dist/chunk-f769xhg0.js +1 -0
- package/dist/{chunk-abtq0kjb.js → chunk-fg1t369y.js} +1 -1
- package/dist/chunk-fgy8pbk6.js +1 -0
- package/dist/{chunk-8efpk2z9.js → chunk-h61xsxmy.js} +2 -2
- package/dist/{chunk-6bywhrm9.js → chunk-jx1q1f88.js} +1 -1
- package/dist/{chunk-6g2tsx64.js → chunk-k89zf5h1.js} +1 -1
- package/dist/{chunk-vannpbp0.js → chunk-kjwc997q.js} +1 -1
- package/dist/chunk-kmf716yy.js +1 -0
- package/dist/chunk-m3ya6rtr.js +2 -0
- package/dist/chunk-mbxffehd.js +1 -0
- package/dist/{chunk-yann89nx.js → chunk-mmw7jbxg.js} +1 -1
- package/dist/chunk-nwg0bpex.js +116 -0
- package/dist/{chunk-b183w6w0.js → chunk-pserj9y9.js} +1 -1
- package/dist/{chunk-h0q03x9f.js → chunk-qdngw7h1.js} +1 -1
- package/dist/chunk-qnsj1pp3.js +3 -0
- package/dist/{chunk-nv59nazz.js → chunk-qvthjzt5.js} +2 -2
- package/dist/{chunk-c7va41dk.js → chunk-qy36y9xc.js} +2 -2
- package/dist/{chunk-9ka0bdry.js → chunk-r561wfcz.js} +1 -1
- package/dist/{chunk-2j3d4ykq.js → chunk-rb7aayp5.js} +6 -5
- package/dist/{chunk-hvp9kt76.js → chunk-rc9rfrws.js} +1 -1
- package/dist/chunk-rhcts0qe.js +2 -0
- package/dist/{chunk-n7hnp8yj.js → chunk-saneyjmy.js} +1 -1
- package/dist/chunk-v508x7cg.js +0 -0
- package/dist/chunk-vbsk6mjn.js +100 -0
- package/dist/{chunk-48w87cah.js → chunk-ve4wkta1.js} +1 -1
- package/dist/{chunk-czjbz0fp.js → chunk-vjrn667c.js} +2 -2
- package/dist/chunk-w0z7cn13.js +1 -0
- package/dist/chunk-wbvs2tv5.js +25 -0
- package/dist/chunk-whxmvh0n.js +6 -0
- package/dist/{chunk-hpgee5s3.js → chunk-wyq21fev.js} +2 -2
- package/dist/{chunk-9m80tr4t.js → chunk-xjq1htyt.js} +2 -2
- 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-1ejj4jvg.js +0 -1
- package/dist/chunk-2vs6ff2m.js +0 -1
- package/dist/chunk-73shq329.js +0 -1
- package/dist/chunk-9wdg2mqh.js +0 -1
- package/dist/chunk-afv2grka.js +0 -1
- package/dist/chunk-ak7v70sy.js +0 -100
- package/dist/chunk-cjyrr1c0.js +0 -6
- package/dist/chunk-cwyktf92.js +0 -1
- package/dist/chunk-ddj5f5cz.js +0 -1
- package/dist/chunk-gcsygn5a.js +0 -2
- package/dist/chunk-hjvdsrzb.js +0 -2
- package/dist/chunk-k7p4qwdr.js +0 -1
- package/dist/chunk-kaa0np37.js +0 -6
- package/dist/chunk-nbwvc4v4.js +0 -1
- package/dist/chunk-nfm5j63c.js +0 -44
- package/dist/chunk-p29w4zfc.js +0 -1
- package/dist/chunk-q8f1k8ns.js +0 -25
- package/dist/chunk-qjzt9pna.js +0 -1
- package/dist/chunk-rbwntemj.js +0 -1
- package/dist/chunk-s1310gqw.js +0 -1
- package/dist/chunk-sr2stcda.js +0 -2
- package/dist/chunk-tffagd03.js +0 -2
- package/dist/chunk-txqccp76.js +0 -1
- package/dist/chunk-vc2c8wkx.js +0 -2
- package/dist/chunk-vypake1a.js +0 -116
- package/dist/chunk-wax3nm7t.js +0 -1
- package/dist/chunk-x0g7y97q.js +0 -3
- package/dist/chunk-zj651nrm.js +0 -2
- package/dist/web/assets/index-CRCirUK7.js +0 -11
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Uf as j}from"./chunk-vjrn667c.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 of,I as pf,M as qf,V as rf,h as sf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Bc as a,Cc as b,Dc as c}from"./chunk-whxmvh0n.js";import"./chunk-m3ya6rtr.js";import"./chunk-wbvs2tv5.js";import"./chunk-v508x7cg.js";import"./chunk-xjqcc0nt.js";import"./chunk-18n15nn8.js";import"./chunk-565weg3f.js";import"./chunk-58wxa5cj.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-awwe1rqb.js";import"./chunk-7tea6e9y.js";import"./chunk-9tp00s2z.js";import"./chunk-9gtc0kd2.js";import"./chunk-6vhc5gdf.js";import"./chunk-qdngw7h1.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sb as jt,tb as Xt,ub as bn,vb as Tn,wb as fn}from"./chunk-4dnvydyv.js";import{he as Ut}from"./chunk-
|
|
1
|
+
import{sb as jt,tb as Xt,ub as bn,vb as Tn,wb as fn}from"./chunk-4dnvydyv.js";import{he as Ut}from"./chunk-wyq21fev.js";import{Ae as cn,Be as lt,Ce as un,De as Mn,Ee as wn,Ge as S,Je as yn,Ke as Ht,Le as Bt,Me as R,Ne as qt,me as xt,ne as tn,oe as en,pe as zt,qe as B,re as rn,se as gt,te as mt,ve as dn,we as En,xe as U,ye as on,ze as pn}from"./chunk-565weg3f.js";import{bf as X,df as x}from"./chunk-r561wfcz.js";import{nf as vt}from"./chunk-dbb20rxh.js";import{Ff as nn,Gf as sn}from"./chunk-9gtc0kd2.js";import{Wf as ss}from"./chunk-86g3xxx7.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -1,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-qnsj1pp3.js";import"./chunk-fg1t369y.js";import"./chunk-15edqtyv.js";import"./chunk-65pe5x3a.js";import"./chunk-saneyjmy.js";import"./chunk-10yas08a.js";import"./chunk-b22x3h7k.js";import"./chunk-5dr18jzd.js";import"./chunk-a0ga35qv.js";import"./chunk-4dnvydyv.js";import"./chunk-vbsk6mjn.js";import"./chunk-nwg0bpex.js";import"./chunk-xjq1htyt.js";import{ad as M}from"./chunk-wbvs2tv5.js";import"./chunk-v508x7cg.js";import"./chunk-xjqcc0nt.js";import"./chunk-0t0dsepx.js";import"./chunk-763aam58.js";import"./chunk-m27w377p.js";import"./chunk-mmw7jbxg.js";import"./chunk-rb7aayp5.js";import"./chunk-5xph8r1k.js";import"./chunk-5sw8j9ae.js";import"./chunk-18n15nn8.js";import"./chunk-wyq21fev.js";import"./chunk-6pb6zs96.js";import"./chunk-565weg3f.js";import"./chunk-58wxa5cj.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-awwe1rqb.js";import"./chunk-7tea6e9y.js";import"./chunk-9tp00s2z.js";import{Ff as J}from"./chunk-9gtc0kd2.js";import"./chunk-6vhc5gdf.js";import"./chunk-qdngw7h1.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";import b from"chalk";import H from"open";var $=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{rc as a,sc as b,tc as c,uc as d,vc as e,wc as f,xc as g,yc as h}from"./chunk-nwg0bpex.js";import"./chunk-awwe1rqb.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
|
|
@@ -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 +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-5dr18jzd.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as Q}from"./chunk-dbb20rxh.js";import"./chunk-awwe1rqb.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.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{$c as f,Wc as a,Xc as b,Yc as c,Zc as d,_c as e,ad as g,bd as h,cd as i,dd as j,ed as k,fd as l,gd as m,hd as n,id as o,jd as p,kd as q}from"./chunk-wbvs2tv5.js";import"./chunk-v508x7cg.js";import"./chunk-xjqcc0nt.js";import"./chunk-565weg3f.js";import"./chunk-58wxa5cj.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-awwe1rqb.js";import"./chunk-7tea6e9y.js";import"./chunk-9tp00s2z.js";import"./chunk-9gtc0kd2.js";import"./chunk-6vhc5gdf.js";import"./chunk-qdngw7h1.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{td as a,ud as b,vd as c}from"./chunk-763aam58.js";import"./chunk-m27w377p.js";import"./chunk-7tea6e9y.js";import"./chunk-9tp00s2z.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{xf as o}from"./chunk-7tea6e9y.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 @@
|
|
|
1
|
+
import{Ef as a,Ff as b,Gf as c,Hf as d,If as e,Jf as f}from"./chunk-9gtc0kd2.js";import"./chunk-86g3xxx7.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Xc as W}from"./chunk-wbvs2tv5.js";import{he as X}from"./chunk-wyq21fev.js";import{nf as V}from"./chunk-dbb20rxh.js";import{pf as Q,rf as U}from"./chunk-awwe1rqb.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 Fc,P as Gc,L as Hc,k as Ic};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as E}from"./chunk-
|
|
1
|
+
import{r as E}from"./chunk-65pe5x3a.js";import{s as YJ}from"./chunk-saneyjmy.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-10yas08a.js";import{ka as WJ}from"./chunk-b22x3h7k.js";import"./chunk-5dr18jzd.js";import{$a as p,Ma as c,ib as v}from"./chunk-a0ga35qv.js";import{tb as T}from"./chunk-4dnvydyv.js";import{Lb as f,Ub as M,Vb as u,Xb as R,_b as g,dc as N,gc as D}from"./chunk-vbsk6mjn.js";import"./chunk-nwg0bpex.js";import"./chunk-xjq1htyt.js";import"./chunk-wbvs2tv5.js";import"./chunk-v508x7cg.js";import{ld as ZJ}from"./chunk-xjqcc0nt.js";import"./chunk-0t0dsepx.js";import"./chunk-763aam58.js";import{wd as $J}from"./chunk-m27w377p.js";import"./chunk-mmw7jbxg.js";import"./chunk-rb7aayp5.js";import"./chunk-5xph8r1k.js";import{$d as zJ}from"./chunk-5sw8j9ae.js";import"./chunk-18n15nn8.js";import"./chunk-wyq21fev.js";import"./chunk-6pb6zs96.js";import"./chunk-565weg3f.js";import"./chunk-58wxa5cj.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{rf as b}from"./chunk-awwe1rqb.js";import"./chunk-7tea6e9y.js";import{Bf as QJ,yf as JJ}from"./chunk-9tp00s2z.js";import"./chunk-9gtc0kd2.js";import"./chunk-6vhc5gdf.js";import"./chunk-qdngw7h1.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.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=c.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 p(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,4 +1,4 @@
|
|
|
1
|
-
import{$ as F,Z as y}from"./chunk-
|
|
1
|
+
import{$ as F,Z as y}from"./chunk-10yas08a.js";import{Yb as Z,_b as x,gc as K}from"./chunk-vbsk6mjn.js";import{Td as $}from"./chunk-rb7aayp5.js";import{nf as V}from"./chunk-dbb20rxh.js";async function O(){await $(V())}async function j(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let Q of z)G.push(Q);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function I(b){if(!y(b))return{mode:"agent",content:b};let q=await F(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:Q}=z;return{mode:"agent",content:Q?`Please use the "${G}" skill to help me with: ${Q}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
|
|
2
2
|
|
|
3
3
|
${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as B,stat as D}from"node:fs/promises";import H from"node:path";function L(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return x(z).schema}async function A(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return L(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=H.resolve(b.outputSchema),z=await D(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>Z)throw Error(`Output schema exceeds ${Z} bytes: ${q}`);return L(await B(q,"utf8"),q)}function J(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function N(b){try{return await K.loadSessionModelContext(b,V())}catch(q){if(J(q))return null;throw q}}async function f(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),Q=await K.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...Q,messages:await K.loadSessionModelContext(Q.sessionId,G)}}let[q,z]=await Promise.all([K.loadSessionModelContext(b.resume),K.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await K.listSessions({cwd:V()}):await K.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),Q=await K.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...Q,messages:await K.loadSessionModelContext(Q.sessionId,G)}}return{sessionId:z,messages:await K.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await N(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await K.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{O as m,j as n,I as o,A as p,f as q};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-86g3xxx7.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Rd as a,Sd as b,Td as c,Ud as d,Vd as e}from"./chunk-rb7aayp5.js";import"./chunk-5xph8r1k.js";import"./chunk-5sw8j9ae.js";import"./chunk-18n15nn8.js";import"./chunk-wyq21fev.js";import"./chunk-6pb6zs96.js";import"./chunk-565weg3f.js";import"./chunk-58wxa5cj.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-awwe1rqb.js";import"./chunk-7tea6e9y.js";import"./chunk-9tp00s2z.js";import"./chunk-9gtc0kd2.js";import"./chunk-6vhc5gdf.js";import"./chunk-qdngw7h1.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ee as Q}from"./chunk-18n15nn8.js";import{bf as F,df as k,gf as G}from"./chunk-r561wfcz.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}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 H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.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:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
|
|
2
|
+
export{Z as Ec};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sd as a}from"./chunk-0t0dsepx.js";import"./chunk-awwe1rqb.js";import"./chunk-7tea6e9y.js";import"./chunk-9tp00s2z.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";export{a as createChatServiceAsync};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{_e as F}from"./chunk-565weg3f.js";import{wf as D,xf as E}from"./chunk-7tea6e9y.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
|
|
2
2
|
export{H as yd,Q as zd,T as Ad};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import{rf as i}from"./chunk-awwe1rqb.js";import{Mf as o,Of as C,Qf as L,Uf as j,Vf as n}from"./chunk-vjrn667c.js";import{Wf as I}from"./chunk-86g3xxx7.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 hc,q_ as ic,y_ as jc,z as kc,Y as lc,y as mc,$_ as nc,z_ as oc,k_ as pc,f_ as qc,r as rc,K_ as sc,U_ as tc,B_ as uc,A_ as vc,n_ as wc,i_ as xc,d_ as yc};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$a as f,Sa as a,Ta as b,Va as c,Za as d,_a as e,ab as g,bb as h,cb as i,db as j,eb as k,jb as l,kb as m,lb as n,mb as o,nb as p,ob as q,pb as r}from"./chunk-
|
|
1
|
+
import{$a as f,Sa as a,Ta as b,Va as c,Za as d,_a as e,ab as g,bb as h,cb as i,db as j,eb as k,jb as l,kb as m,lb as n,mb as o,nb as p,ob as q,pb as r}from"./chunk-a0ga35qv.js";import"./chunk-4dnvydyv.js";import"./chunk-vbsk6mjn.js";import"./chunk-nwg0bpex.js";import"./chunk-xjqcc0nt.js";import"./chunk-0t0dsepx.js";import"./chunk-m27w377p.js";import"./chunk-5xph8r1k.js";import"./chunk-5sw8j9ae.js";import"./chunk-wyq21fev.js";import"./chunk-6pb6zs96.js";import"./chunk-58wxa5cj.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-awwe1rqb.js";import"./chunk-7tea6e9y.js";import"./chunk-9tp00s2z.js";import"./chunk-9gtc0kd2.js";import"./chunk-qdngw7h1.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{promises as A}from"node:fs";import q from"node:path";var J=new Map;async function L(B){let b=B;while(!0){try{return await A.lstat(q.join(b,".git")),b}catch(H){if(H.code!=="ENOENT")return}let E=q.dirname(b);if(E===b)return;b=E}}async function M(B){let b=q.join(B,".git"),E=await A.lstat(b);if(E.isDirectory())return B;if(!E.isFile())return;let H=await A.readFile(b,"utf8"),F=/^gitdir:\s*(.+)\s*$/im.exec(H);if(!F)return;let z=await A.realpath(q.isAbsolute(F[1])?F[1]:q.resolve(B,F[1])),I=z;try{let x=(await A.readFile(q.join(z,"commondir"),"utf8")).trim();if(x)I=await A.realpath(q.resolve(z,x))}catch(x){if(x.code!=="ENOENT")throw x}return q.basename(I)===".git"?A.realpath(q.dirname(I)):void 0}async function S(B){if(!q.isAbsolute(B))throw Error("Workspace path must be absolute");let b=await A.realpath(B),E=J.get(b);if(E)return E;let H=b;try{let z=await L(b);if(z){let I=await M(z),x=q.relative(z,b);if(I&&(x===""||!x.startsWith(`..${q.sep}`)&&x!==".."&&!q.isAbsolute(x))){let K=q.resolve(I,x);H=await A.realpath(K).catch(()=>K)}}}catch{}let F={projectPath:b,trustRoot:H};if(J.size>=512){let z=J.keys().next().value;if(z)J.delete(z)}return J.set(b,F),F}
|
|
2
|
-
export{S as
|
|
2
|
+
export{S as Lf};
|