blade-code 0.10.95 → 0.10.96

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 (61) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-3aayczyy.js → chunk-0r4bnnr4.js} +1 -1
  3. package/dist/{chunk-bd4nqrtm.js → chunk-0vkk338p.js} +1 -1
  4. package/dist/{chunk-871g570t.js → chunk-1t097t5f.js} +326 -326
  5. package/dist/{chunk-hfd00skc.js → chunk-36tgee8v.js} +1 -1
  6. package/dist/{chunk-hqb6qxzj.js → chunk-46shzdny.js} +1 -1
  7. package/dist/{chunk-09ya3a21.js → chunk-4n4a3vm2.js} +1 -1
  8. package/dist/{chunk-hrpqz2jv.js → chunk-4p6q87bp.js} +1 -1
  9. package/dist/{chunk-4smdhn1h.js → chunk-4pamygxp.js} +1 -1
  10. package/dist/{chunk-4fmyjf1x.js → chunk-50em9ww2.js} +1 -1
  11. package/dist/{chunk-vt99w0vh.js → chunk-5j0b62sr.js} +1 -1
  12. package/dist/{chunk-hajer580.js → chunk-5vg1dwh1.js} +1 -1
  13. package/dist/{chunk-2zzc7g29.js → chunk-721g4w9f.js} +1 -1
  14. package/dist/{chunk-sckqp0t9.js → chunk-729bsa9b.js} +1 -1
  15. package/dist/{chunk-xm8w4jaa.js → chunk-7jg5d0bz.js} +1 -1
  16. package/dist/{chunk-e5ht9d18.js → chunk-9vp2qgt2.js} +1 -1
  17. package/dist/{chunk-qp165b79.js → chunk-ax8tta9d.js} +1 -1
  18. package/dist/{chunk-rjw8pj7t.js → chunk-b12wtvac.js} +2 -2
  19. package/dist/{chunk-es4evt6m.js → chunk-bfxj0w4r.js} +1 -1
  20. package/dist/{chunk-f66cptes.js → chunk-brs43rma.js} +1 -1
  21. package/dist/{chunk-cnnht4m3.js → chunk-bss2kc28.js} +1 -1
  22. package/dist/{chunk-rrav5aea.js → chunk-c9zd429t.js} +1 -1
  23. package/dist/{chunk-esstp9h0.js → chunk-g9m309s9.js} +2 -2
  24. package/dist/{chunk-eqbcxa12.js → chunk-ggf76jxn.js} +1 -1
  25. package/dist/{chunk-vxwqsmqg.js → chunk-gnffwz1c.js} +1 -1
  26. package/dist/{chunk-wwzc3ryj.js → chunk-jrjaente.js} +1 -1
  27. package/dist/{chunk-8pvsw4gw.js → chunk-jzc7ez35.js} +1 -1
  28. package/dist/{chunk-ktt7vmqz.js → chunk-kpxz0hbg.js} +1 -1
  29. package/dist/{chunk-cvybf60x.js → chunk-p3nqvg65.js} +1 -1
  30. package/dist/{chunk-h2a3edj4.js → chunk-q74xmdkf.js} +1 -1
  31. package/dist/{chunk-s2erwc49.js → chunk-qrj0d6a5.js} +1 -1
  32. package/dist/{chunk-bxtqcgvs.js → chunk-qstdm5xh.js} +1 -1
  33. package/dist/{chunk-2ge1zqts.js → chunk-srqfz4rw.js} +1 -1
  34. package/dist/chunk-tw63vfgh.js +118 -0
  35. package/dist/chunk-vdfwj5fy.js +1 -0
  36. package/dist/{chunk-2f0wn3ne.js → chunk-wj403wry.js} +7 -7
  37. package/dist/chunk-x9t8340h.js +1 -0
  38. package/dist/{chunk-4p69xraf.js → chunk-xzzrtwjx.js} +1 -1
  39. package/dist/web/assets/{ChatView-CpKiglLV.js → ChatView-EtPiVi9S.js} +4 -4
  40. package/dist/web/assets/{CodeBlockHighlighter-BzmHeWKU.js → CodeBlockHighlighter-CJJQKiYA.js} +1 -1
  41. package/dist/web/assets/{FilePreview-uShTCL2_.js → FilePreview-p9GkBrrr.js} +1 -1
  42. package/dist/web/assets/{KanbanBoard-CnZoKZFy.js → KanbanBoard-B3HgXU0l.js} +1 -1
  43. package/dist/web/assets/{MarkdownRenderer-CxcqGo57.js → MarkdownRenderer-DQd1r_NH.js} +3 -3
  44. package/dist/web/assets/{SettingsModal-Bu5uH8ic.js → SettingsModal-CJ8604CG.js} +1 -1
  45. package/dist/web/assets/{TaskSwitcher-BDwk7i6w.js → TaskSwitcher-zfuhsPf1.js} +1 -1
  46. package/dist/web/assets/{TerminalPanel-PiLhnW-8.js → TerminalPanel-BF6GORqQ.js} +1 -1
  47. package/dist/web/assets/{arrow-left-B7RwOx8T.js → arrow-left-BSNY0aTj.js} +1 -1
  48. package/dist/web/assets/{calendar-clock-BeSXiMFw.js → calendar-clock-BizCOffP.js} +1 -1
  49. package/dist/web/assets/{chevrons-up-down-DuC8PppK.js → chevrons-up-down-CN8I3dkY.js} +1 -1
  50. package/dist/web/assets/{clock-3-lYrt_Amt.js → clock-3-D5q6Flxt.js} +1 -1
  51. package/dist/web/assets/{external-link-BTHyQJWk.js → external-link-Dw5epjDt.js} +1 -1
  52. package/dist/web/assets/{folder-CX6zAF9w.js → folder-Dcq3CYVD.js} +1 -1
  53. package/dist/web/assets/{index-FdbcPJSj.js → index-CpHES-wJ.js} +48 -48
  54. package/dist/web/assets/{pause-qlDcCjBJ.js → pause-DhspNLAg.js} +1 -1
  55. package/dist/web/assets/{play-BGPTTFWa.js → play-B4wnlOAa.js} +1 -1
  56. package/dist/web/assets/{teamService-Bk8B4hZp.js → teamService-DelV4FvL.js} +1 -1
  57. package/dist/web/index.html +1 -1
  58. package/package.json +1 -1
  59. package/dist/chunk-4hb71f98.js +0 -1
  60. package/dist/chunk-cbafxem4.js +0 -118
  61. package/dist/chunk-gnzcz6e1.js +0 -1
@@ -1,4 +1,4 @@
1
- import{m as SH,n as TH,o as bH,p as IH,q as RH,r as gH}from"./chunk-4fmyjf1x.js";import{A as VH,v as yH,w as HH,x as JH,y as KH,z as d}from"./chunk-qp165b79.js";import{$ as FH,T as _H,V as GH,W as PH,Y as qH}from"./chunk-871g570t.js";import"./chunk-z5rtzcm4.js";import"./chunk-2f0wn3ne.js";import"./chunk-8eh0vp98.js";import{Cb as xH,Lb as UH,qb as o}from"./chunk-rjw8pj7t.js";import"./chunk-ya5p7mx7.js";import{Cd as O,Nd as i,nd as WH,rd as jH}from"./chunk-cbafxem4.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as AH}from"./chunk-2ge1zqts.js";import{le as MH,me as fH,ne as zH}from"./chunk-e5ht9d18.js";import{oe as EH}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Oe as LH}from"./chunk-eqbcxa12.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-vxwqsmqg.js";import"./chunk-ktt7vmqz.js";import{$f as $H}from"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-h2a3edj4.js";import"./chunk-74yge4ka.js";import"./chunk-4p69xraf.js";import{sh as QH}from"./chunk-t48zm299.js";import{uh as DH,wh as H,xh as ZH,zh as N}from"./chunk-7dqh8bqm.js";import{Dh as a,Eh as s}from"./chunk-d83bfr0b.js";import{Ih as g}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-vt99w0vh.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import SJ from"yargs";import{hideBin as TJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function uH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),P=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let y=K.once?.bind(K)??K.on?.bind(K);y?.("drain",x),y?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function dH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await uH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new VH({maxPendingItems:V.maxPendingItems??HH,maxPendingBytes:V.maxPendingBytes??JH,writeTimeoutMs:V.writeTimeoutMs??KH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>dH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var XH=1;function D(K){return H.Object({event_version:H.Literal(XH),...K})}var pH=D({type:H.Literal("content_delta"),delta:H.String()}),vH=D({type:H.Literal("thinking_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking"),content:H.String()}),aH=D({type:H.Literal("stream_end")}),sH=D({type:H.Literal("content"),content:H.String()}),iH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),oH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),rH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),nH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(oH)}),tH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),eH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(tH)}),HJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),JJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),VJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),ZJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),$J=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),XJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),YJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),BJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),NJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),QJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),DJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),LJ=D({type:H.Literal("task_update"),tasks:H.Array(qH)}),WJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N($H)),premature_stop_count:H.Optional(H.Integer({minimum:1}))}),jJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),xJ=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),UJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),_J=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),GJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),PJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),FJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),EJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),MJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),fJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),yJ=D({type:H.Literal("error"),message:H.String()}),rJ=ZH(H.Union([pH,vH,lH,aH,sH,iH,rH,nH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,GJ,PJ,_J,FJ,EJ,AJ,MJ,fJ,zJ,yJ]));function YH(K,V){return{event_version:XH,type:K,...V}}function bJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function IJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var RJ=N(["text","jsonl"]),gJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(QH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(RJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function CJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function kJ(K){let V=DH(gJ,K);if(!V.success)throw Error(`Invalid headless options: ${CJ(V.error)}`);return V.data}function hJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await dJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
1
+ import{m as SH,n as TH,o as bH,p as IH,q as RH,r as gH}from"./chunk-50em9ww2.js";import{A as VH,v as yH,w as HH,x as JH,y as KH,z as d}from"./chunk-ax8tta9d.js";import{$ as FH,T as _H,V as GH,W as PH,Y as qH}from"./chunk-1t097t5f.js";import"./chunk-z5rtzcm4.js";import"./chunk-wj403wry.js";import"./chunk-8eh0vp98.js";import{Cb as xH,Lb as UH,qb as o}from"./chunk-b12wtvac.js";import"./chunk-ya5p7mx7.js";import{Cd as O,Nd as i,nd as WH,rd as jH}from"./chunk-tw63vfgh.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as AH}from"./chunk-srqfz4rw.js";import{le as MH,me as fH,ne as zH}from"./chunk-9vp2qgt2.js";import{oe as EH}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Oe as LH}from"./chunk-ggf76jxn.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-gnffwz1c.js";import"./chunk-kpxz0hbg.js";import{$f as $H}from"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-q74xmdkf.js";import"./chunk-74yge4ka.js";import"./chunk-xzzrtwjx.js";import{sh as QH}from"./chunk-t48zm299.js";import{uh as DH,wh as H,xh as ZH,zh as N}from"./chunk-7dqh8bqm.js";import{Dh as a,Eh as s}from"./chunk-d83bfr0b.js";import{Ih as g}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-5j0b62sr.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import SJ from"yargs";import{hideBin as TJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function uH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),P=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let y=K.once?.bind(K)??K.on?.bind(K);y?.("drain",x),y?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function dH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await uH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new VH({maxPendingItems:V.maxPendingItems??HH,maxPendingBytes:V.maxPendingBytes??JH,writeTimeoutMs:V.writeTimeoutMs??KH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>dH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var XH=1;function D(K){return H.Object({event_version:H.Literal(XH),...K})}var pH=D({type:H.Literal("content_delta"),delta:H.String()}),vH=D({type:H.Literal("thinking_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking"),content:H.String()}),aH=D({type:H.Literal("stream_end")}),sH=D({type:H.Literal("content"),content:H.String()}),iH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),oH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),rH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),nH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(oH)}),tH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),eH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(tH)}),HJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),JJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),VJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),ZJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),$J=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),XJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),YJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),BJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),NJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),QJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),DJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),LJ=D({type:H.Literal("task_update"),tasks:H.Array(qH)}),WJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N($H)),premature_stop_count:H.Optional(H.Integer({minimum:1}))}),jJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),xJ=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),UJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),_J=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),GJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),PJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),FJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),EJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),MJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),fJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),yJ=D({type:H.Literal("error"),message:H.String()}),rJ=ZH(H.Union([pH,vH,lH,aH,sH,iH,rH,nH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,GJ,PJ,_J,FJ,EJ,AJ,MJ,fJ,zJ,yJ]));function YH(K,V){return{event_version:XH,type:K,...V}}function bJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function IJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var RJ=N(["text","jsonl"]),gJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(QH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(RJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function CJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function kJ(K){let V=DH(gJ,K);if(!V.success)throw Error(`Invalid headless options: ${CJ(V.error)}`);return V.data}function hJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await dJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
2
2
  `)}function OJ(K){return`[task] [${K.status}] ${K.subject}`}function wJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function mJ(K){if(!(K instanceof Error))return"Unknown error";let q=K.lastError??K;if(q.responseBody)try{let W=JSON.parse(q.responseBody)?.error?.message;if(W)return q.statusCode?`${W} (HTTP ${q.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function cJ(K){return K==="jsonl"?"jsonl":"text"}function BH(K,V){let Q=(...q)=>{for(let J of q){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function uJ(K,V,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function NH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify(YH(J,Z))}
3
3
  `)};return{contentDelta(J){if(V==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return q("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){q("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){q("stream_end",{});return}if(Z)K.stderr.write(`
4
4
  `);if(J)K.stdout.write(`
@@ -1 +1 @@
1
- import{le as a,me as b,ne as c}from"./chunk-e5ht9d18.js";import"./chunk-wbfa6xce.js";import"./chunk-eqbcxa12.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-4cvmfne8.js";import"./chunk-4p69xraf.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-vt99w0vh.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
1
+ import{le as a,me as b,ne as c}from"./chunk-9vp2qgt2.js";import"./chunk-wbfa6xce.js";import"./chunk-ggf76jxn.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-4cvmfne8.js";import"./chunk-xzzrtwjx.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-5j0b62sr.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,4 +1,4 @@
1
- import{He as N}from"./chunk-eqbcxa12.js";import{jg as $}from"./chunk-h2a3edj4.js";import{Ih as _}from"./chunk-qa4efys0.js";import{gi as Y,ii as Z}from"./chunk-h4j0nve8.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{He as N}from"./chunk-ggf76jxn.js";import{jg as $}from"./chunk-q74xmdkf.js";import{Ih as _}from"./chunk-qa4efys0.js";import{gi as Y,ii as Z}from"./chunk-h4j0nve8.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
4
4
  export{O as pe,y as qe,j as re,C as se};
@@ -1 +1 @@
1
- import{Ab as d,Bb as e,Cb as f,Db as g,Eb as h,Fb as i,Gb as j,Hb as k,Ob as l,Pb as m,Qb as n,Rb as o,Tb as p,Ub as q,Vb as r,tb as a,ub as b,wb as c}from"./chunk-rjw8pj7t.js";import"./chunk-ya5p7mx7.js";import"./chunk-cbafxem4.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-z6xfknxe.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-h2a3edj4.js";import"./chunk-74yge4ka.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-vt99w0vh.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
1
+ import{Ab as d,Bb as e,Cb as f,Db as g,Eb as h,Fb as i,Gb as j,Hb as k,Ob as l,Pb as m,Qb as n,Rb as o,Tb as p,Ub as q,Vb as r,tb as a,ub as b,wb as c}from"./chunk-b12wtvac.js";import"./chunk-ya5p7mx7.js";import"./chunk-tw63vfgh.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-z6xfknxe.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-q74xmdkf.js";import"./chunk-74yge4ka.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-5j0b62sr.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1 +1 @@
1
- import{nf as a,of as b,pf as c}from"./chunk-vxwqsmqg.js";import"./chunk-4p69xraf.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-vt99w0vh.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
1
+ import{nf as a,of as b,pf as c}from"./chunk-gnffwz1c.js";import"./chunk-xzzrtwjx.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-5j0b62sr.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1,4 +1,4 @@
1
- import{pa as F,ra as L}from"./chunk-871g570t.js";import{Dd as $,Fd as B,Nd as Q}from"./chunk-cbafxem4.js";import{Nf as y}from"./chunk-ktt7vmqz.js";import{Ih as V}from"./chunk-qa4efys0.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{pa as F,ra as L}from"./chunk-1t097t5f.js";import{Dd as $,Fd as B,Nd as Q}from"./chunk-tw63vfgh.js";import{Nf as y}from"./chunk-kpxz0hbg.js";import{Ih as V}from"./chunk-qa4efys0.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{j as m,I as n,M as o,R as p,_ as q,C as r};
@@ -1,2 +1,2 @@
1
- import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.95",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
1
+ import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.96",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
2
2
  export{y as vi,p as wi,v as xi,g as yi,f as zi,w as Ai};
@@ -1,2 +1,2 @@
1
- import{wi as S}from"./chunk-vt99w0vh.js";import{Qi as f}from"./chunk-nh45xp7r.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{wi as S}from"./chunk-5j0b62sr.js";import{Qi as f}from"./chunk-nh45xp7r.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{_ as h,u as i,g as j,C as k,V as l};
@@ -1,4 +1,4 @@
1
- import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-4fmyjf1x.js";import{$ as y,T as M}from"./chunk-871g570t.js";import"./chunk-z5rtzcm4.js";import"./chunk-2f0wn3ne.js";import"./chunk-8eh0vp98.js";import{Cb as h,Lb as A}from"./chunk-rjw8pj7t.js";import"./chunk-ya5p7mx7.js";import{Nd as U,zd as w}from"./chunk-cbafxem4.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as C}from"./chunk-2ge1zqts.js";import{le as I,me as S,ne as v}from"./chunk-e5ht9d18.js";import{oe as O}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Le as P}from"./chunk-eqbcxa12.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-vxwqsmqg.js";import"./chunk-ktt7vmqz.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-h2a3edj4.js";import"./chunk-74yge4ka.js";import"./chunk-4p69xraf.js";import{sh as F}from"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Ih as z}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-vt99w0vh.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-50em9ww2.js";import{$ as y,T as M}from"./chunk-1t097t5f.js";import"./chunk-z5rtzcm4.js";import"./chunk-wj403wry.js";import"./chunk-8eh0vp98.js";import{Cb as h,Lb as A}from"./chunk-b12wtvac.js";import"./chunk-ya5p7mx7.js";import{Nd as U,zd as w}from"./chunk-tw63vfgh.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as C}from"./chunk-srqfz4rw.js";import{le as I,me as S,ne as v}from"./chunk-9vp2qgt2.js";import{oe as O}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Le as P}from"./chunk-ggf76jxn.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-gnffwz1c.js";import"./chunk-kpxz0hbg.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-q74xmdkf.js";import"./chunk-74yge4ka.js";import"./chunk-xzzrtwjx.js";import{sh as F}from"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Ih as z}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-5j0b62sr.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -1 +1 @@
1
- import{Ai as f,vi as a,wi as b,xi as c,yi as d,zi as e}from"./chunk-vt99w0vh.js";import"./chunk-nh45xp7r.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{Ai as f,vi as a,wi as b,xi as c,yi as d,zi as e}from"./chunk-5j0b62sr.js";import"./chunk-nh45xp7r.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +1 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-s2erwc49.js";import"./chunk-7k5v52ct.js";import"./chunk-9318pj5k.js";import"./chunk-cnnht4m3.js";import"./chunk-rrav5aea.js";import"./chunk-qp165b79.js";import"./chunk-871g570t.js";import"./chunk-z5rtzcm4.js";import"./chunk-2f0wn3ne.js";import"./chunk-8eh0vp98.js";import"./chunk-rjw8pj7t.js";import"./chunk-ya5p7mx7.js";import"./chunk-cbafxem4.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{qe as n}from"./chunk-09ya3a21.js";import"./chunk-ztp2ff01.js";import{Me as s}from"./chunk-eqbcxa12.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-vxwqsmqg.js";import"./chunk-ktt7vmqz.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-h2a3edj4.js";import"./chunk-74yge4ka.js";import"./chunk-4p69xraf.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-vt99w0vh.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
1
+ import{a,b as i,c as l,d as m}from"./chunk-qrj0d6a5.js";import"./chunk-7k5v52ct.js";import"./chunk-9318pj5k.js";import"./chunk-bss2kc28.js";import"./chunk-c9zd429t.js";import"./chunk-ax8tta9d.js";import"./chunk-1t097t5f.js";import"./chunk-z5rtzcm4.js";import"./chunk-wj403wry.js";import"./chunk-8eh0vp98.js";import"./chunk-b12wtvac.js";import"./chunk-ya5p7mx7.js";import"./chunk-tw63vfgh.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{qe as n}from"./chunk-4n4a3vm2.js";import"./chunk-ztp2ff01.js";import{Me as s}from"./chunk-ggf76jxn.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-gnffwz1c.js";import"./chunk-kpxz0hbg.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-q74xmdkf.js";import"./chunk-74yge4ka.js";import"./chunk-xzzrtwjx.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-5j0b62sr.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1,4 +1,4 @@
1
- import{oe as s}from"./chunk-wbfa6xce.js";import{He as o}from"./chunk-eqbcxa12.js";import{Rg as y,Sg as D,Ug as N,Wg as j,Xg as F,Zg as R,bh as E,ch as _,dh as f,eh as C,gh as S,hh as m,lh as c,qh as l,rh as n}from"./chunk-4p69xraf.js";import{sh as Y}from"./chunk-t48zm299.js";import{uh as x,wh as k,zh as Z}from"./chunk-7dqh8bqm.js";import{Gh as X}from"./chunk-qa4efys0.js";import{$h as O,Kh as h,Lh as A,Rh as P,Sh as T,Uh as $,Vh as U,Wh as G,Yh as L,Zh as M,ai as I}from"./chunk-hrfh7wck.js";import{ii as d}from"./chunk-h4j0nve8.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{oe as s}from"./chunk-wbfa6xce.js";import{He as o}from"./chunk-ggf76jxn.js";import{Rg as y,Sg as D,Ug as N,Wg as j,Xg as F,Zg as R,bh as E,ch as _,dh as f,eh as C,gh as S,hh as m,lh as c,qh as l,rh as n}from"./chunk-xzzrtwjx.js";import{sh as Y}from"./chunk-t48zm299.js";import{uh as x,wh as k,zh as Z}from"./chunk-7dqh8bqm.js";import{Gh as X}from"./chunk-qa4efys0.js";import{$h as O,Kh as h,Lh as A,Rh as P,Sh as T,Uh as $,Vh as U,Wh as G,Yh as L,Zh as M,ai as I}from"./chunk-hrfh7wck.js";import{ii as d}from"./chunk-h4j0nve8.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -1,2 +1,2 @@
1
- import{N as I}from"./chunk-871g570t.js";import{Nd as M}from"./chunk-cbafxem4.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
1
+ import{N as I}from"./chunk-1t097t5f.js";import{Nd as M}from"./chunk-tw63vfgh.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
2
2
  export{C as v,$ as w,V as x,x as y,i as z,K as A};
@@ -1,4 +1,4 @@
1
- import{_b as E4}from"./chunk-ya5p7mx7.js";import{Cd as I0,Ed as V6,Fd as R1,Gd as K6,Nd as n$,Rc as kJ,Tc as CJ,Uc as vJ,Vc as d2,Wc as m2,ac as X$,ad as IJ,bd as S4,cd as T4,dd as v2,ed as x1,fd as M4,gd as R4,hd as E1,kd as UJ,sd as V1}from"./chunk-cbafxem4.js";import{Sd as F0,Vd as _J,Wd as k0}from"./chunk-4jbpvete.js";import{Xe as tJ}from"./chunk-zj4kfyer.js";import{$e as HJ,Ye as _4,Ze as i0,_e as O4,cf as b1,df as Y6,ef as zJ,ff as BJ,hf as jJ}from"./chunk-0eqk29xr.js";import{Sf as J$,Tf as r0,Wf as b4,_f as X4}from"./chunk-yjh47zv6.js";import{jg as A$}from"./chunk-h2a3edj4.js";import{th as rJ}from"./chunk-t48zm299.js";import{Ih as H0}from"./chunk-qa4efys0.js";import{ii as h0}from"./chunk-h4j0nve8.js";import{wi as xJ}from"./chunk-vt99w0vh.js";import{Hi as _$,Ji as i6,Ki as y0,Li as M1,Ni as MJ,Oi as RJ,Pi as hJ}from"./chunk-na1cney5.js";import{Qi as G8}from"./chunk-nh45xp7r.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class f1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),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)=>!f$(W)&&!O$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}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(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);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)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function _6($){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 b6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function E6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var d4=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"]),m4=/^(LD_.+|DYLD_.+|PATH)$/,S6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function c$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(!d4.has(K))break;J=Y}return J}function vZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(m4.test(K))break;J=Y}return J}var c4=[/^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 U2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of c4){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 l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var l4=new Set(["npm","pnpm","yarn","bun"]),M6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),i4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),r4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function n4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function R6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function o4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function a4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function s4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function t4($){let J=R6($.replace(r4,"").trim()),Z=a4(J);if(!Z)return;if(Z.length===0)return h6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=R6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!s4(V))return;return h6(Y)}function h6($){let Z=l$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=t4($);if(!Z)return!1;let W=c$(Z),Y=l$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:o4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...i4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(l4.has(Q??""))return n4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&M6.has(X??""))return!0;if(M6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function dZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var D2=h0("Agent"),e4=3;function w2($,J,Z){if($!=="length")return{action:"none"};if(J>=e4)return{action:"truncated"};if(_6(Z)==="stop")return D2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var $5=[/:\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],J5=/```[\s\S]{50,}```/,x6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Z5=2;function q2($,J,Z=!0){if(!$||J>=Z5)return{action:"none"};if(!Z&&J5.test($))return{action:"retry",prompt:x6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if($5.some((K)=>K.test(W)))return{action:"retry",prompt:x6};return{action:"none"}}var W5=[/\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}(?:测试|单测|集成测试|检查|构建)/],k6={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},Y5={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},V5="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.",K5="Required verification did not run successfully before the retry limit.",Q5=3;function v6($,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&&y$(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 V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function G2($,J,Z){if(!$||!W5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(k6).filter((X)=>k6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Y5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=Q5)return{action:"fail",message:K5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${V5}${Q}`}}var X5=[/\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|子代理|子智能体)/],I6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function u6($){return typeof $==="string"&&I6.some((J)=>J.test($))}var H5=[/\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|子代理)/],z5=[/\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 B5($){if(typeof $!=="string")return;if(z5.some((J)=>J.test($)))return"multiple-allowed";return H5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=B5(J);if(Z!==void 0)return Z==="required"}return!1}var j5="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.",U5="Required delegation did not complete before the retry limit.",D5=3;function g6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(I6.some((Q)=>Q.test(K)))break;if(X5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=D5)return{action:"fail",message:U5};return{action:"retry",prompt:j5}}var w5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],G5=[/\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 p6($){return G5.reduce((J,Z)=>J.replace(Z," "),$)}function A1($){if(typeof $!=="string")return!1;let J=p6($);return w5.some((Z)=>Z.test(J))}var F5="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.",L5="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.",O5="Required worktree lifecycle did not complete before the retry limit.",f5=3;function d6($,J,Z){if(!$)return{action:"none"};let W=p6($);if(!A1(W))return{action:"none"};let Y=q5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=f5)return{action:"fail",message:O5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?F5:L5}}var C6=30000;async function F2($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),C6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return D2.warn(`[Loop] Stop hook 超时 (${C6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return D2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function y5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var A5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function P5($){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 N5($){let J=$;for(let X of A5)J=J.replace(X," ");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 V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function m6($){return N5(P5($))}import{EventEmitter as _5}from"events";import c6 from"node:path";function L2($){if(i6($.sessionId),!c6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:c6.resolve($.projectPath)}}function l6($){let J=L2($);return JSON.stringify([J.projectPath,J.sessionId])}function $3($,J){return l6($)===l6(J)}class P$ extends _5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=L2($);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 r$=P$.getInstance();var t0=h0("Agent"),P1=new Set;async function b5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=m6(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var O2=`<turn_aborted>
1
+ import{_b as E4}from"./chunk-ya5p7mx7.js";import{Cd as I0,Ed as V6,Fd as R1,Gd as K6,Nd as n$,Rc as kJ,Tc as CJ,Uc as vJ,Vc as d2,Wc as m2,ac as X$,ad as IJ,bd as S4,cd as T4,dd as v2,ed as x1,fd as M4,gd as R4,hd as E1,kd as UJ,sd as V1}from"./chunk-tw63vfgh.js";import{Sd as F0,Vd as _J,Wd as k0}from"./chunk-4jbpvete.js";import{Xe as tJ}from"./chunk-zj4kfyer.js";import{$e as HJ,Ye as _4,Ze as i0,_e as O4,cf as b1,df as Y6,ef as zJ,ff as BJ,hf as jJ}from"./chunk-0eqk29xr.js";import{Sf as J$,Tf as r0,Wf as b4,_f as X4}from"./chunk-yjh47zv6.js";import{jg as A$}from"./chunk-q74xmdkf.js";import{th as rJ}from"./chunk-t48zm299.js";import{Ih as H0}from"./chunk-qa4efys0.js";import{ii as h0}from"./chunk-h4j0nve8.js";import{wi as xJ}from"./chunk-5j0b62sr.js";import{Hi as _$,Ji as i6,Ki as y0,Li as M1,Ni as MJ,Oi as RJ,Pi as hJ}from"./chunk-na1cney5.js";import{Qi as G8}from"./chunk-nh45xp7r.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class f1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),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)=>!f$(W)&&!O$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}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(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);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)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function _6($){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 b6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function E6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var d4=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"]),m4=/^(LD_.+|DYLD_.+|PATH)$/,S6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function c$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(!d4.has(K))break;J=Y}return J}function vZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(m4.test(K))break;J=Y}return J}var c4=[/^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 U2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of c4){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 l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var l4=new Set(["npm","pnpm","yarn","bun"]),M6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),i4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),r4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function n4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function R6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function o4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function a4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function s4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function t4($){let J=R6($.replace(r4,"").trim()),Z=a4(J);if(!Z)return;if(Z.length===0)return h6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=R6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!s4(V))return;return h6(Y)}function h6($){let Z=l$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=t4($);if(!Z)return!1;let W=c$(Z),Y=l$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:o4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...i4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(l4.has(Q??""))return n4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&M6.has(X??""))return!0;if(M6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function dZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var D2=h0("Agent"),e4=3;function w2($,J,Z){if($!=="length")return{action:"none"};if(J>=e4)return{action:"truncated"};if(_6(Z)==="stop")return D2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var $5=[/:\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],J5=/```[\s\S]{50,}```/,x6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Z5=2;function q2($,J,Z=!0){if(!$||J>=Z5)return{action:"none"};if(!Z&&J5.test($))return{action:"retry",prompt:x6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if($5.some((K)=>K.test(W)))return{action:"retry",prompt:x6};return{action:"none"}}var W5=[/\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}(?:测试|单测|集成测试|检查|构建)/],k6={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},Y5={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},V5="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.",K5="Required verification did not run successfully before the retry limit.",Q5=3;function v6($,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&&y$(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 V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function G2($,J,Z){if(!$||!W5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(k6).filter((X)=>k6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Y5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=Q5)return{action:"fail",message:K5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${V5}${Q}`}}var X5=[/\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|子代理|子智能体)/],I6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function u6($){return typeof $==="string"&&I6.some((J)=>J.test($))}var H5=[/\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|子代理)/],z5=[/\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 B5($){if(typeof $!=="string")return;if(z5.some((J)=>J.test($)))return"multiple-allowed";return H5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=B5(J);if(Z!==void 0)return Z==="required"}return!1}var j5="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.",U5="Required delegation did not complete before the retry limit.",D5=3;function g6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(I6.some((Q)=>Q.test(K)))break;if(X5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=D5)return{action:"fail",message:U5};return{action:"retry",prompt:j5}}var w5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],G5=[/\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 p6($){return G5.reduce((J,Z)=>J.replace(Z," "),$)}function A1($){if(typeof $!=="string")return!1;let J=p6($);return w5.some((Z)=>Z.test(J))}var F5="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.",L5="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.",O5="Required worktree lifecycle did not complete before the retry limit.",f5=3;function d6($,J,Z){if(!$)return{action:"none"};let W=p6($);if(!A1(W))return{action:"none"};let Y=q5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=f5)return{action:"fail",message:O5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?F5:L5}}var C6=30000;async function F2($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),C6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return D2.warn(`[Loop] Stop hook 超时 (${C6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return D2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function y5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var A5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function P5($){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 N5($){let J=$;for(let X of A5)J=J.replace(X," ");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 V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function m6($){return N5(P5($))}import{EventEmitter as _5}from"events";import c6 from"node:path";function L2($){if(i6($.sessionId),!c6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:c6.resolve($.projectPath)}}function l6($){let J=L2($);return JSON.stringify([J.projectPath,J.sessionId])}function $3($,J){return l6($)===l6(J)}class P$ extends _5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=L2($);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 r$=P$.getInstance();var t0=h0("Agent"),P1=new Set;async function b5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=m6(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var O2=`<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>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",r6="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 N$ 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 z$($){return $.executionEngine?.getContextManager()}async function l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)b5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new N$("user_message",{cause:Q})}return null}async function x0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let B=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!B)throw Error("Durable assistant-message commit returned no identity");return B}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new N$("assistant_message",{cause:X})}return null}async function n6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",O2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function o6($,J,Z,W,Y){try{let V=z$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.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(V){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function f2($,J,Z,W,Y,V={}){try{let K=z$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function N1($,J,Z,W,Y,V,K,Q,X,H={}){try{let B=z$($);if(B&&J.sessionId){let j=await B.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(B){if(t0.warn("[Loop] 保存工具结果失败:",B),H.required)throw B}return null}async function o$($,J,Z,W,Y={}){try{let V=z$($);if(V&&J.sessionId){let K=await V.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(V){if(t0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function U0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,B=await x0(J,Z,Y,H,V);if(B)H=B;if(Q!==void 0){let j={role:"user",content:Q};if(X)j.metadata=X;W.appendControl("user",j);let z=await l0(J,Z,j.content,H,X);if(z)H=z}return H}import{createHash as Q6}from"node:crypto";import{promises as m5}from"node:fs";import c5 from"node:path";import{nanoid as e0}from"nanoid";import*as J0 from"node:fs/promises";import*as B$ from"node:path";var a6={enabled:!0,maxIndexLines:200};var E5="memory",s6="MEMORY.md";class y2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=_$($);this.memoryDir=B$.join(W,E5)}this.config={...a6,...J}}async initialize(){if(this.initialized)return;await J0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=B$.join(this.memoryDir,s6);try{let J=await J0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
4
4
  `),Y=Z.slice(0,this.config.maxIndexLines).join(`
@@ -8,7 +8,7 @@ The previous turn was interrupted. Commands or tool calls may have partially com
8
8
  `)?`
9
9
  `:"";await J0.writeFile(W,Y+V+J,"utf-8")}else await J0.writeFile(W,J,"utf-8")}async updateIndex($,J="overwrite"){await this.initialize();let Z=B$.join(this.memoryDir,s6);if(J==="append"){let W="";try{W=await J0.readFile(Z,"utf-8")}catch{}let Y=W&&!W.endsWith(`
10
10
  `)?`
11
- `:"";await J0.writeFile(Z,W+Y+$,"utf-8")}else await J0.writeFile(Z,$,"utf-8")}async listTopics(){await this.initialize();try{let $=await J0.readdir(this.memoryDir,{withFileTypes:!0}),J=[];for(let Z of $){if(!Z.isFile()||!Z.name.endsWith(".md"))continue;let W=B$.join(this.memoryDir,Z.name),Y=await J0.stat(W);J.push({name:Z.name.replace(/\.md$/,""),size:Y.size,lastModified:Y.mtime})}return J.sort((Z,W)=>W.lastModified.getTime()-Z.lastModified.getTime())}catch{return[]}}async deleteTopic($){let J=this.resolveTopicPath($);try{return await J0.unlink(J),!0}catch{return!1}}async clearAll(){let $=await this.listTopics(),J=0;for(let Z of $){let W=B$.join(this.memoryDir,`${Z.name}.md`);try{await J0.unlink(W),J++}catch{}}return J}getMemoryDir(){return this.memoryDir}resolveTopicPath($){let J=$.replace(/[/\\:*?"<>|]/g,"-"),Z=J.endsWith(".md")?J:`${J}.md`,W=B$.join(this.memoryDir,Z);if(!W.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${$}`);return W}}var S5=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],T5=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,M5=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function R5($){let J=new Map;for(let Z of $){if(!Z.content||typeof Z.content!=="string")continue;let W=Z.content;if(Z.role==="user")for(let{pattern:Y,topic:V}of S5){let K=W.match(Y);if(K?.[1]){let Q=J.get(V)??[];Q.push(K[1].trim()),J.set(V,Q)}}if(Z.role==="assistant"){let Y=W.match(T5);if(Y?.[1]&&Y[1].length>20&&Y[1].length<200){let V=J.get("debugging")??[];V.push(Y[1].trim()),J.set("debugging",V)}}if(Z.role==="tool"&&Z.content?.includes("Error")){let Y=W.match(M5);if(Y?.[1]&&Y[1].length>10){let V=J.get("debugging")??[];if(V.length<5)V.push(`Tool error pattern: ${Y[1].trim().slice(0,150)}`),J.set("debugging",V)}}}return J}async function t6($){let J=R5($);if(J.size===0)return{extracted:0,topics:[]};try{let Z=new y2(H0());await Z.initialize();let W=[],Y=0;for(let[V,K]of J){if(K.length===0)continue;let Q=new Date().toISOString().split("T")[0],X=K.map((H)=>`- [${Q}] ${H}`).join(`
11
+ `:"";await J0.writeFile(Z,W+Y+$,"utf-8")}else await J0.writeFile(Z,$,"utf-8")}async listTopics(){await this.initialize();try{let $=await J0.readdir(this.memoryDir,{withFileTypes:!0}),J=[];for(let Z of $){if(!Z.isFile()||!Z.name.endsWith(".md"))continue;let W=B$.join(this.memoryDir,Z.name),Y=await J0.stat(W);J.push({name:Z.name.replace(/\.md$/,""),size:Y.size,lastModified:Y.mtime})}return J.sort((Z,W)=>W.lastModified.getTime()-Z.lastModified.getTime())}catch($){if($.code==="ENOENT")return[];throw $}}async deleteTopic($){let J=this.resolveTopicPath($);try{return await J0.unlink(J),!0}catch{return!1}}async clearAll(){let $=await this.listTopics(),J=0;for(let Z of $){let W=B$.join(this.memoryDir,`${Z.name}.md`);try{await J0.unlink(W),J++}catch{}}return J}getMemoryDir(){return this.memoryDir}resolveTopicPath($){let J=$.replace(/[/\\:*?"<>|]/g,"-"),Z=J.endsWith(".md")?J:`${J}.md`,W=B$.join(this.memoryDir,Z);if(!W.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${$}`);return W}}var S5=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],T5=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,M5=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function R5($){let J=new Map;for(let Z of $){if(!Z.content||typeof Z.content!=="string")continue;let W=Z.content;if(Z.role==="user")for(let{pattern:Y,topic:V}of S5){let K=W.match(Y);if(K?.[1]){let Q=J.get(V)??[];Q.push(K[1].trim()),J.set(V,Q)}}if(Z.role==="assistant"){let Y=W.match(T5);if(Y?.[1]&&Y[1].length>20&&Y[1].length<200){let V=J.get("debugging")??[];V.push(Y[1].trim()),J.set("debugging",V)}}if(Z.role==="tool"&&Z.content?.includes("Error")){let Y=W.match(M5);if(Y?.[1]&&Y[1].length>10){let V=J.get("debugging")??[];if(V.length<5)V.push(`Tool error pattern: ${Y[1].trim().slice(0,150)}`),J.set("debugging",V)}}}return J}async function t6($){let J=R5($);if(J.size===0)return{extracted:0,topics:[]};try{let Z=new y2(H0());await Z.initialize();let W=[],Y=0;for(let[V,K]of J){if(K.length===0)continue;let Q=new Date().toISOString().split("T")[0],X=K.map((H)=>`- [${Q}] ${H}`).join(`
12
12
  `);await Z.writeTopic(V,X+`
13
13
  `,"append"),W.push(V),Y+=K.length}return{extracted:Y,topics:W}}catch{return{extracted:0,topics:[]}}}import{encodingForModel as e6}from"js-tiktoken";class i{static encodingCache=new Map;static countTokens($,J){let Z=this.getEncoding(J),W=0;for(let Y of $){if(W+=4,Y.role)W+=Z.encode(Y.role).length;if(Y.content)if(typeof Y.content==="string")W+=Z.encode(Y.content).length;else W+=Z.encode(JSON.stringify(Y.content)).length;if(Y.reasoningContent)W+=Z.encode(Y.reasoningContent).length;if(Y.tool_calls&&Array.isArray(Y.tool_calls))W+=this.countToolCallTokens(Y.tool_calls,Z);if(Y.name)W+=Z.encode(Y.name).length}return W}static countTextTokens($,J){return this.getEncoding(J).encode($).length}static getTokenLimit($){return $}static shouldCompact($,J,Z,W=0.8){let Y=this.countTokens($,J),V=Math.floor(Z*W);return Y>=V}static getEncoding($){if(!this.encodingCache.has($))try{let J=e6($);this.encodingCache.set($,J)}catch{try{let J=e6("gpt-4");this.encodingCache.set($,J)}catch{console.warn(`[TokenCounter] 无法为模型 ${$} 获取 encoding,使用粗略估算`),this.encodingCache.set($,{encode:(J)=>{return Array(Math.ceil(J.length/4))}})}}return this.encodingCache.get($)}static countToolCallTokens($,J){let Z=0;for(let W of $){if(Z+=4,W.type==="function"&&W.function?.name)Z+=J.encode(W.function.name).length;if(W.type==="function"&&W.function?.arguments)Z+=J.encode(W.function.arguments).length;if(W.id)Z+=J.encode(W.id).length}return Z}static clearCache(){this.encodingCache.clear()}static estimateTokens($){let J=($.match(/[\u4e00-\u9fa5]/g)||[]).length,Z=$.length-J;return Math.ceil(J/1.5+Z/4)}}var ZJ=5000,WJ=0.8,YJ=0.5,VJ=50000,h5="[image omitted from compaction]",A2=`
14
14
  ...[message truncated to fit fallback token budget]...
@@ -1,4 +1,4 @@
1
- import{e as DJ,f as VJ}from"./chunk-7k5v52ct.js";import{i as RY,j as MY,k as TY}from"./chunk-hajer580.js";import{u as s2}from"./chunk-rrav5aea.js";import{$ as z2,B as c6,F as gY,H as OQ,I as XQ,J as v6,O as A6,P as P6,T as j1,V as e4,W as $6,Z as y6,aa as nJ,ba as tJ,ea as sJ,fa as eJ,ja as L4,ka as $9,ma as t6,na as s6,oa as mY,pa as O6,ra as z6,ta as x6}from"./chunk-871g570t.js";import"./chunk-z5rtzcm4.js";import{Ba as qJ,Ca as OJ,Da as zJ,Ga as EY}from"./chunk-2f0wn3ne.js";import{Ia as b6}from"./chunk-8eh0vp98.js";import{Cb as w6,Lb as QQ,pb as L6,qb as B6}from"./chunk-rjw8pj7t.js";import{Wb as W2}from"./chunk-ya5p7mx7.js";import{Ad as Z6,Cd as d2,Kd as O2,Nd as C0,_c as _6,md as t4,rd as s4,yd as Y6,zd as $Q}from"./chunk-cbafxem4.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{oe as PY}from"./chunk-wbfa6xce.js";import{pe as H2,qe as e2,se as C1}from"./chunk-09ya3a21.js";import"./chunk-ztp2ff01.js";import{Ae as g$,Be as r2,Ce as v9,De as Q4,Ee as MJ,Fe as D9,Ge as V$,He as l0,Ie as jY,Je as o0,Ke as AY,Le as D8,Me as N2,Pe as U6,We as p0,we as k$,xe as a0,ye as Q$,ze as jQ}from"./chunk-eqbcxa12.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import{kf as J4}from"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-vxwqsmqg.js";import{Ef as iJ,Nf as hY,wf as Q8,zf as _Y}from"./chunk-ktt7vmqz.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import{hg as gQ,jg as q1}from"./chunk-h2a3edj4.js";import"./chunk-74yge4ka.js";import{lh as DY,qh as oJ,rh as VY}from"./chunk-4p69xraf.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import{Ah as m$,Bh as a2,Dh as mQ}from"./chunk-d83bfr0b.js";import{Ih as d0}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import{fi as vY,ii as t1}from"./chunk-h4j0nve8.js";import{ki as kJ,li as SJ,oi as h1}from"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import{Ai as bJ}from"./chunk-vt99w0vh.js";import{Di as F4}from"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import{Oi as e8}from"./chunk-na1cney5.js";import{Qi as EQ}from"./chunk-nh45xp7r.js";import{useMemoizedFn as u8}from"ahooks";import{useEffect as S7,useState as l8}from"react";import{useMemoizedFn as s0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as R7,useRef as p8}from"react";import{useShallow as uY}from"zustand/react/shallow";import{useStore as xY}from"zustand";function t($){return xY(V$,$)}var lY=[],j$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),B4=()=>t(($)=>$.session.messages),w4=()=>t(($)=>$.session.clearCount),b4=()=>t(($)=>$.session.isCompacting),A4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),P4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return L4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),y4=()=>t(($)=>$.session.providerCircuit),R4=()=>t(($)=>$.session.providerAdmission),M4=()=>t(($)=>$.session.providerRetry),T4=()=>t(($)=>$.session.providerStall),C4=()=>t(($)=>$.session.actionStationarity),i1=()=>t(($)=>$.session.actions),I4=()=>t(($)=>{let{totalTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),f4=()=>t(($)=>$.app.initializationStatus),k4=()=>t(($)=>$.app.initializationError),D2=()=>t(($)=>$.app.activeModal),S4=()=>t(($)=>$.app.tasks),v4=()=>t(($)=>$.app.modelEditorTarget),D4=()=>t(($)=>$.app.sessionSelectorData),V4=()=>t(($)=>$.app.awaitingSecondCtrlC),n1=()=>t(($)=>$.app.actions),V2=()=>t(($)=>$.app.sideConversation),j4=()=>t(($)=>$.app.teams),j2=()=>t(($)=>$.app.initializationStatus==="ready"),h4=()=>t(($)=>$.app.tasks.length>0),h$=()=>t(($)=>$.config.config?.permissionMode||"default"),E4=()=>t(($)=>$.config.config?.models??lY),h2=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),E2=()=>t(($)=>$.config.config?.currentModelId),g4=()=>t(($)=>$.config.config?.agentTeamsEnabled===!0),b0=()=>t(($)=>{return a0.getTheme()}),m4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),p4=()=>t(($)=>$.focus.actions),E$=()=>t(($)=>$.command.isProcessing),c4=()=>t(($)=>$.command.actions),g2=()=>t(($)=>$.command.pendingCommands),x4=()=>t(($)=>$.command.recoveredSteeringCount),m2=()=>t(($)=>$.app.reasoningEffort!=="off"),p2=()=>t(($)=>$.app.reasoningEffort),c2=()=>t(($)=>$.app.serviceTier),x2=()=>t(($)=>$.app.responseVerbosity),u2=()=>t(($)=>$.app.communicationStyle),u4=()=>t(($)=>$.session.currentThinkingContent),l4=()=>t(($)=>$.session.thinkingExpanded),d4=()=>t(($)=>$.session.currentStreamingMessageId),r4=()=>t(uY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),a4=()=>t(($)=>$.session.finalizingStreamingMessageId),o4=()=>t(($)=>$.session.historyExpanded),i4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as s1}from"ahooks";import{useEffect as c$,useRef as s8}from"react";function dY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let U=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function rY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function aY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function l2($){let Q=rY($),Y=aY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=dY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as oY,mkdirSync as iY,writeFileSync as nY}from"node:fs";import tY from"node:os";import a8 from"node:path";var n4=null;function sY(){let $=process.env.BLADE_STORAGE_ROOT||a8.join(tY.homedir(),".blade");return a8.join($,"logs","stream-debug.log")}function eY($){if(n4===$)return;let Q=a8.dirname($);iY(Q,{recursive:!0,mode:493}),nY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{e as DJ,f as VJ}from"./chunk-7k5v52ct.js";import{i as RY,j as MY,k as TY}from"./chunk-5vg1dwh1.js";import{u as s2}from"./chunk-c9zd429t.js";import{$ as z2,B as c6,F as gY,H as OQ,I as XQ,J as v6,O as A6,P as P6,T as j1,V as e4,W as $6,Z as y6,aa as nJ,ba as tJ,ea as sJ,fa as eJ,ja as L4,ka as $9,ma as t6,na as s6,oa as mY,pa as O6,ra as z6,ta as x6}from"./chunk-1t097t5f.js";import"./chunk-z5rtzcm4.js";import{Ba as qJ,Ca as OJ,Da as zJ,Ga as EY}from"./chunk-wj403wry.js";import{Ia as b6}from"./chunk-8eh0vp98.js";import{Cb as w6,Lb as QQ,pb as L6,qb as B6}from"./chunk-b12wtvac.js";import{Wb as W2}from"./chunk-ya5p7mx7.js";import{Ad as Z6,Cd as d2,Kd as O2,Nd as C0,_c as _6,md as t4,rd as s4,yd as Y6,zd as $Q}from"./chunk-tw63vfgh.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{oe as PY}from"./chunk-wbfa6xce.js";import{pe as H2,qe as e2,se as C1}from"./chunk-4n4a3vm2.js";import"./chunk-ztp2ff01.js";import{Ae as g$,Be as r2,Ce as v9,De as Q4,Ee as MJ,Fe as D9,Ge as V$,He as l0,Ie as jY,Je as o0,Ke as AY,Le as D8,Me as N2,Pe as U6,We as p0,we as k$,xe as a0,ye as Q$,ze as jQ}from"./chunk-ggf76jxn.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import{kf as J4}from"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-gnffwz1c.js";import{Ef as iJ,Nf as hY,wf as Q8,zf as _Y}from"./chunk-kpxz0hbg.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import{hg as gQ,jg as q1}from"./chunk-q74xmdkf.js";import"./chunk-74yge4ka.js";import{lh as DY,qh as oJ,rh as VY}from"./chunk-xzzrtwjx.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import{Ah as m$,Bh as a2,Dh as mQ}from"./chunk-d83bfr0b.js";import{Ih as d0}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import{fi as vY,ii as t1}from"./chunk-h4j0nve8.js";import{ki as kJ,li as SJ,oi as h1}from"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import{Ai as bJ}from"./chunk-5j0b62sr.js";import{Di as F4}from"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import{Oi as e8}from"./chunk-na1cney5.js";import{Qi as EQ}from"./chunk-nh45xp7r.js";import{useMemoizedFn as u8}from"ahooks";import{useEffect as S7,useState as l8}from"react";import{useMemoizedFn as s0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as R7,useRef as p8}from"react";import{useShallow as uY}from"zustand/react/shallow";import{useStore as xY}from"zustand";function t($){return xY(V$,$)}var lY=[],j$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),B4=()=>t(($)=>$.session.messages),w4=()=>t(($)=>$.session.clearCount),b4=()=>t(($)=>$.session.isCompacting),A4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),P4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return L4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),y4=()=>t(($)=>$.session.providerCircuit),R4=()=>t(($)=>$.session.providerAdmission),M4=()=>t(($)=>$.session.providerRetry),T4=()=>t(($)=>$.session.providerStall),C4=()=>t(($)=>$.session.actionStationarity),i1=()=>t(($)=>$.session.actions),I4=()=>t(($)=>{let{totalTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),f4=()=>t(($)=>$.app.initializationStatus),k4=()=>t(($)=>$.app.initializationError),D2=()=>t(($)=>$.app.activeModal),S4=()=>t(($)=>$.app.tasks),v4=()=>t(($)=>$.app.modelEditorTarget),D4=()=>t(($)=>$.app.sessionSelectorData),V4=()=>t(($)=>$.app.awaitingSecondCtrlC),n1=()=>t(($)=>$.app.actions),V2=()=>t(($)=>$.app.sideConversation),j4=()=>t(($)=>$.app.teams),j2=()=>t(($)=>$.app.initializationStatus==="ready"),h4=()=>t(($)=>$.app.tasks.length>0),h$=()=>t(($)=>$.config.config?.permissionMode||"default"),E4=()=>t(($)=>$.config.config?.models??lY),h2=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),E2=()=>t(($)=>$.config.config?.currentModelId),g4=()=>t(($)=>$.config.config?.agentTeamsEnabled===!0),b0=()=>t(($)=>{return a0.getTheme()}),m4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),p4=()=>t(($)=>$.focus.actions),E$=()=>t(($)=>$.command.isProcessing),c4=()=>t(($)=>$.command.actions),g2=()=>t(($)=>$.command.pendingCommands),x4=()=>t(($)=>$.command.recoveredSteeringCount),m2=()=>t(($)=>$.app.reasoningEffort!=="off"),p2=()=>t(($)=>$.app.reasoningEffort),c2=()=>t(($)=>$.app.serviceTier),x2=()=>t(($)=>$.app.responseVerbosity),u2=()=>t(($)=>$.app.communicationStyle),u4=()=>t(($)=>$.session.currentThinkingContent),l4=()=>t(($)=>$.session.thinkingExpanded),d4=()=>t(($)=>$.session.currentStreamingMessageId),r4=()=>t(uY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),a4=()=>t(($)=>$.session.finalizingStreamingMessageId),o4=()=>t(($)=>$.session.historyExpanded),i4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as s1}from"ahooks";import{useEffect as c$,useRef as s8}from"react";function dY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let U=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function rY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function aY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function l2($){let Q=rY($),Y=aY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=dY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as oY,mkdirSync as iY,writeFileSync as nY}from"node:fs";import tY from"node:os";import a8 from"node:path";var n4=null;function sY(){let $=process.env.BLADE_STORAGE_ROOT||a8.join(tY.homedir(),".blade");return a8.join($,"logs","stream-debug.log")}function eY($){if(n4===$)return;let Q=a8.dirname($);iY(Q,{recursive:!0,mode:493}),nY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),n4=$}function o8($,Q,Y){try{let J=sY();eY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",K=`[${Z}] [${$}] ${Q}${X}
3
3
  `;oY(J,K)}catch{}}var q2=t1("UI");function Q6($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,o8("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),q2.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),o8("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),K=$.getStreamingMessageId();if(K){if(Z)g$(K,Z);r2(K)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_admission":{let{kind:Z,...X}=J;$.sessionActions.setProviderAdmission(J.phase==="queued"?X:null);break}case"provider_circuit":{let{kind:Z,...X}=J;$.sessionActions.setProviderCircuit(J.phase==="closed"?null:X);break}case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="recovered"?null:X);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"action_stationarity":{let{kind:Z,...X}=J;$.sessionActions.setActionStationarity(J.phase==="recovered"?null:X);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;if(q2.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),K=e4(Z.function.name,X);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:X})}catch(X){q2.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",K=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...J.update.admission?{admission:J.update.admission}:{}});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;q2.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=s4($6(Z.function.name,J.result),t4);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":q2.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
4
4
  `)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`