blade-code 0.10.43 → 0.10.44

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-t2r7tqn0.js → chunk-1vydfzvy.js} +1 -1
  3. package/dist/{chunk-k87p7x1e.js → chunk-3nfse1ps.js} +1 -1
  4. package/dist/{chunk-rwjm6p0f.js → chunk-50a5xx45.js} +1 -1
  5. package/dist/{chunk-7s5hw0gr.js → chunk-583kv07t.js} +1 -1
  6. package/dist/{chunk-pyk2ey7y.js → chunk-619q1w65.js} +1 -1
  7. package/dist/{chunk-bct3s5vs.js → chunk-63p5mj97.js} +1 -1
  8. package/dist/{chunk-e1vyznkn.js → chunk-706zda55.js} +1 -1
  9. package/dist/{chunk-jpz805fs.js → chunk-74hcqcn7.js} +1 -1
  10. package/dist/{chunk-8vsx6m43.js → chunk-7z5t63ke.js} +1 -1
  11. package/dist/chunk-86tba7p4.js +1 -0
  12. package/dist/{chunk-fzqsea19.js → chunk-99nka030.js} +1 -1
  13. package/dist/{chunk-6skymhz5.js → chunk-a68fws4p.js} +1 -1
  14. package/dist/{chunk-m8a2qj5c.js → chunk-agbyfdvw.js} +1 -1
  15. package/dist/{chunk-c8ddch38.js → chunk-aw7w91f0.js} +3 -3
  16. package/dist/{chunk-yqy000kg.js → chunk-cf2541w5.js} +1 -1
  17. package/dist/{chunk-n7dvqbrc.js → chunk-ckqj0pxz.js} +1 -1
  18. package/dist/{chunk-txkrtgcd.js → chunk-d18mw6d1.js} +1 -1
  19. package/dist/{chunk-32g59k4p.js → chunk-fk0q25dp.js} +1 -1
  20. package/dist/{chunk-ag5ea7ce.js → chunk-g96t2yrz.js} +1 -1
  21. package/dist/{chunk-vbpykrxd.js → chunk-j0k3mbkd.js} +1 -1
  22. package/dist/{chunk-yypnfmed.js → chunk-m1b6v1zn.js} +1 -1
  23. package/dist/{chunk-3bpxvanm.js → chunk-mzq3ps9j.js} +2 -2
  24. package/dist/{chunk-nynfqgsj.js → chunk-n4ywszmn.js} +1 -1
  25. package/dist/{chunk-qnxgzyyx.js → chunk-p4egmgt6.js} +1 -1
  26. package/dist/chunk-pk9peyzp.js +1 -0
  27. package/dist/{chunk-c3020yav.js → chunk-qzd9d0p8.js} +1 -1
  28. package/dist/{chunk-w5ayh9b8.js → chunk-r085zhqr.js} +1 -1
  29. package/dist/{chunk-372mmzj3.js → chunk-s4denzh4.js} +1 -1
  30. package/dist/{chunk-x2vqgssm.js → chunk-svj24r6g.js} +1 -1
  31. package/dist/{chunk-skb4h36j.js → chunk-synjj8b3.js} +1 -1
  32. package/dist/{chunk-qmcj20g2.js → chunk-t33njg4e.js} +1 -1
  33. package/dist/{chunk-5wzjdfde.js → chunk-tzp486wc.js} +1 -1
  34. package/dist/{chunk-nsrghqdx.js → chunk-vx5tjahq.js} +1 -1
  35. package/dist/{chunk-s9s9daak.js → chunk-wr2rkg9t.js} +1 -1
  36. package/dist/{chunk-6ch7a6xf.js → chunk-wx5nj2s2.js} +1 -1
  37. package/dist/{chunk-dcp5gg6q.js → chunk-x3cyg9pe.js} +1 -1
  38. package/dist/{chunk-d5x5wknc.js → chunk-z9absgab.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-nwzjmcxq.js +0 -1
  41. package/dist/chunk-yt9qer14.js +0 -1
@@ -1,4 +1,4 @@
1
- import{m as MH,n as fH,o as yH,p as SH,q as TH,r as bH}from"./chunk-372mmzj3.js";import{A as JH,v as AH,w as t,x as e,y as HH,z as d}from"./chunk-txkrtgcd.js";import{N as jH,P as xH,Q as UH,S as VH,V as _H}from"./chunk-c8ddch38.js";import"./chunk-7s5hw0gr.js";import"./chunk-y6tkxqjx.js";import{Ya as s,lb as LH,ub as WH}from"./chunk-dcp5gg6q.js";import"./chunk-mrsc4a55.js";import{Ac as a,ac as QH,ec as DH,pc as O}from"./chunk-ag5ea7ce.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{Xc as PH}from"./chunk-t2r7tqn0.js";import{$c as zH,Zc as FH,_c as EH}from"./chunk-nynfqgsj.js";import{ad as GH}from"./chunk-v9tzhe90.js";import"./chunk-fk4wbmv6.js";import{Ad as NH}from"./chunk-w5ayh9b8.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-jpz805fs.js";import"./chunk-yypnfmed.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-e1vyznkn.js";import"./chunk-cxzx7j0p.js";import"./chunk-6ch7a6xf.js";import{Sf as YH}from"./chunk-7sna3js9.js";import{Tf as BH,Vf as H,Wf as KH,Yf as N}from"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{dg as g}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-vbpykrxd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import MJ from"yargs";import{hideBin as fJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function wH(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",G)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),G=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){G();return}let f=K.once?.bind(K)??K.on?.bind(K);f?.("drain",x),f?.("error",j),V.addEventListener("abort",G,{once:!0})})}async function mH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await wH(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 JH({maxPendingItems:V.maxPendingItems??t,maxPendingBytes:V.maxPendingBytes??e,writeTimeoutMs:V.writeTimeoutMs??HH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>mH(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 ZH=1;function D(K){return H.Object({event_version:H.Literal(ZH),...K})}var cH=D({type:H.Literal("content_delta"),delta:H.String()}),uH=D({type:H.Literal("thinking_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking"),content:H.String()}),pH=D({type:H.Literal("stream_end")}),vH=D({type:H.Literal("content"),content:H.String()}),lH=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"]),aH=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})}),sH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),iH=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(aH)}),oH=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"])}),rH=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(oH)}),nH=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())}),tH=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())}),eH=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),HJ=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())}),JJ=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())}),KJ=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())}),VJ=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())}),ZJ=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()}),$J=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),qJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),XJ=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()}),YJ=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())}),BJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),NJ=D({type:H.Literal("task_update"),tasks:H.Array(VH)}),QJ=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}$"}))}),DJ=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}))}),LJ=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()),cost_usd:H.Optional(H.Number())}),WJ=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})),post_tokens:H.Optional(H.Number({minimum:0}))}),jJ=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"]))}),xJ=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}))}),UJ=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}))}),_J=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()}),GJ=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()}),PJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),FJ=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())}),EJ=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()}),AJ=D({type:H.Literal("error"),message:H.String()}),aJ=KH(H.Union([cH,uH,dH,pH,vH,lH,sH,iH,rH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,xJ,UJ,jJ,_J,GJ,PJ,FJ,EJ,zJ,AJ]));function $H(K,V){return{event_version:ZH,type:K,...V}}function yJ(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 SJ(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 TJ=N(["text","jsonl"]),bJ=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(YH)),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(TJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class RH{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 RJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function IJ(K){let V=BH(bJ,K);if(!V.success)throw Error(`Invalid headless options: ${RJ(V.error)}`);return V.data}function gJ(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 mJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
1
+ import{m as MH,n as fH,o as yH,p as SH,q as TH,r as bH}from"./chunk-s4denzh4.js";import{A as JH,v as AH,w as t,x as e,y as HH,z as d}from"./chunk-d18mw6d1.js";import{N as jH,P as xH,Q as UH,S as VH,V as _H}from"./chunk-aw7w91f0.js";import"./chunk-583kv07t.js";import"./chunk-y6tkxqjx.js";import{Ya as s,lb as LH,ub as WH}from"./chunk-x3cyg9pe.js";import"./chunk-mrsc4a55.js";import{Ac as a,ac as QH,ec as DH,pc as O}from"./chunk-g96t2yrz.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{Xc as PH}from"./chunk-1vydfzvy.js";import{$c as zH,Zc as FH,_c as EH}from"./chunk-n4ywszmn.js";import{ad as GH}from"./chunk-v9tzhe90.js";import"./chunk-fk4wbmv6.js";import{Ad as NH}from"./chunk-r085zhqr.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-74hcqcn7.js";import"./chunk-m1b6v1zn.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-706zda55.js";import"./chunk-cxzx7j0p.js";import"./chunk-wx5nj2s2.js";import{Sf as YH}from"./chunk-7sna3js9.js";import{Tf as BH,Vf as H,Wf as KH,Yf as N}from"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{dg as g}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-j0k3mbkd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import MJ from"yargs";import{hideBin as fJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function wH(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",G)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),G=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){G();return}let f=K.once?.bind(K)??K.on?.bind(K);f?.("drain",x),f?.("error",j),V.addEventListener("abort",G,{once:!0})})}async function mH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await wH(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 JH({maxPendingItems:V.maxPendingItems??t,maxPendingBytes:V.maxPendingBytes??e,writeTimeoutMs:V.writeTimeoutMs??HH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>mH(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 ZH=1;function D(K){return H.Object({event_version:H.Literal(ZH),...K})}var cH=D({type:H.Literal("content_delta"),delta:H.String()}),uH=D({type:H.Literal("thinking_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking"),content:H.String()}),pH=D({type:H.Literal("stream_end")}),vH=D({type:H.Literal("content"),content:H.String()}),lH=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"]),aH=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})}),sH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),iH=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(aH)}),oH=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"])}),rH=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(oH)}),nH=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())}),tH=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())}),eH=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),HJ=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())}),JJ=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())}),KJ=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())}),VJ=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())}),ZJ=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()}),$J=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),qJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),XJ=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()}),YJ=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())}),BJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),NJ=D({type:H.Literal("task_update"),tasks:H.Array(VH)}),QJ=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}$"}))}),DJ=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}))}),LJ=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()),cost_usd:H.Optional(H.Number())}),WJ=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})),post_tokens:H.Optional(H.Number({minimum:0}))}),jJ=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"]))}),xJ=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}))}),UJ=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}))}),_J=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()}),GJ=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()}),PJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),FJ=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())}),EJ=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()}),AJ=D({type:H.Literal("error"),message:H.String()}),aJ=KH(H.Union([cH,uH,dH,pH,vH,lH,sH,iH,rH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,xJ,UJ,jJ,_J,GJ,PJ,FJ,EJ,zJ,AJ]));function $H(K,V){return{event_version:ZH,type:K,...V}}function yJ(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 SJ(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 TJ=N(["text","jsonl"]),bJ=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(YH)),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(TJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class RH{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 RJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function IJ(K){let V=BH(bJ,K);if(!V.success)throw Error(`Invalid headless options: ${RJ(V.error)}`);return V.data}function gJ(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 mJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
2
2
  `)}function CJ(K){return`[task] [${K.status}] ${K.subject}`}function kJ(){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 hJ(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 OJ(K){return K==="jsonl"?"jsonl":"text"}function qH(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 wJ(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 XH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify($H(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 +1 @@
1
- import{Rg as a,Sg as b,Tg as c,Ug as d,Vg as e,Wg as f}from"./chunk-vbpykrxd.js";import"./chunk-hfrcwkc8.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{Rg as a,Sg as b,Tg as c,Ug as d,Vg as e,Wg as f}from"./chunk-j0k3mbkd.js";import"./chunk-hfrcwkc8.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1,4 +1,4 @@
1
- import{Tf as mn,Uf as j,Vf as o}from"./chunk-m8ss9rmx.js";import{Zf as bt,_f as ct}from"./chunk-j7edwwg1.js";import{dg as a}from"./chunk-kfpzrmq7.js";import{Ag as Gt,eg as Zn,fg as Xt,gg as gt,kg as pt,lg as On,mg as it,ng as Rt,og as Ct,pg as Jn,qg as zt,rg as Bt,sg as kn,tg as Kt,ug as Ut,vg as yn,wg as Ht,xg as Yt,yg as qt,zg as Vt}from"./chunk-yk9pxkc1.js";import{Eg as hn}from"./chunk-fhnkyqfb.js";import{Hg as $t,Kg as Z}from"./chunk-26wse17p.js";import{Sg as wn,Tg as an}from"./chunk-vbpykrxd.js";import{Xg as d}from"./chunk-bvf9syb2.js";import{fh as En}from"./chunk-qb0sqh29.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as l}from"node:crypto";import MM from"node:http";import{auth as sn}from"@modelcontextprotocol/sdk/client/auth.js";import eM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as J,promises as P}from"node:fs";import k from"node:path";import{Mutex as Ot}from"async-mutex";import Jt from"write-file-atomic";var Tn=1,kt=1048576,yt=5000,jt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),Sn=o.Object({version:o.Literal(Tn),credentials:o.Record(o.String(),on)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function un(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function Y(n){let t=new URL(n);return t.hash="",t.toString()}function F(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:Y(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class N{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=En()){this.stateRoot=k.join(n,"mcp"),this.tokenFilePath=k.join(this.stateRoot,"oauth-credentials.json");let t=N.mutexes.get(this.tokenFilePath);if(!t)t=new Ot,N.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?y(e):null);if(r)M.credentials[n]=j(on,r);else delete M.credentials[n];return r?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>kt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=mn(Sn,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return un(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:Tn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(Sn,n);un(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{Tf as mn,Uf as j,Vf as o}from"./chunk-m8ss9rmx.js";import{Zf as bt,_f as ct}from"./chunk-j7edwwg1.js";import{dg as a}from"./chunk-kfpzrmq7.js";import{Ag as Gt,eg as Zn,fg as Xt,gg as gt,kg as pt,lg as On,mg as it,ng as Rt,og as Ct,pg as Jn,qg as zt,rg as Bt,sg as kn,tg as Kt,ug as Ut,vg as yn,wg as Ht,xg as Yt,yg as qt,zg as Vt}from"./chunk-yk9pxkc1.js";import{Eg as hn}from"./chunk-fhnkyqfb.js";import{Hg as $t,Kg as Z}from"./chunk-26wse17p.js";import{Sg as wn,Tg as an}from"./chunk-j0k3mbkd.js";import{Xg as d}from"./chunk-bvf9syb2.js";import{fh as En}from"./chunk-qb0sqh29.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as l}from"node:crypto";import MM from"node:http";import{auth as sn}from"@modelcontextprotocol/sdk/client/auth.js";import eM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as J,promises as P}from"node:fs";import k from"node:path";import{Mutex as Ot}from"async-mutex";import Jt from"write-file-atomic";var Tn=1,kt=1048576,yt=5000,jt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),Sn=o.Object({version:o.Literal(Tn),credentials:o.Record(o.String(),on)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function un(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function Y(n){let t=new URL(n);return t.hash="",t.toString()}function F(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:Y(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class N{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=En()){this.stateRoot=k.join(n,"mcp"),this.tokenFilePath=k.join(this.stateRoot,"oauth-credentials.json");let t=N.mutexes.get(this.tokenFilePath);if(!t)t=new Ot,N.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?y(e):null);if(r)M.credentials[n]=j(on,r);else delete M.credentials[n];return r?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>kt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=mn(Sn,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return un(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:Tn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(Sn,n);un(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=k.join(this.stateRoot,".oauth-credentials.lock"),t=Zt(),M=Date.now()+yt;while(Date.now()<M)try{let e=await P.open(n,J.O_CREAT|J.O_EXCL|J.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((r)=>setTimeout(r,jt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await P.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!tM(M.pid))await P.unlink(n)}}var An="127.0.0.1",bn=7777,cn="/oauth/callback",rM=300000;class v extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Ln extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function _M(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -1,4 +1,4 @@
1
- import{Hb as HJ}from"./chunk-mrsc4a55.js";import{Ac as f$,Ib as l0,Pb as O6,Qb as U6,Rb as $2,Sb as J2,Zb as H6,fc as C$,pc as y0,rc as G2,sc as X1,tc as O2}from"./chunk-ag5ea7ce.js";import{Fc as t,Ic as D6,Jc as O0}from"./chunk-56qew7w0.js";import{Jd as T6}from"./chunk-wwvb6znp.js";import{Kd as ZJ,Ld as C0,Md as a6,Pd as WJ,Qd as q2,Sd as Y6}from"./chunk-egczvfsv.js";import{Ae as YJ,we as v0,xe as A0}from"./chunk-tpa75y39.js";import{Je as Z$}from"./chunk-e1vyznkn.js";import{dg as a}from"./chunk-kfpzrmq7.js";import{Eg as G0}from"./chunk-fhnkyqfb.js";import{Sg as G6}from"./chunk-vbpykrxd.js";import{_g as H$,ah as a2,bh as z0,ch as K1,eh as L6,gh as q6}from"./chunk-qb0sqh29.js";import{hh as _8}from"./chunk-hfrcwkc8.js";function $$($){return $.role==="system"&&Array.isArray($.content)}function e0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class a${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find($$);if(this._contextualSystemMessages=$.messages.filter(e0),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!$$(W)&&!e0(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!e0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter($$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!$$(J)&&!e0(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(e0),this._history=$.filter((J)=>!$$(J)&&!e0(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function x2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function h2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import i0 from"node:path";var wJ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),LJ=/^(LD_.+|DYLD_.+|PATH)$/,R2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function S$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(!wJ.has(K))break;J=Y}return J}function m4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(LJ.test(K))break;J=Y}return J}var qJ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function I1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of qJ){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function s$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){Z+=X,H=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function C2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let H=$[Y];if(W){W=!1;continue}if(H==="\\"&&!J){W=!0;continue}if(H==="'"&&!Z){J=!J;continue}if(H==='"'&&!J){Z=!Z;continue}if(J)continue;if(H==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(H==="`")return!0;if(Z)continue;if(H==="|")return!0;if(H===">"||H==="<")return!0;if(H==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function A$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){if(H=!0,Y){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,H=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var GJ=new Set(["npm","pnpm","yarn","bun"]),I2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),OJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function UJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function yJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function FJ($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=A$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let H=Y[1];if(!H||H==="-")return;let K=i0.isAbsolute(H)?i0.resolve(H):i0.resolve(Z,H);if(!l0.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function J$($,J){let Z=S$(yJ($)),W=s$(Z);if(!W||C2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:FJ(Z,W,J);if(!Y)return!1;let H=A$(Y);if(H.length===0||H.some((z)=>[...OJ].some((j)=>z===j||z.startsWith(`${j}=`))))return!1;let[K,X,Q]=H;if(GJ.has(K??""))return UJ(X==="run"?Q:X)||X==="--test";if((K==="npx"||K==="bunx")&&I2.has(X??""))return!0;if(I2.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function l4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!i0.isAbsolute($);let Z=i0.isAbsolute($)?i0.resolve($):i0.resolve(J,$);return l0.isWithinWorkspace(Z,J)}var v1=G0("Agent"),_J=3;function p1($,J,Z){if($!=="length")return{action:"none"};if(J>=_J)return{action:"truncated"};if(x2(Z)==="stop")return v1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var bJ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],NJ=/```[\s\S]{50,}```/,v2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",PJ=2;function g1($,J,Z=!0){if(!$||J>=PJ)return{action:"none"};if(!Z&&NJ.test($))return{action:"retry",prompt:v2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(bJ.some((K)=>K.test(W)))return{action:"retry",prompt:v2};return{action:"none"}}var SJ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],p2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},AJ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},EJ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",fJ="Required verification did not run successfully before the retry limit.",TJ=3;function m2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&J$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let H of Y)if(typeof H==="string"&&J$(H,W))$.add(H)}function m1($,J,Z){if(!$||!SJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(p2).filter((Q)=>p2[Q].test($)),Y=[...J],H=W.filter((Q)=>!Y.some((z)=>AJ[Q].test(z)));if(W.length>0?H.length===0:Y.some((Q)=>J$(Q)))return{action:"none"};if(Z>=TJ)return{action:"fail",message:fJ};let X=W.length>1&&H.length>0?` Missing successful verification categories: ${H.join(", ")}.`:"";return{action:"retry",prompt:`${EJ}${X}`}}var kJ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],u2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function d2($){return typeof $==="string"&&u2.some((J)=>J.test($))}var xJ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],MJ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function hJ($){if(typeof $!=="string")return;if(MJ.some((J)=>J.test($)))return"multiple-allowed";return xJ.some((J)=>J.test($))?"required":void 0}function e$($){for(let J of $){let Z=hJ(J);if(Z!==void 0)return Z==="required"}return!1}var RJ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",CJ="Required delegation did not complete before the retry limit.",IJ=3;function c2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=e$(W),H=!1;if(!Y)for(let K of W){if(u2.some((X)=>X.test(K)))break;if(kJ.some((X)=>X.test(K))){H=!0;break}}if(W.length===0||!Y&&!H||J.has("Task"))return{action:"none"};if(Z>=IJ)return{action:"fail",message:CJ};return{action:"retry",prompt:RJ}}var vJ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],pJ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],gJ=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function i2($){return gJ.reduce((J,Z)=>J.replace(Z," "),$)}function $1($){if(typeof $!=="string")return!1;let J=i2($);return vJ.some((Z)=>Z.test(J))}var mJ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",uJ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",dJ="Required worktree lifecycle did not complete before the retry limit.",cJ=3;function l2($,J,Z){if(!$)return{action:"none"};let W=i2($);if(!$1(W))return{action:"none"};let Y=pJ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let H=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!H)return{action:"none"};if(Z>=cJ)return{action:"fail",message:dJ};return{action:"retry",tool:H,prompt:H==="EnterWorktree"?mJ:uJ}}var g2=30000;async function u1($){try{let Z=Z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??a(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((H)=>{W=setTimeout(()=>H("timeout"),g2)});try{let H=await Promise.race([Z,Y]);if(H==="timeout")return v1.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=H;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return v1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function iJ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var lJ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function rJ($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function nJ($){let J=$;for(let Q of lJ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let H=Y.slice(0,60),K=H.lastIndexOf(" ");return`${(K>36?H.slice(0,K):H).trimEnd()}…`}function r2($){return nJ(rJ($))}import{EventEmitter as oJ}from"events";import n2 from"node:path";function d1($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=d1($);return JSON.stringify([J.projectPath,J.sessionId])}function Y5($,J){return o2($)===o2(J)}class W$ extends oJ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!W$.instance)W$.instance=new W$;return W$.instance}publish($,J,Z,W){let Y=d1($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var E$=W$.getInstance();var M0=G0("Agent"),J1=new Set;async function aJ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(J1.has(Z))return;if(J1.size>=5000)J1.clear();J1.add(Z);try{let W=$.workspaceRoot,Y=await f$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let H=r2(J);if(!H)return;await f$.updateSessionMetadata(Z,Y.projectPath,{title:H}),E$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:H})}catch(W){M0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var c1=`<turn_aborted>
1
+ import{Hb as HJ}from"./chunk-mrsc4a55.js";import{Ac as f$,Ib as l0,Pb as O6,Qb as U6,Rb as $2,Sb as J2,Zb as H6,fc as C$,pc as y0,rc as G2,sc as X1,tc as O2}from"./chunk-g96t2yrz.js";import{Fc as t,Ic as D6,Jc as O0}from"./chunk-56qew7w0.js";import{Jd as T6}from"./chunk-wwvb6znp.js";import{Kd as ZJ,Ld as C0,Md as a6,Pd as WJ,Qd as q2,Sd as Y6}from"./chunk-egczvfsv.js";import{Ae as YJ,we as v0,xe as A0}from"./chunk-tpa75y39.js";import{Je as Z$}from"./chunk-706zda55.js";import{dg as a}from"./chunk-kfpzrmq7.js";import{Eg as G0}from"./chunk-fhnkyqfb.js";import{Sg as G6}from"./chunk-j0k3mbkd.js";import{_g as H$,ah as a2,bh as z0,ch as K1,eh as L6,gh as q6}from"./chunk-qb0sqh29.js";import{hh as _8}from"./chunk-hfrcwkc8.js";function $$($){return $.role==="system"&&Array.isArray($.content)}function e0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class a${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find($$);if(this._contextualSystemMessages=$.messages.filter(e0),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!$$(W)&&!e0(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!e0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter($$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!$$(J)&&!e0(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(e0),this._history=$.filter((J)=>!$$(J)&&!e0(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function x2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function h2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import i0 from"node:path";var wJ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),LJ=/^(LD_.+|DYLD_.+|PATH)$/,R2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function S$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(!wJ.has(K))break;J=Y}return J}function m4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(LJ.test(K))break;J=Y}return J}var qJ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function I1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of qJ){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function s$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){Z+=X,H=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function C2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let H=$[Y];if(W){W=!1;continue}if(H==="\\"&&!J){W=!0;continue}if(H==="'"&&!Z){J=!J;continue}if(H==='"'&&!J){Z=!Z;continue}if(J)continue;if(H==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(H==="`")return!0;if(Z)continue;if(H==="|")return!0;if(H===">"||H==="<")return!0;if(H==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function A$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){if(H=!0,Y){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,H=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var GJ=new Set(["npm","pnpm","yarn","bun"]),I2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),OJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function UJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function yJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function FJ($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=A$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let H=Y[1];if(!H||H==="-")return;let K=i0.isAbsolute(H)?i0.resolve(H):i0.resolve(Z,H);if(!l0.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function J$($,J){let Z=S$(yJ($)),W=s$(Z);if(!W||C2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:FJ(Z,W,J);if(!Y)return!1;let H=A$(Y);if(H.length===0||H.some((z)=>[...OJ].some((j)=>z===j||z.startsWith(`${j}=`))))return!1;let[K,X,Q]=H;if(GJ.has(K??""))return UJ(X==="run"?Q:X)||X==="--test";if((K==="npx"||K==="bunx")&&I2.has(X??""))return!0;if(I2.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function l4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!i0.isAbsolute($);let Z=i0.isAbsolute($)?i0.resolve($):i0.resolve(J,$);return l0.isWithinWorkspace(Z,J)}var v1=G0("Agent"),_J=3;function p1($,J,Z){if($!=="length")return{action:"none"};if(J>=_J)return{action:"truncated"};if(x2(Z)==="stop")return v1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var bJ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],NJ=/```[\s\S]{50,}```/,v2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",PJ=2;function g1($,J,Z=!0){if(!$||J>=PJ)return{action:"none"};if(!Z&&NJ.test($))return{action:"retry",prompt:v2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(bJ.some((K)=>K.test(W)))return{action:"retry",prompt:v2};return{action:"none"}}var SJ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],p2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},AJ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},EJ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",fJ="Required verification did not run successfully before the retry limit.",TJ=3;function m2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&J$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let H of Y)if(typeof H==="string"&&J$(H,W))$.add(H)}function m1($,J,Z){if(!$||!SJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(p2).filter((Q)=>p2[Q].test($)),Y=[...J],H=W.filter((Q)=>!Y.some((z)=>AJ[Q].test(z)));if(W.length>0?H.length===0:Y.some((Q)=>J$(Q)))return{action:"none"};if(Z>=TJ)return{action:"fail",message:fJ};let X=W.length>1&&H.length>0?` Missing successful verification categories: ${H.join(", ")}.`:"";return{action:"retry",prompt:`${EJ}${X}`}}var kJ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],u2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function d2($){return typeof $==="string"&&u2.some((J)=>J.test($))}var xJ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],MJ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function hJ($){if(typeof $!=="string")return;if(MJ.some((J)=>J.test($)))return"multiple-allowed";return xJ.some((J)=>J.test($))?"required":void 0}function e$($){for(let J of $){let Z=hJ(J);if(Z!==void 0)return Z==="required"}return!1}var RJ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",CJ="Required delegation did not complete before the retry limit.",IJ=3;function c2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=e$(W),H=!1;if(!Y)for(let K of W){if(u2.some((X)=>X.test(K)))break;if(kJ.some((X)=>X.test(K))){H=!0;break}}if(W.length===0||!Y&&!H||J.has("Task"))return{action:"none"};if(Z>=IJ)return{action:"fail",message:CJ};return{action:"retry",prompt:RJ}}var vJ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],pJ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],gJ=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function i2($){return gJ.reduce((J,Z)=>J.replace(Z," "),$)}function $1($){if(typeof $!=="string")return!1;let J=i2($);return vJ.some((Z)=>Z.test(J))}var mJ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",uJ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",dJ="Required worktree lifecycle did not complete before the retry limit.",cJ=3;function l2($,J,Z){if(!$)return{action:"none"};let W=i2($);if(!$1(W))return{action:"none"};let Y=pJ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let H=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!H)return{action:"none"};if(Z>=cJ)return{action:"fail",message:dJ};return{action:"retry",tool:H,prompt:H==="EnterWorktree"?mJ:uJ}}var g2=30000;async function u1($){try{let Z=Z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??a(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((H)=>{W=setTimeout(()=>H("timeout"),g2)});try{let H=await Promise.race([Z,Y]);if(H==="timeout")return v1.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=H;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return v1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function iJ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var lJ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function rJ($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function nJ($){let J=$;for(let Q of lJ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let H=Y.slice(0,60),K=H.lastIndexOf(" ");return`${(K>36?H.slice(0,K):H).trimEnd()}…`}function r2($){return nJ(rJ($))}import{EventEmitter as oJ}from"events";import n2 from"node:path";function d1($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=d1($);return JSON.stringify([J.projectPath,J.sessionId])}function Y5($,J){return o2($)===o2(J)}class W$ extends oJ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!W$.instance)W$.instance=new W$;return W$.instance}publish($,J,Z,W){let Y=d1($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var E$=W$.getInstance();var M0=G0("Agent"),J1=new Set;async function aJ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(J1.has(Z))return;if(J1.size>=5000)J1.clear();J1.add(Z);try{let W=$.workspaceRoot,Y=await f$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let H=r2(J);if(!H)return;await f$.updateSessionMetadata(Z,Y.projectPath,{title:H}),E$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:H})}catch(W){M0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var c1=`<turn_aborted>
2
2
  The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
3
3
  </turn_aborted>`,r0="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",s2="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class Y$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function n0($){return $.executionEngine?.getContextManager()}async function K0($,J,Z,W=null,Y,H={}){let K=H.required??$.executionEngine!==void 0;try{let X=n0($),Q=typeof Z==="string"?Z.trim()!=="":Z.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(X&&J.sessionId&&Q){let z=await X.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!z)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)aJ(J,Z);return z}if(K&&J.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(X){if(M0.warn("[Loop] 保存用户消息失败:",X),K)throw new Y$("user_message",{cause:X})}return null}async function g($,J,Z,W,Y,H,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=n0($),z=Boolean(Z.trim()||Y?.trim());if(Q&&J.sessionId&&z){let j=await Q.saveMessage(J.sessionId,"assistant",Z,W,H,J.subagentInfo,Y);if(X&&!j)throw Error("Durable assistant-message commit returned no identity");return j}if(X&&J.sessionId&&z)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(M0.warn("[Loop] 保存助手消息失败:",Q),X)throw new Y$("assistant_message",{cause:Q})}return null}async function t2($,J,Z){try{let W=n0($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",c1,Z,void 0,J.subagentInfo)}catch(W){M0.warn("[Loop] 保存中断边界失败:",W)}return null}async function e2($,J,Z,W,Y){try{let H=n0($);if(!H||!J.sessionId||Z.length===0)return null;return await H.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(H){M0.warn("[Loop] 保存 contextual project rules provenance 失败:",H)}return null}async function i1($,J,Z,W,Y,H={}){try{let K=n0($);if(K&&J.sessionId){let X=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo);if(H.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(H.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(M0.warn("[Loop] 保存工具调用失败:",K),H.required)throw K}return null}async function Z1($,J,Z,W,Y,H,K,X,Q,z={}){try{let j=n0($);if(j&&J.sessionId){let q=await j.saveToolResult(J.sessionId,Z,W,Y,H,K,J.subagentInfo,X,Q);if(z.required&&!q)throw Error("Durable tool-result commit returned no identity");return q}if(z.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(j){if(M0.warn("[Loop] 保存工具结果失败:",j),z.required)throw j}return null}async function T$($,J,Z,W,Y={}){try{let H=n0($);if(H&&J.sessionId){let K=await H.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(H){if(M0.warn("[Loop] 保存压缩数据失败:",H),Y.required)throw H}return null}import{createHash as y4}from"node:crypto";import{promises as K8}from"node:fs";import X8 from"node:path";import{nanoid as R0}from"nanoid";import*as i from"node:fs/promises";import*as o0 from"node:path";var $6={enabled:!0,maxIndexLines:200};var sJ="memory",J6="MEMORY.md";class l1{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=H$($);this.memoryDir=o0.join(W,sJ)}this.config={...$6,...J}}async initialize(){if(this.initialized)return;await i.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=o0.join(this.memoryDir,J6);try{let J=await i.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
4
4
  `),Y=Z.slice(0,this.config.maxIndexLines).join(`
@@ -1,2 +1,2 @@
1
- import{Sg as S}from"./chunk-vbpykrxd.js";import{hh as f}from"./chunk-hfrcwkc8.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{Sg as S}from"./chunk-j0k3mbkd.js";import{hh as f}from"./chunk-hfrcwkc8.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 a,u as b,g as c,C as d,V as e};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.43",
3
+ "version": "0.10.44",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{a,b,c,d,e}from"./chunk-d5x5wknc.js";import"./chunk-vbpykrxd.js";import"./chunk-hfrcwkc8.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +0,0 @@
1
- import{Xc as a,Yc as b}from"./chunk-t2r7tqn0.js";import"./chunk-vbpykrxd.js";import"./chunk-hfrcwkc8.js";export{a as globalOptions,b as cliConfig};