blade-code 0.10.21 → 0.10.23
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-72ztan96.js → chunk-0affe05f.js} +3 -3
- package/dist/{chunk-2c3zavy2.js → chunk-18n15nn8.js} +1 -1
- package/dist/chunk-1ejj4jvg.js +1 -0
- package/dist/{chunk-g7p165yz.js → chunk-2j3d4ykq.js} +2 -2
- package/dist/{chunk-wc1ee4tc.js → chunk-2kpynwxa.js} +1 -1
- package/dist/chunk-2vs6ff2m.js +1 -0
- package/dist/{chunk-e9xv0yyr.js → chunk-33wheqb0.js} +1 -1
- package/dist/{chunk-73jh6fz9.js → chunk-3d2f82yb.js} +2 -2
- package/dist/{chunk-ryhk5qmv.js → chunk-46nbyp0r.js} +459 -369
- package/dist/{chunk-bdn1tkyz.js → chunk-48w87cah.js} +1 -1
- package/dist/{chunk-095x2ykj.js → chunk-4dnvydyv.js} +1 -1
- package/dist/{chunk-6sb7cg95.js → chunk-5sw8j9ae.js} +1 -1
- package/dist/{chunk-r1jxbx1h.js → chunk-5xph8r1k.js} +1 -1
- package/dist/{chunk-jahf977w.js → chunk-698qsvyb.js} +2 -2
- package/dist/{chunk-kfqj54ax.js → chunk-6bywhrm9.js} +2 -2
- package/dist/{chunk-ns5015tn.js → chunk-6g2tsx64.js} +1 -1
- package/dist/{chunk-4tkn9bky.js → chunk-70jrd752.js} +1 -1
- package/dist/chunk-73shq329.js +1 -0
- package/dist/{chunk-w5m418w5.js → chunk-8472vz3s.js} +2 -2
- package/dist/{chunk-edphxwj1.js → chunk-8efpk2z9.js} +2 -2
- package/dist/{chunk-r561wfcz.js → chunk-9ka0bdry.js} +1 -1
- package/dist/{chunk-65kbckpt.js → chunk-9m80tr4t.js} +2 -2
- package/dist/chunk-9wdg2mqh.js +1 -0
- package/dist/{chunk-jhzk287k.js → chunk-abtq0kjb.js} +1 -1
- package/dist/chunk-afk22y4r.js +10 -0
- package/dist/{chunk-jdsr22s2.js → chunk-afv2grka.js} +1 -1
- package/dist/chunk-ak7v70sy.js +100 -0
- package/dist/chunk-b183w6w0.js +1 -0
- package/dist/{chunk-q4fjec99.js → chunk-c7va41dk.js} +2 -2
- package/dist/{chunk-fasxw5bb.js → chunk-c7zk9zj2.js} +1 -1
- package/dist/{chunk-033vmd74.js → chunk-cjyrr1c0.js} +2 -2
- package/dist/chunk-cwyktf92.js +1 -0
- package/dist/{chunk-kmeccj99.js → chunk-czjbz0fp.js} +2 -2
- package/dist/chunk-ddj5f5cz.js +1 -0
- package/dist/{chunk-77z6x1zb.js → chunk-djh79rde.js} +2 -2
- package/dist/{chunk-9wqr1sbq.js → chunk-f9tahtz6.js} +1 -1
- package/dist/{chunk-ah8hky46.js → chunk-gcsygn5a.js} +1 -1
- package/dist/{chunk-1y52h772.js → chunk-h0q03x9f.js} +1 -1
- package/dist/{chunk-k106g2p6.js → chunk-hjvdsrzb.js} +2 -2
- package/dist/{chunk-17jpjcvb.js → chunk-hpgee5s3.js} +3 -3
- package/dist/{chunk-bjf7ecgy.js → chunk-hvp9kt76.js} +1 -1
- package/dist/chunk-k7p4qwdr.js +1 -0
- package/dist/{chunk-2wp6h1p8.js → chunk-kaa0np37.js} +2 -2
- package/dist/chunk-kky5ydtw.js +2 -0
- package/dist/{chunk-afhdpen9.js → chunk-ksm02qjh.js} +2 -2
- package/dist/{chunk-dbb20rxh.js → chunk-kvd5nexw.js} +1 -1
- package/dist/{chunk-5chec8rs.js → chunk-m27w377p.js} +1 -1
- package/dist/{chunk-4v8nxcxp.js → chunk-n7hnp8yj.js} +1 -1
- package/dist/chunk-nbwvc4v4.js +1 -0
- package/dist/{chunk-mvc0tad6.js → chunk-nfm5j63c.js} +2 -2
- package/dist/{chunk-vzgy95tp.js → chunk-nv59nazz.js} +1 -1
- package/dist/chunk-p29w4zfc.js +1 -0
- package/dist/{chunk-whftbz4b.js → chunk-q8f1k8ns.js} +2 -2
- package/dist/chunk-qjzt9pna.js +1 -0
- package/dist/chunk-rbwntemj.js +1 -0
- package/dist/{chunk-sj2w24fe.js → chunk-rxfmqnf7.js} +2 -2
- package/dist/chunk-s1310gqw.js +1 -0
- package/dist/{chunk-jyeas4p9.js → chunk-sr2stcda.js} +1 -1
- package/dist/{chunk-wxqkpvqw.js → chunk-tffagd03.js} +2 -2
- package/dist/{chunk-a1ztrwjb.js → chunk-tw0eh910.js} +1 -1
- package/dist/chunk-txqccp76.js +1 -0
- package/dist/{chunk-y68sxcgk.js → chunk-vannpbp0.js} +1 -1
- package/dist/chunk-vc2c8wkx.js +2 -0
- package/dist/{chunk-vprpk6q1.js → chunk-vypake1a.js} +2 -2
- package/dist/{chunk-5hhfv1w1.js → chunk-wax3nm7t.js} +1 -1
- package/dist/{chunk-pmw9pn3v.js → chunk-x0g7y97q.js} +1 -1
- package/dist/{chunk-yz2bsntj.js → chunk-xjqcc0nt.js} +1 -1
- package/dist/{chunk-4ypy5bk8.js → chunk-yann89nx.js} +2 -2
- package/dist/{chunk-7mpa4esh.js → chunk-yqk501wp.js} +1 -1
- package/dist/{chunk-2ygqbd1z.js → chunk-zj651nrm.js} +1 -1
- package/dist/web/assets/ChatView-CCxjYDmJ.js +7 -0
- package/dist/web/assets/{CodeBlockHighlighter-DYuOTwXS.js → CodeBlockHighlighter-D9MqsrZP.js} +1 -1
- package/dist/web/assets/{FilePreview-CWOBOnzz.js → FilePreview-Cn5HOlPw.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-YiYvkN2w.js → MarkdownRenderer-ALTOCdfi.js} +3 -3
- package/dist/web/assets/{SettingsModal-BT-oFKGN.js → SettingsModal-Dk69F1bS.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-D5Gd6FN9.js → TaskSwitcher-DRZZocE1.js} +1 -1
- package/dist/web/assets/{TerminalPanel-C1hLHq_K.js → TerminalPanel-ByAqKZ47.js} +1 -1
- package/dist/web/assets/{index-DuYx6fkN.js → index-CRCirUK7.js} +5 -5
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-0et4h9p3.js +0 -1
- package/dist/chunk-0qayfsc9.js +0 -2
- package/dist/chunk-1p5822w7.js +0 -100
- package/dist/chunk-303cba4k.js +0 -1
- package/dist/chunk-51vnya3v.js +0 -1
- package/dist/chunk-6f3rp67k.js +0 -1
- package/dist/chunk-6v4dwkw7.js +0 -1
- package/dist/chunk-7p4qvftj.js +0 -1
- package/dist/chunk-9snsxf18.js +0 -1
- package/dist/chunk-c23c1vn6.js +0 -1
- package/dist/chunk-cb0rb9ss.js +0 -1
- package/dist/chunk-cysaxtfp.js +0 -10
- package/dist/chunk-efkqwhff.js +0 -1
- package/dist/chunk-ktbe458z.js +0 -2
- package/dist/chunk-r73fanrm.js +0 -1
- package/dist/chunk-smh39yy2.js +0 -1
- package/dist/chunk-w9tnd1q2.js +0 -1
- package/dist/chunk-zz9rax72.js +0 -1
- package/dist/web/assets/ChatView-YFotW0KS.js +0 -7
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import{gc as v,hc as fq,ic as x$,jc as Qq,kc as u,lc as G$,mc as Kq,nc as J$,oc as N$,pc as L$,rc as A0,uc as Z$,vc as Vq}from"./chunk-vypake1a.js";import{wd as Q0}from"./chunk-m27w377p.js";import{$d as K0}from"./chunk-5sw8j9ae.js";import{je as j$}from"./chunk-sr2stcda.js";import{ne as X0}from"./chunk-djh79rde.js";import{lf as Lq,mf as Zq}from"./chunk-vc2c8wkx.js";import{rf as O$}from"./chunk-kvd5nexw.js";import{Af as f0,xf as Z0}from"./chunk-f9tahtz6.js";import{Ef as n}from"./chunk-tffagd03.js";import{Lf as Nq,Mf as B0,Of as R,Pf as m,Rf as q$,Sf as c,Tf as N0}from"./chunk-czjbz0fp.js";import{readdir as t$,readFile as a,rm as D0,stat as Q1}from"node:fs/promises";import*as F from"node:path";import{nanoid as j}from"nanoid";import{createHash as Uq,randomUUID as zq}from"node:crypto";import*as I from"node:fs/promises";import*as T0 from"node:path";import{execFileSync as Yq}from"node:child_process";import{createHash as Hq}from"node:crypto";import{readFileSync as Xq}from"node:fs";var Oq=/^[a-f0-9]{64}$/;function T$($){if(!$||typeof $!=="object")return!1;let q=$;return(q.platform==="linux"||q.platform==="darwin"||q.platform==="win32")&&typeof q.fingerprint==="string"&&Oq.test(q.fingerprint)}var Wq={readFile:($)=>Xq($,"utf8"),execFile:($,q)=>Yq($,q,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})};function m0($,q){return{platform:$,fingerprint:Hq("sha256").update(`${$}\x00${q}`).digest("hex")}}function _q($,q){let x=q.readFile(`/proc/${$}/stat`).trim(),G=x.lastIndexOf(")");if(G<0)throw Error("Invalid /proc process stat");let J=x.slice(G+2).split(/\s+/)[19];if(!J||!/^\d+$/.test(J))throw Error("Missing process start ticks");return J}function I0($,q=process.platform,x=Wq){if(!Number.isInteger($)||$<=1)return;try{if(q==="linux")return m0(q,_q($,x));if(q==="darwin"){let G=x.execFile("ps",["-o","lstart=","-p",String($)]).trim();return G?m0(q,G):void 0}if(q==="win32"){let G=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,N=x.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",G]).trim();return N?m0(q,N):void 0}}catch{return}return}function Y$($,q){return I0($,q.platform)?.fingerprint===q.fingerprint}var W$=1;function Dq($,q){let x=Uq("sha256").update(q).digest("hex");return T0.join(B0($),".locks",`${x}.lock`)}function F0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function v0($){try{let q=JSON.parse(await I.readFile($,"utf8"));if(q.version!==W$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||q.processIdentity!==void 0&&!T$(q.processIdentity)||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function H$($){let q=await v0($);if(q)return q;return await new Promise((x)=>setTimeout(x,10)),v0($)}function Rq($){try{return process.kill($,0),!0}catch(q){return F0(q,"EPERM")}}async function X$($,q){let x;try{return x=await I.open($,"wx",384),await x.writeFile(`${JSON.stringify(q)}
|
|
2
|
+
`,"utf8"),!0}catch(G){if(F0(G,"EEXIST"))return!1;if(x)await I.unlink($).catch(()=>{return});throw G}finally{await x?.close().catch(()=>{return})}}class p extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class i{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=O$()){let x=Dq(q,$),G={version:W$,sessionId:$,ownerId:zq(),pid:process.pid,processIdentity:I0(process.pid),acquiredAt:new Date().toISOString()};if(await I.mkdir(T0.dirname(x),{recursive:!0,mode:448}),await X$(x,G))return new i(x,G);let N=await H$(x);if(N&&Rq(N.pid)&&(!N.processIdentity||Y$(N.pid,N.processIdentity)))throw new p(N.pid);if(await I.unlink(x).catch((J)=>{if(!F0(J,"ENOENT"))throw J}),await X$(x,G))return new i(x,G);throw new p((await H$(x))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await v0(this.filePath))?.ownerId!==this.record.ownerId)return;await I.unlink(this.filePath).catch((q)=>{if(!F0(q,"ENOENT"))throw q})}}var P1=1;function u0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Aq($){if(!u0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&u0($.image_url)&&typeof $.image_url.url==="string"}function Mq($){if(!u0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(Aq)}function _$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let q=JSON.stringify($);if(Buffer.byteLength(q)>16777216)return;let x=JSON.parse(q);if(!Array.isArray(x)||!x.every(Mq))return;return x}function h1($){let q=_$($);if(!q)throw Error("Compaction replacement context is invalid or exceeds limits");return q}function U$($){return _$($)}function wq($,q){for(let x of $){if(x.type!=="part_created"||x.data.partType!=="tool_result")continue;let G=x.data.payload;if(!G||typeof G!=="object"||Array.isArray(G))continue;let N=G;if(N.toolCallId===q||x.data.partId===q||x.data.messageId===q)return N}return}function z$($){let q=v($),x=new Map;for(let G of q){if(G.type==="interaction_requested"){x.set(G.data.requestId,{request:G.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(G.type==="interaction_responded"){let N=x.get(G.data.requestId);if(N)N.response=G.data;continue}if(G.type==="interaction_recovered"){let N=x.get(G.data.requestId);if(N)N.recovery=G.data}}for(let G of x.values()){let N=wq(q,G.request.toolCallId);G.hasToolResult=N!==void 0;let J=N?.metadata&&typeof N.metadata==="object"?N.metadata:void 0;G.hasRecoveryToolResult=J?.interactionRecovery===!0&&J.requestId===G.request.requestId}return[...x.values()]}function D$($){return z$($).reverse().find((q)=>!q.response&&!q.recovery)}function l1($){let q=new Map;for(let x of z$($))q.set(x.request.toolCallId,x);return[...q.values()].filter((x)=>x.response&&!x.recovery&&(!x.hasToolResult||x.hasRecoveryToolResult))}function R$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function Y0($){let q=new Map,x=[];for(let G of $){if(G.type==="review_started"){if(!q.has(G.data.reviewId))x.push(G.data.reviewId),q.set(G.data.reviewId,{start:G.data});continue}if(G.type!=="review_completed")continue;let N=q.get(G.data.reviewId);if(N&&N.completion===void 0)N.completion=G.data}return x.map((G)=>q.get(G)).filter((G)=>G!==void 0)}function i1($){return Y0($).reverse().find((q)=>q.completion===void 0)}function P0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function A$($,q){let x=["## Code Review","",`Target: ${$.target.label}`,`Status: ${P0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)x.push("","No actionable findings.");else{x.push("","### Findings");for(let[G,N]of q.findings.entries()){let J=N.codeLocation.lineStart===N.codeLocation.lineEnd?`${N.codeLocation.lineStart}`:`${N.codeLocation.lineStart}-${N.codeLocation.lineEnd}`;x.push("",`${G+1}. ${N.title}`,` ${N.codeLocation.path}:L${J} · confidence ${N.confidenceScore.toFixed(2)}`,` ${N.body}`)}}if(q.error)x.push("",`Error: ${q.error}`);return x.join(`
|
|
3
|
+
`)}function M$($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((x)=>({title:x.title,body:x.body,priority:x.priority,confidenceScore:x.confidenceScore,codeLocation:{...x.codeLocation}})),...q.error?{error:q.error}:{}}}var h0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function Eq($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function bq($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";return"runtime"}function gq($){return{code:$,...h0[$]}}function c0($){return gq(bq(Eq($)))}function n0($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in h0))return!1;let x=h0[q.code];return q.message===x.message&&q.retryable===x.retryable}import{promises as x0,realpathSync as yq}from"node:fs";import H0 from"node:path";import*as r from"fs/promises";import*as O from"path";var w$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class l0{static normalize($,q){let x=O.isAbsolute($)?$:O.resolve(q,$),G=O.normalize(x),N=O.normalize(q);if(!this.isWithinWorkspace(G,N))throw new d(`Path outside workspace: ${$} (resolved to ${G}, workspace: ${N})`,"PATH_OUTSIDE_WORKSPACE");return G}static checkRestricted($){let q=$.split(O.sep);for(let x of w$)if(q.includes(x))throw new d(`Access denied: "${x}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let x=this.normalize($,q);this.checkRestricted(x);try{await r.access(x)}catch(G){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return x}static async resolveSymlink($,q){try{let x=await r.realpath($),G=await r.realpath(q);if(!this.isWithinWorkspace(x,G))throw new d(`Symlink points outside workspace: ${$} -> ${x}`,"SYMLINK_OUTSIDE_WORKSPACE");return x}catch(x){if(x instanceof d)throw x;return $}}static getRelativePath($,q){return O.relative(q,$)}static isWithinWorkspace($,q){let x=O.resolve($),G=O.resolve(q),N=O.relative(G,x);return N===""||N!==".."&&!N.startsWith(`..${O.sep}`)&&!O.isAbsolute(N)}static async isWithinWorkspaceResolved($,q){let x=O.resolve(q),G=O.isAbsolute($)?O.resolve($):O.resolve(x,$);if(!this.isWithinWorkspace(G,x))return!1;let N;try{N=await r.realpath(x)}catch{return!1}let J=G;while(!0){try{let Z=await r.realpath(J);return this.isWithinWorkspace(Z,N)}catch(Z){let K=Z.code;if(K!=="ENOENT"&&K!=="ENOTDIR")return!1}let L=O.dirname(J);if(L===J)return!1;J=L}}static isRestricted($){let q=$.split(O.sep);return w$.some((x)=>q.includes(x))}}var G0=X0("Tool");class h{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}async recordFileRead($,q){try{let x=await x0.stat($),G={filePath:H0.resolve($),accessTime:Date.now(),mtime:x.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(G),await this.recordAliases($,G.filePath),G0.debug(`记录文件读取: ${$}`)}catch(x){G0.warn(`记录文件读取失败: ${$}`,x)}}async recordFileEdit($,q,x="edit"){try{let G=await x0.stat($),N={filePath:H0.resolve($),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:q,lastOperation:x};this.setRecord(N),await this.recordAliases($,N.filePath),G0.debug(`记录文件${x==="edit"?"编辑":"写入"}: ${$}`)}catch(G){G0.warn(`记录文件${x==="edit"?"编辑":"写入"}失败: ${$}`,G)}}hasFileBeenRead($,q){let x=this.accessedFiles.get(this.resolveTrackedPath($));if(!x)return!1;return q?x.has(q):x.size>0}async checkFileModification($,q){let x=this.getFileRecord($,q);if(!x)return{modified:!1,message:"文件未被跟踪"};try{let G=await x0.stat($);if(Math.abs(G.mtimeMs-x.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(x.accessTime).toISOString()}, 当前修改时间: ${G.mtime.toISOString()})`};return{modified:!1}}catch(G){let N=G;if(N.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${N.message}`}}}async checkExternalModification($,q){let x=this.getFileRecord($,q);if(!x)return{isExternal:!1,message:"文件未被跟踪"};try{let G=await x0.stat($);if(G.mtimeMs-x.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(x.accessTime).toISOString()} (${x.lastOperation}) 之后被外部程序修改(当前修改时间: ${G.mtime.toISOString()})`};return{isExternal:!1}}catch(G){let N=G;if(N.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return G0.warn(`检查文件外部修改失败: ${$}`,G),{isExternal:!1,message:`无法检查文件状态: ${N.message}`}}}getFileRecord($,q){let x=this.accessedFiles.get(this.resolveTrackedPath($));if(!x)return;if(q)return x.get(q);return[...x.values()].sort((G,N)=>N.accessTime-G.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let x=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(x),this.removeAliases(x);return}let G=this.accessedFiles.get(x);if(G?.delete(q),G?.size===0)this.accessedFiles.delete(x),this.removeAliases(x)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[x,G]of this.accessedFiles.entries()){if(q&&!l0.isWithinWorkspace(x,q))continue;if(G.delete($),G.size===0)this.accessedFiles.delete(x),this.removeAliases(x)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){h.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(H0.resolve($),q);let x=await x0.realpath($).catch(()=>{return});if(x)this.pathAliases.set(x,q)}resolveTrackedPath($){let q=H0.resolve($);if(this.accessedFiles.has(q))return q;let x=this.pathAliases.get(q);if(x)return x;try{let G=yq.native(q);return this.pathAliases.get(G)??G}catch{return q}}removeAliases($){for(let[q,x]of this.pathAliases)if(x===$)this.pathAliases.delete(q)}}import*as J0 from"node:crypto";import{promises as T}from"node:fs";import*as H from"node:path";import p0 from"write-file-atomic";var E$="missing";class O0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(R($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!H.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?H.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=N0();this.snapshotDir=H.join(q,"file-history",this.sessionId),this.manifestPath=H.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await T.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=N0(),q=await T.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),x=J0.createHash("sha256").update(q).digest("hex").slice(0,24),G=H.join($,"file-history",this.sessionId),N=H.join($,"file-history","workspaces",x,this.sessionId),J=H.join(N,"manifest.json");try{await T.access(J)}catch{await this.migrateLegacySnapshotDir(G,N,q)}this.snapshotDir=N,this.manifestPath=J}async migrateLegacySnapshotDir($,q,x){let G;try{G=JSON.parse(await T.readFile(H.join($,"manifest.json"),"utf8"))}catch{return}if(G.schemaVersion!==1||!Array.isArray(G.snapshots)||!G.snapshots.every((N)=>this.isWithinWorkspace(N.filePath,x)))return;await T.mkdir(H.dirname(q),{recursive:!0,mode:493});try{await T.rename($,q)}catch(N){let J=N.code;if(J!=="ENOENT"&&J!=="EEXIST"&&J!=="ENOTEMPTY")throw N}}isWithinWorkspace($,q){if(!H.isAbsolute($))return!1;let x=H.relative(q,H.resolve($));return x===""||x!==".."&&!x.startsWith(`..${H.sep}`)&&!H.isAbsolute(x)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let x=await this.resolveFileIdentity($),G=!0;try{await T.access(x)}catch{G=!1}let N=this.trackedFileBackups.get(x),J=N?N.version+1:1,L=this.generateFileHash(x,J),Z=this.getSnapshotPath(L,J),K=new Date;if(G){let Q=await T.readFile(x);await T.writeFile(Z,Q)}let f={backupFileName:L,version:J,backupTime:K};return this.trackedFileBackups.set(x,f),this.snapshots.push({messageId:q,backupFileName:L,timestamp:K,filePath:x,version:J,existedBefore:G}),await this.cleanupOldSnapshots(x),await this.persistManifest(),f}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let x=await this.resolveFileIdentity($),G=this.snapshots.find((N)=>N.filePath===x&&N.backupFileName===q.backupFileName&&N.version===q.version);if(!G)throw Error(`未找到待完成的快照: ${x}`);G.postEditHash=await this.hashFile(x),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let x=await this.resolveFileIdentity($),G=this.snapshots.find((N)=>N.filePath===x&&N.backupFileName===q.backupFileName&&N.version===q.version);if(!G)return;this.removeSnapshot(G),await T.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),x=this.snapshots.slice().reverse().find((J)=>J.filePath===q&&J.postEditHash!==void 0);if(!x?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==x.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let N=this.getSnapshotPath(x.backupFileName,x.version);if(x.existedBefore){let J=await T.readFile(N);await T.mkdir(H.dirname(q),{recursive:!0}),await T.writeFile(q,J)}else await T.rm(q,{force:!0});return this.removeSnapshot(x),await T.rm(N,{force:!0}),await this.persistManifest(),x}async restoreSnapshot($,q){let x=await this.resolveFileIdentity($),G=this.snapshots.slice().reverse().find((J)=>J.messageId===q&&J.filePath===x);if(!G)throw Error(`未找到快照: messageId=${q}, filePath=${x}`);let N=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let J=await T.readFile(N);await T.mkdir(H.dirname(x),{recursive:!0}),await T.writeFile(x,J)}else await T.rm(x,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((x)=>x.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((x)=>x.filePath),snapshotCount:q.reduce((x,G)=>x+G.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let x=new Map;for(let N of q){let J,L=!0;try{J=await T.readFile(N.filePath)}catch(K){if(K.code!=="ENOENT")throw K;L=!1}if((J?J0.createHash("sha256").update(J).digest("hex"):E$)!==N.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${N.filePath}`);if(x.set(N.filePath,{existed:L,content:J}),N.target.existedBefore)await T.access(this.getSnapshotPath(N.target.backupFileName,N.target.version))}let G=[...this.snapshots];try{for(let J of q)if(J.target.existedBefore){let L=await T.readFile(this.getSnapshotPath(J.target.backupFileName,J.target.version));await T.mkdir(H.dirname(J.filePath),{recursive:!0}),await p0(J.filePath,L)}else await T.rm(J.filePath,{force:!0});let N=new Set(q.flatMap((J)=>J.selected));this.snapshots=this.snapshots.filter((J)=>!N.has(J)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...N].map((J)=>T.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return})))}catch(N){this.snapshots=G,this.rebuildTrackedFileBackups();let J=[];for(let[L,Z]of x)try{if(Z.existed&&Z.content)await p0(L,Z.content);else await T.rm(L,{force:!0})}catch(K){J.push(K)}if(J.length>0)throw AggregateError([N,...J],"快照回退失败且无法完整恢复回退前状态");throw N}return{files:q.map((N)=>N.filePath),snapshotCount:q.reduce((N,J)=>N+J.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),x=new Set(q.flatMap((N)=>N.selected));if(x.size===0)return{files:[],snapshotCount:0};let G=[...this.snapshots];this.snapshots=this.snapshots.filter((N)=>!x.has(N)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(N){throw this.snapshots=G,this.rebuildTrackedFileBackups(),N}return await Promise.all([...x].map((N)=>T.rm(this.getSnapshotPath(N.backupFileName,N.version),{force:!0}).catch(()=>{return}))),{files:q.map((N)=>N.filePath),snapshotCount:x.size}}buildRewindPlan($){let q=new Set($),x=this.snapshots.filter((J)=>J.postEditHash!==void 0),G=x.filter((J)=>q.has(J.messageId));return[...new Set(G.map((J)=>J.filePath))].sort().map((J)=>{let L=x.filter((Q)=>Q.filePath===J),Z=L.filter((Q)=>q.has(Q.messageId)),K=L.indexOf(Z[0]),f=L.slice(K);if(f.length!==Z.length||f.some((Q)=>!q.has(Q.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${J}`);return{filePath:J,selected:Z,target:Z[0],latest:Z.at(-1)}})}async loadManifest(){try{let $=await T.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(x)=>({...x,filePath:await this.resolveFileIdentity(x.filePath),timestamp:new Date(x.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await T.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await p0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let x=this.snapshots.filter((G)=>G.filePath===$).slice(0,-this.maxSnapshots);for(let G of x)await T.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),this.removeSnapshot(G)}async cleanup($=0){let q=this.snapshots.slice().sort((G,N)=>N.timestamp.getTime()-G.timestamp.getTime()),x=new Set(q.slice(0,$));for(let G of this.snapshots)if(!x.has(G))await T.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return H.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=H.resolve($),x=[],G=q;while(!0){try{let J=await T.realpath(G);return H.join(J,...x.reverse())}catch(J){let L=J.code;if(L!=="ENOENT"&&L!=="ENOTDIR")throw J}let N=H.dirname(G);if(N===G)return q;x.push(H.basename(G)),G=N}}async hashFile($){try{let q=await T.readFile($);return J0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return E$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let x=J0.createHash("md5");return x.update(`${$}:${q}`),x.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}import{createHash as iq}from"node:crypto";import v$ from"node:path";import{StringDecoder as Iq}from"node:string_decoder";function Sq($,q){let x=q;while(x<$.length&&($[x]&192)===128)x+=1;return x}class i0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?Buffer.from($):Buffer.from($);if(q.length===0)return;this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),omittedBytes:this.omittedBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}trimToLimit(){while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let q=this.retainedBytes-this.maxBytes;if($.length<=q){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length;continue}let x=Sq($,q);this.chunks[0]=$.subarray(x),this.retainedBytes-=x,this.omittedBytes+=x}}}var W0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},o={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},b$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},jq={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},mq=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:W0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:W0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:o,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:b$},{pattern:/^git\s+(status|branch|remote)/i,config:o},{pattern:/^git\s+(log|diff|show)/i,config:b$},{pattern:/^(ls|dir|tree)\s+/i,config:o,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:o,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:o,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:W0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:W0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:o,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:o,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class d0{static getConfigForCommand($){for(let{pattern:q,config:x,summaryTemplate:G}of mq)if(q.test($))return{config:x,summaryTemplate:G};return{config:jq}}static truncate($,q){let{config:x,summaryTemplate:G}=this.getConfigForCommand(q);return this.truncateWithConfig($,x,G)}static truncateWithConfig($,q,x){let G=$.length,N=$.split(`
|
|
4
|
+
`),J=N.length;if(J<=q.maxLines&&G<=q.maxChars)return{content:$,truncated:!1,originalLines:J,originalChars:G};let L=N.slice(0,q.keepHead),Z=N.slice(-q.keepTail),K=J-q.keepHead-q.keepTail,f=L.join(`
|
|
5
|
+
`);if(f+=`
|
|
6
|
+
|
|
7
|
+
... (${K} lines truncated, showing first ${q.keepHead} and last ${q.keepTail} of ${J} total) ...
|
|
8
|
+
|
|
9
|
+
`,f+=Z.join(`
|
|
10
|
+
`),f.length>q.maxChars){let V=Math.floor(q.maxChars/2)-50,C=f.slice(0,V),B=f.slice(-V);f=`${C}
|
|
11
|
+
|
|
12
|
+
... (content truncated to ${q.maxChars} chars) ...
|
|
13
|
+
|
|
14
|
+
${B}`}let Q=q.summarize&&x?x(J,G):void 0;if(Q)f+=`
|
|
15
|
+
|
|
16
|
+
[Summary: ${Q}]`;return{content:f,truncated:!0,originalLines:J,originalChars:G,summary:Q}}static truncateForLLM($,q,x){let G=this.truncate($,x),N=this.truncate(q,x),J;if(G.truncated||N.truncated){let L=[];if(G.truncated)L.push(`stdout: ${G.originalLines} lines -> ${G.content.split(`
|
|
17
|
+
`).length} lines`);if(N.truncated)L.push(`stderr: ${N.originalLines} lines -> ${N.content.split(`
|
|
18
|
+
`).length} lines`);J=`Output truncated: ${L.join(", ")}`}return{stdout:G.content,stderr:N.content,truncationInfo:J}}static shouldTruncate($,q){let{config:x}=this.getConfigForCommand(q);return $.split(`
|
|
19
|
+
`).length>x.maxLines||$.length>x.maxChars}static getStats($){return{lines:$.split(`
|
|
20
|
+
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var g$=32768,vq=1048576,uq=65536,Pq=3600000,k$=4096,hq=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;class r0{stream;executionId;onEvent;output=new i0(vq/2);decoder=new Iq("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor($,q,x){this.stream=$;this.executionId=q;this.onEvent=x}append($){let q=Buffer.isBuffer($)?$:Buffer.from($);if(q.length===0)return;if(this.totalBytes+=q.length,this.sniffBytes<k$){let G=q.subarray(0,Math.min(q.length,k$-this.sniffBytes));this.sniffChunks.push(G),this.sniffBytes+=G.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let x=y$(this.decoder.write(q));this.output.append(x),this.emit(x)}finish(){if(this.binary)return;let $=y$(this.decoder.end());this.output.append($),this.emit($)}snapshot(){let $=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:$.content,omittedBytes:$.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit($){if(!$||!this.onEvent||this.streamTruncated)return;let q=uq-this.streamedBytes;if(q<=0){this.streamTruncated=!0;return}let x=cq($,q);if(this.streamedBytes+=Buffer.byteLength(x),x.length<$.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:x,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function y$($){return $.replace(hq,"")}function cq($,q){let x=Buffer.from($);if(x.length<=q)return $;let G=q;while(G>0&&(x[G]&192)===128)G-=1;return x.subarray(0,G).toString("utf8")}function S$($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function nq($){let q=$.trim();if(!q)throw Error("User shell command cannot be empty");if(q.length>g$)throw Error(`User shell command exceeds ${g$} characters`);if(q.includes("\x00"))throw Error("User shell command contains a null byte");return q}function lq(){return{execute($,q){return new Promise((x)=>{let G=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",N=process.platform==="win32"?["/d","/s","/c",$]:["-l","-c",$],{child:J,processTree:L}=j$(G,N,{cwd:q.cwd,env:q.env,stdio:["ignore","pipe","pipe"]}),Z="",K="",f=!1,Q=!1,V=!1,C,B=()=>{return C??=L.terminate(),C},E=setTimeout(()=>{f=!0,B()},q.timeoutMs),M=()=>{Q=!0,B()};if(q.signal.addEventListener("abort",M,{once:!0}),q.signal.aborted)M();J.stdout?.on("data",(_)=>{q.onOutput?.("stdout",_)}),J.stderr?.on("data",(_)=>{q.onOutput?.("stderr",_)});let b=async(_)=>{if(V)return;if(V=!0,clearTimeout(E),q.signal.removeEventListener("abort",M),f||Q)await B();x({..._,stdout:"",stderr:"",timedOut:f,aborted:Q})};J.once("error",(_)=>{b({exitCode:null,error:_.message})}),J.once("close",(_)=>{b({exitCode:_})})})}}}async function V2($,q){let x=nq($),G=q.timeoutMs??Pq,N=new r0("stdout",q.executionId,q.onEvent),J=new r0("stderr",q.executionId,q.onEvent),L=Date.now();await q.onEvent?.({type:"started",executionId:q.executionId,command:x});let Z,K=!1,f=!1;try{Z=await(q.executor??lq()).execute(x,{cwd:q.cwd,env:q.env,timeoutMs:G,signal:q.signal,onOutput:(M,b)=>{if(M==="stdout")K=!0;else f=!0;(M==="stdout"?N:J).append(b)}})}catch(M){Z={exitCode:null,stdout:"",stderr:"",error:M instanceof Error?M.message:String(M)}}if(!K)N.append(Z.stdout);if(!f)J.append(Z.stderr);N.finish(),J.finish(),await Promise.all([N.flushEvents(),J.flushEvents()]);let Q=N.snapshot(),V=J.snapshot(),C=d0.truncateForLLM(Q.content.trim(),V.content.trim(),x),B=Z.aborted||q.signal.aborted?"aborted":Z.timedOut?"timed_out":Z.error?"spawn_error":Z.exitCode===0?"completed":"failed",E={version:1,command:x,status:B,exitCode:Z.exitCode,durationMs:Math.max(0,Date.now()-L),stdout:C.stdout,stderr:Z.error?[C.stderr,Z.error].filter(Boolean).join(`
|
|
21
|
+
`):C.stderr,stdoutOmittedBytes:Q.omittedBytes,stderrOmittedBytes:V.omittedBytes,binaryOutput:Q.binary||V.binary,truncated:Boolean(C.truncationInfo)||Q.omittedBytes>0||V.omittedBytes>0};return await q.onEvent?.({type:"completed",executionId:q.executionId,record:E}),E}function C2($){let q=[$.stdout?`stdout:
|
|
22
|
+
${$.stdout}`:"",$.stderr?`stderr:
|
|
23
|
+
${$.stderr}`:""].filter(Boolean).join(`
|
|
24
|
+
`);return["<user_shell_command>",`<command>${S$($.command)}</command>`,"<result>",`Status: ${$.status}`,`Exit code: ${$.exitCode??"null"}`,`Duration: ${($.durationMs/1000).toFixed(3)} seconds`,`Output:
|
|
25
|
+
${S$(q||"(no output)")}`,"</result>","</user_shell_command>"].join(`
|
|
26
|
+
`)}function m$($){let q=[$.stdout,$.stderr?`stderr:
|
|
27
|
+
${$.stderr}`:""].filter(Boolean).join(`
|
|
28
|
+
`);return[`! ${$.command}`,q||"(no output)"].join(`
|
|
29
|
+
`)}function pq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(q.version!==1||typeof q.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String(q.status))||q.exitCode!==null&&typeof q.exitCode!=="number"||typeof q.durationMs!=="number"||typeof q.stdout!=="string"||typeof q.stderr!=="string"||typeof q.stdoutOmittedBytes!=="number"||typeof q.stderrOmittedBytes!=="number"||typeof q.binaryOutput!=="boolean"||typeof q.truncated!=="boolean")return;return q}function _0($){if(!$||typeof $!=="object"||Array.isArray($))return;return pq($.userShellCommand)}var U0=16777216,I$=65536,X2=1048576,dq=8,z0=200,rq=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,oq=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,tq=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,aq=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),sq=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function k($,q){return $.count+=1,q}function eq($){return rq.test($.replace(/[A-Z]/g,(q)=>`_${q.toLowerCase()}`))}function $1($){return[...$].filter((q)=>{if(q===`
|
|
30
|
+
`||q==="\r"||q==="\t")return!0;let x=q.codePointAt(0)??0;if(x<32||x===127)return!1;if(x>=57344&&x<=63743)return!1;if(x>=983040&&x<=1048573)return!1;if(x>=1048576&&x<=1114109)return!1;if(x>=917504&&x<=917631)return!1;return!/[\p{Cf}\p{Cn}]/u.test(q)}).join("")}function g($,q){let x=$.normalize("NFKC"),G=x.replace(aq,"");if(G!==x)q.count+=1;x=G,x=x.replace(sq,()=>k(q,"[redacted-private-key]")),x=x.replace(/\bBearer\s+[^\s"'`]+/gi,()=>k(q,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>k(q,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>k(q,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(J,L,Z)=>`${L}${Z}${k(q,"[redacted]")}`);let N=$1(x);if(N!==x)q.count+=1;return N.replace(/\r\n?/g,`
|
|
31
|
+
`)}function u$($,q,x){if(/^data:[^;,]+;base64,/i.test($))return k(x,"[binary omitted]");let G=g($,x),N=v$.resolve(q);for(let J of[N,N.startsWith("/private/")?N.slice(8):`/private${N}`])G=G.replaceAll(J,".");return G=G.replace(oq,(J)=>J.startsWith("./")?J:k(x,"[host-path]")),G=G.replace(tq,()=>k(x,"[host-path]")),G=G.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(J)=>{try{let L=new URL(J);if(L.username||L.password||L.search||L.hash)x.count+=1;return L.username="",L.password="",L.search="",L.hash="",L.toString()}catch{return k(x,"[redacted-url]")}}),G}function a0($,q,x,G=0,N){if(N&&eq(N))return k(x,"[redacted]");if(G>=dq)return k(x,"[depth limit]");if(typeof $==="string")return u$($,q,x);if($===null||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return $;if(Array.isArray($)){let J=$.slice(0,z0).map((L)=>a0(L,q,x,G+1));if($.length>J.length)J.push(k(x,`[${$.length-J.length} items omitted]`));return J}if($&&typeof $==="object"){let J={},L=Object.entries($);for(let[Z,K]of L.slice(0,z0))J[g(Z,x)]=a0(K,q,x,G+1,Z);if(L.length>z0)J["[entries omitted]"]=L.length-z0;return J}return String($)}function q1($,q){let x=Buffer.from($,"utf8");if(x.length<=q)return $;let G=x.subarray(0,q).toString("utf8");while(Buffer.byteLength(G,"utf8")>q)G=G.slice(0,-1);return G}function x1($,q,x){let G=JSON.stringify(a0($,q,x),null,2);if(Buffer.byteLength(G,"utf8")<=I$)return G;x.count+=1;let N=`
|
|
32
|
+
... [activity truncated]`;return q1(G,I$-Buffer.byteLength(N))+N}function s0($,q=""){let x=Math.max(2,...[...$.matchAll(/`+/g)].map((N)=>N[0].length)),G="`".repeat(x+1);return`${G}${q}
|
|
33
|
+
${$}
|
|
34
|
+
${G}`}function o0($){return $.replace(/\s+/g," ").trim()}function G1($){let q=new Map,x=new Map,G=new Map,N=0;for(let J of v($)){if(J.type==="message_created"){let Q=x.get(J.data.messageId);if(Q)Q.role=J.data.role,Q.metadata=J.data.metadata,q.set(J.data.messageId,Q),x.delete(J.data.messageId);else if(!q.has(J.data.messageId))q.set(J.data.messageId,{order:N++,role:J.data.role,parts:[],metadata:J.data.metadata});continue}if(J.type!=="part_created"&&J.type!=="part_updated")continue;let L=q.get(J.data.messageId)??x.get(J.data.messageId);if(!L)L={order:N++,role:"activity",parts:[]},x.set(J.data.messageId,L);let Z=`${J.data.messageId}\x00${J.data.partType}\x00${J.data.partId}`,K=G.get(Z);if(K){K.event=J;continue}let f={order:N++,event:J};G.set(Z,f),L.parts.push(f)}return[...q.values(),...x.values()].sort((J,L)=>J.order-L.order)}function t0($,q,x,G){return`## Activity: ${$}
|
|
35
|
+
|
|
36
|
+
${s0(x1(q,x.projectPath,G),"json")}`}function P$($,q,x={}){let G={count:0},N=x.includeReasoning===!0,J=[],L=0,Z=0,K=0;for(let b of G1($)){let _=_0(b.metadata);if(_){let D=g(_.command,G),z=g([_.stdout,_.stderr?`stderr:
|
|
37
|
+
${_.stderr}`:""].filter(Boolean).join(`
|
|
38
|
+
`)||"(no output)",G);J.push(`## User shell command
|
|
39
|
+
|
|
40
|
+
${s0(`$ ${D}
|
|
41
|
+
${z}`,"console")}`),L+=1;continue}let s=[],e=[],y=[],S=Number.POSITIVE_INFINITY;for(let D of b.parts.sort((z,A)=>z.order-A.order)){let{partType:z,payload:A}=D.event.data;if(z==="text"){let Y=A.text;if(typeof Y==="string"&&Y.trim())s.push(g(Y,G)),S=Math.min(S,D.order)}else if(z==="image"){let Y=A.mimeType;e.push(typeof Y==="string"?`[Image: ${g(Y,G)}]`:"[Image]"),S=Math.min(S,D.order)}else if(z==="reasoning"&&N){let Y=A.text;if(typeof Y==="string"&&Y.trim())y.push({order:D.order,markdown:`## Reasoning
|
|
42
|
+
|
|
43
|
+
${g(Y,G).trim()}`}),K+=1}else if(z==="tool_call"){let Y=A,w=typeof Y.toolName==="string"?g(Y.toolName,G):"unknown";y.push({order:D.order,markdown:t0(`${w} call`,Y.input??{},q,G)}),Z+=1}else if(z==="tool_result"){let Y=A,w=typeof Y.toolName==="string"?g(Y.toolName,G):"unknown";y.push({order:D.order,markdown:t0(`${w} result`,typeof Y.error==="string"?{error:Y.error}:{output:Y.output??null},q,G)}),Z+=1}else if(z==="summary"){let Y=A.text;if(typeof Y==="string"&&Y.trim())y.push({order:D.order,markdown:`## Summary
|
|
44
|
+
|
|
45
|
+
${g(Y,G).trim()}`})}else if(z==="subtask_ref")y.push({order:D.order,markdown:t0("Subagent",A,q,G)}),Z+=1;else if(z==="diff"||z==="patch"){let Y=typeof A==="string"?A:JSON.stringify(A,null,2);y.push({order:D.order,markdown:`## File changes
|
|
46
|
+
|
|
47
|
+
${s0(u$(Y,q.projectPath,G),"diff")}`}),Z+=1}}if((b.role==="user"||b.role==="assistant")&&(s.length>0||e.length>0))y.push({order:S,markdown:`## ${b.role==="user"?"User":"Assistant"}
|
|
48
|
+
|
|
49
|
+
${[...s,...e].join(`
|
|
50
|
+
|
|
51
|
+
`).trim()}`}),L+=1;J.push(...y.sort((D,z)=>D.order-z.order).map((D)=>D.markdown))}if(J.length===0)throw Error("No conversation content to export");let f=`${J.join(`
|
|
52
|
+
|
|
53
|
+
`)}
|
|
54
|
+
`,Q=Buffer.byteLength(f,"utf8");if(Q>U0)throw Error(`Session export exceeds ${U0} bytes`);let V=iq("sha256").update(f).digest("hex"),C=v$.basename(q.taskSourceProjectPath??q.projectPath),B=q.selectedModelId??q.taskModelId,M=["# Blade conversation","",`- Session: \`${q.sessionId}\``,...q.title?[`- Title: ${o0(g(q.title,G))}`]:[],`- Project: \`${o0(g(C,G))}\``,...B?[`- Model: \`${o0(g(B,G))}\``]:[],...q.permissionMode?[`- Permission mode: ${q.permissionMode}`]:[],`- Created: ${q.firstMessageTime}`,`- Updated: ${q.lastMessageTime}`,`- State: ${q.archivedAt?"archived":"active"}`,`- Reasoning: ${N?"included":"omitted"}`,...q.reasoningEffort?[`- Reasoning effort: ${q.reasoningEffort}`]:[],...q.serviceTier?[`- Service tier: ${q.serviceTier}`]:[],...q.responseVerbosity?[`- Response verbosity: ${q.responseVerbosity}`]:[],...q.communicationStyle?[`- Communication style: ${q.communicationStyle}`]:[],...q.communicationStyleDigest?[`- Communication style SHA-256: \`${q.communicationStyleDigest}\``]:[],...q.projectInstructionsDigest?[`- Project instructions SHA-256: \`${q.projectInstructionsDigest}\``]:[],`- Content SHA-256: \`${V}\``,`- Content bytes: ${Q}`,`- Redactions: ${G.count}`,"","---",""].join(`
|
|
55
|
+
`)+`
|
|
56
|
+
`+f;if(Buffer.byteLength(M,"utf8")>U0)throw Error(`Session export exceeds ${U0} bytes`);return{filename:`blade-session-${q.sessionId.slice(0,12)}.md`,markdown:M,contentSha256:V,contentBytes:Q,messageCount:L,activityCount:Z,reasoningIncluded:N,reasoningCount:K,redactionCount:G.count}}import{createHash as J1}from"node:crypto";import N1 from"ajv";var r$="StructuredOutput",h$=65536,c$=131072,U2=2,n$=20,l$=1000,p$=200;function t($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function i$($,q){if(!t($))throw Error(`${q} must be a JSON object`);let x;try{x=JSON.stringify($)}catch(N){throw Error(`${q} must be JSON-serializable`,{cause:N})}if(x===void 0)throw Error(`${q} must be JSON-serializable`);let G=JSON.parse(x);if(!t(G))throw Error(`${q} must be a JSON object`);return G}function L1($){let q=0,x=0,G=(N,J)=>{if(q++,q>l$)throw Error(`Output schema exceeds the ${l$} node complexity limit`);if(J>n$)throw Error(`Output schema exceeds the ${n$} level depth limit`);if(Array.isArray(N)){for(let L of N)G(L,J+1);return}if(!t(N))return;if("$ref"in N){let L=N.$ref;if(typeof L!=="string"||!(L==="#"||L.startsWith("#/$defs/")||L.startsWith("#/definitions/")))throw Error("Output schema only supports self-contained local $ref values")}if("properties"in N&&t(N.properties)){if(x+=Object.keys(N.properties).length,x>p$)throw Error(`Output schema exceeds the ${p$} property limit`)}for(let L of Object.values(N))G(L,J+1)};G($,0)}function Z1($){if(!$||$.length===0)return"Structured output does not match the requested schema";return $.slice(0,8).map((q)=>{return`${q.instancePath||"root"}: ${q.message??q.keyword}`}).join("; ")}function f1($){let q=new N1({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return q.compile($)}catch(x){throw Error(`Invalid output schema: ${x instanceof Error?x.message:String(x)}`)}}function o$($){let q=i$($,"Output schema"),x=JSON.stringify(q);if(Buffer.byteLength(x)>h$)throw Error(`Output schema exceeds ${h$} bytes`);if(q.type!=="object")throw Error('Output schema root type must be "object"');L1(q);let N=f1(q),J=J1("sha256").update(x).digest("hex");return{schema:q,schemaDigest:J,declaration:{name:r$,description:"Submit the final response as an object matching the requested JSON Schema. Call this exactly once after all requested work and verification are complete.",parameters:q,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(L){let Z;try{Z=i$(L,"Structured output")}catch(f){return{success:!1,message:f instanceof Error?f.message:String(f)}}let K=JSON.stringify(Z);if(Buffer.byteLength(K)>c$)return{success:!1,message:`Structured output exceeds ${c$} bytes`};if(!N(Z))return{success:!1,message:Z1(N.errors)};return{success:!0,output:Z}}}}function d$($,q){if(!t($))return;let x=t($.structuredOutput)?$.structuredOutput:$;if(x.schemaDigest!==q.schemaDigest||!("output"in x))return;let G=q.validate(x.output);return G.success?G.output:void 0}function z2($,q){for(let x=$.length-1;x>=0;x--){let G=$[x];if(!G)continue;if(G.role==="user")return;if(G.role==="assistant"){let L=d$(G.metadata,q);if(L)return{output:L,completed:!0};continue}if(G.role!=="tool"||G.name!==r$)continue;let N=t(G.metadata)?G.metadata:void 0,J=d$(N?.metadata,q);if(J)return{output:J,completed:!1}}return}var R0=X0("Service"),a$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),f$=new Set(["local","worktree"]),K1=new Set(["default","autoEdit","yolo","plan"]),V1=new Set(["applied","discarded","conflicted"]);class Q$ extends Error{}function s$($){try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}}function e$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["sessionId","name","branch","baseCommit","originalBranch","repositoryRoot","originalWorkspaceRoot","worktreeRoot","workspaceRoot"].some((G)=>typeof q[G]!=="string"||!q[G])||typeof q.sourceHadChanges!=="boolean"||q.sourceStateFingerprint!==void 0&&(typeof q.sourceStateFingerprint!=="string"||!/^[a-f0-9]{64}$/.test(q.sourceStateFingerprint)))return;return q}function $q($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(!V1.has(String(q.status))||typeof q.updatedAt!=="string"||!Number.isFinite(Date.parse(q.updatedAt))||q.sourceCommit!==void 0&&(typeof q.sourceCommit!=="string"||!/^[a-f0-9]{40,64}$/.test(q.sourceCommit))||q.changedFiles!==void 0&&(typeof q.changedFiles!=="number"||!Number.isInteger(q.changedFiles)||q.changedFiles<0)||q.message!==void 0&&(typeof q.message!=="string"||!q.message.trim()||q.message.length>500))return;return{status:q.status,updatedAt:q.updatedAt,...typeof q.sourceCommit==="string"?{sourceCommit:q.sourceCommit}:{},...typeof q.changedFiles==="number"?{changedFiles:q.changedFiles}:{},...typeof q.message==="string"?{message:q.message}:{}}}function qq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["changedFiles","additions","deletions","commits"].some((G)=>typeof q[G]!=="number"||!Number.isInteger(q[G])||q[G]<0))return;return q}function xq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$,x;if(q.outputSchema!==void 0)try{x=o$(q.outputSchema).schema}catch{return}if(q.version!==1||typeof q.prompt!=="string"||!q.prompt.trim()||q.prompt.length>32000||typeof q.sourceProjectPath!=="string"||!F.isAbsolute(q.sourceProjectPath)||!f$.has(q.isolation)||!M0(q.permissionMode)||q.title!==void 0&&(typeof q.title!=="string"||!q.title.trim()||q.title.length>200)||q.modelId!==void 0&&(typeof q.modelId!=="string"||!q.modelId.trim()||q.modelId.length>500)||q.reasoningEffort!==void 0&&!Q0(q.reasoningEffort)||q.serviceTier!==void 0&&!f0(q.serviceTier)||q.responseVerbosity!==void 0&&!Z0(q.responseVerbosity)||q.communicationStyle!==void 0&&!K0(q.communicationStyle)||q.communicationStyleDigest!==void 0&&(typeof q.communicationStyleDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.communicationStyleDigest))||q.projectInstructionsDigest!==void 0&&(typeof q.projectInstructionsDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.projectInstructionsDigest)))return;let G;if(q.attachments!==void 0){if(!Array.isArray(q.attachments)||q.attachments.length>Lq)return;let N=0;for(let J of q.attachments){if(!J||typeof J!=="object"||Array.isArray(J))return;let L=J;if(!["file","image","url"].includes(String(L.type)))return;for(let Z of["path","url","content","mimeType","name"])if(L[Z]!==void 0&&typeof L[Z]!=="string")return;N+=typeof L.content==="string"?Buffer.byteLength(L.content):0}if(N>Zq)return;G=q.attachments.map((J)=>{let L=J;return{type:L.type,...L.path!==void 0?{path:L.path}:{},...L.url!==void 0?{url:L.url}:{},...L.content!==void 0?{content:L.content}:{},...L.mimeType!==void 0?{mimeType:L.mimeType}:{},...L.name!==void 0?{name:L.name}:{}}})}return{version:1,prompt:q.prompt,...typeof q.title==="string"?{title:q.title}:{},sourceProjectPath:F.resolve(q.sourceProjectPath),isolation:q.isolation,permissionMode:q.permissionMode,...typeof q.modelId==="string"?{modelId:q.modelId}:{},...Q0(q.reasoningEffort)?{reasoningEffort:q.reasoningEffort}:{},...f0(q.serviceTier)?{serviceTier:q.serviceTier}:{},...Z0(q.responseVerbosity)?{responseVerbosity:q.responseVerbosity}:{},...K0(q.communicationStyle)?{communicationStyle:q.communicationStyle}:{},...typeof q.communicationStyleDigest==="string"?{communicationStyleDigest:q.communicationStyleDigest}:{},...typeof q.projectInstructionsDigest==="string"?{projectInstructionsDigest:q.projectInstructionsDigest}:{},...G?{attachments:G}:{},...x?{outputSchema:x}:{}}}function M0($){return typeof $==="string"&&K1.has($)}function Gq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(typeof q.sessionId!=="string"||!q.sessionId||typeof q.projectPath!=="string"||!F.isAbsolute(q.projectPath))return;return{sessionId:q.sessionId,projectPath:F.resolve(q.projectPath)}}var Cq={stat($){return Q1($,{bigint:!0})},readFile($){return a($,"utf-8")}},L0=Cq;function o2($){L0=$}function t2(){L0=Cq}class Fq extends Error{constructor($){super(`Session has no durable creation record: ${$}`);this.name="SessionMissingCreationError"}}class $0 extends Error{sessionId;archivedBySessionId;code="BLADE_SESSION_ARCHIVED";constructor($,q){super($===q?`Session is archived: ${$}`:`Session is archived by ancestor ${q}: ${$}`);this.sessionId=$;this.archivedBySessionId=q;this.name="SessionArchivedError"}}class P extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor($){super($);this.name="SessionArchiveConflictError"}}function e0($,q){return`${$}\x00${q}`}function C1($){if($.kind==="base")return`/review base ${$.baseSha??$.label}`;if($.kind==="commit")return`/review commit ${$.commitSha??$.label}`;return"/review uncommitted"}function Bq($){return typeof $==="string"&&$.length<=64&&Number.isFinite(Date.parse($))}function F1($){let q=new Map($.map((x)=>[e0(x.projectPath,x.sessionId),x]));return $.map((x)=>{let G=x,N=new Set;while(G){let K=e0(G.projectPath,G.sessionId);if(N.has(K))break;if(N.add(K),Bq(G.archivedAt))return{...x,archivedAt:G.archivedAt,archivedBySessionId:G.sessionId};G=G.parentId?q.get(e0(G.projectPath,G.parentId)):void 0}let{archivedAt:J,archivedBySessionId:L,...Z}=x;return Z})}function $$($,q){let x=F1($);if(q===null)return x;return x.filter((G)=>Boolean(G.archivedAt)===q)}class X{static toUISafeMessages($){let q=Date.now(),x=$.length,G=[];return $.forEach((N,J)=>{if(N.role!=="user"&&N.role!=="assistant")return;let L;if(typeof N.content==="string")L=N.content;else if(Array.isArray(N.content))L=N.content.map((V)=>V.type==="text"?V.text:"[Image]").join("");else L="";let Z=L.trim();if(!Z)return;let K=_0(N.metadata),f=K?m$(K):Z,Q=G[G.length-1];if(Q&&Q.role===N.role&&Q.content===f)return;G.push({id:`restored-${q}-${J}`,role:N.role,content:f,timestamp:q-(x-J)*1000,metadata:N.metadata&&typeof N.metadata==="object"?N.metadata:void 0})}),G}static async listSessionPage($={}){let q=J$($),x=await this.listSessionPageFromProjection(q);if(x)return x;let N=(await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,q.cursor?5000:0,q.archived)).sort(N$),J=L$(N,q);return{sessions:J.sessions.map((L)=>this.toPublicMetadata(L)),nextCursor:J.nextCursor}}static async listSessionPageFromProjection($){let q=Kq($);try{let x=await A0();if(!x)return null;await Z$(x,this.projectionDeriver(),$.cursor?5000:0);let G=[],N=[];if($.cwd)G.push("s.project_path = ?"),N.push($.cwd);if(!$.includeSubagents)G.push("s.is_subagent = 0");if(G.push($.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"),q){G.push(`(
|
|
57
|
+
s.last_message_time < ?
|
|
58
|
+
OR (
|
|
59
|
+
s.last_message_time = ?
|
|
60
|
+
AND (
|
|
61
|
+
s.project_sort_key > ?
|
|
62
|
+
OR (s.project_sort_key = ? AND s.session_sort_key > ?)
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
)`);let K=G$(q.projectPath);N.push(q.lastMessageTime,q.lastMessageTime,K,K,G$(q.sessionId))}let L=x.prepare(`WITH RECURSIVE archive_members(
|
|
66
|
+
project_path, session_id, archive_root_id, effective_archived_at, depth
|
|
67
|
+
) AS (
|
|
68
|
+
SELECT project_path, session_id, session_id, archived_at, 0
|
|
69
|
+
FROM sessions
|
|
70
|
+
WHERE archived_at IS NOT NULL
|
|
71
|
+
UNION ALL
|
|
72
|
+
SELECT child.project_path, child.session_id, parent.archive_root_id,
|
|
73
|
+
parent.effective_archived_at, parent.depth + 1
|
|
74
|
+
FROM sessions child
|
|
75
|
+
JOIN archive_members parent
|
|
76
|
+
ON child.project_path = parent.project_path
|
|
77
|
+
AND child.parent_id = parent.session_id
|
|
78
|
+
WHERE parent.depth < 128
|
|
79
|
+
),
|
|
80
|
+
ranked_archive AS (
|
|
81
|
+
SELECT project_path, session_id, archive_root_id,
|
|
82
|
+
effective_archived_at,
|
|
83
|
+
ROW_NUMBER() OVER (
|
|
84
|
+
PARTITION BY project_path, session_id
|
|
85
|
+
ORDER BY depth ASC, archive_root_id ASC
|
|
86
|
+
) AS rank
|
|
87
|
+
FROM archive_members
|
|
88
|
+
)
|
|
89
|
+
SELECT s.metadata_json, a.archive_root_id, a.effective_archived_at
|
|
90
|
+
FROM sessions s
|
|
91
|
+
LEFT JOIN ranked_archive a
|
|
92
|
+
ON a.project_path = s.project_path
|
|
93
|
+
AND a.session_id = s.session_id
|
|
94
|
+
AND a.rank = 1
|
|
95
|
+
${G.length>0?`WHERE ${G.join(" AND ")}`:""}
|
|
96
|
+
ORDER BY s.last_message_time DESC,
|
|
97
|
+
s.project_sort_key ASC,
|
|
98
|
+
s.session_sort_key ASC
|
|
99
|
+
LIMIT ?`).all(...N,$.limit+1).map((K)=>{let f=JSON.parse(K.metadata_json);if(K.archive_root_id&&K.effective_archived_at)return{...f,archivedAt:K.effective_archived_at,archivedBySessionId:K.archive_root_id};let{archivedAt:Q,archivedBySessionId:V,...C}=f;return C}),Z=L$(L,$);return{sessions:Z.sessions.map((K)=>this.toPublicMetadata(K)),nextCursor:Z.nextCursor}}catch{return null}}static async listSessions($={}){let q=J$($),x=await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,0,q.archived),G=new Set;return x.sort(N$).flatMap((N)=>{let J=`${N.projectPath}\x00${N.sessionId}`;if(G.has(J))return[];return G.add(J),[this.toPublicMetadata(N)]})}static async findSessionMetadata($,q){if(R($),q!==void 0){if(!F.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=F.resolve(q),N=this.getSessionFilePath(G,$);try{let J=await this.readStoredSessionMetadata(N,$,G);if(J.projectPath!==G)return;if(!J.parentId||J.archivedAt)return this.toPublicMetadata($$([J],null)[0]??J);let L=await this.scanStoredSessions(G,!0,0,null);return this.toPublicMetadata(L.find((Z)=>Z.sessionId===$)??J)}catch(J){if(J.code==="ENOENT")return;throw J}}let x=(await this.scanStoredSessions(void 0,!0,0,null)).filter((G)=>G.sessionId===$);if(x.length===0)return;if(x.length>1)throw Error(`Ambiguous session ID: ${$}`);return this.toPublicMetadata(x[0])}static async loadSession($,q){try{if(q){if(!F.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=F.resolve(q),N=this.getSessionFilePath(G,$);try{return await this.loadSessionFromFile(N,$,G)}catch(J){if(J.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw J}}let x=(await this.scanStoredSessions(void 0,!0,0,null)).find((G)=>G.sessionId===$);if(!x)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(x.filePath,$)}catch(x){throw R0.error(`[SessionService] 加载会话失败 (${$}):`,x),x}}static async loadSessionModelContext($,q){try{if(q){if(!F.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=F.resolve(q),N=this.getSessionFilePath(G,$);try{return await this.loadSessionModelContextFromFile(N,$,G)}catch(J){if(J.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw J}}let x=(await this.scanStoredSessions(void 0,!0,0,null)).find((G)=>G.sessionId===$);if(!x)throw Error(`未找到会话: ${$}`);return await this.loadSessionModelContextFromFile(x.filePath,$)}catch(x){throw R0.error(`[SessionService] 加载模型上下文失败 (${$}):`,x),x}}static async exportSessionMarkdown($,q,x={}){R($);let G=this.resolveCatalogWorkspace(q),N=m(G,$),J;try{J=await this.readStableSessionSnapshot(N,$)}catch(K){throw this.sanitizeStoredSessionError(K,$)}let L=this.projectMetadataFromEntries(J,$,G,N);if(L.projectPath!==G)throw Error(`Session export workspace mismatch: ${$}`);let Z=L.archivedAt;if(!Z&&L.parentId)Z=(await this.findArchivedAncestor(L.parentId,G))?.archivedAt;return P$(J,{...L,archivedAt:Z},x)}static async listRewindCheckpoints($,q){R($);let x=this.resolveCatalogWorkspace(q),G=m(x,$),N=await this.readStableSessionSnapshot(G,$);this.validateSessionWorkspace(N,$,x);let J=new O0({sessionId:$,workspaceRoot:x});await J.initialize();let L=fq(N),Z=[];for(let K of L){let f=x$(N,K.messageId),Q=await J.previewRewind(f.snapshotMessageIds);Z.push({...K,fileCount:Q.files.length})}return Z}static async rewindSession($,q,x){R($);let G=this.resolveCatalogWorkspace(q);await this.assertSessionWritable($,G);let N=m(G,$),J=new u(N),L;try{await J.appendValidatedAsync(async(Z)=>{this.validateSessionWorkspace(Z,$,G);let K=x$(Z,x.targetMessageId),f=new O0({sessionId:$,workspaceRoot:G});await f.initialize();let Q=await f.previewRewind(K.snapshotMessageIds),V=x.mode==="conversation"?await f.commitSnapshots(K.snapshotMessageIds):await f.rewindSnapshots(K.snapshotMessageIds),C=new Date().toISOString(),B={id:j(),sessionId:$,timestamp:C,type:"session_rewound",cwd:G,gitBranch:c(G),version:n(),data:{rewindId:j(),targetMessageId:x.targetMessageId,mode:x.mode,restoredFiles:x.mode==="conversation"?[]:V.files,createdAt:C}},E=v([...Z,B]);return L={checkpoint:{...K.checkpoint,fileCount:Q.files.length},mode:x.mode,removedTurns:K.removedTurns,restoredFiles:B.data.restoredFiles,messages:this.convertJSONLToMessages(E)},B})}catch(Z){throw this.sanitizeStoredSessionError(Z,$)}if(!L)throw Error(`Session rewind did not produce a result: ${$}`);for(let Z of L.restoredFiles)h.getInstance().clearFileRecord(Z);return L}static async forkSession($,q){R($);let x=q.newSessionId??`fork-${Date.now()}-${j(8)}`;R(x);let G=this.resolveForkWorkspace(q.sourceProjectPath),N=this.resolveForkWorkspace(q.targetProjectPath);if(G!==N)throw Error("Session forks must stay in the source workspace");let J=m(G,$),L=await this.readStableSessionSnapshot(J,$),Z=this.getSessionCreatedEntry(L,$);if(Z.data.sessionId!==$)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!F.isAbsolute(Z.cwd)||F.resolve(Z.cwd)!==G)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let K=this.projectMetadataFromEntries(L,$,G,J);if(K.archivedAt)throw new $0($,$);if(K.parentId){let W=await this.findArchivedAncestor(K.parentId,G);if(W)throw new $0($,W.sessionId)}let f=v(L),Q=new Date().toISOString(),V=Z.data.rootId||$,C=c(N),B=n(),{status:E,taskStatus:M,taskStatusReason:b,taskFailure:_,taskStartedAt:s,taskCompletedAt:e,taskOwnerPid:y,taskPromptSummary:S,taskDispatch:D,taskModelId:z,taskRetriedFrom:A,taskDelivery:Y,taskIsolation:w,taskSourceProjectPath:w0,taskWorktree:K$,taskDiffStat:V$,taskQueuePosition:C$,taskQueueDepth:F$,taskConcurrencyLimit:B$,pendingInteraction:E0,...b0}=Z.data,g0={id:j(),sessionId:x,timestamp:Q,type:"session_created",cwd:N,gitBranch:C,version:B,data:{...b0,sessionId:x,rootId:V,parentId:$,relationType:"fork",taskStatus:"completed",taskCompletedAt:Q,taskIsolation:"local",taskSourceProjectPath:N,createdAt:Q,updatedAt:Q}},k0=f.filter((W)=>W.type!=="session_created"&&W.type!=="inbox_acknowledged"&&W.type!=="interaction_requested"&&W.type!=="interaction_responded"&&W.type!=="interaction_recovered"&&W.type!=="review_started"&&W.type!=="review_completed").map((W)=>{let l={...W,id:j(),sessionId:x,cwd:N,gitBranch:C,version:B};if(W.type==="session_updated"){let{status:C0,taskStatus:U,taskStatusReason:j0,taskFailure:B1,taskStartedAt:T1,taskCompletedAt:Y1,taskOwnerPid:H1,taskPromptSummary:X1,taskDispatch:O1,taskModelId:W1,taskRetriedFrom:_1,taskDelivery:U1,taskIsolation:z1,taskSourceProjectPath:D1,taskWorktree:R1,taskDiffStat:A1,taskQueuePosition:M1,taskQueueDepth:w1,taskConcurrencyLimit:E1,pendingInteraction:b1,...Tq}=W.data;return{...l,type:"session_updated",data:{...Tq,sessionId:x,rootId:V,parentId:$,relationType:"fork"}}}if(W.type==="message_created"){let{inboxMessageId:C0,...U}=W.data;return{...l,type:"message_created",data:U}}return l}),y0={id:j(),sessionId:x,timestamp:Q,type:"session_updated",cwd:N,gitBranch:C,version:B,data:{sessionId:x,rootId:V,parentId:$,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:Q,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:N,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:Q}},q0=[g0,...k0,y0],V0=m(N,x);try{await new u(V0).createExclusive(q0)}catch(W){if(W.code==="EEXIST")throw Error(`Fork session already exists: ${x}`,{cause:W});throw W}let S0=this.projectMetadataFromEntries(q0,x,N,V0);return{sessionId:x,parentSessionId:$,projectPath:N,messages:this.convertJSONLToMessages(q0),metadata:this.toPublicMetadata(S0)}}static async deleteSession($,q){if(R($),q){if(!F.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=F.resolve(q),N=this.getSessionFilePath(G,$),J=new u(N),L;try{L=await J.deleteValidated((Z)=>{return this.projectMetadataFromEntries(Z,$,G,N).projectPath===G})}catch(Z){if(!this.isCorruptSessionJSONLError(Z))throw Z;L=await J.delete()}if(!L)return 0;return await D0(F.join(F.dirname(N),`${$}.inbox.json`),{force:!0}),await D0(q$(G,$),{force:!0}),await this.removeFromProjection($,G),1}let x=(await this.scanStoredSessions(void 0,!0)).filter((G)=>G.sessionId===$);if(x.length===0)return 0;return await Promise.all(x.map(async(G)=>{await new u(G.filePath).delete(),await D0(F.join(F.dirname(G.filePath),`${G.sessionId}.inbox.json`),{force:!0}),await D0(q$(G.projectPath,G.sessionId),{force:!0}),await this.removeFromProjection(G.sessionId,G.projectPath)})),x.length}static async removeFromProjection($,q){try{let x=await A0();if(x)Vq(x,$,q)}catch{}}static validateTaskMetadataUpdate($,q){if($.taskPromptSummary!==void 0&&$.taskPromptSummary!==null&&(!$.taskPromptSummary.trim()||$.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if($.taskFailure!==void 0&&$.taskFailure!==null&&!n0($.taskFailure))throw Error("Invalid session task failure");if($.taskDispatch!==void 0&&$.taskDispatch!==null&&!xq($.taskDispatch))throw Error("Invalid durable task dispatch");if($.taskModelId!==void 0&&$.taskModelId!==null&&(!$.taskModelId.trim()||$.taskModelId.length>500))throw Error("Invalid session task model ID");if($.selectedModelId!==void 0&&$.selectedModelId!==null&&(!$.selectedModelId.trim()||$.selectedModelId.length>500))throw Error("Invalid selected session model ID");if($.permissionMode!==void 0&&$.permissionMode!==null&&!M0($.permissionMode))throw Error("Invalid session permission mode");if($.reasoningEffort!==void 0&&$.reasoningEffort!==null&&!Q0($.reasoningEffort))throw Error("Invalid session reasoning effort");if($.serviceTier!==void 0&&$.serviceTier!==null&&!f0($.serviceTier))throw Error("Invalid session service tier");if($.responseVerbosity!==void 0&&$.responseVerbosity!==null&&!Z0($.responseVerbosity))throw Error("Invalid session response verbosity");if($.communicationStyle!==void 0&&$.communicationStyle!==null&&!K0($.communicationStyle))throw Error("Invalid session communication style");if($.communicationStyleDigest!==void 0&&$.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test($.communicationStyleDigest))throw Error("Invalid session communication style digest");if($.projectInstructionsDigest!==void 0&&$.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test($.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if($.taskRetriedFrom!==void 0&&$.taskRetriedFrom!==null&&!Gq($.taskRetriedFrom))throw Error("Invalid session task retry source");if($.taskDelivery!==void 0&&$.taskDelivery!==null&&!$q($.taskDelivery))throw Error("Invalid session task delivery");if($.taskIsolation!==void 0&&$.taskIsolation!==null&&!f$.has($.taskIsolation))throw Error(`Invalid session task isolation: ${String($.taskIsolation)}`);if($.taskSourceProjectPath!==void 0&&$.taskSourceProjectPath!==null&&!F.isAbsolute($.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if($.taskWorktree!==void 0&&$.taskWorktree!==null){let x=e$($.taskWorktree);if(!x||x.sessionId!==q||![x.repositoryRoot,x.originalWorkspaceRoot,x.worktreeRoot,x.workspaceRoot].every((G)=>F.isAbsolute(G)))throw Error("Invalid session task worktree metadata")}if($.taskDiffStat!==void 0&&$.taskDiffStat!==null&&!qq($.taskDiffStat))throw Error("Invalid session task diff stat");if($.taskQueuePosition!==void 0&&$.taskQueuePosition!==null&&(!Number.isInteger($.taskQueuePosition)||$.taskQueuePosition<1))throw Error("Invalid session task queue position");if($.taskQueueDepth!==void 0&&$.taskQueueDepth!==null&&(!Number.isInteger($.taskQueueDepth)||$.taskQueueDepth<0))throw Error("Invalid session task queue depth");if($.taskConcurrencyLimit!==void 0&&$.taskConcurrencyLimit!==null&&(!Number.isInteger($.taskConcurrencyLimit)||$.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof $.taskQueuePosition==="number"&&typeof $.taskQueueDepth==="number"&&$.taskQueuePosition>$.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata($,q,x={}){R($),X.validateTaskMetadataUpdate(x,$);let G=X.resolveCatalogWorkspace(q);if(x.taskWorktree&&F.resolve(x.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let N=new Date().toISOString(),J={id:j(),sessionId:$,timestamp:N,type:"session_created",cwd:G,gitBranch:c(G),version:n(),data:{sessionId:$,rootId:$,...x.title!==void 0?{title:x.title}:{},taskStatus:x.taskStatus??"queued",...x.taskPromptSummary!==void 0?{taskPromptSummary:x.taskPromptSummary}:{},...x.taskDispatch!==void 0?{taskDispatch:x.taskDispatch}:{},...x.taskModelId!==void 0?{taskModelId:x.taskModelId}:{},...x.taskRetriedFrom!==void 0?{taskRetriedFrom:x.taskRetriedFrom}:{},...x.taskIsolation!==void 0?{taskIsolation:x.taskIsolation}:{},...x.taskSourceProjectPath!==void 0?{taskSourceProjectPath:x.taskSourceProjectPath}:{},...x.taskWorktree!==void 0?{taskWorktree:x.taskWorktree}:{},...x.selectedModelId!==void 0?{selectedModelId:x.selectedModelId}:{},...x.permissionMode!==void 0?{permissionMode:x.permissionMode}:{},...x.reasoningEffort!==void 0?{reasoningEffort:x.reasoningEffort}:{},...x.serviceTier!==void 0?{serviceTier:x.serviceTier}:{},...x.responseVerbosity!==void 0?{responseVerbosity:x.responseVerbosity}:{},...x.communicationStyle!==void 0?{communicationStyle:x.communicationStyle}:{},...x.communicationStyleDigest!==void 0?{communicationStyleDigest:x.communicationStyleDigest}:{},...x.projectInstructionsDigest!==void 0?{projectInstructionsDigest:x.projectInstructionsDigest}:{},createdAt:N,updatedAt:N}},L=X.getSessionFilePath(G,$);return await new u(L).createExclusive([J]),X.toPublicMetadata(X.projectMetadataFromEntries([J],$,G,L))}static async assertSessionWritable($,q){let x=await this.findSessionMetadata($,q);if(!x)throw Error(`Session not found: ${$}`);if(x.archivedAt)throw new $0($,x.archivedBySessionId??$);return x}static async findArchivedAncestor($,q){let x=new Set,G=$;while(G){if(x.has(G))throw Error("Session lineage contains a cycle");x.add(G),R(G);let N=m(q,G),J;try{J=await a(N,"utf8")}catch(Z){if(Z.code==="ENOENT")return;throw Z}let L=this.projectMetadataFromEntries(this.parseStoredSession(J,G),G,q,N);if(L.projectPath!==q)throw Error("Session lineage escapes the requested workspace");if(L.archivedAt)return{sessionId:L.sessionId,archivedAt:L.archivedAt};G=L.parentId}return}static async listSessionArchiveMembers($,q){R($);let x=this.resolveCatalogWorkspace(q),G=await this.scanStoredSessions(x,!0,0,null);if(!G.some((L)=>L.sessionId===$))throw Error(`Session not found: ${$}`);let N=new Set([$]),J=!0;while(J){J=!1;for(let L of G)if(L.parentId&&N.has(L.parentId)&&!N.has(L.sessionId))N.add(L.sessionId),J=!0}return G.filter((L)=>N.has(L.sessionId)).sort((L,Z)=>L.sessionId.localeCompare(Z.sessionId)).map((L)=>this.toPublicMetadata(L))}static async archiveSession($,q){R($);let x=this.resolveCatalogWorkspace(q),G=await this.findSessionMetadata($,x);if(!G)throw Error(`Session not found: ${$}`);if(G.archivedAt)return G;let N=await this.listSessionArchiveMembers($,x),J=N.find((Z)=>Z.taskStatus==="queued"||Z.taskStatus==="running");if(J)throw new P(`Stop session ${J.sessionId} before archiving this session tree`);let L=[];try{for(let Q of N)L.push(await i.acquire(Q.sessionId,x));let Z=m(x,$),K=new u(Z),f=[];return await K.appendValidated((Q)=>{let V=this.projectMetadataFromEntries(Q,$,x,Z);if(V.archivedAt)throw new P(`Session archive state changed concurrently: ${$}`);if(V.taskStatus==="queued"||V.taskStatus==="running")throw new P(`Stop session ${$} before archiving it`);let C=new Date().toISOString(),B={id:j(),sessionId:$,timestamp:C,type:"session_updated",cwd:x,gitBranch:c(x),version:n(),data:{sessionId:$,archivedAt:C,updatedAt:C}};return f=[...Q,B],B}),this.toPublicMetadata({...this.projectMetadataFromEntries(f,$,x,Z),archivedBySessionId:$})}catch(Z){if(Z instanceof P)throw Z;if(Z instanceof p)throw new P(Z.message);throw this.sanitizeStoredSessionError(Z,$)}finally{for(let Z of L.reverse())await Z.release()}}static async unarchiveSession($,q){R($);let x=this.resolveCatalogWorkspace(q),G=await this.findSessionMetadata($,x);if(!G)throw Error(`Session not found: ${$}`);if(!G.archivedAt)return G;if(G.archivedBySessionId&&G.archivedBySessionId!==$)throw new P(`Unarchive ancestor ${G.archivedBySessionId} to restore session ${$}`);let N;try{N=await i.acquire($,x);let J=m(x,$),L=new u(J),Z=[];return await L.appendValidated((K)=>{if(!this.projectMetadataFromEntries(K,$,x,J).archivedAt)throw new P(`Session archive state changed concurrently: ${$}`);let Q=new Date().toISOString(),V={id:j(),sessionId:$,timestamp:Q,type:"session_updated",cwd:x,gitBranch:c(x),version:n(),data:{sessionId:$,archivedAt:null,updatedAt:Q}};return Z=[...K,V],V}),this.toPublicMetadata(this.projectMetadataFromEntries(Z,$,x,J))}catch(J){if(J instanceof P)throw J;if(J instanceof p)throw new P(J.message);throw this.sanitizeStoredSessionError(J,$)}finally{await N?.release()}}static async updateSessionMetadata($,q,x){if(R($),X.validateTaskMetadataUpdate(x,$),x.taskStatus!==void 0&&!a$.has(x.taskStatus))throw Error(`Invalid session task status: ${String(x.taskStatus)}`);if(x.taskOwnerPid!==void 0&&x.taskOwnerPid!==null&&(!Number.isInteger(x.taskOwnerPid)||x.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let G=X.resolveCatalogWorkspace(q);if(x.taskWorktree&&F.resolve(x.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let N=X.getSessionFilePath(G,$),J=new u(N),L=[];try{await J.appendValidatedAsync(async(Z)=>{let K=X.getSessionCreatedEntry(Z,$);if(K.data.sessionId!==$)throw Error(`Session metadata creation record sessionId mismatch: ${$}`);if(!F.isAbsolute(K.cwd)||F.resolve(K.cwd)!==G)throw Error(`Session metadata creation record cwd mismatch: ${$}`);let f=X.projectMetadataFromEntries(Z,$,G,N);if(f.archivedAt)throw new $0($,$);if(f.parentId){let C=await X.findArchivedAncestor(f.parentId,G);if(C)throw new $0($,C.sessionId)}let Q=new Date().toISOString(),V={id:j(),sessionId:$,timestamp:Q,type:"session_updated",cwd:G,gitBranch:c(G),version:n(),data:{sessionId:$,...x.title!==void 0?{title:x.title}:{},...x.taskStatus!==void 0?{taskStatus:x.taskStatus}:{},...x.taskStatusReason!==void 0?{taskStatusReason:x.taskStatusReason}:{},...x.taskFailure!==void 0?{taskFailure:x.taskFailure}:{},...x.taskStartedAt!==void 0?{taskStartedAt:x.taskStartedAt}:{},...x.taskCompletedAt!==void 0?{taskCompletedAt:x.taskCompletedAt}:{},...x.taskOwnerPid!==void 0?{taskOwnerPid:x.taskOwnerPid}:{},...x.taskPromptSummary!==void 0?{taskPromptSummary:x.taskPromptSummary}:{},...x.taskDispatch!==void 0?{taskDispatch:x.taskDispatch}:{},...x.taskModelId!==void 0?{taskModelId:x.taskModelId}:{},...x.taskRetriedFrom!==void 0?{taskRetriedFrom:x.taskRetriedFrom}:{},...x.taskDelivery!==void 0?{taskDelivery:x.taskDelivery}:{},...x.taskIsolation!==void 0?{taskIsolation:x.taskIsolation}:{},...x.taskSourceProjectPath!==void 0?{taskSourceProjectPath:x.taskSourceProjectPath}:{},...x.taskWorktree!==void 0?{taskWorktree:x.taskWorktree}:{},...x.taskDiffStat!==void 0?{taskDiffStat:x.taskDiffStat}:{},...x.taskQueuePosition!==void 0?{taskQueuePosition:x.taskQueuePosition}:{},...x.taskQueueDepth!==void 0?{taskQueueDepth:x.taskQueueDepth}:{},...x.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:x.taskConcurrencyLimit}:{},...x.selectedModelId!==void 0?{selectedModelId:x.selectedModelId}:{},...x.permissionMode!==void 0?{permissionMode:x.permissionMode}:{},...x.reasoningEffort!==void 0?{reasoningEffort:x.reasoningEffort}:{},...x.serviceTier!==void 0?{serviceTier:x.serviceTier}:{},...x.responseVerbosity!==void 0?{responseVerbosity:x.responseVerbosity}:{},...x.communicationStyle!==void 0?{communicationStyle:x.communicationStyle}:{},...x.communicationStyleDigest!==void 0?{communicationStyleDigest:x.communicationStyleDigest}:{},...x.projectInstructionsDigest!==void 0?{projectInstructionsDigest:x.projectInstructionsDigest}:{},updatedAt:Q}};return L=[...Z,V],V})}catch(Z){throw X.sanitizeStoredSessionError(Z,$)}return X.toPublicMetadata(X.projectMetadataFromEntries(L,$,G,N))}static async setSessionPermissionMode($,q,x){if(R($),!M0(x))throw Error("Invalid session permission mode");let G=X.resolveCatalogWorkspace(q),N=await X.findSessionMetadata($,G);if(N?.permissionMode===x)return N;if(N)return X.updateSessionMetadata($,G,{permissionMode:x});try{return await X.createSessionMetadata($,G,{taskStatus:"completed",permissionMode:x})}catch(J){if(J.code!=="EEXIST")throw J;return X.updateSessionMetadata($,G,{permissionMode:x})}}static async findSessionTaskWorktree($,q){R($);let x=X.resolveCatalogWorkspace(q),G=X.getSessionFilePath(x,$);try{return(await X.readStoredSessionMetadata(G,$,x)).taskWorktree}catch(N){if(N.code==="ENOENT")return;throw X.sanitizeStoredSessionError(N,$)}}static async findSessionTaskDispatch($,q){R($);let x=X.resolveCatalogWorkspace(q),G=X.getSessionFilePath(x,$);try{return(await X.readStoredSessionMetadata(G,$,x)).taskDispatch}catch(N){if(N.code==="ENOENT")return;throw X.sanitizeStoredSessionError(N,$)}}static async loadSessionFromFile($,q,x){let G=await a($,"utf-8"),N=this.parseStoredSession(G,q);if(x!==void 0){if(this.projectMetadataFromEntries(N,q,x,$).projectPath!==x)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToMessages(N)}static async loadSessionModelContextFromFile($,q,x){let G=await a($,"utf-8"),N=this.parseStoredSession(G,q);if(x!==void 0){if(this.projectMetadataFromEntries(N,q,x,$).projectPath!==x)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToModelContext(N)}static convertJSONLToModelContext($){let q=v($),x=-1,G;for(let J=0;J<q.length;J++){let L=q[J];if(L?.type!=="part_created"||L.data.partType!=="summary")continue;let Z=L.data.payload;if(x=J,G=U$(Z.replacementMessages),!G)G=[{role:"user",content:Z.text??"",metadata:L.data.payload}]}if(x<0||!G)return this.convertJSONLToMessages(q);let N=this.convertJSONLToMessages(q.slice(x+1));return[...G,...N]}static convertJSONLToMessages($){let q=[],x=new Map,G=new Map,N=new Map,J=new Map,L=new Map,Z=v($),K=new Set;for(let f of Z){if(f.type==="message_created"){let Q=f.data.metadata&&typeof f.data.metadata==="object"&&!Array.isArray(f.data.metadata)?f.data.metadata:void 0,V=Q?.codeReview&&typeof Q.codeReview==="object"&&!Array.isArray(Q.codeReview)?Q.codeReview:void 0;if(V?.phase==="completed"&&typeof V.reviewId==="string")K.add(V.reviewId);let C=f.data.role==="assistant"&&f.data.parentMessageId?N.get(f.data.parentMessageId):void 0,B=C??{role:f.data.role,content:"",...f.data.metadata||f.data.inboxMessageId?{metadata:{...f.data.metadata&&typeof f.data.metadata==="object"&&!Array.isArray(f.data.metadata)?f.data.metadata:{},...f.data.inboxMessageId?{inboxMessageId:f.data.inboxMessageId}:{}}}:{}};if(x.set(f.data.messageId,B),G.set(f.data.messageId,[]),!C)q.push(B)}if(f.type==="part_created"){if(f.data.partType==="reasoning"){let Q=x.get(f.data.messageId);if(Q){let V=f.data.payload;Q.reasoningContent=(Q.reasoningContent??"")+(V.text??"")}}if(f.data.partType==="text"){let Q=x.get(f.data.messageId);if(Q){let V=f.data.payload,C=G.get(f.data.messageId);if(C)C.push({type:"text",text:V.text??""}),Q.content=Jq(C);else Q.content=V.text??""}}if(f.data.partType==="image"){let Q=x.get(f.data.messageId);if(Q){let V=f.data.payload,C=G.get(f.data.messageId);if(C&&V.dataUrl)C.push({type:"image_url",image_url:{url:V.dataUrl}}),Q.content=Jq(C)}}if(f.data.partType==="tool_call"){let Q=x.get(f.data.messageId);if(Q?.role!=="assistant"){if(Q=N.get(f.data.messageId),!Q)Q={role:"assistant",content:"",tool_calls:[]},N.set(f.data.messageId,Q),q.push(Q)}if(Q.role==="assistant"){let V=f.data.payload,C=V.toolCallId??f.data.partId;J.set(f.data.partId,C),L.set(C,Q),Q.tool_calls??=[],Q.tool_calls.push({id:C,type:"function",function:{name:V.toolName??"unknown",arguments:JSON.stringify(V.input??{})}})}}if(f.data.partType==="tool_result"){let Q=f.data.payload,V=typeof Q.error==="string"?`Error: ${Q.error}`:typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??""),C=Q;q.push({role:"tool",content:V,tool_call_id:J.get(f.data.messageId)??Q.toolCallId,name:Q.toolName,metadata:C})}if(f.data.partType==="summary"){let Q=f.data.payload,V=f.data.payload;q.push({role:"system",content:Q.text??"",metadata:V})}if(f.data.partType==="subtask_ref"){let Q=x.get(f.data.messageId)??L.get(f.data.messageId);if(Q){let V=f.data.payload,C=Q.metadata??{};Q.metadata={...C,subtaskRef:V}}}}}for(let f of Y0(Z)){if(f.completion===void 0||K.has(f.start.reviewId))continue;q.push({role:"assistant",content:A$(f.start,f.completion),metadata:{codeReview:{...M$(f.start,f.completion),synthetic:!0}}})}return q}static projectionDeriver(){return($,q,x)=>{try{let G=m(x,q);return this.projectMetadataFromEntries($,q,x,G)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection($,q,x=0,G=!1){try{let N=await A0();if(!N)return null;await Z$(N,this.projectionDeriver(),x);let J=$?N.prepare("SELECT metadata_json, is_subagent FROM sessions WHERE project_path=?").all($):N.prepare("SELECT metadata_json, is_subagent FROM sessions").all(),L=[];for(let Z of J){if(!q&&Z.is_subagent===1)continue;try{let K=JSON.parse(Z.metadata_json);if($!==void 0&&K.projectPath!==$)continue;L.push(K)}catch{}}return $$(L,G)}catch{return null}}static async scanStoredSessions($,q=!1,x=0,G=!1){let N=$?F.resolve($):void 0,J=await this.scanStoredSessionsFromProjection(N,q,x,G);if(J)return J;let L=N?[{storagePath:B0(N),projectPath:N}]:await this.listAllProjectStorageDirectories(),Z=[];for(let K of L){let f;try{f=await t$(K.storagePath)}catch(Q){if(Q.code==="ENOENT")continue;throw Q}for(let Q of f){if(!Q.endsWith(".jsonl"))continue;let V=Q.slice(0,-6),C=F.join(K.storagePath,Q);try{let B=await this.readStoredSessionMetadata(C,V,K.projectPath);if(N!==void 0&&B.projectPath!==N){R0.warn(`[SessionService] Skipping out-of-scope session transcript: ${V}`);continue}if(!q&&B.relationType==="subagent")continue;Z.push(B)}catch(B){let E=B.code;if(E==="ENOENT")continue;if(E)throw B;R0.warn(`[SessionService] Skipping invalid session transcript: ${V}`)}}}return $$(Z,G)}static async listAllProjectStorageDirectories(){let $=F.join(N0(),"projects"),q;try{q=await t$($,{withFileTypes:!0,encoding:"utf8"})}catch(x){if(x.code==="ENOENT")return[];throw x}return q.filter((x)=>x.isDirectory()).map((x)=>({storagePath:F.join($,x.name),projectPath:Nq(x.name)}))}static async readStoredSessionMetadata($,q,x){let G=await a($,"utf-8"),N=this.parseStoredSession(G,q);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(N,q,x,$))}static async reconcileInterruptedTask($){let q=$.taskOwnerPid;if($.taskStatus!=="running"||q===void 0||s$(q))return $;let x;try{x=await i.acquire($.sessionId,$.projectPath)}catch(J){if(!(J instanceof p))throw J;let L=await a($.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(L,$.sessionId),$.sessionId,$.projectPath,$.filePath)}let G=new u($.filePath),N;try{try{await G.appendValidated((J)=>{let L=this.projectMetadataFromEntries(J,$.sessionId,$.projectPath,$.filePath);if(L.taskStatus!=="running"||L.taskOwnerPid!==q||s$(q))throw new Q$;let Z=new Date().toISOString(),K={id:j(),sessionId:$.sessionId,timestamp:Z,type:"session_updated",cwd:$.projectPath,gitBranch:c($.projectPath),version:n(),data:{sessionId:$.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:Z,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:Z}};return N=[...J,K],K})}catch(J){if(!(J instanceof Q$))throw J}if(!N){let J=await a($.filePath,"utf-8");N=this.parseStoredSession(J,$.sessionId)}return this.projectMetadataFromEntries(N,$.sessionId,$.projectPath,$.filePath)}finally{await x.release()}}static projectMetadataFromEntries($,q,x,G){if($.length===0)throw Error(`Empty session transcript: ${q}`);let N=this.getSessionCreatedEntry($,q),J=$.reduce((U,j0)=>j0.type==="session_updated"?{...U,...j0.data}:U,{...N.data}),L=v($),Z=R$(D$(L)),f=Y0(L).at(-1),Q=L.findLastIndex((U)=>U.type==="review_started"&&U.data.reviewId===f?.start.reviewId||U.type==="review_completed"&&U.data.reviewId===f?.start.reviewId),V=L.findLastIndex((U)=>(U.type==="session_created"||U.type==="session_updated")&&Object.hasOwn(U.data,"taskStatus")),C=f!==void 0&&Q>V,B=C?f.completion===void 0?"running":f.completion.status==="completed"||f.completion.status==="stale"?"completed":f.completion.status==="aborted"?"cancelled":f.completion.status==="interrupted"?"interrupted":"failed":void 0,E=L.filter((U)=>U.type==="message_created"&&["user","assistant"].includes(U.data.role)).length,M=L.some((U)=>U.type==="part_created"&&U.data.partType==="tool_result"&&typeof U.data.payload.error==="string"),b=a$.has(J.taskStatus)?J.taskStatus:void 0,_=B??b??(M?"failed":"completed"),s=typeof J.taskOwnerPid==="number"&&Number.isInteger(J.taskOwnerPid)&&J.taskOwnerPid>0?J.taskOwnerPid:void 0,e=f$.has(J.taskIsolation)?J.taskIsolation:void 0,y=typeof J.taskSourceProjectPath==="string"&&F.isAbsolute(J.taskSourceProjectPath)?F.resolve(J.taskSourceProjectPath):void 0,S=N.cwd;if(S!==void 0&&!F.isAbsolute(S))throw Error(`Session catalog cwd must be absolute: ${q}`);let D=S===void 0?x:F.resolve(S),z=e$(J.taskWorktree),A=z?.sessionId===q&&F.resolve(z.workspaceRoot)===D?z:void 0,Y=qq(J.taskDiffStat),w=xq(J.taskDispatch),w0=typeof J.taskModelId==="string"&&J.taskModelId.trim()?J.taskModelId:w?.modelId,K$=typeof J.selectedModelId==="string"&&J.selectedModelId.trim()?J.selectedModelId:w0,V$=M0(J.permissionMode)?J.permissionMode:w?.permissionMode,C$=Q0(J.reasoningEffort)?J.reasoningEffort:w?.reasoningEffort,F$=f0(J.serviceTier)?J.serviceTier:w?.serviceTier,B$=Z0(J.responseVerbosity)?J.responseVerbosity:w?.responseVerbosity,E0=K0(J.communicationStyle)?J.communicationStyle:w?.communicationStyle,b0=Object.hasOwn(J,"communicationStyleDigest")?typeof J.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(J.communicationStyleDigest)?J.communicationStyleDigest:void 0:E0===w?.communicationStyle?w?.communicationStyleDigest:void 0,g0=Object.hasOwn(J,"projectInstructionsDigest")?typeof J.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(J.projectInstructionsDigest)?J.projectInstructionsDigest:void 0:w?.projectInstructionsDigest,k0=Bq(J.archivedAt)?J.archivedAt:void 0,y0=Gq(J.taskRetriedFrom),q0=$q(J.taskDelivery),V0=typeof J.taskQueuePosition==="number"&&Number.isInteger(J.taskQueuePosition)&&J.taskQueuePosition>0?J.taskQueuePosition:void 0,S0=typeof J.taskQueueDepth==="number"&&Number.isInteger(J.taskQueueDepth)&&J.taskQueueDepth>=0?J.taskQueueDepth:void 0,W=typeof J.taskConcurrencyLimit==="number"&&Number.isInteger(J.taskConcurrencyLimit)&&J.taskConcurrencyLimit>0?J.taskConcurrencyLimit:void 0,l=C?f?.completion?f.completion.status==="completed"?void 0:`Code review ${P0(f.completion.status)}`:`Reviewing ${f?.start.target.label??"changes"}`:void 0,C0=C?_==="failed"&&l?c0(l):void 0:n0(J.taskFailure)?J.taskFailure:_==="failed"&&typeof J.taskStatusReason==="string"?c0(J.taskStatusReason):void 0;return{sessionId:q,projectPath:D,gitBranch:N.gitBranch,rootId:J.rootId||q,parentId:J.parentId,relationType:J.relationType,resumedFrom:J.resumedFrom,rootAgentId:J.rootAgentId,resumeDepth:J.resumeDepth,title:J.title,agentType:J.agentType,model:J.model,selectedModelId:K$,permissionMode:V$,reasoningEffort:C$,serviceTier:F$,responseVerbosity:B$,communicationStyle:E0,communicationStyleDigest:b0,projectInstructionsDigest:g0,pendingInteraction:Z,taskStatus:_,taskStatusReason:C0?.message??l??(typeof J.taskStatusReason==="string"?J.taskStatusReason:void 0),taskFailure:C0,taskStartedAt:C?f?.start.startedAt:typeof J.taskStartedAt==="string"?J.taskStartedAt:void 0,taskCompletedAt:C?f?.completion?.completedAt:typeof J.taskCompletedAt==="string"?J.taskCompletedAt:void 0,taskPromptSummary:C?f?C1(f.start.target):"/review uncommitted":typeof J.taskPromptSummary==="string"?J.taskPromptSummary:void 0,taskModelId:w0,taskRetryAvailable:w!==void 0,taskRetriedFrom:y0,taskDelivery:q0,taskIsolation:e,taskSourceProjectPath:y,taskWorktreePath:A?.worktreeRoot,taskWorktreeBranch:A?.branch,taskBaseCommit:A?.baseCommit,taskDiffStat:Y,taskQueuePosition:V0,taskQueueDepth:S0,taskConcurrencyLimit:W,archivedAt:k0,taskOwnerPid:C?void 0:s,taskWorktree:A,taskDispatch:w,messageCount:E,firstMessageTime:$[0].timestamp,lastMessageTime:$.at(-1).timestamp,hasErrors:M||_==="failed",filePath:G}}static toPublicMetadata($){let{filePath:q,taskOwnerPid:x,taskWorktree:G,taskDispatch:N,...J}=$;return J}static getSessionFilePath($,q){return m($,q)}static getSessionCreatedEntry($,q){let x=$.find((G)=>G.type==="session_created");if(!x)throw new Fq(q);return x}static resolveCatalogWorkspace($){if(!F.isAbsolute($))throw Error("Session catalog cwd must be absolute");return F.resolve($)}static validateSessionWorkspace($,q,x){let G=this.getSessionCreatedEntry($,q);if(G.data.sessionId!==q)throw Error(`Session creation record sessionId mismatch: ${q}`);if(!F.isAbsolute(G.cwd)||F.resolve(G.cwd)!==x)throw Error(`Session creation record cwd mismatch: ${q}`)}static resolveForkWorkspace($){if(!F.isAbsolute($))throw Error("Fork workspace paths must be absolute");return F.resolve($)}static parseStoredSession($,q){return Qq($,`session ${q}`)}static isCorruptSessionJSONLError($){return $ instanceof Error&&$.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError($,q){if(!this.isCorruptSessionJSONLError($)||!($ instanceof Error))return $;let x=$.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${q}${x?` at line ${x}`:""}`,{cause:$.cause})}static async readStableSessionSnapshot($,q,x=3){for(let G=0;G<x;G+=1){let N=await L0.stat($),J=await L0.readFile($),L=this.parseStoredSession(J,q),Z=await L0.stat($);if(N.size===Z.size&&N.mtimeNs===Z.mtimeNs&&N.dev===Z.dev&&N.ino===Z.ino)return L}throw Error("Session changed while creating fork; retry the operation")}}function Jq($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}
|
|
100
|
+
export{l0 as yb,T$ as zb,I0 as Ab,Y$ as Bb,p as Cb,i as Db,P1 as Eb,h1 as Fb,D$ as Gb,l1 as Hb,Y0 as Ib,i1 as Jb,P0 as Kb,A$ as Lb,M$ as Mb,c0 as Nb,h as Ob,O0 as Pb,i0 as Qb,d0 as Rb,V2 as Sb,C2 as Tb,m$ as Ub,_0 as Vb,X2 as Wb,r$ as Xb,h$ as Yb,U2 as Zb,o$ as _b,z2 as $b,o2 as ac,t2 as bc,Fq as cc,$0 as dc,P as ec,X as fc};
|
|
@@ -0,0 +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-0affe05f.js";import"./chunk-4dnvydyv.js";import"./chunk-ak7v70sy.js";import"./chunk-vypake1a.js";import"./chunk-xjqcc0nt.js";import"./chunk-rxfmqnf7.js";import"./chunk-m27w377p.js";import"./chunk-5xph8r1k.js";import"./chunk-5sw8j9ae.js";import"./chunk-hpgee5s3.js";import"./chunk-sr2stcda.js";import"./chunk-djh79rde.js";import"./chunk-gcsygn5a.js";import"./chunk-9ka0bdry.js";import"./chunk-vc2c8wkx.js";import"./chunk-kvd5nexw.js";import"./chunk-8472vz3s.js";import"./chunk-f9tahtz6.js";import"./chunk-tffagd03.js";import"./chunk-h0q03x9f.js";import"./chunk-czjbz0fp.js";import"./chunk-c7zk9zj2.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
|
-
import{
|
|
2
|
-
export{q as
|
|
1
|
+
import{Ef as d,Gf as h}from"./chunk-tffagd03.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
|
+
export{q as yc,w as zc};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as a}from"node:module";var c=a(import.meta.url);
|
|
2
|
-
export{c as
|
|
2
|
+
export{c as Vf};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{m as Gq,n as Vq,o as Xq,p as Bq,q as Kq}from"./chunk-ns5015tn.js";import{s as $q}from"./chunk-4v8nxcxp.js";import{F as a,H as o,I as n,K as y,L as t}from"./chunk-ryhk5qmv.js";import"./chunk-4tkn9bky.js";import"./chunk-ktbe458z.js";import{Va as i,Ya as s,hb as r}from"./chunk-72ztan96.js";import"./chunk-095x2ykj.js";import{Tb as S,bc as h}from"./chunk-1p5822w7.js";import"./chunk-vprpk6q1.js";import{uc as qq}from"./chunk-q4fjec99.js";import{wc as Qq,xc as Yq,yc as Zq}from"./chunk-2wp6h1p8.js";import{zc as e}from"./chunk-k106g2p6.js";import"./chunk-65kbckpt.js";import{Zc as v}from"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-sj2w24fe.js";import"./chunk-afhdpen9.js";import"./chunk-5chec8rs.js";import"./chunk-4ypy5bk8.js";import"./chunk-g7p165yz.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import{Ze as m,_e as l}from"./chunk-ah8hky46.js";import{bf as u,df as Q,ef as w,gf as j}from"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as I}from"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import nq from"yargs";import{hideBin as tq}from"yargs/helpers";var g=1;function K(Y){return Q.Object({event_version:Q.Literal(g),...Y})}var Uq=K({type:Q.Literal("content_delta"),delta:Q.String()}),Rq=K({type:Q.Literal("thinking_delta"),delta:Q.String()}),Mq=K({type:Q.Literal("thinking"),content:Q.String()}),Pq=K({type:Q.Literal("stream_end")}),fq=K({type:Q.Literal("content"),content:Q.String()}),Nq=K({type:Q.Literal("structured_output"),output:Q.Record(Q.String(),Q.Unknown()),schema_digest:Q.String({pattern:"^[a-f0-9]{64}$"})}),T=j(["readonly","write","execute"]),Eq=K({type:Q.Literal("tool_start"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T)}),xq=K({type:Q.Literal("tool_progress"),tool_name:Q.String(),message:Q.String(),progress:Q.Optional(Q.Number()),total:Q.Optional(Q.Number())}),Iq=K({type:Q.Literal("tool_result"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T),success:Q.Optional(Q.Boolean()),error_type:Q.Optional(Q.String()),error_message:Q.Optional(Q.String())}),Jq=K({type:Q.Literal("mcp_catalog_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Lq=K({type:Q.Literal("mcp_content_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),content_kind:j(["resources","resource_templates","prompts"]),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Wq=K({type:Q.Literal("mcp_resource_updated"),revision:Q.Integer({minimum:1}),server_name:Q.String(),uri:Q.String()}),Sq=K({type:Q.Literal("mcp_connection_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),phase:j(["reconnecting","recovered","failed"]),reason:Q.String(),attempt:Q.Integer({minimum:0}),max_attempts:Q.Integer({minimum:0}),next_retry_at:Q.Optional(Q.Integer({minimum:0})),error:Q.Optional(Q.String())}),Oq=K({type:Q.Literal("mcp_log"),revision:Q.Integer({minimum:1}),server_name:Q.String(),level:j(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:Q.Optional(Q.String()),message:Q.String(),projected_bytes:Q.Integer({minimum:0}),data_sha256:Q.String(),truncated:Q.Boolean(),details_omitted:Q.Boolean(),timestamp:Q.Integer({minimum:0}),synthetic:Q.Optional(Q.Boolean())}),hq=K({type:Q.Literal("mcp_instructions_changed"),revision:Q.Integer({minimum:0}),server_name:Q.String(),action:j(["added","removed"]),reason:j(["snapshot","connection","disconnection"]),text:Q.Optional(Q.String()),source_bytes:Q.Optional(Q.Integer({minimum:0})),projected_bytes:Q.Optional(Q.Integer({minimum:0})),sha256:Q.Optional(Q.String()),truncated:Q.Optional(Q.Boolean()),details_omitted:Q.Optional(Q.Boolean())}),Cq=K({type:Q.Literal("mcp_task_changed"),revision:Q.Integer({minimum:0}),task_id:Q.String(),server_name:Q.String(),tool_name:Q.String(),status:j(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:Q.Optional(Q.String()),created_at:Q.Integer({minimum:0}),updated_at:Q.Integer({minimum:0}),completed_at:Q.Optional(Q.Integer({minimum:0})),has_result:Q.Boolean(),error:Q.Optional(Q.String())}),kq=K({type:Q.Literal("project_rules_loaded"),files:Q.Array(Q.Object({id:Q.String(),relative_path:Q.String(),source:j(["project","local"]),conditional:Q.Boolean(),content_sha256:Q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:Q.Array(Q.String()),blocked_write:Q.Boolean()}),Fq=K({type:Q.Literal("user_shell_started"),execution_id:Q.String(),command:Q.String(),auxiliary:Q.Boolean()}),wq=K({type:Q.Literal("user_shell_output"),execution_id:Q.String(),stream:j(["stdout","stderr"]),chunk:Q.String(),stream_truncated:Q.Boolean()}),yq=K({type:Q.Literal("user_shell_completed"),execution_id:Q.String(),message_id:Q.String(),status:j(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:Q.Union([Q.Integer(),Q.Null()]),duration_ms:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),truncated:Q.Boolean(),auxiliary:Q.Boolean()}),gq=K({type:Q.Literal("phase"),phase:j(["turn","searching","inspecting","target_hit","executing","completed"]),status:j(["ongoing","hit","done"]),message:Q.String(),turn:Q.Optional(Q.Number()),tool_name:Q.Optional(Q.String()),target:Q.Optional(Q.String())}),Tq=K({type:Q.Literal("tool_detail"),tool_name:Q.String(),detail:Q.String()}),cq=K({type:Q.Literal("task_update"),tasks:Q.Array(y)}),dq=K({type:Q.Literal("goal"),state:j(["updated","cleared"]),goal_id:Q.Optional(Q.String()),status:Q.Optional(j(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:Q.Optional(Q.Integer({minimum:1})),verification_status:Q.Optional(j(["pending","pass","fail","partial"])),verifier_session_id:Q.Optional(Q.String()),verification_evidence_sha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))}),pq=K({type:Q.Literal("subagent"),state:j(["spawned","completed"]),session_id:Q.String(),subagent_type:Q.Optional(Q.String()),success:Q.Optional(Q.Boolean()),summary:Q.Optional(Q.String()),verification_verdict:Q.Optional(j(["pass","fail","partial"])),resumed_from:Q.Optional(Q.String()),root_agent_id:Q.Optional(Q.String()),resume_depth:Q.Optional(Q.Integer({minimum:0}))}),mq=K({type:Q.Literal("token_usage"),input_tokens:Q.Number(),output_tokens:Q.Number(),total_tokens:Q.Number(),max_context_tokens:Q.Number(),cache_read_tokens:Q.Optional(Q.Number()),cache_write_tokens:Q.Optional(Q.Number()),cost_usd:Q.Optional(Q.Number())}),uq=K({type:Q.Literal("compacting"),state:j(["started","completed"]),reason:Q.Optional(j(["threshold","context_limit","turn_limit","manual"])),strategy:Q.Optional(j(["llm","fallback","snip"])),outcome:Q.Optional(j(["completed","fallback","failed"])),pre_tokens:Q.Optional(Q.Number({minimum:0})),post_tokens:Q.Optional(Q.Number({minimum:0}))}),lq=K({type:Q.Literal("provider_retry"),phase:j(["scheduled","attempt","recovered","exhausted"]),attempt:Q.Integer({minimum:0}),max_retries:Q.Integer({minimum:0}),reason:j(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:Q.Optional(Q.Integer({minimum:100,maximum:599})),delay_ms:Q.Optional(Q.Integer({minimum:0})),next_retry_at:Q.Optional(Q.Integer({minimum:0}))}),vq=K({type:Q.Literal("provider_stall"),phase:j(["detected","recovered"]),stall_count:Q.Integer({minimum:1}),duration_ms:Q.Integer({minimum:0}),warning_after_ms:Q.Integer({minimum:1}),timeout_ms:Q.Integer({minimum:1}),output_started:Q.Boolean()}),iq=K({type:Q.Literal("turn_limit"),turns_count:Q.Number(),action:Q.Literal("continue")}),sq=K({type:Q.Literal("task_session"),session_id:Q.String(),project_path:Q.String(),source_project_path:Q.String(),isolation:j(["local","worktree"]),worktree_branch:Q.Optional(Q.String()),base_commit:Q.Optional(Q.String())}),rq=K({type:Q.Literal("task_admission"),state:j(["queued","running"]),queue_position:Q.Optional(Q.Integer({minimum:1})),queue_depth:Q.Integer({minimum:0}),in_flight:Q.Integer({minimum:0}),max_concurrent_tasks:Q.Integer({minimum:1})}),aq=K({type:Q.Literal("output"),content:Q.String(),exit_code:Q.Number()}),oq=K({type:Q.Literal("error"),message:Q.String()}),zQ=w(Q.Union([Uq,Rq,Mq,Pq,fq,Nq,Eq,xq,Iq,Jq,Lq,Wq,Sq,Oq,hq,Cq,kq,Fq,wq,yq,gq,Tq,cq,dq,pq,mq,uq,lq,vq,iq,sq,rq,aq,oq]));function c(Y,Z){return{event_version:g,type:Y,...Z}}function eq(Y){if(Y?.signal)return{signal:Y.signal,dispose:()=>{return}};let Z=new AbortController,H=()=>Z.abort("interrupt");return process.once("SIGINT",H),process.once("SIGTERM",H),{signal:Z.signal,dispose:()=>{process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H)}}}var qQ=j(["text","jsonl"]),QQ=Q.Object({headless:Q.Optional(Q.Boolean()),message:Q.Optional(Q.String()),_:Q.Optional(Q.Array(Q.Union([Q.String(),Q.Number()]))),model:Q.Optional(Q.String()),systemPrompt:Q.Optional(Q.String()),appendSystemPrompt:Q.Optional(Q.String()),maxTurns:Q.Optional(Q.Refine(Q.Integer({maximum:l}),(Y)=>Y===-1||Y>0,()=>"must be -1 or a positive integer")),permissionMode:Q.Optional(Q.Enum(m)),mcpConfig:Q.Optional(Q.Array(Q.String())),strictMcpConfig:Q.Optional(Q.Boolean()),sessionId:Q.Optional(Q.String()),allowedTools:Q.Optional(Q.Array(Q.String())),disallowedTools:Q.Optional(Q.Array(Q.String())),agents:Q.Optional(Q.String()),continue:Q.Optional(Q.Boolean()),resume:Q.Optional(Q.Union([Q.String(),Q.Boolean()])),forkSession:Q.Optional(Q.Boolean()),taskIsolation:Q.Optional(j(["local","worktree"])),outputFormat:Q.Optional(qQ),jsonSchema:Q.Optional(Q.String()),outputSchema:Q.Optional(Q.String())});class Dq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Y){this.openedThinking=Y}hasOpenThinking(){return this.openedThinking}completeStream(){let Y={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Y}}function YQ(Y){return Y.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function ZQ(Y){let Z=u(QQ,Y);if(!Z.success)throw Error(`Invalid headless options: ${YQ(Z.error)}`);return Z.data}function $Q(Y){return Y.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(Z)=>{if(!Z.headless)return;let H=await DQ(Z);process.exit(H)})}function D(Y,Z=""){Y.write(`${Z}
|
|
1
|
+
import{m as Gq,n as Vq,o as Xq,p as Bq,q as Kq}from"./chunk-6g2tsx64.js";import{s as $q}from"./chunk-n7hnp8yj.js";import{F as a,H as o,I as n,K as y,L as t}from"./chunk-46nbyp0r.js";import"./chunk-70jrd752.js";import"./chunk-kky5ydtw.js";import{$a as s,Ma as i,ib as r}from"./chunk-0affe05f.js";import"./chunk-4dnvydyv.js";import{Xb as S,fc as h}from"./chunk-ak7v70sy.js";import"./chunk-vypake1a.js";import{yc as qq}from"./chunk-c7va41dk.js";import{Ac as Qq,Bc as Yq,Cc as Zq}from"./chunk-kaa0np37.js";import{Dc as e}from"./chunk-hjvdsrzb.js";import"./chunk-9m80tr4t.js";import{bd as v}from"./chunk-q8f1k8ns.js";import"./chunk-wax3nm7t.js";import"./chunk-xjqcc0nt.js";import"./chunk-rxfmqnf7.js";import"./chunk-ksm02qjh.js";import"./chunk-m27w377p.js";import"./chunk-yann89nx.js";import"./chunk-2j3d4ykq.js";import"./chunk-5xph8r1k.js";import"./chunk-5sw8j9ae.js";import"./chunk-18n15nn8.js";import"./chunk-hpgee5s3.js";import"./chunk-sr2stcda.js";import"./chunk-djh79rde.js";import"./chunk-nfm5j63c.js";import{bf as m,cf as l}from"./chunk-gcsygn5a.js";import{ff as u,hf as Q,if as w,kf as j}from"./chunk-9ka0bdry.js";import"./chunk-vc2c8wkx.js";import{rf as I}from"./chunk-kvd5nexw.js";import"./chunk-8472vz3s.js";import"./chunk-f9tahtz6.js";import"./chunk-tffagd03.js";import"./chunk-698qsvyb.js";import"./chunk-h0q03x9f.js";import"./chunk-czjbz0fp.js";import"./chunk-c7zk9zj2.js";import nq from"yargs";import{hideBin as tq}from"yargs/helpers";var g=1;function K(Y){return Q.Object({event_version:Q.Literal(g),...Y})}var Uq=K({type:Q.Literal("content_delta"),delta:Q.String()}),Rq=K({type:Q.Literal("thinking_delta"),delta:Q.String()}),Mq=K({type:Q.Literal("thinking"),content:Q.String()}),Pq=K({type:Q.Literal("stream_end")}),fq=K({type:Q.Literal("content"),content:Q.String()}),Nq=K({type:Q.Literal("structured_output"),output:Q.Record(Q.String(),Q.Unknown()),schema_digest:Q.String({pattern:"^[a-f0-9]{64}$"})}),T=j(["readonly","write","execute"]),Eq=K({type:Q.Literal("tool_start"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T)}),xq=K({type:Q.Literal("tool_progress"),tool_name:Q.String(),message:Q.String(),progress:Q.Optional(Q.Number()),total:Q.Optional(Q.Number())}),Iq=K({type:Q.Literal("tool_result"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T),success:Q.Optional(Q.Boolean()),error_type:Q.Optional(Q.String()),error_message:Q.Optional(Q.String())}),Jq=K({type:Q.Literal("mcp_catalog_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Lq=K({type:Q.Literal("mcp_content_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),content_kind:j(["resources","resource_templates","prompts"]),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Wq=K({type:Q.Literal("mcp_resource_updated"),revision:Q.Integer({minimum:1}),server_name:Q.String(),uri:Q.String()}),Sq=K({type:Q.Literal("mcp_connection_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),phase:j(["reconnecting","recovered","failed"]),reason:Q.String(),attempt:Q.Integer({minimum:0}),max_attempts:Q.Integer({minimum:0}),next_retry_at:Q.Optional(Q.Integer({minimum:0})),error:Q.Optional(Q.String())}),Oq=K({type:Q.Literal("mcp_log"),revision:Q.Integer({minimum:1}),server_name:Q.String(),level:j(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:Q.Optional(Q.String()),message:Q.String(),projected_bytes:Q.Integer({minimum:0}),data_sha256:Q.String(),truncated:Q.Boolean(),details_omitted:Q.Boolean(),timestamp:Q.Integer({minimum:0}),synthetic:Q.Optional(Q.Boolean())}),hq=K({type:Q.Literal("mcp_instructions_changed"),revision:Q.Integer({minimum:0}),server_name:Q.String(),action:j(["added","removed"]),reason:j(["snapshot","connection","disconnection"]),text:Q.Optional(Q.String()),source_bytes:Q.Optional(Q.Integer({minimum:0})),projected_bytes:Q.Optional(Q.Integer({minimum:0})),sha256:Q.Optional(Q.String()),truncated:Q.Optional(Q.Boolean()),details_omitted:Q.Optional(Q.Boolean())}),Cq=K({type:Q.Literal("mcp_task_changed"),revision:Q.Integer({minimum:0}),task_id:Q.String(),server_name:Q.String(),tool_name:Q.String(),status:j(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:Q.Optional(Q.String()),created_at:Q.Integer({minimum:0}),updated_at:Q.Integer({minimum:0}),completed_at:Q.Optional(Q.Integer({minimum:0})),has_result:Q.Boolean(),error:Q.Optional(Q.String())}),kq=K({type:Q.Literal("project_rules_loaded"),files:Q.Array(Q.Object({id:Q.String(),relative_path:Q.String(),source:j(["project","local"]),conditional:Q.Boolean(),content_sha256:Q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:Q.Array(Q.String()),blocked_write:Q.Boolean()}),Fq=K({type:Q.Literal("user_shell_started"),execution_id:Q.String(),command:Q.String(),auxiliary:Q.Boolean()}),wq=K({type:Q.Literal("user_shell_output"),execution_id:Q.String(),stream:j(["stdout","stderr"]),chunk:Q.String(),stream_truncated:Q.Boolean()}),yq=K({type:Q.Literal("user_shell_completed"),execution_id:Q.String(),message_id:Q.String(),status:j(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:Q.Union([Q.Integer(),Q.Null()]),duration_ms:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),truncated:Q.Boolean(),auxiliary:Q.Boolean()}),gq=K({type:Q.Literal("phase"),phase:j(["turn","searching","inspecting","target_hit","executing","completed"]),status:j(["ongoing","hit","done"]),message:Q.String(),turn:Q.Optional(Q.Number()),tool_name:Q.Optional(Q.String()),target:Q.Optional(Q.String())}),Tq=K({type:Q.Literal("tool_detail"),tool_name:Q.String(),detail:Q.String()}),cq=K({type:Q.Literal("task_update"),tasks:Q.Array(y)}),dq=K({type:Q.Literal("goal"),state:j(["updated","cleared"]),goal_id:Q.Optional(Q.String()),status:Q.Optional(j(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:Q.Optional(Q.Integer({minimum:1})),verification_status:Q.Optional(j(["pending","pass","fail","partial"])),verifier_session_id:Q.Optional(Q.String()),verification_evidence_sha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))}),pq=K({type:Q.Literal("subagent"),state:j(["spawned","completed"]),session_id:Q.String(),subagent_type:Q.Optional(Q.String()),success:Q.Optional(Q.Boolean()),summary:Q.Optional(Q.String()),verification_verdict:Q.Optional(j(["pass","fail","partial"])),resumed_from:Q.Optional(Q.String()),root_agent_id:Q.Optional(Q.String()),resume_depth:Q.Optional(Q.Integer({minimum:0}))}),mq=K({type:Q.Literal("token_usage"),input_tokens:Q.Number(),output_tokens:Q.Number(),total_tokens:Q.Number(),max_context_tokens:Q.Number(),cache_read_tokens:Q.Optional(Q.Number()),cache_write_tokens:Q.Optional(Q.Number()),cost_usd:Q.Optional(Q.Number())}),uq=K({type:Q.Literal("compacting"),state:j(["started","completed"]),reason:Q.Optional(j(["threshold","context_limit","turn_limit","manual"])),strategy:Q.Optional(j(["llm","fallback","snip"])),outcome:Q.Optional(j(["completed","fallback","failed"])),pre_tokens:Q.Optional(Q.Number({minimum:0})),post_tokens:Q.Optional(Q.Number({minimum:0}))}),lq=K({type:Q.Literal("provider_retry"),phase:j(["scheduled","attempt","recovered","exhausted"]),attempt:Q.Integer({minimum:0}),max_retries:Q.Integer({minimum:0}),reason:j(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:Q.Optional(Q.Integer({minimum:100,maximum:599})),delay_ms:Q.Optional(Q.Integer({minimum:0})),next_retry_at:Q.Optional(Q.Integer({minimum:0}))}),vq=K({type:Q.Literal("provider_stall"),phase:j(["detected","recovered"]),stall_count:Q.Integer({minimum:1}),duration_ms:Q.Integer({minimum:0}),warning_after_ms:Q.Integer({minimum:1}),timeout_ms:Q.Integer({minimum:1}),output_started:Q.Boolean()}),iq=K({type:Q.Literal("turn_limit"),turns_count:Q.Number(),action:Q.Literal("continue")}),sq=K({type:Q.Literal("task_session"),session_id:Q.String(),project_path:Q.String(),source_project_path:Q.String(),isolation:j(["local","worktree"]),worktree_branch:Q.Optional(Q.String()),base_commit:Q.Optional(Q.String())}),rq=K({type:Q.Literal("task_admission"),state:j(["queued","running"]),queue_position:Q.Optional(Q.Integer({minimum:1})),queue_depth:Q.Integer({minimum:0}),in_flight:Q.Integer({minimum:0}),max_concurrent_tasks:Q.Integer({minimum:1})}),aq=K({type:Q.Literal("output"),content:Q.String(),exit_code:Q.Number()}),oq=K({type:Q.Literal("error"),message:Q.String()}),zQ=w(Q.Union([Uq,Rq,Mq,Pq,fq,Nq,Eq,xq,Iq,Jq,Lq,Wq,Sq,Oq,hq,Cq,kq,Fq,wq,yq,gq,Tq,cq,dq,pq,mq,uq,lq,vq,iq,sq,rq,aq,oq]));function c(Y,Z){return{event_version:g,type:Y,...Z}}function eq(Y){if(Y?.signal)return{signal:Y.signal,dispose:()=>{return}};let Z=new AbortController,H=()=>Z.abort("interrupt");return process.once("SIGINT",H),process.once("SIGTERM",H),{signal:Z.signal,dispose:()=>{process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H)}}}var qQ=j(["text","jsonl"]),QQ=Q.Object({headless:Q.Optional(Q.Boolean()),message:Q.Optional(Q.String()),_:Q.Optional(Q.Array(Q.Union([Q.String(),Q.Number()]))),model:Q.Optional(Q.String()),systemPrompt:Q.Optional(Q.String()),appendSystemPrompt:Q.Optional(Q.String()),maxTurns:Q.Optional(Q.Refine(Q.Integer({maximum:l}),(Y)=>Y===-1||Y>0,()=>"must be -1 or a positive integer")),permissionMode:Q.Optional(Q.Enum(m)),mcpConfig:Q.Optional(Q.Array(Q.String())),strictMcpConfig:Q.Optional(Q.Boolean()),sessionId:Q.Optional(Q.String()),allowedTools:Q.Optional(Q.Array(Q.String())),disallowedTools:Q.Optional(Q.Array(Q.String())),agents:Q.Optional(Q.String()),continue:Q.Optional(Q.Boolean()),resume:Q.Optional(Q.Union([Q.String(),Q.Boolean()])),forkSession:Q.Optional(Q.Boolean()),taskIsolation:Q.Optional(j(["local","worktree"])),outputFormat:Q.Optional(qQ),jsonSchema:Q.Optional(Q.String()),outputSchema:Q.Optional(Q.String())});class Dq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Y){this.openedThinking=Y}hasOpenThinking(){return this.openedThinking}completeStream(){let Y={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Y}}function YQ(Y){return Y.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function ZQ(Y){let Z=u(QQ,Y);if(!Z.success)throw Error(`Invalid headless options: ${YQ(Z.error)}`);return Z.data}function $Q(Y){return Y.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(Z)=>{if(!Z.headless)return;let H=await DQ(Z);process.exit(H)})}function D(Y,Z=""){Y.write(`${Z}
|
|
2
2
|
`)}function GQ(Y){return`[task] [${Y.status}] ${Y.subject}`}function VQ(){return{requestConfirmation:async(Y)=>Y.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:Y.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function XQ(Y){if(!(Y instanceof Error))return"Unknown error";let V=Y.lastError??Y;if(V.responseBody)try{let b=JSON.parse(V.responseBody)?.error?.message;if(b)return V.statusCode?`${b} (HTTP ${V.statusCode})`:b}catch{}let q=Y.message.match(/Last error:\s*(.+)$/);if(q)return q[1];return Y.message}function BQ(Y){return Y==="jsonl"?"jsonl":"text"}function d(Y,Z){let H=(...V)=>{for(let q of V){let $=Z[q];if(typeof $==="string"&&$.trim()!=="")return $}return};switch(Y){case"Read":case"Edit":case"Write":case"UndoEdit":return H("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return H("notebook_path");case"Grep":return H("path","pattern");case"Glob":return H("pattern");case"WebFetch":return H("url");case"WebSearch":return H("query");case"Bash":return H("command","description");case"Task":return H("description");case"LSP":return H("filePath","operation");case"EnterWorktree":return H("name");case"ExitWorktree":return H("action");default:return}}function KQ(Y,Z,H,V){let q=new Set(["Glob","Grep","WebSearch","LS"]),$=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(Y)&&!V.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(V.targetLocked)return{phase:"executing",status:"hit",message:H?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(q.has(Y))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if($.has(Y))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:V.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function p(Y,Z,H=!1){let V=(q,$)=>{Y.stdout.write(`${JSON.stringify(c(q,$))}
|
|
3
3
|
`)};return{contentDelta(q){if(Z==="jsonl"){V("content_delta",{delta:q});return}if(H)return;Y.stdout.write(q)},thinkingDelta(q,$){if(Z==="jsonl")return V("thinking_delta",{delta:q}),$;if(!$)Y.stderr.write("[thinking] ");return Y.stderr.write(q),!0},thinking(q){if(Z==="jsonl"){V("thinking",{content:q});return}D(Y.stderr,`[thinking] ${q}`)},streamEnd(q,$){if(Z==="jsonl"){V("stream_end",{});return}if($)Y.stderr.write(`
|
|
4
4
|
`);if(q)Y.stdout.write(`
|
|
5
|
-
`)},content(q){if(Z==="jsonl"){V("content",{content:q});return}D(Y.stdout,q)},structuredOutput(q){if(Z==="jsonl"){V("structured_output",{output:q.output,schema_digest:q.schemaDigest});return}D(Y.stdout,JSON.stringify(q.output))},toolStart(q,$,b,z){if(Z==="jsonl"){V("tool_start",{tool_name:q,summary:$,target:b,tool_kind:z});return}D(Y.stderr,`[tool:start] ${$}`)},toolProgress(q,$,b,z){if(Z==="jsonl"){V("tool_progress",{tool_name:q,message:$,progress:b,total:z});return}D(Y.stderr,`[tool:progress] ${q}: ${$}`)},toolResult(q,$,b,z,R){if(Z==="jsonl"){V("tool_result",{tool_name:q,summary:$,target:b,tool_kind:z,success:R?.success,error_type:R?.errorType,error_message:R?.errorMessage});return}D(Y.stderr,`[tool:result] ${$}`)},mcpCatalogChanged(q){if(Z==="jsonl"){V("mcp_catalog_changed",{revision:q.revision,server_name:q.serverName,added:q.added,removed:q.removed,updated:q.updated});return}D(Y.stderr,`[mcp:catalog] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpContentChanged(q){if(Z==="jsonl"){V("mcp_content_changed",{revision:q.revision,server_name:q.serverName,content_kind:q.contentKind==="resourceTemplates"?"resource_templates":q.contentKind,added:q.added,removed:q.removed,updated:q.updated});return}D(Y.stderr,`[mcp:${q.contentKind}] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpResourceUpdated(q){if(Z==="jsonl"){V("mcp_resource_updated",{revision:q.revision,server_name:q.serverName,uri:q.uri});return}D(Y.stderr,`[mcp:resource] r${q.revision} ${q.serverName} updated ${q.uri}`)},mcpConnectionChanged(q){if(Z==="jsonl"){V("mcp_connection_changed",{revision:q.revision,server_name:q.serverName,phase:q.phase,reason:q.reason,attempt:q.attempt,max_attempts:q.maxAttempts,...q.nextRetryAt!==void 0?{next_retry_at:q.nextRetryAt}:{},...q.error?{error:q.error}:{}});return}D(Y.stderr,`[mcp:connection] r${q.revision} ${q.serverName} ${q.phase} ${q.attempt}/${q.maxAttempts}`)},mcpLog(q){if(Z==="jsonl"){V("mcp_log",{revision:q.revision,server_name:q.serverName,level:q.level,logger:q.logger,message:q.message,projected_bytes:q.projectedBytes,data_sha256:q.dataSha256,truncated:q.truncated,details_omitted:q.detailsOmitted,timestamp:q.timestamp,synthetic:q.synthetic});return}D(Y.stderr,`[mcp:log] ${q.level} ${q.serverName}${q.logger?` logger=${q.logger}`:""}: ${q.message}`)},mcpInstructionsChanged(q){if(Z==="jsonl"){V("mcp_instructions_changed",{revision:q.revision,server_name:q.serverName,action:q.action,reason:q.reason,text:q.text,source_bytes:q.sourceBytes,projected_bytes:q.projectedBytes,sha256:q.sha256,truncated:q.truncated,details_omitted:q.detailsOmitted});return}D(Y.stderr,`[mcp:instructions] ${q.action} ${q.serverName}${q.truncated?" (truncated)":""}`)},mcpTaskChanged(q){if(Z==="jsonl"){V("mcp_task_changed",{revision:q.revision,task_id:q.taskId,server_name:q.serverName,tool_name:q.toolName,status:q.status,status_message:q.statusMessage,created_at:q.createdAt,updated_at:q.updatedAt,completed_at:q.completedAt,has_result:q.hasResult,error:q.error});return}D(Y.stderr,`[mcp:task] ${q.taskId} ${q.serverName}/${q.toolName} `+q.status)},projectRulesLoaded(q){if(Z==="jsonl"){V("project_rules_loaded",{files:q.files.map(($)=>({id:$.id,relative_path:$.relativePath,source:$.source,conditional:$.conditional,content_sha256:$.contentSha256})),trigger_paths:q.triggerPaths,blocked_write:q.blockedWrite});return}D(Y.stderr,`[project-rules] loaded ${q.files.length} file(s)${q.blockedWrite?" before write":""}`)},userShellStarted(q,$,b){if(Z==="jsonl"){V("user_shell_started",{execution_id:q,command:$,auxiliary:b});return}D(Y.stderr,`[user-shell:start] ${$}`)},userShellOutput(q,$,b,z){if(Z==="jsonl"){V("user_shell_output",{execution_id:q,stream:$,chunk:b,stream_truncated:z});return}($==="stderr"?Y.stderr:Y.stdout).write(b)},userShellCompleted(q){if(Z==="jsonl"){V("user_shell_completed",{execution_id:q.executionId,message_id:q.messageId,status:q.record.status,exit_code:q.record.exitCode,duration_ms:q.record.durationMs,stdout:q.record.stdout,stderr:q.record.stderr,truncated:q.record.truncated,auxiliary:q.auxiliary});return}D(Y.stderr,`[user-shell:${q.record.status}] exit=${q.record.exitCode??"null"} ${q.record.durationMs}ms`)},phase(q,$,b,z={}){if(Z==="jsonl"){V("phase",{phase:q,status:$,message:b,turn:z.turn,tool_name:z.toolName,target:z.target});return}D(Y.stderr,`[phase:${q}] ${b}`)},toolDetail(q,$){if(Z==="jsonl"){V("tool_detail",{tool_name:q,detail:$});return}D(Y.stderr,$)},taskUpdate(q){if(Z==="jsonl"){V("task_update",{tasks:q});return}for(let $ of q)D(Y.stderr,GQ($))},goal(q){if(Z==="jsonl"){V("goal",{state:q.goal?"updated":"cleared",goal_id:q.goal?.goalId,status:q.goal?.status,verification_attempt:q.goal?.completionVerification?.attempt,verification_status:q.goal?.completionVerification?.status,verifier_session_id:q.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:q.goal?.completionVerification?.evidenceSha256});return}if(q.goal)D(Y.stderr,`[goal:${q.goal.status}] ${q.goal.objective}`);else D(Y.stderr,"[goal:cleared]")},subagent(q){let $=q.kind==="subagent_spawned";if(Z==="jsonl"){V("subagent",{state:$?"spawned":"completed",session_id:q.sessionId,subagent_type:q.type,success:$?void 0:q.success,summary:$?void 0:q.summary,verification_verdict:$?void 0:q.verificationVerdict,resumed_from:q.resumedFrom,root_agent_id:q.rootAgentId,resume_depth:q.resumeDepth});return}D(Y.stderr,`[subagent:${$?"spawned":"completed"}] ${q.sessionId}${q.resumedFrom?` resumed from ${q.resumedFrom}`:""}`)},tokenUsage(q){if(Z==="jsonl"){V("token_usage",{input_tokens:q.inputTokens,output_tokens:q.outputTokens,total_tokens:q.totalTokens,max_context_tokens:q.maxContextTokens,cache_read_tokens:q.cacheReadTokens,cache_write_tokens:q.cacheWriteTokens,cost_usd:q.costUsd});return}D(Y.stderr,`[tokens] in=${q.inputTokens} out=${q.outputTokens} total=${q.totalTokens} / ${q.maxContextTokens}`)},compacting(q){let $=q.phase==="start";if(Z==="jsonl"){V("compacting",{state:$?"started":"completed",reason:q.reason,strategy:q.strategy,outcome:q.outcome,pre_tokens:q.preTokens,post_tokens:q.postTokens});return}D(Y.stderr,$?`[context] compacting started${q.reason?` (${q.reason})`:""}`:`[context] compacting ${q.outcome??"completed"}`)},providerRetry(q){if(Z==="jsonl"){V("provider_retry",{phase:q.phase,attempt:q.attempt,max_retries:q.maxRetries,reason:q.reason,status_code:q.statusCode,delay_ms:q.delayMs,next_retry_at:q.nextRetryAt});return}let $=q.delayMs!==void 0?` in ${Math.max(0,Math.ceil(q.delayMs/1000))}s`:"";D(Y.stderr,`[provider-retry:${q.phase}] ${q.attempt}/${q.maxRetries} ${q.reason}${$}`)},providerStall(q){if(Z==="jsonl"){V("provider_stall",{phase:q.phase,stall_count:q.stallCount,duration_ms:q.durationMs,warning_after_ms:q.warningAfterMs,timeout_ms:q.timeoutMs,output_started:q.outputStarted});return}D(Y.stderr,`[provider-stall:${q.phase}] ${q.durationMs}ms / ${q.timeoutMs}ms`)},turnLimit(q){if(Z==="jsonl"){V("turn_limit",{turns_count:q,action:"continue"});return}D(Y.stderr,`[turn-limit] continuing after ${q} turns`)},taskSession(q){if(Z==="jsonl"){V("task_session",{session_id:q.sessionId,project_path:q.projectPath,source_project_path:q.sourceProjectPath,isolation:q.isolation,worktree_branch:q.worktreeBranch,base_commit:q.baseCommit});return}D(Y.stderr,`[task:${q.isolation}] ${q.sessionId} ${q.sourceProjectPath} -> ${q.projectPath}${q.worktreeBranch?` (${q.worktreeBranch})`:""}`)},taskAdmission(q){if(Z==="jsonl"){V("task_admission",{state:q.state,queue_position:q.queuePosition,queue_depth:q.queueDepth,in_flight:q.inFlight,max_concurrent_tasks:q.maxConcurrentTasks});return}D(Y.stderr,q.state==="queued"?`[task:queued] position ${q.queuePosition??1}/${q.queueDepth} (running ${q.inFlight}/${q.maxConcurrentTasks})`:`[task:running] admitted (running ${q.inFlight}/${q.maxConcurrentTasks})`)},output(q,$=0){if(Z==="jsonl"){V("output",{content:q,exit_code:$});return}D($===0?Y.stdout:Y.stderr,q)},error(q){if(Z==="jsonl"){V("error",{message:q});return}D(Y.stderr,q)}}}async function DQ(Y,Z={stdout:process.stdout,stderr:process.stderr},H){let V="text",q=p(Z,V),$=new Dq,b={targetLocked:!1},z,R,J=eq(H);try{let B=ZQ(Y);V=BQ(B.outputFormat);let P=await Bq(B);q=p(Z,V,Boolean(P)),await Gq();let jq=await Vq(B),A=await Xq(jq);if(A.mode==="output"){if(A.content)q.output(A.content,A.exitCode??0);return A.exitCode??0}let L=A.content.trimStart().startsWith("!")?A.content.trimStart().slice(1).trim():void 0;if(L!==void 0&&B.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(L!==void 0&&P)throw Error("Output schemas cannot be combined with user shell commands");if(B.taskIsolation&&(B.continue||B.resume||B.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:U,messages:C,metadata:k}=await Kq({sessionId:B.sessionId,continue:B.continue,resume:B.resume,forkSession:B.forkSession,fallbackSessionPrefix:"headless"}),E=B.permissionMode??k?.permissionMode??"yolo",F=B.model&&B.model!=="inherit"?B.model:v()?.id,_=B.taskIsolation?await $q.createSessionTask({sessionId:U,prompt:A.content,sourceProjectPath:I(),isolation:B.taskIsolation,dispatch:{version:1,prompt:A.content,sourceProjectPath:I(),isolation:B.taskIsolation,permissionMode:E,...F?{modelId:F}:{},...P?{outputSchema:P}:{}}}):void 0,M=_?.metadata.projectPath??k?.projectPath??I();if(!_)await h.setSessionPermissionMode(U,M,E);let bq=_?!1:await r.cancelPendingNonInteractive(M,U);if(_)q.taskSession({sessionId:U,projectPath:M,sourceProjectPath:_.metadata.taskSourceProjectPath??I(),isolation:B.taskIsolation,worktreeBranch:_.metadata.taskWorktreeBranch,baseCommit:_.metadata.taskBaseCommit}),R=s.subscribe((G)=>{if(G.type!=="task.status"||G.sessionId!==U||G.projectPath!==M||!["queued","running"].includes(String(G.properties.taskStatus))||typeof G.properties.taskQueueDepth!=="number"||typeof G.properties.taskInFlight!=="number"||typeof G.properties.taskConcurrencyLimit!=="number")return;q.taskAdmission({state:G.properties.taskStatus,queuePosition:typeof G.properties.taskQueuePosition==="number"?G.properties.taskQueuePosition:void 0,queueDepth:G.properties.taskQueueDepth,inFlight:G.properties.taskInFlight,maxConcurrentTasks:G.properties.taskConcurrencyLimit})});let Hq={messages:bq?await h.loadSessionModelContext(U,M):[...C],userId:"cli-user",sessionId:U,workspaceRoot:M,permissionMode:E,signal:J.signal,..._?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:VQ()};if(z=await a.create({sessionId:U,workspaceRoot:M,modelId:B.model,permissionMode:E,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig,agents:B.agents?e(B.agents):void 0,..._?.taskWorktree?{taskWorktree:_.taskWorktree}:{},..._?.metadata.taskIsolation?{taskIsolation:_.metadata.taskIsolation}:{},...C.length>0?{sessionStart:{isResume:!0,resumeSessionId:U}}:{}}),L!==void 0){let G=await z.executeUserShellCommand(L,{signal:J.signal,onEvent:(X)=>{if(X.type==="started")q.userShellStarted(X.executionId,X.command,X.auxiliary);else if(X.type==="output")q.userShellOutput(X.executionId,X.stream,X.chunk,X.streamTruncated)}});return q.userShellCompleted(G),G.record.status==="completed"?0:G.record.status==="aborted"?130:G.record.exitCode??1}let zq=B.maxTurns??z.getConfig().maxTurns,_q=_?.taskWorktree?[...new Set([...B.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:B.disallowedTools,Aq=await t.createWithRuntime(z,{sessionId:U,systemPrompt:B.systemPrompt,appendSystemPrompt:B.appendSystemPrompt,maxTurns:B.maxTurns,modelId:B.model,permissionMode:E,toolWhitelist:B.allowedTools,toolBlacklist:_q,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig}),O=await i(Aq.chatStream(A.content,Hq,{stream:!0,signal:J.signal,maxTurns:B.maxTurns,outputSchema:P,...zq===-1?{onTurnLimitReached:async(G)=>{return q.turnLimit(G.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(G)=>{switch(G.kind){case"content_delta":if(!P||V==="jsonl")$.markAssistantContent();q.contentDelta(G.delta);break;case"thinking_delta":$.setThinkingOpened(q.thinkingDelta(G.delta,$.hasOpenThinking()));break;case"stream_end":{let X=$.completeStream();q.streamEnd(X.wroteAssistantContent,X.openedThinking);break}case"tool_start":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),N=o(X.function.name,f),x=d(X.function.name,f),W=KQ(X.function.name,N,x,b);if(W.shouldLockTarget)b.targetLocked=!0;q.phase(W.phase,W.status,W.message,{toolName:X.function.name,target:x}),q.toolStart(X.function.name,N,x,G.toolKind)}catch{q.phase(b.targetLocked?"executing":"searching",b.targetLocked?"hit":"ongoing",b.targetLocked?`Working within target: ${X.function.name}`:`Still searching: ${X.function.name}`,{toolName:X.function.name}),q.toolStart(X.function.name,X.function.name,void 0,G.toolKind)}break}case"tool_progress":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;q.toolProgress(X.function.name,G.update.message,G.update.progress,G.update.total);break}case"tool_result":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;let f;try{let x=JSON.parse(X.function.arguments);f=d(X.function.name,x)}catch{f=void 0}let N=n(X.function.name,G.result);if(q.toolResult(X.function.name,N.summary,f,void 0,{success:G.result.success,errorType:G.result.error?.type,errorMessage:G.result.error?.message}),N.detail)q.toolDetail(X.function.name,N.detail);break}case"token_usage":q.tokenUsage(G.usage);break;case"compaction":q.compacting(G);break;case"task_update":q.taskUpdate(G.tasks);break;case"structured_output":q.structuredOutput(G);break;case"mcp_catalog_changed":q.mcpCatalogChanged(G);break;case"mcp_content_changed":q.mcpContentChanged(G);break;case"mcp_resource_updated":q.mcpResourceUpdated(G);break;case"mcp_connection_changed":q.mcpConnectionChanged(G);break;case"mcp_log":q.mcpLog(G);break;case"mcp_instructions_changed":q.mcpInstructionsChanged(G);break;case"mcp_task_changed":q.mcpTaskChanged(G);break;case"project_rules_loaded":q.projectRulesLoaded(G);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":q.goal(G);break;case"subagent_spawned":case"subagent_completed":q.subagent(G);break;case"model_fallback":break;case"provider_retry":q.providerRetry(G);break;case"provider_stall":q.providerStall(G);break;case"turn_start":if(G.turn===1)b.targetLocked=!1;q.phase("turn",b.targetLocked?"hit":"ongoing",`Turn ${G.turn} started`,{turn:G.turn});break;default:{let X=G}}});if(O.metadata?.outputTruncated)q.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!O.success)return q.error(`Error: ${O.error?.message??"Agent execution failed"}`),1;return q.phase("completed","done","Headless run completed"),0}catch(B){if($.hasOpenThinking()&&V==="text")Z.stderr.write(`
|
|
5
|
+
`)},content(q){if(Z==="jsonl"){V("content",{content:q});return}D(Y.stdout,q)},structuredOutput(q){if(Z==="jsonl"){V("structured_output",{output:q.output,schema_digest:q.schemaDigest});return}D(Y.stdout,JSON.stringify(q.output))},toolStart(q,$,b,z){if(Z==="jsonl"){V("tool_start",{tool_name:q,summary:$,target:b,tool_kind:z});return}D(Y.stderr,`[tool:start] ${$}`)},toolProgress(q,$,b,z){if(Z==="jsonl"){V("tool_progress",{tool_name:q,message:$,progress:b,total:z});return}D(Y.stderr,`[tool:progress] ${q}: ${$}`)},toolResult(q,$,b,z,R){if(Z==="jsonl"){V("tool_result",{tool_name:q,summary:$,target:b,tool_kind:z,success:R?.success,error_type:R?.errorType,error_message:R?.errorMessage});return}D(Y.stderr,`[tool:result] ${$}`)},mcpCatalogChanged(q){if(Z==="jsonl"){V("mcp_catalog_changed",{revision:q.revision,server_name:q.serverName,added:q.added,removed:q.removed,updated:q.updated});return}D(Y.stderr,`[mcp:catalog] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpContentChanged(q){if(Z==="jsonl"){V("mcp_content_changed",{revision:q.revision,server_name:q.serverName,content_kind:q.contentKind==="resourceTemplates"?"resource_templates":q.contentKind,added:q.added,removed:q.removed,updated:q.updated});return}D(Y.stderr,`[mcp:${q.contentKind}] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpResourceUpdated(q){if(Z==="jsonl"){V("mcp_resource_updated",{revision:q.revision,server_name:q.serverName,uri:q.uri});return}D(Y.stderr,`[mcp:resource] r${q.revision} ${q.serverName} updated ${q.uri}`)},mcpConnectionChanged(q){if(Z==="jsonl"){V("mcp_connection_changed",{revision:q.revision,server_name:q.serverName,phase:q.phase,reason:q.reason,attempt:q.attempt,max_attempts:q.maxAttempts,...q.nextRetryAt!==void 0?{next_retry_at:q.nextRetryAt}:{},...q.error?{error:q.error}:{}});return}D(Y.stderr,`[mcp:connection] r${q.revision} ${q.serverName} ${q.phase} ${q.attempt}/${q.maxAttempts}`)},mcpLog(q){if(Z==="jsonl"){V("mcp_log",{revision:q.revision,server_name:q.serverName,level:q.level,logger:q.logger,message:q.message,projected_bytes:q.projectedBytes,data_sha256:q.dataSha256,truncated:q.truncated,details_omitted:q.detailsOmitted,timestamp:q.timestamp,synthetic:q.synthetic});return}D(Y.stderr,`[mcp:log] ${q.level} ${q.serverName}${q.logger?` logger=${q.logger}`:""}: ${q.message}`)},mcpInstructionsChanged(q){if(Z==="jsonl"){V("mcp_instructions_changed",{revision:q.revision,server_name:q.serverName,action:q.action,reason:q.reason,text:q.text,source_bytes:q.sourceBytes,projected_bytes:q.projectedBytes,sha256:q.sha256,truncated:q.truncated,details_omitted:q.detailsOmitted});return}D(Y.stderr,`[mcp:instructions] ${q.action} ${q.serverName}${q.truncated?" (truncated)":""}`)},mcpTaskChanged(q){if(Z==="jsonl"){V("mcp_task_changed",{revision:q.revision,task_id:q.taskId,server_name:q.serverName,tool_name:q.toolName,status:q.status,status_message:q.statusMessage,created_at:q.createdAt,updated_at:q.updatedAt,completed_at:q.completedAt,has_result:q.hasResult,error:q.error});return}D(Y.stderr,`[mcp:task] ${q.taskId} ${q.serverName}/${q.toolName} `+q.status)},projectRulesLoaded(q){if(Z==="jsonl"){V("project_rules_loaded",{files:q.files.map(($)=>({id:$.id,relative_path:$.relativePath,source:$.source,conditional:$.conditional,content_sha256:$.contentSha256})),trigger_paths:q.triggerPaths,blocked_write:q.blockedWrite});return}D(Y.stderr,`[project-rules] loaded ${q.files.length} file(s)${q.blockedWrite?" before write":""}`)},userShellStarted(q,$,b){if(Z==="jsonl"){V("user_shell_started",{execution_id:q,command:$,auxiliary:b});return}D(Y.stderr,`[user-shell:start] ${$}`)},userShellOutput(q,$,b,z){if(Z==="jsonl"){V("user_shell_output",{execution_id:q,stream:$,chunk:b,stream_truncated:z});return}($==="stderr"?Y.stderr:Y.stdout).write(b)},userShellCompleted(q){if(Z==="jsonl"){V("user_shell_completed",{execution_id:q.executionId,message_id:q.messageId,status:q.record.status,exit_code:q.record.exitCode,duration_ms:q.record.durationMs,stdout:q.record.stdout,stderr:q.record.stderr,truncated:q.record.truncated,auxiliary:q.auxiliary});return}D(Y.stderr,`[user-shell:${q.record.status}] exit=${q.record.exitCode??"null"} ${q.record.durationMs}ms`)},phase(q,$,b,z={}){if(Z==="jsonl"){V("phase",{phase:q,status:$,message:b,turn:z.turn,tool_name:z.toolName,target:z.target});return}D(Y.stderr,`[phase:${q}] ${b}`)},toolDetail(q,$){if(Z==="jsonl"){V("tool_detail",{tool_name:q,detail:$});return}D(Y.stderr,$)},taskUpdate(q){if(Z==="jsonl"){V("task_update",{tasks:q});return}for(let $ of q)D(Y.stderr,GQ($))},goal(q){if(Z==="jsonl"){V("goal",{state:q.goal?"updated":"cleared",goal_id:q.goal?.goalId,status:q.goal?.status,verification_attempt:q.goal?.completionVerification?.attempt,verification_status:q.goal?.completionVerification?.status,verifier_session_id:q.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:q.goal?.completionVerification?.evidenceSha256});return}if(q.goal)D(Y.stderr,`[goal:${q.goal.status}] ${q.goal.objective}`);else D(Y.stderr,"[goal:cleared]")},subagent(q){let $=q.kind==="subagent_spawned";if(Z==="jsonl"){V("subagent",{state:$?"spawned":"completed",session_id:q.sessionId,subagent_type:q.type,success:$?void 0:q.success,summary:$?void 0:q.summary,verification_verdict:$?void 0:q.verificationVerdict,resumed_from:q.resumedFrom,root_agent_id:q.rootAgentId,resume_depth:q.resumeDepth});return}D(Y.stderr,`[subagent:${$?"spawned":"completed"}] ${q.sessionId}${q.resumedFrom?` resumed from ${q.resumedFrom}`:""}`)},tokenUsage(q){if(Z==="jsonl"){V("token_usage",{input_tokens:q.inputTokens,output_tokens:q.outputTokens,total_tokens:q.totalTokens,max_context_tokens:q.maxContextTokens,cache_read_tokens:q.cacheReadTokens,cache_write_tokens:q.cacheWriteTokens,cost_usd:q.costUsd});return}D(Y.stderr,`[tokens] in=${q.inputTokens} out=${q.outputTokens} total=${q.totalTokens} / ${q.maxContextTokens}`)},compacting(q){let $=q.phase==="start";if(Z==="jsonl"){V("compacting",{state:$?"started":"completed",reason:q.reason,strategy:q.strategy,outcome:q.outcome,pre_tokens:q.preTokens,post_tokens:q.postTokens});return}D(Y.stderr,$?`[context] compacting started${q.reason?` (${q.reason})`:""}`:`[context] compacting ${q.outcome??"completed"}`)},providerRetry(q){if(Z==="jsonl"){V("provider_retry",{phase:q.phase,attempt:q.attempt,max_retries:q.maxRetries,reason:q.reason,status_code:q.statusCode,delay_ms:q.delayMs,next_retry_at:q.nextRetryAt});return}let $=q.delayMs!==void 0?` in ${Math.max(0,Math.ceil(q.delayMs/1000))}s`:"";D(Y.stderr,`[provider-retry:${q.phase}] ${q.attempt}/${q.maxRetries} ${q.reason}${$}`)},providerStall(q){if(Z==="jsonl"){V("provider_stall",{phase:q.phase,stall_count:q.stallCount,duration_ms:q.durationMs,warning_after_ms:q.warningAfterMs,timeout_ms:q.timeoutMs,output_started:q.outputStarted});return}D(Y.stderr,`[provider-stall:${q.phase}] ${q.durationMs}ms / ${q.timeoutMs}ms`)},turnLimit(q){if(Z==="jsonl"){V("turn_limit",{turns_count:q,action:"continue"});return}D(Y.stderr,`[turn-limit] continuing after ${q} turns`)},taskSession(q){if(Z==="jsonl"){V("task_session",{session_id:q.sessionId,project_path:q.projectPath,source_project_path:q.sourceProjectPath,isolation:q.isolation,worktree_branch:q.worktreeBranch,base_commit:q.baseCommit});return}D(Y.stderr,`[task:${q.isolation}] ${q.sessionId} ${q.sourceProjectPath} -> ${q.projectPath}${q.worktreeBranch?` (${q.worktreeBranch})`:""}`)},taskAdmission(q){if(Z==="jsonl"){V("task_admission",{state:q.state,queue_position:q.queuePosition,queue_depth:q.queueDepth,in_flight:q.inFlight,max_concurrent_tasks:q.maxConcurrentTasks});return}D(Y.stderr,q.state==="queued"?`[task:queued] position ${q.queuePosition??1}/${q.queueDepth} (running ${q.inFlight}/${q.maxConcurrentTasks})`:`[task:running] admitted (running ${q.inFlight}/${q.maxConcurrentTasks})`)},output(q,$=0){if(Z==="jsonl"){V("output",{content:q,exit_code:$});return}D($===0?Y.stdout:Y.stderr,q)},error(q){if(Z==="jsonl"){V("error",{message:q});return}D(Y.stderr,q)}}}async function DQ(Y,Z={stdout:process.stdout,stderr:process.stderr},H){let V="text",q=p(Z,V),$=new Dq,b={targetLocked:!1},z,R,J=eq(H);try{let B=ZQ(Y);V=BQ(B.outputFormat);let P=await Bq(B);q=p(Z,V,Boolean(P)),await Gq();let jq=await Vq(B),A=await Xq(jq);if(A.mode==="output"){if(A.content)q.output(A.content,A.exitCode??0);return A.exitCode??0}let L=A.content.trimStart().startsWith("!")?A.content.trimStart().slice(1).trim():void 0;if(L!==void 0&&B.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(L!==void 0&&P)throw Error("Output schemas cannot be combined with user shell commands");if(B.taskIsolation&&(B.continue||B.resume||B.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:U,messages:C,metadata:k}=await Kq({sessionId:B.sessionId,continue:B.continue,resume:B.resume,forkSession:B.forkSession,fallbackSessionPrefix:"headless"}),E=B.permissionMode??k?.permissionMode??"yolo",F=B.model&&B.model!=="inherit"?B.model:v()?.id,_=B.taskIsolation?await $q.createSessionTask({sessionId:U,prompt:A.content,sourceProjectPath:I(),isolation:B.taskIsolation,dispatch:{version:1,prompt:A.content,sourceProjectPath:I(),isolation:B.taskIsolation,permissionMode:E,...F?{modelId:F}:{},...P?{outputSchema:P}:{}}}):void 0,M=_?.metadata.projectPath??k?.projectPath??I();if(!_)await h.setSessionPermissionMode(U,M,E);let bq=_?!1:await r.cancelPendingNonInteractive(M,U);if(_)q.taskSession({sessionId:U,projectPath:M,sourceProjectPath:_.metadata.taskSourceProjectPath??I(),isolation:B.taskIsolation,worktreeBranch:_.metadata.taskWorktreeBranch,baseCommit:_.metadata.taskBaseCommit}),R=i.subscribe((G)=>{if(G.type!=="task.status"||G.sessionId!==U||G.projectPath!==M||!["queued","running"].includes(String(G.properties.taskStatus))||typeof G.properties.taskQueueDepth!=="number"||typeof G.properties.taskInFlight!=="number"||typeof G.properties.taskConcurrencyLimit!=="number")return;q.taskAdmission({state:G.properties.taskStatus,queuePosition:typeof G.properties.taskQueuePosition==="number"?G.properties.taskQueuePosition:void 0,queueDepth:G.properties.taskQueueDepth,inFlight:G.properties.taskInFlight,maxConcurrentTasks:G.properties.taskConcurrencyLimit})});let Hq={messages:bq?await h.loadSessionModelContext(U,M):[...C],userId:"cli-user",sessionId:U,workspaceRoot:M,permissionMode:E,signal:J.signal,..._?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:VQ()};if(z=await a.create({sessionId:U,workspaceRoot:M,modelId:B.model,permissionMode:E,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig,agents:B.agents?e(B.agents):void 0,..._?.taskWorktree?{taskWorktree:_.taskWorktree}:{},..._?.metadata.taskIsolation?{taskIsolation:_.metadata.taskIsolation}:{},...C.length>0?{sessionStart:{isResume:!0,resumeSessionId:U}}:{}}),L!==void 0){let G=await z.executeUserShellCommand(L,{signal:J.signal,onEvent:(X)=>{if(X.type==="started")q.userShellStarted(X.executionId,X.command,X.auxiliary);else if(X.type==="output")q.userShellOutput(X.executionId,X.stream,X.chunk,X.streamTruncated)}});return q.userShellCompleted(G),G.record.status==="completed"?0:G.record.status==="aborted"?130:G.record.exitCode??1}let zq=B.maxTurns??z.getConfig().maxTurns,_q=_?.taskWorktree?[...new Set([...B.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:B.disallowedTools,Aq=await t.createWithRuntime(z,{sessionId:U,systemPrompt:B.systemPrompt,appendSystemPrompt:B.appendSystemPrompt,maxTurns:B.maxTurns,modelId:B.model,permissionMode:E,toolWhitelist:B.allowedTools,toolBlacklist:_q,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig}),O=await s(Aq.chatStream(A.content,Hq,{stream:!0,signal:J.signal,maxTurns:B.maxTurns,outputSchema:P,...zq===-1?{onTurnLimitReached:async(G)=>{return q.turnLimit(G.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(G)=>{switch(G.kind){case"content_delta":if(!P||V==="jsonl")$.markAssistantContent();q.contentDelta(G.delta);break;case"thinking_delta":$.setThinkingOpened(q.thinkingDelta(G.delta,$.hasOpenThinking()));break;case"stream_end":{let X=$.completeStream();q.streamEnd(X.wroteAssistantContent,X.openedThinking);break}case"tool_start":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),N=o(X.function.name,f),x=d(X.function.name,f),W=KQ(X.function.name,N,x,b);if(W.shouldLockTarget)b.targetLocked=!0;q.phase(W.phase,W.status,W.message,{toolName:X.function.name,target:x}),q.toolStart(X.function.name,N,x,G.toolKind)}catch{q.phase(b.targetLocked?"executing":"searching",b.targetLocked?"hit":"ongoing",b.targetLocked?`Working within target: ${X.function.name}`:`Still searching: ${X.function.name}`,{toolName:X.function.name}),q.toolStart(X.function.name,X.function.name,void 0,G.toolKind)}break}case"tool_progress":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;q.toolProgress(X.function.name,G.update.message,G.update.progress,G.update.total);break}case"tool_result":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;let f;try{let x=JSON.parse(X.function.arguments);f=d(X.function.name,x)}catch{f=void 0}let N=n(X.function.name,G.result);if(q.toolResult(X.function.name,N.summary,f,void 0,{success:G.result.success,errorType:G.result.error?.type,errorMessage:G.result.error?.message}),N.detail)q.toolDetail(X.function.name,N.detail);break}case"token_usage":q.tokenUsage(G.usage);break;case"compaction":q.compacting(G);break;case"task_update":q.taskUpdate(G.tasks);break;case"structured_output":q.structuredOutput(G);break;case"mcp_catalog_changed":q.mcpCatalogChanged(G);break;case"mcp_content_changed":q.mcpContentChanged(G);break;case"mcp_resource_updated":q.mcpResourceUpdated(G);break;case"mcp_connection_changed":q.mcpConnectionChanged(G);break;case"mcp_log":q.mcpLog(G);break;case"mcp_instructions_changed":q.mcpInstructionsChanged(G);break;case"mcp_task_changed":q.mcpTaskChanged(G);break;case"project_rules_loaded":q.projectRulesLoaded(G);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":q.goal(G);break;case"subagent_spawned":case"subagent_completed":q.subagent(G);break;case"model_fallback":break;case"provider_retry":q.providerRetry(G);break;case"provider_stall":q.providerStall(G);break;case"turn_start":if(G.turn===1)b.targetLocked=!1;q.phase("turn",b.targetLocked?"hit":"ongoing",`Turn ${G.turn} started`,{turn:G.turn});break;default:{let X=G}}});if(O.metadata?.outputTruncated)q.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!O.success)return q.error(`Error: ${O.error?.message??"Agent execution failed"}`),1;return q.phase("completed","done","Headless run completed"),0}catch(B){if($.hasOpenThinking()&&V==="text")Z.stderr.write(`
|
|
6
6
|
`);return q.error(`Error: ${XQ(B)}`),1}finally{R?.();try{await z?.dispose()}finally{J.dispose()}}}async function cQ(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:H,"output-format":V,"system-prompt":q,"append-system-prompt":$,"max-turns":b,...z}=qq,R=nq(tq(process.argv)).scriptName("blade").strict(!1).options(z).middleware([Yq,Qq,Zq]);return $Q(R),await R.parse(),!0}export{DQ as runHeadless,cQ as handleHeadlessMode,QQ as HeadlessOptionsSchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as y,g as A,h as C,i as D}from"./chunk-x0g7y97q.js";import"./chunk-abtq0kjb.js";import"./chunk-2kpynwxa.js";import"./chunk-tw0eh910.js";import"./chunk-n7hnp8yj.js";import"./chunk-46nbyp0r.js";import"./chunk-70jrd752.js";import"./chunk-kky5ydtw.js";import"./chunk-0affe05f.js";import"./chunk-4dnvydyv.js";import"./chunk-ak7v70sy.js";import"./chunk-vypake1a.js";import"./chunk-9m80tr4t.js";import{$c as q}from"./chunk-q8f1k8ns.js";import"./chunk-wax3nm7t.js";import"./chunk-xjqcc0nt.js";import"./chunk-rxfmqnf7.js";import"./chunk-ksm02qjh.js";import"./chunk-m27w377p.js";import"./chunk-yann89nx.js";import"./chunk-2j3d4ykq.js";import"./chunk-5xph8r1k.js";import"./chunk-5sw8j9ae.js";import"./chunk-18n15nn8.js";import"./chunk-hpgee5s3.js";import"./chunk-sr2stcda.js";import"./chunk-djh79rde.js";import"./chunk-nfm5j63c.js";import"./chunk-gcsygn5a.js";import"./chunk-9ka0bdry.js";import"./chunk-vc2c8wkx.js";import"./chunk-kvd5nexw.js";import"./chunk-8472vz3s.js";import"./chunk-f9tahtz6.js";import"./chunk-tffagd03.js";import"./chunk-698qsvyb.js";import"./chunk-h0q03x9f.js";import"./chunk-czjbz0fp.js";import"./chunk-c7zk9zj2.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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{M as
|
|
1
|
+
import{Vf as F}from"./chunk-c7zk9zj2.js";import{execSync as G}from"node:child_process";import*as C from"node:os";import*as v from"node:path";function H(k){return v.resolve(k).replace(/[/\\]/g,"-").replace(/:/g,"_")}function M(k){let q=k.replace(/_/g,":");if(q.startsWith("-"))q="/"+q.slice(1);return q.replace(/-/g,"/")}function z(k){let q=H(k);return v.join(E(),"projects",q)}function J(k){return typeof k==="string"&&k!=="."&&k!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(k)}function A(k){if(!J(k))throw Error(`Invalid session ID: ${k}`)}function N(k,q){return A(q),v.join(z(k),`${q}.jsonl`)}function O(k,q){return A(q),v.join(z(k),`${q}.inbox.json`)}function Q(k,q){return A(q),v.join(z(k),`${q}.goal.json`)}function T(k){try{return G("git rev-parse --abbrev-ref HEAD",{cwd:k,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E(){return process.env.BLADE_STORAGE_ROOT||v.join(C.homedir(),".blade")}async function U(){let{readdir:k}=await import("node:fs/promises");try{let q=v.join(E(),"projects");return(await k(q,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}
|
|
2
|
+
export{M as Lf,z as Mf,J as Nf,A as Of,N as Pf,O as Qf,Q as Rf,T as Sf,E as Tf,U as Uf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Df as a,Ef as b,Ff as c,Gf as d,Hf as e,If as f}from"./chunk-tffagd03.js";import"./chunk-c7zk9zj2.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Tf as j}from"./chunk-czjbz0fp.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 ke,I as le,M as me,V as ne,h as oe};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as xf,p as yf,u as zf,S as Af,c as Bf,l as Cf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var r;((t)=>{t.DEFAULT="default";t.AUTO_EDIT="autoEdit";t.YOLO="yolo";t.PLAN="plan"})(r||={});var N=100;function _(n){return Number.isInteger(n)&&n>=-1&&n<=100}function u(){return"-1, 0, or an integer from 1 to 100"}
|
|
2
|
-
export{r as
|
|
2
|
+
export{r as bf,N as cf,_ as df,u as ef};
|
|
@@ -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 Kf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{O as
|
|
1
|
+
import{ee as W}from"./chunk-18n15nn8.js";import{cf as V}from"./chunk-gcsygn5a.js";import{ff as F,hf as k,kf as H}from"./chunk-9ka0bdry.js";var $=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),Q=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),b=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(Q),disallowedTools:k.Optional(Q),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(H(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1,maximum:V})),isolation:k.Optional(H(["none","worktree"]))},{additionalProperties:!1});function O(Y){let w;try{w=JSON.parse(Y)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let I=Object.entries(w);if(I.length>64)throw Error("--agents supports at most 64 definitions");return I.map(([z,Z])=>{if(!F($,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let K=F(b,Z);if(!K.success)throw Error(`Invalid --agents definition for "${z}"`);let q=K.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:W(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
|
|
2
|
+
export{O as Dc};
|