blade-code 0.10.92 → 0.10.93

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.
Files changed (41) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-jqky08cw.js → chunk-05fctawm.js} +1 -1
  3. package/dist/{chunk-kp40bxpa.js → chunk-0pnj92hk.js} +1 -1
  4. package/dist/{chunk-t5hfc8xq.js → chunk-37csc3d2.js} +1 -1
  5. package/dist/{chunk-36dhm0fm.js → chunk-3p7c1dsk.js} +1 -1
  6. package/dist/{chunk-602decf8.js → chunk-5rtjx9xk.js} +1 -1
  7. package/dist/{chunk-0ayxntzc.js → chunk-61efg3yh.js} +1 -1
  8. package/dist/{chunk-wm02k4gq.js → chunk-7b718dgf.js} +1 -1
  9. package/dist/{chunk-ysephh7s.js → chunk-7jgj63tj.js} +1 -1
  10. package/dist/{chunk-z24ha5jk.js → chunk-7wf2acxx.js} +1 -1
  11. package/dist/{chunk-rtdvy14c.js → chunk-82n941y8.js} +1 -1
  12. package/dist/{chunk-27y5dt0f.js → chunk-93rvs2hb.js} +1 -1
  13. package/dist/{chunk-cx7g79et.js → chunk-96pnk11m.js} +1 -1
  14. package/dist/{chunk-nje776xv.js → chunk-9h756tk9.js} +2 -2
  15. package/dist/{chunk-xphk45bp.js → chunk-9kfk68qj.js} +1 -1
  16. package/dist/{chunk-78agjkm5.js → chunk-b9bbyzk4.js} +1 -1
  17. package/dist/{chunk-w4e6xp05.js → chunk-fkhtff66.js} +1 -1
  18. package/dist/{chunk-z5xtgfja.js → chunk-fs8ra760.js} +1 -1
  19. package/dist/{chunk-1tjm9zdt.js → chunk-fyms8zy1.js} +1 -1
  20. package/dist/{chunk-jgd76jdj.js → chunk-gynpj5sv.js} +1 -1
  21. package/dist/{chunk-myzmv0ns.js → chunk-hn1xztva.js} +1 -1
  22. package/dist/chunk-jaegtaq3.js +1 -0
  23. package/dist/{chunk-dj0jfyms.js → chunk-m4tpqesg.js} +3 -3
  24. package/dist/{chunk-dq5ry3nq.js → chunk-mmd1hx8c.js} +1 -1
  25. package/dist/{chunk-30pq99z7.js → chunk-n23chvhe.js} +1 -1
  26. package/dist/{chunk-xdvk6frk.js → chunk-nht2hy5h.js} +1 -1
  27. package/dist/{chunk-cadgtmrr.js → chunk-ns5vb2p4.js} +1 -1
  28. package/dist/{chunk-qy68f2g6.js → chunk-qern9m2c.js} +1 -1
  29. package/dist/{chunk-h6fcb6ky.js → chunk-qr3w31ys.js} +1 -1
  30. package/dist/{chunk-k8h7k11c.js → chunk-sbrj2czw.js} +1 -1
  31. package/dist/{chunk-3qtmrh3z.js → chunk-scfwdpph.js} +1 -1
  32. package/dist/{chunk-qxm67agj.js → chunk-t7nj9vg8.js} +1 -1
  33. package/dist/{chunk-7tda8v4p.js → chunk-tt3n8gnq.js} +1 -1
  34. package/dist/{chunk-339r521e.js → chunk-v7rnx21e.js} +1 -1
  35. package/dist/{chunk-p8hgymk2.js → chunk-wgd4ject.js} +1 -1
  36. package/dist/{chunk-8hry1mq6.js → chunk-xby5w74x.js} +1 -1
  37. package/dist/{chunk-fthm9y4q.js → chunk-xh4pgtj2.js} +1 -1
  38. package/dist/chunk-z2asrfm1.js +1 -0
  39. package/package.json +1 -1
  40. package/dist/chunk-1ydbdbfj.js +0 -1
  41. package/dist/chunk-2rpcwgr9.js +0 -1
@@ -1,2 +1,2 @@
1
- import{wi as d,yi as h}from"./chunk-myzmv0ns.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},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",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};
1
+ import{wi as d,yi as h}from"./chunk-hn1xztva.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},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",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
2
  export{q as je,w as ke};
@@ -1,4 +1,4 @@
1
- import{e as k4,f as f4}from"./chunk-7k5v52ct.js";import{g as xx}from"./chunk-9318pj5k.js";import{s as Z0,t as z4}from"./chunk-cx7g79et.js";import{u as nO}from"./chunk-1tjm9zdt.js";import{A as w1,v as $4,w as O1,x as x1,y as $1,z as $0}from"./chunk-k8h7k11c.js";import{$ as x4,C as o1,D as M1,E as i4,H as n1,I as G0,J as kx,K as t0,L as b1,M as jx,N as EO,O as s1,P as r1,Q as e1,R as Ax,S as gO,T as R0,W as y0,X as P0,Z as Z$,_ as O4,aa as _4,ba as D4,ca as L4,da as H4,ea as b4,fa as j4,ga as A4,ha as S4,ia as M4,la as E4,oa as K$,ta as c4}from"./chunk-dj0jfyms.js";import{Aa as K1,Ga as UO}from"./chunk-36dhm0fm.js";import{$a as Y4,Ka as Nx,Na as o4,Oa as fx,Pa as w4,Qa as Q4,Ra as n4,Sa as t4,Ta as yx,Ua as s4,Va as rO,Wa as P4,Xa as m4,Ya as h4,Za as Z4,_a as J4,ab as N4,bb as sx,cb as px}from"./chunk-8eh0vp98.js";import{Cb as bx,Lb as tO,nb as pO,ob as P,qb as R,rb as t1}from"./chunk-339r521e.js";import{Wb as h1}from"./chunk-ya5p7mx7.js";import{Ad as c1,Cd as Y0,Fd as Dx,Kd as a1,Ld as Lx,Md as Hx,Nd as q,Pc as d1,_c as v1,jd as s0,pc as g1,pd as k0,qd as Tx,rd as f0,td as l1,wc as u1,xc as Bx,yc as p1,zc as _x,zd as i1}from"./chunk-qxm67agj.js";import{He as w$,Le as QO,Pe as _1,We as HO}from"./chunk-0ayxntzc.js";import{Xe as Fx}from"./chunk-zj4kfyer.js";import{mf as P1}from"./chunk-z6xfknxe.js";import{of as n0}from"./chunk-cadgtmrr.js";import{Bf as B4,Ff as S0,Gf as M0,Kf as H$,Nf as TO,Of as T0,Rf as b$,wf as Q$,yf as p4}from"./chunk-7tda8v4p.js";import{dg as D1,eg as m1}from"./chunk-rsh4rw9k.js";import{ig as X1,jg as Q0}from"./chunk-602decf8.js";import{Bg as V1,Vg as k1,Yg as f1,_g as y1,lh as G1,qh as A0}from"./chunk-z24ha5jk.js";import{th as Kx}from"./chunk-t48zm299.js";import{uh as E,wh as z,xh as RO,zh as r}from"./chunk-7dqh8bqm.js";import{Bh as e0,Eh as Ux}from"./chunk-d83bfr0b.js";import{Ih as c}from"./chunk-qa4efys0.js";import{ii as o}from"./chunk-h4j0nve8.js";import{oi as aO}from"./chunk-w63dfcx5.js";import{qi as F1,ri as I1,ti as B1,ui as E1}from"./chunk-n4gtzx4x.js";import{wi as w0}from"./chunk-myzmv0ns.js";import{Di as ux}from"./chunk-rzja9zza.js";import{Ji as c0,Ni as Z1,Oi as r0}from"./chunk-na1cney5.js";import{Qi as mx}from"./chunk-nh45xp7r.js";var y3={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function P3(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as dx,readFileSync as g0}from"node:fs";import{createServer as G3}from"node:http";import{networkInterfaces as W3}from"node:os";import{dirname as V3,extname as K3,join as iO}from"node:path";import{fileURLToPath as U3}from"node:url";import{brotliCompressSync as F3,gzipSync as B3,constants as _3}from"node:zlib";import{Hono as D3}from"hono";import{cors as L3}from"hono/cors";import{WebSocketServer as H3}from"ws";var x0=o("Service"),S$=30000,M$=new Set(["completed","failed","cancelled","interrupted"]);class zx{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??sx.getInstance(),this.tickMs=O.tickMs??S$}start(){if(this.timer)return;x0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!M$.has(x))return;this.recordTerminalStatus(O.sessionId,x,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,x0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){x0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),x0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let w=x.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??T$(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:Nx(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:w,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),x0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);x0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let J=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:Nx(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastStatus:"error",lastError:Y,nextRunAt:J?J.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Q=(await this.store.list()).find((Y)=>Y.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function T$(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class xO extends Error{code;statusCode;details;constructor(O,x,$=500,w){super(x);this.code=O;this.statusCode=$;this.details=w;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class y extends xO{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class B extends xO{constructor(O){super("BAD_REQUEST",O,400)}}class I extends xO{constructor(O){super("CONFLICT",O,409)}}class fO extends xO{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class yO extends xO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class LO extends xO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class n extends xO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var l3=z.Object({error:z.Object({code:z.String(),message:z.String(),details:z.Optional(z.Record(z.String(),z.Unknown()))})});import{Hono as R$}from"hono";var Xx=o("Service"),q$=z.Object({updates:z.Record(z.String(),z.Any()),options:z.Optional(z.Object({scope:z.Optional(r(["local","project","global"])),immediate:z.Optional(z.Boolean())}))});function C$(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var rx=()=>{let O=new R$;return O.get("/",async(x)=>{try{let $=QO();return x.json($?C$($):{})}catch($){return Xx.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),w=E(q$,$);if(!w.success)throw new B("Invalid config update format");let{updates:Q,options:Y}=w.data;return await HO().updateConfig(Q,Y),x.json({success:!0,updates:Q})}catch($){throw Xx.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=QO();return x.json($?.permissions||{})}catch($){return Xx.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as I$}from"hono";import{streamSSE as E$}from"hono/streaming";function ex(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
1
+ import{e as k4,f as f4}from"./chunk-7k5v52ct.js";import{g as xx}from"./chunk-9318pj5k.js";import{s as Z0,t as z4}from"./chunk-96pnk11m.js";import{u as nO}from"./chunk-fyms8zy1.js";import{A as w1,v as $4,w as O1,x as x1,y as $1,z as $0}from"./chunk-sbrj2czw.js";import{$ as x4,C as o1,D as M1,E as i4,H as n1,I as G0,J as kx,K as t0,L as b1,M as jx,N as EO,O as s1,P as r1,Q as e1,R as Ax,S as gO,T as R0,W as y0,X as P0,Z as Z$,_ as O4,aa as _4,ba as D4,ca as L4,da as H4,ea as b4,fa as j4,ga as A4,ha as S4,ia as M4,la as E4,oa as K$,ta as c4}from"./chunk-m4tpqesg.js";import{Aa as K1,Ga as UO}from"./chunk-3p7c1dsk.js";import{$a as Y4,Ka as Nx,Na as o4,Oa as fx,Pa as w4,Qa as Q4,Ra as n4,Sa as t4,Ta as yx,Ua as s4,Va as rO,Wa as P4,Xa as m4,Ya as h4,Za as Z4,_a as J4,ab as N4,bb as sx,cb as px}from"./chunk-8eh0vp98.js";import{Cb as bx,Lb as tO,nb as pO,ob as P,qb as R,rb as t1}from"./chunk-v7rnx21e.js";import{Wb as h1}from"./chunk-ya5p7mx7.js";import{Ad as c1,Cd as Y0,Fd as Dx,Kd as a1,Ld as Lx,Md as Hx,Nd as q,Pc as d1,_c as v1,jd as s0,pc as g1,pd as k0,qd as Tx,rd as f0,td as l1,wc as u1,xc as Bx,yc as p1,zc as _x,zd as i1}from"./chunk-t7nj9vg8.js";import{He as w$,Le as QO,Pe as _1,We as HO}from"./chunk-61efg3yh.js";import{Xe as Fx}from"./chunk-zj4kfyer.js";import{mf as P1}from"./chunk-z6xfknxe.js";import{of as n0}from"./chunk-ns5vb2p4.js";import{Bf as B4,Ff as S0,Gf as M0,Kf as H$,Nf as TO,Of as T0,Rf as b$,wf as Q$,yf as p4}from"./chunk-tt3n8gnq.js";import{dg as D1,eg as m1}from"./chunk-rsh4rw9k.js";import{ig as X1,jg as Q0}from"./chunk-5rtjx9xk.js";import{Bg as V1,Vg as k1,Yg as f1,_g as y1,lh as G1,qh as A0}from"./chunk-7wf2acxx.js";import{th as Kx}from"./chunk-t48zm299.js";import{uh as E,wh as z,xh as RO,zh as r}from"./chunk-7dqh8bqm.js";import{Bh as e0,Eh as Ux}from"./chunk-d83bfr0b.js";import{Ih as c}from"./chunk-qa4efys0.js";import{ii as o}from"./chunk-h4j0nve8.js";import{oi as aO}from"./chunk-w63dfcx5.js";import{qi as F1,ri as I1,ti as B1,ui as E1}from"./chunk-n4gtzx4x.js";import{wi as w0}from"./chunk-hn1xztva.js";import{Di as ux}from"./chunk-rzja9zza.js";import{Ji as c0,Ni as Z1,Oi as r0}from"./chunk-na1cney5.js";import{Qi as mx}from"./chunk-nh45xp7r.js";var y3={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function P3(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as dx,readFileSync as g0}from"node:fs";import{createServer as G3}from"node:http";import{networkInterfaces as W3}from"node:os";import{dirname as V3,extname as K3,join as iO}from"node:path";import{fileURLToPath as U3}from"node:url";import{brotliCompressSync as F3,gzipSync as B3,constants as _3}from"node:zlib";import{Hono as D3}from"hono";import{cors as L3}from"hono/cors";import{WebSocketServer as H3}from"ws";var x0=o("Service"),S$=30000,M$=new Set(["completed","failed","cancelled","interrupted"]);class zx{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??sx.getInstance(),this.tickMs=O.tickMs??S$}start(){if(this.timer)return;x0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!M$.has(x))return;this.recordTerminalStatus(O.sessionId,x,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,x0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){x0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),x0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let w=x.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??T$(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:Nx(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:w,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),x0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);x0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let J=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:Nx(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastStatus:"error",lastError:Y,nextRunAt:J?J.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Q=(await this.store.list()).find((Y)=>Y.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function T$(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class xO extends Error{code;statusCode;details;constructor(O,x,$=500,w){super(x);this.code=O;this.statusCode=$;this.details=w;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class y extends xO{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class B extends xO{constructor(O){super("BAD_REQUEST",O,400)}}class I extends xO{constructor(O){super("CONFLICT",O,409)}}class fO extends xO{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class yO extends xO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class LO extends xO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class n extends xO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var l3=z.Object({error:z.Object({code:z.String(),message:z.String(),details:z.Optional(z.Record(z.String(),z.Unknown()))})});import{Hono as R$}from"hono";var Xx=o("Service"),q$=z.Object({updates:z.Record(z.String(),z.Any()),options:z.Optional(z.Object({scope:z.Optional(r(["local","project","global"])),immediate:z.Optional(z.Boolean())}))});function C$(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var rx=()=>{let O=new R$;return O.get("/",async(x)=>{try{let $=QO();return x.json($?C$($):{})}catch($){return Xx.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),w=E(q$,$);if(!w.success)throw new B("Invalid config update format");let{updates:Q,options:Y}=w.data;return await HO().updateConfig(Q,Y),x.json({success:!0,updates:Q})}catch($){throw Xx.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=QO();return x.json($?.permissions||{})}catch($){return Xx.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as I$}from"hono";import{streamSSE as E$}from"hono/streaming";function ex(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)x+=`event: ${O.event}
3
3
  `;for(let $ of O.data.split(/\r\n|\r|\n/))x+=`data: ${$}
4
4
  `;if(O.retry!==void 0)x+=`retry: ${O.retry}
@@ -1,4 +1,4 @@
1
- import{U as P}from"./chunk-dj0jfyms.js";import{sb as K}from"./chunk-339r521e.js";import{$c as s,Nd as B,Xc as G,Yc as N,Zc as S,_c as O}from"./chunk-qxm67agj.js";import{Wd as j}from"./chunk-4jbpvete.js";import{Xe as q}from"./chunk-zj4kfyer.js";import{tf as v}from"./chunk-7tda8v4p.js";import{Ki as z}from"./chunk-na1cney5.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{U as P}from"./chunk-m4tpqesg.js";import{sb as K}from"./chunk-v7rnx21e.js";import{$c as s,Nd as B,Xc as G,Yc as N,Zc as S,_c as O}from"./chunk-t7nj9vg8.js";import{Wd as j}from"./chunk-4jbpvete.js";import{Xe as q}from"./chunk-zj4kfyer.js";import{tf as v}from"./chunk-tt3n8gnq.js";import{Ki as z}from"./chunk-na1cney5.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -1 +1 @@
1
- import{nf as a,of as b,pf as c}from"./chunk-cadgtmrr.js";import"./chunk-z24ha5jk.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-myzmv0ns.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
1
+ import{nf as a,of as b,pf as c}from"./chunk-ns5vb2p4.js";import"./chunk-7wf2acxx.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-hn1xztva.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1,2 +1,2 @@
1
- import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.92",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
1
+ import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.93",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
2
2
  export{y as vi,p as wi,v as xi,g as yi,f as zi,w as Ai};
@@ -0,0 +1 @@
1
+ import{je as a,ke as b}from"./chunk-fkhtff66.js";import"./chunk-hn1xztva.js";import"./chunk-nh45xp7r.js";export{a as globalOptions,b as cliConfig};
@@ -1,4 +1,4 @@
1
- import{va as G5}from"./chunk-z5rtzcm4.js";import{Ea as OY,Fa as s3,Ga as c0,ya as C,za as l0}from"./chunk-36dhm0fm.js";import{Ha as n4,Ja as QQ,La as WQ,Ma as eZ,cb as UQ}from"./chunk-8eh0vp98.js";import{Bb as D9,Cb as H$,Ib as F4,Jb as BY,Kb as MJ,Mb as M2,Nb as iJ,Sb as G7,Vb as D7,db as k$,eb as S1,fb as I3,gb as B1,hb as b3,ib as h3,jb as A3,kb as g3,lb as u3,mb as P7,qb as U0,sb as I6,vb as a6,xb as QZ,yb as o6,zb as s6}from"./chunk-339r521e.js";import{$b as l5,Ac as N1,Bc as U2,Bd as DY,Cc as j1,Dc as $6,Ec as A1,Fc as Z6,Fd as z7,Gc as J6,Hc as D$,Ic as Y6,Jc as C5,Kc as w2,Kd as cJ,Lc as Q6,Ld as lJ,Mc as W6,Nc as U6,Nd as s,Oc as X6,Pc as M5,Qc as R5,Sc as P5,ac as D0,bc as s1,cc as o$,dc as n2,ec as Q5,fc as r6,gc as n6,hc as M3,ic as R3,jc as dJ,jd as H4,kc as z5,kd as E0,lc as Y1,ld as U$,mc as K5,nc as h4,oc as T$,pc as f$,qc as V2,rc as X2,sc as B2,tc as t2,uc as e2,ud as W5,vc as Q2,vd as r0,wc as q5,wd as k1,xc as W2,xd as mJ,yc as g4,yd as pJ,zc as C1}from"./chunk-qxm67agj.js";import{Od as m,Pd as k7,Qd as v7,Rd as v1}from"./chunk-gbsxnvgg.js";import{Sd as VQ,Vd as BQ,ce as wQ,ie as KQ}from"./chunk-4jbpvete.js";import{te as K9,ue as B9}from"./chunk-ztp2ff01.js";import{Ge as t6,He as H0,Ie as y,Le as F0,Me as x6,Ne as y1,Oe as u$,Pe as zZ,Qe as Q1,Re as K7,We as T1}from"./chunk-0ayxntzc.js";import{Xe as z1}from"./chunk-zj4kfyer.js";import{af as H7,bf as B7,gf as JY,hf as h6}from"./chunk-0eqk29xr.js";import{jf as k0,kf as a$}from"./chunk-rxbxvq67.js";import{lf as KY}from"./chunk-z6xfknxe.js";import{nf as IJ,of as xJ,pf as hJ}from"./chunk-cadgtmrr.js";import{Af as X$,Bf as J$,Cf as i4,Df as M1,Ef as D4,Ff as F1,Gf as q1,Hf as uJ,Lf as SZ,Nf as v0,Of as z$,Qf as g6,Rf as rJ,qf as m6,rf as p6,sf as c6,uf as l6,vf as i6,wf as i$,xf as g7,zf as q$}from"./chunk-7tda8v4p.js";import{$f as x5,Tf as m$,Vf as K$,Wf as C6,Xf as v5,Yf as y5,Zf as K2,_f as I5,ag as B6}from"./chunk-yjh47zv6.js";import{bg as TY,dg as gJ,eg as K4,fg as H9}from"./chunk-rsh4rw9k.js";import{hg as rZ,jg as R0}from"./chunk-602decf8.js";import{kg as u2,lg as Y5,mg as d2,ng as O1}from"./chunk-74yge4ka.js";import{Bg as LY,Fg as t5,Hg as SJ,Jg as v3,Kg as y3,Qg as K1,Tg as j3,bh as e3,ch as $7,dh as Z7,eh as J7,fh as KZ,gh as Y7,hh as g$,ih as Q7,jh as W7,kh as U7,mh as m5,oh as aJ,pg as o5,ph as yJ,qh as X0,ug as s5,wg as mZ}from"./chunk-z24ha5jk.js";import{th as S$}from"./chunk-t48zm299.js";import{uh as V6,vh as m4,wh as H,xh as c7,yh as T,zh as x}from"./chunk-7dqh8bqm.js";import{Bh as AJ,Dh as CJ}from"./chunk-d83bfr0b.js";import{Gh as z6,Ih as M}from"./chunk-qa4efys0.js";import{ii as o}from"./chunk-h4j0nve8.js";import{ni as kJ,oi as vJ}from"./chunk-w63dfcx5.js";import{pi as SY,si as RY}from"./chunk-n4gtzx4x.js";import{wi as IY}from"./chunk-myzmv0ns.js";import{Ci as nJ,Di as g0}from"./chunk-rzja9zza.js";import{Hi as r2,Ji as x$,Li as fJ,Mi as k5,Oi as J0}from"./chunk-na1cney5.js";import{Qi as n0}from"./chunk-nh45xp7r.js";import{randomUUID as f4}from"crypto";import{randomUUID as TQ}from"node:crypto";var AQ=String.raw`
1
+ import{va as G5}from"./chunk-z5rtzcm4.js";import{Ea as OY,Fa as s3,Ga as c0,ya as C,za as l0}from"./chunk-3p7c1dsk.js";import{Ha as n4,Ja as QQ,La as WQ,Ma as eZ,cb as UQ}from"./chunk-8eh0vp98.js";import{Bb as D9,Cb as H$,Ib as F4,Jb as BY,Kb as MJ,Mb as M2,Nb as iJ,Sb as G7,Vb as D7,db as k$,eb as S1,fb as I3,gb as B1,hb as b3,ib as h3,jb as A3,kb as g3,lb as u3,mb as P7,qb as U0,sb as I6,vb as a6,xb as QZ,yb as o6,zb as s6}from"./chunk-v7rnx21e.js";import{$b as l5,Ac as N1,Bc as U2,Bd as DY,Cc as j1,Dc as $6,Ec as A1,Fc as Z6,Fd as z7,Gc as J6,Hc as D$,Ic as Y6,Jc as C5,Kc as w2,Kd as cJ,Lc as Q6,Ld as lJ,Mc as W6,Nc as U6,Nd as s,Oc as X6,Pc as M5,Qc as R5,Sc as P5,ac as D0,bc as s1,cc as o$,dc as n2,ec as Q5,fc as r6,gc as n6,hc as M3,ic as R3,jc as dJ,jd as H4,kc as z5,kd as E0,lc as Y1,ld as U$,mc as K5,nc as h4,oc as T$,pc as f$,qc as V2,rc as X2,sc as B2,tc as t2,uc as e2,ud as W5,vc as Q2,vd as r0,wc as q5,wd as k1,xc as W2,xd as mJ,yc as g4,yd as pJ,zc as C1}from"./chunk-t7nj9vg8.js";import{Od as m,Pd as k7,Qd as v7,Rd as v1}from"./chunk-gbsxnvgg.js";import{Sd as VQ,Vd as BQ,ce as wQ,ie as KQ}from"./chunk-4jbpvete.js";import{te as K9,ue as B9}from"./chunk-ztp2ff01.js";import{Ge as t6,He as H0,Ie as y,Le as F0,Me as x6,Ne as y1,Oe as u$,Pe as zZ,Qe as Q1,Re as K7,We as T1}from"./chunk-61efg3yh.js";import{Xe as z1}from"./chunk-zj4kfyer.js";import{af as H7,bf as B7,gf as JY,hf as h6}from"./chunk-0eqk29xr.js";import{jf as k0,kf as a$}from"./chunk-rxbxvq67.js";import{lf as KY}from"./chunk-z6xfknxe.js";import{nf as IJ,of as xJ,pf as hJ}from"./chunk-ns5vb2p4.js";import{Af as X$,Bf as J$,Cf as i4,Df as M1,Ef as D4,Ff as F1,Gf as q1,Hf as uJ,Lf as SZ,Nf as v0,Of as z$,Qf as g6,Rf as rJ,qf as m6,rf as p6,sf as c6,uf as l6,vf as i6,wf as i$,xf as g7,zf as q$}from"./chunk-tt3n8gnq.js";import{$f as x5,Tf as m$,Vf as K$,Wf as C6,Xf as v5,Yf as y5,Zf as K2,_f as I5,ag as B6}from"./chunk-yjh47zv6.js";import{bg as TY,dg as gJ,eg as K4,fg as H9}from"./chunk-rsh4rw9k.js";import{hg as rZ,jg as R0}from"./chunk-5rtjx9xk.js";import{kg as u2,lg as Y5,mg as d2,ng as O1}from"./chunk-74yge4ka.js";import{Bg as LY,Fg as t5,Hg as SJ,Jg as v3,Kg as y3,Qg as K1,Tg as j3,bh as e3,ch as $7,dh as Z7,eh as J7,fh as KZ,gh as Y7,hh as g$,ih as Q7,jh as W7,kh as U7,mh as m5,oh as aJ,pg as o5,ph as yJ,qh as X0,ug as s5,wg as mZ}from"./chunk-7wf2acxx.js";import{th as S$}from"./chunk-t48zm299.js";import{uh as V6,vh as m4,wh as H,xh as c7,yh as T,zh as x}from"./chunk-7dqh8bqm.js";import{Bh as AJ,Dh as CJ}from"./chunk-d83bfr0b.js";import{Gh as z6,Ih as M}from"./chunk-qa4efys0.js";import{ii as o}from"./chunk-h4j0nve8.js";import{ni as kJ,oi as vJ}from"./chunk-w63dfcx5.js";import{pi as SY,si as RY}from"./chunk-n4gtzx4x.js";import{wi as IY}from"./chunk-hn1xztva.js";import{Ci as nJ,Di as g0}from"./chunk-rzja9zza.js";import{Hi as r2,Ji as x$,Li as fJ,Mi as k5,Oi as J0}from"./chunk-na1cney5.js";import{Qi as n0}from"./chunk-nh45xp7r.js";import{randomUUID as f4}from"crypto";import{randomUUID as TQ}from"node:crypto";var AQ=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -838,7 +838,7 @@ ${a}
838
838
  </approved-plan>
839
839
 
840
840
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof F==="string")i0=F+B0;else i0=[...F,{type:"text",text:B0}]}v=yield*this.runLoop(i0,L,{...I,inputMessageId:void 0})}if(!this.sessionRuntime||!S)return v;let k=await this.sessionRuntime.recordGoalProgress({tokens:v.metadata?.tokensUsed??0,elapsedMs:v.metadata?.duration??0,prematureStopPattern:v.success?k3(v.finalMessage):void 0});if(k)yield{kind:"goal_updated",goal:k};if(!v.success||L.signal?.aborted){if(k=await this.sessionRuntime.pauseActiveGoal(L.signal?.aborted?"goal paused after user cancellation":v.error?.message??"goal paused after turn failure"),k)yield{kind:"goal_updated",goal:k}}if(v.success&&!L.signal?.aborted&&P<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(S,L.signal);let d=v.success&&!L.signal?.aborted&&P<20,Z0=PV(v);if(j=await this.sessionRuntime.finishTurn(S,{continuePending:d,...Z0?{acknowledgeInput:!0}:{},outcome:v.success&&!L.signal?.aborted?{status:"completed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}:{status:"aborted",cause:L.signal?.aborted?"cancelled":"failed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}}),j){P++,q=!0,E=!1,N=null,F="",R=void 0,A="",O=void 0,b=g(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:p()};continue}if(!v.success||L.signal?.aborted)return v;if(k=await this.sessionRuntime.getGoal(),!k||k.status!=="active"&&k.status!=="verifying")return v;if(N=await this.sessionRuntime.beginGoalContinuation(),!N)return v;j=await this.sessionRuntime.beginTurn("goal"),q=!1,E=!0,F=L8(N),R=void 0,b=void 0,yield{kind:"goal_continuation_started",goal:N,continuation:N.continuationCount,...N.prematureStop?{prematureStopPattern:N.prematureStop.pattern,prematureStopCount:N.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:N}}}finally{if(this.sessionRuntime&&j)await this.sessionRuntime.finishTurn(j)}}let G=typeof B==="string"?B:B.filter((F)=>F.type==="text").map((F)=>F.text).join(`
841
- `),_={id:this.generateTaskId(),type:"simple",prompt:G};return{success:!0,finalMessage:(await this.executeTask(_)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-30pq99z7.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await v$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:M2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),Q;if(typeof $==="string")Q=G2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:G2(U.text)}:X)}else Q=[{type:"text",text:G2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){n.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await v$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:M2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return D7(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,X={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],B=G7(Y,X);if(B)V.push(B);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,n.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);n.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);n.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){n.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){n.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await v$({projectPath:this.sessionRuntime?.workspaceRoot??M(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),n.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await u6({sessionId:"default",configDir:J0(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});n.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;n.debug(`Builtin tools registered: ${Z} tools`),n.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw n.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await G6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){n.debug("No MCP servers configured");return}let Z=c0.createIsolated({artifactWriter:new z2(`legacy-${RV()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{n.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),n.debug(`MCP server "${W}" connected`)}catch(X){n.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(L2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)n.debug(`Registered ${Y.tools.length} MCP tools`),n.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){n.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await v0(M());if(this.agentResources=g6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)n.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else n.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;n.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return n.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)n.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
841
+ `),_={id:this.generateTaskId(),type:"simple",prompt:G};return{success:!0,finalMessage:(await this.executeTask(_)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-n23chvhe.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await v$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:M2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),Q;if(typeof $==="string")Q=G2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:G2(U.text)}:X)}else Q=[{type:"text",text:G2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){n.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await v$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:M2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return D7(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,X={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],B=G7(Y,X);if(B)V.push(B);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,n.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);n.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);n.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){n.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){n.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await v$({projectPath:this.sessionRuntime?.workspaceRoot??M(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),n.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await u6({sessionId:"default",configDir:J0(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});n.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;n.debug(`Builtin tools registered: ${Z} tools`),n.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw n.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await G6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){n.debug("No MCP servers configured");return}let Z=c0.createIsolated({artifactWriter:new z2(`legacy-${RV()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{n.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),n.debug(`MCP server "${W}" connected`)}catch(X){n.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(L2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)n.debug(`Registered ${Y.tools.length} MCP tools`),n.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){n.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await v0(M());if(this.agentResources=g6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)n.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else n.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;n.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return n.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)n.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
842
842
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;n.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return n.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let W=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${W?` range="${W}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
843
843
 
844
844
  <system-reminder>
@@ -1649,7 +1649,7 @@ ${J}
1649
1649
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1650
1650
  `)}}case"create":{let X=Xz(W);if("error"in X)return Y.sendMessage(`创建失败:${X.error}`),{success:!1,error:X.error};let V={prompt:X.prompt,projectPath:U,trigger:X.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let B=await $.create(V),w=B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${B.id}\`
1651
1651
  ${eZ(B.trigger)} · 下次运行: ${w}`),{success:!0,message:`Schedule ${B.id} created`}}catch(B){let w=B instanceof Error?B.message:String(B);return Y.sendMessage(`创建失败:${w}`),{success:!1,error:w}}}case"remove":case"rm":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(X);return Y.sendMessage(V?`[OK] 已删除 \`${X}\``:`未找到 \`${X}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let X=W[0];if(!X)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(X,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${X}\``:`未找到 \`${X}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await Vz(X),Y.sendMessage(`[OK] 已触发 \`${X}\``),{success:!0,message:"Schedule triggered"}}catch(V){let B=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${B}`),{success:!1,error:B}}}default:return Y.sendMessage(`未知子命令: ${Q}
1652
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var XQ=Bz();import*as n1 from"node:fs/promises";import*as a1 from"node:path";async function HQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??r2(Q??M());if(!W){let z=await wz($,Q??M(),J,Y);if(z)return z}let X;try{X=(await n1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>a1.join(U,G))}catch{return[]}let B=(await Promise.all(X.map(async(z)=>{try{let G=await n1.stat(z);return{path:z,mtime:G.mtimeMs}}catch{return null}}))).filter((z)=>z!==null).sort((z,G)=>G.mtime-z.mtime).map((z)=>z.path),w=[],K=Y?$:$.toLowerCase();for(let z of B){if(w.length>=J)break;let G=a1.basename(z,".jsonl"),_=await Kz(z,K,Y,G);if(w.push(..._),w.length>=J){w.length=J;break}}return w}async function wz($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-vy4dz3yz.js"),W=await wQ();if(!W)return null;let{SessionService:U}=await import("./chunk-jqky08cw.js");await Q(W,U.projectionDeriverForSearch());let X=a1.resolve(Z),V=KQ(W,$,X,J*4),B=Y?$:$.toLowerCase(),w=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let z=$5(K.text,B,Y,K.session_id,K.role,K.timestamp??void 0,0);if(z)w.push(z);if(w.length>=J)break}return w}catch{return null}}async function Kz($,Z,J,Y){try{let Q=await n1.readFile($,"utf8"),U=Q.split(`
1652
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var XQ=Bz();import*as n1 from"node:fs/promises";import*as a1 from"node:path";async function HQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??r2(Q??M());if(!W){let z=await wz($,Q??M(),J,Y);if(z)return z}let X;try{X=(await n1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>a1.join(U,G))}catch{return[]}let B=(await Promise.all(X.map(async(z)=>{try{let G=await n1.stat(z);return{path:z,mtime:G.mtimeMs}}catch{return null}}))).filter((z)=>z!==null).sort((z,G)=>G.mtime-z.mtime).map((z)=>z.path),w=[],K=Y?$:$.toLowerCase();for(let z of B){if(w.length>=J)break;let G=a1.basename(z,".jsonl"),_=await Kz(z,K,Y,G);if(w.push(..._),w.length>=J){w.length=J;break}}return w}async function wz($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-vy4dz3yz.js"),W=await wQ();if(!W)return null;let{SessionService:U}=await import("./chunk-05fctawm.js");await Q(W,U.projectionDeriverForSearch());let X=a1.resolve(Z),V=KQ(W,$,X,J*4),B=Y?$:$.toLowerCase(),w=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let z=$5(K.text,B,Y,K.session_id,K.role,K.timestamp??void 0,0);if(z)w.push(z);if(w.length>=J)break}return w}catch{return null}}async function Kz($,Z,J,Y){try{let Q=await n1.readFile($,"utf8"),U=Q.split(`
1653
1653
  `).flatMap((K,z)=>{if(!K.trim())return[];try{return[{event:JSON.parse(K),index:z}]}catch{return[]}});if(!U.some(({event:K})=>K.type==="session_created"))return Hz(U,Z,J,Y);let V=new Map(U.flatMap(({event:K,index:z})=>typeof K.id==="string"?[[K.id,z+1]]:[])),B=VQ(BQ(Q,$)),w=new Map;for(let K of B){if(K.type==="message_created"&&(K.data.role==="user"||K.data.role==="assistant"))w.set(K.data.messageId,{role:K.data.role,content:[],timestamp:K.timestamp,lineNumber:V.get(K.id)??0});if(K.type==="part_created"&&K.data.partType==="text"){let z=w.get(K.data.messageId),G=K.data.payload.text;if(z&&typeof G==="string")z.content.push(G)}}return[...w.values()].flatMap((K)=>{let z=$5(K.content.join(" "),Z,J,Y,K.role,K.timestamp,K.lineNumber);return z?[z]:[]})}catch{return[]}}function Hz($,Z,J,Y){return $.flatMap(({event:Q,index:W})=>{if(Q.type!=="message")return[];let U=Q.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let X=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((B)=>typeof B==="object"&&B!==null&&B.type==="text"&&typeof B.text==="string").map((B)=>B.text).join(" "):"",V=$5(X,Z,J,Y,U.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,W+1);return V?[V]:[]})}function $5($,Z,J,Y,Q,W,U){if(!$)return;let X=J?$:$.toLowerCase();if(!X.includes(Z))return;let V=X.indexOf(Z),B=Math.max(0,V-80),w=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(B>0?"...":"")+$.slice(B,w).replace(/\n/g," ")+(w<$.length?"...":""),timestamp:W,lineNumber:U}}function zQ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1654
1654
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1655
1655
  `)}var zz={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=u(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await HQ(Y,{maxResults:15,projectPath:Z.cwd}),W=zQ(Q);return J.sendMessage(W),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let W=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${W}`),{success:!1,error:W}}}},GQ=zz;var Gz={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await z$(J,async(Y)=>{await Y.skills.refresh(),q1(J),await F1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return y().addAssistantMessage(Y),{success:!1,error:Y}}}},DQ=Gz;import Dz from"node:path";function A4($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function _Q($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function FQ($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function _z($,Z){let J=u(Z),Y=$[0],Q=e.getInstance(),W=V0.getInstance(),U=Z.sessionId??"",X=Z.sessionId?{sessionId:Z.sessionId,projectPath:Dz.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let G=$[1],_=$.slice(2).join(" ").trim();if(!G||!_)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let D=await Z.subagents.resume(G,_),F=`Resumed \`${G}\` as \`${D.session.id}\` (depth ${D.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:G,subagent:D.session}}}if(Y==="clean"){let G=W.cleanupExpiredSessionsForParent(X??U,0);return J.sendMessage(`已清理 ${G} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${G} agent sessions`}}let V=[`**后台任务列表**
@@ -1 +1 @@
1
- import{h as o}from"./chunk-3qtmrh3z.js";import"./chunk-myzmv0ns.js";import"./chunk-nh45xp7r.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{h as o}from"./chunk-scfwdpph.js";import"./chunk-hn1xztva.js";import"./chunk-nh45xp7r.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1 +1 @@
1
- import{Ab as d,Bb as e,Cb as f,Db as g,Eb as h,Fb as i,Gb as j,Hb as k,Ob as l,Pb as m,Qb as n,Rb as o,Tb as p,Ub as q,Vb as r,tb as a,ub as b,wb as c}from"./chunk-339r521e.js";import"./chunk-ya5p7mx7.js";import"./chunk-qxm67agj.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-z6xfknxe.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-602decf8.js";import"./chunk-74yge4ka.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-myzmv0ns.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.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
+ import{Ab as d,Bb as e,Cb as f,Db as g,Eb as h,Fb as i,Gb as j,Hb as k,Ob as l,Pb as m,Qb as n,Rb as o,Tb as p,Ub as q,Vb as r,tb as a,ub as b,wb as c}from"./chunk-v7rnx21e.js";import"./chunk-ya5p7mx7.js";import"./chunk-t7nj9vg8.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-z6xfknxe.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-5rtjx9xk.js";import"./chunk-74yge4ka.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-hn1xztva.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.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 +1 @@
1
- import{le as a,me as b,ne as c}from"./chunk-8hry1mq6.js";import"./chunk-wbfa6xce.js";import"./chunk-0ayxntzc.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-4cvmfne8.js";import"./chunk-z24ha5jk.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-myzmv0ns.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
1
+ import{le as a,me as b,ne as c}from"./chunk-xby5w74x.js";import"./chunk-wbfa6xce.js";import"./chunk-61efg3yh.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-4cvmfne8.js";import"./chunk-7wf2acxx.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-hn1xztva.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,2 +1,2 @@
1
- import{qh as F}from"./chunk-z24ha5jk.js";import{ni as D,oi as E}from"./chunk-w63dfcx5.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
1
+ import{qh as F}from"./chunk-7wf2acxx.js";import{ni as D,oi as E}from"./chunk-w63dfcx5.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
2
  export{H as nf,Q as of,T as pf};
@@ -1,4 +1,4 @@
1
- import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-p8hgymk2.js";import{$ as y,T as M}from"./chunk-dj0jfyms.js";import"./chunk-z5rtzcm4.js";import"./chunk-36dhm0fm.js";import"./chunk-8eh0vp98.js";import{Cb as h,Lb as A}from"./chunk-339r521e.js";import"./chunk-ya5p7mx7.js";import{Nd as U,zd as w}from"./chunk-qxm67agj.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as C}from"./chunk-w4e6xp05.js";import{le as I,me as S,ne as v}from"./chunk-8hry1mq6.js";import{oe as O}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Le as P}from"./chunk-0ayxntzc.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-cadgtmrr.js";import"./chunk-7tda8v4p.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-602decf8.js";import"./chunk-74yge4ka.js";import"./chunk-z24ha5jk.js";import{sh as F}from"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Ih as z}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-myzmv0ns.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-wgd4ject.js";import{$ as y,T as M}from"./chunk-m4tpqesg.js";import"./chunk-z5rtzcm4.js";import"./chunk-3p7c1dsk.js";import"./chunk-8eh0vp98.js";import{Cb as h,Lb as A}from"./chunk-v7rnx21e.js";import"./chunk-ya5p7mx7.js";import{Nd as U,zd as w}from"./chunk-t7nj9vg8.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as C}from"./chunk-fkhtff66.js";import{le as I,me as S,ne as v}from"./chunk-xby5w74x.js";import{oe as O}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Le as P}from"./chunk-61efg3yh.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-ns5vb2p4.js";import"./chunk-tt3n8gnq.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-5rtjx9xk.js";import"./chunk-74yge4ka.js";import"./chunk-7wf2acxx.js";import{sh as F}from"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Ih as z}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-hn1xztva.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -1,4 +1,4 @@
1
- import{m as SH,n as TH,o as bH,p as IH,q as RH,r as gH}from"./chunk-p8hgymk2.js";import{A as VH,v as yH,w as HH,x as JH,y as KH,z as d}from"./chunk-k8h7k11c.js";import{$ as FH,T as _H,V as GH,W as PH,Y as qH}from"./chunk-dj0jfyms.js";import"./chunk-z5rtzcm4.js";import"./chunk-36dhm0fm.js";import"./chunk-8eh0vp98.js";import{Cb as xH,Lb as UH,qb as o}from"./chunk-339r521e.js";import"./chunk-ya5p7mx7.js";import{Cd as O,Nd as i,nd as WH,rd as jH}from"./chunk-qxm67agj.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as AH}from"./chunk-w4e6xp05.js";import{le as MH,me as fH,ne as zH}from"./chunk-8hry1mq6.js";import{oe as EH}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Oe as LH}from"./chunk-0ayxntzc.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-cadgtmrr.js";import"./chunk-7tda8v4p.js";import{$f as $H}from"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-602decf8.js";import"./chunk-74yge4ka.js";import"./chunk-z24ha5jk.js";import{sh as QH}from"./chunk-t48zm299.js";import{uh as DH,wh as H,xh as ZH,zh as N}from"./chunk-7dqh8bqm.js";import{Dh as a,Eh as s}from"./chunk-d83bfr0b.js";import{Ih as g}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-myzmv0ns.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import SJ from"yargs";import{hideBin as TJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function uH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),P=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let y=K.once?.bind(K)??K.on?.bind(K);y?.("drain",x),y?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function dH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await uH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new VH({maxPendingItems:V.maxPendingItems??HH,maxPendingBytes:V.maxPendingBytes??JH,writeTimeoutMs:V.writeTimeoutMs??KH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>dH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var XH=1;function D(K){return H.Object({event_version:H.Literal(XH),...K})}var pH=D({type:H.Literal("content_delta"),delta:H.String()}),vH=D({type:H.Literal("thinking_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking"),content:H.String()}),aH=D({type:H.Literal("stream_end")}),sH=D({type:H.Literal("content"),content:H.String()}),iH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),oH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),rH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),nH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(oH)}),tH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),eH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(tH)}),HJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),JJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),VJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),ZJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),$J=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),XJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),YJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),BJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),NJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),QJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),DJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),LJ=D({type:H.Literal("task_update"),tasks:H.Array(qH)}),WJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N($H)),premature_stop_count:H.Optional(H.Integer({minimum:1}))}),jJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),xJ=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),UJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),_J=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),GJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),PJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),FJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),EJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),MJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),fJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),yJ=D({type:H.Literal("error"),message:H.String()}),rJ=ZH(H.Union([pH,vH,lH,aH,sH,iH,rH,nH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,GJ,PJ,_J,FJ,EJ,AJ,MJ,fJ,zJ,yJ]));function YH(K,V){return{event_version:XH,type:K,...V}}function bJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;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 IJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var RJ=N(["text","jsonl"]),gJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(QH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(RJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function CJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function kJ(K){let V=DH(gJ,K);if(!V.success)throw Error(`Invalid headless options: ${CJ(V.error)}`);return V.data}function hJ(K){return K.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 Q=await dJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
1
+ import{m as SH,n as TH,o as bH,p as IH,q as RH,r as gH}from"./chunk-wgd4ject.js";import{A as VH,v as yH,w as HH,x as JH,y as KH,z as d}from"./chunk-sbrj2czw.js";import{$ as FH,T as _H,V as GH,W as PH,Y as qH}from"./chunk-m4tpqesg.js";import"./chunk-z5rtzcm4.js";import"./chunk-3p7c1dsk.js";import"./chunk-8eh0vp98.js";import{Cb as xH,Lb as UH,qb as o}from"./chunk-v7rnx21e.js";import"./chunk-ya5p7mx7.js";import{Cd as O,Nd as i,nd as WH,rd as jH}from"./chunk-t7nj9vg8.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as AH}from"./chunk-fkhtff66.js";import{le as MH,me as fH,ne as zH}from"./chunk-xby5w74x.js";import{oe as EH}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Oe as LH}from"./chunk-61efg3yh.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-ns5vb2p4.js";import"./chunk-tt3n8gnq.js";import{$f as $H}from"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-5rtjx9xk.js";import"./chunk-74yge4ka.js";import"./chunk-7wf2acxx.js";import{sh as QH}from"./chunk-t48zm299.js";import{uh as DH,wh as H,xh as ZH,zh as N}from"./chunk-7dqh8bqm.js";import{Dh as a,Eh as s}from"./chunk-d83bfr0b.js";import{Ih as g}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-hn1xztva.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import SJ from"yargs";import{hideBin as TJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function uH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),P=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let y=K.once?.bind(K)??K.on?.bind(K);y?.("drain",x),y?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function dH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await uH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new VH({maxPendingItems:V.maxPendingItems??HH,maxPendingBytes:V.maxPendingBytes??JH,writeTimeoutMs:V.writeTimeoutMs??KH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>dH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var XH=1;function D(K){return H.Object({event_version:H.Literal(XH),...K})}var pH=D({type:H.Literal("content_delta"),delta:H.String()}),vH=D({type:H.Literal("thinking_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking"),content:H.String()}),aH=D({type:H.Literal("stream_end")}),sH=D({type:H.Literal("content"),content:H.String()}),iH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),oH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),rH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),nH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(oH)}),tH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),eH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(tH)}),HJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),JJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),VJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),ZJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),$J=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),XJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),YJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),BJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),NJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),QJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),DJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),LJ=D({type:H.Literal("task_update"),tasks:H.Array(qH)}),WJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N($H)),premature_stop_count:H.Optional(H.Integer({minimum:1}))}),jJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),xJ=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),UJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),_J=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),GJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),PJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),FJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),EJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),MJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),fJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),yJ=D({type:H.Literal("error"),message:H.String()}),rJ=ZH(H.Union([pH,vH,lH,aH,sH,iH,rH,nH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,GJ,PJ,_J,FJ,EJ,AJ,MJ,fJ,zJ,yJ]));function YH(K,V){return{event_version:XH,type:K,...V}}function bJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;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 IJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var RJ=N(["text","jsonl"]),gJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(QH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(RJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function CJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function kJ(K){let V=DH(gJ,K);if(!V.success)throw Error(`Invalid headless options: ${CJ(V.error)}`);return V.data}function hJ(K){return K.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 Q=await dJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
2
2
  `)}function OJ(K){return`[task] [${K.status}] ${K.subject}`}function wJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function mJ(K){if(!(K instanceof Error))return"Unknown error";let q=K.lastError??K;if(q.responseBody)try{let W=JSON.parse(q.responseBody)?.error?.message;if(W)return q.statusCode?`${W} (HTTP ${q.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function cJ(K){return K==="jsonl"?"jsonl":"text"}function BH(K,V){let Q=(...q)=>{for(let J of q){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function uJ(K,V,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))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 NH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify(YH(J,Z))}
3
3
  `)};return{contentDelta(J){if(V==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return q("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){q("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){q("stream_end",{});return}if(Z)K.stderr.write(`
4
4
  `);if(J)K.stdout.write(`
@@ -1,2 +1,2 @@
1
- import{N as I}from"./chunk-dj0jfyms.js";import{Nd as M}from"./chunk-qxm67agj.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
1
+ import{N as I}from"./chunk-m4tpqesg.js";import{Nd as M}from"./chunk-t7nj9vg8.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
2
2
  export{C as v,$ as w,V as x,x as y,i as z,K as A};
@@ -1,2 +1,2 @@
1
- import{wi as S}from"./chunk-myzmv0ns.js";import{Qi as f}from"./chunk-nh45xp7r.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{wi as S}from"./chunk-hn1xztva.js";import{Qi as f}from"./chunk-nh45xp7r.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{_ as h,u as i,g as j,C as k,V as l};
@@ -1,4 +1,4 @@
1
- import{$d as l_,Sd as l,Td as M$,Ud as u_,Vd as F$,Wd as j,Xd as h_,Yd as D$,Zd as c_,_d as z$,ae as n_,ce as i0,fe as p_,ge as x$}from"./chunk-4jbpvete.js";import{lf as F0}from"./chunk-z6xfknxe.js";import{bg as D0}from"./chunk-rsh4rw9k.js";import{ng as t1}from"./chunk-74yge4ka.js";import{Ah as E$,Bh as A$,Ch as W0,Dh as S0,Eh as X0}from"./chunk-d83bfr0b.js";import{Ih as X1}from"./chunk-qa4efys0.js";import{ii as u0}from"./chunk-h4j0nve8.js";import{pi as A0,si as M0}from"./chunk-n4gtzx4x.js";import{wi as a}from"./chunk-myzmv0ns.js";import{Gi as U$,Hi as Z0,Ii as K$,Ji as f,Ki as u,Mi as K0,Ni as t,Oi as k}from"./chunk-na1cney5.js";import{readdir as m_,readFile as L0,rm as G0,stat as d0}from"node:fs/promises";import*as Z from"node:path";import{nanoid as P}from"nanoid";import{createHash as P$,randomUUID as u$}from"node:crypto";import*as h from"node:fs/promises";import*as w0 from"node:path";import{execFileSync as g$}from"node:child_process";import{createHash as j$}from"node:crypto";import{readFileSync as y$}from"node:fs";var I$=/^[a-f0-9]{64}$/;function R1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&I$.test($.fingerprint)}var O1={readFile:(_)=>y$(_,"utf8"),execFile:(_,$)=>g$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},m$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function L_(_,$){return{platform:_,fingerprint:j$("sha256").update(`${_}\x00${$}`).digest("hex")}}function v$(_,$){let R=$.readFile(`/proc/${_}/stat`).trim(),O=R.lastIndexOf(")");if(O<0)throw Error("Invalid /proc process stat");let L=R.slice(O+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function x0(_,$=process.platform,R=O1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return L_($,v$(_,R));if($==="darwin"){let O=R.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return O?L_($,O):void 0}if($==="win32"){let O=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,B=R.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",O]).trim();return B?L_($,B):void 0}}catch{return}return}function L1(_,$){return x0(_,$.platform)?.fingerprint===$.fingerprint}function w4(_,$,R=O1,O=m$){if(!Number.isInteger(_)||_<=1)return!1;let B=x0(_,$.platform,R);if(B)return B.fingerprint===$.fingerprint;return!O(_)}var W1=1;function h$(_,$){let R=P$("sha256").update($).digest("hex");return w0.join(Z0(_),".locks",`${R}.lock`)}function f0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function B_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==W1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!R1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function B1(_){let $=await B_(_);if($)return $;return await new Promise((R)=>setTimeout(R,10)),B_(_)}function c$(_){try{return process.kill(_,0),!0}catch($){return f0($,"EPERM")}}async function T1(_,$){let R;try{return R=await h.open(_,"wx",384),await R.writeFile(`${JSON.stringify($)}
1
+ import{$d as l_,Sd as l,Td as M$,Ud as u_,Vd as F$,Wd as j,Xd as h_,Yd as D$,Zd as c_,_d as z$,ae as n_,ce as i0,fe as p_,ge as x$}from"./chunk-4jbpvete.js";import{lf as F0}from"./chunk-z6xfknxe.js";import{bg as D0}from"./chunk-rsh4rw9k.js";import{ng as t1}from"./chunk-74yge4ka.js";import{Ah as E$,Bh as A$,Ch as W0,Dh as S0,Eh as X0}from"./chunk-d83bfr0b.js";import{Ih as X1}from"./chunk-qa4efys0.js";import{ii as u0}from"./chunk-h4j0nve8.js";import{pi as A0,si as M0}from"./chunk-n4gtzx4x.js";import{wi as a}from"./chunk-hn1xztva.js";import{Gi as U$,Hi as Z0,Ii as K$,Ji as f,Ki as u,Mi as K0,Ni as t,Oi as k}from"./chunk-na1cney5.js";import{readdir as m_,readFile as L0,rm as G0,stat as d0}from"node:fs/promises";import*as Z from"node:path";import{nanoid as P}from"nanoid";import{createHash as P$,randomUUID as u$}from"node:crypto";import*as h from"node:fs/promises";import*as w0 from"node:path";import{execFileSync as g$}from"node:child_process";import{createHash as j$}from"node:crypto";import{readFileSync as y$}from"node:fs";var I$=/^[a-f0-9]{64}$/;function R1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&I$.test($.fingerprint)}var O1={readFile:(_)=>y$(_,"utf8"),execFile:(_,$)=>g$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},m$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function L_(_,$){return{platform:_,fingerprint:j$("sha256").update(`${_}\x00${$}`).digest("hex")}}function v$(_,$){let R=$.readFile(`/proc/${_}/stat`).trim(),O=R.lastIndexOf(")");if(O<0)throw Error("Invalid /proc process stat");let L=R.slice(O+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function x0(_,$=process.platform,R=O1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return L_($,v$(_,R));if($==="darwin"){let O=R.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return O?L_($,O):void 0}if($==="win32"){let O=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,B=R.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",O]).trim();return B?L_($,B):void 0}}catch{return}return}function L1(_,$){return x0(_,$.platform)?.fingerprint===$.fingerprint}function w4(_,$,R=O1,O=m$){if(!Number.isInteger(_)||_<=1)return!1;let B=x0(_,$.platform,R);if(B)return B.fingerprint===$.fingerprint;return!O(_)}var W1=1;function h$(_,$){let R=P$("sha256").update($).digest("hex");return w0.join(Z0(_),".locks",`${R}.lock`)}function f0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function B_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==W1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!R1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function B1(_){let $=await B_(_);if($)return $;return await new Promise((R)=>setTimeout(R,10)),B_(_)}function c$(_){try{return process.kill(_,0),!0}catch($){return f0($,"EPERM")}}async function T1(_,$){let R;try{return R=await h.open(_,"wx",384),await R.writeFile(`${JSON.stringify($)}
2
2
  `,"utf8"),!0}catch(O){if(f0(O,"EEXIST"))return!1;if(R)await h.unlink(_).catch(()=>{return});throw O}finally{await R?.close().catch(()=>{return})}}class d 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 o{filePath;record;released=!1;constructor(_,$){this.filePath=_;this.record=$}static async acquire(_,$=X1()){let R=h$($,_),O={version:W1,sessionId:_,ownerId:u$(),pid:process.pid,processIdentity:x0(process.pid),acquiredAt:new Date().toISOString()};if(await h.mkdir(w0.dirname(R),{recursive:!0,mode:448}),await T1(R,O))return new o(R,O);let B=await B1(R);if(B&&c$(B.pid)&&(!B.processIdentity||L1(B.pid,B.processIdentity)))throw new d(B.pid);if(await h.unlink(R).catch((L)=>{if(!f0(L,"ENOENT"))throw L}),await T1(R,O))return new o(R,O);throw new d((await B1(R))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await B_(this.filePath))?.ownerId!==this.record.ownerId)return;await h.unlink(this.filePath).catch(($)=>{if(!f0($,"ENOENT"))throw $})}}import{createHash as b0}from"node:crypto";import{constants as s,promises as c}from"node:fs";import i from"node:path";import{Mutex as l$}from"async-mutex";var G1=128,C1=67108864,n$=24576,J1=65536,X_=1,q1=/^[a-f0-9]{64}$/,p$=/^[a-f0-9]{64}\.txt$/,H1=64,g0=`
3
3
 
4
4
  ...[middle omitted; read the private prompt artifact for the complete request]...
@@ -1,4 +1,4 @@
1
- import{Sf as b1,Tf as L0,Uf as z1,Zf as N0}from"./chunk-yjh47zv6.js";import{cg as jO,dg as wO}from"./chunk-rsh4rw9k.js";import{gg as A1}from"./chunk-4cvmfne8.js";import{hg as b0,jg as J0}from"./chunk-602decf8.js";import{lh as S0,mh as GO,qh as I0}from"./chunk-z24ha5jk.js";import{uh as u,wh as L,zh as c1}from"./chunk-7dqh8bqm.js";import{Ih as M}from"./chunk-qa4efys0.js";import{ii as k,ji as S}from"./chunk-h4j0nve8.js";import{wi as u0}from"./chunk-myzmv0ns.js";import{Di as N}from"./chunk-rzja9zza.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
1
+ import{Sf as b1,Tf as L0,Uf as z1,Zf as N0}from"./chunk-yjh47zv6.js";import{cg as jO,dg as wO}from"./chunk-rsh4rw9k.js";import{gg as A1}from"./chunk-4cvmfne8.js";import{hg as b0,jg as J0}from"./chunk-5rtjx9xk.js";import{lh as S0,mh as GO,qh as I0}from"./chunk-7wf2acxx.js";import{uh as u,wh as L,zh as c1}from"./chunk-7dqh8bqm.js";import{Ih as M}from"./chunk-qa4efys0.js";import{ii as k,ji as S}from"./chunk-h4j0nve8.js";import{wi as u0}from"./chunk-hn1xztva.js";import{Di as N}from"./chunk-rzja9zza.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
2
2
  ${J.map((K)=>`- ${K}`).join(`
3
3
  `)}`:""].filter(Boolean).join(`
4
4