blade-code 0.10.205 → 0.10.206
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-09kqfdpa.js +3 -0
- package/dist/{chunk-efjjkha8.js → chunk-0ef47wgr.js} +2 -2
- package/dist/chunk-1j39te3t.js +23 -0
- package/dist/{chunk-fdr4fcrf.js → chunk-1n4v80hy.js} +1 -1
- package/dist/{chunk-ynd1v33f.js → chunk-28n945me.js} +2 -2
- package/dist/{chunk-ys8gysg8.js → chunk-28tzj187.js} +1 -1
- package/dist/{chunk-qtwgm95z.js → chunk-3crwyd2r.js} +3 -3
- package/dist/{chunk-zfxcef0z.js → chunk-50vwafn5.js} +1 -1
- package/dist/chunk-514va7ce.js +2 -0
- package/dist/{chunk-kkzznz4w.js → chunk-53vh6vpt.js} +1 -1
- package/dist/chunk-5k8k56f2.js +731 -0
- package/dist/{chunk-515yj7mt.js → chunk-65wc1h38.js} +1 -1
- package/dist/{chunk-xbs91jd8.js → chunk-67wy9mm7.js} +2 -2
- package/dist/chunk-6p0hkf4f.js +1 -0
- package/dist/{chunk-qdbbke8f.js → chunk-6xzk4hsg.js} +1 -1
- package/dist/chunk-793wjhvz.js +332 -0
- package/dist/{chunk-rtwd35gd.js → chunk-826xegd8.js} +2 -2
- package/dist/chunk-867bpjzg.js +1 -0
- package/dist/{chunk-zj1g4nbq.js → chunk-870szc6v.js} +1 -1
- package/dist/chunk-983hqzat.js +1 -0
- package/dist/{chunk-0eajnhrj.js → chunk-9kj19a8t.js} +1 -1
- package/dist/{chunk-430b319j.js → chunk-9sf1t8gw.js} +1 -1
- package/dist/chunk-9tpzmy8v.js +4 -0
- package/dist/chunk-af0m5227.js +1 -0
- package/dist/{chunk-f8kjdxz7.js → chunk-asgmmaec.js} +2 -2
- package/dist/{chunk-vz88tqtd.js → chunk-av799ng5.js} +2 -2
- package/dist/{chunk-bwe49m6n.js → chunk-az3rehz9.js} +360 -360
- package/dist/{chunk-p0wyhp5a.js → chunk-dnpkf5mv.js} +2 -2
- package/dist/chunk-dpg006xj.js +1 -0
- package/dist/{chunk-xmymx75h.js → chunk-e0ft3vwg.js} +1 -1
- package/dist/chunk-e45r1a8r.js +25 -0
- package/dist/{chunk-g01mth5d.js → chunk-ebpg1srd.js} +2 -2
- package/dist/{chunk-4wx5sya5.js → chunk-ed2hdrwe.js} +1 -1
- package/dist/{chunk-7ajvrtb3.js → chunk-erhaedch.js} +1 -1
- package/dist/{chunk-kehgewqh.js → chunk-ewwrss2w.js} +1 -1
- package/dist/{chunk-kf9gj2gn.js → chunk-fc1gz532.js} +2 -2
- package/dist/{chunk-9jz1q7bk.js → chunk-fd0a8h55.js} +2 -2
- package/dist/{chunk-qp2qc4p2.js → chunk-fnmqxhv1.js} +2 -2
- package/dist/chunk-g7tphxme.js +6 -0
- package/dist/{chunk-eg3ms291.js → chunk-gmpsfkgg.js} +1 -1
- package/dist/chunk-gpnkxh4c.js +1 -0
- package/dist/{chunk-b8ast0cp.js → chunk-gz84aewr.js} +1 -1
- package/dist/{chunk-xxbxc31z.js → chunk-h4k69z1b.js} +1 -1
- package/dist/{chunk-17d4m89n.js → chunk-h6ahwwpa.js} +2 -2
- package/dist/chunk-hpge30p8.js +8 -0
- package/dist/{chunk-1cy4ab77.js → chunk-hv8nt7wj.js} +1 -1
- package/dist/chunk-mtvbm7xe.js +1 -0
- package/dist/chunk-mys9mmcp.js +1 -0
- package/dist/{chunk-wezr6wfq.js → chunk-n34qsnks.js} +1 -1
- package/dist/chunk-n5jzmwhy.js +25 -0
- package/dist/chunk-new78c3h.js +1 -0
- package/dist/{chunk-8pd1hp4r.js → chunk-nj6kpdte.js} +2 -2
- package/dist/chunk-nng1xbsm.js +10 -0
- package/dist/{chunk-xyypxrad.js → chunk-p2y1zqsb.js} +2 -2
- package/dist/chunk-p8vpvx07.js +12 -0
- package/dist/{chunk-w42j9p3t.js → chunk-pdna2qvv.js} +2 -2
- package/dist/{chunk-gn9er641.js → chunk-pga8gxtf.js} +1 -1
- package/dist/chunk-pt0y4zrg.js +14 -0
- package/dist/{chunk-5zmp7p0n.js → chunk-q6abav45.js} +51 -51
- package/dist/chunk-r4em0ha7.js +1 -0
- package/dist/chunk-rdzbd5vk.js +1 -0
- package/dist/chunk-sbfe9vh3.js +94 -0
- package/dist/chunk-sqk8cnej.js +44 -0
- package/dist/{chunk-5yyp6njq.js → chunk-t0gm0pn1.js} +1 -1
- package/dist/{chunk-egss0m1x.js → chunk-tsm8rhmd.js} +1 -1
- package/dist/chunk-tzvb0nd2.js +2 -0
- package/dist/{chunk-kvp523gt.js → chunk-v4cxk10d.js} +1 -1
- package/dist/{chunk-ak5xvsxr.js → chunk-v5vx6nz9.js} +1 -1
- package/dist/{chunk-qq5y7b2r.js → chunk-vx2g1faw.js} +1 -1
- package/dist/chunk-w6zat4v4.js +1 -0
- package/dist/chunk-wsd3rn0q.js +1 -0
- package/dist/{chunk-c51wwnh2.js → chunk-xcq0cehr.js} +5 -6
- package/dist/chunk-yjjxv7fn.js +352 -0
- package/dist/{chunk-6169xxb4.js → chunk-yzf2jpam.js} +2 -2
- package/dist/web/assets/{ChatView-BF6HUrBw.js → ChatView-lUD-61n0.js} +4 -4
- package/dist/web/assets/{CodeBlockHighlighter-C4CgCiRf.js → CodeBlockHighlighter--TbfcBxW.js} +1 -1
- package/dist/web/assets/FilePreview-R6OKQPf2.js +55 -0
- package/dist/web/assets/{KanbanBoard-DDXB-yq1.js → KanbanBoard-BHOKtiv5.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DS7RznBE.js → MarkdownRenderer-DqxNq8pa.js} +3 -3
- package/dist/web/assets/{ScrollArea-BM9NzGZM.js → ScrollArea-Dhu0B-zB.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-DnRySeLE.js → SessionHistorySurface-aZvoj3ma.js} +1 -1
- package/dist/web/assets/{SettingsModal-D5YLUtIo.js → SettingsModal-C7QBnIqa.js} +1 -1
- package/dist/web/assets/{Sidebar-BZC6OkDJ.js → Sidebar-Bznnq91x.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-WewOkw5m.js → TaskSwitcher-DJczhDRp.js} +1 -1
- package/dist/web/assets/{TerminalPanel-C5SGdRNr.js → TerminalPanel-Vk4p0V3p.js} +1 -1
- package/dist/web/assets/{archive-DkczUU08.js → archive-0hLYBKQf.js} +1 -1
- package/dist/web/assets/{arrow-left-9pBiQwu7.js → arrow-left-CXb6Gqf3.js} +1 -1
- package/dist/web/assets/{calendar-clock-BFnUlxrU.js → calendar-clock-DiaFI9Jk.js} +1 -1
- package/dist/web/assets/{chevron-right-yCVkAEcj.js → chevron-right-CcPXH37D.js} +1 -1
- package/dist/web/assets/{clock-3-CcoWoRQs.js → clock-3-D6VR6gJc.js} +1 -1
- package/dist/web/assets/{copy-HJF0oQBS.js → copy-C3eUAQgp.js} +1 -1
- package/dist/web/assets/{download-DSBCIqk3.js → download-DHvS9tI3.js} +1 -1
- package/dist/web/assets/{external-link-zIgEO0KB.js → external-link-BDVaEuqY.js} +1 -1
- package/dist/web/assets/{folder-BdRo64o3.js → folder-B80Ac6rr.js} +1 -1
- package/dist/web/assets/index-VwIiNjc8.css +1 -0
- package/dist/web/assets/{index-BVDkKudh.js → index-YqughEZk.js} +4 -4
- package/dist/web/assets/{message-square-plus-3klTXO0S.js → message-square-plus-D15quyPH.js} +1 -1
- package/dist/web/assets/{pause-B9Q5JWvH.js → pause-BjMlj6Bx.js} +1 -1
- package/dist/web/assets/{pencil-CbYIz1b1.js → pencil-BMoJvcB7.js} +1 -1
- package/dist/web/assets/{play-CZMTj43e.js → play-BHh4py3p.js} +1 -1
- package/dist/web/assets/{plus-Cc7I8fhb.js → plus-DeFz_gQq.js} +1 -1
- package/dist/web/assets/session-events-DCHBz9We.js +25 -0
- package/dist/web/assets/{settings-DSF3exX2.js → settings-CI8xbId2.js} +1 -1
- package/dist/web/assets/{team-qfeJHL9s.js → team-zZ803hH9.js} +1 -1
- package/dist/web/assets/{teamService-Bs9qBKI8.js → teamService-CgLBXgmv.js} +1 -1
- package/dist/web/assets/{terminal-DQLqe-Ed.js → terminal-1WxSJ47E.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-18swytk4.js +0 -25
- package/dist/chunk-3297ghav.js +0 -1
- package/dist/chunk-33ck9ryb.js +0 -1
- package/dist/chunk-4fa11h6f.js +0 -94
- package/dist/chunk-535s1mm8.js +0 -1
- package/dist/chunk-57939tb3.js +0 -8
- package/dist/chunk-6v0cdqkw.js +0 -1
- package/dist/chunk-8kwj6px8.js +0 -1
- package/dist/chunk-a8z11yd2.js +0 -3
- package/dist/chunk-aatfjx15.js +0 -2
- package/dist/chunk-b2ek44t5.js +0 -12
- package/dist/chunk-b9d0ex8n.js +0 -4
- package/dist/chunk-ccgtbzrz.js +0 -14
- package/dist/chunk-jgxfhk9k.js +0 -733
- package/dist/chunk-jhpwwwjt.js +0 -1
- package/dist/chunk-jjj86dej.js +0 -1
- package/dist/chunk-kejvty9z.js +0 -23
- package/dist/chunk-mhe1zppc.js +0 -1
- package/dist/chunk-pb1q26gw.js +0 -181
- package/dist/chunk-pc5f77qh.js +0 -1
- package/dist/chunk-pkx6kfy6.js +0 -1
- package/dist/chunk-qjptyj18.js +0 -1
- package/dist/chunk-shgxzmdw.js +0 -1
- package/dist/chunk-thytjs86.js +0 -44
- package/dist/chunk-tm3789m3.js +0 -2
- package/dist/chunk-tnmcrvk2.js +0 -25
- package/dist/chunk-wejthch2.js +0 -1
- package/dist/chunk-xv6ejk2z.js +0 -353
- package/dist/chunk-yvgef7rp.js +0 -10
- package/dist/chunk-zj48897e.js +0 -6
- package/dist/web/assets/FilePreview-BS4PgFKb.js +0 -55
- package/dist/web/assets/index-CaCifsSK.css +0 -1
- package/dist/web/assets/session-events-NEjosinC.js +0 -31
package/dist/chunk-zj48897e.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{p as gH,q as kH,r as CH,s as hH,t as OH,u as wH}from"./chunk-b9d0ex8n.js";import{B as RH,C as ZH,D as $H,E as qH,F as a,G as XH}from"./chunk-17d4m89n.js";import{H as NH,da as MH,fa as zH,ga as fH,ka as AH}from"./chunk-bwe49m6n.js";import"./chunk-g01mth5d.js";import"./chunk-tnmcrvk2.js";import{ab as QH}from"./chunk-kf9gj2gn.js";import{Nb as e,Zb as FH,ic as EH}from"./chunk-pb1q26gw.js";import"./chunk-fdr4fcrf.js";import{Td as GH,Xd as PH,Zd as d,ie as t}from"./chunk-4fa11h6f.js";import"./chunk-egss0m1x.js";import"./chunk-xv6ejk2z.js";import"./chunk-efjjkha8.js";import{sf as TH}from"./chunk-9jz1q7bk.js";import{uf as yH,vf as bH,wf as IH}from"./chunk-rtwd35gd.js";import{xf as SH}from"./chunk-8pd1hp4r.js";import"./chunk-p0wyhp5a.js";import{Xf as _H}from"./chunk-18swytk4.js";import"./chunk-5yyp6njq.js";import"./chunk-v508x7cg.js";import"./chunk-57939tb3.js";import"./chunk-ynd1v33f.js";import"./chunk-w42j9p3t.js";import"./chunk-zfxcef0z.js";import"./chunk-xyypxrad.js";import"./chunk-jgxfhk9k.js";import"./chunk-kehgewqh.js";import{ih as c,mh as BH}from"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-c51wwnh2.js";import"./chunk-ys8gysg8.js";import{Fh as xH}from"./chunk-thytjs86.js";import{Zi as r,_i as n}from"./chunk-tm3789m3.js";import{cj as C}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import{Gj as UH,Ij as H,Jj as YH,Lj as Y}from"./chunk-a8z11yd2.js";import"./chunk-qtwgm95z.js";import"./chunk-0eajnhrj.js";import"./chunk-6169xxb4.js";import"./chunk-f8kjdxz7.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import uJ from"yargs";import{hideBin as dJ}from"yargs/helpers";function i(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function aH(V,Z){if(!V.once&&!V.on||!V.off&&!V.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,K=()=>{i(V,"drain",x),i(V,"error",j),Z.removeEventListener("abort",P)},D=(F)=>{if(J)return;J=!0,K(),F()},x=()=>D(Q),j=(F)=>D(()=>q(F??Error("Writable emitted an error"))),P=()=>D(()=>q(Z.reason??Error("Writable drain aborted")));if(Z.aborted){P();return}let T=V.once?.bind(V)??V.on?.bind(V);T?.("drain",x),T?.("error",j),Z.addEventListener("abort",P,{once:!0})})}async function iH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await aH(V,Q)}class o{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new a("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new XH({maxPendingItems:Z.maxPendingItems??ZH,maxPendingBytes:Z.maxPendingBytes??$H,writeTimeoutMs:Z.writeTimeoutMs??qH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>iH(V[q],J,K),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(V.stdout),V.stderr!==V.stdout)this.observeSinkErrors(V.stderr);if(Z.signal?.addEventListener("abort",this.handleAbort,{once:!0}),Z.signal?.aborted)this.handleAbort()}write(V,Z){return this.queues[V].offer(Z).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(V){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(V){if(!V.on||!V.off&&!V.removeListener)return;let Z=(Q)=>{this.fail(new a("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};V.on("error",Z),this.sinkErrorListeners.push({writer:V,listener:Z})}fail(V){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V),this.options.onFailure?.(V)}removeSinkErrorListeners(){for(let{writer:V,listener:Z}of this.sinkErrorListeners.splice(0))i(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var oH=L({type:H.Literal("content_delta"),delta:H.String()}),sH=L({type:H.Literal("thinking_delta"),delta:H.String()}),rH=L({type:H.Literal("thinking"),content:H.String()}),nH=L({type:H.Literal("stream_end")}),tH=L({type:H.Literal("content"),content:H.String()}),eH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),s=Y(["readonly","write","execute"]),HJ=H.Object({kind:s,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),JJ=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s)}),KJ=L({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(HJ)}),VJ=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:Y(["local","acp"])}),ZJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(VJ)}),$J=L({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())}),qJ=L({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:Y(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),XJ=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),YJ=L({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:Y(["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())}),BJ=L({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:Y(["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())}),NJ=L({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:Y(["added","removed"]),reason:Y(["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=L({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:Y(["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())}),DJ=L({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:Y(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),LJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),WJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),jJ=L({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:Y(["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()}),xJ=L({type:H.Literal("phase"),phase:Y(["turn","searching","inspecting","target_hit","executing","completed"]),status:Y(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),UJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),_J=L({type:H.Literal("task_update"),tasks:H.Array(NH)}),GJ=L({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:Y(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),PJ=L({type:H.Literal("goal"),state:Y(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(Y(["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(Y(BH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),execution_host_failure_category:H.Optional(Y(["timeout","admission","spawn","finalization","sandbox_start","terminal"])),execution_host_failure_count:H.Optional(H.Integer({minimum:1,maximum:3})),frontier_stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3})),root_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),current_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),parent_turn_id:H.Optional(H.String({minLength:1,maxLength:c}))}),FJ=L({type:H.Literal("subagent"),state:Y(["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(Y(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),EJ=L({type:H.Literal("token_usage"),scope:H.Optional(H.Literal("auxiliary")),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:Y(["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())}),MJ=L({type:H.Literal("compacting"),state:Y(["started","completed"]),reason:H.Optional(Y(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(Y(["llm","fallback","snip"])),outcome:H.Optional(Y(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(Y(["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(Y(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"])),memory:H.Optional(QH)}),zJ=L({type:H.Literal("provider_retry"),phase:Y(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:Y(["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(Y(["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(Y(["attempt_limit","recovery_budget"]))}),fJ=L({type:H.Literal("provider_admission"),phase:Y(["queued","admitted","rejected"]),request_class:Y(["foreground","background","internal"]),resource:Y(["stream","pending_count","pending_bytes"]),scope:Y(["global","domain","owner","class"]),reason:H.Optional(Y(["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}))}),AJ=L({type:H.Literal("provider_circuit"),phase:Y(["opened","waiting","probe","closed","reopened","rejected"]),reason:Y(["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}))}),SJ=L({type:H.Literal("provider_stall"),phase:Y(["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()}),u=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),DH=H.Union([H.Object({source:Y(["retry","circuit"]),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),H.Object({source:H.Literal("admission"),reason:Y(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),H.Object({source:H.Literal("stall"),reason:H.Literal("timeout")},{additionalProperties:!1})]),TJ=H.Object({activity:Y(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),reason:Y(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),updated_at:H.Integer({minimum:0}),next_action_at:H.Optional(H.Integer({minimum:0})),retry:H.Optional(H.Object({attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),delay_ms:H.Optional(H.Integer({minimum:0})),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}))},{additionalProperties:!1})),admission:H.Optional(H.Object({request_class:Y(["foreground","background","internal"]),scope:Y(["global","domain","owner","class"]),resource:Y(["stream","pending_count","pending_bytes"]),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}))},{additionalProperties:!1})),circuit:H.Optional(H.Object({phase:Y(["opened","reopened","waiting","probe","rejected"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),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}))},{additionalProperties:!1})),stall:H.Optional(H.Object({stall_count:H.Integer({minimum:0}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:0}),timeout_ms:H.Integer({minimum:0}),output_started:H.Boolean()},{additionalProperties:!1})),fallback:H.Optional(H.Object({from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}))},{additionalProperties:!1}),yJ=H.Object({event_version:H.Literal(k),type:H.Literal("provider_recovery"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([TJ,H.Null()])},{additionalProperties:!1}),bJ=H.Object({name:H.String({minLength:1,maxLength:128}),kind:H.Optional(Y(["readonly","write","execute"])),started_at:H.Integer({minimum:0}),progress:H.Optional(H.Integer({minimum:0})),total:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1}),IJ=H.Object({phase:Y(["starting","thinking","responding","executing_tools","compacting","continuing"]),started_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),turn:H.Integer({minimum:0}),max_turns:H.Union([H.Integer({minimum:0}),H.Null()]),output_started:H.Boolean(),tool_calls_started:H.Integer({minimum:0}),tool_calls_completed:H.Integer({minimum:0}),active_tools:H.Array(bJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),RJ=H.Object({event_version:H.Literal(k),type:H.Literal("turn_activity"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([IJ,H.Null()])},{additionalProperties:!1}),gJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}),kJ=L({type:H.Literal("action_stationarity"),phase:Y(["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()}),CJ=L({type:H.Literal("turn_recovery"),state:Y(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(Y(["successful_tool_result","interrupted_tool_call"]))}),hJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),OJ=L({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:Y(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),wJ=L({type:H.Literal("task_admission"),state:Y(["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})}),mJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),cJ=L({type:H.Literal("error"),message:H.String()}),NK=YH(H.Union([oH,sH,rH,nH,tH,eH,JJ,KJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,EJ,MJ,fJ,AJ,zJ,SJ,yJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ,mJ,cJ]));function LH(V,Z){return{event_version:k,type:V,...Z}}function pJ(V){if(!V||typeof V!=="object"||Array.isArray(V))return;let Z=V;if(Z.auto_backgrounded!==!0||Z.background_reason!=="foreground_budget"||!Number.isSafeInteger(Z.foreground_budget_ms)||Z.foreground_budget_ms<=0||typeof Z.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(Z.shell_id)||Z.shell_id.length>128||Z.terminal_transport!=="local"&&Z.terminal_transport!=="acp"||Z.pid!==void 0&&(!Number.isSafeInteger(Z.pid)||Z.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:Z.foreground_budget_ms,shell_id:Z.shell_id,...Z.pid===void 0?{}:{pid:Z.pid},terminal_transport:Z.terminal_transport}}function vJ(V){let Z=new AbortController,Q=(K)=>{if(!Z.signal.aborted)Z.abort(K)},q=()=>Q("interrupt"),J=()=>Q(V?.signal?.reason);if(V?.signal){if(V.signal.addEventListener("abort",J,{once:!0}),V.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:Z.signal,abort:Q,dispose:()=>{V?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var lJ=Y(["text","jsonl"]),aJ=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(),(V)=>V===-1||V>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(xH)),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(Y(["local","worktree"])),outputFormat:H.Optional(lJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class mH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(V){this.openedThinking=V}hasOpenThinking(){return this.openedThinking}completeStream(){let V={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,V}}function iJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function oJ(V){let Z=UH(aJ,V);if(!Z.success)throw Error(`Invalid headless options: ${iJ(Z.error)}`);return Z.data}function sJ(V){return V.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.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(Z)=>{if(!Z.headless)return;let Q=await JK(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
|
|
2
|
-
`)}function rJ(V){return`[task] [${V.status}] ${V.subject}`}function nJ(){return{requestConfirmation:async(V)=>V.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:V.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function tJ(V){if(!(V instanceof Error))return"Unknown error";let q=V.lastError??V;if(q.responseBody)try{let D=JSON.parse(q.responseBody)?.error?.message;if(D)return q.statusCode?`${D} (HTTP ${q.statusCode})`:D}catch{}let J=V.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return V.message}function eJ(V){return V==="jsonl"?"jsonl":"text"}function WH(V,Z){let Q=(...q)=>{for(let J of q){let K=Z[J];if(typeof K==="string"&&K.trim()!=="")return K}return};switch(V){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 HK(V,Z,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),K=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(V)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(J.has(V))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if(K.has(V))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function jH(V,Z,Q=!1){let q=(J,K)=>{V.stdout.write(`${JSON.stringify(LH(J,K))}
|
|
3
|
-
`)};return{contentDelta(J){if(Z==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;V.stdout.write(J)},thinkingDelta(J,K){if(Z==="jsonl")return q("thinking_delta",{delta:J}),K;if(!K)V.stderr.write("[thinking] ");return V.stderr.write(J),!0},thinking(J){if(Z==="jsonl"){q("thinking",{content:J});return}W(V.stderr,`[thinking] ${J}`)},streamEnd(J,K){if(Z==="jsonl"){q("stream_end",{});return}if(K)V.stderr.write(`
|
|
4
|
-
`);if(J)V.stdout.write(`
|
|
5
|
-
`)},content(J){if(Z==="jsonl"){q("content",{content:J});return}W(V.stdout,J)},structuredOutput(J){if(Z==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}W(V.stdout,JSON.stringify(J.output))},toolStart(J,K,D,x){if(Z==="jsonl"){q("tool_start",{tool_name:J,summary:K,target:D,tool_kind:x});return}W(V.stderr,`[tool:start] ${K}`)},toolProgress(J,K,D,x,j){if(Z==="jsonl"){q("tool_progress",{tool_name:J,message:K,progress:D,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}W(V.stderr,`[tool:progress] ${J}: ${K}`)},toolResult(J,K,D,x,j){if(Z==="jsonl"){q("tool_result",{tool_name:J,summary:K,target:D,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}W(V.stderr,`[tool:result] ${K}`)},mcpCatalogChanged(J){if(Z==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}W(V.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(Z==="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}W(V.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(Z==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}W(V.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(Z==="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}W(V.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(Z==="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}W(V.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(Z==="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}W(V.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(Z==="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}W(V.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(Z==="jsonl"){q("project_rules_loaded",{files:J.files.map((K)=>({id:K.id,relative_path:K.relativePath,source:K.source,conditional:K.conditional,content_sha256:K.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}W(V.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,K,D){if(Z==="jsonl"){q("user_shell_started",{execution_id:J,command:K,auxiliary:D});return}W(V.stderr,`[user-shell:start] ${K}`)},userShellOutput(J,K,D,x){if(Z==="jsonl"){q("user_shell_output",{execution_id:J,stream:K,chunk:D,stream_truncated:x});return}(K==="stderr"?V.stderr:V.stdout).write(D)},userShellCompleted(J){if(Z==="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}W(V.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,K,D,x={}){if(Z==="jsonl"){q("phase",{phase:J,status:K,message:D,turn:x.turn,tool_name:x.toolName,target:x.target});return}W(V.stderr,`[phase:${J}] ${D}`)},toolDetail(J,K){if(Z==="jsonl"){q("tool_detail",{tool_name:J,detail:K});return}W(V.stderr,K)},taskUpdate(J){if(Z==="jsonl"){q("task_update",{tasks:J});return}for(let K of J)W(V.stderr,rJ(K))},goalFrontier(J){if(Z==="jsonl"){q("goal_frontier",{goal_id:J.goal.goalId,status:J.goal.status,task_list_id:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,in_progress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,next_task:J.frontier.nextTask,digest_sha256:J.frontier.digestSha256,observed_at:J.frontier.observedAt,stall_category:J.goal.frontierStall?.category,stall_count:J.goal.frontierStall?.consecutiveCount});return}let K=J.frontier.nextTask?` next=#${J.frontier.nextTask.id} ${J.frontier.nextTask.subject}`:"";W(V.stderr,`[goal-frontier] ${J.frontier.completed}/${J.frontier.total} completed${K}`)},turnRecovery(J){let K=J.assessment;if(Z==="jsonl"){q("turn_recovery",{state:K.state,turn_id:K.turnId,input_message_count:K.inputMessageCount,reason:K.state==="requires_attention"?K.reason:void 0});return}W(V.stderr,`[turn-recovery:${K.state}] ${K.turnId}`)},goal(J){if(Z==="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,execution_host_failure_category:J.goal?.executionHostFailure?.category,execution_host_failure_count:J.goal?.executionHostFailure?.consecutiveCount,frontier_stall_category:J.goal?.frontierStall?.category,frontier_stall_count:J.goal?.frontierStall?.consecutiveCount,root_turn_id:J.goal?.turnLineage?.rootTurnId,current_turn_id:J.goal?.turnLineage?.currentTurnId,parent_turn_id:J.goal?.turnLineage?.parentTurnId});return}if(J.goal)W(V.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else W(V.stderr,"[goal:cleared]")},subagent(J){let K=J.kind==="subagent_spawned";if(Z==="jsonl"){q("subagent",{state:K?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:K?void 0:J.success,summary:K?void 0:J.summary,verification_verdict:K?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}W(V.stderr,`[subagent:${K?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(Z==="jsonl"){q("token_usage",{...J.scope?{scope:J.scope}:{},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}W(V.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let K=J.phase==="start";if(Z==="jsonl"){q("compacting",{state:K?"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,memory:J.memory});return}W(V.stderr,K?`[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`:""}${J.memory?.outcome==="written"?`; saved ${J.memory.entries} project memories`:""}`)},providerAdmission(J){if(Z==="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}W(V.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(Z==="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 K=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";W(V.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${K}`)},providerCircuit(J){if(Z==="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 K=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";W(V.stderr,`[provider-circuit:${J.phase}] ${J.reason}${K}`)},providerStall(J){if(Z==="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}W(V.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},providerRecovery(J){let K=J.recovery.snapshot;if(Z==="jsonl"){q("provider_recovery",{generation:J.recovery.generation,revision:J.recovery.revision,snapshot:K?{activity:K.activity,reason:K.reason,updated_at:K.updatedAt,next_action_at:K.nextActionAt,retry:K.retry?{attempt:K.retry.attempt,max_retries:K.retry.maxRetries,status_code:K.retry.statusCode,delay_ms:K.retry.delayMs,recovery_budget_ms:K.retry.recoveryBudgetMs,recovery_elapsed_ms:K.retry.recoveryElapsedMs,recovery_remaining_ms:K.retry.recoveryRemainingMs}:void 0,admission:K.admission?{request_class:K.admission.requestClass,scope:K.admission.scope,resource:K.admission.resource,queue_position:K.admission.queuePosition,queue_depth:K.admission.queueDepth,in_flight:K.admission.inFlight,limit:K.admission.limit,wait_ms:K.admission.waitMs,max_wait_ms:K.admission.maxWaitMs,recovery_remaining_ms:K.admission.recoveryRemainingMs}:void 0,circuit:K.circuit?{phase:K.circuit.phase,status_code:K.circuit.statusCode,retry_after_ms:K.circuit.retryAfterMs,next_probe_at:K.circuit.nextProbeAt,open_duration_ms:K.circuit.openDurationMs,sample_count:K.circuit.sampleCount,failure_count:K.circuit.failureCount,recovery_remaining_ms:K.circuit.recoveryRemainingMs}:void 0,stall:K.stall?{stall_count:K.stall.stallCount,duration_ms:K.stall.durationMs,warning_after_ms:K.stall.warningAfterMs,timeout_ms:K.stall.timeoutMs,output_started:K.stall.outputStarted}:void 0,fallback:K.fallback?{from:K.fallback.from,to:K.fallback.to,candidate:K.fallback.candidate,candidate_count:K.fallback.candidateCount,trigger:K.fallback.trigger.source==="retry"||K.fallback.trigger.source==="circuit"?{source:K.fallback.trigger.source,reason:K.fallback.trigger.reason,status_code:K.fallback.trigger.statusCode}:K.fallback.trigger}:void 0}:null});return}W(V.stderr,K?`[provider-recovery:${K.activity}] ${K.reason}`:"[provider-recovery:clear]")},turnActivity(J){if(Z!=="jsonl")return;let K=J.activity.snapshot;q("turn_activity",{generation:J.activity.generation,revision:J.activity.revision,snapshot:K?{phase:K.phase,started_at:K.startedAt,updated_at:K.updatedAt,turn:K.turn,max_turns:K.maxTurns,output_started:K.outputStarted,tool_calls_started:K.toolCallsStarted,tool_calls_completed:K.toolCallsCompleted,active_tools:K.activeTools.map((D)=>({name:D.name,kind:D.kind,started_at:D.startedAt,progress:D.progress,total:D.total})),active_tool_overflow:K.activeToolOverflow}:null})},modelFallback(J){let K=J.trigger.source==="retry"||J.trigger.source==="circuit"?{source:J.trigger.source,reason:J.trigger.reason,status_code:J.trigger.statusCode}:J.trigger;if(Z==="jsonl"){q("model_fallback",{from:J.from,to:J.to,candidate:J.candidate,candidate_count:J.candidateCount,trigger:K});return}W(V.stderr,`[provider-fallback] ${J.from.model} -> ${J.to.model}`)},actionStationarity(J){if(Z==="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}W(V.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(Z==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}W(V.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(Z==="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}W(V.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(Z==="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}W(V.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,K=0){if(Z==="jsonl"){q("output",{content:J,exit_code:K});return}W(K===0?V.stdout:V.stderr,J)},error(J){if(Z==="jsonl"){q("error",{message:J});return}W(V.stderr,J)}}}async function JK(V,Z={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new mH,K={targetLocked:!1},D,x,j,P=vJ(Q),T=!1,F=new o(Z,{signal:P.signal,onFailure:(N)=>{T=!0,P.abort(N)}}),p={stdout:{write:(N)=>F.write("stdout",N)},stderr:{write:(N)=>F.write("stderr",N)}},B=jH(p,q),v=async()=>{try{return await F.flush(),!T}catch{return!1}},E=async(N)=>{return x?.(),x=void 0,j?.(),j=void 0,await v()?N:1};try{let N=oJ(V);q=eJ(N.outputFormat);let y=await OH(N);B=jH(p,q,Boolean(y)),await gH();let HH=N.forkSession!==!0&&(N.continue===!0||typeof N.resume==="string"&&N.resume.length>0)?await CH({message:N.message,_:N._,stdin:Q?.stdin}):await kH({...N,stdin:Q?.stdin}),M=HH===void 0,_=M?{mode:"agent",content:""}:await hH(HH);if(_.mode==="output"){if(_.content)B.output(_.content,_.exitCode??0);return await E(_.exitCode??0)}if(!M&&_.content.length>r)throw Error(`User prompt exceeds the ${r}-character durable input limit`);if(!M&&Buffer.byteLength(_.content,"utf8")>n)throw Error(`User prompt exceeds the ${n}-byte durable input limit`);let h=_.content.trimStart().startsWith("!")?_.content.trimStart().slice(1).trim():void 0;if(h!==void 0&&N.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(h!==void 0&&y)throw Error("Output schemas cannot be combined with user shell commands");if(N.taskIsolation&&(N.continue||N.resume||N.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:G,messages:JH,metadata:KH}=await wH({sessionId:N.sessionId,continue:N.continue,resume:N.resume,forkSession:N.forkSession,fallbackSessionPrefix:"headless"}),R=N.permissionMode??KH?.permissionMode??"yolo",VH=N.model&&N.model!=="inherit"?N.model:_H()?.id,U=N.taskIsolation?await RH.createSessionTask({sessionId:G,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,dispatch:{version:1,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,permissionMode:R,...VH?{modelId:VH}:{},...y?{outputSchema:y}:{}}}):void 0,z=U?.metadata.projectPath??KH?.projectPath??C();if(j=e.subscribe(($)=>{if($.type!=="subagent.provider.admission"||$.sessionId!==G||$.projectPath!==z)return;let X=$.properties,f=["queued","admitted","rejected"],A=["foreground","background","internal"],S=["stream","pending_count","pending_bytes"],I=["global","domain","owner","class"],lH=["capacity","queue_full","wait_timeout","closed"];if(!f.includes(X.phase)||!A.includes(X.requestClass)||!S.includes(X.resource)||!I.includes(X.scope)||X.reason!==void 0&&!lH.includes(X.reason)||typeof X.queuePosition!=="number"||typeof X.queueDepth!=="number"||typeof X.inFlight!=="number"||typeof X.limit!=="number"||typeof X.waitMs!=="number"||typeof X.maxWaitMs!=="number"||X.recoveryRemainingMs!==void 0&&typeof X.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:X.phase,requestClass:X.requestClass,resource:X.resource,scope:X.scope,...X.reason!==void 0?{reason:X.reason}:{},queuePosition:X.queuePosition,queueDepth:X.queueDepth,inFlight:X.inFlight,limit:X.limit,waitMs:X.waitMs,maxWaitMs:X.maxWaitMs,...X.recoveryRemainingMs!==void 0?{recoveryRemainingMs:X.recoveryRemainingMs}:{}})}),!U)await t.setSessionPermissionMode(G,z,R);let cH=U?!1:await EH.cancelPendingNonInteractive(z,G);if(U)B.taskSession({sessionId:G,projectPath:z,sourceProjectPath:U.metadata.taskSourceProjectPath??C(),isolation:N.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=e.subscribe(($)=>{if($.type!=="task.status"||$.sessionId!==G||$.projectPath!==z||!["queued","running"].includes(String($.properties.taskStatus))||typeof $.properties.taskQueueDepth!=="number"||typeof $.properties.taskInFlight!=="number"||typeof $.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:$.properties.taskStatus,queuePosition:typeof $.properties.taskQueuePosition==="number"?$.properties.taskQueuePosition:void 0,queueDepth:$.properties.taskQueueDepth,inFlight:$.properties.taskInFlight,maxConcurrentTasks:$.properties.taskConcurrencyLimit})});let uH={messages:cH?await t.loadSessionModelContext(G,z):[...JH],userId:"cli-user",sessionId:G,workspaceRoot:z,permissionMode:R,signal:P.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:nJ()};D=await MH.create({sessionId:G,workspaceRoot:z,modelId:N.model,permissionMode:R,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig,agents:N.agents?SH(N.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...JH.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}});let g=M&&D.getPendingSteeringCount()>0,O=M&&!g?await D.getGoal():null,w=O?.status==="active"||O?.status==="verifying",l=D.getTurnRecoveryAssessment?.()??{state:"none"};if(M&&!g&&!w&&l.state==="requires_attention")return B.turnRecovery({kind:"turn_recovery",assessment:l}),B.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);let b=M&&!g&&!w?await D.getRecoveredFinalResponse():void 0;if(M&&!g&&!w){if(!b)throw Error("No unfinished turn or active goal to resume");let $=l;if($.state!=="none")B.turnRecovery({kind:"turn_recovery",assessment:$});if(O)B.goal({kind:"goal_updated",goal:O});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 E(0)}if(h!==void 0){let $=await D.executeUserShellCommand(h,{signal:P.signal,onEvent:async(X)=>{if(X.type==="started")B.userShellStarted(X.executionId,X.command,X.auxiliary);else if(X.type==="output")B.userShellOutput(X.executionId,X.stream,X.chunk,X.streamTruncated);await v()}});return B.userShellCompleted($),await E($.record.status==="completed"?0:$.record.status==="aborted"?130:$.record.exitCode??1)}let dH=N.maxTurns??D.getConfig().maxTurns,pH=U?.taskWorktree?[...new Set([...N.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:N.disallowedTools,vH=await AH.createWithRuntime(D,{sessionId:G,systemPrompt:N.systemPrompt,appendSystemPrompt:N.appendSystemPrompt,maxTurns:N.maxTurns,modelId:N.model,permissionMode:R,toolWhitelist:N.allowedTools,toolBlacklist:pH,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig}),m=await FH(vH.chatStream(_.content,uH,{stream:!0,signal:P.signal,maxTurns:N.maxTurns,builtinVerification:N.verificationAgent!==!1,outputSchema:y,pendingInputOnly:g,goalContinuationOnly:w,...dH===-1?{onTurnLimitReached:async($)=>{return B.turnLimit($.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async($)=>{switch($.kind){case"content_delta":if(!y||q==="jsonl")J.markAssistantContent();B.contentDelta($.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta($.delta,J.hasOpenThinking()));break;case"stream_end":{let X=J.completeStream();B.streamEnd(X.wroteAssistantContent,X.openedThinking);break}case"tool_start":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===d)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),A=zH(X.function.name,f),S=WH(X.function.name,f),I=HK(X.function.name,A,S,K);if(I.shouldLockTarget)K.targetLocked=!0;B.phase(I.phase,I.status,I.message,{toolName:X.function.name,target:S}),B.toolStart(X.function.name,A,S,$.toolKind)}catch{B.phase(K.targetLocked?"executing":"searching",K.targetLocked?"hit":"ongoing",K.targetLocked?`Working within target: ${X.function.name}`:`Still searching: ${X.function.name}`,{toolName:X.function.name}),B.toolStart(X.function.name,X.function.name,void 0,$.toolKind)}break}case"tool_progress":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===d)break;B.toolProgress(X.function.name,$.update.message,$.update.progress,$.update.total,$.update.admission);break}case"tool_result":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===d)break;let f;try{let S=JSON.parse(X.function.arguments);f=WH(X.function.name,S)}catch{f=void 0}let A=PH(fH(X.function.name,$.result),GH);if(B.toolResult(X.function.name,A.summary,f,void 0,{success:$.result.success,errorType:$.result.error?.type,errorMessage:$.result.error?.message,background:pJ($.result.metadata)}),A.detail)B.toolDetail(X.function.name,A.detail);break}case"token_usage":B.tokenUsage($.usage);break;case"compaction":B.compacting($);break;case"task_update":B.taskUpdate($.tasks);break;case"goal_frontier_updated":B.goalFrontier($);break;case"turn_recovery":B.turnRecovery($);break;case"structured_output":B.structuredOutput($);break;case"mcp_catalog_changed":B.mcpCatalogChanged($);break;case"mcp_content_changed":B.mcpContentChanged($);break;case"mcp_resource_updated":B.mcpResourceUpdated($);break;case"mcp_connection_changed":B.mcpConnectionChanged($);break;case"mcp_log":B.mcpLog($);break;case"mcp_instructions_changed":B.mcpInstructionsChanged($);break;case"mcp_task_changed":B.mcpTaskChanged($);break;case"project_rules_loaded":B.projectRulesLoaded($);break;case"steering_applied":case"follow_up_started":case"follow_up_queue_changed":case"goal_continuation_started":break;case"goal_updated":B.goal($);break;case"subagent_spawned":case"subagent_completed":B.subagent($);break;case"model_fallback":B.modelFallback($);break;case"provider_admission":B.providerAdmission($);break;case"provider_retry":B.providerRetry($);break;case"provider_circuit":B.providerCircuit($);break;case"provider_stall":B.providerStall($);break;case"provider_recovery":B.providerRecovery($);break;case"turn_activity":B.turnActivity($);break;case"action_stationarity":B.actionStationarity($);break;case"turn_start":if($.turn===1)K.targetLocked=!1;B.phase("turn",K.targetLocked?"hit":"ongoing",`Turn ${$.turn} started`,{turn:$.turn});break;default:{let X=$}}await v()});if(m.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(m.metadata?.recoveryAttention)return B.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);if(!m.success)return B.error(`Error: ${m.error?.message??"Agent execution failed"}`),await E(1);return B.phase("completed","done","Headless run completed"),await E(0)}catch(N){if(!T){if(J.hasOpenThinking()&&q==="text")p.stderr.write(`
|
|
6
|
-
`);B.error(`Error: ${tJ(N)}`)}return await E(1)}finally{x?.(),j?.();try{await D?.dispose()}finally{F.close(),P.dispose()}}}async function OK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":K,"max-turns":D,...x}=TH,j=uJ(dJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([bH,yH,IH]);return sJ(j),await j.parse(),!0}export{JK as runHeadless,OK as handleHeadlessMode,aJ as HeadlessOptionsSchema};
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-B5mUEr6D.js","assets/vendor-react-DofNRwfy.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{c as be,j as _,a2 as Ke,w as at,L as Be,V as q,aj as gr,ak as kr,S as wr,t as Vt,R as Kt,B as yr,a as z,O as Jt,d as jr,al as Nr,J as Sr,u as je,$ as mt,o as Qt,F as Xt,am as Cr,s as Je,an as dt,l as Er,X as Tr,E as Rr,_ as Lr}from"./index-BVDkKudh.js";import{r as i,j as e}from"./vendor-react-DofNRwfy.js";import{x as Pr,a9 as Ct,N as Qe,$ as Z,a0 as Et}from"./session-events-NEjosinC.js";import{M as Ir,a as Dr,A as Fr,C as $r}from"./message-square-plus-3klTXO0S.js";import{A as Ar,E as Tt}from"./external-link-zIgEO0KB.js";import{A as Mr}from"./arrow-left-9pBiQwu7.js";import{A as _r,F as Wr}from"./folder-BdRo64o3.js";import{C as Yt}from"./chevron-right-yCVkAEcj.js";import"./vendor-radix-D6QrtXqd.js";/**
|
|
3
|
-
* @license lucide-react v0.300.0 - ISC
|
|
4
|
-
*
|
|
5
|
-
* This source code is licensed under the ISC license.
|
|
6
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
7
|
-
*/const zr=be("AppWindow",[["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}],["path",{d:"M10 4v4",key:"pp8u80"}],["path",{d:"M2 8h20",key:"d11cs7"}],["path",{d:"M6 4v4",key:"1svtjw"}]]);/**
|
|
8
|
-
* @license lucide-react v0.300.0 - ISC
|
|
9
|
-
*
|
|
10
|
-
* This source code is licensed under the ISC license.
|
|
11
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
12
|
-
*/const Ur=be("ChevronsDownUp",[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]]);/**
|
|
13
|
-
* @license lucide-react v0.300.0 - ISC
|
|
14
|
-
*
|
|
15
|
-
* This source code is licensed under the ISC license.
|
|
16
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/const st=be("FileCode",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["path",{d:"m10 13-2 2 2 2",key:"17smn8"}],["path",{d:"m14 17 2-2-2-2",key:"14mezr"}]]);/**
|
|
18
|
-
* @license lucide-react v0.300.0 - ISC
|
|
19
|
-
*
|
|
20
|
-
* This source code is licensed under the ISC license.
|
|
21
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
22
|
-
*/const Br=be("FlaskConical",[["path",{d:"M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2",key:"pzvekw"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M7 16h10",key:"wp8him"}]]);/**
|
|
23
|
-
* @license lucide-react v0.300.0 - ISC
|
|
24
|
-
*
|
|
25
|
-
* This source code is licensed under the ISC license.
|
|
26
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
27
|
-
*/const Rt=be("MonitorUp",[["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}],["path",{d:"M12 13V7",key:"h0r20n"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/**
|
|
28
|
-
* @license lucide-react v0.300.0 - ISC
|
|
29
|
-
*
|
|
30
|
-
* This source code is licensed under the ISC license.
|
|
31
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
32
|
-
*/const Lt=be("MousePointer2",[["path",{d:"m4 4 7.07 17 2.51-7.39L21 11.07z",key:"1vqm48"}]]);/**
|
|
33
|
-
* @license lucide-react v0.300.0 - ISC
|
|
34
|
-
*
|
|
35
|
-
* This source code is licensed under the ISC license.
|
|
36
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
-
*/const Or=be("TerminalSquare",[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]]);/**
|
|
38
|
-
* @license lucide-react v0.300.0 - ISC
|
|
39
|
-
*
|
|
40
|
-
* This source code is licensed under the ISC license.
|
|
41
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
42
|
-
*/const qr=be("UserRound",[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]]);/**
|
|
43
|
-
* @license lucide-react v0.300.0 - ISC
|
|
44
|
-
*
|
|
45
|
-
* This source code is licensed under the ISC license.
|
|
46
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
47
|
-
*/const Hr=be("Wifi",[["path",{d:"M5 13a10 10 0 0 1 14 0",key:"6v8j51"}],["path",{d:"M8.5 16.5a5 5 0 0 1 7 0",key:"sej527"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["line",{x1:"12",x2:"12.01",y1:"20",y2:"20",key:"of4bc4"}]]),Zt=i.createContext(null);function er(t){const n=i.useContext(Zt);if(!n)throw new Error(`${t} must be used within <Tabs>`);return n}function Gr({value:t,onValueChange:n,className:r,children:s}){const a=i.useMemo(()=>({value:t,setValue:n}),[t,n]);return e.jsx(Zt.Provider,{value:a,children:e.jsx("div",{className:r,children:s})})}function Vr({className:t,children:n}){return e.jsx("div",{role:"tablist",className:_("inline-flex items-center",t),children:n})}function et({value:t,className:n,children:r}){const{value:s,setValue:a}=er("TabsTrigger"),l=s===t;return e.jsx("button",{type:"button",role:"tab","aria-selected":l,"data-state":l?"active":"inactive",onClick:()=>a(t),className:_("inline-flex items-center justify-center whitespace-nowrap rounded-sm transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--deck-accent))]",n),children:r})}function tt({value:t,className:n,children:r,forceMount:s=!1}){const{value:a}=er("TabsContent"),l=a===t;return!l&&!s?null:e.jsx("div",{role:"tabpanel",hidden:!l,className:n,children:r})}const Kr={"ayu-dark":{background:{primary:"#0f1419",secondary:"#14191f"},text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773"},border:{light:"#2d323b"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},dracula:{background:{primary:"#282a36",secondary:"#44475a"},text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4"},border:{light:"#44475a"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},monokai:{background:{primary:"#272822",secondary:"#3e3d32"},text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e"},border:{light:"#3e3d32"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},nord:{background:{primary:"#2e3440",secondary:"#3b4252"},text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a"},border:{light:"#434c5e"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},"solarized-light":{background:{primary:"#fdf6e3",secondary:"#eee8d5"},text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1"},border:{light:"#eee8d5"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},"solarized-dark":{background:{primary:"#002b36",secondary:"#073642"},text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75"},border:{light:"#073642"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},"tokyo-night":{background:{primary:"#1a1b26",secondary:"#292e42"},text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89"},border:{light:"#292e42"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},github:{background:{primary:"#ffffff",secondary:"#f6f8fa"},text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781"},border:{light:"#d0d7de"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},gruvbox:{background:{primary:"#282828",secondary:"#3c3836"},text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374"},border:{light:"#3c3836"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#b8bb26",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#fabd2f",default:"#ebdbb2"}},"one-dark":{background:{primary:"#282c34",secondary:"#21252b"},text:{primary:"#abb2bf",secondary:"#e5c07b",muted:"#5c6370"},border:{light:"#3e4451"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},catppuccin:{background:{primary:"#1e1e2e",secondary:"#313244"},text:{primary:"#cdd6f4",secondary:"#f5e0dc",muted:"#6c7086"},border:{light:"#313244"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#f5e0dc",operator:"#89dceb",type:"#f9e2af",tag:"#f38ba8",attr:"#f9e2af",default:"#cdd6f4"}},"rose-pine":{background:{primary:"#191724",secondary:"#1f1d2e"},text:{primary:"#e0def4",secondary:"#908caa",muted:"#6e6a86"},border:{light:"#26233a"},syntax:{comment:"#6e6a86",string:"#f6c177",number:"#ebbcba",keyword:"#c4a7e7",function:"#9ccfd8",variable:"#e0def4",operator:"#31748f",type:"#eb6f92",tag:"#eb6f92",attr:"#c4a7e7",default:"#e0def4"}},kanagawa:{background:{primary:"#1f1f28",secondary:"#2a2a37"},text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169"},border:{light:"#2a2a37"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#e46876",attr:"#ffa066",default:"#dcd7ba"}}};function Jr(t){const n=t.replace("#",""),r=parseInt(n.substring(0,2),16),s=parseInt(n.substring(2,4),16),a=parseInt(n.substring(4,6),16);return(.299*r+.587*s+.114*a)/255<.5}function Qr(t){return{base:Jr(t.background.primary)?"vs-dark":"vs",inherit:!0,rules:[{token:"",foreground:t.text.primary.replace("#",""),background:t.background.primary.replace("#","")},{token:"comment",foreground:t.syntax.comment.replace("#",""),fontStyle:"italic"},{token:"string",foreground:t.syntax.string.replace("#","")},{token:"number",foreground:t.syntax.number.replace("#","")},{token:"keyword",foreground:t.syntax.keyword.replace("#","")},{token:"type",foreground:t.syntax.type.replace("#","")},{token:"identifier",foreground:t.syntax.variable.replace("#","")},{token:"function",foreground:t.syntax.function.replace("#","")},{token:"variable",foreground:t.syntax.variable.replace("#","")},{token:"operator",foreground:t.syntax.operator.replace("#","")},{token:"delimiter",foreground:t.syntax.operator.replace("#","")},{token:"tag",foreground:t.syntax.tag.replace("#","")},{token:"attribute.name",foreground:t.syntax.attr.replace("#","")},{token:"attribute.value",foreground:t.syntax.string.replace("#","")}],colors:{"editor.background":t.background.primary,"editor.foreground":t.text.primary,"editor.lineHighlightBackground":t.background.secondary,"editor.selectionBackground":`${t.syntax.function}40`,"editorLineNumber.foreground":t.text.muted,"editorLineNumber.activeForeground":t.text.secondary,"editorCursor.foreground":t.text.primary,"editorIndentGuide.background":t.border.light,"editorWidget.background":t.background.secondary,"editorWidget.border":t.border.light,"scrollbarSlider.background":`${t.text.muted}40`,"scrollbarSlider.hoverBackground":`${t.text.muted}60`}}}const Pt=new Set;function It(t,n){const r=n.toLowerCase().replace(/\s+/g,"-"),s=Kr[r];if(!s)return"vs-dark";if(!Pt.has(r)){const a=Qr(s);t.editor.defineTheme(r,a),Pt.add(r)}return r}function We(t,n,r={}){const s=Pr.parse(t),a=new URLSearchParams({projectPath:s.projectPath});for(const[l,x]of Object.entries(r))x!==void 0&&a.set(l,String(x));return`/sessions/${encodeURIComponent(s.sessionId)}/browser/${n}?${a.toString()}`}const xe={navigate:async(t,n)=>Ke(We(t,"navigate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),snapshot:async(t,n={})=>Ke(We(t,"snapshot",n)),interact:async(t,n)=>Ke(We(t,"interact"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),inspect:async(t,n)=>Ke(We(t,"inspect",n)),screenshot:async(t,n={})=>{var s;const r=await fetch(We(t,"inspect",{...n,target:"screenshot"}));if(!r.ok){const a=await r.json().catch(()=>{});throw new Error(((s=a==null?void 0:a.error)==null?void 0:s.message)||"Failed to capture browser image")}return r.blob()},reset:async t=>{await Ke(We(t,"reset"),{method:"POST"})}},Xr={en:{frameTitle:"Project preview",empty:"No preview open",loading:"Loading preview…"},zh:{frameTitle:"项目预览",empty:"未打开项目预览",loading:"正在加载预览…"}};function Yr({url:t,revision:n,loadState:r,onLoad:s,onError:a}){const{locale:l}=at(),x=Xr[l];return e.jsx("section",{"data-preview-browser":!0,className:"relative h-full min-h-0 overflow-hidden bg-white",children:t?e.jsxs(e.Fragment,{children:[e.jsx("iframe",{"data-preview-browser-frame":!0,src:t,title:x.frameTitle,sandbox:"allow-downloads allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts",referrerPolicy:"no-referrer",onLoad:s,onError:a,className:"block h-full w-full border-0 bg-white"},`${t}:${n}`),r==="loading"&&e.jsxs("div",{className:"pointer-events-none absolute inset-x-0 top-0 flex h-8 items-center justify-center border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas)/0.92)] backdrop-blur-sm",children:[e.jsx(Be,{className:"mr-2 h-3.5 w-3.5 animate-spin text-[hsl(var(--deck-accent))]"}),e.jsx("span",{className:"font-mono text-[10.5px] text-[hsl(var(--deck-ink-muted))]",children:x.loading})]})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 bg-[hsl(var(--deck-canvas-veil))] text-center",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] text-[hsl(var(--deck-ink-faint))]",children:e.jsx(st,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:x.empty})]})})}const Zr={en:{unavailable:"No active Session",empty:"No Test page",screenshotAlt:"Chromium page",selectedRef:"Selected ref",noRef:"No ref selected",valuePlaceholder:"Input value",click:"Click selected element",fill:"Fill selected control",scrollUp:"Scroll up",scrollDown:"Scroll down",snapshot:"Refresh snapshot",reset:"Reset Test browser",dom:"DOM",console:"Console",network:"Network",errors:"Errors",noEntries:"No entries",user:"User",agent:"Agent",sourceAria:"Test browser source",selectElement:"Select element from page",stopSelecting:"Stop selecting elements",addToConversation:"Add to conversation"},zh:{unavailable:"没有活动 Session",empty:"未打开测试页面",screenshotAlt:"Chromium 页面",selectedRef:"已选 ref",noRef:"未选择 ref",valuePlaceholder:"输入内容",click:"点击已选元素",fill:"填入已选控件",scrollUp:"向上滚动",scrollDown:"向下滚动",snapshot:"刷新快照",reset:"重置测试浏览器",dom:"DOM",console:"控制台",network:"网络",errors:"错误",noEntries:"暂无记录",user:"用户",agent:"Agent",sourceAria:"测试浏览器来源",selectElement:"从页面选择元素",stopSelecting:"停止选择元素",addToConversation:"添加到对话"}};function es(t){return t.split(`
|
|
48
|
-
`).map(n=>{var a;const r=n.match(/\[box=(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)\]/),s=r==null?void 0:r.slice(1).map(Number);return{text:n,ref:(a=n.match(/\[ref=([a-z][a-z0-9]*)\]/))==null?void 0:a[1],...s&&s.length===4&&s.every(Number.isFinite)&&s[2]>0&&s[3]>0?{box:{x:s[0],y:s[1],width:s[2],height:s[3]}}:{}}})}function ut(t){return JSON.stringify(t.slice(0,2048)).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function ts(t,n){const r=t.text.replace(/\s+\[ref=[^\]]+\]/g,"").replace(/\s+\[box=[^\]]+\]/g,"").trim();return['<browser_element_context trust="untrusted">',`url: ${ut(n.url)}`,`title: ${ut(n.title)}`,`element: ${ut(r)}`,...n.viewport?[`viewport: [${n.viewport.width}, ${n.viewport.height}]`]:[],...t.box?[`viewport_box: [${t.box.x}, ${t.box.y}, ${t.box.width}, ${t.box.height}]`]:[],"</browser_element_context>"].join(`
|
|
49
|
-
`)}function rs(t){return[t.kind,t.level,t.method,t.status,t.url,t.text].filter(n=>n!==void 0&&n!=="").join(" · ")}function ss({source:t,agentAvailable:n,sessionAvailable:r,observation:s,screenshotUrl:a,interaction:l,pointerRevision:x,busy:c,error:w,diagnostics:u,diagnosticsLoading:y,onInteract:p,onInspect:g,onSnapshot:M,onReset:S,onSourceChange:k,pickerActive:d,onPickerChange:L,onAddToConversation:O}){var ae,ce,oe,de;const{locale:F}=at(),j=Zr[F],[D,E]=i.useState(null),[ee,Ie]=i.useState(""),[X,le]=i.useState("dom"),Ne=i.useRef(null),ve=i.useRef(null),[I,ge]=i.useState({left:0,top:0,width:0,height:0,sourceWidth:0,sourceHeight:0}),A=t==="agent",te=i.useMemo(()=>es((s==null?void 0:s.snapshot)??""),[s==null?void 0:s.snapshot]),H=X==="dom"?[]:u[X]??[],ke=i.useMemo(()=>te.filter(h=>!!(h.ref&&h.box)).sort((h,v)=>v.box.width*v.box.height-h.box.width*h.box.height),[te]),T=i.useMemo(()=>te.find(h=>h.ref===D),[D,te]);i.useEffect(()=>{E(null)},[s==null?void 0:s.snapshotId]),i.useEffect(()=>{A&&le("dom")},[A]);const ne=i.useCallback(()=>{var ue,se,K,Se;const h=Ne.current,v=ve.current,B=((ue=s==null?void 0:s.viewport)==null?void 0:ue.width)??((se=l==null?void 0:l.viewport)==null?void 0:se.width)??(v==null?void 0:v.naturalWidth),J=((K=s==null?void 0:s.viewport)==null?void 0:K.height)??((Se=l==null?void 0:l.viewport)==null?void 0:Se.height)??(v==null?void 0:v.naturalHeight);if(!h||!B||!J){ge({left:0,top:0,width:0,height:0,sourceWidth:0,sourceHeight:0});return}const Q=h.getBoundingClientRect(),G=Math.min(Q.width/B,Q.height/J),De=B*G,V=J*G;ge({left:(Q.width-De)/2,top:(Q.height-V)/2,width:De,height:V,sourceWidth:B,sourceHeight:J})},[(ae=l==null?void 0:l.viewport)==null?void 0:ae.height,(ce=l==null?void 0:l.viewport)==null?void 0:ce.width,(oe=s==null?void 0:s.viewport)==null?void 0:oe.height,(de=s==null?void 0:s.viewport)==null?void 0:de.width]);i.useEffect(()=>{ne();const h=Ne.current;if(!h||typeof ResizeObserver>"u")return;const v=new ResizeObserver(ne);return v.observe(h),()=>v.disconnect()},[ne,a]);const U=i.useMemo(()=>{const h=l==null?void 0:l.targetBox,v=l==null?void 0:l.viewport;if(!h||!v||I.width<=0||I.height<=0)return null;const B=Math.min(v.width,Math.max(0,h.x+h.width/2)),J=Math.min(v.height,Math.max(0,h.y+h.height/2));return{left:I.left+B/v.width*I.width,top:I.top+J/v.height*I.height}},[l,I]),re=h=>{A&&h!=="dom"||(le(h),h!=="dom"&&g(h))};return e.jsxs("section",{"data-browser-test":!0,"data-browser-source":t,"data-browser-snapshot-id":s==null?void 0:s.snapshotId,className:"flex h-full min-h-0 flex-col bg-[hsl(var(--deck-canvas))]",children:[e.jsxs("div",{ref:Ne,className:"relative flex min-h-0 flex-1 items-center justify-center overflow-hidden bg-neutral-950",children:[a?e.jsx("img",{ref:ve,"data-browser-test-screenshot":!0,src:a,alt:j.screenshotAlt,onLoad:ne,className:"h-full w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-3 text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(zr,{className:"h-7 w-7"}),e.jsx("span",{className:"font-mono text-[11px]",children:r?j.empty:j.unavailable})]}),!A&&a&&I.width>0&&I.height>0&&e.jsxs("div",{"data-browser-element-layer":!0,className:"pointer-events-none absolute z-20",style:{left:I.left,top:I.top,width:I.width,height:I.height},children:[d&&!c&&ke.map(h=>e.jsx("button",{type:"button","data-browser-pick-ref":h.ref,"aria-label":`${j.selectElement}: ${h.text}`,title:h.text,onClick:()=>E(h.ref),className:_("pointer-events-auto absolute cursor-crosshair border border-cyan-300/70 bg-cyan-300/5 transition-colors hover:border-cyan-300 hover:bg-cyan-300/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-300",D===h.ref&&"border-2 border-cyan-300 bg-cyan-300/15"),style:{left:`${h.box.x/I.sourceWidth*100}%`,top:`${h.box.y/I.sourceHeight*100}%`,width:`${h.box.width/I.sourceWidth*100}%`,height:`${h.box.height/I.sourceHeight*100}%`}},h.ref)),!d&&(T==null?void 0:T.box)&&e.jsx("div",{"data-browser-selected-element":T.ref,className:"absolute border-2 border-cyan-300 bg-cyan-300/10 shadow-[0_0_0_1px_rgba(8,145,178,0.35)]",style:{left:`${T.box.x/I.sourceWidth*100}%`,top:`${T.box.y/I.sourceHeight*100}%`,width:`${T.box.width/I.sourceWidth*100}%`,height:`${T.box.height/I.sourceHeight*100}%`}})]}),!A&&T&&a&&e.jsxs(q,{type:"button","data-browser-add-to-composer":!0,disabled:c,onClick:()=>{s&&(O(ts(T,s)),E(null),L(!1))},className:"absolute bottom-3 left-3 z-30 h-8 rounded-md bg-neutral-950 px-3 font-mono text-[10.5px] text-white shadow-lg hover:bg-neutral-800",children:[e.jsx(Ir,{className:"mr-1.5 h-3.5 w-3.5"}),j.addToConversation]}),A&&U&&e.jsxs("div",{"data-browser-agent-pointer":!0,"data-browser-action":l==null?void 0:l.action,className:"pointer-events-none absolute z-10 transition-[left,top] duration-300 ease-out",style:U,children:[e.jsx("span",{className:"absolute -left-2 -top-2 h-4 w-4 animate-ping rounded-full bg-cyan-400/70"},x),e.jsx(Lt,{className:"relative h-5 w-5 fill-white text-neutral-950 drop-shadow-[0_1px_2px_rgba(0,0,0,0.8)]"})]}),c&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/35",children:e.jsx(Be,{className:"h-5 w-5 animate-spin text-white"})}),w&&e.jsx("div",{role:"alert",className:"absolute inset-x-0 bottom-0 border-t border-red-500/30 bg-red-950/90 px-3 py-2 font-mono text-[10.5px] text-red-200",children:w})]}),e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-1 border-y border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-2",children:[e.jsx("div",{role:"group","aria-label":j.sourceAria,className:"flex h-7 shrink-0 items-center border border-[hsl(var(--deck-border))]",children:[["user",j.user,qr],["agent",j.agent,gr]].map(([h,v,B])=>e.jsxs("button",{type:"button",disabled:h==="agent"&&!n,"aria-pressed":t===h,onClick:()=>k(h),className:_("flex h-full items-center gap-1 border-r border-[hsl(var(--deck-border))] px-1.5 font-mono text-[9.5px] text-[hsl(var(--deck-ink-muted))] last:border-r-0 disabled:opacity-40",t===h&&"bg-[hsl(var(--deck-canvas-veil))] text-[hsl(var(--deck-ink))]"),children:[e.jsx(B,{className:"h-3 w-3"}),e.jsx("span",{children:v})]},h))}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:A||!s||!a||c,"aria-pressed":d,title:d?j.stopSelecting:j.selectElement,"aria-label":d?j.stopSelecting:j.selectElement,onClick:()=>void L(!d),className:_("h-7 w-7 rounded-md",d&&"bg-[hsl(var(--deck-accent-soft))] text-[hsl(var(--deck-accent))]"),children:e.jsx(kr,{className:"h-3.5 w-3.5"})}),e.jsx("span",{title:D?`${j.selectedRef}: ${D}`:j.noRef,className:"w-20 shrink-0 truncate font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:D??"ref"}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:A||!D||c,title:j.click,"aria-label":j.click,onClick:()=>{D&&p({kind:"click"},D)},className:"h-7 w-7 rounded-md",children:e.jsx(Lt,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"flex h-7 min-w-0 flex-1 items-center border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas))] px-2",children:[e.jsx("input",{value:ee,onChange:h=>Ie(h.target.value),disabled:A,placeholder:j.valuePlaceholder,"aria-label":j.valuePlaceholder,className:"min-w-0 flex-1 bg-transparent font-mono text-[10.5px] outline-none"}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:A||!D||!ee||c,title:j.fill,"aria-label":j.fill,onClick:()=>{D&&p({kind:"fill",value:ee},D)},className:"h-6 w-6 rounded-md",children:e.jsx(wr,{className:"h-3 w-3"})})]}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:A||!s||c,title:j.scrollUp,"aria-label":j.scrollUp,onClick:()=>void p({kind:"scroll",direction:"up",amount:560}),className:"h-7 w-7 rounded-md",children:e.jsx(Dr,{className:"h-3.5 w-3.5"})}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:A||!s||c,title:j.scrollDown,"aria-label":j.scrollDown,onClick:()=>void p({kind:"scroll",direction:"down",amount:560}),className:"h-7 w-7 rounded-md",children:e.jsx(Fr,{className:"h-3.5 w-3.5"})}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:A||!s||c,title:j.snapshot,"aria-label":j.snapshot,onClick:()=>void M(),className:"h-7 w-7 rounded-md",children:e.jsx(Vt,{className:"h-3.5 w-3.5"})}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:A||!r||c,title:j.reset,"aria-label":j.reset,onClick:()=>{E(null),S()},className:"h-7 w-7 rounded-md",children:e.jsx(Kt,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex h-[38%] min-h-32 shrink-0 flex-col overflow-hidden",children:[e.jsx("div",{role:"tablist",className:"grid h-8 shrink-0 grid-cols-4 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[["dom",j.dom,yr],["console",j.console,Or],["network",j.network,Hr],["page-errors",j.errors,Ar]].map(([h,v,B])=>e.jsxs("button",{type:"button",role:"tab",disabled:A&&h!=="dom","aria-selected":X===h,onClick:()=>re(h),className:_("flex min-w-0 items-center justify-center gap-1 border-r border-[hsl(var(--deck-border))] px-1 font-mono text-[10px] text-[hsl(var(--deck-ink-muted))] last:border-r-0",X===h&&"bg-[hsl(var(--deck-canvas-veil))] text-[hsl(var(--deck-ink))]"),children:[e.jsx(B,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:v})]},h))}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto bg-[hsl(var(--deck-canvas-veil))] p-2 font-mono text-[10px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:X==="dom"?te.length>0?te.map((h,v)=>h.ref?e.jsx("button",{type:"button","data-browser-ref":h.ref,disabled:A,onClick:()=>E(h.ref??null),className:_("block w-full whitespace-pre-wrap px-1 text-left hover:bg-[hsl(var(--deck-accent)/0.08)]",D===h.ref&&"bg-[hsl(var(--deck-accent)/0.12)] text-[hsl(var(--deck-ink))]"),children:h.text},`${h.ref}:${v}`):e.jsx("div",{className:"whitespace-pre-wrap px-1",children:h.text},`${h.text}:${v}`)):e.jsx("div",{className:"flex h-full items-center justify-center",children:j.noEntries}):y===X?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(Be,{className:"h-4 w-4 animate-spin"})}):H.length>0?H.map(h=>e.jsx("div",{className:"border-b border-[hsl(var(--deck-border))] px-1 py-1 last:border-b-0",children:rs(h)},h.sequence)):e.jsx("div",{className:"flex h-full items-center justify-center",children:j.noEntries})})]})]})}const ns="http://localhost:3000",as=2048,os=/^(?:localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\]|10(?:\.\d{1,3}){3}|192\.168(?:\.\d{1,3}){2}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2})(?::\d+)?$/i,is=/^[a-z\d.-]+:\d+$/i;function tr(){return typeof window>"u"?void 0:window.location.origin}function ht(t,n=tr(),r=!1){const s=t.trim();if(!s)return{ok:!1,reason:"empty"};if(s.length>as)return{ok:!1,reason:"invalid"};let a=s;const l=a.split(/[/?#]/,1)[0]??"";os.test(l)||is.test(l)?a=`http://${a}`:a.startsWith("//")?a=`https:${a}`:/^[a-z][a-z\d+.-]*:/i.test(a)||(a=`https://${a}`);let x;try{x=new URL(a)}catch{return{ok:!1,reason:"invalid"}}return x.protocol!=="http:"&&x.protocol!=="https:"?{ok:!1,reason:"protocol"}:x.username||x.password?{ok:!1,reason:"credentials"}:r&&n&&x.origin===n?{ok:!1,reason:"same_origin"}:{ok:!0,url:x.href}}function ls(t,n=tr()){return ht(t,n,!0)}function cs(t,n){if(t.entries[t.index]===n)return t;const r=[...t.entries.slice(0,t.index+1),n].slice(-50);return{entries:r,index:r.length-1}}function ds(t){try{const n=new URL(t).protocol;return n==="http:"||n==="https:"}catch{return!1}}const us={en:{modeAria:"Browser mode",preview:"Preview",test:"Test",external:"External",noSession:"No active Session",snapshotRefreshed:"The page changed. Snapshot refreshed; select the element again.",toolbarAria:"Browser navigation",addressAria:"Browser address",addressPlaceholder:"Enter an HTTP or HTTPS URL",back:"Go back",forward:"Go forward",reload:"Reload page",go:"Open address",openExternal:"Open in system browser",externalEmpty:"No external page selected",status:{idle:"Idle",loading:"Loading…",ready:"Ready",error:"Failed"},error:{empty:"Enter a URL.",invalid:"Enter a valid URL.",protocol:"Only HTTP and HTTPS URLs are supported.",credentials:"URLs containing credentials are not allowed.",same_origin:"The Blade Web origin cannot be embedded in itself."}},zh:{modeAria:"浏览器模式",preview:"预览",test:"测试",external:"外部",noSession:"没有活动 Session",snapshotRefreshed:"页面已变化,快照已刷新,请重新选择元素。",toolbarAria:"浏览器导航",addressAria:"浏览器地址",addressPlaceholder:"输入 HTTP 或 HTTPS 地址",back:"后退",forward:"前进",reload:"刷新页面",go:"打开地址",openExternal:"在系统浏览器中打开",externalEmpty:"未选择外部页面",status:{idle:"空闲",loading:"正在加载…",ready:"就绪",error:"失败"},error:{empty:"请输入地址。",invalid:"请输入有效地址。",protocol:"仅支持 HTTP 与 HTTPS 地址。",credentials:"不允许使用包含凭据的地址。",same_origin:"不能在面板中嵌套 Blade Web 自身地址。"}}};function fs({sessionRef:t=null,onElementAdded:n}){const{locale:r}=at(),s=us[r],a=Ct(f=>f.agentActivity),l=z(f=>Qe(f.historySurfaceSelection)),x=t!==null&&a!==null&&a.sessionRef.sessionId===t.sessionId&&a.sessionRef.projectPath===t.projectPath,[c,w]=i.useState("preview"),[u,y]=i.useState("user"),[p,g]=i.useState(ns),[M,S]=i.useState({entries:[],index:-1}),k=i.useRef(M),[d,L]=i.useState(0),[O,F]=i.useState("idle"),[j,D]=i.useState(null),[E,ee]=i.useState(null),[Ie,X]=i.useState(null),[le,Ne]=i.useState(null),[ve,I]=i.useState(!1),[ge,A]=i.useState(null),[te,H]=i.useState(!1),[ke,T]=i.useState(null),[ne,U]=i.useState(!1),[re,ae]=i.useState(null),[ce,oe]=i.useState({}),[de,h]=i.useState(null),v=i.useRef(0),B=i.useRef(null),J=i.useRef(null),Q=M.entries[M.index]??null,G=c==="preview"?Q:c==="test"?u==="agent"&&x?(a==null?void 0:a.url)??null:(E==null?void 0:E.url)??null:re,De=i.useMemo(()=>{if(!G)return"";try{return new URL(G).host}catch{return""}},[G]),V=c==="preview"?O:c==="test"?u==="agent"&&x?ve||(a==null?void 0:a.phase)==="running"?"loading":ge||(a==null?void 0:a.phase)==="error"?"error":le?"ready":"idle":te?"loading":ke?"error":E?"ready":"idle":re?"ready":"idle",ue=j!==null?s.error[j]:c==="test"?u==="agent"&&x?ge??(a==null?void 0:a.errorCode)??null:ke:null,se=f=>{B.current&&URL.revokeObjectURL(B.current),B.current=f,X(f)},K=f=>{J.current&&URL.revokeObjectURL(J.current),J.current=f,Ne(f)};i.useEffect(()=>{const f=v.current+1;return v.current=f,ee(null),y("user"),T(null),A(null),I(!1),U(!1),oe({}),se(null),K(null),()=>{v.current===f&&(v.current+=1)}},[l,t==null?void 0:t.projectPath,t==null?void 0:t.sessionId]),i.useEffect(()=>()=>{B.current&&URL.revokeObjectURL(B.current),J.current&&URL.revokeObjectURL(J.current)},[]),i.useEffect(()=>{l||!t||!x||!a||(w("test"),y("agent"),D(null),a.url&&g(a.url))},[a==null?void 0:a.revision,x,l,t]),i.useEffect(()=>{if(l||!t||!x||!a||!a.pageId||!a.origin||a.frameRevision===0)return;if(!ds(a.origin)){I(!1),A(null),K(null);return}const f=v.current,m=a.frameRevision,N=()=>{const P=Ct.getState().agentActivity;return v.current===f&&(P==null?void 0:P.frameRevision)===m&&P.sessionRef.sessionId===t.sessionId&&P.sessionRef.projectPath===t.projectPath};I(!0),A(null),xe.screenshot(t,{source:"agent",pageId:a.pageId,expectedOrigin:a.origin}).then(P=>{N()&&K(URL.createObjectURL(P))}).catch(P=>{N()&&A(P instanceof Error?P.message:String(P))}).finally(()=>{N()&&I(!1)})},[a==null?void 0:a.frameRevision,a==null?void 0:a.origin,a==null?void 0:a.pageId,x,l,t]);const Se=async(f,m,N)=>{if(Z(z.getState()))return;const P=await xe.screenshot(f,{pageId:m.pageId,expectedOrigin:m.origin});v.current===N&&se(URL.createObjectURL(P))},Ce=async(f,m,N)=>{v.current===N&&(ee(m),g(m.url),oe({}),await Se(f,m,N))},Fe=async f=>{if(Z(z.getState()))return;if(!t){T(s.noSession);return}const m=v.current;U(!1),H(!0),T(null);try{const N=await xe.navigate(t,f);await Ce(t,N,m)}catch(N){v.current===m&&T(N instanceof Error?N.message:String(N))}finally{v.current===m&&H(!1)}},Oe=f=>{const m=cs(k.current,f);k.current=m,S(m),g(f),F("loading")},qe=f=>{if(f.preventDefault(),Z(z.getState()))return;const m=c==="preview"?ls(p):ht(p);if(!m.ok){D(m.reason);return}if(D(null),c==="preview"){m.url===Q&&L(N=>N+1),Oe(m.url);return}if(c==="test"){if(u==="agent")return;Fe({action:"goto",url:m.url});return}ae(m.url),g(m.url),window.open(m.url,"_blank","noopener,noreferrer")},$e=f=>{const m=k.current.index+f,N=k.current.entries[m];if(!N)return;const P={...k.current,index:m};k.current=P,S(P),g(N),F("loading")},Ee=f=>{if(!Z(z.getState())){if(c==="preview"){f==="back"?$e(-1):f==="forward"?$e(1):Q&&(F("loading"),L(m=>m+1));return}c==="test"&&u==="user"&&E&&Fe({action:f,pageId:E.pageId,expectedOrigin:E.origin})}},Xe=f=>{U(!1),w(f),D(null),T(null);const m=f==="preview"?Q:f==="test"?u==="agent"&&x?a==null?void 0:a.url:E==null?void 0:E.url:re;m&&g(m)},He=f=>{if(f==="agent"&&!x)return;y(f),U(!1),D(null),T(null),A(null);const m=f==="agent"?a==null?void 0:a.url:E==null?void 0:E.url;m&&g(m)},Ye=async(f,m)=>{if(Z(z.getState())||!t||!E)return;const N=E,P=v.current;U(!1),H(!0),T(null);try{const Y=await xe.interact(t,{pageId:N.pageId,snapshotId:N.snapshotId,expectedOrigin:N.origin,...m?{ref:m}:{},action:f});if(Y.outcome==="applied")await Ce(t,Y.observation,P);else if(Y.outcome==="applied_observation_failed"){if(Z(z.getState()))return;const ye=await xe.snapshot(t,{pageId:Y.pageId});await Ce(t,ye,P)}else T(Y.errorCode)}catch(Y){if(v.current===P){const ye=Y instanceof Error?Y.message:String(Y);if(/snapshot is stale/i.test(ye))try{if(Z(z.getState()))return;const Re=await xe.snapshot(t,{pageId:N.pageId});await Ce(t,Re,P),v.current===P&&T(s.snapshotRefreshed)}catch(Re){v.current===P&&T(Re instanceof Error?Re.message:String(Re))}else T(ye)}}finally{v.current===P&&H(!1)}},fe=async(f=!1)=>{if(Z(z.getState())||!t||!E)return!1;const m=v.current;H(!0),T(null);try{const N=await xe.snapshot(t,{pageId:E.pageId,...f?{includeBoxes:!0}:{}});return await Ce(t,N,m),v.current===m}catch(N){return v.current===m&&T(N instanceof Error?N.message:String(N)),!1}finally{v.current===m&&H(!1)}},Ae=async f=>{if(Z(z.getState())||!t||!E)return;const m=v.current;h(f);try{const N=await xe.inspect(t,{target:f,pageId:E.pageId,expectedOrigin:E.origin});v.current===m&&oe(P=>({...P,[f]:N.entries??[]}))}catch(N){v.current===m&&T(N instanceof Error?N.message:String(N))}finally{v.current===m&&h(null)}},we=async f=>{if(!f){U(!1);return}if(u==="agent")return;await fe(!0)&&U(!0)},Ge=f=>{if(Z(z.getState()))return;const m=t?`session:${jr(t)}`:"session:temporary";Nr(m,f)&&(U(!1),n==null||n(),requestAnimationFrame(()=>Sr()))},Me=async()=>{if(Z(z.getState())||!t)return;const f=v.current;U(!1),H(!0),T(null);try{await xe.reset(t),v.current===f&&(ee(null),oe({}),se(null))}catch(m){v.current===f&&T(m instanceof Error?m.message:String(m))}finally{v.current===f&&H(!1)}},he=()=>{if(Z(z.getState()))return;const m=ht(G??p);if(!m.ok){D(m.reason);return}ae(m.url),window.open(m.url,"_blank","noopener,noreferrer")},ie=c==="preview"?M.index>0:c==="test"&&u==="user"&&!!E,_e=c==="preview"?M.index>=0&&M.index<M.entries.length-1:c==="test"&&u==="user"&&!!E,Te=c==="test"&&u==="agent",pe=u==="agent"?ve||(a==null?void 0:a.phase)==="running":te;return l?null:e.jsxs("section",{"data-browser-panel":!0,"data-browser-mode":c,"data-browser-test-source":u,"data-browser-history-count":M.entries.length,"data-browser-history-index":M.index,className:"flex h-full min-h-0 flex-col bg-[hsl(var(--deck-canvas))]",children:[e.jsx("div",{role:"tablist","aria-label":s.modeAria,className:"grid h-9 shrink-0 grid-cols-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[["preview",s.preview,st],["test",s.test,Br],["external",s.external,Rt]].map(([f,m,N])=>e.jsxs("button",{type:"button",role:"tab","aria-selected":c===f,onClick:()=>Xe(f),className:_("flex min-w-0 items-center justify-center gap-1.5 border-r border-[hsl(var(--deck-border))] px-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] last:border-r-0",c===f&&"bg-[hsl(var(--deck-canvas-veil))] text-[hsl(var(--deck-ink))]"),children:[e.jsx(N,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:m})]},f))}),e.jsxs("form",{"aria-label":s.toolbarAria,onSubmit:qe,className:"flex h-12 shrink-0 items-center gap-1 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-2",children:[e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:!ie||c==="test"&&pe,"aria-label":s.back,title:s.back,onClick:()=>Ee("back"),className:"h-8 w-8 rounded-md text-[hsl(var(--deck-ink-muted))]",children:e.jsx(Mr,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:!_e||c==="test"&&pe,"aria-label":s.forward,title:s.forward,onClick:()=>Ee("forward"),className:"h-8 w-8 rounded-md text-[hsl(var(--deck-ink-muted))]",children:e.jsx(_r,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:c==="external"||Te||!G||c==="test"&&pe,"aria-label":s.reload,title:s.reload,onClick:()=>Ee("reload"),className:"h-8 w-8 rounded-md text-[hsl(var(--deck-ink-muted))]",children:e.jsx(Vt,{className:_("h-4 w-4",V==="loading"&&"animate-spin")})}),e.jsxs("div",{className:_("flex h-8 min-w-0 flex-1 items-center gap-2 rounded-md border bg-[hsl(var(--deck-canvas))] px-2",ue?"border-red-500/70":"border-[hsl(var(--deck-border))] focus-within:border-[hsl(var(--deck-accent)/0.65)]"),children:[e.jsx(st,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("input",{"data-browser-panel-address":!0,"data-preview-browser-address":c==="preview"||void 0,value:p,readOnly:Te,onChange:f=>{g(f.target.value),D(null)},onKeyDown:f=>{f.key==="Escape"&&G&&(f.preventDefault(),g(G),D(null))},"aria-label":s.addressAria,placeholder:s.addressPlaceholder,autoCapitalize:"none",autoComplete:"off",spellCheck:!1,className:"min-w-0 flex-1 bg-transparent font-mono text-[11px] text-[hsl(var(--deck-ink))] outline-none placeholder:text-[hsl(var(--deck-ink-faint))]"})]}),e.jsx(q,{type:"submit",variant:"ghost",size:"icon","aria-label":s.go,title:s.go,disabled:Te||c==="test"&&pe,className:"h-8 w-8 rounded-md text-[hsl(var(--deck-accent))]",children:V==="loading"?e.jsx(Be,{className:"h-4 w-4 animate-spin"}):e.jsx(Jt,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",disabled:!G,"aria-label":s.openExternal,title:s.openExternal,onClick:he,className:"h-8 w-8 rounded-md text-[hsl(var(--deck-ink-muted))]",children:e.jsx(Tt,{className:"h-4 w-4"})})]}),ue&&c!=="test"&&e.jsx("div",{role:"alert",className:"shrink-0 border-b border-red-500/25 bg-red-500/10 px-3 py-2 font-mono text-[10.5px] text-red-700 dark:text-red-300",children:ue}),e.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:c==="preview"?e.jsx(Yr,{url:Q,revision:d,loadState:O,onLoad:()=>F("ready"),onError:()=>F("error")}):c==="test"?e.jsx(ss,{source:u,agentAvailable:x,sessionAvailable:!!t,observation:u==="agent"?null:E,screenshotUrl:u==="agent"?le:Ie,interaction:u==="agent"?a==null?void 0:a.interaction:void 0,pointerRevision:u==="agent"?(a==null?void 0:a.pointerRevision)??0:0,busy:pe,error:ue,diagnostics:u==="agent"?{}:ce,diagnosticsLoading:u==="agent"?null:de,onInteract:Ye,onInspect:Ae,onSnapshot:async()=>{await fe()},onReset:Me,onSourceChange:He,pickerActive:ne,onPickerChange:we,onAddToConversation:Ge}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 bg-[hsl(var(--deck-canvas-veil))]",children:[e.jsx(Rt,{className:"h-7 w-7 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:re?new URL(re).host:s.externalEmpty}),e.jsxs(q,{type:"button",variant:"outline",onClick:he,disabled:!p.trim(),className:"h-8 rounded-md font-mono text-[11px]",children:[e.jsx(Tt,{className:"mr-2 h-3.5 w-3.5"}),s.openExternal]})]})}),e.jsxs("div",{"data-browser-panel-status":V,"data-preview-browser-status":c==="preview"?V:void 0,"aria-live":"polite",className:"flex h-7 shrink-0 items-center justify-between border-t border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:_("h-1.5 w-1.5 shrink-0 rounded-full bg-[hsl(var(--deck-ink-faint))]",V==="loading"&&"bg-amber-500",V==="ready"&&"bg-emerald-500",V==="error"&&"bg-red-500")}),e.jsx("span",{children:s.status[V]})]}),e.jsx("span",{className:"ml-3 truncate",children:De||s[c]})]})]})}function nt(t){return t.normalize("NFKC").toLocaleLowerCase().trim()}function hs(t,n,r){const s=nt(n).split(/\s+/).filter(Boolean);return t.filter(a=>{if(r!=="all"&&a.status!==r)return!1;if(s.length===0)return!0;const l=nt([a.title,a.subtitle,a.content].filter(Boolean).join(" "));return s.every(x=>l.includes(x))})}function rr(t){return t.replace(/\/+$/,"").split("/").filter(Boolean).at(-1)||t}function ps(t,n){const r=nt(n).split(/\s+/).filter(Boolean);return r.length===0?t:t.filter(s=>{const a=nt([s.filePath,s.summary].filter(Boolean).join(" "));return r.every(l=>a.includes(l))})}function ms(t,n,r){return n===0?0:(t+r+n)%n}const Dt=20,Ft=20,$t=160,At=240;function Mt(t,n){const r=l=>l.replace(/\\/g,"/").replace(/^\.?\//,"").replace(/\/+/g,"/"),s=r(t),a=r(n);return s===a||s.endsWith(`/${a}`)||a.endsWith(`/${s}`)}function xs({diffs:t,expanded:n,targetPath:r,onToggle:s,onSetAllExpanded:a}){var S,k;const l=je(),[x,c]=i.useState(""),w=`${x}\0${t.length}\0${((S=t[0])==null?void 0:S.filePath)??""}\0${((k=t.at(-1))==null?void 0:k.filePath)??""}`,[u,y]=i.useState({key:w,count:Dt}),p=u.key===w?u.count:Dt,g=i.useMemo(()=>ps(t,x),[t,x]),M=i.useMemo(()=>{const d=g.slice(0,p);if(!r)return d;const L=g.find(O=>O.filePath&&Mt(O.filePath,r));return L&&!d.includes(L)?[...d,L]:d},[g,r,p]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"sticky top-0 z-10 space-y-2 bg-[hsl(var(--deck-canvas))] pb-1",children:[e.jsxs("div",{className:"flex h-8 items-center gap-2 rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-2 focus-within:border-[hsl(var(--deck-accent)/0.6)]",children:[e.jsx(mt,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("input",{type:"search","aria-label":l("preview.diff.searchAria"),placeholder:l("preview.diff.searchPlaceholder"),value:x,onChange:d=>c(d.target.value),className:"min-w-0 flex-1 bg-transparent font-mono text-[11px] text-[hsl(var(--deck-ink))] outline-none placeholder:text-[hsl(var(--deck-ink-faint))]"}),e.jsxs("span",{className:"font-mono text-[9px] tabular-nums text-[hsl(var(--deck-ink-faint))]",children:[g.length,"/",t.length]})]}),e.jsxs("div",{className:"flex items-center justify-between font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:[e.jsx("span",{children:l("preview.diff.changedFiles",{count:t.length})}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsxs("button",{type:"button",onClick:()=>a(!0),className:"inline-flex items-center gap-1 rounded px-1.5 py-1 transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink-muted))]",children:[e.jsx($r,{className:"h-3 w-3"}),l("preview.diff.expandAll")]}),e.jsxs("button",{type:"button",onClick:()=>a(!1),className:"inline-flex items-center gap-1 rounded px-1.5 py-1 transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(Ur,{className:"h-3 w-3"}),l("preview.diff.collapseAll")]})]})]})]}),g.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-[hsl(var(--deck-border))] p-6 text-center font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:l("preview.diff.noMatches")}):M.map(d=>{const L=d.filePath||"unknown",O=t.indexOf(d),F=n[L]??O===0,j=!!(r&&Mt(L,r));return e.jsxs("div",{"data-preview-diff-path":d.filePath,className:_("overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] transition-colors",j&&"border-[hsl(var(--deck-accent)/0.7)] bg-[hsl(var(--deck-accent-soft))] ring-1 ring-[hsl(var(--deck-accent)/0.2)]"),children:[e.jsxs("button",{type:"button","aria-expanded":F,onClick:()=>s(L),className:"flex w-full items-center gap-2 bg-[hsl(var(--deck-surface-2))] px-3 py-2 transition-colors hover:bg-[hsl(var(--deck-surface))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[hsl(var(--deck-accent)/0.65)]",children:[F?e.jsx(Qt,{className:"h-4 w-4 text-[hsl(var(--deck-ink-muted))]"}):e.jsx(Yt,{className:"h-4 w-4 text-[hsl(var(--deck-ink-muted))]"}),e.jsx(Xt,{className:"h-4 w-4 text-[hsl(var(--deck-ink-muted))]"}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-left font-mono text-[13px] text-[hsl(var(--deck-ink))]",children:rr(L)}),d.summary&&e.jsx("span",{className:"shrink-0 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:d.summary})]}),F&&e.jsxs("div",{className:"border-t border-[hsl(var(--deck-border))]",children:[e.jsx("div",{className:"truncate px-3 py-1 font-mono text-[11px] text-[hsl(var(--deck-ink-faint))]",children:d.filePath}),e.jsx(bs,{diff:d.diff})]})]},L)}),p<g.length&&e.jsx("div",{className:"flex justify-center pt-1",children:e.jsx("button",{type:"button",onClick:()=>y({key:w,count:Math.min(g.length,p+Ft)}),className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-3 py-1.5 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:border-[hsl(var(--deck-border-strong))] hover:text-[hsl(var(--deck-ink))]",children:l("preview.diff.showMoreFiles",{count:Math.min(Ft,g.length-p)})})})]})}function bs({diff:t}){const n=je(),r=i.useMemo(()=>t.patch.split(`
|
|
50
|
-
`),[t.patch]),[s,a]=i.useState({patch:t.patch,count:$t}),l=s.patch===t.patch?s.count:$t,x=r.slice(0,l);let c=0,w=0;return e.jsxs("div",{className:"overflow-hidden rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx("span",{children:n("preview.diff.patch")}),t.matchLine&&e.jsx("span",{children:n("preview.diff.line",{line:t.matchLine})})]}),e.jsx("div",{className:"overflow-x-auto font-mono text-[12px]",children:x.map((u,y)=>{if(u.startsWith("@@")){const p=/@@ -(?<old>\d+),?(?<oldCount>\d*) \+(?<new>\d+),?(?<newCount>\d*) @@/.exec(u);return p!=null&&p.groups&&(c=Number.parseInt(p.groups.old,10),w=Number.parseInt(p.groups.new,10)),e.jsx(ze,{line:u},`${u}-${y}`)}if(u.startsWith("---")||u.startsWith("+++")||u.startsWith("Index:")||u.startsWith("==="))return e.jsx(ze,{line:u},`${u}-${y}`);if(u.startsWith("+")){const p=w++;return e.jsx(ze,{line:u,oldLine:null,newLine:p},`${u}-${y}`)}if(u.startsWith("-")){const p=c++;return e.jsx(ze,{line:u,oldLine:p,newLine:null},`${u}-${y}`)}return u.startsWith(" ")?e.jsx(ze,{line:u,oldLine:c++,newLine:w++},`${u}-${y}`):e.jsx(ze,{line:u},`${u}-${y}`)})}),l<r.length&&e.jsx("div",{className:"flex justify-center border-t border-[hsl(var(--deck-border))] p-2",children:e.jsx("button",{type:"button",onClick:()=>a({patch:t.patch,count:Math.min(r.length,l+At)}),className:"rounded-md border border-[hsl(var(--deck-border))] px-3 py-1 font-mono text-[10.5px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:bg-[hsl(var(--deck-surface-2))] hover:text-[hsl(var(--deck-ink))]",children:n("preview.diff.showMoreLines",{count:Math.min(At,r.length-l)})})})]})}function ze({line:t,oldLine:n,newLine:r}){const s=t.startsWith("---")||t.startsWith("+++")||t.startsWith("Index:")||t.startsWith("==="),a=t.startsWith("@@"),l=t[0],x=s||a?t:t.slice(1),c=s?"text-[hsl(var(--deck-ink-muted))]":l==="+"?"bg-[#22C55E]/10 text-[#166534] dark:bg-[#22C55E]/10 dark:text-[#86efac]":l==="-"?"bg-[#EF4444]/10 text-[#b91c1c] dark:bg-[#EF4444]/10 dark:text-[#fca5a5]":a?"bg-[#DBEAFE] text-[#1d4ed8] dark:bg-[#1e3a8a]/30 dark:text-[#93c5fd]":"text-[hsl(var(--deck-ink))]";return e.jsxs("div",{"data-preview-diff-line":!0,className:_("grid min-w-max grid-cols-[40px_40px_1fr] gap-2 px-3 py-0.5",c),children:[e.jsx("span",{className:"text-right text-[hsl(var(--deck-ink-faint))]",children:n?String(n).padStart(2," "):""}),e.jsx("span",{className:"text-right text-[hsl(var(--deck-ink-faint))]",children:r?String(r).padStart(2," "):""}),e.jsx("span",{className:"whitespace-pre",children:x})]})}function vs({nodes:t,expandedDirs:n,childrenCache:r,directoryStates:s,selectedPath:a,onToggleDir:l,onRetryDir:x,onSelectFile:c}){return e.jsx(e.Fragment,{children:t.map(w=>e.jsx(sr,{node:w,depth:0,expandedDirs:n,childrenCache:r,directoryStates:s,selectedPath:a,onToggleDir:l,onRetryDir:x,onSelectFile:c},w.path))})}function sr({node:t,depth:n,expandedDirs:r,childrenCache:s,directoryStates:a,selectedPath:l,onToggleDir:x,onRetryDir:c,onSelectFile:w}){const u=je(),y=t.type==="dir",p=!!r[t.path],g=!y&&l===t.path,M=s[t.path]??[],S=a[t.path],k=n*14+24;return e.jsxs("div",{children:[e.jsxs("button",{type:"button","aria-expanded":y?p:void 0,"aria-busy":y&&(S==null?void 0:S.status)==="loading",onClick:()=>y?x(t.path):w(t.path),className:_("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left font-mono text-[12px] transition-colors",g?"border border-[#16A34A]/30 bg-[#16A34A]/10 text-[#111827] dark:border-[#22C55E]/30 dark:bg-[#22C55E]/10 dark:text-[#E5E5E5]":"text-[hsl(var(--deck-ink-muted))] hover:bg-[hsl(var(--deck-surface))]",y&&"cursor-pointer"),style:{paddingLeft:n*14+8},children:[y?(S==null?void 0:S.status)==="loading"?e.jsx(Be,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-[hsl(var(--deck-accent))]"}):p?e.jsx(Cr,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-ink))]"}):e.jsx(Wr,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-ink-muted))]"}):e.jsx(Xt,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:t.name})]}),y&&p&&e.jsxs("div",{children:[(S==null?void 0:S.status)==="loading"&&e.jsx("div",{role:"status",style:{paddingLeft:k},className:"py-1 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:u("preview.files.directoryLoading")}),(S==null?void 0:S.status)==="error"&&e.jsxs("div",{role:"alert",style:{marginLeft:k},className:"my-1 mr-1 rounded-md border border-red-200 bg-red-50/70 px-2 py-1.5 font-mono text-[10px] text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300",children:[e.jsx("div",{className:"truncate",title:S.message,children:S.message}),e.jsxs("button",{type:"button",onClick:()=>c(t.path),className:"mt-1 inline-flex items-center gap-1 font-medium underline-offset-2 hover:underline",children:[e.jsx(Kt,{className:"h-2.5 w-2.5"}),u("preview.action.retry")]})]}),(S==null?void 0:S.status)==="loaded"&&M.length===0&&e.jsx("div",{style:{paddingLeft:k},className:"py-1 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:u("preview.files.directoryEmpty")}),M.map(d=>e.jsx(sr,{node:d,depth:n+1,expandedDirs:r,childrenCache:s,directoryStates:a,selectedPath:l,onToggleDir:x,onRetryDir:c,onSelectFile:w},d.path))]})]})}const _t=80,Wt=80;function gs({logs:t}){var S,k;const n=je(),[r,s]=i.useState(""),[a,l]=i.useState("all"),[x,c]=i.useState({}),w=`${a}\0${r}\0${t.length}\0${((S=t[0])==null?void 0:S.id)??""}\0${((k=t.at(-1))==null?void 0:k.id)??""}`,[u,y]=i.useState({key:w,count:_t}),p=i.useMemo(()=>hs(t,r,a),[a,t,r]),g=u.key===w?u.count:_t,M=p.slice(0,g);return e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"space-y-2 border-b border-[hsl(var(--deck-border))] px-4 py-3",children:[e.jsxs("div",{className:"flex h-8 items-center gap-2 rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-2 focus-within:border-[hsl(var(--deck-accent)/0.6)]",children:[e.jsx(mt,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("input",{type:"search","aria-label":n("preview.logs.searchAria"),placeholder:n("preview.logs.searchPlaceholder"),value:r,onChange:d=>s(d.target.value),className:"min-w-0 flex-1 bg-transparent font-mono text-[11px] text-[hsl(var(--deck-ink))] outline-none placeholder:text-[hsl(var(--deck-ink-faint))]"}),e.jsxs("span",{className:"font-mono text-[9px] tabular-nums text-[hsl(var(--deck-ink-faint))]",children:[p.length,"/",t.length]})]}),e.jsx("div",{className:"flex items-center gap-1","aria-label":n("preview.logs.filterAria"),children:["all","running","error","success"].map(d=>e.jsx("button",{type:"button","aria-pressed":a===d,onClick:()=>l(d),className:_("rounded-md border px-2 py-1 font-mono text-[9.5px] transition-colors",a===d?"border-[hsl(var(--deck-accent)/0.45)] bg-[hsl(var(--deck-accent-soft))] text-[hsl(var(--deck-accent))]":"border-[hsl(var(--deck-border))] text-[hsl(var(--deck-ink-faint))] hover:text-[hsl(var(--deck-ink-muted))]"),children:n(`preview.logs.filter.${d}`)},d))})]}),e.jsxs("div",{className:"min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-4",children:[t.length===0?e.jsx(zt,{title:n("preview.logs.emptyTitle"),subtitle:n("preview.logs.emptyHint")}):p.length===0?e.jsx(zt,{title:n("preview.logs.noMatches"),subtitle:n("preview.logs.noMatchesHint")}):M.map(d=>{var D;const L=x[d.id],O=(d.content||"").split(`
|
|
51
|
-
`),F=O.length>10||(((D=d.content)==null?void 0:D.length)||0)>800,j=L||!F?O:O.slice(0,8);return e.jsxs("div",{"data-preview-log-id":d.id,className:"overflow-hidden rounded-lg border border-[hsl(var(--deck-border))]",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"font-mono text-[12px] text-[hsl(var(--deck-ink))]",children:d.title}),d.subtitle&&e.jsx("div",{className:"font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:d.subtitle})]}),e.jsx(ks,{status:d.status})]}),d.content&&e.jsxs("div",{className:"space-y-2 px-3 py-3",children:[e.jsxs("pre",{className:"overflow-x-auto whitespace-pre-wrap rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] p-3 font-mono text-[12px] text-[hsl(var(--deck-ink))]",children:[j.join(`
|
|
52
|
-
`),!L&&F&&`
|
|
53
|
-
…`]}),F&&e.jsxs("button",{type:"button",onClick:()=>c(E=>({...E,[d.id]:!E[d.id]})),className:"flex items-center gap-1 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:text-[hsl(var(--deck-ink))]",children:[L?e.jsx(Qt,{className:"h-3 w-3"}):e.jsx(Yt,{className:"h-3 w-3"}),n(L?"preview.logs.collapse":"preview.logs.expand")]})]})]},d.id)}),g<p.length&&e.jsx("div",{className:"flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>y({key:w,count:Math.min(p.length,g+Wt)}),className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-3 py-1.5 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:border-[hsl(var(--deck-border-strong))] hover:text-[hsl(var(--deck-ink))]",children:n("preview.logs.showMore",{count:Math.min(Wt,p.length-g)})})})]})]})}function zt({title:t,subtitle:n}){return e.jsxs("div",{className:"rounded-lg border border-dashed border-[hsl(var(--deck-border))] p-6 text-center",children:[e.jsx("div",{className:"font-mono text-[13px] text-[hsl(var(--deck-ink))]",children:t}),e.jsx("div",{className:"mt-1 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:n})]})}function ks({status:t}){const n=je(),r=n(t==="success"?"preview.logs.status.success":t==="error"?"preview.logs.status.error":"preview.logs.status.running"),s=t==="success"?"bg-[#22C55E] text-white":t==="error"?"bg-[#FEE2E2] text-[#b91c1c] dark:bg-[#EF4444]/20 dark:text-[#fca5a5]":"bg-[hsl(var(--deck-surface))] text-[hsl(var(--deck-ink-muted))]";return e.jsx("span",{className:_("rounded-full px-2 py-0.5 font-mono text-[11px]",s),children:r})}const ws=640,nr=360,pt=960,As=i.forwardRef(function({open:n,maximized:r,disabled:s,onToggleMaximized:a,onTogglePreview:l},x){const c=je(),{locale:w}=at(),u=w==="zh"?{maximize:"全屏预览",restore:"还原分栏预览"}:{maximize:"Maximize preview",restore:"Restore split preview"},y=r?u.restore:u.maximize;return e.jsxs(e.Fragment,{children:[n&&e.jsx(q,{variant:"ghost",size:"icon","aria-pressed":!!r,"aria-label":y,title:y,onClick:a,className:_("hidden h-8 w-8 rounded-md text-[hsl(var(--deck-ink-faint))] hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] lg:inline-flex",r&&"bg-[hsl(var(--deck-surface))] text-[hsl(var(--deck-ink))]"),children:e.jsx(Jt,{className:_("h-4 w-4 transition-transform",r&&"rotate-180")})}),e.jsx(q,{ref:x,variant:"ghost",size:"icon",onClick:l,disabled:s,title:c("preview.title"),"aria-label":w==="zh"?"切换预览面板":"Toggle preview panel",className:_("h-8 w-8 rounded-md text-[hsl(var(--deck-ink-faint))] hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))]",n&&"bg-[hsl(var(--deck-accent-soft))] text-[hsl(var(--deck-accent))] hover:bg-[hsl(var(--deck-accent-soft))] hover:text-[hsl(var(--deck-accent))]"),children:e.jsx(st,{className:"h-4 w-4"})})]})});function Ut(t){const n=typeof window>"u"?pt:Math.max(280,Math.floor(window.innerWidth*.72));return Math.min(pt,n,Math.max(nr,Math.round(t)))}function ar(t,n,r){var s;if(t){const a=(s=r==null?void 0:r.taskDelivery)==null?void 0:s.status;return(r==null?void 0:r.taskIsolation)==="worktree"&&r.taskSourceProjectPath&&(a==="applied"||a==="discarded")?{sessionId:t.sessionId,projectPath:r.taskSourceProjectPath}:t}return n?{sessionId:`project:${n}`,projectPath:n}:null}function ft(){const t=z.getState();if(Qe(t.historySurfaceSelection))return null;const n=t.sessions.find(r=>Je({sessionId:r.sessionId,projectPath:r.projectPath},t.currentSessionRef));return ar(t.currentSessionRef,t.selectedProjectPath,n)}function Bt(t,n){const r=l=>l.replace(/\\/g,"/").replace(/^\.?\//,"").replace(/\/+/g,"/"),s=r(t),a=r(n);return s===a||s.endsWith(`/${a}`)||a.endsWith(`/${s}`)}const ys=i.lazy(async()=>({default:(await Lr(()=>import("./index-B5mUEr6D.js"),__vite__mapDeps([0,1]))).Editor}));function rt(t,n){return t instanceof Error?t.message:n}function Ms({returnFocusElement:t,maximized:n=!1}={}){var Nt,St;const r=je(),{toggleFilePreview:s,previewWidth:a,setPreviewWidth:l,previewTab:x,setPreviewTab:c,previewTargetPath:w,previewRequestId:u}=Et(),y=z(o=>o.messages),p=z(o=>o.currentSessionRef),g=z(o=>o.historySurfaceSelection),M=z(o=>o.sessions),S=z(o=>o.selectedProjectPath),k=i.useMemo(()=>M.find(o=>Je({sessionId:o.sessionId,projectPath:o.projectPath},p)),[p,M]),d=i.useMemo(()=>Qe(g)?null:ar(p,S,k),[k,p,g,S]),[L,O]=i.useState(x),[F,j]=i.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 1023px)").matches),[D,E]=i.useState(null),[ee,Ie]=i.useState(!1),[X,le]=i.useState([]),[Ne,ve]=i.useState({}),[I,ge]=i.useState({}),[A,te]=i.useState(0),[H,ke]=i.useState(!1),[T,ne]=i.useState(null),[U,re]=i.useState(""),[ae,ce]=i.useState([]),[oe,de]=i.useState(!1),[h,v]=i.useState(!1),[B,J]=i.useState(0),[Q,G]=i.useState(0),[De,V]=i.useState({}),[ue,se]=i.useState({}),[K,Se]=i.useState(null),[Ce,Fe]=i.useState(""),[Oe,qe]=i.useState(!1),[$e,Ee]=i.useState(null),[Xe,He]=i.useState(!1),Ye=i.useRef(d),fe=i.useRef(0),Ae=i.useRef(0),we=i.useRef({}),Ge=i.useRef(0),Me=i.useRef(0),he=i.useRef(0),ie=i.useRef({}),_e=i.useRef({}),Te=i.useRef({}),pe=i.useRef(null),f=i.useRef(null),m=i.useRef(null),N=i.useRef(null),P=i.useRef(a),Y=i.useRef(p),ye=i.useRef(null);i.useLayoutEffect(()=>{Je(Ye.current,d)||(fe.current+=1),Ye.current=d},[d]),i.useEffect(()=>{if(typeof window.matchMedia!="function")return;const o=window.matchMedia("(max-width: 1023px)"),b=()=>j(o.matches);return b(),o.addEventListener("change",b),()=>o.removeEventListener("change",b)},[]),i.useEffect(()=>(N.current=t??(document.activeElement instanceof HTMLElement?document.activeElement:null),()=>{const o=N.current;requestAnimationFrame(()=>{o!=null&&o.isConnected&&o.focus({preventScroll:!0})})}),[t]),i.useEffect(()=>{var o;F&&((o=m.current)==null||o.focus({preventScroll:!0}))},[F]);const Re=o=>{var W;if(!F)return;if(o.key==="Escape"){o.preventDefault(),s();return}if(o.key!=="Tab")return;const b=Array.from(((W=f.current)==null?void 0:W.querySelectorAll('button:not([disabled]), input:not([disabled]), [href], [tabindex]:not([tabindex="-1"])'))??[]).filter($=>!$.closest("[hidden]"));if(b.length===0)return;const R=b[0],C=b[b.length-1];o.shiftKey&&document.activeElement===R?(o.preventDefault(),C==null||C.focus()):!o.shiftKey&&document.activeElement===C&&(o.preventDefault(),R==null||R.focus())},Ve=(o,b)=>b===fe.current&&Je(ft(),o),xt=async(o,b="")=>{const R=b?`/suggestions/files/tree?path=${encodeURIComponent(b)}`:"/suggestions/files/tree",C=await fetch(R,{headers:dt(o)});if(!C.ok)throw new Error(r("preview.files.treeFailed"));return(await C.json()).map($=>({...$,children:$.type==="dir"?[]:void 0}))};i.useEffect(()=>{const o=++Ae.current;return(async()=>{if(!d){le([]),ke(!1),ne(null);return}const R={...d},C=fe.current,W=()=>o===Ae.current&&Ve(R,C);if(W()){le([]),ke(!0),ne(null);try{const $=await xt(R);W()&&le($)}catch($){W()&&ne(rt($,r("preview.files.treeFailed")))}finally{W()&&ke(!1)}}})(),()=>{Ae.current===o&&(Ae.current+=1)}},[A,d==null?void 0:d.projectPath,d==null?void 0:d.sessionId]),i.useEffect(()=>{pe.current=null,ie.current={},_e.current={},Te.current={},we.current={},Ge.current+=1,Se(null),Fe(""),qe(!1),Ee(null),He(!1),V({}),ve({}),ge({}),re(""),ce([]),de(!1),v(!1),G(0),se({})},[d==null?void 0:d.projectPath,d==null?void 0:d.sessionId]);const or=i.useMemo(()=>Ns(y),[y]),[ir,bt]=i.useState(null),[lr,ot]=i.useState(!1),[vt,gt]=i.useState(null),[cr,dr]=i.useState(0),it=(k==null?void 0:k.taskIsolation)==="worktree"&&((Nt=k.taskDelivery)==null?void 0:Nt.status)==="discarded",kt=(k==null?void 0:k.taskIsolation)==="worktree"&&!!k.taskDiffStat&&!it,wt=kt&&!!(k!=null&&k.taskDiffStat&&k.taskDiffStat.changedFiles>0),Le=it?[]:kt?ir??[]:or,ur=i.useMemo(()=>js(y),[y]);i.useEffect(()=>{const o=U.trim(),b=++Me.current;if(G(0),v(!1),!o||L!=="files"||!d){ce([]),de(!1);return}const R={...d},C=fe.current;de(!0);const W=window.setTimeout(()=>{fetch(`/suggestions/files?q=${encodeURIComponent(o)}&limit=100&type=file`,{headers:dt(R)}).then(async $=>{if(!$.ok)throw new Error(r("preview.files.searchFailed"));return await $.json()}).then($=>{b===Me.current&&Ve(R,C)&&(ce($.filter(me=>!me.endsWith("/"))),v(!1))}).catch(()=>{b===Me.current&&Ve(R,C)&&(ce([]),v(!0))}).finally(()=>{b===Me.current&&de(!1)})},160);return()=>window.clearTimeout(W)},[L,U,B,d==null?void 0:d.projectPath,d==null?void 0:d.sessionId]),i.useEffect(()=>{O(Et.getState().previewTab)},[u]),i.useEffect(()=>{const o=Y.current;if(Y.current=p,p||!S){ye.current=null;return}const b=!!o||ye.current!==S;ye.current=S,b&&L==="diff"&&(O("files"),c("files"))},[L,p==null?void 0:p.projectPath,p==null?void 0:p.sessionId,S,c]),i.useEffect(()=>{var R;if(!w||L!=="diff")return;const o=(R=Le.find(C=>C.filePath&&Bt(C.filePath,w)))==null?void 0:R.filePath;if(!o)return;se(C=>({...C,[o]:!0}));const b=requestAnimationFrame(()=>{var W,$;const C=Array.from(((W=f.current)==null?void 0:W.querySelectorAll("[data-preview-diff-path]"))??[]).find(me=>Bt(me.dataset.previewDiffPath??"",w));typeof(C==null?void 0:C.scrollIntoView)=="function"&&C.scrollIntoView({block:"nearest",behavior:"smooth"}),($=C==null?void 0:C.querySelector("button"))==null||$.focus({preventScroll:!0})});return()=>cancelAnimationFrame(b)},[L,Le,u,w]),i.useEffect(()=>{const o=++he.current;if(bt(null),gt(null),ot(!1),Qe(g)||!p||!wt)return;const b={...p};return ot(!0),Er.getTaskDiff(b).then(R=>{o!==he.current||!Je(z.getState().currentSessionRef,b)||bt(R.files.map(C=>({filePath:C.path,diff:{patch:C.patch},summary:C.binary?"binary":`+${C.additions} -${C.deletions}${C.truncated?" (truncated)":""}`})))}).catch(R=>{o===he.current&>(rt(R,r("preview.diff.failedTitle")))}).finally(()=>{o===he.current&&ot(!1)}),()=>{he.current===o&&(he.current+=1)}},[k==null?void 0:k.taskCompletedAt,(St=k==null?void 0:k.taskDelivery)==null?void 0:St.status,k==null?void 0:k.taskDiffStat,k==null?void 0:k.taskIsolation,p,g,wt,cr]);const fr=o=>{se(b=>({...b,[o]:!b[o]}))},hr=o=>{se(Object.fromEntries(Le.map(b=>[b.filePath||"unknown",o])))},Ze=async o=>{const b=ft();if(!b)return;const R=fe.current,C=++Ge.current,W=()=>C===Ge.current&&pe.current===o&&Ve(b,R);pe.current=o,Se(o),Fe(""),qe(!0),Ee(null),He(!1);try{const $=await fetch(`/suggestions/files/content?path=${encodeURIComponent(o)}`,{headers:dt(b)});if(!$.ok)throw new Error(r("preview.files.contentFailed"));const me=await $.json();W()&&(Fe(me.content||""),He(!!me.truncated))}catch($){W()&&Ee(rt($,r("preview.files.contentFailed")))}finally{W()&&qe(!1)}},pr=o=>{if(o.key==="ArrowDown"||o.key==="ArrowUp"){o.preventDefault(),G(b=>ms(b,ae.length,o.key==="ArrowDown"?1:-1));return}if(o.key==="Enter"){const b=ae[Q];if(!b)return;o.preventDefault(),Ze(b);return}o.key==="Escape"&&(o.preventDefault(),re(""))},lt=(o,b)=>{const R={...Te.current,[o]:b};Te.current=R,ge(R)},yt=async o=>{const b=(we.current[o]??0)+1;we.current[o]=b,lt(o,{status:"loading"});const R=ft();if(!R)return;const C=fe.current,W=()=>we.current[o]===b&&ie.current[o]===!0&&Ve(R,C);try{const $=await xt(R,o);if(W()){const me={..._e.current,[o]:$};_e.current=me,ve(me),lt(o,{status:"loaded"})}}catch($){W()&<(o,{status:"error",message:rt($,r("preview.files.treeFailed"))})}},mr=o=>{const b=!ie.current[o],R={...ie.current,[o]:b};if(ie.current=R,V(R),!b){we.current[o]=(we.current[o]??0)+1;return}_e.current[o]||yt(o)},xr=o=>{if(!ie.current[o]){const b={...ie.current,[o]:!0};ie.current=b,V(b)}yt(o)},br=o=>{o.preventDefault(),o.currentTarget.setPointerCapture(o.pointerId),P.current=a,Ie(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},vr=o=>{if(!ee)return;const b=Ut(window.innerWidth-o.clientX);P.current=b,E(b)},jt=o=>{ee&&(o.currentTarget.hasPointerCapture(o.pointerId)&&o.currentTarget.releasePointerCapture(o.pointerId),Ie(!1),E(null),l(P.current),document.body.style.cursor="",document.body.style.userSelect="")};i.useEffect(()=>()=>{document.body.style.cursor="",document.body.style.userSelect=""},[]);const ct=Ut(D??a);return Qe(g)?null:e.jsxs("div",{ref:f,"data-testid":"file-preview",role:F?"dialog":"complementary","aria-modal":F||void 0,"aria-label":r("preview.title"),onKeyDown:Re,style:n?{width:"100%",maxWidth:"none"}:{width:ct,maxWidth:"72vw"},className:_("relative flex h-full flex-col bg-[hsl(var(--deck-canvas))] max-lg:fixed max-lg:inset-0 max-lg:z-[60] max-lg:!h-dvh max-lg:!w-full max-lg:!max-w-full max-lg:min-w-0 max-lg:border-l-0",n?"absolute inset-0 z-20 min-w-0 border-l-0 shadow-none":"border-l shadow-xl min-w-[360px] shrink-0 border-[hsl(var(--deck-border))]"),children:[!n&&e.jsx("div",{role:"separator","aria-label":r("preview.action.resize"),"aria-orientation":"vertical","aria-valuemin":nr,"aria-valuemax":pt,"aria-valuenow":ct,"aria-hidden":F||void 0,tabIndex:F?-1:0,onPointerDown:br,onPointerMove:vr,onPointerUp:jt,onPointerCancel:jt,onDoubleClick:()=>l(ws),onKeyDown:o=>{o.key!=="ArrowLeft"&&o.key!=="ArrowRight"||(o.preventDefault(),l(ct+(o.key==="ArrowLeft"?24:-24)))},className:_("absolute inset-y-0 -left-1 z-20 w-2 cursor-col-resize touch-none outline-none max-lg:hidden","after:absolute after:inset-y-0 after:left-1/2 after:w-px after:-translate-x-1/2 after:bg-transparent after:transition-colors","hover:after:bg-[hsl(var(--deck-accent)/0.6)] focus-visible:after:bg-[hsl(var(--deck-accent))]",ee&&"after:bg-[hsl(var(--deck-accent))]")}),e.jsxs(Gr,{value:L,onValueChange:o=>{const b=o;O(b),c(b)},className:"flex flex-col flex-1 min-h-0",children:[e.jsxs("div",{"data-preview-toolbar":!0,className:"flex shrink-0 items-center gap-2 border-b border-[hsl(var(--deck-border))] px-3 py-3",children:[e.jsxs(Vr,{className:"grid h-9 min-w-0 flex-1 grid-cols-4 rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] p-1",children:[e.jsx(et,{value:"diff",className:"px-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))] data-[state=active]:bg-[hsl(var(--deck-canvas-veil))] data-[state=active]:text-[hsl(var(--deck-ink))]",children:r("preview.tab.diff")}),e.jsx(et,{value:"files",className:"px-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))] data-[state=active]:bg-[hsl(var(--deck-canvas-veil))] data-[state=active]:text-[hsl(var(--deck-ink))]",children:r("preview.tab.files")}),e.jsx(et,{value:"logs",className:"px-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))] data-[state=active]:bg-[hsl(var(--deck-canvas-veil))] data-[state=active]:text-[hsl(var(--deck-ink))]",children:r("preview.tab.logs")}),e.jsx(et,{value:"browser",className:"px-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))] data-[state=active]:bg-[hsl(var(--deck-canvas-veil))] data-[state=active]:text-[hsl(var(--deck-ink))]",children:r("preview.tab.browser")})]}),F&&e.jsx(q,{ref:m,variant:"ghost",size:"icon",onClick:s,"aria-label":r("preview.action.close"),title:r("preview.action.close"),className:"h-9 w-9 shrink-0 rounded-md text-[hsl(var(--deck-ink-faint))] hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))]",children:e.jsx(Tr,{className:"w-4 h-4"})})]}),e.jsx(tt,{value:"diff",className:"overflow-hidden flex-1 mt-0",children:e.jsx("div",{className:"overflow-y-auto px-4 py-4 space-y-3 h-full",children:it?e.jsx(Pe,{title:r("preview.diff.discardedTitle"),subtitle:r("preview.diff.discardedHint"),role:"status"}):lr&&Le.length===0?e.jsx(Pe,{title:r("preview.diff.loadingTitle"),subtitle:r("preview.diff.loadingHint")}):vt&&Le.length===0?e.jsx(Pe,{title:r("preview.diff.failedTitle"),subtitle:vt,actionLabel:r("preview.action.retry"),onAction:()=>dr(o=>o+1),role:"alert"}):Le.length===0?e.jsx(Pe,{title:r("preview.diff.emptyTitle"),subtitle:r("preview.diff.emptyHint")}):e.jsx(xs,{diffs:Le,expanded:ue,targetPath:w,onToggle:fr,onSetAllExpanded:hr})})}),e.jsx(tt,{value:"files",className:"overflow-hidden flex-1 mt-0",children:e.jsxs("div",{className:"px-4 py-4 h-full",children:[H&&e.jsx(Pe,{title:r("preview.files.loadingTitle"),subtitle:r("preview.files.loadingHint")}),!H&&T&&e.jsx(Pe,{title:r("preview.files.failedTitle"),subtitle:T,actionLabel:r("preview.action.retry"),onAction:()=>te(o=>o+1),role:"alert"}),!H&&!T&&X.length===0&&e.jsx(Pe,{title:r("preview.files.emptyTitle"),subtitle:r("preview.files.emptyHint")}),!H&&!T&&X.length>0&&e.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[minmax(170px,220px)_minmax(0,1fr)] gap-3 max-sm:grid-cols-1 max-sm:grid-rows-[180px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"flex min-h-0 flex-col overflow-hidden rounded-lg border border-[hsl(var(--deck-border))]",children:[e.jsx("div",{className:"border-b border-[hsl(var(--deck-border))] p-2",children:e.jsxs("div",{className:"flex h-8 items-center gap-2 rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-2 focus-within:border-[hsl(var(--deck-accent)/0.6)]",children:[e.jsx(mt,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("input",{type:"search","aria-label":r("preview.files.searchAria"),placeholder:r("preview.files.searchPlaceholder"),value:U,onChange:o=>re(o.target.value),onKeyDown:pr,className:"min-w-0 flex-1 bg-transparent font-mono text-[11px] text-[hsl(var(--deck-ink))] outline-none placeholder:text-[hsl(var(--deck-ink-faint))]"}),oe&&e.jsx(Be,{className:"h-3 w-3 shrink-0 animate-spin text-[hsl(var(--deck-accent))]"})]})}),e.jsx("div",{role:U?"listbox":void 0,"aria-label":U?r("preview.files.searchResultsAria"):void 0,className:"overflow-y-auto flex-1 p-2 min-h-0",children:U?h?e.jsxs("div",{role:"alert",className:"px-2 py-5 text-center font-mono text-[10.5px] text-red-700 dark:text-red-300",children:[e.jsx("div",{children:r("preview.files.searchFailed")}),e.jsx("button",{type:"button",onClick:()=>J(o=>o+1),className:"mt-1 underline underline-offset-2",children:r("preview.action.retry")})]}):ae.length>0?ae.map((o,b)=>e.jsxs("button",{type:"button",role:"option","aria-selected":b===Q,"data-preview-file-result":b,onMouseEnter:()=>G(b),onClick:()=>void Ze(o),className:_("mb-0.5 flex w-full min-w-0 flex-col rounded-md px-2 py-1.5 text-left font-mono transition-colors",b===Q?"bg-[hsl(var(--deck-accent-soft))] text-[hsl(var(--deck-ink))]":"text-[hsl(var(--deck-ink-muted))] hover:bg-[hsl(var(--deck-surface))]"),children:[e.jsx("span",{className:"truncate text-[11.5px]",children:rr(o)}),e.jsx("span",{className:"truncate text-[9px] text-[hsl(var(--deck-ink-faint))]",children:o})]},o)):!oe&&e.jsx("div",{className:"px-2 py-5 text-center font-mono text-[10.5px] text-[hsl(var(--deck-ink-faint))]",children:r("preview.files.noMatches")}):e.jsx(vs,{nodes:X,expandedDirs:De,childrenCache:Ne,directoryStates:I,selectedPath:K,onToggleDir:mr,onRetryDir:xr,onSelectFile:Ze})})]}),e.jsxs("div",{className:"border border-[hsl(var(--deck-border))] rounded-lg overflow-hidden flex flex-col min-h-0",children:[e.jsxs("div",{className:"px-3 py-2 bg-[hsl(var(--deck-surface-2))] border-b border-[hsl(var(--deck-border))] text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono flex items-center justify-between",children:[e.jsx("span",{className:"min-w-0 truncate",children:K||r("preview.files.selectTitle")}),K&&e.jsx("span",{className:"ml-2 shrink-0 text-[11px] text-[hsl(var(--deck-ink-faint))] font-mono",children:r(Oe?"preview.files.status.loading":Xe?"preview.files.status.truncated":"preview.files.status.ready")})]}),Xe&&!Oe&&e.jsx("div",{className:"px-3 py-2 bg-[#FEF3C7] dark:bg-[#111113] border-b border-[hsl(var(--deck-border))] text-[11px] text-[#b45309] dark:text-[#facc15] font-mono",children:r("preview.files.truncatedNotice")}),e.jsxs("div",{className:"flex-1 min-h-0",children:[!K&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:r("preview.files.pickHint")}),K&&$e&&e.jsxs("div",{role:"alert",className:"flex h-full flex-col items-center justify-center gap-2 px-4 text-center font-mono text-[12px] text-[#DC2626] dark:text-[#fca5a5]",children:[e.jsx("span",{children:$e}),e.jsx("button",{type:"button",onClick:()=>void Ze(K),className:"underline underline-offset-2",children:r("preview.action.retry")})]}),K&&!$e&&e.jsx("div",{className:"h-full",children:Oe?e.jsx(Gt,{}):e.jsx(i.Suspense,{fallback:e.jsx(Gt,{}),children:e.jsx(Ss,{content:Ce,filename:K})})})]})]})]})]})}),e.jsx(tt,{value:"logs",className:"overflow-hidden flex-1 mt-0",children:e.jsx(gs,{logs:ur})}),e.jsx(tt,{value:"browser",forceMount:!0,className:"overflow-hidden flex-1 min-h-0",children:e.jsx(fs,{sessionRef:p,onElementAdded:()=>{F&&s()}})})]})]})}function Pe({title:t,subtitle:n,actionLabel:r,onAction:s,role:a}){return e.jsxs("div",{role:a,className:"border border-dashed border-[hsl(var(--deck-border))] rounded-lg p-6 text-center",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:t}),e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono mt-1",children:n}),r&&s&&e.jsx("button",{type:"button",onClick:s,className:"mt-3 rounded-md border border-[hsl(var(--deck-border))] px-2.5 py-1 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))]",children:r})]})}function js(t){return t.flatMap(n=>{var a,l,x;const r=[];if((a=n.agentContent)!=null&&a.toolCalls)for(const c of n.agentContent.toolCalls){const w=Ht(c.arguments),u=c.output,y=u?(l=Ue(u))!=null&&l.diff?qt(u):u:void 0;r.push({id:`${n.id}-${c.toolCallId}`,title:c.toolName||"Tool",subtitle:c.summary,status:c.status==="success"?"success":c.status==="error"?"error":"running",content:y||(w?`Arguments:
|
|
54
|
-
${w}`:void 0),timestamp:n.timestamp})}const s=n.metadata;if(s){if(s.kind==="tool_call"){const c=s.toolName||"Tool",w=Ht(s.arguments);r.push({id:n.id,title:`Tool Call · ${c}`,subtitle:s.toolKind?String(s.toolKind):void 0,status:s.status==="success"?"success":s.status==="error"?"error":"running",content:w?`Arguments:
|
|
55
|
-
${w}`:void 0,timestamp:n.timestamp})}if(s.kind==="tool_result"){const c=s.toolName||"Tool",w=s.success,u=s.summary,y=s.output,p=y?(x=Ue(y))!=null&&x.diff?qt(y):y:void 0;r.push({id:n.id,title:`Tool Result · ${c}`,subtitle:u,status:w===void 0?"running":w?"success":"error",content:p,timestamp:n.timestamp})}}return r})}function Ns(t){var s;const n=[],r=new Set;for(let a=t.length-1;a>=0;a-=1){const l=t[a];if((s=l.agentContent)!=null&&s.toolCalls)for(let y=l.agentContent.toolCalls.length-1;y>=0;y-=1){const p=l.agentContent.toolCalls[y],g=p.metadata;if((g==null?void 0:g.kind)==="patch"&&Array.isArray(g.changes)){Ot(n,r,g.changes,p.summary);continue}const M=p.output||"",S=Ue(M)||Ue((g==null?void 0:g.diff_snippet)||"");if(S!=null&&S.diff){const k=(g==null?void 0:g.file_path)||p.toolName||"unknown";if(!r.has(k)){r.add(k);const d=typeof(g==null?void 0:g.oldContent)=="string"?g.oldContent:void 0,L=typeof(g==null?void 0:g.newContent)=="string"?g.newContent:void 0;n.push({diff:S.diff,filePath:k,summary:p.summary,oldContent:d,newContent:L})}}}const x=l.metadata;if(!x||x.kind!=="tool_result")continue;const c=x.metadata;if((c==null?void 0:c.kind)==="patch"&&Array.isArray(c.changes)){Ot(n,r,c.changes,x.summary);continue}const w=x.output||(typeof l.content=="string"?l.content:"")||"",u=Ue(w)||Ue((c==null?void 0:c.diff_snippet)||"");if(u!=null&&u.diff){const y=(c==null?void 0:c.file_path)||x.toolName||"unknown";if(!r.has(y)){r.add(y);const p=typeof(c==null?void 0:c.oldContent)=="string"?c.oldContent:void 0,g=typeof(c==null?void 0:c.newContent)=="string"?c.newContent:void 0;n.push({diff:u.diff,filePath:y,summary:x.summary,oldContent:p,newContent:g})}}}return n.reverse()}function Ot(t,n,r,s){for(let a=r.length-1;a>=0;a--){const l=r[a];!l||typeof l!="object"||!("path"in l)||typeof l.path!="string"||!("diff"in l)||typeof l.diff!="string"||n.has(l.path)||(n.add(l.path),t.push({diff:{patch:l.diff,startLine:1,matchLine:1},filePath:l.path,summary:s,oldContent:"oldContent"in l&&typeof l.oldContent=="string"?l.oldContent:void 0,newContent:"newContent"in l&&typeof l.newContent=="string"?l.newContent:void 0}))}}function Ue(t){if(!t)return null;const n=/<<<DIFF>>>\s*([\s\S]*?)\s*<<<\/DIFF>>>/m,r=t.match(n);if(!r)return null;try{return{diff:JSON.parse(r[1])}}catch{return null}}function qt(t){return t?t.replace(/<<<DIFF>>>[\s\S]*?<<<\/DIFF>>>/m,"").trim():""}function Ht(t){if(!t)return"";if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return JSON.stringify(t,null,2)}function Gt(){const t=je();return e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:t("preview.files.editorLoading")})}function Ss({content:t,filename:n}){const{codeTheme:r}=Rr(),s=i.useRef(null),[a,l]=i.useState("vs-dark"),x=Cs(n),c=w=>{s.current=w;const u=It(w,r);l(u)};return i.useEffect(()=>{if(s.current){const w=It(s.current,r);l(w)}},[r]),e.jsx(ys,{value:t,language:x,theme:a,height:"100%",beforeMount:c,options:{readOnly:!0,minimap:{enabled:!1},fontSize:12,lineNumbers:"on",wordWrap:"on",scrollBeyondLastLine:!1,automaticLayout:!0}},n)}function Cs(t){var s;const n=((s=t.split(".").pop())==null?void 0:s.toLowerCase())||"";return{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",json:"json",md:"markdown",css:"css",scss:"scss",html:"html",yml:"yaml",yaml:"yaml",go:"go",rs:"rust",py:"python",java:"java",c:"c",cpp:"cpp",h:"cpp",hpp:"cpp",sh:"shell",zsh:"shell",toml:"toml",xml:"xml"}[n]||"plaintext"}export{Ms as FilePreview,As as PreviewControls};
|