blade-code 0.10.100 → 0.10.101
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-gkdynynx.js → chunk-2191220r.js} +1 -1
- package/dist/{chunk-rmhgyrgh.js → chunk-2cg8f38t.js} +1 -1
- package/dist/{chunk-hx55j0d0.js → chunk-2f5kkhan.js} +274 -274
- package/dist/chunk-2r0f3b4t.js +1 -0
- package/dist/{chunk-q1cc7kwn.js → chunk-3an3vxzt.js} +1 -1
- package/dist/{chunk-8zm5r6g8.js → chunk-3c01jje5.js} +1 -1
- package/dist/{chunk-ttg3xrsc.js → chunk-8yt4nmyb.js} +1 -1
- package/dist/{chunk-tagtjbw9.js → chunk-8z9d0zd0.js} +1 -1
- package/dist/chunk-9ajkzcqj.js +12 -0
- package/dist/chunk-as2ezx8p.js +1 -0
- package/dist/{chunk-axycs651.js → chunk-bswjne5v.js} +1 -1
- package/dist/{chunk-dfxfcsm1.js → chunk-c663rajb.js} +1 -1
- package/dist/chunk-cjgpas7y.js +23 -0
- package/dist/{chunk-c3yd59qh.js → chunk-dcjh1cj6.js} +1 -1
- package/dist/{chunk-ara0zd89.js → chunk-f8z5v101.js} +1 -1
- package/dist/{chunk-6p9p71qm.js → chunk-fqbc1ppx.js} +1 -1
- package/dist/{chunk-h8qjkxee.js → chunk-hpjnk87v.js} +18 -18
- package/dist/{chunk-qc4fe1j6.js → chunk-j22d84s7.js} +1 -1
- package/dist/{chunk-jac8cc04.js → chunk-jvxskq6a.js} +1 -1
- package/dist/{chunk-sgzqcr55.js → chunk-kdatgrjy.js} +1 -1
- package/dist/{chunk-njctfzqw.js → chunk-kfcs62nw.js} +1 -1
- package/dist/{chunk-3ktsyk2g.js → chunk-mzab7qak.js} +1 -1
- package/dist/{chunk-s15phq98.js → chunk-n5jfmzp2.js} +1 -1
- package/dist/{chunk-cc74b8qp.js → chunk-nh4jy5cs.js} +1 -1
- package/dist/{chunk-x677fstt.js → chunk-qgjgjzbx.js} +1 -1
- package/dist/{chunk-5dkzqgxa.js → chunk-qjeadpj2.js} +1 -1
- package/dist/chunk-qjv5kz7q.js +171 -0
- package/dist/chunk-sa7t9kht.js +6 -0
- package/dist/{chunk-pzp42zf0.js → chunk-tazb5tze.js} +1 -1
- package/dist/chunk-tc9rq0st.js +160 -0
- package/dist/{chunk-1nwc2wt6.js → chunk-tp5bep1y.js} +1 -1
- package/dist/{chunk-6jhndjnq.js → chunk-twhf09qs.js} +1 -1
- package/dist/{chunk-6rd8x9j0.js → chunk-vc7gh3wc.js} +1 -1
- package/dist/{chunk-y7bsjbsa.js → chunk-wbf4qcws.js} +2 -2
- package/dist/chunk-ykf4cqpg.js +8 -0
- package/dist/{chunk-v9pcf4w4.js → chunk-z0dmm227.js} +1 -1
- package/dist/{chunk-gcnke6s4.js → chunk-z5a8ay9s.js} +1 -1
- package/dist/{chunk-gr6e2vsy.js → chunk-zjpph3ys.js} +1 -1
- package/dist/{chunk-6hr7mv7f.js → chunk-zydvg30x.js} +1 -1
- package/dist/web/assets/{ChatView-Cwc3fRAC.js → ChatView-Cc4bXZ6x.js} +14 -14
- package/dist/web/assets/{CodeBlockHighlighter-IGDocZUy.js → CodeBlockHighlighter-DZcVFtJE.js} +1 -1
- package/dist/web/assets/{FilePreview-EWE-k9VN.js → FilePreview-CzNS6kfM.js} +1 -1
- package/dist/web/assets/{KanbanBoard-FiiVQgTQ.js → KanbanBoard-cdh2g0r0.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DjhWmikM.js → MarkdownRenderer-BqBOUlXa.js} +3 -3
- package/dist/web/assets/{SettingsModal-bHPx0fVG.js → SettingsModal-meSWhCOP.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-CclOfJEl.js → TaskSwitcher-CiQi64Yl.js} +1 -1
- package/dist/web/assets/{TerminalPanel-Bnep8jE2.js → TerminalPanel-Bze9t5mz.js} +1 -1
- package/dist/web/assets/{arrow-left-CiX0E9Mt.js → arrow-left-DpTnLOBT.js} +1 -1
- package/dist/web/assets/{calendar-clock-Bgfr-twh.js → calendar-clock-DlAXXpl_.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-B4T5fHUs.js → chevrons-up-down-CmAktdaR.js} +1 -1
- package/dist/web/assets/{clock-3-CGIhJjon.js → clock-3-_w8nIuEK.js} +1 -1
- package/dist/web/assets/{external-link-DnQv1VYE.js → external-link-AlymrIfc.js} +1 -1
- package/dist/web/assets/{folder-C5f8TpGj.js → folder-CrxO-9Rc.js} +1 -1
- package/dist/web/assets/{index-DNoVz0u1.js → index-JJH0FKfo.js} +5 -5
- package/dist/web/assets/{pause-Cb0ijwnO.js → pause-GQZaG_P3.js} +1 -1
- package/dist/web/assets/{play-Dsw1qmpk.js → play-BPhmPVpi.js} +1 -1
- package/dist/web/assets/{session-events-B4Cq2TwN.js → session-events-CO2pRY9U.js} +8 -8
- package/dist/web/assets/{teamService-C69fFhny.js → teamService-BqS4iOx0.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-2s86w4yb.js +0 -171
- package/dist/chunk-73t5j9dn.js +0 -160
- package/dist/chunk-8wzn2p00.js +0 -6
- package/dist/chunk-hx3c0qn6.js +0 -9
- package/dist/chunk-p4h3p1at.js +0 -23
- package/dist/chunk-t29x8420.js +0 -1
- package/dist/chunk-tsthz2ex.js +0 -8
- package/dist/chunk-vgevdm8b.js +0 -1
package/dist/chunk-8wzn2p00.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{m as SH,n as TH,o as bH,p as IH,q as RH,r as gH}from"./chunk-jac8cc04.js";import{A as VH,v as yH,w as HH,x as JH,y as KH,z as d}from"./chunk-sgzqcr55.js";import{U as _H,W as GH,X as PH,Z as qH,aa as FH}from"./chunk-hx55j0d0.js";import"./chunk-0zhdjaen.js";import"./chunk-rmhgyrgh.js";import"./chunk-hz5rsfxv.js";import{Db as xH,Mb as UH,rb as o}from"./chunk-2s86w4yb.js";import"./chunk-8hprmrd5.js";import{Fd as O,Qd as i,qd as WH,ud as jH}from"./chunk-6hr7mv7f.js";import"./chunk-s0tq8gyx.js";import"./chunk-h8qjkxee.js";import{oe as AH}from"./chunk-qc4fe1j6.js";import{qe as MH,re as fH,se as zH}from"./chunk-8zm5r6g8.js";import{te as EH}from"./chunk-10taec1j.js";import"./chunk-rej5bbbs.js";import{Te as LH}from"./chunk-v9pcf4w4.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-3awjdsef.js";import"./chunk-53xtssbf.js";import"./chunk-2hb222re.js";import"./chunk-gkdynynx.js";import"./chunk-cc74b8qp.js";import{eg as $H}from"./chunk-fvfc95g3.js";import"./chunk-qcy79mva.js";import"./chunk-p0rvgzpx.js";import"./chunk-c3yd59qh.js";import"./chunk-c6tq09mt.js";import"./chunk-gcnke6s4.js";import{xh as QH}from"./chunk-f9asjkfz.js";import{Bh as H,Ch as ZH,Eh as N,zh as DH}from"./chunk-czcxx8tb.js";import{Ih as a,Jh as s}from"./chunk-maebpz1j.js";import{Nh as g}from"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import"./chunk-k7vv9vne.js";import"./chunk-tagtjbw9.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.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
|
-
`)}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
|
-
`)};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
|
-
`);if(J)K.stdout.write(`
|
|
5
|
-
`)},content(J){if(V==="jsonl"){q("content",{content:J});return}L(K.stdout,J)},structuredOutput(J){if(V==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}L(K.stdout,JSON.stringify(J.output))},toolStart(J,Z,W,x){if(V==="jsonl"){q("tool_start",{tool_name:J,summary:Z,target:W,tool_kind:x});return}L(K.stderr,`[tool:start] ${Z}`)},toolProgress(J,Z,W,x,j){if(V==="jsonl"){q("tool_progress",{tool_name:J,message:Z,progress:W,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}L(K.stderr,`[tool:progress] ${J}: ${Z}`)},toolResult(J,Z,W,x,j){if(V==="jsonl"){q("tool_result",{tool_name:J,summary:Z,target:W,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}L(K.stderr,`[tool:result] ${Z}`)},mcpCatalogChanged(J){if(V==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(V==="jsonl"){q("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(V==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}L(K.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(V==="jsonl"){q("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}L(K.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(V==="jsonl"){q("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}L(K.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(V==="jsonl"){q("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}L(K.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(V==="jsonl"){q("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}L(K.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(V==="jsonl"){q("project_rules_loaded",{files:J.files.map((Z)=>({id:Z.id,relative_path:Z.relativePath,source:Z.source,conditional:Z.conditional,content_sha256:Z.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}L(K.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,Z,W){if(V==="jsonl"){q("user_shell_started",{execution_id:J,command:Z,auxiliary:W});return}L(K.stderr,`[user-shell:start] ${Z}`)},userShellOutput(J,Z,W,x){if(V==="jsonl"){q("user_shell_output",{execution_id:J,stream:Z,chunk:W,stream_truncated:x});return}(Z==="stderr"?K.stderr:K.stdout).write(W)},userShellCompleted(J){if(V==="jsonl"){q("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}L(K.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,Z,W,x={}){if(V==="jsonl"){q("phase",{phase:J,status:Z,message:W,turn:x.turn,tool_name:x.toolName,target:x.target});return}L(K.stderr,`[phase:${J}] ${W}`)},toolDetail(J,Z){if(V==="jsonl"){q("tool_detail",{tool_name:J,detail:Z});return}L(K.stderr,Z)},taskUpdate(J){if(V==="jsonl"){q("task_update",{tasks:J});return}for(let Z of J)L(K.stderr,OJ(Z))},goal(J){if(V==="jsonl"){q("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256,verification_summary:J.goal?.completionVerification?.summary,verification_stall_count:J.goal?.verificationStall?.consecutiveCount,premature_stop_pattern:J.goal?.prematureStop?.pattern,premature_stop_count:J.goal?.prematureStop?.consecutiveCount});return}if(J.goal)L(K.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else L(K.stderr,"[goal:cleared]")},subagent(J){let Z=J.kind==="subagent_spawned";if(V==="jsonl"){q("subagent",{state:Z?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:Z?void 0:J.success,summary:Z?void 0:J.summary,verification_verdict:Z?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}L(K.stderr,`[subagent:${Z?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(V==="jsonl"){q("token_usage",{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}L(K.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let Z=J.phase==="start";if(V==="jsonl"){q("compacting",{state:Z?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,pre_token_source:J.preTokenSource,estimated_pending_tokens:J.estimatedPendingTokens,post_tokens:J.postTokens,sample_attempts:J.sampleAttempts,input_reductions:J.inputReductions,messages_omitted:J.messagesOmitted,files_omitted:J.filesOmitted,images_omitted:J.imagesOmitted,fallback_target_tokens:J.fallbackTargetTokens,fallback_messages_omitted:J.fallbackMessagesOmitted,fallback_messages_truncated:J.fallbackMessagesTruncated,failure_reason:J.failureReason});return}L(K.stderr,Z?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}${J.sampleAttempts!==void 0?` after ${J.sampleAttempts} sample attempt${J.sampleAttempts===1?"":"s"}`:""}${J.inputReductions?` with ${J.inputReductions} input reduction${J.inputReductions===1?"":"s"}`:""}${J.imagesOmitted?` and ${J.imagesOmitted} image${J.imagesOmitted===1?"":"s"} omitted`:""}${J.fallbackTargetTokens!==void 0?`; fallback target ${J.fallbackTargetTokens} tokens, ${J.fallbackMessagesOmitted??0} messages omitted, ${J.fallbackMessagesTruncated??0} truncated`:""}`)},providerAdmission(J){if(V==="jsonl"){q("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}L(K.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(V==="jsonl"){q("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let Z=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";L(K.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${Z}`)},providerCircuit(J){if(V==="jsonl"){q("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let Z=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";L(K.stderr,`[provider-circuit:${J.phase}] ${J.reason}${Z}`)},providerStall(J){if(V==="jsonl"){q("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}L(K.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},actionStationarity(J){if(V==="jsonl"){q("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}L(K.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(V==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}L(K.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(V==="jsonl"){q("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}L(K.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(V==="jsonl"){q("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}L(K.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,Z=0){if(V==="jsonl"){q("output",{content:J,exit_code:Z});return}L(Z===0?K.stdout:K.stderr,J)},error(J){if(V==="jsonl"){q("error",{message:J});return}L(K.stderr,J)}}}async function dJ(K,V={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new CH,Z={targetLocked:!1},W,x,j,P=IJ(Q),y=!1,F=new v(V,{signal:P.signal,onFailure:(Y)=>{y=!0,P.abort(Y)}}),w={stdout:{write:(Y)=>F.write("stdout",Y)},stderr:{write:(Y)=>F.write("stderr",Y)}},B=NH(w,q),m=async()=>{try{return await F.flush(),!y}catch{return!1}},S=async(Y)=>{return x?.(),x=void 0,j?.(),j=void 0,await m()?Y:1};try{let Y=kJ(K);q=cJ(Y.outputFormat);let T=await RH(Y);B=NH(w,q,Boolean(T)),await SH();let r=Y.forkSession!==!0&&(Y.continue===!0||typeof Y.resume==="string"&&Y.resume.length>0)?await bH({message:Y.message,_:Y._,stdin:Q?.stdin}):await TH({...Y,stdin:Q?.stdin}),f=r===void 0,_=f?{mode:"agent",content:""}:await IH(r);if(_.mode==="output"){if(_.content)B.output(_.content,_.exitCode??0);return await S(_.exitCode??0)}if(!f&&_.content.length>a)throw Error(`User prompt exceeds the ${a}-character durable input limit`);if(!f&&Buffer.byteLength(_.content,"utf8")>s)throw Error(`User prompt exceeds the ${s}-byte durable input limit`);let C=_.content.trimStart().startsWith("!")?_.content.trimStart().slice(1).trim():void 0;if(C!==void 0&&Y.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(C!==void 0&&T)throw Error("Output schemas cannot be combined with user shell commands");if(Y.taskIsolation&&(Y.continue||Y.resume||Y.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:G,messages:n,metadata:t}=await gH({sessionId:Y.sessionId,continue:Y.continue,resume:Y.resume,forkSession:Y.forkSession,fallbackSessionPrefix:"headless"}),R=Y.permissionMode??t?.permissionMode??"yolo",e=Y.model&&Y.model!=="inherit"?Y.model:LH()?.id,U=Y.taskIsolation?await yH.createSessionTask({sessionId:G,prompt:_.content,sourceProjectPath:g(),isolation:Y.taskIsolation,dispatch:{version:1,prompt:_.content,sourceProjectPath:g(),isolation:Y.taskIsolation,permissionMode:R,...e?{modelId:e}:{},...T?{outputSchema:T}:{}}}):void 0,E=U?.metadata.projectPath??t?.projectPath??g();if(j=o.subscribe((X)=>{if(X.type!=="subagent.provider.admission"||X.sessionId!==G||X.projectPath!==E)return;let $=X.properties,A=["queued","admitted","rejected"],M=["foreground","background","internal"],z=["stream","pending_count","pending_bytes"],I=["global","domain","owner","class"],cH=["capacity","queue_full","wait_timeout","closed"];if(!A.includes($.phase)||!M.includes($.requestClass)||!z.includes($.resource)||!I.includes($.scope)||$.reason!==void 0&&!cH.includes($.reason)||typeof $.queuePosition!=="number"||typeof $.queueDepth!=="number"||typeof $.inFlight!=="number"||typeof $.limit!=="number"||typeof $.waitMs!=="number"||typeof $.maxWaitMs!=="number"||$.recoveryRemainingMs!==void 0&&typeof $.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}})}),!U)await i.setSessionPermissionMode(G,E,R);let kH=U?!1:await UH.cancelPendingNonInteractive(E,G);if(U)B.taskSession({sessionId:G,projectPath:E,sourceProjectPath:U.metadata.taskSourceProjectPath??g(),isolation:Y.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=o.subscribe((X)=>{if(X.type!=="task.status"||X.sessionId!==G||X.projectPath!==E||!["queued","running"].includes(String(X.properties.taskStatus))||typeof X.properties.taskQueueDepth!=="number"||typeof X.properties.taskInFlight!=="number"||typeof X.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:X.properties.taskStatus,queuePosition:typeof X.properties.taskQueuePosition==="number"?X.properties.taskQueuePosition:void 0,queueDepth:X.properties.taskQueueDepth,inFlight:X.properties.taskInFlight,maxConcurrentTasks:X.properties.taskConcurrencyLimit})});let hH={messages:kH?await i.loadSessionModelContext(G,E):[...n],userId:"cli-user",sessionId:G,workspaceRoot:E,permissionMode:R,signal:P.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:wJ()};W=await _H.create({sessionId:G,workspaceRoot:E,modelId:Y.model,permissionMode:R,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig,agents:Y.agents?EH(Y.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...n.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}});let k=f&&W.getPendingSteeringCount()>0,h=f&&!k?await W.getGoal():null,c=h?.status==="active"||h?.status==="verifying",b=f&&!k&&!c?await W.getRecoveredFinalResponse():void 0;if(f&&!k&&!c){if(!b)throw Error("No unfinished turn or active goal to resume");if(h)B.goal({kind:"goal_updated",goal:h});if(b.structuredOutput&&b.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:b.structuredOutput,schemaDigest:b.structuredOutputSchemaDigest});else B.content(b.content);return B.phase("completed","done","Recovered headless run completed"),await S(0)}if(C!==void 0){let X=await W.executeUserShellCommand(C,{signal:P.signal,onEvent:async($)=>{if($.type==="started")B.userShellStarted($.executionId,$.command,$.auxiliary);else if($.type==="output")B.userShellOutput($.executionId,$.stream,$.chunk,$.streamTruncated);await m()}});return B.userShellCompleted(X),await S(X.record.status==="completed"?0:X.record.status==="aborted"?130:X.record.exitCode??1)}let OH=Y.maxTurns??W.getConfig().maxTurns,wH=U?.taskWorktree?[...new Set([...Y.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:Y.disallowedTools,mH=await FH.createWithRuntime(W,{sessionId:G,systemPrompt:Y.systemPrompt,appendSystemPrompt:Y.appendSystemPrompt,maxTurns:Y.maxTurns,modelId:Y.model,permissionMode:R,toolWhitelist:Y.allowedTools,toolBlacklist:wH,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig}),u=await xH(mH.chatStream(_.content,hH,{stream:!0,signal:P.signal,maxTurns:Y.maxTurns,builtinVerification:Y.verificationAgent!==!1,outputSchema:T,pendingInputOnly:k,goalContinuationOnly:c,...OH===-1?{onTurnLimitReached:async(X)=>{return B.turnLimit(X.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(X)=>{switch(X.kind){case"content_delta":if(!T||q==="jsonl")J.markAssistantContent();B.contentDelta(X.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta(X.delta,J.hasOpenThinking()));break;case"stream_end":{let $=J.completeStream();B.streamEnd($.wroteAssistantContent,$.openedThinking);break}case"tool_start":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;if(["TaskCreate","TaskUpdate","TaskList"].includes($.function.name))break;try{let A=JSON.parse($.function.arguments),M=GH($.function.name,A),z=BH($.function.name,A),I=uJ($.function.name,M,z,Z);if(I.shouldLockTarget)Z.targetLocked=!0;B.phase(I.phase,I.status,I.message,{toolName:$.function.name,target:z}),B.toolStart($.function.name,M,z,X.toolKind)}catch{B.phase(Z.targetLocked?"executing":"searching",Z.targetLocked?"hit":"ongoing",Z.targetLocked?`Working within target: ${$.function.name}`:`Still searching: ${$.function.name}`,{toolName:$.function.name}),B.toolStart($.function.name,$.function.name,void 0,X.toolKind)}break}case"tool_progress":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;B.toolProgress($.function.name,X.update.message,X.update.progress,X.update.total,X.update.admission);break}case"tool_result":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;let A;try{let z=JSON.parse($.function.arguments);A=BH($.function.name,z)}catch{A=void 0}let M=jH(PH($.function.name,X.result),WH);if(B.toolResult($.function.name,M.summary,A,void 0,{success:X.result.success,errorType:X.result.error?.type,errorMessage:X.result.error?.message,background:bJ(X.result.metadata)}),M.detail)B.toolDetail($.function.name,M.detail);break}case"token_usage":B.tokenUsage(X.usage);break;case"compaction":B.compacting(X);break;case"task_update":B.taskUpdate(X.tasks);break;case"structured_output":B.structuredOutput(X);break;case"mcp_catalog_changed":B.mcpCatalogChanged(X);break;case"mcp_content_changed":B.mcpContentChanged(X);break;case"mcp_resource_updated":B.mcpResourceUpdated(X);break;case"mcp_connection_changed":B.mcpConnectionChanged(X);break;case"mcp_log":B.mcpLog(X);break;case"mcp_instructions_changed":B.mcpInstructionsChanged(X);break;case"mcp_task_changed":B.mcpTaskChanged(X);break;case"project_rules_loaded":B.projectRulesLoaded(X);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":B.goal(X);break;case"subagent_spawned":case"subagent_completed":B.subagent(X);break;case"model_fallback":break;case"provider_admission":B.providerAdmission(X);break;case"provider_retry":B.providerRetry(X);break;case"provider_circuit":B.providerCircuit(X);break;case"provider_stall":B.providerStall(X);break;case"action_stationarity":B.actionStationarity(X);break;case"turn_start":if(X.turn===1)Z.targetLocked=!1;B.phase("turn",Z.targetLocked?"hit":"ongoing",`Turn ${X.turn} started`,{turn:X.turn});break;default:{let $=X}}await m()});if(u.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!u.success)return B.error(`Error: ${u.error?.message??"Agent execution failed"}`),await S(1);return B.phase("completed","done","Headless run completed"),await S(0)}catch(Y){if(!y){if(J.hasOpenThinking()&&q==="text")w.stderr.write(`
|
|
6
|
-
`);B.error(`Error: ${mJ(Y)}`)}return await S(1)}finally{x?.(),j?.();try{await W?.dispose()}finally{F.close(),P.dispose()}}}async function AK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":Z,"max-turns":W,...x}=AH,j=SJ(TJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([fH,MH,zH]);return hJ(j),await j.parse(),!0}export{dJ as runHeadless,AK as handleHeadlessMode,gJ as HeadlessOptionsSchema};
|
package/dist/chunk-hx3c0qn6.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-jac8cc04.js";import{U as M,aa as y}from"./chunk-hx55j0d0.js";import"./chunk-0zhdjaen.js";import"./chunk-rmhgyrgh.js";import"./chunk-hz5rsfxv.js";import{Db as h,Mb as A}from"./chunk-2s86w4yb.js";import"./chunk-8hprmrd5.js";import{Cd as w,Qd as U}from"./chunk-6hr7mv7f.js";import"./chunk-s0tq8gyx.js";import"./chunk-h8qjkxee.js";import{oe as C}from"./chunk-qc4fe1j6.js";import{qe as I,re as S,se as v}from"./chunk-8zm5r6g8.js";import{te as O}from"./chunk-10taec1j.js";import"./chunk-rej5bbbs.js";import{Qe as P}from"./chunk-v9pcf4w4.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-3awjdsef.js";import"./chunk-53xtssbf.js";import"./chunk-2hb222re.js";import"./chunk-gkdynynx.js";import"./chunk-cc74b8qp.js";import"./chunk-fvfc95g3.js";import"./chunk-qcy79mva.js";import"./chunk-p0rvgzpx.js";import"./chunk-c3yd59qh.js";import"./chunk-c6tq09mt.js";import"./chunk-gcnke6s4.js";import{xh as F}from"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import"./chunk-maebpz1j.js";import{Nh as z}from"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import"./chunk-k7vv9vne.js";import"./chunk-tagtjbw9.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.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
|
-
`);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
|
-
`);else j.io.stdout.write(`${j.response}
|
|
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}
|
|
5
|
-
`);return T.exitCode??0}let K=T.content,V=await m(j),W=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(W!==void 0&&V)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:H,messages:a,metadata:D}=await l({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),X=D?.projectPath??z(),$=t(j.permissionMode)??D?.permissionMode??P()?.permissionMode??"default";await U.setSessionPermissionMode(H,X,$);let E=await A.cancelPendingNonInteractive(X,H)?await U.loadSessionModelContext(H,X):a;q=await M.create({sessionId:H,workspaceRoot:X,modelId:j.model,permissionMode:$,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?O(j.agents):void 0,...E.length>0?{sessionStart:{isResume:!0,resumeSessionId:H}}:{}});let b=J&&q.getPendingSteeringCount()>0,G=J&&!b?await q.getGoal():null,f=G?.status==="active"||G?.status==="verifying",L=J&&!b&&!f?await q.getRecoveredFinalResponse():void 0;if(J&&!b&&!f){if(!L)throw Error("No unfinished turn or active goal to resume");return x({io:B,options:j,response:L.content,requestInput:K,structuredOutput:L.structuredOutput,structuredOutputSchemaDigest:L.structuredOutputSchemaDigest}),0}if(W!==void 0){let Q=await q.executeUserShellCommand(W);if(j.outputFormat==="json")B.stdout.write(`${JSON.stringify(Q,null,2)}
|
|
6
|
-
`);else if(j.outputFormat==="stream-json")B.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:Q.executionId,record:Q.record})}
|
|
7
|
-
`);else B.stdout.write(`${w(Q.record)}
|
|
8
|
-
`);return Q.record.status==="completed"?0:Q.record.status==="aborted"?130:Q.record.exitCode??1}let N=await y.createWithRuntime(q,{sessionId:H,systemPrompt:j.systemPrompt,appendSystemPrompt:j.appendSystemPrompt,maxTurns:j.maxTurns,modelId:j.model,permissionMode:$,toolWhitelist:j.allowedTools,toolBlacklist:j.disallowedTools,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig}),k={messages:[...E],userId:"cli-user",sessionId:H,workspaceRoot:X,permissionMode:$},Y=await h(V||J?N.chatStream(K,k,{...V?{outputSchema:V}:{},pendingInputOnly:b,goalContinuationOnly:f}):N.chatStream(K,k));if(!Y.success)throw Error(Y.error?.message??"Agent execution failed");let r=Y.finalMessage||"",u=Y.metadata?.structuredOutput;return x({io:B,options:j,response:r,requestInput:K,structuredOutput:u,structuredOutputSchemaDigest:Y.metadata?.structuredOutputSchemaDigest}),0}catch(Z){return B.stderr.write(`Error: ${Z instanceof Error?Z.message:"未知错误"}
|
|
9
|
-
`),1}finally{await q?.dispose()}}async function _j(){if(process.argv.slice(2).findIndex((q)=>q==="--print"||q==="-p")===-1)return!1;try{let{print:q,"output-format":Z,"include-partial-messages":_,"input-format":J,"system-prompt":T,"append-system-prompt":K,"max-turns":V,...W}=C,H=p(e(process.argv)).scriptName("blade").strict(!1).options(W).middleware([S,I,v]);return i(H),await H.parse(),!0}catch(q){console.error(`Print mode error: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}export{n as runPrint,_j as handlePrintMode};
|
package/dist/chunk-p4h3p1at.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{s as cz,t as pz}from"./chunk-6p9p71qm.js";import{u as S}from"./chunk-1nwc2wt6.js";import{A as Nz,v as gz,w as wz,x as Dz,y as _z,z as Az}from"./chunk-sgzqcr55.js";import{G as E,P as Bz,Q as Gz,U as Uz,X as jz,Y as Vz,aa as Kz,qa as Oz,ra as qz,sa as Pz,ta as Rz}from"./chunk-hx55j0d0.js";import"./chunk-0zhdjaen.js";import{Ha as uz}from"./chunk-rmhgyrgh.js";import{Ja as Fz}from"./chunk-hz5rsfxv.js";import{Db as Yz,Mb as Lz,rb as Xz}from"./chunk-2s86w4yb.js";import{Xb as g}from"./chunk-8hprmrd5.js";import{Cd as p,Dd as $z,Fd as h,Id as Wz,Nd as P,Qd as j,ad as zz,kd as y,ld as c,md as Hz,rd as Jz,ud as Qz,wd as Zz}from"./chunk-6hr7mv7f.js";import"./chunk-s0tq8gyx.js";import"./chunk-h8qjkxee.js";import{ve as mz}from"./chunk-ttg3xrsc.js";import"./chunk-rej5bbbs.js";import{Qe as kz,Re as Iz}from"./chunk-v9pcf4w4.js";import"./chunk-v508x7cg.js";import{af as m}from"./chunk-dg0d3303.js";import{ff as e}from"./chunk-3awjdsef.js";import"./chunk-53xtssbf.js";import{qf as Cz}from"./chunk-2hb222re.js";import"./chunk-gkdynynx.js";import"./chunk-cc74b8qp.js";import"./chunk-fvfc95g3.js";import{gg as fz}from"./chunk-qcy79mva.js";import"./chunk-p0rvgzpx.js";import"./chunk-c3yd59qh.js";import"./chunk-c6tq09mt.js";import{_g as yz,bh as Mz}from"./chunk-gcnke6s4.js";import"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import{Fh as C,Gh as t,Ih as f,Jh as u}from"./chunk-maebpz1j.js";import{Nh as bz}from"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import{ni as M}from"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import{ui as hz,xi as Sz}from"./chunk-k7vv9vne.js";import"./chunk-tagtjbw9.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import{Ti as s}from"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";import{Readable as JH,Writable as QH}from"node:stream";import*as k from"@agentclientprotocol/sdk";import Ez from"node:path";import{PROTOCOL_VERSION as zH,RequestError as HH}from"@agentclientprotocol/sdk";import{createHash as lz}from"node:crypto";import{RequestError as Tz}from"@agentclientprotocol/sdk";import{nanoid as I}from"nanoid";var U=M("Agent"),i=4,iz=1000,a=4000,r=120000,o=0.2;function n(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function az(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:n(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:n("headers"in z?z.headers:void 0)};return null}function rz(z){let J={};for(let H of z){let W=az(H);if(W)J[H.name]=W}return J}function xz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function oz(z){let J=$z(z.metadata);return J?[{type:"text",text:p(J)}]:xz(z.content)}function nz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
-
`)}function sz(z){if(!e(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...y("capacity"),resource:z.resource}}function tz(z,J){let H=Math.max(0,J-1),W=Math.min(iz*2**H,a),$=lz("sha256").update(`${z}\x00${J}`).digest().readUInt32BE(0)/4294967295,Z=1-o+2*o*$;return Math.min(a,Math.max(0,Math.round(W*Z)))}function ez(z){if(!(z instanceof Tz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Hz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}class b{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,H,W,X={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=W;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new Nz({maxPendingItems:wz,maxPendingBytes:Dz,writeTimeoutMs:_z,signal:H.signal,sizeOf:($)=>Buffer.byteLength(JSON.stringify($)),write:async($)=>{await H.sessionUpdate($)},onFailure:($)=>this.handleUpdateEgressFailure($)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([j.loadSession(this.id,this.cwd),j.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await j.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Kz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(U.debug(`[AcpSession ${this.id}] Initializing...`),await j.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),E.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async($)=>{await this.sendUpdateAndWait($)}),U.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Lz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:($)=>this.requestPermission($)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?rz(this.options.mcpServers):void 0,H=E.getInstance().getTerminalService(this.id);if(this.runtime=await Uz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,Z)=>{let Y=await H.execute($,{cwd:Z.cwd,env:Z.env,timeout:Z.timeoutMs,signal:Z.signal,allowLocalFallback:!1,onOutput:(F)=>Z.onOutput?.("stdout",F)});return{exitCode:Y.exitCode,stdout:Y.stdout,stderr:Y.stderr,...Y.error?{error:Y.error}:{},timedOut:Y.failureKind==="timeout",aborted:Y.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await S.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await qz(this.cwd),U.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Xz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:Z,messageId:Y,content:F}=$.properties,L=$.properties.metadata;if($.type==="team.message.received"&&typeof Z==="string"&&typeof Y==="string"&&typeof F==="string"&&Gz(L,{messageId:Y,teamName:Z}))(async()=>{let B=await this.runtime?.enqueueSteering(F,{allowBeforeTurn:!0,messageId:Y,origin:"team_message",metadata:L});if(!B?.accepted)return;if(await new Bz(Z,s()).markDelivered([Y]),B.delivery==="next_turn")this.requestPendingResume()})().catch((B)=>{U.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,B)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let X=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||X?.status==="active"||X?.status==="verifying")this.requestPendingResume({defer:this.options.initialMessages!==void 0})}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Zz(J))continue;let H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let W of oz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:W}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);U.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{U.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let Y=await this.runtime.rewindSession(Z);return this.messages=[...Y.messages],this.contextMessages=await this.loadModelContextOr(Y.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),Y}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Z)=>{if(await this.setServiceTier(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Z)=>{if(await this.setResponseVerbosity(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Z)=>{if(await this.setCommunicationStyle(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,L,B=(D)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:D.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:D.result?.message||D.result?.error||`Subagent ${D.status}`}}]})},G=this.runtime.resumeSubagent({agentId:Z,prompt:Y,onCompleted:(D)=>{if(F)B(D);else L=D}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,L)B(L);return G}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,Y,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,Y,F)},complete:async(Z,Y,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,Y,F)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,Y)},getLogs:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,Y)},setLoggingLevel:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,Y)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Z,{signal:Y})}},codeReview:{run:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await S.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:Y,onEvent:(G)=>{if(G.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.toolCall.id,status:"in_progress",title:`Review: ${G.toolCall.function.name}`,content:[],kind:this.mapToolKind(G.toolKind)});else if(G.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.toolCall.id,status:G.result.success?"completed":"failed",content:[]})}}),L=await F.completion,B=(await S.list(this.cwd,this.id)).find((G)=>G.start.reviewId===F.reviewId);if(!B)throw Error(`Review not found: ${F.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:F.reviewId,status:L.status,findings:L.findings.length,content:zz(B.start,L)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,Y,F)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:B})},sendToolResult:(Z,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},W=await Pz(z,H),X=W.data?.action;if(X==="start_goal"||X==="resume_goal")this.requestPendingResume();if(X==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages],this.contextMessages=await this.loadModelContextOr(W.data.messages);if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages){this.contextMessages=[...W.data.compactedMessages];let Z=await j.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let $=W.content||W.message;if($)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return await this.flushUpdates(),{stopReason:W.success?"end_turn":"cancelled"}}catch(H){if(J.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};return U.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,H,W=new Promise((X)=>{H=X});this.pendingSideConversation=J,this.pendingSideConversationCompletion=W;try{return await this.handleSlashCommand(z,J.signal)}catch(X){if(J.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw X}finally{if(H(),this.pendingSideConversationCompletion===W)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Rz(this.cwd,this.runtime?.getAgentResources()),J=["model","permissions","theme","config","exit","ide"],W=z.filter((X)=>!J.includes(X.name)&&(X.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((X)=>{let $;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)$=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;$=$?`${$} | ${Z}`:Z}return{name:X.name,description:X.description,input:$?{hint:$}:void 0}});U.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),U.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(z){U.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(E.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),W=H.content,X=H.displayText,$=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((K)=>K.outputSchema)?.outputSchema:void 0),Z;if($!==void 0)Z=Wz($).schema;if(X.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let Y=Fz(X);if(Y){if(Z)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(W)&&W.some((K)=>K.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(Y.question?`/btw ${Y.question}`:"/btw")}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(X.trim()))return this.handleSlashCommand(X,this.pendingPrompt.signal);let K=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!K.accepted)throw Error(K.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(U.debug(`[AcpSession ${this.id}] Queued steering for active turn (${K.queued})`),K.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let F=new AbortController,L=()=>{F.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let B=!1,G=!1,D=!1,R,T=new Promise((K)=>{R=K});this.pendingPrompt=F,this.pendingPromptCompletion=T;try{if(U.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),Oz(X)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,F.signal)}let K={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Q)=>{this.mode=this.mapPermissionModeToMode(Q),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Q)=>{return this.requestPermission(Q)}}},A=await Yz(this.agent.chatStream(W,K,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async(Q)=>{switch(Q.kind){case"content_delta":if(Z)break;if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q.delta}});break;case"thinking_delta":if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Q.delta}});break;case"tool_start":{D=!0;let V=Q.toolCall,N=V.function.name;if(N===h)break;let q=this.mapToolKind(Q.toolKind),w=`Executing ${N}`;if(N==="Task"&&"function"in V)try{let x=JSON.parse(V.function.arguments),_=x.resume_from??x.resume;if(typeof _==="string")w=`Resuming ${String(x.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:q});break}case"tool_progress":{D=!0;let V=Q.toolCall;if(V.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Q.update.message}}]});break}case"tool_result":{D=!0;let V=Q.toolCall;if(V.function.name===h)break;let N=Q.result,q=[],w=N.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let _ of w.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;q.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))q.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let _=V.function.name,vz=Vz(Qz(jz(_,N),Jz));q.push({type:"content",content:{type:"text",text:vz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let x=N.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:x,content:q});break}case"structured_output":G=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Q.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
|
|
3
|
-
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Q.contentKind} r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
|
|
4
|
-
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Q.revision} (${Q.serverName}): ${Q.uri}
|
|
5
|
-
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${Q.revision} (${Q.serverName}): ${Q.phase} ${Q.attempt}/${Q.maxAttempts}
|
|
6
|
-
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${Q.revision} (${Q.serverName}) ${Q.level}${Q.logger?` logger=${Q.logger}`:""}: ${Q.message}
|
|
7
|
-
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Q.revision} (${Q.serverName}): ${Q.action}${Q.detailsOmitted?" details-omitted":""}
|
|
8
|
-
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Q.revision} ${Q.taskId} (${Q.serverName}/${Q.toolName}): ${Q.status}${Q.hasResult?" result-available":""}
|
|
9
|
-
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Q.files.length}${Q.blockedWrite?" (write retry required)":""}
|
|
10
|
-
`}});break;case"provider_admission":B=Q.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":Q.phase!=="admitted"?{phase:Q.phase,requestClass:Q.requestClass,resource:Q.resource,scope:Q.scope,...Q.reason!==void 0?{reason:Q.reason}:{},queuePosition:Q.queuePosition,queueDepth:Q.queueDepth,inFlight:Q.inFlight,limit:Q.limit,waitMs:Q.waitMs,maxWaitMs:Q.maxWaitMs,...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:Q.phase,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.retryAfterMs!==void 0?{retryAfterMs:Q.retryAfterMs}:{},...Q.nextProbeAt!==void 0?{nextProbeAt:Q.nextProbeAt}:{},openDurationMs:Q.openDurationMs,...Q.sampleCount!==void 0?{sampleCount:Q.sampleCount}:{},...Q.failureCount!==void 0?{failureCount:Q.failureCount}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:Q.phase,attempt:Q.attempt,maxRetries:Q.maxRetries,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.delayMs!==void 0?{delayMs:Q.delayMs}:{},...Q.nextRetryAt!==void 0?{nextRetryAt:Q.nextRetryAt}:{},...Q.mode!==void 0?{mode:Q.mode}:{},...Q.recoveryBudgetMs!==void 0?{recoveryBudgetMs:Q.recoveryBudgetMs}:{},...Q.recoveryElapsedMs!==void 0?{recoveryElapsedMs:Q.recoveryElapsedMs}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{},...Q.exhaustedBy!==void 0?{exhaustedBy:Q.exhaustedBy}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:Q.phase,stallCount:Q.stallCount,durationMs:Q.durationMs,warningAfterMs:Q.warningAfterMs,timeoutMs:Q.timeoutMs,outputStarted:Q.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:Q.phase,toolName:Q.toolName,runLength:Q.runLength,nudgeThreshold:Q.nudgeThreshold,haltThreshold:Q.haltThreshold,progressAware:Q.progressAware}}});break;case"task_update":this.sendPlanUpdate(Q.tasks);break;case"steering_applied":break;case"follow_up_started":{let V=0;for(let N of Q.messages){if(!N.recovered||N.persisted)continue;if(J.projectedRecoveredInputIds?.has(N.id))continue;for(let q of xz(N.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(N.id),V++}if(V>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${V} queued instruction${V===1?"":"s"} recovered after restart]
|
|
11
|
-
`}});break}case"goal_updated":if(Q.goal)this.sendUpdate(this.goalSessionUpdate(Q.goal));if(Q.goal&&Q.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Q.goal.status}: ${Q.goal.objective}]
|
|
12
|
-
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:Q.goal.goalId,continuation:Q.continuation,...Q.prematureStopPattern?{prematureStopPattern:Q.prematureStopPattern}:{},...Q.prematureStopCount!==void 0?{prematureStopCount:Q.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:Q.phase,...Q.reason?{reason:Q.reason}:{},...Q.strategy?{strategy:Q.strategy}:{},...Q.outcome?{outcome:Q.outcome}:{},...Q.preTokens!==void 0?{preTokens:Q.preTokens}:{},...Q.preTokenSource?{preTokenSource:Q.preTokenSource}:{},...Q.estimatedPendingTokens!==void 0?{estimatedPendingTokens:Q.estimatedPendingTokens}:{},...Q.postTokens!==void 0?{postTokens:Q.postTokens}:{},...Q.sampleAttempts!==void 0?{sampleAttempts:Q.sampleAttempts}:{},...Q.inputReductions!==void 0?{inputReductions:Q.inputReductions}:{},...Q.messagesOmitted!==void 0?{messagesOmitted:Q.messagesOmitted}:{},...Q.filesOmitted!==void 0?{filesOmitted:Q.filesOmitted}:{},...Q.imagesOmitted!==void 0?{imagesOmitted:Q.imagesOmitted}:{},...Q.fallbackTargetTokens!==void 0?{fallbackTargetTokens:Q.fallbackTargetTokens}:{},...Q.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:Q.fallbackMessagesOmitted}:{},...Q.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:Q.fallbackMessagesTruncated}:{},...Q.failureReason?{failureReason:Q.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())F.abort("acp-egress-failed")});if(!await this.flushUpdates())F.abort("acp-egress-failed");this.contextMessages=[...K.messages];let d=await j.loadSession(this.id,this.cwd);if(this.messages=d.length>0?d:[...K.messages],!A.success){let Q=A.error?.type??"unknown",V=A.error?.details??A.error?.message??"Agent execution failed",N=sz(V)??c(V);throw Tz.internalError({failureType:Q,taskFailure:N,outputStarted:G,toolExecutionStarted:D,...Number.isInteger(A.metadata?.toolCallsCount)?{toolCallsCount:A.metadata.toolCallsCount}:{}},`Agent turn failed (${Q})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let l={...A.metadata?.structuredOutput?{structuredOutput:A.metadata.structuredOutput,outputSchemaDigest:A.metadata.structuredOutputSchemaDigest}:{},...A.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:A.metadata.goalVerificationVerdict,...A.metadata.goalVerifierSessionId?{verifierSessionId:A.metadata.goalVerifierSessionId}:{},...A.metadata.goalVerificationEvidenceSha256?{evidenceSha256:A.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(l).length>0?{_meta:l}:{}}}catch(K){if(F.signal.aborted||K instanceof Error&&K.name==="AbortError")return{stopReason:"cancelled"};throw U.error(`[AcpSession ${this.id}] Prompt error:`,K),K}finally{if(J.abortSignal?.removeEventListener("abort",L),B&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(R(),this.pendingPromptCompletion===T)this.pendingPromptCompletion=null;if(this.pendingPrompt===F){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let H=new AbortController,W,X=new Promise((Y)=>{W=Y});this.pendingUserShell=H,this.pendingUserShellCompletion=X;let $,Z="";try{let Y=await this.runtime.executeUserShellCommand(J,{signal:H.signal,onEvent:async(L)=>{if($=L.executionId,L.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.executionId,status:"in_progress",title:`! ${L.command}`,content:[],kind:"execute"});return}if(L.type==="output"){Z+=L.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:L.chunk}}]});return}let B=p(L.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:L.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Z?nz(L.record):B}}]})}}),F={role:"user",content:Y.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(Y.record))}};if(this.messages.push(F),this.contextMessages.push(F),Y.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return H.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:Y.record.status==="aborted"?"cancelled":"end_turn"}}catch(Y){if($)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$,status:"failed",content:[{type:"content",content:{type:"text",text:Y instanceof Error?Y.message:String(Y)}}]});if(H.signal.aborted)return{stopReason:"cancelled"};throw Y}finally{if(W(),this.pendingUserShellCompletion===X)this.pendingUserShellCompletion=null;if(this.pendingUserShell===H){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight)return;this.pendingResumeScheduled=!0;let J=this.pendingResumeGeneration,H=()=>{if(J!==this.pendingResumeGeneration)return;this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,this.resumePendingIfIdle()};if(z>0)this.pendingResumeTimer=setTimeout(H,z),this.pendingResumeTimer.unref?.();else queueMicrotask(H)}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:i,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let H="preflight",W=!1,X,$=null;try{let Z=this.runtime.getPendingSteeringCount()>0,Y=Z?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let F=Y?.status==="active"||Y?.status==="verifying";if(!Z&&!F){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}H=Z?"pending_input":"goal",W=!0;let L=r-(Date.now()-this.pendingResumeRecoveryStartedAt);if(L<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}let B=new AbortController;$=setTimeout(()=>{B.abort("acp-pending-resume-budget-exhausted")},L),$.unref?.();let G=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Z,goalContinuationOnly:F,projectedRecoveredInputIds:H==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:B.signal});if(z!==this.pendingResumeGeneration)return;if(B.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}if(G.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1)this.sendUpdate(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:H}));this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Z){if(z!==this.pendingResumeGeneration)return;let Y=W?ez(Z):{taskFailure:c(Z),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},L=(H==="preflight"||H==="pending_input"&&this.runtime.getPendingSteeringCount()>0)&&Y?.taskFailure.retryable===!0&&!Y.toolExecutionStarted&&Y.toolCallsCount===0&&!Y.outputStarted,B=tz(this.id,J),G=Date.now()-this.pendingResumeRecoveryStartedAt,D=J<i,R=G+B<=r;if(L&&D&&R)this.pendingResumeRequested=!0,X=B,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:H,taskFailure:Y.taskFailure,delayMs:B})),U.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${B}ms`);else{let T=L&&(!D||!R)?"exhausted":"failed";if(this.sendUpdate(this.pendingResumeSessionUpdate(T,{attempt:J,kind:H,taskFailure:Y?.taskFailure})),U.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${L}, phase=${T})`,Z),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest()}}finally{if($!==null)clearTimeout($);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.ensurePendingResumeScheduled(X)}}cancel(){U.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)U.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"].includes(z)?z:"default",W=this.mapModeIdToPermissionMode(H);await j.setSessionPermissionMode(this.id,this.cwd,W),this.mode=H,U.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(U.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await j.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(H){if(J&&J!==z)await this.agent.switchModel(J).catch((W)=>{U.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw H}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(H){throw await this.runtime.refresh({reasoningEffort:J.selection}),H}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(H){throw await this.runtime.refresh({serviceTier:J.selection}),H}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(H){throw await this.runtime.refresh({responseVerbosity:J.selection}),H}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),H=this.runtime.resolveCommunicationStyleConfiguration(z);if(H.source!=="built-in"&&!H.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:H.source==="built-in"?null:H.contentSha256})}catch(W){if(!(W instanceof P)&&W.code!=="ENOENT")throw W;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...H.source!=="built-in"&&H.contentSha256?{communicationStyleDigest:H.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:J.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Az("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,H=this.runtime,W=this.pendingPromptCompletion,X=this.pendingUserShellCompletion,$=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Z,Y=async(F)=>{try{await F()}catch(L){Z??=L}};if(await Y(()=>this.cancel()),W)await Y(()=>W);if(X)await Y(()=>X);if($)await Y(()=>$);if(z&&W&&H)await Y(()=>H.discardPendingInput());if(J)await Y(()=>J.destroy());if(H)await Y(()=>H.dispose());if(await Y(()=>E.destroySession(this.id)),U.debug(`[AcpSession ${this.id}] Destroyed`),Z!==void 0)throw Z}resolvePrompt(z){let J=[],H=[],W=0,X=0,$=0,Z=(L)=>{if(H.length>0)H.push({type:"text",text:`
|
|
13
|
-
`}),$+=1;if(H.push(L),L.type==="text")$+=L.text.length};for(let L of z)if(L.type==="text")J.push(L.text),Z({type:"text",text:L.text});else if(L.type==="image"){let B=`data:${L.mimeType};base64,${L.data}`;W+=1,X+=B.length,J.push(`[Image: ${L.mimeType}]`),Z({type:"image_url",image_url:{url:B}})}else if(L.type==="resource"){let B=L.resource;if("text"in B){let G=`<file path="${B.uri}">
|
|
14
|
-
${B.text}
|
|
15
|
-
</file>`;J.push(G),Z({type:"text",text:G})}}else if(L.type==="resource_link"){let B=`[Resource: ${L.uri}]`;J.push(B),Z({type:"text",text:B})}if(W>C)throw Error(`ACP prompt contains more than ${C} images`);if(X>t)throw Error("ACP prompt images exceed the 5 MiB limit");if($>f)throw Error(`ACP prompt text exceeds ${f} characters`);if(Buffer.byteLength(J.join(`
|
|
16
|
-
`),"utf8")>u)throw Error(`ACP prompt text exceeds ${u} bytes`);let F=J.join(`
|
|
17
|
-
`);return{content:W>0?H:F,displayText:F}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;U.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let J=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));U.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let H=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(H))return U.debug(`[AcpSession ${this.id}] Auto-approving ${H} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(H==="write"||H==="execute"))return U.debug(`[AcpSession ${this.id}] Rejecting ${H} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let W=I(),X=[];if(z.message)X.push({type:"content",content:{type:"text",text:z.message}});if(z.details)X.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)X.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
-
- ${z.risks.join(`
|
|
19
|
-
- `)}`}});let $=this.mapToolKind(H),Z={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:W,status:"pending",title:z.title||"Permission Required",content:X,kind:$}},Y=await this.waitForClientInteraction(this.connection.requestPermission(Z),J);if(!Y)return{approved:!1,reason:g};let F=Y.outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let L=F.optionId;if(L==="allow_always")return{approved:!0,scope:"project"};if(L==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let B=L==="allow_once";return{approved:B,scope:"once",reason:B?void 0:"User denied the operation"}}catch(W){return U.warn(`[AcpSession ${this.id}] Permission request failed:`,W),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let H=z.questions??[];if(H.length===0)return{approved:!1,reason:"No structured questions were provided"};if(H.some((X)=>X.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let W={};try{for(let[X,$]of H.entries()){let Z=$.options.map((B,G)=>`answer:${X}:${G}`),Y=`answer:${X}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...$.options.map((B,G)=>({optionId:Z[G],name:B.label,kind:"allow_once"})),{optionId:Y,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:I(),status:"pending",title:$.header,kind:"think",content:[{type:"content",content:{type:"text",text:[$.question,...$.options.map((B)=>`${B.label}: ${B.description}`)].join(`
|
|
20
|
-
`)}}]}}),J);if(!F)return{approved:!1,reason:g};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let L=Z.indexOf(F.outcome.optionId);if(L<0)return{approved:!1,reason:"User cancelled the question prompt"};W[$.header]=$.options[L].label}return{approved:!0,answers:W}}catch(X){return U.warn(`[AcpSession ${this.id}] Question request failed:`,X),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let H=z.mcpElicitation;if(!H)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(H.mode==="url"){let X=await this.requestElicitationChoice("MCP external authorization",[H.message,`Server: ${H.serverName}`,`Domain: ${H.domain??"unknown"}`,`URL: ${H.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
21
|
-
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],J);if(X==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:X==="decline"?"User declined URL":"User cancelled",elicitation:{action:X==="decline"?"decline":"cancel"}}}let W=Object.create(null);for(let X of H.fields??[]){let $=await this.collectAcpElicitationField(X,J);if($.cancelled)return{approved:!1,reason:$.reason,elicitation:{action:"cancel"}};if($.value!==void 0)W[X.name]=$.value}return{approved:!0,elicitation:{action:"accept",content:W}}}catch(W){return U.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,W),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let H=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map(($,Z)=>({id:`option:${Z}`,label:$.label,value:$.value})),W=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
-
`),[...H.map(($)=>({id:$.id,label:$.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(W==="skip")return{cancelled:!1};let X=H.find(($)=>$.id===W);if(!X)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:X.value}}if(z.defaultValue!==void 0){let H=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
23
|
-
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(H==="default")return{cancelled:!1,value:z.defaultValue};if(H==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,H,W){let X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.map(($)=>({optionId:$.id,name:$.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:I(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),W);return X?.outcome.outcome==="selected"?X.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((H,W)=>{let X=!1,$=(Y)=>{if(X)return;X=!0,J.removeEventListener("abort",Z),Y()},Z=()=>$(()=>H(void 0));if(J.addEventListener("abort",Z,{once:!0}),J.aborted)Z();z.then((Y)=>$(()=>H(Y)),(Y)=>$(()=>W(Y)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var O=M("Agent");class v{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;constructor(z){this.connection=z}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=kz();this.runtimeResidencyValue=new pz({maxResident:z?.maxResidentSessionRuntimes??yz,idleMs:z?.sessionRuntimeIdleMs??Mz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof cz)throw HH.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return O.info("[BladeAgent] Initializing ACP connection"),O.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await Iz(),{protocolVersion:zH,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=m("acp"),H=await this.reserveSessionRuntime(J),W=z.cwd||bz(),X=z._meta?.["blade/taskIsolation"],$=X==="local"||X==="worktree"?X:void 0,Z=z._meta?.["blade/taskPrompt"],Y;try{let F=$?await gz.createSessionTask({sessionId:J,prompt:typeof Z==="string"&&Z.trim()?Z:"ACP task session",sourceProjectPath:W,isolation:$}):void 0,L=F?.metadata.projectPath??W;return O.info(`[BladeAgent] Creating new session: ${J}`),O.debug(`[BladeAgent] Session cwd: ${L}`),Y=new b(J,L,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...F?.taskWorktree?{taskWorktree:F.taskWorktree}:{},...F?.metadata.taskIsolation?{taskIsolation:F.metadata.taskIsolation}:{}}),await Y.initialize(),this.assertNotDestroyed(),this.commitSession(J,Y,H),O.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),Y.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,F?.metadata,Y.getModelConfiguration())}catch(F){throw H.cancel(),await Y?.destroy().catch(()=>{return}),F}}async listSessions(z){if(z.cwd!=null&&!Ez.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=await j.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((H)=>({sessionId:H.sessionId,cwd:H.projectPath,title:H.title??null,updatedAt:H.lastMessageTime,_meta:{"blade/taskStatus":H.taskStatus,...H.taskStatusReason?{"blade/taskStatusReason":H.taskStatusReason}:{},...H.taskFailure?{"blade/taskFailure":H.taskFailure}:{},...H.taskStartedAt?{"blade/taskStartedAt":H.taskStartedAt}:{},...H.taskCompletedAt?{"blade/taskCompletedAt":H.taskCompletedAt}:{},...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskIsolation?{"blade/taskIsolation":H.taskIsolation}:{},...H.taskSourceProjectPath?{"blade/taskSourceProjectPath":H.taskSourceProjectPath}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{},...H.taskDiffStat?{"blade/taskDiffStat":H.taskDiffStat}:{},...H.taskQueuePosition?{"blade/taskQueuePosition":H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{"blade/taskQueueDepth":H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":H.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!Ez.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let J=m("fork"),H=await this.reserveSessionRuntime(J),W;try{let X=await j.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd,newSessionId:J});return this.assertNotDestroyed(),W=new b(X.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:X.messages,permissionMode:X.metadata.permissionMode,mcpServers:z.mcpServers}),await W.initialize(),this.assertNotDestroyed(),this.commitSession(X.sessionId,W,H),W.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(X.sessionId,X.metadata,W.getModelConfiguration())}catch(X){throw H.cancel(),await W?.destroy().catch(()=>{return}),X}}async loadSession(z){this.assertNotDestroyed(),O.info(`[BladeAgent] Loading session: ${z.sessionId}`);let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{return await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await j.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let J=await this.reserveSessionRuntime(z.sessionId),H;try{let[W,X]=await Promise.all([j.loadSession(z.sessionId,z.cwd),j.findSessionMetadata(z.sessionId,z.cwd)]);if(!X)throw Error(`Session not found: ${z.sessionId}`);return H=new b(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:X.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),await H.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,H,J),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}catch(W){throw J.cancel(),await H?.destroy().catch(()=>{return}),W}}commitSession(z,J,H){let W=H.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),W.release()}async closeResidentSession(z,J={}){let H=this.sessions.get(z);if(!H)return;let W=this.runtimeResidency.owns(z,H),X;try{await H.destroy(J)}catch(Z){X=Z}let $=await this.runtimeResidency.forget(z,H);if(this.sessions.get(z)===H)this.sessions.delete(z);if(W&&!$&&X===void 0)throw Error(`ACP Session is still active: ${z}`);if(X!==void 0)throw X}buildChildSessionResponse(z,J,H){return{sessionId:z,...this.buildSessionSetup(H,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let H=z?.models??[],W=(z?.currentModelId&&H.some((Z)=>Z.id===z.currentModelId)?z.currentModelId:void 0)??H[0]?.id,X=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],$=[];if(H.length>0)$.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:W,options:H.map((Z)=>({value:Z.id,name:Z.displayName??Z.model,description:`${z?.modelProviders[Z.provider]?.name??Z.provider} · ${Z.model}`}))});if(z?.reasoning)$.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="off"?"Disable model reasoning":`Use ${Z} reasoning effort`}))]});if(z?.serviceTier)$.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="fast"?"Use the provider priority tier":Z==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)$.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:`Use ${Z} response verbosity`}))]});if(z?.communicationStyle)$.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Z)=>({value:Z.id,name:Z.name,description:`${Z.description} · ${Z.source}`}))});return{modes:{availableModes:X,currentModeId:J},configOptions:$.length>0?$:void 0}}async closeSession(z){this.assertNotDestroyed();let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){O.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){O.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else O.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){O.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let H=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")O.info(`[BladeAgent] Setting session model: ${z.value}`),await H.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&Cz(z.value))O.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await H.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&Sz(z.value))O.info(`[BladeAgent] Setting service tier: ${z.value}`),await H.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&hz(z.value))O.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await H.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&fz(z.value))O.info(`[BladeAgent] Setting communication style: ${z.value}`),await H.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(H.getModelConfiguration(),H.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(H){z??=H}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await uz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function eH(){let z=QH.toWeb(process.stdout),J=JH.toWeb(process.stdin),H=k.ndJsonStream(z,J),W,X=new k.AgentSideConnection((Z)=>{return W=new v(Z),W},H),$=mz(async()=>{await W?.destroy()});try{await X.closed}finally{$(),await W?.destroy()}}export{eH as runAcpIntegration};
|
package/dist/chunk-t29x8420.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{h as a,i as b,j as c,k as d,l as e}from"./chunk-ara0zd89.js";import"./chunk-tagtjbw9.js";import"./chunk-w9xfks7f.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|