blade-code 0.10.136 → 0.10.138

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-03zfvfen.js +10 -0
  3. package/dist/{chunk-82x77b2p.js → chunk-14j2dbd6.js} +2 -2
  4. package/dist/{chunk-24rsvr6e.js → chunk-16648v5c.js} +1 -1
  5. package/dist/{chunk-77x1rrz9.js → chunk-1bqatrxs.js} +1 -1
  6. package/dist/chunk-23c4pys6.js +23 -0
  7. package/dist/{chunk-hx10bph0.js → chunk-2m79vd9p.js} +1 -1
  8. package/dist/{chunk-w2n1vwzg.js → chunk-2t0wp7gm.js} +2 -2
  9. package/dist/chunk-303b3x5q.js +1 -0
  10. package/dist/{chunk-wzkh3e6a.js → chunk-3eskgvpy.js} +1 -1
  11. package/dist/chunk-3g2z6hae.js +1 -0
  12. package/dist/chunk-3t5r41yh.js +1 -0
  13. package/dist/{chunk-ntd69c0k.js → chunk-516adpx6.js} +1 -1
  14. package/dist/{chunk-9z9v8v4j.js → chunk-56py3ryh.js} +1 -1
  15. package/dist/chunk-59980a8h.js +1 -0
  16. package/dist/{chunk-6rvrx275.js → chunk-5bfvdy62.js} +2 -2
  17. package/dist/chunk-5gy3x011.js +1 -0
  18. package/dist/{chunk-q0s3gcjm.js → chunk-5j68055h.js} +1 -1
  19. package/dist/{chunk-91pb41e7.js → chunk-5v1pjexj.js} +1 -1
  20. package/dist/chunk-5xgyx25z.js +2 -0
  21. package/dist/{chunk-bdtpq7j9.js → chunk-65c3vjwm.js} +1 -1
  22. package/dist/{chunk-wj16pvvn.js → chunk-6ezffjq1.js} +1 -1
  23. package/dist/{chunk-kbnxbb23.js → chunk-6qhbdcse.js} +2 -2
  24. package/dist/{chunk-nzwh9v6t.js → chunk-7j4s1nrc.js} +1 -1
  25. package/dist/chunk-7vdf66jp.js +171 -0
  26. package/dist/chunk-8cnxy251.js +1 -0
  27. package/dist/chunk-8cqm87j5.js +1 -0
  28. package/dist/chunk-8py443a5.js +1 -0
  29. package/dist/{chunk-yacv7f7h.js → chunk-8rccn1y2.js} +1 -1
  30. package/dist/{chunk-v2qxszks.js → chunk-92n2p24j.js} +2 -2
  31. package/dist/{chunk-r51afpkk.js → chunk-9m7d3ajv.js} +1 -1
  32. package/dist/{chunk-mq1mk3v5.js → chunk-a5hkv8er.js} +2 -2
  33. package/dist/chunk-ar85hxx2.js +5 -0
  34. package/dist/{chunk-mm1atkae.js → chunk-atdq9btn.js} +2 -2
  35. package/dist/{chunk-fnc97xg7.js → chunk-awheqy52.js} +2 -2
  36. package/dist/{chunk-sv5z5sna.js → chunk-az08pq83.js} +1 -1
  37. package/dist/chunk-bq6d0v5b.js +2 -0
  38. package/dist/{chunk-c85xvthj.js → chunk-byeq45rv.js} +1 -1
  39. package/dist/{chunk-g4vgnxh4.js → chunk-d11mqbqk.js} +1 -1
  40. package/dist/{chunk-vvawhvea.js → chunk-d64b7wta.js} +1 -1
  41. package/dist/chunk-ddcz0nwv.js +1 -0
  42. package/dist/{chunk-jc28ddt0.js → chunk-dv2m2xe5.js} +1 -1
  43. package/dist/chunk-e71y87zg.js +1 -0
  44. package/dist/{chunk-1p9sjb8d.js → chunk-earhezc8.js} +1 -1
  45. package/dist/{chunk-qm96k94k.js → chunk-ec7ykyqz.js} +3 -3
  46. package/dist/{chunk-ffh4c30x.js → chunk-egadh3e9.js} +1 -1
  47. package/dist/{chunk-jb8stg10.js → chunk-fbrdcveb.js} +1 -1
  48. package/dist/{chunk-1pmvyqed.js → chunk-fndqbf45.js} +1 -1
  49. package/dist/chunk-ft1bdqbs.js +3 -0
  50. package/dist/{chunk-hqwpnb0x.js → chunk-gcg56vaw.js} +2 -2
  51. package/dist/chunk-h2gp7smy.js +1 -0
  52. package/dist/{chunk-46jmq302.js → chunk-he0f6h5q.js} +1 -1
  53. package/dist/{chunk-tev70rzj.js → chunk-hrcz179j.js} +2 -2
  54. package/dist/{chunk-qjydadex.js → chunk-j21hez8g.js} +5 -5
  55. package/dist/{chunk-c5rfnzhf.js → chunk-j58wrt5n.js} +4 -4
  56. package/dist/{chunk-s3a017q7.js → chunk-jb4hmk56.js} +2 -2
  57. package/dist/{chunk-zy2etr3v.js → chunk-jy7k2dwm.js} +2 -2
  58. package/dist/{chunk-xtngc0th.js → chunk-k10d8t4f.js} +1 -1
  59. package/dist/chunk-mc2mr1kn.js +2 -0
  60. package/dist/{chunk-0qq64xqm.js → chunk-mjnkxem3.js} +4 -4
  61. package/dist/chunk-n2tfj82m.js +1 -0
  62. package/dist/{chunk-1cbaqh71.js → chunk-nnas8tdt.js} +2 -2
  63. package/dist/{chunk-gdnyt8a7.js → chunk-npc7jt96.js} +1 -1
  64. package/dist/{chunk-mxe4pr8t.js → chunk-nqts5by0.js} +2 -2
  65. package/dist/chunk-nyw686sf.js +6 -0
  66. package/dist/chunk-pty1ncam.js +6 -0
  67. package/dist/chunk-qdjqbgts.js +1 -0
  68. package/dist/{chunk-cgkbdh2m.js → chunk-r7bv1hmq.js} +1 -1
  69. package/dist/{chunk-f7hsagj6.js → chunk-rhwkvx96.js} +1 -1
  70. package/dist/{chunk-na3nregt.js → chunk-t88sfhjj.js} +1 -1
  71. package/dist/{chunk-13sdjfks.js → chunk-v2fewxvw.js} +2 -2
  72. package/dist/chunk-wv1mnf2m.js +1 -0
  73. package/dist/{chunk-sy0vxdc3.js → chunk-y66f1t18.js} +387 -387
  74. package/dist/{chunk-5sknjz9b.js → chunk-yvmexv2c.js} +1 -1
  75. package/dist/{chunk-g45camrd.js → chunk-z9qv0d6k.js} +1 -1
  76. package/dist/{chunk-z3hpstky.js → chunk-zx78c1an.js} +1 -1
  77. package/dist/web/assets/ChatView-CZLmEMBO.js +63 -0
  78. package/dist/web/assets/{CodeBlockHighlighter-41xRPXs2.js → CodeBlockHighlighter-6-iPmomS.js} +1 -1
  79. package/dist/web/assets/{FilePreview-lcc_hL7J.js → FilePreview-D0aSwNF3.js} +7 -7
  80. package/dist/web/assets/{KanbanBoard-BHgM338V.js → KanbanBoard-xPziptbY.js} +2 -2
  81. package/dist/web/assets/{MarkdownRenderer-BMAuTkc6.js → MarkdownRenderer-TWNqhwrr.js} +3 -3
  82. package/dist/web/assets/{ScrollArea-DJq2Kdpi.js → ScrollArea-CSQyGeWr.js} +1 -1
  83. package/dist/web/assets/{SessionHistorySurface-DSe8ePBJ.js → SessionHistorySurface-PRpOrUav.js} +1 -1
  84. package/dist/web/assets/{SettingsModal-Cih4bWul.js → SettingsModal-Ds-Uf-3r.js} +5 -10
  85. package/dist/web/assets/{Sidebar-DnWlUKmO.js → Sidebar-D6VyjkRY.js} +2 -2
  86. package/dist/web/assets/{TaskSwitcher-D3mrXv_i.js → TaskSwitcher-BEsAgt0k.js} +1 -1
  87. package/dist/web/assets/{TerminalPanel-BNKHhBVM.js → TerminalPanel-C_2lnmKH.js} +1 -1
  88. package/dist/web/assets/{archive-Dof4YpyT.js → archive-CPBIxP8f.js} +1 -1
  89. package/dist/web/assets/{arrow-left-DGFXaGox.js → arrow-left-z3DhPgf-.js} +1 -1
  90. package/dist/web/assets/{calendar-clock-BoxUNOvH.js → calendar-clock-tYt1E6zR.js} +1 -1
  91. package/dist/web/assets/{chevron-right-Brb1rhaA.js → chevron-right-BGTvSaVS.js} +1 -1
  92. package/dist/web/assets/{chevrons-up-down-N-VshXV_.js → chevrons-up-down-Jw3ElnjQ.js} +1 -1
  93. package/dist/web/assets/{clock-3-gdZEKe2U.js → clock-3-v0h4RrLK.js} +1 -1
  94. package/dist/web/assets/{copy-d9M8JUfQ.js → copy-CF3TUa0u.js} +1 -1
  95. package/dist/web/assets/{download-CQ-Pwfq0.js → download-ZG8PfhmH.js} +1 -1
  96. package/dist/web/assets/{external-link-GRAtjoO2.js → external-link-BKCjDDt-.js} +1 -1
  97. package/dist/web/assets/{folder-CqLD0IBh.js → folder-M-NM2bQG.js} +1 -1
  98. package/dist/web/assets/index-DC2p1vGD.css +1 -0
  99. package/dist/web/assets/index-VQVOzFZT.js +203 -0
  100. package/dist/web/assets/{pause-BqsFgQi0.js → pause-CP_wlUro.js} +1 -1
  101. package/dist/web/assets/{pencil-Ca9289F-.js → pencil-U3n9D8ed.js} +1 -1
  102. package/dist/web/assets/{play-DmEPnYDS.js → play-NBWnc2gU.js} +1 -1
  103. package/dist/web/assets/{plus-kIBLgk0p.js → plus-CmPqJgff.js} +1 -1
  104. package/dist/web/assets/session-events-DKjIMNKI.js +29 -0
  105. package/dist/web/assets/{settings-BuSrJl6s.js → settings-CVFpbh_y.js} +1 -1
  106. package/dist/web/assets/team-B9Na0Ocd.js +6 -0
  107. package/dist/web/assets/{teamService-B7Fp8Oyg.js → teamService-ZQZLqsjy.js} +1 -1
  108. package/dist/web/assets/{terminal-Qkr_gcNu.js → terminal-BdmigqIS.js} +1 -1
  109. package/dist/web/index.html +2 -2
  110. package/package.json +1 -1
  111. package/dist/chunk-1dscf8xj.js +0 -23
  112. package/dist/chunk-1n5d6b5k.js +0 -1
  113. package/dist/chunk-1qdemrkr.js +0 -1
  114. package/dist/chunk-83nxcfz3.js +0 -1
  115. package/dist/chunk-9y7j565j.js +0 -6
  116. package/dist/chunk-acsfh1cw.js +0 -5
  117. package/dist/chunk-as8stb2j.js +0 -10
  118. package/dist/chunk-azaqc1b6.js +0 -1
  119. package/dist/chunk-e1warjkn.js +0 -171
  120. package/dist/chunk-g13jmewd.js +0 -1
  121. package/dist/chunk-g7h0peka.js +0 -3
  122. package/dist/chunk-gq7fdc8c.js +0 -2
  123. package/dist/chunk-gwjah260.js +0 -1
  124. package/dist/chunk-n238rdz8.js +0 -1
  125. package/dist/chunk-nfzad4te.js +0 -2
  126. package/dist/chunk-pnanbvn3.js +0 -1
  127. package/dist/chunk-pz91qga3.js +0 -1
  128. package/dist/chunk-s4b1r3my.js +0 -1
  129. package/dist/chunk-t6cajkaj.js +0 -6
  130. package/dist/chunk-tah2002b.js +0 -1
  131. package/dist/chunk-tzfd2fza.js +0 -1
  132. package/dist/chunk-v3veeja5.js +0 -1
  133. package/dist/chunk-vptn8fhx.js +0 -2
  134. package/dist/chunk-wj813rcc.js +0 -1
  135. package/dist/web/assets/ChatView-Bc9twpWM.js +0 -63
  136. package/dist/web/assets/index-CPpIFWLG.css +0 -1
  137. package/dist/web/assets/index-DiRs2_w4.js +0 -203
  138. package/dist/web/assets/session-events-BqQQkbAN.js +0 -29
  139. package/dist/web/assets/team-QZ9byb3E.js +0 -1
@@ -0,0 +1,6 @@
1
+ import{p as IH,q as RH,r as gH,s as kH,t as CH,u as hH}from"./chunk-k10d8t4f.js";import{B as bH,C as VH,D as ZH,E as $H,F as l,G as qH}from"./chunk-d11mqbqk.js";import{H as BH,ca as FH,ea as EH,fa as MH,ja as zH}from"./chunk-y66f1t18.js";import"./chunk-16648v5c.js";import"./chunk-2m79vd9p.js";import"./chunk-5xgyx25z.js";import{Ib as t,Ub as GH,bc as PH}from"./chunk-j58wrt5n.js";import"./chunk-3eskgvpy.js";import{Md as UH,Qd as _H,Sd as u,be as n}from"./chunk-nqts5by0.js";import"./chunk-zx78c1an.js";import"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import{lf as AH}from"./chunk-gcg56vaw.js";import{nf as SH,of as TH,pf as yH}from"./chunk-nyw686sf.js";import{qf as fH}from"./chunk-v2fewxvw.js";import"./chunk-6qhbdcse.js";import{Qf as xH}from"./chunk-mjnkxem3.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-ar85hxx2.js";import"./chunk-bq6d0v5b.js";import"./chunk-hrcz179j.js";import"./chunk-d64b7wta.js";import"./chunk-14j2dbd6.js";import"./chunk-nnas8tdt.js";import{fh as YH}from"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import"./chunk-atdq9btn.js";import{Li as WH}from"./chunk-npc7jt96.js";import{Qi as s,Ri as r}from"./chunk-mc2mr1kn.js";import{Vi as C}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import{Aj as XH,Cj as Y,xj as jH,zj as H}from"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";import mJ from"yargs";import{hideBin as cJ}from"yargs/helpers";function a(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function vH(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=()=>{a(V,"drain",x),a(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 lH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await vH(V,Q)}class i{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new l("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new qH({maxPendingItems:Z.maxPendingItems??VH,maxPendingBytes:Z.maxPendingBytes??ZH,writeTimeoutMs:Z.writeTimeoutMs??$H,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>lH(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 l("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))a(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var aH=L({type:H.Literal("content_delta"),delta:H.String()}),iH=L({type:H.Literal("thinking_delta"),delta:H.String()}),oH=L({type:H.Literal("thinking"),content:H.String()}),sH=L({type:H.Literal("stream_end")}),rH=L({type:H.Literal("content"),content:H.String()}),nH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),o=Y(["readonly","write","execute"]),tH=H.Object({kind:o,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),eH=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(o)}),HJ=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(tH)}),JJ=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"])}),KJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(o),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(JJ)}),VJ=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())}),ZJ=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())}),$J=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),qJ=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())}),XJ=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())}),YJ=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())}),BJ=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())}),NJ=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()}),QJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),DJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),LJ=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()}),WJ=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())}),jJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),xJ=L({type:H.Literal("task_update"),tasks:H.Array(BH)}),UJ=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}))}),_J=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(YH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),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}))}),GJ=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}))}),PJ=L({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason: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())}),FJ=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"]))}),EJ=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"]))}),MJ=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}))}),zJ=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}))}),fJ=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()}),c=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),NH=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})]),AJ=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:c,to:c,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:NH},{additionalProperties:!1}))},{additionalProperties:!1}),SJ=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([AJ,H.Null()])},{additionalProperties:!1}),TJ=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}),yJ=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(TJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),bJ=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([yJ,H.Null()])},{additionalProperties:!1}),IJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:c,to:c,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:NH},{additionalProperties:!1}),RJ=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()}),gJ=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"]))}),kJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),CJ=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())}),hJ=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})}),OJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),wJ=L({type:H.Literal("error"),message:H.String()}),XK=XH(H.Union([aH,iH,oH,sH,rH,nH,eH,HJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,MJ,zJ,EJ,fJ,SJ,bJ,IJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ]));function QH(V,Z){return{event_version:k,type:V,...Z}}function uJ(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 dJ(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 pJ=Y(["text","jsonl"]),vJ=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(WH)),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(pJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class OH{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 lJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function aJ(V){let Z=jH(vJ,V);if(!Z.success)throw Error(`Invalid headless options: ${lJ(Z.error)}`);return Z.data}function iJ(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 eJ(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
2
+ `)}function oJ(V){return`[task] [${V.status}] ${V.subject}`}function sJ(){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 rJ(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 nJ(V){return V==="jsonl"?"jsonl":"text"}function DH(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 tJ(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 LH(V,Z,Q=!1){let q=(J,K)=>{V.stdout.write(`${JSON.stringify(QH(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,oJ(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,frontier_stall_category:J.goal?.frontierStall?.category,frontier_stall_count:J.goal?.frontierStall?.consecutiveCount});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",{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});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`:""}`)},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 eJ(V,Z={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new OH,K={targetLocked:!1},D,x,j,P=dJ(Q),T=!1,F=new i(Z,{signal:P.signal,onFailure:(N)=>{T=!0,P.abort(N)}}),d={stdout:{write:(N)=>F.write("stdout",N)},stderr:{write:(N)=>F.write("stderr",N)}},B=LH(d,q),p=async()=>{try{return await F.flush(),!T}catch{return!1}},E=async(N)=>{return x?.(),x=void 0,j?.(),j=void 0,await p()?N:1};try{let N=aJ(V);q=nJ(N.outputFormat);let y=await CH(N);B=LH(d,q,Boolean(y)),await IH();let e=N.forkSession!==!0&&(N.continue===!0||typeof N.resume==="string"&&N.resume.length>0)?await gH({message:N.message,_:N._,stdin:Q?.stdin}):await RH({...N,stdin:Q?.stdin}),M=e===void 0,_=M?{mode:"agent",content:""}:await kH(e);if(_.mode==="output"){if(_.content)B.output(_.content,_.exitCode??0);return await E(_.exitCode??0)}if(!M&&_.content.length>s)throw Error(`User prompt exceeds the ${s}-character durable input limit`);if(!M&&Buffer.byteLength(_.content,"utf8")>r)throw Error(`User prompt exceeds the ${r}-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:HH,metadata:JH}=await hH({sessionId:N.sessionId,continue:N.continue,resume:N.resume,forkSession:N.forkSession,fallbackSessionPrefix:"headless"}),R=N.permissionMode??JH?.permissionMode??"yolo",KH=N.model&&N.model!=="inherit"?N.model:xH()?.id,U=N.taskIsolation?await bH.createSessionTask({sessionId:G,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,dispatch:{version:1,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,permissionMode:R,...KH?{modelId:KH}:{},...y?{outputSchema:y}:{}}}):void 0,z=U?.metadata.projectPath??JH?.projectPath??C();if(j=t.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"],pH=["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&&!pH.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 n.setSessionPermissionMode(G,z,R);let wH=U?!1:await PH.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=t.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 mH={messages:wH?await n.loadSessionModelContext(G,z):[...HH],userId:"cli-user",sessionId:G,workspaceRoot:z,permissionMode:R,signal:P.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:sJ()};D=await FH.create({sessionId:G,workspaceRoot:z,modelId:N.model,permissionMode:R,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig,agents:N.agents?fH(N.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...HH.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",v=D.getTurnRecoveryAssessment?.()??{state:"none"};if(M&&!g&&!w&&v.state==="requires_attention")return B.turnRecovery({kind:"turn_recovery",assessment:v}),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 $=v;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 p()}});return B.userShellCompleted($),await E($.record.status==="completed"?0:$.record.status==="aborted"?130:$.record.exitCode??1)}let cH=N.maxTurns??D.getConfig().maxTurns,uH=U?.taskWorktree?[...new Set([...N.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:N.disallowedTools,dH=await zH.createWithRuntime(D,{sessionId:G,systemPrompt:N.systemPrompt,appendSystemPrompt:N.appendSystemPrompt,maxTurns:N.maxTurns,modelId:N.model,permissionMode:R,toolWhitelist:N.allowedTools,toolBlacklist:uH,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig}),m=await GH(dH.chatStream(_.content,mH,{stream:!0,signal:P.signal,maxTurns:N.maxTurns,builtinVerification:N.verificationAgent!==!1,outputSchema:y,pendingInputOnly:g,goalContinuationOnly:w,...cH===-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===u)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),A=EH(X.function.name,f),S=DH(X.function.name,f),I=tJ(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===u)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===u)break;let f;try{let S=JSON.parse(X.function.arguments);f=DH(X.function.name,S)}catch{f=void 0}let A=_H(MH(X.function.name,$.result),UH);if(B.toolResult(X.function.name,A.summary,f,void 0,{success:$.result.success,errorType:$.result.error?.type,errorMessage:$.result.error?.message,background:uJ($.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 p()});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")d.stderr.write(`
6
+ `);B.error(`Error: ${rJ(N)}`)}return await E(1)}finally{x?.(),j?.();try{await D?.dispose()}finally{F.close(),P.dispose()}}}async function kK(){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}=AH,j=mJ(cJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([TH,SH,yH]);return iJ(j),await j.parse(),!0}export{eJ as runHeadless,kK as handleHeadlessMode,vJ as HeadlessOptionsSchema};
@@ -0,0 +1 @@
1
+ import{a,b as i,c as l,d as m}from"./chunk-j21hez8g.js";import"./chunk-fndqbf45.js";import"./chunk-9m7d3ajv.js";import"./chunk-56py3ryh.js";import"./chunk-he0f6h5q.js";import"./chunk-d11mqbqk.js";import"./chunk-y66f1t18.js";import"./chunk-16648v5c.js";import"./chunk-2m79vd9p.js";import"./chunk-5xgyx25z.js";import"./chunk-j58wrt5n.js";import"./chunk-3eskgvpy.js";import"./chunk-nqts5by0.js";import"./chunk-zx78c1an.js";import"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import{sf as n}from"./chunk-92n2p24j.js";import"./chunk-6qhbdcse.js";import{Of as s}from"./chunk-mjnkxem3.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-ar85hxx2.js";import"./chunk-bq6d0v5b.js";import"./chunk-hrcz179j.js";import"./chunk-d64b7wta.js";import"./chunk-14j2dbd6.js";import"./chunk-nnas8tdt.js";import"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import"./chunk-atdq9btn.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1,4 +1,4 @@
1
- import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-xtngc0th.js";import{ca as O,ja as S}from"./chunk-sy0vxdc3.js";import"./chunk-24rsvr6e.js";import"./chunk-hx10bph0.js";import"./chunk-gq7fdc8c.js";import{Rb as M,_b as E}from"./chunk-c5rfnzhf.js";import"./chunk-wzkh3e6a.js";import{_d as f}from"./chunk-mxe4pr8t.js";import"./chunk-z3hpstky.js";import{De as h}from"./chunk-mq1mk3v5.js";import"./chunk-fnc97xg7.js";import{if as I}from"./chunk-hqwpnb0x.js";import{kf as y,lf as R,mf as g}from"./chunk-t6cajkaj.js";import{nf as C}from"./chunk-13sdjfks.js";import"./chunk-kbnxbb23.js";import{Kf as w}from"./chunk-0qq64xqm.js";import"./chunk-v508x7cg.js";import"./chunk-q0s3gcjm.js";import"./chunk-acsfh1cw.js";import"./chunk-tev70rzj.js";import"./chunk-vvawhvea.js";import"./chunk-82x77b2p.js";import"./chunk-1cbaqh71.js";import"./chunk-5sknjz9b.js";import"./chunk-f7hsagj6.js";import"./chunk-sv5z5sna.js";import"./chunk-qm96k94k.js";import"./chunk-77x1rrz9.js";import"./chunk-mm1atkae.js";import{Gi as A}from"./chunk-gdnyt8a7.js";import"./chunk-vptn8fhx.js";import{Qi as P}from"./chunk-jc28ddt0.js";import"./chunk-nfzad4te.js";import"./chunk-jb8stg10.js";import"./chunk-g7h0peka.js";import"./chunk-s3a017q7.js";import"./chunk-bdtpq7j9.js";import"./chunk-w2n1vwzg.js";import"./chunk-zy2etr3v.js";import"./chunk-1p9sjb8d.js";import"./chunk-na3nregt.js";import"./chunk-ntd69c0k.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-k10d8t4f.js";import{ca as O,ja as S}from"./chunk-y66f1t18.js";import"./chunk-16648v5c.js";import"./chunk-2m79vd9p.js";import"./chunk-5xgyx25z.js";import{Ub as M,bc as E}from"./chunk-j58wrt5n.js";import"./chunk-3eskgvpy.js";import{be as f}from"./chunk-nqts5by0.js";import"./chunk-zx78c1an.js";import{Ge as h}from"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import{lf as I}from"./chunk-gcg56vaw.js";import{nf as y,of as R,pf as g}from"./chunk-nyw686sf.js";import{qf as C}from"./chunk-v2fewxvw.js";import"./chunk-6qhbdcse.js";import{Nf as w}from"./chunk-mjnkxem3.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-ar85hxx2.js";import"./chunk-bq6d0v5b.js";import"./chunk-hrcz179j.js";import"./chunk-d64b7wta.js";import"./chunk-14j2dbd6.js";import"./chunk-nnas8tdt.js";import"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import"./chunk-atdq9btn.js";import{Li as A}from"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import{Vi as P}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -15,4 +15,4 @@ More specific user instructions about presentation take precedence for that resp
15
15
  <communication_style>
16
16
  ${h.prompt}
17
17
  </communication_style>`}
18
- export{R as eh,z as fh,H as gh,W as hh,Z as ih};
18
+ export{R as jh,z as kh,H as lh,W as mh,Z as nh};
@@ -1,2 +1,2 @@
1
1
  import*as z from"node:os";import*as x from"node:path";function F(){return process.env.BLADE_STORAGE_ROOT||x.join(z.homedir(),".blade")}import{AsyncLocalStorage as Lq}from"node:async_hooks";import{createHash as Vq}from"node:crypto";import{lstat as L,mkdir as Cq,readdir as bq,realpath as N}from"node:fs/promises";import Z from"node:path";import{createHash as Gq}from"node:crypto";var E=new WeakSet,j=new WeakSet,Jq={"not-absolute":"ACP remote file path must be absolute","style-mismatch":"ACP remote file path does not match the expected style","drive-relative":"ACP remote file path cannot be drive-relative","root-relative":"ACP remote file path cannot be root-relative","unc-not-supported":"ACP remote file path must be absolute; UNC paths are not supported","device-namespace-not-supported":"ACP remote file path device namespaces are not supported","trailing-dot-or-space":"ACP remote file path components cannot end with a dot or space","alternate-data-stream":"ACP remote file path alternate data streams are not supported","reserved-device-name":"ACP remote file path reserved device names are not supported","short-name-alias":"ACP remote file path short-name aliases are not supported","invalid-character":"ACP remote file path contains characters that are not supported"},Oq=new Set(["CON","PRN","AUX","NUL","CONIN$","CONOUT$","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9","COM¹","COM²","COM³","LPT¹","LPT²","LPT³"]);class _ extends Error{reason;style;name="AcpRemotePathError";code="acp_remote_path_invalid";constructor(q,G){super(Jq[q]);this.reason=q;this.style=G;Object.setPrototypeOf(this,new.target.prototype)}toJSON(){return{name:this.name,code:this.code,reason:this.reason,style:this.style,message:this.message}}}class V extends Error{name="AcpRemotePathIdentityError";code="acp_remote_path_identity_invalid";constructor(){super("ACP remote path identity is invalid");Object.setPrototypeOf(this,new.target.prototype)}}function Qq(q){if(!E.has(q))throw new V}function Uq(q){if(!j.has(q))throw new V;if(Qq(q.workspace),q.style!==q.workspace.style)throw new V}function gq(q){Uq(q);let G=Object.freeze({style:q.style,workspace:q.workspace});return j.add(G),G}function Rq(q){let G=C(q),J=Object.freeze({style:G.style,workspace:G});return j.add(J),J}function C(q,G){let J=W(q,G);if(J.kind==="error")throw new _(J.reason,J.style);let O=J.style==="win32"?Yq(q):Xq(q);return k(J.style,O)}function Sq(q,G){let J=C(q),O=J.style==="win32"?Fq(J.wirePath,G):_q(J.wirePath,G);return k(J.style,O)}function W(q,G){if(R(q))return{kind:"error",reason:"device-namespace-not-supported",style:"win32"};if(g(q))return{kind:"error",reason:"unc-not-supported",style:G==="posix"?"posix":"win32"};if(S(q))return{kind:"error",reason:"unc-not-supported",style:"win32"};if(P(q)){if(G==="posix")return{kind:"error",reason:"style-mismatch",style:"posix"};return{kind:"absolute",style:"win32"}}if(Mq(q))return{kind:"error",reason:"drive-relative",style:"win32"};if(q.startsWith("\\"))return{kind:"error",reason:"root-relative",style:"win32"};if(q.startsWith("/")){if(G==="win32")return{kind:"error",reason:"style-mismatch",style:"win32"};return{kind:"absolute",style:"posix"}}return{kind:"error",reason:"not-absolute",style:"unknown"}}function k(q,G){let J=q==="win32"?G.toUpperCase():G,O=Object.freeze({style:q,wirePath:G,exactIdentity:I("acp-remote-exact-path",q,G),collisionIdentity:I("acp-remote-collision-path",q,J)});return E.add(O),O}function I(q,G,J){return`${q}:${Gq("sha256").update(`${G}\x00${J}`).digest("hex")}`}function Xq(q){let G=q.split("/"),J=[];for(let O of G.slice(1)){if(O.length===0||O===".")continue;if(O===".."){if(J.length>0)J.pop();continue}A(O),J.push(O)}return J.length===0?"/":`/${J.join("/")}`}function Yq(q){let G=q[0].toUpperCase(),J=Bq(q),O=[],Q="";for(let U of q.slice(2)){if(m(U)){if(Q.length>0)v(O,Q),Q="";continue}Q+=U}if(Q.length>0)v(O,Q);if(J&&O.length>0)throw new _("trailing-dot-or-space","win32");if(O.length===0)return`${G}:\\`;return`${G}:\\${O.join("\\")}`}function Zq(q,G){let J=q==="/"?[]:q.slice(1).split("/"),O=[...J];for(let Q of G.split("/")){if(Q.length===0||Q===".")continue;if(Q===".."){if(O.length===J.length)throw new _("not-absolute","posix");O.pop();continue}A(Q),O.push(Q)}return O.length===0?"/":`/${O.join("/")}`}function _q(q,G){if(R(G))throw new _("device-namespace-not-supported","win32");if(g(G))throw new _("unc-not-supported","posix");if(S(G))throw new _("unc-not-supported","win32");if(P(G)||G.startsWith("/"))throw new _("style-mismatch","posix");return Zq(q,G)}function $q(q,G){let J=q.indexOf("\\"),O=J===q.length-1?[]:q.slice(J+1).split("\\"),Q=[...O],U="";for(let K of G){if(m(K)){if(U.length>0)y(O.length,Q,U),U="";continue}U+=K}if(U.length>0)y(O.length,Q,U);let $=q.slice(0,J+1);if(Q.length===0)return $;return`${$}${Q.join("\\")}`}function Fq(q,G){let J=W(G,"win32");if(J.kind==="absolute")throw new _("style-mismatch","win32");if(J.reason!=="not-absolute")throw new _(J.reason,J.style);return $q(q,G)}function y(q,G,J){if(J===".")return;if(J===".."){if(G.length===q)throw new _("not-absolute","win32");G.pop();return}f(J),G.push(J)}function v(q,G){if(G===".")return;if(G===".."){if(q.length>0)q.pop();return}f(G),q.push(G)}function A(q){if(q.includes("\x00"))throw new _("invalid-character","posix")}function f(q){let G=Hq(q),J=Kq(G);if(J!==void 0&&Oq.has(J.toUpperCase()))throw new _("reserved-device-name","win32");if(G!==q)throw new _("trailing-dot-or-space","win32");if(q.includes(":"))throw new _("alternate-data-stream","win32");if(/~\d/u.test(q))throw new _("short-name-alias","win32");for(let O of q){let Q=O.codePointAt(0);if(Q===void 0||Q===0||Q>=1&&Q<=31||'<>"|?*'.includes(O))throw new _("invalid-character","win32")}}function Hq(q){let G=q.length;while(G>0){let J=q[G-1];if(J!=="."&&J!==" ")break;G-=1}return q.slice(0,G)}function Kq(q){if(q.length===0)return;let G=q.indexOf(".");return G===-1?q:q.slice(0,G)}function g(q){return q.startsWith("//")||q.startsWith("/\\")}function R(q){return/^([\\/]){2}[?.][\\/]/u.test(q)}function S(q){return/^[\\/]{2}/u.test(q)}function P(q){return/^[A-Za-z]:[\\/]/u.test(q)}function Mq(q){return/^[A-Za-z]:(?![\\/])/u.test(q)}function m(q){return q==="\\"||q==="/"}function Bq(q){if(q.length<=3)return!1;let G=q[q.length-1];return G==="\\"||G==="/"}var H="acp-remote-workspaces",d=/^[a-f0-9]{64}$/,b=new Map,h=new Lq,Nq;class X extends Error{name="AcpRemoteWorkspaceStateError";code="acp_remote_workspace_state_invalid";constructor(q){super(`ACP remote workspace durable state is invalid (${q})`);Object.setPrototypeOf(this,new.target.prototype)}}function iq(q){return{version:1,kind:"acp-remote",style:q.style,wirePath:q.workspace.wirePath,exactIdentity:q.workspace.exactIdentity,collisionIdentity:q.workspace.collisionIdentity}}function Tq(q){if(!q||typeof q!=="object"||Array.isArray(q))throw new X("descriptor-shape");let G=q;if(G.version!==1)throw new X("descriptor-version");if(G.kind!=="acp-remote")throw new X("descriptor-kind");if(G.style!=="posix"&&G.style!=="win32")throw new X("descriptor-style");if(typeof G.wirePath!=="string"||typeof G.exactIdentity!=="string"||typeof G.collisionIdentity!=="string")throw new X("descriptor-shape");let J;try{J=C(G.wirePath,G.style)}catch{throw new X("descriptor-wire-path")}if(J.exactIdentity!==G.exactIdentity||J.collisionIdentity!==G.collisionIdentity)throw new X("descriptor-identity");return{version:1,kind:"acp-remote",style:G.style,wirePath:J.wirePath,exactIdentity:J.exactIdentity,collisionIdentity:J.collisionIdentity}}function cq(q,G=F()){if(typeof q!=="string"||!/^acp-remote-collision-path:[a-f0-9]{64}$/.test(q))throw new X("descriptor-collision-identity");let J=Z.resolve(G),O=Vq("sha256").update(`acp-remote-host-state\x00${q}`).digest("hex");return Z.join(J,H,O)}async function sq(q){let G=Z.resolve(F());await jq(q,G)}async function rq(q,G){let J=Z.resolve(F());return s(q,J,G)}async function oq(q,G){let J=String(q);if(Z.dirname(G)!==J)throw new X("state-file-path");let O=await L(G);if(O.isSymbolicLink()||!O.isFile())throw new X("state-file-type");if(typeof process.getuid==="function"&&O.uid!==process.getuid())throw new X("state-file-owner");let Q=typeof O.mode==="bigint"?Number(O.mode&BigInt(511)):O.mode&511;if(process.platform!=="win32"&&Q!==384)throw new X("state-file-mode");await M(G,J,Z.basename(G))}async function aq(q,G,J){let O=String(q);if(Z.dirname(G)!==O)throw new X("state-file-path");let[Q,U]=await Promise.all([J.stat({bigint:!0}),L(G,{bigint:!0})]);if(U.isSymbolicLink()||!U.isFile()||!Q.isFile()||U.dev!==Q.dev||U.ino!==Q.ino)throw new X("state-file-replaced");if(typeof process.getuid==="function"&&(Number(U.uid)!==process.getuid()||Number(Q.uid)!==process.getuid()))throw new X("state-file-owner");let $=Number(U.mode&BigInt(511)),K=Number(Q.mode&BigInt(511));if(process.platform!=="win32"&&($!==384||K!==384))throw new X("state-file-mode");await M(G,O,Z.basename(G))}function tq(q,G,J,O){let Q=q[0];if(Q?.type!=="session_created"||Q.sessionId!==G||Q.data.sessionId!==G||Q.cwd!==J||Q.projectPath!==J)throw new X("remote-session-identity");if(O){let U=Tq(Q.data.remoteWorkspace);if(U.version!==O.version||U.kind!==O.kind||U.style!==O.style||U.wirePath!==O.wirePath||U.exactIdentity!==O.exactIdentity||U.collisionIdentity!==O.collisionIdentity)throw new X("remote-session-workspace")}for(let U of q)if(U.sessionId!==G||U.cwd!==J||U.projectPath!==J)throw new X("remote-session-event-identity");return Q}function n(q){return d.test(q)}async function p(q=F()){let G=Z.resolve(q);return u(`${G}\x00${H}`,async()=>{let J=Z.join(G,H),O;try{O=await c(G,(U)=>bq(U,{withFileTypes:!0}))}catch(U){if(U.code==="ENOENT")return[];throw U}await Nq?.();let Q=[];for(let U of O){if(!n(U.name))continue;let $=Z.join(J,U.name);try{let K=await s($,G,async(qq)=>qq);Q.push(K)}catch(K){if(K.code==="ENOENT")throw new X("protected-root-missing");throw K}}return Q.sort((U,$)=>U.localeCompare($))})}function i(q,G){if(typeof q!=="string"||!Z.isAbsolute(q))throw new X("protected-root-shape");let J=Z.resolve(q);if(J!==q)throw new X("protected-root-shape");let O=Z.relative(G,J),Q=`${H}${Z.sep}`;if(O===""||O===H||!O.startsWith(Q)||O.includes(`${Z.sep}..`)||O.startsWith(`..${Z.sep}`)||Z.isAbsolute(O))throw new X("protected-root-shape");let U=O.split(Z.sep);if(U.length!==2||U[0]!==H)throw new X("protected-root-shape");if(!d.test(U[1]??""))throw new X("protected-root-digest");return{storageRoot:G,digest:U[1]}}async function c(q,G){await r(q,q);let J=Z.join(q,H);try{await D(J,q),await M(J,q,H)}catch(O){if(O.code==="ENOENT")throw O;throw O}return G(J)}async function jq(q,G){await u(q,async()=>{let J=i(q,G);if(J.storageRoot!==G)throw new X("storage-root-mismatch");await r(J.storageRoot,G);let O=Z.join(J.storageRoot,H);await l(O,J.storageRoot),await M(O,G,H);let Q=Z.join(O,J.digest);await l(Q,O),await M(Q,O,J.digest)})}async function s(q,G,J){return u(q,async()=>{let O=i(q,G);if(O.storageRoot!==G)throw new X("storage-root-mismatch");let Q=Z.join(O.storageRoot,H);await c(G,async($)=>{if($!==Q)throw new X("protected-root-shape")});let U=Z.join(Q,O.digest);return await D(U,Q),await M(U,Q,O.digest),J(U)})}async function l(q,G){try{let J=await L(q);o(J,q)}catch(J){if(J.code!=="ENOENT")throw J;await Cq(q,{recursive:!1,mode:448})}await D(q,G)}async function D(q,G){let J=await L(q);o(J,q),await M(q,G,Z.basename(q))}async function r(q,G){let J=await L(q);Dq(J,q),await uq(q,G)}function Dq(q,G){a(q,G);let J=t(q);if(process.platform!=="win32"&&((J&448)!==448||(J&18)!==0))throw new X("protected-root-mode")}function o(q,G){a(q,G);let J=t(q);if(process.platform!=="win32"&&J!==448)throw new X("protected-root-mode")}function a(q,G){if(q.isSymbolicLink()||!q.isDirectory())throw new X("protected-root-symlink");if(typeof process.getuid==="function"&&q.uid!==process.getuid())throw new X("protected-root-owner");if(G.includes(`..${Z.sep}`))throw new X("protected-root-shape")}function t(q){return typeof q.mode==="bigint"?Number(q.mode&BigInt(511)):q.mode&511}async function M(q,G,J){let O=await N(q),Q=await N(G),U=Z.join(Q,J);if(O!==U)throw new X("protected-root-realpath")}async function uq(q,G){let J=await N(q),O=await N(G);if(J!==O)throw new X("protected-root-realpath")}async function u(q,G){let J=h.getStore();if(J?.has(q))throw new X("state-root-reentry");let O=b.get(q)??Promise.resolve(),Q=new Set(J??[]);Q.add(q);let U=O.catch(()=>{return}).then(()=>h.run(Q,G)),$=U.then(()=>{return},()=>{return});b.set(q,$);try{return await U}finally{if(b.get(q)===$)b.delete(q)}}import{execSync as wq}from"node:child_process";import{createHash as zq}from"node:crypto";import{realpathSync as xq}from"node:fs";import{readdir as Iq}from"node:fs/promises";import*as Y from"node:path";function yq(q){return Y.resolve(q).replace(/[/\\]/g,"-").replace(/:/g,"_")}function vq(q){let G=q.replace(/_/g,":");if(G.startsWith("-"))G="/"+G.slice(1);return G.replace(/-/g,"/")}function Eq(q){let G=yq(q);return Y.join(F(),"projects",G)}function e(q){let G=Y.resolve(q),J=[];while(!0)try{return Y.resolve(xq.native(G),...J.reverse())}catch(O){let Q=O.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")throw O;let U=Y.dirname(G);if(U===G)return Y.resolve(q);J.push(Y.basename(G)),G=U}}function XG(q,G="projectPath"){if(!Y.isAbsolute(q))throw Error(`${G} must be absolute`);let J=Y.resolve(q),O=e(J),Q=Y.join(e(F()),"acp-remote-workspaces"),U=Y.relative(Q,O),$=U.split(Y.sep)[0];if(U===""||U!==".."&&!Y.isAbsolute(U)&&!U.startsWith(`..${Y.sep}`)&&$!==void 0&&/^[a-f0-9]{64}$/i.test($))throw Error(`${G} must reference a local workspace`);return J}function w(q){return Eq(q)}function T(q){return String(q)}function Wq(q){return typeof q==="string"&&q!=="."&&q!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(q)}function B(q){if(!Wq(q))throw Error(`Invalid session ID: ${q}`)}function YG(q,G){return B(G),Y.join(w(q),`${G}.jsonl`)}function ZG(q,G){return B(G),Y.join(T(q),`${G}.jsonl`)}function _G(q,G){return B(G),Y.join(w(q),`${G}.inbox.json`)}function $G(q,G){return B(G),Y.join(T(q),`${G}.inbox.json`)}function FG(q,G){return B(G),Y.join(w(q),`${G}.goal.json`)}function HG(q,G){return B(G),Y.join(T(q),`${G}.goal.json`)}function KG(q,G){B(G);let J=zq("sha256").update(G).digest("hex");return Y.join(T(q),`.session-lease-${J}.lock`)}function MG(q){try{return wq("git rev-parse --abbrev-ref HEAD",{cwd:q,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}async function kq(){try{let q=Y.join(F(),"projects");return(await Iq(q,{withFileTypes:!0})).filter((J)=>J.isDirectory()).map((J)=>J.name)}catch{return[]}}async function BG(){let q=Y.resolve(F()),G=await kq().then((O)=>O.map((Q)=>({storagePath:Y.join(q,"projects",Q),projectPath:vq(Q),kind:"local"}))).catch(()=>[]),J=await p().then((O)=>O.map((Q)=>({storagePath:String(Q),projectPath:String(Q),kind:"acp-remote"})));return[...G,...J]}
2
- export{F as Uj,_ as Vj,Qq as Wj,Uq as Xj,gq as Yj,Rq as Zj,C as _j,Sq as $j,X as ak,iq as bk,Tq as ck,cq as dk,sq as ek,rq as fk,oq as gk,aq as hk,tq as ik,p as jk,vq as kk,Eq as lk,XG as mk,Wq as nk,B as ok,YG as pk,ZG as qk,_G as rk,$G as sk,FG as tk,HG as uk,KG as vk,MG as wk,kq as xk,BG as yk};
2
+ export{F as Zj,_ as _j,Qq as $j,Uq as ak,gq as bk,Rq as ck,C as dk,Sq as ek,X as fk,iq as gk,Tq as hk,cq as ik,sq as jk,rq as kk,oq as lk,aq as mk,tq as nk,p as ok,vq as pk,Eq as qk,XG as rk,Wq as sk,B as tk,YG as uk,ZG as vk,_G as wk,$G as xk,FG as yk,HG as zk,KG as Ak,MG as Bk,kq as Ck,BG as Dk};
@@ -1,2 +1,2 @@
1
- import{jh as Q}from"./chunk-sv5z5sna.js";import{Ri as F,Ti as k,Wi as G}from"./chunk-nfzad4te.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
- export{Z as nf};
1
+ import{oh as Q}from"./chunk-az08pq83.js";import{Cj as G,xj as F,zj as k}from"./chunk-ft1bdqbs.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
+ export{Z as qf};
@@ -0,0 +1 @@
1
+ import{Lb as a,Mb as b,Ob as c,Sb as d,Tb as e,Ub as f,Vb as g,Wb as h,Xb as i,Yb as j,Zb as k,ec as l,fc as m,gc as n,hc as o,jc as p,kc as q,lc as r}from"./chunk-j58wrt5n.js";import"./chunk-3eskgvpy.js";import"./chunk-nqts5by0.js";import"./chunk-zx78c1an.js";import"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import"./chunk-5j68055h.js";import"./chunk-ar85hxx2.js";import"./chunk-bq6d0v5b.js";import"./chunk-d64b7wta.js";import"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};