blade-code 0.10.35 → 0.10.36
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-09qkatb5.js +10 -0
- package/dist/{chunk-0g7cjx1t.js → chunk-0dj2qm8a.js} +1 -1
- package/dist/{chunk-vpe44cnj.js → chunk-0evyrnx0.js} +2 -2
- package/dist/{chunk-b7xdtjh8.js → chunk-0m4s8r87.js} +358 -356
- package/dist/{chunk-wmvj44cr.js → chunk-1raz6s2b.js} +2 -2
- package/dist/{chunk-9h41rm97.js → chunk-1t8ebwsp.js} +2 -2
- package/dist/{chunk-nwtgx6p6.js → chunk-250vpvr5.js} +1 -1
- package/dist/{chunk-132q0hyf.js → chunk-2mvp3rqw.js} +2 -2
- package/dist/chunk-3pxn6gcj.js +1 -0
- package/dist/{chunk-pmxqjb29.js → chunk-3rjmkaey.js} +1 -1
- package/dist/{chunk-0zs3mn75.js → chunk-4bbnytq5.js} +1 -1
- package/dist/chunk-4f1g8f6q.js +1 -0
- package/dist/{chunk-7m5az521.js → chunk-4s0c6tkd.js} +1 -1
- package/dist/{chunk-aytg9gw0.js → chunk-4vq34v09.js} +2 -2
- package/dist/chunk-515mkr66.js +44 -0
- package/dist/chunk-5c5qh3ab.js +1 -0
- package/dist/{chunk-pgy1mtgw.js → chunk-5cgyevqj.js} +1 -1
- package/dist/chunk-5vkxcjn1.js +1 -0
- package/dist/chunk-5xc50n8e.js +1 -0
- package/dist/{chunk-znp4bexg.js → chunk-6360fg4j.js} +1 -1
- package/dist/{chunk-031n82db.js → chunk-6gcmfvfj.js} +2 -2
- package/dist/{chunk-t1zs40rj.js → chunk-6jpspf3v.js} +2 -2
- package/dist/chunk-738a282r.js +1 -0
- package/dist/{chunk-k5gv2phs.js → chunk-7c5tnz4y.js} +1 -1
- package/dist/{chunk-4en93rc4.js → chunk-8ft7j7aw.js} +1 -1
- package/dist/chunk-8m87dnk2.js +1 -0
- package/dist/{chunk-38ca5c9f.js → chunk-93jx06kq.js} +1 -1
- package/dist/{chunk-3nn4rth6.js → chunk-95k17p11.js} +1 -1
- package/dist/{chunk-2kzg80r3.js → chunk-95n8g52h.js} +1 -1
- package/dist/{chunk-rwtgrs8d.js → chunk-99ywfge1.js} +1 -1
- package/dist/{chunk-zj29g9rc.js → chunk-9g6rzbcv.js} +2 -2
- package/dist/{chunk-r84jsjnc.js → chunk-a7pvtxvz.js} +1 -1
- package/dist/{chunk-pf8rybpm.js → chunk-acw8q8w9.js} +2 -2
- package/dist/{chunk-xf03b657.js → chunk-atsw605q.js} +1 -1
- package/dist/{chunk-rcp5maxt.js → chunk-cc7dmst6.js} +3 -3
- package/dist/{chunk-015fx09x.js → chunk-ck5tvxkj.js} +2 -2
- package/dist/{chunk-hq8cbzfv.js → chunk-ckfc7j7m.js} +1 -1
- package/dist/chunk-cnctwxqn.js +1 -0
- package/dist/{chunk-ck9r8h1h.js → chunk-e23sz81n.js} +2 -2
- package/dist/chunk-e5yage6p.js +1 -0
- package/dist/{chunk-2y4qyct0.js → chunk-ekzck3x7.js} +1 -1
- package/dist/{chunk-83w81bma.js → chunk-g510tpqt.js} +1 -1
- package/dist/{chunk-a1wjgf44.js → chunk-gy8esxaa.js} +2 -2
- package/dist/chunk-hh158y4e.js +6 -0
- package/dist/{chunk-ytec29ph.js → chunk-hq18c6r9.js} +1 -1
- package/dist/{chunk-6v51xb9r.js → chunk-hq1wrf1g.js} +1 -1
- package/dist/chunk-j2tmdkmw.js +1 -0
- package/dist/{chunk-q30azbe2.js → chunk-m2w03hpc.js} +1 -1
- package/dist/{chunk-0hdsbwhf.js → chunk-m6dh31kb.js} +2 -2
- package/dist/{chunk-6b1vvq1f.js → chunk-n4555gej.js} +1 -1
- package/dist/{chunk-4s6w24r3.js → chunk-phgqzja3.js} +2 -2
- package/dist/chunk-psgt2pq7.js +6 -0
- package/dist/{chunk-7jja0242.js → chunk-q15qd9x4.js} +1 -1
- package/dist/chunk-q3r0zfec.js +1 -0
- package/dist/{chunk-d4hcy6p1.js → chunk-qgez5vw6.js} +1 -1
- package/dist/{chunk-qf357j45.js → chunk-qggnvzkc.js} +2 -2
- package/dist/{chunk-sqp79c1a.js → chunk-qvdcesry.js} +2 -2
- package/dist/{chunk-y5kp6fmy.js → chunk-qwrdss51.js} +1 -1
- package/dist/{chunk-hymw69m4.js → chunk-qxvk42rf.js} +1 -1
- package/dist/{chunk-6r9jb465.js → chunk-rshbnfr8.js} +4 -4
- package/dist/chunk-rv6kca90.js +1 -0
- package/dist/{chunk-4ncddyay.js → chunk-s4enbe93.js} +1 -1
- package/dist/chunk-thstqcg3.js +2 -0
- package/dist/{chunk-eqj58q4r.js → chunk-v11r4ahz.js} +1 -1
- package/dist/chunk-ve7kp9rr.js +1 -0
- package/dist/chunk-xf2kjb9a.js +1 -0
- package/dist/{chunk-gg179pdx.js → chunk-xrhtwcd0.js} +1 -1
- package/dist/{chunk-sbyyg6qg.js → chunk-y990fa4r.js} +3 -3
- package/dist/{chunk-3qmawdwf.js → chunk-y9nq48st.js} +2 -2
- package/dist/{chunk-1jagjybs.js → chunk-zwt7f9ab.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-39wa7cfr.js +0 -1
- package/dist/chunk-51b7jb2s.js +0 -1
- package/dist/chunk-7cbe8yjn.js +0 -1
- package/dist/chunk-cz1hb799.js +0 -1
- package/dist/chunk-dbwa9rwr.js +0 -6
- package/dist/chunk-fbxgxwfm.js +0 -1
- package/dist/chunk-gcyd5s5h.js +0 -1
- package/dist/chunk-h7v23pw2.js +0 -1
- package/dist/chunk-hk36a59x.js +0 -1
- package/dist/chunk-js5whev4.js +0 -44
- package/dist/chunk-mkmcwc5r.js +0 -1
- package/dist/chunk-pn2e99pn.js +0 -1
- package/dist/chunk-qhfbdp5e.js +0 -1
- package/dist/chunk-r9j56qcs.js +0 -1
- package/dist/chunk-se9krwes.js +0 -6
- package/dist/chunk-tencwrxf.js +0 -1
- package/dist/chunk-wf7ycftn.js +0 -1
- package/dist/chunk-z45qe8dg.js +0 -2
- package/dist/chunk-zhr1btfv.js +0 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
import{La as J,sa as V,ua as W,va as O}from"./chunk-
|
|
1
|
+
import{La as J,sa as V,ua as W,va as O}from"./chunk-95k17p11.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as Q}from"./chunk-6360fg4j.js";import"./chunk-qvdcesry.js";import"./chunk-y9nq48st.js";import"./chunk-4s0c6tkd.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Rf as i}from"./chunk-qvdcesry.js";import{kg as o,mg as C,og as L,sg as j,tg as n}from"./chunk-y9nq48st.js";import{ug as I}from"./chunk-4s0c6tkd.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
|
|
2
2
|
`),W=!_.endsWith(`
|
|
3
3
|
`),$=[];for(let[H,k]of R.entries())try{let M=V_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E=await V.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map(x).join(`
|
|
4
4
|
`)}
|
|
@@ -113,4 +113,4 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
|
113
113
|
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
114
114
|
WHERE parts_fts MATCH ?
|
|
115
115
|
ORDER BY timestamp DESC LIMIT ?`,M=_.prepare(k);return R?M.all(H,R,W):M.all(H,W)}
|
|
116
|
-
export{w as
|
|
116
|
+
export{w as Cc,q_ as Dc,y_ as Ec,z as Fc,Y as Gc,y as Hc,$_ as Ic,z_ as Jc,k_ as Kc,f_ as Lc,r as Mc,K_ as Nc,U_ as Oc,B_ as Pc,A_ as Qc,n_ as Rc,i_ as Sc,d_ as Tc};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{m as fq,n as Eq,o as Iq,p as Lq,q as Wq,r as Sq}from"./chunk-m2w03hpc.js";import{t as Jq,u as o,v as n,w as t,x as m,y as e}from"./chunk-q15qd9x4.js";import{L as Uq,N as _q,O as Mq,Q as Zq,S as Pq}from"./chunk-0m4s8r87.js";import"./chunk-7c5tnz4y.js";import"./chunk-95k17p11.js";import{Va as zq,ib as jq,rb as Hq}from"./chunk-y990fa4r.js";import"./chunk-5cgyevqj.js";import{Zb as Gq,bc as Dq,mc as g,xc as v}from"./chunk-6gcmfvfj.js";import"./chunk-qgez5vw6.js";import"./chunk-phgqzja3.js";import{Uc as Aq}from"./chunk-1t8ebwsp.js";import{Wc as xq,Xc as Rq,Yc as bq}from"./chunk-hh158y4e.js";import{Zc as Nq}from"./chunk-qggnvzkc.js";import"./chunk-0evyrnx0.js";import{xd as Bq}from"./chunk-e23sz81n.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-4vq34v09.js";import"./chunk-6jpspf3v.js";import"./chunk-3rjmkaey.js";import"./chunk-acw8q8w9.js";import"./chunk-9g6rzbcv.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-ckfc7j7m.js";import"./chunk-cc7dmst6.js";import"./chunk-v11r4ahz.js";import"./chunk-515mkr66.js";import{Af as Xq}from"./chunk-a7pvtxvz.js";import{Bf as Kq,Df as q,Ef as qq,Gf as j}from"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as h}from"./chunk-6360fg4j.js";import"./chunk-qvdcesry.js";import"./chunk-2mvp3rqw.js";import"./chunk-g510tpqt.js";import"./chunk-gy8esxaa.js";import"./chunk-m6dh31kb.js";import"./chunk-0dj2qm8a.js";import"./chunk-y9nq48st.js";import"./chunk-4s0c6tkd.js";import RZ from"yargs";import{hideBin as bZ}from"yargs/helpers";function p($,V,D){if($.off){$.off(V,D);return}$.removeListener?.(V,D)}function Tq($,V){if(!$.once&&!$.on||!$.off&&!$.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((D,Q)=>{let Z=!1,Y=()=>{p($,"drain",M),p($,"error",_),V.removeEventListener("abort",x)},H=(b)=>{if(Z)return;Z=!0,Y(),b()},M=()=>H(D),_=(b)=>H(()=>Q(b??Error("Writable emitted an error"))),x=()=>H(()=>Q(V.reason??Error("Writable drain aborted")));if(V.aborted){x();return}let R=$.once?.bind($)??$.on?.bind($);R?.("drain",M),R?.("error",_),V.addEventListener("abort",x,{once:!0})})}async function gq($,V,D){if($.destroyed||$.writableEnded)throw Error("Writable is already closed");if($.write(V)===!1)await Tq($,D)}class u{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new m("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor($,V={}){this.options=V;let D=(Q)=>new e({maxPendingItems:V.maxPendingItems??o,maxPendingBytes:V.maxPendingBytes??n,writeTimeoutMs:V.writeTimeoutMs??t,sizeOf:(Z)=>Buffer.byteLength(Z),write:(Z,Y)=>gq($[Q],Z,Y),onFailure:(Z)=>this.fail(Z)});if(this.queues={stdout:D("stdout"),stderr:D("stderr")},this.observeSinkErrors($.stdout),$.stderr!==$.stdout)this.observeSinkErrors($.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write($,V){return this.queues[$].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close($){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close($),this.queues.stderr.close($)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors($){if(!$.on||!$.off&&!$.removeListener)return;let V=(D)=>{this.fail(new m("write_failed","Headless writable failed",{cause:D??Error("Writable emitted an error")}))};$.on("error",V),this.sinkErrorListeners.push({writer:$,listener:V})}fail($){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close($),this.queues.stderr.close($),this.options.onFailure?.($)}removeSinkErrorListeners(){for(let{writer:$,listener:V}of this.sinkErrorListeners.splice(0))p($,"error",V)}}var $q=1;function z($){return q.Object({event_version:q.Literal($q),...$})}var wq=z({type:q.Literal("content_delta"),delta:q.String()}),cq=z({type:q.Literal("thinking_delta"),delta:q.String()}),dq=z({type:q.Literal("thinking"),content:q.String()}),mq=z({type:q.Literal("stream_end")}),pq=z({type:q.Literal("content"),content:q.String()}),uq=z({type:q.Literal("structured_output"),output:q.Record(q.String(),q.Unknown()),schema_digest:q.String({pattern:"^[a-f0-9]{64}$"})}),l=j(["readonly","write","execute"]),lq=q.Object({kind:l,scope:j(["global","session"]),queue_position:q.Integer({minimum:1}),in_flight:q.Integer({minimum:0}),limit:q.Integer({minimum:1})}),vq=z({type:q.Literal("tool_start"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(l)}),sq=z({type:q.Literal("tool_progress"),tool_name:q.String(),message:q.String(),progress:q.Optional(q.Number()),total:q.Optional(q.Number()),admission:q.Optional(lq)}),iq=q.Object({auto_backgrounded:q.Literal(!0),background_reason:q.Literal("foreground_budget"),foreground_budget_ms:q.Integer({minimum:1}),shell_id:q.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:q.Optional(q.Integer({minimum:1})),terminal_transport:j(["local","acp"])}),aq=z({type:q.Literal("tool_result"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(l),success:q.Optional(q.Boolean()),error_type:q.Optional(q.String()),error_message:q.Optional(q.String()),background:q.Optional(iq)}),rq=z({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())}),oq=z({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())}),nq=z({type:q.Literal("mcp_resource_updated"),revision:q.Integer({minimum:1}),server_name:q.String(),uri:q.String()}),tq=z({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())}),eq=z({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())}),qZ=z({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())}),ZZ=z({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())}),$Z=z({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()}),VZ=z({type:q.Literal("user_shell_started"),execution_id:q.String(),command:q.String(),auxiliary:q.Boolean()}),YZ=z({type:q.Literal("user_shell_output"),execution_id:q.String(),stream:j(["stdout","stderr"]),chunk:q.String(),stream_truncated:q.Boolean()}),QZ=z({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()}),XZ=z({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())}),KZ=z({type:q.Literal("tool_detail"),tool_name:q.String(),detail:q.String()}),BZ=z({type:q.Literal("task_update"),tasks:q.Array(Zq)}),GZ=z({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}$"}))}),DZ=z({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}))}),zZ=z({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())}),jZ=z({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}))}),HZ=z({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}))}),UZ=z({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()}),_Z=z({type:q.Literal("action_stationarity"),phase:j(["detected","recovered","halted"]),tool_name:q.String(),run_length:q.Integer({minimum:1}),nudge_threshold:q.Integer({minimum:1}),halt_threshold:q.Integer({minimum:1}),progress_aware:q.Boolean()}),MZ=z({type:q.Literal("turn_limit"),turns_count:q.Number(),action:q.Literal("continue")}),PZ=z({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())}),NZ=z({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})}),AZ=z({type:q.Literal("output"),content:q.String(),exit_code:q.Number()}),xZ=z({type:q.Literal("error"),message:q.String()}),pZ=qq(q.Union([wq,cq,dq,mq,pq,uq,vq,sq,aq,rq,oq,nq,tq,eq,qZ,ZZ,$Z,VZ,YZ,QZ,XZ,KZ,BZ,GZ,DZ,zZ,jZ,HZ,UZ,_Z,MZ,PZ,NZ,AZ,xZ]));function Vq($,V){return{event_version:$q,type:$,...V}}function JZ($){if(!$||typeof $!=="object"||Array.isArray($))return;let V=$;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function fZ($){let V=new AbortController,D=(Y)=>{if(!V.signal.aborted)V.abort(Y)},Q=()=>D("interrupt"),Z=()=>D($?.signal?.reason);if($?.signal){if($.signal.addEventListener("abort",Z,{once:!0}),$.signal.aborted)Z()}else process.once("SIGINT",Q),process.once("SIGTERM",Q);return{signal:V.signal,abort:D,dispose:()=>{$?.signal?.removeEventListener("abort",Z),process.removeListener("SIGINT",Q),process.removeListener("SIGTERM",Q)}}}var EZ=j(["text","jsonl"]),IZ=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()),verificationAgent:q.Optional(q.Boolean()),maxTurns:q.Optional(q.Refine(q.Integer(),($)=>$===-1||$>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:q.Optional(q.Enum(Xq)),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(EZ),jsonSchema:q.Optional(q.String()),outputSchema:q.Optional(q.String())});class Cq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened($){this.openedThinking=$}hasOpenThinking(){return this.openedThinking}completeStream(){let $={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,$}}function LZ($){return $.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function WZ($){let V=Kq(IZ,$);if(!V.success)throw Error(`Invalid headless options: ${LZ(V.error)}`);return V.data}function SZ($){return $.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.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("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).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(V)=>{if(!V.headless)return;let D=await yZ(V);process.exit(D)})}function U($,V=""){$.write(`${V}
|
|
2
|
+
`)}function CZ($){return`[task] [${$.status}] ${$.subject}`}function OZ(){return{requestConfirmation:async($)=>$.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:$.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function hZ($){if(!($ instanceof Error))return"Unknown error";let Q=$.lastError??$;if(Q.responseBody)try{let H=JSON.parse(Q.responseBody)?.error?.message;if(H)return Q.statusCode?`${H} (HTTP ${Q.statusCode})`:H}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function kZ($){return $==="jsonl"?"jsonl":"text"}function Yq($,V){let D=(...Q)=>{for(let Z of Q){let Y=V[Z];if(typeof Y==="string"&&Y.trim()!=="")return Y}return};switch($){case"Read":case"Edit":case"Write":case"UndoEdit":return D("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return D("notebook_path");case"Grep":return D("path","pattern");case"Glob":return D("pattern");case"WebFetch":return D("url");case"WebSearch":return D("query");case"Bash":return D("command","description");case"Task":return D("description");case"LSP":return D("filePath","operation");case"EnterWorktree":return D("name");case"ExitWorktree":return D("action");default:return}}function FZ($,V,D,Q){let Z=new Set(["Glob","Grep","WebSearch","LS"]),Y=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has($)&&!Q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(Q.targetLocked)return{phase:"executing",status:"hit",message:D?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(Z.has($))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Y.has($))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:Q.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function Qq($,V,D=!1){let Q=(Z,Y)=>{$.stdout.write(`${JSON.stringify(Vq(Z,Y))}
|
|
3
|
+
`)};return{contentDelta(Z){if(V==="jsonl"){Q("content_delta",{delta:Z});return}if(D)return;$.stdout.write(Z)},thinkingDelta(Z,Y){if(V==="jsonl")return Q("thinking_delta",{delta:Z}),Y;if(!Y)$.stderr.write("[thinking] ");return $.stderr.write(Z),!0},thinking(Z){if(V==="jsonl"){Q("thinking",{content:Z});return}U($.stderr,`[thinking] ${Z}`)},streamEnd(Z,Y){if(V==="jsonl"){Q("stream_end",{});return}if(Y)$.stderr.write(`
|
|
4
|
+
`);if(Z)$.stdout.write(`
|
|
5
|
+
`)},content(Z){if(V==="jsonl"){Q("content",{content:Z});return}U($.stdout,Z)},structuredOutput(Z){if(V==="jsonl"){Q("structured_output",{output:Z.output,schema_digest:Z.schemaDigest});return}U($.stdout,JSON.stringify(Z.output))},toolStart(Z,Y,H,M){if(V==="jsonl"){Q("tool_start",{tool_name:Z,summary:Y,target:H,tool_kind:M});return}U($.stderr,`[tool:start] ${Y}`)},toolProgress(Z,Y,H,M,_){if(V==="jsonl"){Q("tool_progress",{tool_name:Z,message:Y,progress:H,total:M,admission:_?{kind:_.kind,scope:_.scope,queue_position:_.queuePosition,in_flight:_.inFlight,limit:_.limit}:void 0});return}U($.stderr,`[tool:progress] ${Z}: ${Y}`)},toolResult(Z,Y,H,M,_){if(V==="jsonl"){Q("tool_result",{tool_name:Z,summary:Y,target:H,tool_kind:M,success:_?.success,error_type:_?.errorType,error_message:_?.errorMessage,background:_?.background});return}U($.stderr,`[tool:result] ${Y}`)},mcpCatalogChanged(Z){if(V==="jsonl"){Q("mcp_catalog_changed",{revision:Z.revision,server_name:Z.serverName,added:Z.added,removed:Z.removed,updated:Z.updated});return}U($.stderr,`[mcp:catalog] r${Z.revision} ${Z.serverName} +${Z.added.length} -${Z.removed.length} ~${Z.updated.length}`)},mcpContentChanged(Z){if(V==="jsonl"){Q("mcp_content_changed",{revision:Z.revision,server_name:Z.serverName,content_kind:Z.contentKind==="resourceTemplates"?"resource_templates":Z.contentKind,added:Z.added,removed:Z.removed,updated:Z.updated});return}U($.stderr,`[mcp:${Z.contentKind}] r${Z.revision} ${Z.serverName} +${Z.added.length} -${Z.removed.length} ~${Z.updated.length}`)},mcpResourceUpdated(Z){if(V==="jsonl"){Q("mcp_resource_updated",{revision:Z.revision,server_name:Z.serverName,uri:Z.uri});return}U($.stderr,`[mcp:resource] r${Z.revision} ${Z.serverName} updated ${Z.uri}`)},mcpConnectionChanged(Z){if(V==="jsonl"){Q("mcp_connection_changed",{revision:Z.revision,server_name:Z.serverName,phase:Z.phase,reason:Z.reason,attempt:Z.attempt,max_attempts:Z.maxAttempts,...Z.nextRetryAt!==void 0?{next_retry_at:Z.nextRetryAt}:{},...Z.error?{error:Z.error}:{}});return}U($.stderr,`[mcp:connection] r${Z.revision} ${Z.serverName} ${Z.phase} ${Z.attempt}/${Z.maxAttempts}`)},mcpLog(Z){if(V==="jsonl"){Q("mcp_log",{revision:Z.revision,server_name:Z.serverName,level:Z.level,logger:Z.logger,message:Z.message,projected_bytes:Z.projectedBytes,data_sha256:Z.dataSha256,truncated:Z.truncated,details_omitted:Z.detailsOmitted,timestamp:Z.timestamp,synthetic:Z.synthetic});return}U($.stderr,`[mcp:log] ${Z.level} ${Z.serverName}${Z.logger?` logger=${Z.logger}`:""}: ${Z.message}`)},mcpInstructionsChanged(Z){if(V==="jsonl"){Q("mcp_instructions_changed",{revision:Z.revision,server_name:Z.serverName,action:Z.action,reason:Z.reason,text:Z.text,source_bytes:Z.sourceBytes,projected_bytes:Z.projectedBytes,sha256:Z.sha256,truncated:Z.truncated,details_omitted:Z.detailsOmitted});return}U($.stderr,`[mcp:instructions] ${Z.action} ${Z.serverName}${Z.truncated?" (truncated)":""}`)},mcpTaskChanged(Z){if(V==="jsonl"){Q("mcp_task_changed",{revision:Z.revision,task_id:Z.taskId,server_name:Z.serverName,tool_name:Z.toolName,status:Z.status,status_message:Z.statusMessage,created_at:Z.createdAt,updated_at:Z.updatedAt,completed_at:Z.completedAt,has_result:Z.hasResult,error:Z.error});return}U($.stderr,`[mcp:task] ${Z.taskId} ${Z.serverName}/${Z.toolName} `+Z.status)},projectRulesLoaded(Z){if(V==="jsonl"){Q("project_rules_loaded",{files:Z.files.map((Y)=>({id:Y.id,relative_path:Y.relativePath,source:Y.source,conditional:Y.conditional,content_sha256:Y.contentSha256})),trigger_paths:Z.triggerPaths,blocked_write:Z.blockedWrite});return}U($.stderr,`[project-rules] loaded ${Z.files.length} file(s)${Z.blockedWrite?" before write":""}`)},userShellStarted(Z,Y,H){if(V==="jsonl"){Q("user_shell_started",{execution_id:Z,command:Y,auxiliary:H});return}U($.stderr,`[user-shell:start] ${Y}`)},userShellOutput(Z,Y,H,M){if(V==="jsonl"){Q("user_shell_output",{execution_id:Z,stream:Y,chunk:H,stream_truncated:M});return}(Y==="stderr"?$.stderr:$.stdout).write(H)},userShellCompleted(Z){if(V==="jsonl"){Q("user_shell_completed",{execution_id:Z.executionId,message_id:Z.messageId,status:Z.record.status,exit_code:Z.record.exitCode,duration_ms:Z.record.durationMs,stdout:Z.record.stdout,stderr:Z.record.stderr,truncated:Z.record.truncated,auxiliary:Z.auxiliary});return}U($.stderr,`[user-shell:${Z.record.status}] exit=${Z.record.exitCode??"null"} ${Z.record.durationMs}ms`)},phase(Z,Y,H,M={}){if(V==="jsonl"){Q("phase",{phase:Z,status:Y,message:H,turn:M.turn,tool_name:M.toolName,target:M.target});return}U($.stderr,`[phase:${Z}] ${H}`)},toolDetail(Z,Y){if(V==="jsonl"){Q("tool_detail",{tool_name:Z,detail:Y});return}U($.stderr,Y)},taskUpdate(Z){if(V==="jsonl"){Q("task_update",{tasks:Z});return}for(let Y of Z)U($.stderr,CZ(Y))},goal(Z){if(V==="jsonl"){Q("goal",{state:Z.goal?"updated":"cleared",goal_id:Z.goal?.goalId,status:Z.goal?.status,verification_attempt:Z.goal?.completionVerification?.attempt,verification_status:Z.goal?.completionVerification?.status,verifier_session_id:Z.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:Z.goal?.completionVerification?.evidenceSha256});return}if(Z.goal)U($.stderr,`[goal:${Z.goal.status}] ${Z.goal.objective}`);else U($.stderr,"[goal:cleared]")},subagent(Z){let Y=Z.kind==="subagent_spawned";if(V==="jsonl"){Q("subagent",{state:Y?"spawned":"completed",session_id:Z.sessionId,subagent_type:Z.type,success:Y?void 0:Z.success,summary:Y?void 0:Z.summary,verification_verdict:Y?void 0:Z.verificationVerdict,resumed_from:Z.resumedFrom,root_agent_id:Z.rootAgentId,resume_depth:Z.resumeDepth});return}U($.stderr,`[subagent:${Y?"spawned":"completed"}] ${Z.sessionId}${Z.resumedFrom?` resumed from ${Z.resumedFrom}`:""}`)},tokenUsage(Z){if(V==="jsonl"){Q("token_usage",{input_tokens:Z.inputTokens,output_tokens:Z.outputTokens,total_tokens:Z.totalTokens,max_context_tokens:Z.maxContextTokens,cache_read_tokens:Z.cacheReadTokens,cache_write_tokens:Z.cacheWriteTokens,cost_usd:Z.costUsd});return}U($.stderr,`[tokens] in=${Z.inputTokens} out=${Z.outputTokens} total=${Z.totalTokens} / ${Z.maxContextTokens}`)},compacting(Z){let Y=Z.phase==="start";if(V==="jsonl"){Q("compacting",{state:Y?"started":"completed",reason:Z.reason,strategy:Z.strategy,outcome:Z.outcome,pre_tokens:Z.preTokens,post_tokens:Z.postTokens});return}U($.stderr,Y?`[context] compacting started${Z.reason?` (${Z.reason})`:""}`:`[context] compacting ${Z.outcome??"completed"}`)},providerRetry(Z){if(V==="jsonl"){Q("provider_retry",{phase:Z.phase,attempt:Z.attempt,max_retries:Z.maxRetries,reason:Z.reason,status_code:Z.statusCode,delay_ms:Z.delayMs,next_retry_at:Z.nextRetryAt});return}let Y=Z.delayMs!==void 0?` in ${Math.max(0,Math.ceil(Z.delayMs/1000))}s`:"";U($.stderr,`[provider-retry:${Z.phase}] ${Z.attempt}/${Z.maxRetries} ${Z.reason}${Y}`)},providerStall(Z){if(V==="jsonl"){Q("provider_stall",{phase:Z.phase,stall_count:Z.stallCount,duration_ms:Z.durationMs,warning_after_ms:Z.warningAfterMs,timeout_ms:Z.timeoutMs,output_started:Z.outputStarted});return}U($.stderr,`[provider-stall:${Z.phase}] ${Z.durationMs}ms / ${Z.timeoutMs}ms`)},actionStationarity(Z){if(V==="jsonl"){Q("action_stationarity",{phase:Z.phase,tool_name:Z.toolName,run_length:Z.runLength,nudge_threshold:Z.nudgeThreshold,halt_threshold:Z.haltThreshold,progress_aware:Z.progressAware});return}U($.stderr,`[action-stationarity:${Z.phase}] ${Z.toolName} ${Z.runLength}/${Z.haltThreshold}`)},turnLimit(Z){if(V==="jsonl"){Q("turn_limit",{turns_count:Z,action:"continue"});return}U($.stderr,`[turn-limit] continuing after ${Z} turns`)},taskSession(Z){if(V==="jsonl"){Q("task_session",{session_id:Z.sessionId,project_path:Z.projectPath,source_project_path:Z.sourceProjectPath,isolation:Z.isolation,worktree_branch:Z.worktreeBranch,base_commit:Z.baseCommit});return}U($.stderr,`[task:${Z.isolation}] ${Z.sessionId} ${Z.sourceProjectPath} -> ${Z.projectPath}${Z.worktreeBranch?` (${Z.worktreeBranch})`:""}`)},taskAdmission(Z){if(V==="jsonl"){Q("task_admission",{state:Z.state,queue_position:Z.queuePosition,queue_depth:Z.queueDepth,in_flight:Z.inFlight,max_concurrent_tasks:Z.maxConcurrentTasks});return}U($.stderr,Z.state==="queued"?`[task:queued] position ${Z.queuePosition??1}/${Z.queueDepth} (running ${Z.inFlight}/${Z.maxConcurrentTasks})`:`[task:running] admitted (running ${Z.inFlight}/${Z.maxConcurrentTasks})`)},output(Z,Y=0){if(V==="jsonl"){Q("output",{content:Z,exit_code:Y});return}U(Y===0?$.stdout:$.stderr,Z)},error(Z){if(V==="jsonl"){Q("error",{message:Z});return}U($.stderr,Z)}}}async function yZ($,V={stdout:process.stdout,stderr:process.stderr},D){let Q="text",Z=new Cq,Y={targetLocked:!1},H,M,_=fZ(D),x=!1,R=new u(V,{signal:_.signal,onFailure:(K)=>{x=!0,_.abort(K)}}),b={stdout:{write:(K)=>R.write("stdout",K)},stderr:{write:(K)=>R.write("stderr",K)}},B=Qq(b,Q),w=async()=>{try{return await R.flush(),!x}catch{return!1}},f=async(K)=>{return M?.(),M=void 0,await w()?K:1};try{let K=WZ($);Q=kZ(K.outputFormat);let E=await Wq(K);B=Qq(b,Q,Boolean(E)),await fq();let s=K.forkSession!==!0&&(K.continue===!0||typeof K.resume==="string"&&K.resume.length>0)?await Iq({message:K.message,_:K._,stdin:D?.stdin}):await Eq({...K,stdin:D?.stdin}),S=s===void 0,N=S?{mode:"agent",content:""}:await Lq(s);if(N.mode==="output"){if(N.content)B.output(N.content,N.exitCode??0);return await f(N.exitCode??0)}let k=N.content.trimStart().startsWith("!")?N.content.trimStart().slice(1).trim():void 0;if(k!==void 0&&K.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(k!==void 0&&E)throw Error("Output schemas cannot be combined with user shell commands");if(K.taskIsolation&&(K.continue||K.resume||K.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:A,messages:i,metadata:a}=await Sq({sessionId:K.sessionId,continue:K.continue,resume:K.resume,forkSession:K.forkSession,fallbackSessionPrefix:"headless"}),C=K.permissionMode??a?.permissionMode??"yolo",r=K.model&&K.model!=="inherit"?K.model:Bq()?.id,P=K.taskIsolation?await Jq.createSessionTask({sessionId:A,prompt:N.content,sourceProjectPath:h(),isolation:K.taskIsolation,dispatch:{version:1,prompt:N.content,sourceProjectPath:h(),isolation:K.taskIsolation,permissionMode:C,...r?{modelId:r}:{},...E?{outputSchema:E}:{}}}):void 0,J=P?.metadata.projectPath??a?.projectPath??h();if(!P)await v.setSessionPermissionMode(A,J,C);let Oq=P?!1:await Hq.cancelPendingNonInteractive(J,A);if(P)B.taskSession({sessionId:A,projectPath:J,sourceProjectPath:P.metadata.taskSourceProjectPath??h(),isolation:K.taskIsolation,worktreeBranch:P.metadata.taskWorktreeBranch,baseCommit:P.metadata.taskBaseCommit}),M=zq.subscribe((X)=>{if(X.type!=="task.status"||X.sessionId!==A||X.projectPath!==J||!["queued","running"].includes(String(X.properties.taskStatus))||typeof X.properties.taskQueueDepth!=="number"||typeof X.properties.taskInFlight!=="number"||typeof X.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:X.properties.taskStatus,queuePosition:typeof X.properties.taskQueuePosition==="number"?X.properties.taskQueuePosition:void 0,queueDepth:X.properties.taskQueueDepth,inFlight:X.properties.taskInFlight,maxConcurrentTasks:X.properties.taskConcurrencyLimit})});let hq={messages:Oq?await v.loadSessionModelContext(A,J):[...i],userId:"cli-user",sessionId:A,workspaceRoot:J,permissionMode:C,signal:_.signal,...P?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:OZ()};H=await Uq.create({sessionId:A,workspaceRoot:J,modelId:K.model,permissionMode:C,mcpConfig:K.mcpConfig,strictMcpConfig:K.strictMcpConfig,agents:K.agents?Nq(K.agents):void 0,...P?.taskWorktree?{taskWorktree:P.taskWorktree}:{},...P?.metadata.taskIsolation?{taskIsolation:P.metadata.taskIsolation}:{},...i.length>0?{sessionStart:{isResume:!0,resumeSessionId:A}}:{}});let F=S&&H.getPendingSteeringCount()>0,y=S&&!F?await H.getGoal():null,c=y?.status==="active"||y?.status==="verifying",I=S&&!F&&!c?await H.getRecoveredFinalResponse():void 0;if(S&&!F&&!c){if(!I)throw Error("No unfinished turn or active goal to resume");if(y)B.goal({kind:"goal_updated",goal:y});if(I.structuredOutput&&I.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:I.structuredOutput,schemaDigest:I.structuredOutputSchemaDigest});else B.content(I.content);return B.phase("completed","done","Recovered headless run completed"),await f(0)}if(k!==void 0){let X=await H.executeUserShellCommand(k,{signal:_.signal,onEvent:async(G)=>{if(G.type==="started")B.userShellStarted(G.executionId,G.command,G.auxiliary);else if(G.type==="output")B.userShellOutput(G.executionId,G.stream,G.chunk,G.streamTruncated);await w()}});return B.userShellCompleted(X),await f(X.record.status==="completed"?0:X.record.status==="aborted"?130:X.record.exitCode??1)}let kq=K.maxTurns??H.getConfig().maxTurns,Fq=P?.taskWorktree?[...new Set([...K.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:K.disallowedTools,yq=await Pq.createWithRuntime(H,{sessionId:A,systemPrompt:K.systemPrompt,appendSystemPrompt:K.appendSystemPrompt,maxTurns:K.maxTurns,modelId:K.model,permissionMode:C,toolWhitelist:K.allowedTools,toolBlacklist:Fq,mcpConfig:K.mcpConfig,strictMcpConfig:K.strictMcpConfig}),d=await jq(yq.chatStream(N.content,hq,{stream:!0,signal:_.signal,maxTurns:K.maxTurns,builtinVerification:K.verificationAgent!==!1,outputSchema:E,pendingInputOnly:F,goalContinuationOnly:c,...kq===-1?{onTurnLimitReached:async(X)=>{return B.turnLimit(X.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(X)=>{switch(X.kind){case"content_delta":if(!E||Q==="jsonl")Z.markAssistantContent();B.contentDelta(X.delta);break;case"thinking_delta":Z.setThinkingOpened(B.thinkingDelta(X.delta,Z.hasOpenThinking()));break;case"stream_end":{let G=Z.completeStream();B.streamEnd(G.wroteAssistantContent,G.openedThinking);break}case"tool_start":{let G=X.toolCall;if(!("function"in G))break;if(G.function.name===g)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(G.function.name))break;try{let L=JSON.parse(G.function.arguments),W=_q(G.function.name,L),O=Yq(G.function.name,L),T=FZ(G.function.name,W,O,Y);if(T.shouldLockTarget)Y.targetLocked=!0;B.phase(T.phase,T.status,T.message,{toolName:G.function.name,target:O}),B.toolStart(G.function.name,W,O,X.toolKind)}catch{B.phase(Y.targetLocked?"executing":"searching",Y.targetLocked?"hit":"ongoing",Y.targetLocked?`Working within target: ${G.function.name}`:`Still searching: ${G.function.name}`,{toolName:G.function.name}),B.toolStart(G.function.name,G.function.name,void 0,X.toolKind)}break}case"tool_progress":{let G=X.toolCall;if(!("function"in G))break;if(G.function.name===g)break;B.toolProgress(G.function.name,X.update.message,X.update.progress,X.update.total,X.update.admission);break}case"tool_result":{let G=X.toolCall;if(!("function"in G))break;if(G.function.name===g)break;let L;try{let O=JSON.parse(G.function.arguments);L=Yq(G.function.name,O)}catch{L=void 0}let W=Dq(Mq(G.function.name,X.result),Gq);if(B.toolResult(G.function.name,W.summary,L,void 0,{success:X.result.success,errorType:X.result.error?.type,errorMessage:X.result.error?.message,background:JZ(X.result.metadata)}),W.detail)B.toolDetail(G.function.name,W.detail);break}case"token_usage":B.tokenUsage(X.usage);break;case"compaction":B.compacting(X);break;case"task_update":B.taskUpdate(X.tasks);break;case"structured_output":B.structuredOutput(X);break;case"mcp_catalog_changed":B.mcpCatalogChanged(X);break;case"mcp_content_changed":B.mcpContentChanged(X);break;case"mcp_resource_updated":B.mcpResourceUpdated(X);break;case"mcp_connection_changed":B.mcpConnectionChanged(X);break;case"mcp_log":B.mcpLog(X);break;case"mcp_instructions_changed":B.mcpInstructionsChanged(X);break;case"mcp_task_changed":B.mcpTaskChanged(X);break;case"project_rules_loaded":B.projectRulesLoaded(X);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":B.goal(X);break;case"subagent_spawned":case"subagent_completed":B.subagent(X);break;case"model_fallback":break;case"provider_retry":B.providerRetry(X);break;case"provider_stall":B.providerStall(X);break;case"action_stationarity":B.actionStationarity(X);break;case"turn_start":if(X.turn===1)Y.targetLocked=!1;B.phase("turn",Y.targetLocked?"hit":"ongoing",`Turn ${X.turn} started`,{turn:X.turn});break;default:{let G=X}}await w()});if(d.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!d.success)return B.error(`Error: ${d.error?.message??"Agent execution failed"}`),await f(1);return B.phase("completed","done","Headless run completed"),await f(0)}catch(K){if(!x){if(Z.hasOpenThinking()&&Q==="text")b.stderr.write(`
|
|
6
|
+
`);B.error(`Error: ${hZ(K)}`)}return await f(1)}finally{M?.();try{await H?.dispose()}finally{R.close(),_.dispose()}}}async function U0(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:D,"output-format":Q,"system-prompt":Z,"append-system-prompt":Y,"max-turns":H,...M}=Aq,_=RZ(bZ(process.argv)).scriptName("blade").strict(!1).options(M).middleware([Rq,xq,bq]);return SZ(_),await _.parse(),!0}export{yZ as runHeadless,U0 as handleHeadlessMode,IZ as HeadlessOptionsSchema};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{I}from"./chunk-
|
|
1
|
+
import{I}from"./chunk-0m4s8r87.js";import{xc as D}from"./chunk-6gcmfvfj.js";import w from"node:path";function C(a){let t=a.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}function P(a){let t=a.replace(/\s+/g," ").trim();return t.length<=500?t:`${t.slice(0,497)}...`}function S(a){return`task/${a.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class z{static async createSessionTask(a){if(!a.prompt.trim())throw Error("Task prompt must not be blank");if(!w.isAbsolute(a.sourceProjectPath))throw Error("Task source project path must be absolute");let t=w.resolve(a.sourceProjectPath),s;try{return s=a.isolation==="worktree"?await I.enter({sessionId:a.sessionId,workspaceRoot:t,name:S(a.sessionId)}):void 0,{metadata:await D.createSessionMetadata(a.sessionId,s?.workspaceRoot??t,{title:a.title?.trim()||C(a.prompt),taskPromptSummary:P(a.prompt),taskDispatch:a.dispatch,taskModelId:a.dispatch?.modelId,selectedModelId:a.dispatch?.modelId,permissionMode:a.dispatch?.permissionMode,reasoningEffort:a.dispatch?.reasoningEffort,serviceTier:a.dispatch?.serviceTier,responseVerbosity:a.dispatch?.responseVerbosity,communicationStyle:a.dispatch?.communicationStyle,communicationStyleDigest:a.dispatch?.communicationStyleDigest,projectInstructionsDigest:a.dispatch?.projectInstructionsDigest,taskRetriedFrom:a.retriedFrom,taskIsolation:a.isolation,taskSourceProjectPath:t,taskWorktree:s}),taskWorktree:s}}catch(k){if(s)await I.exit({sessionId:a.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var N=256,Z=8388608,_=30000;class c extends Error{kind;pendingItems;pendingBytes;constructor(a,t,s){super(t,s);this.kind=a;this.name="BoundedSerialEgressError",this.pendingItems=s?.pendingItems,this.pendingBytes=s?.pendingBytes}}function m(a){a.catch(()=>{return})}class F{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(a){this.options=a;if(this.assertPositiveInteger(a.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(a.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(a.writeTimeoutMs,"writeTimeoutMs"),a.signal?.addEventListener("abort",this.handleAbort,{once:!0}),a.signal?.aborted)this.handleAbort()}offer(a){if(this.closed)return{accepted:!1,error:this.failure??new c("closed","Egress is already closed")};let t;try{t=this.options.sizeOf(a)}catch(i){return this.rejectAdmission(new c("invalid_size","Egress size calculation failed",{cause:i}))}if(!Number.isSafeInteger(t)||t<0)return this.rejectAdmission(new c("invalid_size","Egress size must be a non-negative safe integer"));if(t>this.options.maxPendingBytes)return this.rejectAdmission(new c("oversized",`Egress value requires ${t} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+t>this.options.maxPendingBytes)return this.rejectAdmission(new c("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let s,k,h=new Promise((i,f)=>{s=i,k=f});return m(h),this.nextSequence+=1,this.pending.push({value:a,bytes:t,sequence:this.nextSequence,resolve:s,reject:k,completion:h}),this.pendingBytes+=t,this.startDrain(),{accepted:!0,completion:h}}flush(){if(this.failure){let h=Promise.reject(this.failure);return m(h),h}let a=this.nextSequence;if(a<=this.completedSequence)return Promise.resolve();let t,s,k=new Promise((h,i)=>{t=h,s=i});return m(k),this.flushWaiters.push({targetSequence:a,resolve:t,reject:s}),k}close(a){let t=a instanceof c?a:new c("closed","Egress was closed",{cause:a});this.fail(t)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new c("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(a){return this.fail(a),{accepted:!1,error:a}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let a=this.drain();m(a)}async drain(){try{while(!this.closed){let a=this.pending[0];if(!a)return;try{await this.writeOne(a.value)}catch(t){this.fail(this.normalizeWriteError(t));return}if(this.closed||this.pending[0]!==a)return;this.pending.shift(),this.pendingBytes-=a.bytes,this.completedSequence=a.sequence,a.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(a){let t=new AbortController;this.activeWriteAbort=t;let s,k,h=new Promise((W,T)=>{k=T});m(h),this.activeWriteStop=k;let i=Promise.resolve().then(()=>this.options.write(a,t.signal));m(i);let f=new Promise((W,T)=>{s=setTimeout(()=>{let M=new c("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);t.abort(M),T(M)},this.options.writeTimeoutMs),this.activeWriteTimeout=s});m(f);try{await Promise.race([i,f,h])}finally{if(s!==void 0)clearTimeout(s);if(this.activeWriteTimeout===s)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===t)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(a){if(a instanceof c)return a;return new c("write_failed","Egress write failed",{cause:a})}fail(a){if(this.closed)return;if(a.pendingItems??=this.pending.length,a.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=a,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(a),this.activeWriteStop?.(a),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let t=this.pending.splice(0);this.pendingBytes=0;for(let s of t)s.reject(a);for(let s of this.flushWaiters.splice(0))s.reject(a);try{this.options.onFailure?.(a)}catch{}}settleFlushWaiters(){for(let a=0;a<this.flushWaiters.length;){let t=this.flushWaiters[a];if(t.targetSequence>this.completedSequence){a+=1;continue}this.flushWaiters.splice(a,1),t.resolve()}}assertPositiveInteger(a,t){if(!Number.isSafeInteger(a)||a<=0)throw RangeError(`${t} must be a positive safe integer`)}}
|
|
2
2
|
export{z as t,N as u,Z as v,_ as w,c as x,F as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ig as a}from"./chunk-m6dh31kb.js";import"./chunk-0dj2qm8a.js";import"./chunk-y9nq48st.js";import"./chunk-4s0c6tkd.js";export{a as WorkspaceTrustService};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var f;((c)=>{c.ReadOnly="readonly";c.Write="write";c.Execute="execute"})(f||={});function g(b){return b!==void 0&&typeof b.pattern==="string"&&typeof b.search_path==="string"}function h(b){return b!==void 0&&b.kind==="edit"&&typeof b.matches_found==="number"}function j(b){return b==="readonly"}
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as yc,g as zc,h as Ac,j as Bc};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{Z as
|
|
1
|
+
import{Be as Q}from"./chunk-ckfc7j7m.js";import{Bf as F,Df as k,Gf as G}from"./chunk-93jx06kq.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
|
|
2
|
+
export{Z as Zc};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{sg as j}from"./chunk-y9nq48st.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
|
|
2
2
|
`)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
|
|
3
|
-
export{m as
|
|
3
|
+
export{m as Of,I as Pf,M as Qf,V as Rf,h as Sf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{s as T}from"./chunk-
|
|
1
|
+
import{s as T}from"./chunk-95n8g52h.js";import{t as jz,u as t,v as s,w as e,x as zz,y as Hz}from"./chunk-q15qd9x4.js";import{C as P,L as r,O as a,P as o,S as n,ea as Jz,fa as Qz,ga as Zz,ha as $z}from"./chunk-0m4s8r87.js";import{ra as _z}from"./chunk-7c5tnz4y.js";import"./chunk-95k17p11.js";import{Va as m,ib as l,rb as i}from"./chunk-y990fa4r.js";import{Ab as h}from"./chunk-5cgyevqj.js";import{Tb as g,_b as c,bc as v,jc as S,kc as p,mc as q,pc as d,uc as N,xc as _}from"./chunk-6gcmfvfj.js";import"./chunk-qgez5vw6.js";import"./chunk-phgqzja3.js";import{$c as Gz}from"./chunk-ck5tvxkj.js";import"./chunk-0evyrnx0.js";import"./chunk-e23sz81n.js";import"./chunk-v508x7cg.js";import{Gd as Lz}from"./chunk-atsw605q.js";import"./chunk-4vq34v09.js";import"./chunk-6jpspf3v.js";import{Rd as Bz}from"./chunk-3rjmkaey.js";import"./chunk-acw8q8w9.js";import"./chunk-9g6rzbcv.js";import"./chunk-hq18c6r9.js";import{we as Uz}from"./chunk-zwt7f9ab.js";import"./chunk-ckfc7j7m.js";import"./chunk-cc7dmst6.js";import"./chunk-v11r4ahz.js";import"./chunk-515mkr66.js";import"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import{Hf as y,If as u,Jf as I}from"./chunk-thstqcg3.js";import{Nf as Xz}from"./chunk-6360fg4j.js";import{Rf as x}from"./chunk-qvdcesry.js";import"./chunk-2mvp3rqw.js";import{$f as Fz,Yf as Yz}from"./chunk-g510tpqt.js";import"./chunk-gy8esxaa.js";import"./chunk-m6dh31kb.js";import"./chunk-0dj2qm8a.js";import"./chunk-y9nq48st.js";import"./chunk-4s0c6tkd.js";import{Readable as Ez,Writable as qz}from"node:stream";import*as b from"@agentclientprotocol/sdk";import Wz from"node:path";import{PROTOCOL_VERSION as Pz}from"@agentclientprotocol/sdk";import{RequestError as Az}from"@agentclientprotocol/sdk";import{nanoid as M}from"nanoid";var U=x("Agent");function f(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function Kz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:f(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:f("headers"in z?z.headers:void 0)};return null}function Rz(z){let J={};for(let H of z){let D=Kz(H);if(D)J[H.name]=D}return J}function Dz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,D=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!D)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:D[1]??"image/png",data:D[2]??""}]})}function Nz(z){let J=p(z.metadata);return J?[{type:"text",text:S(J)}]:Dz(z.content)}function Oz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}class E{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,H,D,W={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=D;this.options=W;this.messages=[...W.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(W.permissionMode),this.updateEgress=new Hz({maxPendingItems:t,maxPendingBytes:s,writeTimeoutMs:e,signal:H.signal,sizeOf:(Q)=>Buffer.byteLength(JSON.stringify(Q)),write:async(Q)=>{await H.sessionUpdate(Q)},onFailure:(Q)=>this.handleUpdateEgressFailure(Q)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([_.loadSession(this.id,this.cwd),_.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await _.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return n.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(U.debug(`[AcpSession ${this.id}] Initializing...`),await _.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),P.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(Q)=>{await this.sendUpdateAndWait(Q)}),U.debug(`[AcpSession ${this.id}] ACP service context initialized`),await i.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(Q)=>this.requestPermission(Q)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?Rz(this.options.mcpServers):void 0,H=P.getInstance().getTerminalService(this.id);if(this.runtime=await r.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Q,Z)=>{let X=await H.execute(Q,{cwd:Z.cwd,env:Z.env,timeout:Z.timeoutMs,signal:Z.signal,allowLocalFallback:!1,onOutput:(Y)=>Z.onOutput?.("stdout",Y)});return{exitCode:X.exitCode,stdout:X.stdout,stderr:X.stderr,...X.error?{error:X.error}:{},timedOut:X.failureKind==="timeout",aborted:X.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await T.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Qz(this.cwd),U.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=m.subscribe((Q)=>{if(Q.sessionId!==this.id||Q.projectPath!==this.cwd)return;if(Q.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Q.properties}}),this.schedulePendingResume();return}if(Q.type==="task.delivery"){if(!Q.properties.taskDelivery||typeof Q.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Q.properties.updatedAt==="string"?Q.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Q.properties.taskDelivery,...Q.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Q.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Q.properties.updatedAt==="string"?Q.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Q.properties.taskStatus,...typeof Q.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Q.properties.taskStatusReason}:{},...Q.properties.taskFailure&&typeof Q.properties.taskFailure==="object"?{"blade/taskFailure":Q.properties.taskFailure}:{},...typeof Q.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Q.properties.taskStartedAt}:{},...typeof Q.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Q.properties.taskCompletedAt}:{},...Q.properties.taskDiffStat&&typeof Q.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Q.properties.taskDiffStat}:{},...typeof Q.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Q.properties.taskQueuePosition}:{},...typeof Q.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Q.properties.taskQueueDepth}:{},...typeof Q.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Q.properties.taskConcurrencyLimit}:{},...typeof Q.properties.taskInFlight==="number"?{"blade/taskInFlight":Q.properties.taskInFlight}:{}}})});let W=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||W?.status==="active"||W?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let D of Nz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:D}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);U.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{U.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await this.runtime.rewindSession(Z);return this.messages=[...X.messages],this.contextMessages=await this.loadModelContextOr(X.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),X}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Z)=>{if(await this.setServiceTier(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Z)=>{if(await this.setResponseVerbosity(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Z)=>{if(await this.setCommunicationStyle(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let Y=!1,F,L=(A)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:A.id,status:A.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:A.result?.message||A.result?.error||`Subagent ${A.status}`}}]})},B=this.runtime.resumeSubagent({agentId:Z,prompt:X,onCompleted:(A)=>{if(Y)L(A);else F=A}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.session.id,status:"in_progress",title:`Resuming ${B.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${B.source.id} at depth ${B.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),Y=!0,F)L(F);return B}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,X,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,X,Y)},complete:async(Z,X,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,X,Y)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,X)},getLogs:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,X)},setLoggingLevel:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,X)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let Y=await T.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:X,onEvent:(B)=>{if(B.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.toolCall.id,status:"in_progress",title:`Review: ${B.toolCall.function.name}`,content:[],kind:this.mapToolKind(B.toolKind)});else if(B.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.toolCall.id,status:B.result.success?"completed":"failed",content:[]})}}),F=await Y.completion,L=(await T.list(this.cwd,this.id)).find((B)=>B.start.reviewId===Y.reviewId);if(!L)throw Error(`Review not found: ${Y.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:Y.reviewId,status:F.status,findings:F.findings.length,content:g(L.start,F)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,X,Y)=>{let F=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(Y);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(X,null,2)}}],kind:L})},sendToolResult:(Z,X)=>{if(X.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.summary}})}}},D=await Zz(z,H),W=D.data?.action;if(W==="start_goal"||W==="resume_goal")this.schedulePendingResume();if(W==="rewind_session"&&Array.isArray(D.data?.messages))this.messages=[...D.data.messages],this.contextMessages=await this.loadModelContextOr(D.data.messages);if((D.message==="compact_completed"||D.message==="compact_fallback")&&D.data?.compactedMessages){this.contextMessages=[...D.data.compactedMessages];let Z=await _.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let Q=D.content||D.message;if(Q)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}});if(D.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${D.error}`}});return await this.flushUpdates(),{stopReason:D.success?"end_turn":"cancelled"}}catch(H){return U.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=$z(this.cwd),J=["model","permissions","theme","config","exit","ide"],D=z.filter((W)=>!J.includes(W.name)).map((W)=>{let Q;if(W.usage){let Z=W.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Q=Z}if(W.aliases?.length){let Z=`Aliases: ${W.aliases.join(", ")}`;Q=Q?`${Q} | ${Z}`:Z}return{name:W.name,description:W.description,input:Q?{hint:Q}:void 0}});U.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(D.map((W)=>W.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:D}),U.info(`[AcpSession ${this.id}] Sent ${D.length} available commands`)}catch(z){U.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(P.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),D=H.content,W=H.displayText,Q=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((L)=>L.outputSchema)?.outputSchema:void 0),Z;if(Q!==void 0)Z=d(Q).schema;if(W.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(W)}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(W.trim()))return this.handleSlashCommand(W,this.pendingPrompt.signal);let L=await this.runtime.enqueueSteering(D,{allowBeforeTurn:!0});if(!L.accepted)throw Error(L.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(U.debug(`[AcpSession ${this.id}] Queued steering for active turn (${L.queued})`),L.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let X=new AbortController,Y,F=new Promise((L)=>{Y=L});this.pendingPrompt=X,this.pendingPromptCompletion=F;try{if(U.debug(`[AcpSession ${this.id}] Received prompt: ${W.slice(0,100)}...`),Jz(W)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(W,X.signal)}let L={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:X.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},B=await l(this.agent.chatStream(D,L,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async($)=>{switch($.kind){case"content_delta":if(Z)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let G=$.toolCall,K=G.function.name;if(K===q)break;let R=this.mapToolKind($.toolKind),j=`Executing ${K}`;if(K==="Task"&&"function"in G)try{let O=JSON.parse(G.function.arguments),V=O.resume_from??O.resume;if(typeof V==="string")j=`Resuming ${String(O.subagent_type||"subagent")} from ${V}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.id,status:"in_progress",title:j,content:[],kind:R});break}case"tool_progress":{let G=$.toolCall;if(G.function.name===q)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let G=$.toolCall;if(G.function.name===q)break;let K=$.result,R=[],j=K.metadata;if(j?.kind==="patch"&&Array.isArray(j.changes))for(let V of j.changes){if(!V||typeof V!=="object"||!("path"in V)||typeof V.path!=="string")continue;R.push({type:"diff",path:V.path,oldText:"oldContent"in V&&typeof V.oldContent==="string"?V.oldContent:null,newText:"newContent"in V&&typeof V.newContent==="string"?V.newContent:null})}else if(j?.kind==="edit"&&typeof j.file_path==="string"&&typeof j.oldContent==="string"&&(typeof j.newContent==="string"||j.newContent===void 0))R.push({type:"diff",path:j.file_path,oldText:j.oldContent,newText:j.newContent??null});else{let V=G.function.name,Vz=o(v(a(V,K),c));R.push({type:"content",content:{type:"text",text:Vz}})}if(G.function.name==="Task"&&(j?.verificationVerdict==="pass"||j?.verificationVerdict==="fail"||j?.verificationVerdict==="partial"))R.unshift({type:"content",content:{type:"text",text:`Verification result: ${j.verificationVerdict.toUpperCase()}`}});let O=K.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.id,status:O,content:R});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Xf as o}from"./chunk-2mvp3rqw.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
|
|
2
2
|
export{e as j,i as k};
|