blade-code 0.10.71 → 0.10.72

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 (108) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-fcv8b6ny.js → chunk-06y3rada.js} +2 -2
  3. package/dist/{chunk-k0pa8874.js → chunk-0kat01bw.js} +1 -1
  4. package/dist/{chunk-th4jjfgm.js → chunk-0qj8jfj1.js} +1 -1
  5. package/dist/{chunk-ahg9vjb6.js → chunk-11gdqmbm.js} +1 -1
  6. package/dist/chunk-139s7p91.js +1 -0
  7. package/dist/{chunk-zvz2cnt4.js → chunk-18atvz38.js} +1 -1
  8. package/dist/{chunk-9hchc346.js → chunk-28wsyv32.js} +1 -1
  9. package/dist/{chunk-rm9hbew3.js → chunk-2d2bcyn1.js} +1 -1
  10. package/dist/{chunk-0tm20v38.js → chunk-2fd5trh8.js} +2 -2
  11. package/dist/{chunk-cdy9efgm.js → chunk-2sdnmxts.js} +1 -1
  12. package/dist/chunk-2vkzwqv0.js +1 -0
  13. package/dist/chunk-41smvqs8.js +1 -0
  14. package/dist/{chunk-hat9v5c5.js → chunk-4wvsg8cc.js} +1 -1
  15. package/dist/{chunk-6pyktfa4.js → chunk-4xpj0d6y.js} +1 -1
  16. package/dist/{chunk-byqxaa9v.js → chunk-5va3hhfp.js} +1 -1
  17. package/dist/chunk-61arrvhp.js +1 -0
  18. package/dist/{chunk-yn51162x.js → chunk-6j3k4v08.js} +1 -1
  19. package/dist/{chunk-s7jsadnc.js → chunk-6j9t1xbh.js} +2 -2
  20. package/dist/{chunk-nx31fkkf.js → chunk-6v7f2cv9.js} +53 -53
  21. package/dist/{chunk-j9q1wyxg.js → chunk-7am1z065.js} +1 -1
  22. package/dist/{chunk-2428hhvj.js → chunk-7hf1k2c9.js} +2 -2
  23. package/dist/chunk-8geywf8q.js +1 -0
  24. package/dist/{chunk-wrfay5r3.js → chunk-91qsjpm6.js} +2 -2
  25. package/dist/{chunk-1je1xw6v.js → chunk-a38chc6z.js} +18 -18
  26. package/dist/{chunk-0vrgrw71.js → chunk-awj9aqjy.js} +2 -2
  27. package/dist/chunk-bqz8wera.js +1 -0
  28. package/dist/chunk-brm24s69.js +2 -0
  29. package/dist/{chunk-r9d4mjxj.js → chunk-bs77d8hn.js} +1 -1
  30. package/dist/{chunk-mtphps19.js → chunk-c4j2anbm.js} +2 -2
  31. package/dist/{chunk-82htkvz8.js → chunk-ccgq8nrm.js} +2 -2
  32. package/dist/{chunk-be30r8an.js → chunk-cqeqjtxn.js} +1 -1
  33. package/dist/{chunk-93tvxmqg.js → chunk-cyjnza5n.js} +4 -4
  34. package/dist/chunk-d9a0g85f.js +1 -0
  35. package/dist/{chunk-1pjkgfez.js → chunk-e0hf1317.js} +1 -1
  36. package/dist/chunk-e4ynb9qf.js +1 -0
  37. package/dist/chunk-e6ezndyf.js +22 -0
  38. package/dist/{chunk-jzntxp7f.js → chunk-eh4h7fmr.js} +2 -2
  39. package/dist/chunk-eh9gdzk5.js +160 -0
  40. package/dist/chunk-emqbb5xh.js +1 -0
  41. package/dist/{chunk-h0ft81a3.js → chunk-g8425xh4.js} +1 -1
  42. package/dist/{chunk-t2wgf9tq.js → chunk-gv3ed5gw.js} +2 -2
  43. package/dist/chunk-gzysna9c.js +1 -0
  44. package/dist/{chunk-axtzde5k.js → chunk-hhk5ecpv.js} +2 -2
  45. package/dist/{chunk-gtcxybv5.js → chunk-hhvkzn6m.js} +1 -1
  46. package/dist/{chunk-d3ttqmyt.js → chunk-hryhnmwv.js} +277 -262
  47. package/dist/{chunk-2px6hzdc.js → chunk-hwjmm2br.js} +2 -2
  48. package/dist/{chunk-9q852bsc.js → chunk-j0yvwrd7.js} +2 -2
  49. package/dist/{chunk-m57w4p91.js → chunk-jyds9m8p.js} +1 -1
  50. package/dist/{chunk-v0rsz1rt.js → chunk-m6qgme8k.js} +1 -1
  51. package/dist/{chunk-97aywyzn.js → chunk-mhyat4mq.js} +2 -2
  52. package/dist/{chunk-qgrq04hb.js → chunk-mp4bfn57.js} +1 -1
  53. package/dist/chunk-mrh3vs01.js +2 -0
  54. package/dist/chunk-ph5rn44j.js +1 -0
  55. package/dist/chunk-pqhjrdnq.js +10 -0
  56. package/dist/{chunk-0j22w4wh.js → chunk-q6daf441.js} +1 -1
  57. package/dist/{chunk-0wxkymqv.js → chunk-s9brgcgs.js} +1 -1
  58. package/dist/{chunk-trn6r1g3.js → chunk-ss1znmv0.js} +1 -1
  59. package/dist/{chunk-3hy06st1.js → chunk-tms0pr01.js} +2 -2
  60. package/dist/chunk-v7phc78b.js +1 -0
  61. package/dist/{chunk-t8xmh4w2.js → chunk-wvg81sd9.js} +1 -1
  62. package/dist/{chunk-x9tvjkjv.js → chunk-x4hh8yqg.js} +1 -1
  63. package/dist/{chunk-dwb2nmms.js → chunk-xahapj98.js} +1 -1
  64. package/dist/{chunk-s77sbxr7.js → chunk-xszsveq1.js} +1 -1
  65. package/dist/{chunk-azw0jckv.js → chunk-y858e8pb.js} +2 -2
  66. package/dist/{chunk-bjqjdw34.js → chunk-yhnr8vdb.js} +2 -2
  67. package/dist/{chunk-cff9gphh.js → chunk-yjj7q7hy.js} +1 -1
  68. package/dist/{chunk-zdnk7qtn.js → chunk-ypwjzw5x.js} +2 -2
  69. package/dist/{chunk-4ke8k0xw.js → chunk-z7vj2xrg.js} +3 -3
  70. package/dist/{chunk-5te2jqt3.js → chunk-zac26wwd.js} +1 -1
  71. package/dist/{chunk-wfy851et.js → chunk-zf96d5we.js} +1 -1
  72. package/dist/chunk-zqxj65xc.js +1 -0
  73. package/dist/chunk-zssys78z.js +1 -0
  74. package/dist/web/assets/ChatView-CgUC5rxo.js +18 -0
  75. package/dist/web/assets/{CodeBlockHighlighter-Dy7QpAmC.js → CodeBlockHighlighter-B5DRAEhB.js} +1 -1
  76. package/dist/web/assets/{FilePreview-BI3nkxz1.js → FilePreview-DSpvLsjW.js} +1 -1
  77. package/dist/web/assets/{KanbanBoard-D5dYOyPH.js → KanbanBoard-6K7IeCXi.js} +1 -1
  78. package/dist/web/assets/{MarkdownRenderer-Da1vB81L.js → MarkdownRenderer-D6LiW9kF.js} +3 -3
  79. package/dist/web/assets/{SettingsModal-jcCFqLqS.js → SettingsModal-CFHxLfuL.js} +1 -1
  80. package/dist/web/assets/{TaskSwitcher-CQ--jOLB.js → TaskSwitcher-Bng9nDed.js} +1 -1
  81. package/dist/web/assets/{TerminalPanel-CWzjEXOb.js → TerminalPanel-BnyQZwkN.js} +1 -1
  82. package/dist/web/assets/index-CDdYV8kB.css +1 -0
  83. package/dist/web/assets/index-DId2GJVO.js +11 -0
  84. package/dist/web/assets/{vendor-icons-B63aW_OM.js → vendor-icons-C927DZlr.js} +41 -36
  85. package/dist/web/index.html +3 -3
  86. package/package.json +1 -1
  87. package/dist/chunk-1w83z8j0.js +0 -1
  88. package/dist/chunk-3as0bkqy.js +0 -1
  89. package/dist/chunk-4pexpa3h.js +0 -160
  90. package/dist/chunk-8j568nm6.js +0 -1
  91. package/dist/chunk-92x15fzx.js +0 -2
  92. package/dist/chunk-ckqpt15b.js +0 -1
  93. package/dist/chunk-fcmgwzrj.js +0 -10
  94. package/dist/chunk-gvbx0t4j.js +0 -1
  95. package/dist/chunk-j0p54tqt.js +0 -1
  96. package/dist/chunk-n827nys9.js +0 -1
  97. package/dist/chunk-nwzpnx7m.js +0 -22
  98. package/dist/chunk-qnsvae10.js +0 -1
  99. package/dist/chunk-sp3bn8qh.js +0 -1
  100. package/dist/chunk-v7p533ff.js +0 -1
  101. package/dist/chunk-vthgpdbd.js +0 -1
  102. package/dist/chunk-wneeq8cr.js +0 -1
  103. package/dist/chunk-xdz5zrjt.js +0 -1
  104. package/dist/chunk-xz6y0w4n.js +0 -2
  105. package/dist/chunk-xzz69esf.js +0 -1
  106. package/dist/web/assets/ChatView-BVrhnE2j.js +0 -18
  107. package/dist/web/assets/index-BOgOL4hG.js +0 -11
  108. package/dist/web/assets/index-DbWgTuT3.css +0 -1
@@ -1 +0,0 @@
1
- import{oh as a,ph as b,qh as c}from"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
@@ -1,2 +0,0 @@
1
- import{mg as J,ng as $,og as U,pg as B}from"./chunk-v0rsz1rt.js";import{qg as v,rg as h,sg as u}from"./chunk-xz6y0w4n.js";import{Xg as i}from"./chunk-t2wgf9tq.js";import{Bh as s}from"./chunk-9q852bsc.js";var O=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],r={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},E=new Map;function D(Q,Z,W){let K=new Set;for(let X of Q.split(",")){let[Y,V]=X.split("/"),G=V?Number.parseInt(V,10):1;if(!Number.isInteger(G)||G<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=W;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[k,t]=Y.split("-");j=Number.parseInt(k,10),H=Number.parseInt(t,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>W||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let k=j;k<=H;k+=G)K.add(k)}return K}function R(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[W,K,X,Y,V]=Z,G=D(V,O[4].min,O[4].max),j=new Set([...G].map((H)=>H===7?0:H));return{minutes:D(W,O[0].min,O[0].max),hours:D(K,O[1].min,O[1].max),daysOfMonth:D(X,O[2].min,O[2].max),months:D(Y,O[3].min,O[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:V.trim()!=="*"}}function T(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let W=E.get(Z);if(!W)W=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),E.set(Z,W);let K=Object.fromEntries(W.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(K.minute),hour:Number(K.hour),dayOfMonth:Number(K.day),month:Number(K.month),dayOfWeek:r[K.weekday]??-1}}function y(Q,Z,W){let K=T(Z,W);if(!Q.minutes.has(K.minute))return!1;if(!Q.hours.has(K.hour))return!1;if(!Q.months.has(K.month))return!1;let X=Q.daysOfMonth.has(K.dayOfMonth),Y=Q.daysOfWeek.has(K.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function p(Q,Z,W){let K=R(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(y(K,X,W))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var S={s:1000,m:60000,h:3600000,d:86400000};function zJ(Q){let W=Q.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!W)return null;let K=Number.parseInt(W[1],10);if(!Number.isInteger(K)||K<=0)return null;let X=W[2]||"m";return K*S[X]}function e(Q){for(let Z of["d","h","m","s"]){let W=S[Z];if(Q%W===0)return`${Q/W}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,W){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return p(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((W??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let K=new Date(Q.runAt);if(Number.isNaN(K.getTime()))return null;return K.getTime()>Z.getTime()?K:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(R(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function AJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?e(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as LJ,readFile as PJ}from"node:fs/promises";import a from"node:path";import{nanoid as MJ}from"nanoid";import IJ from"write-file-atomic";var w=$(B(["default","autoEdit","yolo","plan"]));var N=$(B(["user","assistant","system","tool"])),JJ=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),d=J.Union([J.String(),J.Array(JJ)]),xJ=$(J.Object({id:J.String(),role:N,content:d,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),QJ=$(B(["queued","running","completed","failed","cancelled","interrupted"])),F=$(B(["local","worktree"])),q=$(B(["high","medium","low"])),x=$(B(["feature","bug","maintenance","research"])),ZJ=$(B(["applied","discarded","conflicted"])),$J=$(J.Object({status:ZJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),BJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),KJ=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),fJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array(KJ,{maxItems:100}),truncated:J.Boolean()})),WJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),XJ=$(J.Object({name:J.String(),type:B(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(WJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(B(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),CJ=$(J.Object({serverName:J.String(),mode:B(["form","url"]),message:J.String(),fields:J.Optional(J.Array(XJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),YJ=$(J.Object({type:B(["permission","question","elicitation"]),requestId:J.String()})),HJ=$(J.Object({code:B(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","capacity","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean(),resource:J.Optional(B(["pending_count","pending_bytes","resident_runtimes"]))})),L=$(B(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(B(["auto","standard","fast","flex"])),M=$(B(["auto","low","medium","high"])),b=$(J.Union([B(["auto","pragmatic","friendly","explanatory"]),J.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(B(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:U(QJ,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(HJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskPriority:J.Optional(q),taskKind:J.Optional(x),taskDueAt:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional($J),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(BJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(YJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),EJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),RJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),SJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),lJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:B(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),completionVerification:J.Optional(J.Object({attempt:J.Integer({minimum:1}),status:B(["pending","pass","fail","partial"]),requestedAt:J.String(),completedAt:J.Optional(J.String()),verifierSessionId:J.Optional(J.String()),summary:J.Optional(J.String()),evidenceSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),createdAt:J.String(),updatedAt:J.String()})),m=$(J.Object({role:N,content:d,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),hJ=$(J.Object({session:z,messages:J.Array(m)})),c=$(B(["conversation","code","both"])),jJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),uJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:U(c,"conversation")})),dJ=$(J.Object({checkpoint:jJ,mode:c,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(m)})),UJ=B(["running","completed","failed","cancelled"]),l=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:UJ,background:J.Boolean(),rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),restartRecovery:J.Optional(J.Object({outcome:B(["completed","interrupted","failed"]),recoveredAt:J.Number()})),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(B(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),mJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),cJ=$(J.Object({source:l,session:l})),gJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),nJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),oJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),sJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),g=J.Object({type:B(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:h})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),n=J.Record(J.String(),J.Unknown()),iJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),taskPriority:U(q,"medium"),taskKind:U(x,"feature"),taskDueAt:J.Optional(J.String({minLength:1,maxLength:64})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default"),attachments:J.Optional(J.Array(g,{maxItems:v})),outputSchema:J.Optional(n)})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),taskPriority:J.Optional(q),taskKind:J.Optional(x),taskDueAt:J.Optional(J.Union([J.String({minLength:1,maxLength:64}),J.Null()]))})),tJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:B(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),rJ=$(J.Object({action:B(["apply","discard"])})),f=$(J.Object({kind:B(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),kJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default")})),C=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:f,dispatch:kJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(B(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),TJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:f,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default"),enabled:U(J.Boolean(),!0)})),yJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(f),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),pJ=$(J.Object({schedules:J.Array(C)})),eJ=$(J.Object({content:J.String({maxLength:u}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(g,{maxItems:v})),outputSchema:J.Optional(n)})),VJ=B(["completed","failed","aborted","timed_out","spawn_error"]),GJ=$(J.Object({version:J.Literal(1),command:J.String(),status:VJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),JQ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),QQ=$(J.Object({executionId:J.String(),messageId:J.String(),record:GJ,auxiliary:J.Boolean(),delivery:J.Optional(B(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),ZQ=$(J.Object({projectPath:J.String(),kind:B(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),$Q=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),BQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),KQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(B(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:B(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),OJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:B(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),WQ=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(B(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(B(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(B(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(OJ,{maxItems:36})),input:J.Optional(J.Array(B(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),XQ=$(B(["vs-dark","vs-light","hc-black"])),bJ=$(B(["light","dark","system"])),wJ=$(J.Object({language:J.String(),codeTheme:J.String(),uiTheme:bJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),YQ=$(J.Partial(wJ));var o=i("Service"),DJ=1;function FJ(){return a.join(s(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=FJ()){this.filePath=Q}async readFile(){try{let Q=await PJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let W=[],K=0;for(let X of Z.schedules){let Y=C.safeParse(X);if(Y.success)W.push(Y.data);else K+=1}if(K>0)o.warn(`[ScheduleStore] Ignored ${K} invalid persisted schedule(s)`);return W}catch(Q){let Z=Q;if(Z.code!=="ENOENT")o.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await LJ(a.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:DJ,schedules:Q};await IJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((W)=>W.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,W=_(Z);if(W)throw Error(W);let K=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=K.getTime())throw Error("once trigger runAt must be in the future");let X=K.toISOString(),Y=A(Z,K),V={id:MJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},G=await this.readFile();return G.push(V),await this.writeFile(G),V})}async update(Q,Z){return this.serializeWrite(async()=>{let W=await this.readFile(),K=W.findIndex((H)=>H.id===Q);if(K===-1)return;let X=W[K];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,k=_(H);if(k)throw Error(k);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},V=!X.enabled,G=Y.enabled,j=Z.trigger!==void 0;if((j||V&&G)&&Z.nextRunAt===void 0){let H=new Date,k=A(Y.trigger,H);if(Y.nextRunAt=k?k.toISOString():null,j)Y.expiresAt=null}return W[K]=Y,await this.writeFile(W),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),W=Z.filter((K)=>K.id!==Q);if(W.length===Z.length)return!1;return await this.writeFile(W),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var IQ=I.getInstance();
2
- export{zJ as xa,A as ya,_ as za,AJ as Aa,fJ as Ba,z as Ca,uJ as Da,mJ as Ea,iJ as Fa,aJ as Ga,tJ as Ha,rJ as Ia,C as Ja,TJ as Ka,yJ as La,pJ as Ma,eJ as Na,JQ as Oa,ZQ as Pa,I as Qa,IQ as Ra};
@@ -1 +0,0 @@
1
- import{Ab as m,Bb as n,Cb as o,Eb as p,Fb as q,Gb as r,gb as a,hb as b,jb as c,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,zb as l}from"./chunk-nx31fkkf.js";import"./chunk-th4jjfgm.js";import"./chunk-97aywyzn.js";import"./chunk-0wxkymqv.js";import"./chunk-mtphps19.js";import"./chunk-0j22w4wh.js";import"./chunk-zdnk7qtn.js";import"./chunk-yn51162x.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1,10 +0,0 @@
1
- import{f as T,g as W,h as X,i as Y}from"./chunk-93tvxmqg.js";import"./chunk-9hchc346.js";import"./chunk-rm9hbew3.js";import"./chunk-s77sbxr7.js";import"./chunk-ahg9vjb6.js";import"./chunk-byqxaa9v.js";import"./chunk-d3ttqmyt.js";import"./chunk-qgrq04hb.js";import"./chunk-92x15fzx.js";import"./chunk-nx31fkkf.js";import"./chunk-th4jjfgm.js";import"./chunk-97aywyzn.js";import"./chunk-0wxkymqv.js";import"./chunk-mtphps19.js";import{qd as R}from"./chunk-0vrgrw71.js";import"./chunk-bjqjdw34.js";import{Md as Q}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zdnk7qtn.js";import"./chunk-wrfay5r3.js";import"./chunk-yn51162x.js";import"./chunk-fcv8b6ny.js";import"./chunk-axtzde5k.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import{jh as M}from"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";import m from"chalk";import K from"open";var A=`
2
- ____ _ _
3
- | __ )| | __ _ __| | ___
4
- | _ \\| |/ _\` |/ _\` |/ _ \\
5
- | |_) | | (_| | (_| | __/
6
- |____/|_|\\__,_|\\__,_|\\___|
7
- `,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
8
- `));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
9
- `)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
10
- `));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
@@ -1 +0,0 @@
1
- import{ld as a,md as b,nd as c}from"./chunk-2428hhvj.js";import"./chunk-s7jsadnc.js";import"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zvz2cnt4.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1 +0,0 @@
1
- import{bd as a,cd as b,dd as c,ed as d,fd as e,gd as f,hd as g,id as h}from"./chunk-mtphps19.js";import"./chunk-t2wgf9tq.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e}from"./chunk-be30r8an.js";import"./chunk-azw0jckv.js";import"./chunk-wfy851et.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,22 +0,0 @@
1
- import{s as Pz,t as xz}from"./chunk-s77sbxr7.js";import{u as E}from"./chunk-ahg9vjb6.js";import{A as Hz,v as Nz,w as $z,x as Qz,y as Wz,z as Yz}from"./chunk-byqxaa9v.js";import{E as N,N as e,Q as zz,R as Jz,V as Zz,ja as jz,ka as Xz,la as Dz,ma as Lz}from"./chunk-d3ttqmyt.js";import{wa as qz}from"./chunk-qgrq04hb.js";import"./chunk-92x15fzx.js";import{db as n,pb as t,yb as s}from"./chunk-nx31fkkf.js";import{Hb as M}from"./chunk-th4jjfgm.js";import{Ac as a,Cc as x,Fc as o,Kc as R,Nc as F,_b as m,ic as d,jc as v,oc as l,rc as i,tc as r,zc as k}from"./chunk-97aywyzn.js";import"./chunk-0wxkymqv.js";import"./chunk-mtphps19.js";import{qd as Ez}from"./chunk-0vrgrw71.js";import"./chunk-bjqjdw34.js";import{Ld as _z,Md as Oz}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import{Xd as I}from"./chunk-0j22w4wh.js";import{$d as p}from"./chunk-zdnk7qtn.js";import"./chunk-wrfay5r3.js";import{ie as Az}from"./chunk-yn51162x.js";import"./chunk-fcv8b6ny.js";import"./chunk-axtzde5k.js";import"./chunk-hat9v5c5.js";import{Te as Rz}from"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import{Lf as wz,Of as Kz}from"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as h,rg as c,sg as S}from"./chunk-xz6y0w4n.js";import{wg as Fz}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Xg as T}from"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import{ch as Uz,fh as Vz}from"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";import{Readable as uz,Writable as gz}from"node:stream";import*as b from"@agentclientprotocol/sdk";import Gz from"node:path";import{PROTOCOL_VERSION as Cz,RequestError as fz}from"@agentclientprotocol/sdk";import{RequestError as yz}from"@agentclientprotocol/sdk";import{nanoid as y}from"nanoid";var B=T("Agent");function g(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function hz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:g(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:g("headers"in z?z.headers:void 0)};return null}function Sz(z){let Z={};for(let J of z){let Y=hz(J);if(Y)Z[J.name]=Y}return Z}function Bz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function Mz(z){let Z=a(z.metadata);return Z?[{type:"text",text:k(Z)}]:Bz(z.content)}function kz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}function Iz(z){if(!p(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...d("capacity"),resource:z.resource}}class P{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Hz({maxPendingItems:$z,maxPendingBytes:Qz,writeTimeoutMs:Wz,signal:J.signal,sizeOf:(W)=>Buffer.byteLength(JSON.stringify(W)),write:async(W)=>{await J.sessionUpdate(W)},onFailure:(W)=>this.handleUpdateEgressFailure(W)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([F.loadSession(this.id,this.cwd),F.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await F.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Zz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(B.debug(`[AcpSession ${this.id}] Initializing...`),await F.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),B.debug(`[AcpSession ${this.id}] ACP service context initialized`),await s.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?Sz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await e.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,Q)=>{let j=await J.execute(W,{cwd:Q.cwd,env:Q.env,timeout:Q.timeoutMs,signal:Q.signal,allowLocalFallback:!1,onOutput:(X)=>Q.onOutput?.("stdout",X)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Xz(this.cwd),B.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=n.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.schedulePendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!r(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of Mz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);B.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{B.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await this.runtime.rewindSession(Q);return this.messages=[...j.messages],this.contextMessages=await this.loadModelContextOr(j.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),j}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=!1,D,G=(U)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:U.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:U.result?.message||U.result?.error||`Subagent ${U.status}`}}]})},L=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(U)=>{if(X)G(U);else D=U}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.session.id,status:"in_progress",title:`Resuming ${L.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${L.source.id} at depth ${L.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),X=!0,D)G(D);return L}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,X)},complete:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,X)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,j)},getLogs:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,j)},setLoggingLevel:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,j)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(L)=>{if(L.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.toolCall.id,status:"in_progress",title:`Review: ${L.toolCall.function.name}`,content:[],kind:this.mapToolKind(L.toolKind)});else if(L.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.toolCall.id,status:L.result.success?"completed":"failed",content:[]})}}),D=await X.completion,G=(await E.list(this.cwd,this.id)).find((L)=>L.start.reviewId===X.reviewId);if(!G)throw Error(`Review not found: ${X.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:X.reviewId,status:D.status,findings:D.findings.length,content:m(G.start,D)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,X)=>{let D=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,G=this.mapToolKind(X);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:G})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Dz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await F.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let W=Y.content||Y.message;if(W)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){return B.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=Lz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)).map((H)=>{let W;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)W=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;W=W?`${W} | ${Q}`:Q}return{name:H.name,description:H.description,input:W?{hint:W}:void 0}});B.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),B.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){B.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,W=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((L)=>L.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=o(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let L=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!L.accepted)throw Error(L.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(B.debug(`[AcpSession ${this.id}] Queued steering for active turn (${L.queued})`),L.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let j=new AbortController,X=!1,D,G=new Promise((L)=>{D=L});this.pendingPrompt=j,this.pendingPromptCompletion=G;try{if(B.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),jz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,j.signal)}let L={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:j.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},U=await t(this.agent.chatStream(Y,L,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let V=$.toolCall,O=V.function.name;if(O===x)break;let A=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let q=JSON.parse(V.function.arguments),K=q.resume_from??q.resume;if(typeof K==="string")w=`Resuming ${String(q.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:A});break}case"tool_progress":{let V=$.toolCall;if(V.function.name===x)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let V=$.toolCall;if(V.function.name===x)break;let O=$.result,A=[],w=O.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let K of w.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;A.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))A.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,Tz=Jz(i(zz(K,O),l));A.push({type:"content",content:{type:"text",text:Tz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))A.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let q=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:q,content:A});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
- `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
- `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
5
- `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${$.revision} (${$.serverName}): ${$.phase} ${$.attempt}/${$.maxAttempts}
6
- `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${$.revision} (${$.serverName}) ${$.level}${$.logger?` logger=${$.logger}`:""}: ${$.message}
7
- `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${$.revision} (${$.serverName}): ${$.action}${$.detailsOmitted?" details-omitted":""}
8
- `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${$.revision} ${$.taskId} (${$.serverName}/${$.toolName}): ${$.status}${$.hasResult?" result-available":""}
9
- `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${$.files.length}${$.blockedWrite?" (write retry required)":""}
10
- `}});break;case"provider_admission":X=$.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":$.phase!=="admitted"?{phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:$.phase,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.retryAfterMs!==void 0?{retryAfterMs:$.retryAfterMs}:{},...$.nextProbeAt!==void 0?{nextProbeAt:$.nextProbeAt}:{},openDurationMs:$.openDurationMs,...$.sampleCount!==void 0?{sampleCount:$.sampleCount}:{},...$.failureCount!==void 0?{failureCount:$.failureCount}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.delayMs!==void 0?{delayMs:$.delayMs}:{},...$.nextRetryAt!==void 0?{nextRetryAt:$.nextRetryAt}:{},...$.mode!==void 0?{mode:$.mode}:{},...$.recoveryBudgetMs!==void 0?{recoveryBudgetMs:$.recoveryBudgetMs}:{},...$.recoveryElapsedMs!==void 0?{recoveryElapsedMs:$.recoveryElapsedMs}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{},...$.exhaustedBy!==void 0?{exhaustedBy:$.exhaustedBy}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware}}});break;case"task_update":this.sendPlanUpdate($.tasks);break;case"steering_applied":break;case"follow_up_started":for(let V of $.messages){if(!V.recovered||V.persisted)continue;for(let O of Bz(V.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:O})}if($.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${$.recovered} queued instruction${$.recovered===1?"":"s"} recovered after restart]
11
- `}});break;case"goal_updated":if($.goal)this.sendUpdate(this.goalSessionUpdate($.goal));if($.goal&&$.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${$.goal.status}: ${$.goal.objective}]
12
- `}});break;case"goal_continuation_started":break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{}}}});break;default:break}if(!await this.flushUpdates())j.abort("acp-egress-failed")});if(!await this.flushUpdates())j.abort("acp-egress-failed");this.contextMessages=[...L.messages];let f=await F.loadSession(this.id,this.cwd);if(this.messages=f.length>0?f:[...L.messages],!U.success){let $=U.error?.type??"unknown",V=U.error?.details??U.error?.message??"Agent execution failed",O=Iz(V)??v(V);throw yz.internalError({failureType:$,taskFailure:{code:O.code,retryable:O.retryable,...O.resource?{resource:O.resource}:{}}},`Agent turn failed (${$})`)}if(j.signal.aborted)return{stopReason:"cancelled"};let u={...U.metadata?.structuredOutput?{structuredOutput:U.metadata.structuredOutput,outputSchemaDigest:U.metadata.structuredOutputSchemaDigest}:{},...U.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:U.metadata.goalVerificationVerdict,...U.metadata.goalVerifierSessionId?{verifierSessionId:U.metadata.goalVerifierSessionId}:{},...U.metadata.goalVerificationEvidenceSha256?{evidenceSha256:U.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(u).length>0?{_meta:u}:{}}}catch(L){if(j.signal.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};throw B.error(`[AcpSession ${this.id}] Prompt error:`,L),L}finally{if(X&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(D(),this.pendingPromptCompletion===G)this.pendingPromptCompletion=null;if(this.pendingPrompt===j){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=z.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let J=new AbortController,Y,H=new Promise((j)=>{Y=j});this.pendingUserShell=J,this.pendingUserShellCompletion=H;let W,Q="";try{let j=await this.runtime.executeUserShellCommand(Z,{signal:J.signal,onEvent:async(D)=>{if(W=D.executionId,D.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.executionId,status:"in_progress",title:`! ${D.command}`,content:[],kind:"execute"});return}if(D.type==="output"){Q+=D.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:D.chunk}}]});return}let G=k(D.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.executionId,status:D.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?kz(D.record):G}}]})}}),X={role:"user",content:j.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(j.record))}};if(this.messages.push(X),this.contextMessages.push(X),j.delivery==="next_turn")this.schedulePendingResume();if(!await this.flushUpdates())return J.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:j.record.status==="aborted"?"cancelled":"end_turn"}}catch(j){if(W)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W,status:"failed",content:[{type:"content",content:{type:"text",text:j instanceof Error?j.message:String(j)}}]});if(J.signal.aborted)return{stopReason:"cancelled"};throw j}finally{if(Y(),this.pendingUserShellCompletion===H)this.pendingUserShellCompletion=null;if(this.pendingUserShell===J)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let z=this.runtime.getPendingSteeringCount()>0,Z=z?null:await this.runtime.getGoal(),J=Z?.status==="active"||Z?.status==="verifying";if(!z&&!J){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:J}).catch((Y)=>{B.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){B.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let z=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(!z)B.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let J=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(J);await F.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=J,B.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(B.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await F.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(J){if(Z&&Z!==z)await this.agent.switchModel(Z).catch((Y)=>{B.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw J}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid reasoning effort")}if(Z.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(J){throw await this.runtime.refresh({reasoningEffort:Z.selection}),J}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid service tier")}if(Z.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(J){throw await this.runtime.refresh({serviceTier:Z.selection}),J}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid response verbosity")}if(Z.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(J){throw await this.runtime.refresh({responseVerbosity:Z.selection}),J}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),J=this.runtime.resolveCommunicationStyleConfiguration(z);if(J.source!=="built-in"&&!J.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await F.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:J.source==="built-in"?null:J.contentSha256})}catch(Y){if(!(Y instanceof R)&&Y.code!=="ENOENT")throw Y;await F.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...J.source!=="built-in"&&J.contentSha256?{communicationStyleDigest:J.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.updateEgress.close(new Yz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let Z=this.agent,J=this.runtime,Y=this.pendingPromptCompletion,H=this.pendingUserShellCompletion;this.agent=null,this.runtime=null;let W,Q=async(j)=>{try{await j()}catch(X){W??=X}};if(await Q(()=>this.cancel()),Y)await Q(()=>Y);if(H)await Q(()=>H);if(z&&Y&&J)await Q(()=>J.discardPendingInput());if(Z)await Q(()=>Z.destroy());if(J)await Q(()=>J.dispose());if(await Q(()=>N.destroySession(this.id)),B.debug(`[AcpSession ${this.id}] Destroyed`),W!==void 0)throw W}resolvePrompt(z){let Z=[],J=[],Y=0,H=0,W=0,Q=(X)=>{if(J.length>0)J.push({type:"text",text:`
13
- `}),W+=1;if(J.push(X),X.type==="text")W+=X.text.length};for(let X of z)if(X.type==="text")Z.push(X.text),Q({type:"text",text:X.text});else if(X.type==="image"){let D=`data:${X.mimeType};base64,${X.data}`;Y+=1,H+=D.length,Z.push(`[Image: ${X.mimeType}]`),Q({type:"image_url",image_url:{url:D}})}else if(X.type==="resource"){let D=X.resource;if("text"in D){let G=`<file path="${D.uri}">
14
- ${D.text}
15
- </file>`;Z.push(G),Q({type:"text",text:G})}}else if(X.type==="resource_link"){let D=`[Resource: ${X.uri}]`;Z.push(D),Q({type:"text",text:D})}if(Y>h)throw Error(`ACP prompt contains more than ${h} images`);if(H>c)throw Error("ACP prompt images exceed the 5 MiB limit");if(W>S)throw Error(`ACP prompt text exceeds ${S} characters`);let j=Z.join(`
16
- `);return{content:Y>0?J:j,displayText:j}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let Z=this.updateEgress.offer({sessionId:this.id,update:z});if(!Z.accepted)return!1;try{return await Z.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;B.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed")}sendPlanUpdate(z){let Z=z.map((J)=>({content:J.subject,priority:J.priority,status:J.status}));B.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(z){let Z=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,Z);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,Z);let J=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(J))return B.debug(`[AcpSession ${this.id}] Auto-approving ${J} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(J==="write"||J==="execute"))return B.debug(`[AcpSession ${this.id}] Rejecting ${J} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=y(),H=[];if(z.message)H.push({type:"content",content:{type:"text",text:z.message}});if(z.details)H.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
17
- - ${z.risks.join(`
18
- - `)}`}});let W=this.mapToolKind(J),Q={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:z.title||"Permission Required",content:H,kind:W}},j=await this.waitForClientInteraction(this.connection.requestPermission(Q),Z);if(!j)return{approved:!1,reason:M};let X=j.outcome;if(X.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let D=X.optionId;if(D==="allow_always")return{approved:!0,scope:"project"};if(D==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let G=D==="allow_once";return{approved:G,scope:"once",reason:G?void 0:"User denied the operation"}}catch(Y){return B.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,Z){let J=z.questions??[];if(J.length===0)return{approved:!1,reason:"No structured questions were provided"};if(J.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[H,W]of J.entries()){let Q=W.options.map((G,L)=>`answer:${H}:${L}`),j=`answer:${H}:cancel`,X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...W.options.map((G,L)=>({optionId:Q[L],name:G.label,kind:"allow_once"})),{optionId:j,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:y(),status:"pending",title:W.header,kind:"think",content:[{type:"content",content:{type:"text",text:[W.question,...W.options.map((G)=>`${G.label}: ${G.description}`)].join(`
19
- `)}}]}}),Z);if(!X)return{approved:!1,reason:M};if(X.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let D=Q.indexOf(X.outcome.optionId);if(D<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[W.header]=W.options[D].label}return{approved:!0,answers:Y}}catch(H){return B.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,Z){let J=z.mcpElicitation;if(!J)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(J.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[J.message,`Server: ${J.serverName}`,`Domain: ${J.domain??"unknown"}`,`URL: ${J.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
20
- `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let H of J.fields??[]){let W=await this.collectAcpElicitationField(H,Z);if(W.cancelled)return{approved:!1,reason:W.reason,elicitation:{action:"cancel"}};if(W.value!==void 0)Y[H.name]=W.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return B.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,Z){if(z.type==="select"||z.type==="boolean"){let J=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((W,Q)=>({id:`option:${Q}`,label:W.label,value:W.value})),Y=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
21
- `),[...J.map((W)=>({id:W.id,label:W.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Y==="skip")return{cancelled:!1};let H=J.find((W)=>W.id===Y);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(z.defaultValue!==void 0){let J=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
22
- `),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],Z);if(J==="default")return{cancelled:!1,value:z.defaultValue};if(J==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,Z,J,Y){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...J.map((W)=>({optionId:W.id,name:W.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:y(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),Y);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(z,Z){if(!Z)return z;if(Z.aborted)return;return new Promise((J,Y)=>{let H=!1,W=(j)=>{if(H)return;H=!0,Z.removeEventListener("abort",Q),j()},Q=()=>W(()=>J(void 0));if(Z.addEventListener("abort",Q,{once:!0}),Z.aborted)Q();z.then((j)=>W(()=>J(j)),(j)=>W(()=>Y(j)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var _=T("Agent");class C{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;constructor(z){this.connection=z}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=_z();this.runtimeResidencyValue=new xz({maxResident:z?.maxResidentSessionRuntimes??wz,idleMs:z?.sessionRuntimeIdleMs??Kz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(Z){if(Z instanceof Pz)throw fz.internalError({resource:Z.resource,limit:Z.limit,retryable:Z.retryable},Z.message);throw Z}}async initialize(z){return _.info("[BladeAgent] Initializing ACP connection"),_.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await Oz(),{protocolVersion:Cz,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let Z=I("acp"),J=await this.reserveSessionRuntime(Z),Y=z.cwd||Fz(),H=z._meta?.["blade/taskIsolation"],W=H==="local"||H==="worktree"?H:void 0,Q=z._meta?.["blade/taskPrompt"],j;try{let X=W?await Nz.createSessionTask({sessionId:Z,prompt:typeof Q==="string"&&Q.trim()?Q:"ACP task session",sourceProjectPath:Y,isolation:W}):void 0,D=X?.metadata.projectPath??Y;return _.info(`[BladeAgent] Creating new session: ${Z}`),_.debug(`[BladeAgent] Session cwd: ${D}`),j=new P(Z,D,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...X?.taskWorktree?{taskWorktree:X.taskWorktree}:{},...X?.metadata.taskIsolation?{taskIsolation:X.metadata.taskIsolation}:{}}),await j.initialize(),this.assertNotDestroyed(),this.commitSession(Z,j,J),_.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),j.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,X?.metadata,j.getModelConfiguration())}catch(X){throw J.cancel(),await j?.destroy().catch(()=>{return}),X}}async listSessions(z){if(z.cwd!=null&&!Gz.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let Z=await F.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((J)=>({sessionId:J.sessionId,cwd:J.projectPath,title:J.title??null,updatedAt:J.lastMessageTime,_meta:{"blade/taskStatus":J.taskStatus,...J.taskStatusReason?{"blade/taskStatusReason":J.taskStatusReason}:{},...J.taskFailure?{"blade/taskFailure":J.taskFailure}:{},...J.taskStartedAt?{"blade/taskStartedAt":J.taskStartedAt}:{},...J.taskCompletedAt?{"blade/taskCompletedAt":J.taskCompletedAt}:{},...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskIsolation?{"blade/taskIsolation":J.taskIsolation}:{},...J.taskSourceProjectPath?{"blade/taskSourceProjectPath":J.taskSourceProjectPath}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{},...J.taskDiffStat?{"blade/taskDiffStat":J.taskDiffStat}:{},...J.taskQueuePosition?{"blade/taskQueuePosition":J.taskQueuePosition}:{},...J.taskQueueDepth!==void 0?{"blade/taskQueueDepth":J.taskQueueDepth}:{},...J.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":J.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!Gz.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Z=I("fork"),J=await this.reserveSessionRuntime(Z),Y;try{let H=await F.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd,newSessionId:Z});return this.assertNotDestroyed(),Y=new P(H.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:H.messages,permissionMode:H.metadata.permissionMode,mcpServers:z.mcpServers}),await Y.initialize(),this.assertNotDestroyed(),this.commitSession(H.sessionId,Y,J),Y.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H.sessionId,H.metadata,Y.getModelConfiguration())}catch(H){throw J.cancel(),await Y?.destroy().catch(()=>{return}),H}}async loadSession(z){this.assertNotDestroyed(),_.info(`[BladeAgent] Loading session: ${z.sessionId}`);let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await F.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let Z=await this.reserveSessionRuntime(z.sessionId),J;try{let[Y,H]=await Promise.all([F.loadSession(z.sessionId,z.cwd),F.findSessionMetadata(z.sessionId,z.cwd)]);if(!H)throw Error(`Session not found: ${z.sessionId}`);return J=new P(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:Y,permissionMode:H.permissionMode,mcpServers:z.mcpServers}),await J.initialize(),await J.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,J,Z),J.sendAvailableCommandsDelayed(),this.buildSessionSetup(J.getModelConfiguration(),J.getMode())}catch(Y){throw Z.cancel(),await J?.destroy().catch(()=>{return}),Y}}commitSession(z,Z,J){let Y=J.commit({key:z,surface:"acp",value:Z,canEvict:()=>Z.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===Z)this.sessions.delete(z);await Z.destroy()}});this.sessions.set(z,Z),Y.release()}async closeResidentSession(z,Z={}){let J=this.sessions.get(z);if(!J)return;let Y=this.runtimeResidency.owns(z,J),H;try{await J.destroy(Z)}catch(Q){H=Q}let W=await this.runtimeResidency.forget(z,J);if(this.sessions.get(z)===J)this.sessions.delete(z);if(Y&&!W&&H===void 0)throw Error(`ACP Session is still active: ${z}`);if(H!==void 0)throw H}buildChildSessionResponse(z,Z,J){return{sessionId:z,...this.buildSessionSetup(J,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,Z="default"){let J=z?.models??[],Y=(z?.currentModelId&&J.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??J[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],W=[];if(J.length>0)W.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:J.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)W.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="off"?"Disable model reasoning":`Use ${Q} reasoning effort`}))]});if(z?.serviceTier)W.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="fast"?"Use the provider priority tier":Q==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)W.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:`Use ${Q} response verbosity`}))]});if(z?.communicationStyle)W.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Q)=>({value:Q.id,name:Q.name,description:`${Q.description} · ${Q.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:W.length>0?W:void 0}}async closeSession(z){this.assertNotDestroyed();let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let Z=this.runtimeResidency.acquire(z.sessionId);if(!Z)throw Error(`Session not found: ${z.sessionId}`);try{return await Z.value.prompt(z)}finally{Z.release()}}async cancel(z){_.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let Z=this.runtimeResidency.acquire(z.sessionId);if(Z){_.info("[BladeAgent] Found session, calling session.cancel()");try{Z.value.cancel()}finally{Z.release()}}else _.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){_.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let Z=this.runtimeResidency.acquire(z.sessionId);if(Z)try{await Z.value.setMode(z.modeId)}finally{Z.release()}return{}}async setSessionConfigOption(z){let Z=this.runtimeResidency.acquire(z.sessionId);if(!Z)throw Error(`Session not found: ${z.sessionId}`);try{let J=Z.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")_.info(`[BladeAgent] Setting session model: ${z.value}`),await J.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&Az(z.value))_.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await J.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&Vz(z.value))_.info(`[BladeAgent] Setting service tier: ${z.value}`),await J.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&Uz(z.value))_.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await J.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&Rz(z.value))_.info(`[BladeAgent] Setting communication style: ${z.value}`),await J.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(J.getModelConfiguration(),J.getMode()).configOptions??[]}}finally{Z.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let Z of[...this.sessions.keys()])try{await this.closeResidentSession(Z)}catch(J){z??=J}try{await this.runtimeResidency.disposeAll()}catch(Z){z??=Z}this.sessions.clear();try{await qz.getInstance().disconnectAll()}catch(Z){z??=Z}if(z!==void 0)throw z}}async function hJ(){let z=gz.toWeb(process.stdout),Z=uz.toWeb(process.stdin),J=b.ndJsonStream(z,Z),Y,H=new b.AgentSideConnection((Q)=>{return Y=new C(Q),Y},J),W=Ez(async()=>{await Y?.destroy()});try{await H.closed}finally{W(),await Y?.destroy()}}export{hJ as runAcpIntegration};
@@ -1 +0,0 @@
1
- import{f as a,g as i,h as l,i as m}from"./chunk-93tvxmqg.js";import"./chunk-9hchc346.js";import"./chunk-rm9hbew3.js";import"./chunk-s77sbxr7.js";import"./chunk-ahg9vjb6.js";import"./chunk-byqxaa9v.js";import"./chunk-d3ttqmyt.js";import"./chunk-qgrq04hb.js";import"./chunk-92x15fzx.js";import"./chunk-nx31fkkf.js";import"./chunk-th4jjfgm.js";import"./chunk-97aywyzn.js";import"./chunk-0wxkymqv.js";import"./chunk-mtphps19.js";import{qd as n}from"./chunk-0vrgrw71.js";import"./chunk-bjqjdw34.js";import{Md as s}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zdnk7qtn.js";import"./chunk-wrfay5r3.js";import"./chunk-yn51162x.js";import"./chunk-fcv8b6ny.js";import"./chunk-axtzde5k.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.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 +0,0 @@
1
- import{jd as a,kd as b}from"./chunk-3hy06st1.js";import"./chunk-azw0jckv.js";import"./chunk-wfy851et.js";export{a as globalOptions,b as cliConfig};
@@ -1 +0,0 @@
1
- import{Ee as a,Fe as b,Ge as c,He as d,Ie as e,Je as f,Ke as g,Le as h,Me as i,Ne as j}from"./chunk-axtzde5k.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1 +0,0 @@
1
- import{ih as a,jh as b,kh as c,lh as d,mh as e,nh as f}from"./chunk-azw0jckv.js";import"./chunk-wfy851et.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +0,0 @@
1
- import{ee as a}from"./chunk-zdnk7qtn.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{a as createChatServiceAsync};
@@ -1 +0,0 @@
1
- import{Gd as a,Hd as b,Id as c,Jd as d,Kd as e,Ld as f,Md as g,Nd as h,Od as i,Pd as j,Qd as k,Rd as l,Sd as m,Td as n,Ud as o,Vd as p,Wd as q}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,2 +0,0 @@
1
- var _=20,T=5242880,A=32000;
2
- export{_ as qg,T as rg,A as sg};
@@ -1 +0,0 @@
1
- import{fe as a,ge as b,he as c}from"./chunk-wrfay5r3.js";import"./chunk-yn51162x.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
@@ -1,18 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-Da1vB81L.js","assets/index-BOgOL4hG.js","assets/vendor-react-DG5dkZ_t.js","assets/vendor-radix-DXRuAJHH.js","assets/vendor-icons-B63aW_OM.js","assets/session-events-BvtUOaNG.js","assets/index-DbWgTuT3.css"])))=>i.map(i=>d[i]);
2
- import{r as b,j as e}from"./vendor-react-DG5dkZ_t.js";import{u as F,a as y,b as ge,s as Fe,c as qe,d as Q,D as $e,e as De,f as ze,g as Be,h as Ie,i as _e,j as T,k as U,B as xe,_ as Ge,S as We,l as Je,m as Qe,C as Ye,n as Xe}from"./index-BOgOL4hG.js";import{U as we,Q as Ze,G as et,Z as tt,L as R,E as st,T as se,C as ne,_ as at,w as rt,$ as nt,B as it,a0 as Pe,z as ie,n as ve,R as ke,t as ot,H as ct,a1 as Ve,V as lt,a2 as dt,a3 as ut,a4 as mt,P as Le,a5 as ht,X as xt,a6 as pt,a7 as ft,f as Oe,a8 as bt,W as gt,a as vt}from"./vendor-icons-B63aW_OM.js";import{k as kt,g as jt,l as yt,e as wt,t as Nt,j as St}from"./session-events-BvtUOaNG.js";import{j as Ct,k as Et,l as Tt,m as Ue}from"./vendor-radix-DXRuAJHH.js";function Ne(t){return t.split("/").filter(Boolean).at(-1)||t}function Mt(){const t=F(),s=y(S=>S.sessions),a=y(S=>S.currentSessionRef),r=y(S=>S.taskDeliveryActions),i=y(S=>S.deliverTask),n=ge(S=>S.openFilePreview),[d,f]=b.useState(!1),l=s.find(S=>Fe({sessionId:S.sessionId,projectPath:S.projectPath},a));if(!(l!=null&&l.taskIsolation))return null;const c=l.taskDiffStat,k=l.taskIsolation==="worktree",o=qe(l),h=r[Q(o)],u=l.taskDelivery,j=(u==null?void 0:u.status)==="conflicted",N=!!(c&&(c.changedFiles>0||c.commits>0)),m=!["queued","running"].includes(l.taskStatus),w=(u==null?void 0:u.status)==="applied"||(u==null?void 0:u.status)==="discarded",v=k&&N&&m&&!w,p=c?c.additions+c.deletions:0,x=p>0&&c?c.additions/p*100:0,E=S=>{i(o,S).catch(()=>{})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex min-h-10 flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/60 px-3 py-1.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm sm:px-5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[e.jsx(we,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:Ne(l.taskSourceProjectPath||l.projectPath)})]}),e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[k?e.jsx(Ze,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx(we,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:k?"text-[hsl(var(--deck-accent))]":void 0,children:t(k?"artifact.env.isolated":"artifact.env.local")})]}),l.taskWorktreeBranch&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 truncate",title:l.taskWorktreeBranch,children:[e.jsx(et,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:l.taskWorktreeBranch})]})]})]}),c&&e.jsxs("div",{className:"ml-auto flex max-w-full items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(tt,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:c.changedFiles})]}),p>0&&e.jsxs("span",{className:"relative hidden h-1.5 w-14 overflow-hidden rounded-sm border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] sm:inline-flex","aria-hidden":"true",children:[e.jsx("span",{className:"h-full bg-[hsl(var(--deck-accent))]",style:{width:`${x}%`}}),e.jsx("span",{className:"h-full bg-red-500/80",style:{width:`${100-x}%`}})]}),e.jsxs("span",{className:"tabular-nums text-[hsl(var(--deck-accent))]",children:["+",c.additions]}),e.jsxs("span",{className:"tabular-nums text-red-600 dark:text-red-400",children:["-",c.deletions]}),c.commits>0&&e.jsx("span",{className:"hidden tabular-nums text-[hsl(var(--deck-ink-faint))] sm:inline",children:t("artifact.commits",{count:c.commits})}),N&&(u==null?void 0:u.status)!=="discarded"&&e.jsx("button",{type:"button",onClick:()=>n({tab:"diff"}),className:"inline-flex items-center gap-1 rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-2 py-1 text-[hsl(var(--deck-ink))] transition hover:border-[hsl(var(--deck-accent)/0.55)] hover:text-[hsl(var(--deck-accent))]",children:t("artifact.review")}),v&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!h,onClick:()=>E("apply"),className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-accent))] px-2 py-1 font-semibold text-white transition hover:brightness-95 disabled:cursor-wait disabled:opacity-65",children:[h==="apply"?e.jsx(R,{className:"h-3 w-3 animate-spin"}):e.jsx(st,{className:"h-3 w-3"}),t(h==="apply"?"artifact.applying":j?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!h,onClick:()=>f(!0),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-[hsl(var(--deck-ink-faint))] transition hover:bg-red-500/10 hover:text-red-600 disabled:cursor-wait disabled:opacity-50 dark:hover:text-red-400","aria-label":t("artifact.discard"),title:t("artifact.discard"),children:h==="discard"?e.jsx(R,{className:"h-3 w-3 animate-spin"}):e.jsx(se,{className:"h-3 w-3"})})]}),(u==null?void 0:u.status)==="applied"&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-emerald-500/10 px-2 py-1 font-semibold text-emerald-700 dark:text-emerald-300",children:[e.jsx(ne,{className:"h-3 w-3"}),t("artifact.applied")]}),(u==null?void 0:u.status)==="discarded"&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-surface-2))] px-2 py-1 text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(se,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(u==null?void 0:u.status)==="conflicted"&&e.jsxs("div",{className:"flex w-full items-start gap-1.5 border-t border-amber-500/20 pt-1.5 text-amber-700 dark:text-amber-300",role:"alert",children:[e.jsx(at,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1 space-y-0.5",children:[e.jsx("span",{className:"block",children:u.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx($e,{open:d,onOpenChange:f,children:e.jsxs(De,{className:"w-[calc(100%_-_2rem)] max-w-md border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] text-[hsl(var(--deck-ink))]",children:[e.jsxs(ze,{children:[e.jsx(Be,{children:t("artifact.discardDialog.title")}),e.jsx(Ie,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:Ne(l.taskSourceProjectPath||l.projectPath),count:(c==null?void 0:c.changedFiles)??0})})]}),e.jsx("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-xs leading-relaxed text-red-700 dark:text-red-300",children:t("artifact.discardDialog.warning")}),e.jsxs(_e,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>f(!1),className:"rounded-md border border-[hsl(var(--deck-border))] px-3 py-2 text-sm hover:bg-[hsl(var(--deck-surface-2))]",children:t("artifact.discardDialog.cancel")}),e.jsxs("button",{type:"button",onClick:()=>{f(!1),E("discard")},className:"inline-flex items-center justify-center gap-1.5 rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white hover:bg-red-700",children:[e.jsx(se,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}const At=new Set(["completed","stale","failed","aborted","interrupted"]),Rt={completed:"chat.review.status.completed",stale:"chat.review.status.stale",failed:"chat.review.status.failed",aborted:"chat.review.status.aborted",interrupted:"chat.review.status.interrupted"},Ft={completed:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",stale:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20",failed:"bg-red-500/10 text-red-700 dark:text-red-300 border-red-500/20",aborted:"bg-zinc-500/10 text-zinc-700 dark:text-zinc-300 border-zinc-500/20",interrupted:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20"};function ae(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function $t(t){const s=ae(t),a=ae(s==null?void 0:s.codeLocation),r=s==null?void 0:s.priority,i=s==null?void 0:s.confidenceScore,n=a==null?void 0:a.lineStart,d=a==null?void 0:a.lineEnd;if(!(typeof(s==null?void 0:s.title)!="string"||typeof s.body!="string"||r!==0&&r!==1&&r!==2&&r!==3||typeof i!="number"||!Number.isFinite(i)||typeof(a==null?void 0:a.path)!="string"||!Number.isInteger(n)||!Number.isInteger(d)))return{title:s.title,body:s.body,priority:r,confidenceScore:i,codeLocation:{path:a.path,lineStart:n,lineEnd:d}}}function Dt(t){const s=ae(t),a=ae(s==null?void 0:s.target);if((s==null?void 0:s.phase)!=="completed"||typeof s.status!="string"||!At.has(s.status)||typeof(a==null?void 0:a.label)!="string"||a.kind!=="uncommitted"&&a.kind!=="base"&&a.kind!=="commit"||typeof s.overallExplanation!="string"||!Array.isArray(s.findings))return;const r=s.findings.map($t);if(!r.some(i=>i===void 0))return{status:s.status,target:{kind:a.kind,label:a.label,...typeof a.reference=="string"?{reference:a.reference}:{}},overallExplanation:s.overallExplanation,findings:r,...typeof s.error=="string"?{error:s.error}:{}}}function Bt(t){const{path:s,lineStart:a,lineEnd:r}=t.codeLocation;return a===r?`${s}:L${a}`:`${s}:L${a}-${r}`}function It({report:t}){const s=F(),a=t.target.kind==="uncommitted"?s("chat.review.target.uncommitted"):t.target.kind==="base"?s("chat.review.target.base",{ref:t.target.reference??t.target.label}):s("chat.review.target.commit",{ref:t.target.reference??t.target.label});return e.jsxs("section",{"data-code-review-report":!0,className:"overflow-hidden rounded-xl border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface-2))]/60 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.review.title")}),e.jsxs("p",{className:"mt-0.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-faint))]",children:[s("chat.review.target"),": ",a]})]}),e.jsxs("span",{className:T("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",Ft[t.status]),children:[s("chat.review.status"),": ",s(Rt[t.status])]})]}),e.jsxs("div",{className:"space-y-4 px-4 py-3.5",children:[e.jsx("p",{className:"whitespace-pre-wrap text-[13px] leading-6 text-[hsl(var(--deck-ink-muted))]",children:t.overallExplanation}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("h4",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.findings")}),e.jsx("span",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:t.findings.length})]}),t.findings.length===0?e.jsx("div",{className:"rounded-lg bg-[hsl(var(--deck-surface-2))] px-3 py-2.5 text-[12px] text-[hsl(var(--deck-ink-muted))]",children:s("chat.review.noFindings")}):e.jsx("ol",{className:"space-y-2",children:t.findings.map((r,i)=>e.jsxs("li",{className:"rounded-lg border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))] px-3 py-2.5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsx("h5",{className:"text-[12.5px] font-medium leading-5 text-[hsl(var(--deck-ink))]",children:r.title}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.confidence",{value:r.confidenceScore.toFixed(2)})})]}),e.jsx("code",{className:"mt-1 block text-[10.5px] text-[hsl(var(--deck-accent))]",children:Bt(r)}),e.jsx("p",{className:"mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:r.body})]},`${r.codeLocation.path}:${r.codeLocation.lineStart}:${i}`))})]}),t.error&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-[11px] text-red-700 dark:text-red-300",children:[e.jsxs("span",{className:"font-medium",children:[s("chat.review.error"),":"]})," ",t.error]})]})]})}function _t({elicitation:t,messageId:s}){const a=F(),r=y(v=>v.currentSessionRef),i=y(v=>v.setElicitation),[n,d]=b.useState(()=>Vt(t.details.fields??[])),[f,l]=b.useState(()=>Lt(t.details.fields??[])),[c,k]=b.useState(!1),[o,h]=b.useState(),u=t.details.fields??[],j=b.useMemo(()=>u.every(v=>{var x;if(!v.required)return!0;if(oe(v))return!!((x=f[v.name])!=null&&x.trim()||v.defaultValue!==void 0);const p=n[v.name]??v.defaultValue;return Array.isArray(p)?p.length>0:p!==void 0}),[u,f,n]);if(t.status!=="pending")return e.jsx("div",{className:"rounded-lg border 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:a(t.status==="cancelled"?"interaction.elicitation.cancelled":"interaction.elicitation.responded")});const N=async(v,p)=>{if(!(!r||c)){k(!0),h(void 0);try{await U.respondToElicitation(r,t.toolCallId,{action:v,...p?{content:p}:{}}),i(s,{...t,status:"responded"})}catch(x){h(x instanceof Error?x.message:a("interaction.elicitation.failed"))}finally{k(!1)}}},m=async()=>{try{await N("accept",Ot(u,n,f))}catch(v){h(v instanceof Error?v.message:String(v))}},w=()=>{const v=t.details.url;if(!v){h("MCP URL is unavailable");return}if(!window.open(v,"_blank","noopener,noreferrer")){h("The browser blocked the external window");return}N("accept")};return e.jsxs("div",{"data-pending-interaction":"elicitation",tabIndex:-1,role:"alert",className:"space-y-4 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(rt,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"font-mono text-[12px] font-semibold text-[hsl(var(--deck-ink))]",children:[a("interaction.elicitation.title")," · ",t.details.serverName]}),e.jsx("div",{className:"font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:t.details.message}),e.jsx("div",{className:"font-mono text-[11px] text-amber-700 dark:text-amber-300",children:a("interaction.elicitation.warning")})]})]}),t.details.mode==="url"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] p-3 font-mono text-[11px]",children:[e.jsx("div",{className:"text-[hsl(var(--deck-ink-muted))]",children:t.details.domain}),e.jsx("div",{className:"mt-1 break-all text-[hsl(var(--deck-ink))]",children:t.details.url})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(q,{onClick:w,disabled:c,primary:!0,label:a("interaction.elicitation.open"),icon:e.jsx(nt,{className:"h-3.5 w-3.5"})}),e.jsx(q,{onClick:()=>void N("decline"),disabled:c,label:a("interaction.elicitation.decline")}),e.jsx(q,{onClick:()=>void N("cancel"),disabled:c,label:a("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[u.map(v=>e.jsx(Pt,{field:v,value:n[v.name],rawValue:f[v.name]??"",onValueChange:p=>d(x=>({...x,[v.name]:p})),onRawChange:p=>l(x=>({...x,[v.name]:p}))},v.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(q,{onClick:()=>void m(),disabled:c||!j,primary:!0,label:a("interaction.elicitation.submit"),icon:c?e.jsx(R,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(q,{onClick:()=>void N("decline"),disabled:c,label:a("interaction.elicitation.decline")}),e.jsx(q,{onClick:()=>void N("cancel"),disabled:c,label:a("interaction.elicitation.cancel")})]})]}),o&&e.jsx("div",{className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:o})]})}function Pt({field:t,value:s,rawValue:a,onValueChange:r,onRawChange:i}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:`mcp-elicitation-${t.name}`,className:"block font-mono text-[12px] font-medium text-[hsl(var(--deck-ink))]",children:[t.title,t.required?" *":""]}),t.description&&e.jsx("div",{className:"font-mono text-[11px] text-[hsl(var(--deck-ink-faint))]",children:t.description}),t.type==="select"||t.type==="multi-select"||t.type==="boolean"?e.jsx("div",{id:`mcp-elicitation-${t.name}`,className:"flex flex-wrap gap-2",children:Ut(t).map(n=>{const d=Array.isArray(s)?s.includes(n.value):s===n.typedValue;return e.jsx("button",{type:"button","aria-pressed":d,onClick:()=>{if(t.type==="multi-select"){const f=Array.isArray(s)?s:[];r(f.includes(n.value)?f.filter(l=>l!==n.value):[...f,n.value])}else r(n.typedValue)},className:T("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",d?"border-emerald-500 bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200":"border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:n.label},n.value)})}):e.jsx("input",{id:`mcp-elicitation-${t.name}`,type:Ht(t),value:a,onChange:n=>i(n.target.value),min:t.minimum,max:t.maximum,minLength:t.minLength,maxLength:t.maxLength,required:t.required,placeholder:t.defaultValue===void 0?t.required?"Required":"Optional":String(t.defaultValue),className:"w-full rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink))] outline-none transition-colors focus:border-amber-500 focus:ring-1 focus:ring-amber-500"})]})}function q({onClick:t,disabled:s,primary:a=!1,label:r,icon:i}){return e.jsxs("button",{type:"button",onClick:t,disabled:s,className:T("inline-flex min-h-8 items-center gap-1.5 rounded-md px-3 py-1.5 font-mono text-[12px] transition-colors disabled:cursor-wait disabled:opacity-50",a?"bg-amber-600 text-white hover:bg-amber-700":"border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:[i,r]})}function Vt(t){return Object.fromEntries(t.filter(s=>!oe(s)&&s.defaultValue!==void 0).map(s=>[s.name,Array.isArray(s.defaultValue)?[...s.defaultValue]:s.defaultValue]))}function Lt(t){return Object.fromEntries(t.filter(s=>oe(s)&&s.defaultValue!==void 0).map(s=>[s.name,String(s.defaultValue)]))}function Ot(t,s,a){var i;const r={};for(const n of t){if(oe(n)){const f=((i=a[n.name])==null?void 0:i.trim())??"";if(!f){if(n.defaultValue!==void 0)r[n.name]=n.defaultValue;else if(n.required)throw new Error(`${n.title} is required`);continue}if(n.type==="number"||n.type==="integer"){const l=Number(f);if(!Number.isFinite(l))throw new Error(`${n.title} must be a finite number`);if(n.type==="integer"&&!Number.isSafeInteger(l))throw new Error(`${n.title} must be a safe integer`);r[n.name]=l}else r[n.name]=f;continue}const d=s[n.name]??n.defaultValue;if(d===void 0){if(n.required)throw new Error(`${n.title} is required`);continue}if(Array.isArray(d)){if(n.minItems!==void 0&&d.length<n.minItems)throw new Error(`${n.title} requires at least ${n.minItems} choices`);if(n.maxItems!==void 0&&d.length>n.maxItems)throw new Error(`${n.title} allows at most ${n.maxItems} choices`)}r[n.name]=d}return r}function Ut(t){return t.type==="boolean"?[{value:"true",label:"Yes",typedValue:!0},{value:"false",label:"No",typedValue:!1}]:(t.options??[]).map(s=>({...s,typedValue:s.value}))}function oe(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function Ht(t){return t.type==="number"||t.type==="integer"?"number":t.format==="email"?"email":t.format==="uri"?"url":t.format==="date"?"date":t.format==="date-time"?"datetime-local":"text"}function Kt(t){if(!t||typeof t!="object"||Array.isArray(t))return;const s=t;if(!(!s.output||typeof s.output!="object"||Array.isArray(s.output)))return{output:s.output,...typeof s.schemaDigest=="string"?{schemaDigest:s.schemaDigest}:{}}}function qt({report:t}){const s=F(),[a,r]=b.useState(!1),i=JSON.stringify(t.output,null,2),n=async()=>{try{await navigator.clipboard.writeText(i),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}};return e.jsxs("section",{"data-structured-output":!0,className:"overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex min-h-9 items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(it,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsx("span",{className:"font-mono text-[11px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.structuredOutput.title")}),t.schemaDigest&&e.jsxs("span",{title:t.schemaDigest,className:"truncate font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:["sha256:",t.schemaDigest.slice(0,10)]})]}),e.jsx("button",{type:"button",onClick:n,"aria-label":s("chat.structuredOutput.copy"),title:s("chat.structuredOutput.copy"),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-[hsl(var(--deck-ink-faint))] hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:a?e.jsx(ne,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(Pe,{className:"h-3.5 w-3.5"})})]}),e.jsx("pre",{className:"max-h-[440px] overflow-auto whitespace-pre p-3 font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink))]",children:i})]})}const zt=b.lazy(()=>Ge(()=>import("./MarkdownRenderer-Da1vB81L.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Se({text:t,label:s}){const[a,r]=b.useState(!1);if(!t.trim())return null;const i=async()=>{try{await navigator.clipboard.writeText(t),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}};return e.jsx("button",{type:"button","aria-label":s,title:s,onClick:i,className:"flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:a?e.jsx(ne,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(Pe,{className:"h-3.5 w-3.5"})})}function Gt(){return e.jsx("div",{className:"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] shadow-[0_1px_0_hsl(var(--deck-hairline))]",children:e.jsx(xe,{size:20,pulse:!1})})}function Wt(){return e.jsx("div",{className:"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-full border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas-veil))]",children:e.jsx("span",{className:"font-mono text-[11px] font-medium text-[hsl(var(--deck-ink))]",children:"U"})})}function Ce(t){let s=t;return s=s.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,""),s=s.replace(/<file path="[^"]*">[\s\S]*?<\/file>/g,""),s=s.replace(/<attached_files>[\s\S]*?<\/attached_files>/g,""),s=s.trim(),s}function Jt(t){if(typeof t=="string")return{text:Ce(t),images:[]};const s=t.filter(r=>r.type==="text").map(r=>r.text).join(`
3
- `),a=t.filter(r=>r.type==="image_url").map(r=>r.image_url.url);return{text:Ce(s),images:a}}function je(t){return typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.text).join(`
4
- `)}function Qt(t){const s=t.agentContent;return s?kt(s):je(t.content)}function Ee({content:t,syntaxHighlight:s=!0}){return e.jsx(b.Suspense,{fallback:e.jsx("pre",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono whitespace-pre-wrap",children:t}),children:e.jsx(zt,{content:t,syntaxHighlight:s})})}function ye({status:t}){if(!t)return null;const s={running:"bg-[#FEF3C7] text-[#92400E] dark:bg-[#F59E0B]/20 dark:text-[#FBBF24]",success:"bg-[#DCFCE7] text-[#15803D] dark:bg-[#22C55E]/20 dark:text-[#22C55E]",error:"bg-[#FEE2E2] text-[#b91c1c] dark:bg-[#EF4444]/20 dark:text-[#fca5a5]",pending:"bg-[#E5E7EB] text-[#6B7280] dark:bg-[#27272a] dark:text-[#a1a1aa]",info:"bg-[#DBEAFE] text-[#1D4ED8] dark:bg-[#3B82F6]/20 dark:text-[#60A5FA]"},a={running:"Running",success:"Success",error:"Error",pending:"Pending",info:"Info"};return e.jsx("span",{className:T("text-[11px] px-2 py-0.5 rounded-full font-mono",s[t]),children:a[t]})}function Yt(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)}const Te=500;function He(t,s){if(t.length<=s)return t;let a=Math.max(0,s);return a>0&&/[\uD800-\uDBFF]/.test(t.charAt(a-1))&&(a-=1),t.slice(0,a)}function Me(t,s){if(t.length<=s)return t;let a=Math.max(0,t.length-s);return/[\uDC00-\uDFFF]/.test(t.charAt(a))&&(a+=1),t.slice(a)}function de(t,s){if(t.length<=s)return t;if(s<=0)return"";const a=`
5
- ... (display clipped) ...
6
- `,r=s-a.length;if(r<=0)return Me(t,s);const i=Math.floor(r/3);return`${He(t,i)}${a}${Me(t,r-i)}`}function Xt(t){const s=t.split(`
7
- `),a=s.at(-1),r=a!=null&&a.startsWith("Output truncated")?a:void 0,i=r?s.slice(0,-1).join(`
8
- `):t,n=r?`
9
- ${r}`:"",d=Math.max(0,Te-n.length),l=i.indexOf(`
10
- stderr:
11
- `);let c;if(l>=0&&i.includes(`
12
- stdout:
13
- `)){const k=i.slice(0,l),o=i.slice(l+1),h=Math.max(0,d-1),u=Math.floor(h/2);c=`${de(k,u)}
14
- ${de(o,h-u)}`}else c=de(i,d);return{body:He(c,d),...r?{notice:r}:{},truncated:!!r||t.length>Te}}function Zt({tool:t}){const[s,a]=b.useState(!1),r=Yt(t.arguments),i=t.output?Xt(t.output):void 0;return e.jsxs("div",{"data-tool-name":t.toolName,"data-tool-status":t.status,"data-tool-truncated":i!=null&&i.truncated?"true":"false",className:"bg-white dark:bg-[#18181b] border border-[hsl(var(--deck-border))] rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button","aria-expanded":s,"data-tool-call-id":t.toolCallId,onClick:()=>a(n=>!n),className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--deck-surface-2))] hover:bg-[hsl(var(--deck-surface))] transition-colors",children:[e.jsxs("div",{className:"flex gap-2 items-center min-w-0",children:[s?e.jsx(ie,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}):e.jsx(ve,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}),e.jsx("span",{className:"text-[12px] text-[hsl(var(--deck-ink))] font-mono shrink-0",children:t.toolName}),t.summary&&e.jsx("span",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono truncate",children:t.summary})]}),e.jsx(ye,{status:t.status})]}),t.status==="running"&&t.progressMessage&&e.jsxs("div",{className:"border-t border-[hsl(var(--deck-border))] px-3 py-2 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx("span",{className:"truncate",children:t.progressMessage}),t.progressTotal!==void 0&&t.progress!==void 0&&e.jsxs("span",{className:"shrink-0",children:[Math.max(0,Math.min(100,Math.round(t.progress/t.progressTotal*100))),"%"]})]}),t.progressTotal!==void 0&&t.progress!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${t.toolName} progress`,"aria-valuemin":0,"aria-valuemax":t.progressTotal,"aria-valuenow":Math.min(t.progress,t.progressTotal),className:"h-1 overflow-hidden rounded-full bg-[hsl(var(--deck-border))]",children:e.jsx("div",{className:"h-full rounded-full bg-amber-500 transition-[width] duration-150",style:{width:`${Math.max(0,Math.min(100,t.progress/t.progressTotal*100))}%`}})})]}),s&&e.jsxs("div",{className:"px-3 py-2 space-y-2 border-t border-[hsl(var(--deck-border))]",children:[r&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:"Arguments"}),e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:r})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:"Output"}),e.jsxs("pre",{"data-tool-output":!0,className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:[i.body,i.notice&&e.jsxs(e.Fragment,{children:[`
15
- `,e.jsx("span",{"data-tool-truncation-notice":!0,children:i.notice})]})]})]})]})]})}function Ke({toolCalls:t}){return t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map(s=>e.jsx(Zt,{tool:s},s.toolCallId))})}function es({toolCalls:t,toolCallIds:s}){const a=F(),[r,i]=b.useState(!1),n=b.useMemo(()=>new Map(t.map(o=>[o.toolCallId,o])),[t]),d=s.flatMap(o=>{const h=n.get(o);return h?[h]:[]});if(d.length===0)return null;const f=d.filter(o=>o.status==="running").length,l=d.filter(o=>o.status==="error").length,c=[...d].reverse().find(o=>o.status==="running"&&!!o.progressMessage),k=f>0?a(d.length===1?"chat.timeline.tools.runningOne":"chat.timeline.tools.running",{count:d.length}):l>0?a(d.length===1?"chat.timeline.tools.completedOneWithError":"chat.timeline.tools.completedWithErrors",{count:d.length,errors:l}):a(d.length===1?"chat.timeline.tools.completedOne":"chat.timeline.tools.completed",{count:d.length});return e.jsxs("div",{"data-agent-tool-group":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>i(o=>!o),className:"group flex min-h-7 w-full items-center gap-1.5 rounded-md px-1.5 text-left font-mono text-[11.5px] text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))]/65 hover:text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[r?e.jsx(ie,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(ve,{className:"h-3.5 w-3.5 shrink-0"}),f>0&&e.jsx(R,{className:"h-3 w-3 shrink-0 animate-spin text-[hsl(var(--deck-accent))]"}),e.jsx("span",{children:k}),(c==null?void 0:c.progressMessage)&&e.jsxs("span",{className:"min-w-0 truncate text-[10.5px] text-[hsl(var(--deck-ink-muted))]",children:[c.progressMessage,c.progress!==void 0&&c.progressTotal!==void 0&&` · ${Math.max(0,Math.min(100,Math.round(c.progress/c.progressTotal*100)))}%`]})]}),(c==null?void 0:c.progress)!==void 0&&c.progressTotal!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${c.toolName} progress`,"aria-valuemin":0,"aria-valuemax":c.progressTotal,"aria-valuenow":Math.min(c.progress,c.progressTotal),className:"mx-1.5 h-0.5 overflow-hidden rounded-full bg-[hsl(var(--deck-border))]",children:e.jsx("div",{className:"h-full rounded-full bg-amber-500 transition-[width] duration-150",style:{width:`${Math.max(0,Math.min(100,c.progress/c.progressTotal*100))}%`}})}),r&&e.jsx("div",{"data-agent-tool-group-details":!0,className:"mt-2 space-y-2 pl-1",children:e.jsx(Ke,{toolCalls:d})})]})}function ts({content:t}){const s=F(),[a,r]=b.useState(!1);return t?e.jsxs("div",{"data-agent-thinking":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":a,onClick:()=>r(i=>!i),className:"flex min-h-7 w-full items-center gap-1.5 rounded-md px-1.5 text-left font-mono text-[11.5px] text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))]/65 hover:text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[a?e.jsx(ie,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}):e.jsx(ve,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{children:s("chat.timeline.thinking")})]}),a&&e.jsx("div",{className:"ml-1 mt-1 border-l border-[hsl(var(--deck-border))] py-1 pl-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:t})})]}):null}function ss({tasks:t}){if(t.length===0)return null;const s=t.filter(r=>r.status==="completed").length,a=s===t.length;return e.jsx("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:e.jsx("div",{className:"flex gap-2 items-center",children:e.jsx("span",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:a?"✓ All tasks done":`Tasks: ${s}/${t.length}`})})})}function as({toolCalls:t}){const s=ge(r=>r.openFilePreview),a=b.useMemo(()=>{const r=new Map,i=["Write","SearchReplace","Edit","ApplyPatch"];for(const n of t){if(n.status!=="success")continue;const d=n.metadata;if(n.toolName==="ApplyPatch"&&Array.isArray(d==null?void 0:d.changes)){for(const l of d.changes)l&&typeof l=="object"&&"path"in l&&typeof l.path=="string"&&r.set(l.path,{path:l.path,toolName:n.toolName});continue}const f=d==null?void 0:d.file_path;f&&i.includes(n.toolName)&&r.set(f,{path:f,toolName:n.toolName})}return Array.from(r.values())},[t]);return a.length===0?null:e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:[e.jsxs("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono mb-1.5",children:["Changed files (",a.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(({path:r})=>{const i=r.split("/").pop()||r;return e.jsxs("button",{onClick:()=>s({tab:"diff",targetPath:r}),className:"flex items-center gap-1 px-2 py-1 text-[11px] font-mono bg-[#E5E7EB] dark:bg-[#27272a] text-[hsl(var(--deck-ink))] rounded hover:bg-[#D1D5DB] dark:hover:bg-[#3f3f46] transition-colors",title:r,children:[e.jsx(ot,{className:"w-3 h-3"}),i]},r)})})]})}function rs({subagent:t}){var G,K,Y,X;const s=F(),[a,r]=b.useState(null),[i,n]=b.useState(!1),[d,f]=b.useState(null),[l,c]=b.useState(!1),[k,o]=b.useState(""),[h,u]=b.useState(!1),[j,N]=b.useState(null),[m,w]=b.useState(null),[v,p]=b.useState(null),x=y(M=>M.currentSessionRef),E=y(M=>M.isStreaming),S=y(M=>M.isTemporarySession);if(!t)return null;const D=t.status==="running",A=a!==null?a:D,L=t.toolCalls||d||[],_=t.output||t.thinking||L.length>0||t.sessionId,C=m&&m.status!=="running"?m:v,B=(C==null?void 0:C.id)??t.sessionId,H=((G=C==null?void 0:C.restartRecovery)==null?void 0:G.outcome)==="failed",ce=!D&&!E&&!S&&!H&&(m==null?void 0:m.status)!=="running"&&!!(B&&x);b.useEffect(()=>{if(!A||D||!t.sessionId||!(x!=null&&x.projectPath)||d!==null||t.toolCalls&&t.toolCalls.length>0)return;let M=!0;return n(!0),U.getMessages({sessionId:t.sessionId,projectPath:x.projectPath}).then(P=>{var I,$;if(!M)return;const V=wt(P),g=new Map;for(const W of V)if(($=(I=W.agentContent)==null?void 0:I.toolCalls)!=null&&$.length)for(const le of W.agentContent.toolCalls)g.has(le.toolCallId)||g.set(le.toolCallId,le);f(Array.from(g.values()))}).finally(()=>{M&&n(!1)}),()=>{M=!1}},[A,D,t.sessionId,t.toolCalls,d,x==null?void 0:x.projectPath]),b.useEffect(()=>{if(!t.sessionId||!x)return;let M=!0;const P=t.rootAgentId??t.sessionId,V=t.resumeDepth??0;return U.listSubagents(x).then(g=>{if(!M)return;p(g.find($=>$.id===t.sessionId)??null);const I=g.filter($=>$.id!==t.sessionId&&$.rootAgentId===P&&$.resumeDepth>V).sort(($,W)=>W.resumeDepth-$.resumeDepth||W.lastActiveAt-$.lastActiveAt)[0];I&&w(I)}).catch(()=>{}),()=>{M=!1}},[x==null?void 0:x.sessionId,x==null?void 0:x.projectPath,t.sessionId,t.rootAgentId,t.resumeDepth]),b.useEffect(()=>{if(!m||m.status!=="running"||!x)return;let M=!0;const P=async()=>{try{const I=(await U.listSubagents(x)).find($=>$.id===m.id);M&&I&&w(I)}catch{}},V=window.setInterval(()=>{P()},1e3);return()=>{M=!1,window.clearInterval(V)}},[x,m==null?void 0:m.id,m==null?void 0:m.status]);const z=async()=>{if(!(!x||!B||!k.trim()||h)){u(!0),N(null);try{const M=await U.resumeSubagent(x,B,k.trim());w(M.session),o(""),c(!1),r(!0)}catch(M){N(M instanceof Error?M.message:s("chat.subagent.resumeFailed"))}finally{u(!1)}}};return e.jsxs("div",{"data-subagent-id":t.id,"data-subagent-session-id":t.sessionId,className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:[e.jsxs("button",{type:"button",onClick:()=>r(!A),className:"flex gap-2 justify-between items-center w-full transition-opacity cursor-pointer hover:opacity-80",children:[e.jsxs("div",{className:"flex gap-2 items-center",children:[D&&e.jsx(R,{className:"h-3 w-3 animate-spin text-[hsl(var(--deck-ink-muted))]"}),e.jsxs("span",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[t.type,": ",t.description]}),e.jsx(ye,{status:t.status==="completed"?"success":t.status==="failed"?"error":"running"}),t.type==="verification"&&t.verificationVerdict&&e.jsx("span",{"data-verification-verdict":t.verificationVerdict,className:T("rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide",t.verificationVerdict==="pass"?"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400":t.verificationVerdict==="fail"?"bg-red-500/10 text-red-600 dark:text-red-400":"bg-amber-500/10 text-amber-600 dark:text-amber-400"),children:t.verificationVerdict}),t.resumedFrom&&e.jsx("span",{className:"rounded bg-[#EDE9FE] px-1.5 py-0.5 text-[10px] font-mono text-[#6D28D9] dark:bg-[#2E1065] dark:text-[#C4B5FD]",title:s("chat.subagent.resumedFromTitle",{id:t.resumedFrom}),children:s("chat.subagent.resumedDepth",{depth:t.resumeDepth??1})})]}),_&&e.jsx(ie,{className:T("h-3.5 w-3.5 text-[hsl(var(--deck-ink-muted))] transition-transform",A&&"rotate-180")})]}),!A&&!D&&t.output&&e.jsx("div",{"data-subagent-output-summary":!0,className:"mt-2 max-h-10 overflow-hidden whitespace-pre-wrap break-words font-mono text-[11px] text-[hsl(var(--deck-ink))]",children:t.output}),A&&e.jsxs("div",{className:"mt-2 space-y-2",children:[(t.output||t.thinking)&&e.jsxs(e.Fragment,{children:[t.output&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[160px] overflow-y-auto",children:t.output}),t.thinking&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:t.thinking})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[e.jsx(R,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.loadingLogs")]}),!i&&L.length>0&&e.jsx(Ke,{toolCalls:L}),m&&e.jsxs("div",{className:"rounded-md border border-[#DDD6FE] bg-[#F5F3FF] p-2 text-[11px] font-mono text-[#5B21B6] dark:border-[#4C1D95] dark:bg-[#1E1B4B] dark:text-[#C4B5FD]",children:[e.jsx("div",{children:s("chat.subagent.resumedAs",{id:m.id,status:m.status,depth:m.resumeDepth??1})}),(((K=m.result)==null?void 0:K.message)||((Y=m.result)==null?void 0:Y.error))&&e.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[hsl(var(--deck-ink))]",children:m.result.message||m.result.error})]}),H&&((X=C==null?void 0:C.result)==null?void 0:X.error)&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:C.result.error}),ce&&e.jsxs("div",{className:"space-y-2",children:[l?e.jsxs("div",{className:"space-y-2 rounded-md border border-[#E5E7EB] bg-white p-2 dark:border-[#27272a] dark:bg-[#111113]",children:[e.jsx("textarea",{"aria-label":s("chat.subagent.followUpAria"),value:k,onChange:M=>o(M.target.value),placeholder:s("chat.subagent.followUpPlaceholder"),rows:3,className:"w-full resize-y rounded border border-[#D1D5DB] bg-white p-2 text-[11px] text-[#111827] outline-none focus:border-[#8B5CF6] dark:border-[#3f3f46] dark:bg-[#18181b] dark:text-[#f4f4f5]"}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx("button",{type:"button",onClick:()=>{c(!1),N(null)},className:"rounded px-2 py-1 text-[11px] text-[#6B7280] hover:bg-[#F3F4F6] dark:hover:bg-[#27272a]",children:s("chat.subagent.cancel")}),e.jsxs("button",{type:"button",onClick:()=>void z(),disabled:!k.trim()||h,className:"flex items-center gap-1 rounded bg-[#7C3AED] px-2 py-1 text-[11px] font-medium text-white disabled:opacity-50",children:[h&&e.jsx(R,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.resumeAgent")]})]})]}):e.jsxs("button",{type:"button","aria-label":s("chat.subagent.resumeAria"),onClick:()=>c(!0),className:"flex items-center gap-1.5 rounded-md border border-[#D1D5DB] px-2 py-1 text-[11px] font-medium text-[#374151] transition-colors hover:bg-[#F3F4F6] dark:border-[#3f3f46] dark:text-[#d4d4d8] dark:hover:bg-[#27272a]",children:[e.jsx(ke,{className:"w-3 h-3"}),s("chat.subagent.resume")]}),j&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:j})]})]})]})}function ns({confirmation:t,messageId:s}){const a=F(),[r,i]=b.useState(!1),[n,d]=b.useState(null),f=y(k=>k.currentSessionRef),l=y(k=>k.setConfirmation);if(!t)return null;const c=async(k,o)=>{if(!(!f||r)){i(!0),d(null);try{await U.respondPermission(f,t.toolCallId,{approved:k,scope:o}),l(s,{...t,status:k?"approved":"denied"})}catch(h){d(h instanceof Error?h.message:a("interaction.permission.failed"))}finally{i(!1)}}};return t.status!=="pending"?null:e.jsxs("div",{"data-pending-interaction":"permission",tabIndex:-1,role:"alert",className:"space-y-3 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:a("interaction.permission.title",{tool:t.toolName})}),e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:t.description}),t.diff&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[200px] overflow-y-auto",children:t.diff}),n&&e.jsx("div",{role:"alert",className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:n}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void c(!0,"once"),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#22C55E] text-white rounded-md hover:bg-[#16A34A] disabled:cursor-wait disabled:opacity-50",children:r?e.jsx(R,{className:"h-3.5 w-3.5 animate-spin"}):a("interaction.permission.once")}),t.allowRemember!==!1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>void c(!0,"session"),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#3B82F6] text-white rounded-md hover:bg-[#2563EB] disabled:cursor-wait disabled:opacity-50",children:a("interaction.permission.session")}),e.jsx("button",{type:"button",onClick:()=>void c(!0,"project"),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#6366F1] text-white rounded-md hover:bg-[#4F46E5] disabled:cursor-wait disabled:opacity-50",children:a("interaction.permission.project")})]}),e.jsx("button",{type:"button",onClick:()=>void c(!1),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#EF4444] text-white rounded-md hover:bg-[#DC2626] disabled:cursor-wait disabled:opacity-50",children:a("interaction.permission.deny")})]})]})}function is({question:t,messageId:s}){const a=F(),[r,i]=b.useState({}),[n,d]=b.useState({}),[f,l]=b.useState(!1),[c,k]=b.useState(null),o=y(m=>m.currentSessionRef),h=y(m=>m.setQuestion),u=b.useMemo(()=>t?t.questions.reduce((m,w)=>{var E;const v=(E=n[w.header])==null?void 0:E.trim(),p=r[w.header];if(w.multiSelect){const S=Array.isArray(p)?[...p]:[];return v&&S.push(v),S.length>0&&(m[w.header]=S),m}const x=v||(typeof p=="string"?p:"");return x&&(m[w.header]=x),m},{}):{},[r,n,t]),j=(t==null?void 0:t.questions.every(m=>m.header in u))??!1;if(!t)return null;const N=async()=>{if(!(!o||f||!j)){l(!0),k(null);try{await U.respondToQuestion(o,t.toolCallId,u),h(s,{...t,status:"answered",answers:u})}catch(m){k(m instanceof Error?m.message:a("interaction.question.failed"))}finally{l(!1)}}};return t.status!=="pending"?e.jsx("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:a("interaction.question.answered")})}):e.jsxs("div",{"data-pending-interaction":"question",tabIndex:-1,role:"alert",className:"space-y-4 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[t.questions.map((m,w)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:m.question}),e.jsxs("div",{className:"space-y-1",children:[m.options.map((v,p)=>e.jsxs("button",{type:"button",onClick:()=>{if(m.multiSelect){const x=r[m.header]||[],E=x.includes(v.label)?x.filter(S=>S!==v.label):[...x,v.label];i({...r,[m.header]:E})}else i({...r,[m.header]:v.label}),d({...n,[m.header]:""})},className:T("w-full text-left px-3 py-2 rounded-md border text-[12px] font-mono transition-colors","border-[hsl(var(--deck-border))]",(m.multiSelect?(r[m.header]||[]).includes(v.label):r[m.header]===v.label)?"bg-[#DCFCE7] text-[#166534] dark:bg-[#22C55E]/20 dark:text-[#E5E5E5]":"bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))]"),children:[e.jsx("div",{children:v.label}),e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-faint))] mt-1",children:v.description})]},p)),e.jsx("input",{"aria-label":`${m.header} other response`,value:n[m.header]??"",onChange:v=>d({...n,[m.header]:v.target.value}),placeholder:a("interaction.question.other"),className:"w-full rounded-md border border-[#E5E7EB] bg-white px-3 py-2 text-[12px] text-[#111827] outline-none focus:border-[#22C55E] dark:border-[#27272a] dark:bg-[#111113] dark:text-[#E5E5E5]"})]})]},w)),c&&e.jsx("div",{role:"alert",className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:c}),e.jsxs("button",{type:"button",onClick:()=>void N(),disabled:f||!j,className:"inline-flex min-h-8 items-center gap-1.5 px-3 py-1.5 text-[12px] font-mono bg-[#22C55E] text-white rounded-md hover:bg-[#16A34A] disabled:cursor-wait disabled:opacity-50",children:[f&&e.jsx(R,{className:"h-3.5 w-3.5 animate-spin"}),a("interaction.question.submit")]})]})}function os({message:t}){const s=t.agentContent,a=y(j=>j.isStreaming&&j.currentAssistantMessageId===t.id);if(!s){const j=je(t.content);return j?e.jsx(Ee,{content:j}):null}const{toolCalls:r,tasks:i,confirmation:n,question:d,elicitation:f}=s,l=jt(s),c=yt(s);if(!(c.length>0||i.length>0||l.length>0||n||d||f)&&a)return e.jsxs("div",{className:"flex items-center gap-2 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(R,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-[12px] font-mono",children:"Thinking..."})]});const h=r.length>0&&r.every(j=>j.status==="success"||j.status==="error")&&!a,u=!a;return e.jsxs("div",{className:"space-y-3",children:[c.map(j=>j.type==="thinking"?e.jsx("div",{"data-agent-timeline-block":"thinking",children:e.jsx(ts,{content:j.content})},j.id):j.type==="text"?e.jsx("div",{"data-agent-timeline-block":"text",children:e.jsx(Ee,{content:j.content,syntaxHighlight:u})},j.id):e.jsx("div",{"data-agent-timeline-block":"tool_group",children:e.jsx(es,{toolCalls:r,toolCallIds:j.toolCallIds})},j.id)),i.length>0&&e.jsx(ss,{tasks:i}),l.map(j=>e.jsx(rs,{subagent:j},j.id)),n&&e.jsx(ns,{confirmation:n,messageId:t.id}),d&&e.jsx(is,{question:d,messageId:t.id}),f&&e.jsx(_t,{elicitation:f,messageId:t.id}),h&&e.jsx(as,{toolCalls:r})]})}function cs({message:t,showAvatar:s=!0}){var f,l,c,k;const a=t.role==="user";if(t.role==="system"){const o=je(t.content);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"system",className:"flex justify-center p-2 w-full",children:e.jsx("div",{className:"text-xs text-[hsl(var(--deck-ink-muted))] bg-[#F3F4F6] dark:bg-[#18181b] px-3 py-1 rounded-full font-mono",children:o})})}if(a){const o=(f=t.metadata)!=null&&f.userShellCommand&&typeof t.metadata.userShellCommand=="object"?t.metadata.userShellCommand:(l=t.metadata)!=null&&l.userShellExecution&&typeof t.metadata.userShellExecution=="object"?t.metadata.userShellExecution:void 0;if(o){const j=typeof o.command=="string"?o.command:"",N=o.status==="running"?"running":o.status==="completed"?"success":"error",m=typeof o.output=="string"?o.output:[typeof o.stdout=="string"?o.stdout:"",typeof o.stderr=="string"&&o.stderr?`stderr:
16
- ${o.stderr}`:""].filter(Boolean).join(`
17
- `);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"user","data-user-shell-command":!0,className:"flex w-full justify-end p-4",children:e.jsxs("div",{className:"w-full max-w-[85%] overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 truncate font-mono text-[12px] text-[hsl(var(--deck-ink))]",children:[e.jsx("span",{className:"mr-2 text-amber-600 dark:text-amber-400",children:"$"}),j]}),e.jsx(ye,{status:N})]}),e.jsx("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap px-3 py-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:m||"(no output)"}),typeof o.exitCode=="number"&&e.jsxs("div",{className:"border-t border-[hsl(var(--deck-border))] px-3 py-1.5 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:["exit ",o.exitCode,typeof o.durationMs=="number"?` · ${(o.durationMs/1e3).toFixed(3)}s`:"",o.truncated===!0?" · truncated":""]})]})})}const{text:h,images:u}=Jt(t.content);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"user",className:"group flex gap-2 justify-end p-4 w-full items-start",children:[e.jsx("div",{className:"mt-1 flex shrink-0 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(Se,{text:h,label:"Copy message"})}),e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] rounded-lg px-4 py-3 max-w-[85%]",children:[h&&e.jsx("p",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono leading-relaxed whitespace-pre-wrap",children:h}),u.length>0&&e.jsx("div",{className:T("grid gap-2",u.length===1?"grid-cols-1 mt-0":"grid-cols-2 mt-3"),children:u.map((j,N)=>e.jsx("img",{src:j,alt:`attachment-${N+1}`,className:"object-cover w-full max-h-64 rounded-md"},`${j}-${N}`))})]}),e.jsx(Wt,{})]})}const i=Qt(t),n=Dt((c=t.metadata)==null?void 0:c.codeReview),d=Kt((k=t.metadata)==null?void 0:k.structuredOutput);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"assistant",className:T("group flex gap-4 justify-start w-full",s?"p-4":"px-4 pt-0 pb-3"),children:[s?e.jsx(Gt,{}):e.jsx("div",{className:"w-8 shrink-0"}),e.jsxs("div",{className:"overflow-hidden flex-1 min-w-0",children:[n?e.jsx(It,{report:n}):d?e.jsx(qt,{report:d}):e.jsx(os,{message:t}),!d&&i.trim()&&e.jsx("div",{className:"mt-1.5 flex opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(Se,{text:i,label:"Copy response"})})]})]})}const ls=b.memo(cs);function ds(t,s,a){return Math.max(0,t+(a-s))}function us(t,s,a){return Math.min(s,Math.max(0,t)+Math.max(0,a))}function Ae(t,s){return t?t.querySelector(`[data-chat-message-id="${CSS.escape(s)}"]`):null}function ms({turns:t,viewportRef:s,containerRef:a,onRevealTurn:r}){const i=F(),[n,d]=b.useState(null),[f,l]=b.useState(!1),c=b.useRef(null),k=b.useCallback(()=>{var m;const h=s.current,u=a.current;if(!h||!u||t.length===0)return;const j=h.getBoundingClientRect().top;let N=((m=t[0])==null?void 0:m.id)??null;for(const w of t){const v=Ae(u,w.id);if(v)if(v.getBoundingClientRect().top-j<=24)N=w.id;else break}d(N)},[t,s,a]);b.useEffect(()=>{const h=s.current;if(!h)return;const u=()=>{c.current===null&&(c.current=window.requestAnimationFrame(()=>{c.current=null,k()}))};return k(),h.addEventListener("scroll",u,{passive:!0}),()=>{h.removeEventListener("scroll",u),c.current!==null&&(window.cancelAnimationFrame(c.current),c.current=null)}},[k,s]);const o=b.useCallback(h=>{const u=()=>{const N=Ae(a.current,h.id);N&&(N.scrollIntoView({behavior:"smooth",block:"start"}),d(h.id))};r(h.index)?u():window.requestAnimationFrame(()=>window.requestAnimationFrame(u))},[a,r]);return t.length<2?null:e.jsx("nav",{"aria-label":i("chat.turns.aria"),className:"absolute right-1 top-1/2 z-20 hidden -translate-y-1/2 sm:block",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),onFocusCapture:()=>l(!0),onBlurCapture:h=>{h.currentTarget.contains(h.relatedTarget)||l(!1)},children:e.jsxs("div",{className:"relative flex items-center justify-end",children:[e.jsx("ul",{className:T("flex flex-col items-center gap-2 py-2 transition-opacity",f?"opacity-0":"opacity-100"),"aria-hidden":f,children:t.map(h=>e.jsx("li",{children:e.jsx("span",{className:T("block rounded-full transition-all",h.id===n?"h-2 w-2 bg-[hsl(var(--deck-accent))]":"h-1.5 w-1.5 bg-[hsl(var(--deck-ink-faint))]/40")})},h.id))}),e.jsx("div",{className:T("absolute right-0 max-h-[min(70vh,520px)] w-[280px] overflow-y-auto rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]/95 p-1 shadow-xl backdrop-blur transition-all",f?"pointer-events-auto translate-x-0 opacity-100":"pointer-events-none translate-x-2 opacity-0"),children:t.map((h,u)=>e.jsxs("button",{type:"button",onClick:()=>o(h),className:T("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors",h.id===n?"bg-[hsl(var(--deck-hairline))]/70 text-[hsl(var(--deck-ink))]":"text-[hsl(var(--deck-ink-muted))] hover:bg-[hsl(var(--deck-hairline))]/50 hover:text-[hsl(var(--deck-ink))]"),children:[e.jsx("span",{className:T("mt-1 h-1.5 w-1.5 shrink-0 rounded-full",h.id===n?"bg-[hsl(var(--deck-accent))]":"bg-[hsl(var(--deck-ink-faint))]/40")}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block font-mono text-[9.5px] uppercase tracking-[0.12em] text-[hsl(var(--deck-ink-faint))]",children:i("chat.turns.label",{n:u+1})}),e.jsx("span",{className:"line-clamp-2 text-[12px] leading-4",children:h.preview})]})]},h.id))})]})})}const Re=80;function hs(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>s.type==="text").map(s=>s.text).join(" "):""}function xs(t){const s=hs(t).replace(/\s+/g," ").trim();return s?s.length>Re?`${s.slice(0,Re-1)}…`:s:""}function ps(t){const s=[];for(let a=0;a<t.length;a+=1){const r=t[a];if(r.role!=="user"||!r.id)continue;const i=xs(r.content);i&&s.push({id:r.id,index:a,preview:i})}return s}const ue=120,me=80,fs=96;function J(t){return(t==null?void 0:t.querySelector("[data-radix-scroll-area-viewport]"))??null}function bs({messages:t,isLoading:s}){const a=F(),r=b.useRef(null),i=b.useRef(null),n=b.useRef(!0),d=b.useRef(t.length),f=b.useRef(null),[l,c]=b.useState(ue),[k,o]=b.useState(!1);b.useEffect(()=>{const p=J(r.current);if(!p||!n.current)return;const x=window.requestAnimationFrame(()=>{p.scrollTop=p.scrollHeight});return()=>window.cancelAnimationFrame(x)},[t]),b.useEffect(()=>{const p=J(r.current);if(!p)return;i.current=p;const x=()=>{const S=p.scrollHeight-p.scrollTop-p.clientHeight<=fs;n.current=S,o(!S)};return x(),p.addEventListener("scroll",x,{passive:!0}),()=>p.removeEventListener("scroll",x)},[]),b.useEffect(()=>{const p=d.current;d.current=t.length,c(x=>x>=p&&t.length>p?t.length:Math.min(Math.max(x,ue),t.length||ue))},[t.length]);const h=Math.max(t.length-l,0),u=h,j=b.useMemo(()=>t.slice(u),[t,u]),N=b.useMemo(()=>ps(t),[t]);if(b.useLayoutEffect(()=>{var E;const p=f.current;if(!p)return;const x=J(r.current);if(f.current=null,!!x){if((E=p.element)!=null&&E.isConnected){const S=p.element.getBoundingClientRect().top-p.viewportTop;x.scrollTop+=S;return}x.scrollTop=ds(p.scrollTop,p.scrollHeight,x.scrollHeight)}},[l]),s)return e.jsx("div",{role:"status","aria-live":"polite","aria-busy":"true",className:"flex overflow-hidden flex-1 justify-center items-center px-5 py-8 min-h-0",children:e.jsxs("div",{className:"w-full max-w-[560px]",children:[e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-pulse rounded-full bg-[hsl(var(--deck-accent-soft))] blur-xl"}),e.jsx(xe,{size:42,className:"relative"})]}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.16em] text-[hsl(var(--deck-accent))]",children:[e.jsx(ct,{className:"w-3 h-3"}),a("chat.list.loading.eyebrow")]}),e.jsx("h2",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:a("chat.list.loading.title")}),e.jsx("p",{className:"mt-1 max-w-sm text-[11.5px] leading-5 text-[hsl(var(--deck-ink-faint))]",children:a("chat.list.loading.hint")})]}),e.jsx("div",{"aria-hidden":"true",className:"mt-7 space-y-4 rounded-xl border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))]/45 px-4 py-5",children:[72,88,64].map((p,x)=>e.jsxs("div",{className:T("flex gap-3",x%2===1&&"flex-row-reverse"),children:[e.jsx("span",{className:"h-7 w-7 shrink-0 animate-pulse rounded-md bg-[hsl(var(--deck-surface-2))]"}),e.jsx("span",{className:"h-10 animate-pulse rounded-lg bg-[hsl(var(--deck-surface-2))]",style:{width:`${p}%`,animationDelay:`${x*120}ms`}})]},p))})]})});if(t.length===0&&!s)return e.jsx("div",{className:"flex flex-1 justify-center items-center",children:e.jsxs("div",{className:"flex flex-col gap-4 items-center text-center",children:[e.jsx(xe,{size:44}),e.jsxs("div",{children:[e.jsx("div",{className:"deck-eyebrow text-[hsl(var(--deck-accent))]",children:a("chat.list.empty.eyebrow")}),e.jsx("div",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:a("chat.list.empty.title")}),e.jsx("div",{className:"mt-1 max-w-xs text-[12px] text-[hsl(var(--deck-ink-muted))]",children:a("chat.list.empty.hint")})]})]})});const m=()=>{const p=J(r.current);p&&(n.current=!0,o(!1),p.scrollTo({top:p.scrollHeight,behavior:"smooth"}))},w=()=>{var x;const p=J(r.current);if(p){const E=((x=r.current)==null?void 0:x.querySelector("[data-chat-message-id]"))??null;f.current={element:E,viewportTop:(E==null?void 0:E.getBoundingClientRect().top)??0,scrollHeight:p.scrollHeight,scrollTop:p.scrollTop}}c(E=>us(E,t.length,me))},v=p=>p>=u?!0:(c(t.length),!1);return e.jsxs("div",{ref:r,className:"relative flex-1 min-h-0",children:[e.jsx(We,{className:"h-full",children:e.jsxs("div",{className:"flex flex-col px-4 pb-4 w-full md:px-6",children:[h>0&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsx("button",{type:"button",onClick:w,"aria-label":a("chat.list.showEarlierWithRemaining",{count:Math.min(h,me),remaining:h}),className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-3 py-1.5 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:border-[hsl(var(--deck-border-strong))] hover:text-[hsl(var(--deck-ink))]",children:a("chat.list.showEarlier",{count:Math.min(h,me)})})}),j.map((p,x)=>{const E=u+x,S=E>0?t[E-1]:null,D=!S||S.role!==p.role||S.role==="user";return e.jsx(ls,{message:p,showAvatar:D},p.id||`msg-${E}`)})]})}),e.jsx(ms,{turns:N,viewportRef:i,containerRef:r,onRevealTurn:v}),k&&e.jsxs("button",{type:"button",onClick:m,className:"absolute bottom-4 left-1/2 z-10 inline-flex -translate-x-1/2 items-center gap-1.5 rounded-full border border-[hsl(var(--deck-border-strong))] bg-[hsl(var(--deck-surface))]/95 px-3 py-1.5 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] shadow-lg backdrop-blur transition-colors hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[e.jsx(Ve,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}),a("chat.list.jumpLatest")]})]})}const gs=b.memo(bs),pe=Ct,fe=Et,be=Tt,re=b.forwardRef(({className:t,sideOffset:s=4,...a},r)=>e.jsx(Ue,{ref:r,sideOffset:s,className:T("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",t),...a}));re.displayName=Ue.displayName;const vs={active:{labelKey:"goal.status.active",dot:"bg-[hsl(var(--deck-accent))] shadow-[0_0_6px_hsl(var(--deck-accent-glow)/0.5)]",accent:"text-[hsl(var(--deck-accent))]"},verifying:{labelKey:"goal.status.active",dot:"animate-pulse bg-sky-400",accent:"text-sky-600 dark:text-sky-300"},paused:{labelKey:"goal.status.paused",dot:"bg-amber-400",accent:"text-amber-600 dark:text-amber-300"},blocked:{labelKey:"goal.status.blocked",dot:"bg-rose-500",accent:"text-rose-600 dark:text-rose-300"},usage_limited:{labelKey:"goal.status.usageLimited",dot:"bg-orange-500",accent:"text-orange-600 dark:text-orange-300"},budget_limited:{labelKey:"goal.status.budgetLimited",dot:"bg-orange-500",accent:"text-orange-600 dark:text-orange-300"},complete:{labelKey:"goal.status.complete",dot:"bg-emerald-500",accent:"text-emerald-600 dark:text-emerald-300"}};function Z(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function ks(t){if(t<60)return`${t}s`;const s=Math.floor(t/60),a=t%60;return a===0?`${s}m`:`${s}m ${a}s`}function js(){var _;const t=F(),{locale:s}=Je(),a=y(C=>C.goal),r=y(C=>C.pauseGoal),i=y(C=>C.resumeGoal),n=y(C=>C.editGoal),d=y(C=>C.clearGoal),[f,l]=b.useState(!1),[c,k]=b.useState(!1),[o,h]=b.useState(""),[u,j]=b.useState(null),[N,m]=b.useState(!1);if(b.useEffect(()=>{l(!1),k(!1),h((a==null?void 0:a.objective)??""),m(!1)},[a==null?void 0:a.goalId]),!a)return null;const w=vs[a.status],v=["active","verifying","paused","blocked"].includes(a.status),p=a.status==="active"||a.status==="verifying",x=a.status==="paused"||a.status==="blocked",E=u!==null,S=async(C,B)=>{j(C);try{await B()}finally{j(null)}},D=()=>{h(a.objective),k(!0),l(!0)},A=async C=>{C.preventDefault();const B=o.trim();if(!B||B===a.objective){k(!1);return}await S("edit",()=>n(B)),k(!1)},L=async()=>{await S("delete",d),m(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(pe,{delayDuration:250,children:e.jsxs("section",{"aria-label":t("goal.aria.section"),className:"mx-3 mb-1 shrink-0","data-blade-goal-status":a.status,children:[e.jsxs("div",{className:T("flex h-9 items-center gap-2 rounded-lg border px-3 transition-colors","border-[hsl(var(--deck-border))]/60 bg-[hsl(var(--deck-surface))]/80 backdrop-blur-sm",f&&"rounded-b-none border-b-0"),children:[a.status==="complete"?e.jsx(lt,{className:"h-3.5 w-3.5 shrink-0 text-emerald-500"}):e.jsx(dt,{className:T("h-3.5 w-3.5 shrink-0",w.accent)}),e.jsx("span",{className:T("h-1.5 w-1.5 shrink-0 rounded-full",w.dot)}),e.jsx("span",{className:T("shrink-0 text-[10px] font-medium leading-none",w.accent),children:a.status==="verifying"?s==="zh"?"验证中":"Verifying":t(w.labelKey)}),e.jsx("span",{className:"h-3 w-px shrink-0 bg-[hsl(var(--deck-hairline))]"}),e.jsx("button",{type:"button","aria-label":t(f?"goal.action.collapse":"goal.action.expand"),className:"min-w-0 flex-1 truncate text-left text-[12px] leading-5 text-[hsl(var(--deck-ink))]/85 outline-none transition-colors hover:text-[hsl(var(--deck-ink))]",onClick:()=>l(C=>!C),"aria-expanded":f,title:a.objective,children:a.objective}),a.tokensUsed>0&&e.jsxs("span",{className:"hidden shrink-0 text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))] sm:inline",children:[Z(a.tokensUsed),a.tokenBudget!==void 0&&`/${Z(a.tokenBudget)}`]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[p&&e.jsx(ee,{label:t("goal.action.pause"),disabled:E,onClick:()=>void S("pause",r),children:u==="pause"?e.jsx(R,{className:"animate-spin"}):e.jsx(ut,{})}),x&&e.jsx(ee,{label:t("goal.action.resume"),disabled:E,onClick:()=>void S("resume",i),children:u==="resume"?e.jsx(R,{className:"animate-spin"}):e.jsx(mt,{})}),e.jsx(ee,{label:t(v?"goal.action.edit":"goal.action.expand"),disabled:!v&&!f,onClick:v?D:()=>l(C=>!C),children:v?e.jsx(Le,{}):e.jsx(ht,{})}),e.jsx(ee,{label:t("goal.action.delete"),disabled:E,destructive:!0,onClick:()=>m(!0),children:e.jsx(se,{})})]})]}),f&&e.jsx("div",{className:"rounded-b-lg border border-t-0 border-[hsl(var(--deck-border))]/60 bg-[hsl(var(--deck-surface))]/80 px-4 py-3 backdrop-blur-sm",children:c?e.jsxs("form",{onSubmit:A,children:[e.jsx("textarea",{id:"goal-objective",value:o,onChange:C=>h(C.target.value),onKeyDown:C=>{C.key==="Escape"&&k(!1)},rows:3,autoFocus:!0,className:"w-full resize-none rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas))] px-3 py-2 text-[12px] leading-5 text-[hsl(var(--deck-ink))] outline-none transition-shadow focus:border-[hsl(var(--deck-accent))] focus:ring-1 focus:ring-[hsl(var(--deck-accent-glow))]"}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>k(!1),className:"inline-flex h-7 items-center gap-1 rounded-md px-2.5 text-[11px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:bg-[hsl(var(--deck-hairline))]/60",children:[e.jsx(xt,{className:"h-3 w-3"}),t("goal.action.cancel")]}),e.jsxs("button",{type:"submit",disabled:!o.trim()||u==="edit",className:"inline-flex h-7 items-center gap-1 rounded-md bg-[hsl(var(--deck-accent))] px-2.5 text-[11px] font-medium text-white transition-colors hover:bg-[hsl(var(--deck-accent))]/90 disabled:cursor-not-allowed disabled:opacity-50",children:[u==="edit"?e.jsx(R,{className:"h-3 w-3 animate-spin"}):e.jsx(ne,{className:"h-3 w-3"}),t("goal.action.save")]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink))]/90",children:a.objective}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(pt,{className:"h-3 w-3"}),Z(a.tokensUsed),a.tokenBudget!==void 0&&` / ${Z(a.tokenBudget)}`," ",t("goal.metrics.tokens")]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ft,{className:"h-3 w-3"}),ks(a.timeUsedSeconds)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ke,{className:"h-3 w-3"}),a.continuationCount===1?t("goal.metrics.continuationOne",{n:a.continuationCount}):t("goal.metrics.continuationMany",{n:a.continuationCount})]})]}),a.completionVerification&&e.jsxs("div",{"data-goal-verification":a.completionVerification.status,className:"mt-2 rounded-md border border-sky-200/50 bg-sky-50/60 px-2.5 py-2 text-[11px] text-sky-900 dark:border-sky-400/15 dark:bg-sky-400/[0.05] dark:text-sky-100",children:[e.jsxs("p",{className:"font-mono font-medium",children:["#",a.completionVerification.attempt," ·"," ",a.completionVerification.status.toUpperCase()," ·"," ",((_=a.completionVerification.verifierSessionId)==null?void 0:_.slice(0,12))??"-"]}),a.completionVerification.summary&&e.jsx("p",{className:"mt-1 line-clamp-3 whitespace-pre-wrap opacity-80",children:a.completionVerification.summary}),a.completionVerification.evidenceSha256&&e.jsxs("p",{className:"mt-1 font-mono text-[10px] opacity-60",children:["sha256:",a.completionVerification.evidenceSha256.slice(0,12)]})]}),a.statusReason&&e.jsx("div",{className:"mt-2 rounded-md border border-amber-200/50 bg-amber-50/60 px-2.5 py-1.5 text-[11px] text-amber-800 dark:border-amber-400/15 dark:bg-amber-400/[0.05] dark:text-amber-200",children:a.statusReason})]})})]})}),e.jsx($e,{open:N,onOpenChange:m,children:e.jsxs(De,{className:"max-w-[400px] border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsx(Be,{children:t("goal.dialog.title")}),e.jsx(Ie,{children:t("goal.dialog.description")}),e.jsxs(_e,{className:"mt-2",children:[e.jsx("button",{type:"button",onClick:()=>m(!1),className:"inline-flex h-8 items-center justify-center rounded-md border border-[hsl(var(--deck-border))] px-3 text-[12px] text-[hsl(var(--deck-ink))] hover:bg-[hsl(var(--deck-hairline))]/60",children:t("goal.action.cancel")}),e.jsxs("button",{type:"button",disabled:u==="delete",onClick:()=>void L(),className:"inline-flex gap-1.5 justify-center items-center px-3 h-8 text-[12px] font-medium text-white bg-rose-600 rounded-md hover:bg-rose-500 disabled:opacity-50",children:[u==="delete"&&e.jsx(R,{className:"w-3.5 h-3.5 animate-spin"}),t("goal.action.delete")]})]})]})})]})}function ee({label:t,children:s,disabled:a,destructive:r,onClick:i}){return e.jsxs(fe,{children:[e.jsx(be,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":t,disabled:a,onClick:i,className:T("flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-muted))] outline-none transition-colors focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent-glow))]/50 disabled:cursor-not-allowed disabled:opacity-35 [&_svg]:h-3.5 [&_svg]:w-3.5",r?"hover:bg-rose-500/10 hover:text-rose-500":"hover:bg-[hsl(var(--deck-hairline))]/60 hover:text-[hsl(var(--deck-ink))]"),children:s})}),e.jsx(re,{side:"top",className:"text-[10px]",children:t})]})}function ys(){const t=F(),s=y(l=>l.currentSessionRef),a=y(l=>l.sessions),r=y(l=>l.messages),i=b.useMemo(()=>{var c,k,o,h,u;const l=s?(c=Qe(a,s))==null?void 0:c.pendingInteraction:void 0;if(l)return l.type;for(let j=r.length-1;j>=0;j-=1){const N=(k=r[j])==null?void 0:k.agentContent;if(((o=N==null?void 0:N.confirmation)==null?void 0:o.status)==="pending")return"permission";if(((h=N==null?void 0:N.question)==null?void 0:h.status)==="pending")return"question";if(((u=N==null?void 0:N.elicitation)==null?void 0:u.status)==="pending")return"elicitation"}return null},[s,r,a]);if(!i)return null;const n=()=>{const l=document.querySelector(`[data-pending-interaction="${i}"]`);l==null||l.scrollIntoView({block:"center",behavior:"smooth"}),window.setTimeout(()=>l==null?void 0:l.focus(),250)},d=i==="question",f=i==="elicitation";return e.jsxs("div",{role:"alert",className:"mx-3 mb-2 flex flex-wrap items-center gap-2 rounded-lg border border-amber-300/80 bg-amber-50/95 px-3 py-2 font-mono text-amber-950 shadow-sm backdrop-blur dark:border-amber-800/80 dark:bg-amber-950/90 dark:text-amber-100 sm:mx-5",children:[e.jsx(Oe,{className:"h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-[180px] flex-1",children:[e.jsx("div",{className:"text-[11.5px] font-semibold",children:t(d?"interaction.bar.questionTitle":f?"interaction.bar.elicitationTitle":"interaction.bar.permissionTitle")}),e.jsx("div",{className:"mt-0.5 text-[10px] leading-4 text-amber-800 dark:text-amber-300",children:t(d?"interaction.bar.questionHint":f?"interaction.bar.elicitationHint":"interaction.bar.permissionHint")})]}),e.jsxs("button",{type:"button",onClick:n,className:"inline-flex min-h-8 shrink-0 items-center gap-1.5 rounded-md border border-amber-400/80 bg-white/80 px-2.5 text-[10.5px] font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-700 dark:bg-amber-950/70 dark:hover:bg-amber-900",children:[e.jsx(Ve,{className:"h-3 w-3"}),t("interaction.bar.review")]})]})}function he(t){return Number.isFinite(t)?Math.max(0,t):0}function ws(t){const s=he(t.totalInputTokens),a=he(t.cacheReadTokens),r=he(t.cacheWriteTokens),i=Math.min(a,s),n=Math.min(r,Math.max(0,s-i)),d=Math.max(0,s-i-n),f=s>0&&(a>0||r>0);return{totalInputTokens:s,cacheReadTokens:i,cacheWriteTokens:n,uncachedInputTokens:d,...f?{hitRate:i/s}:{}}}function Ns(t){return t===void 0||!Number.isFinite(t)?"—":`${Math.round(Math.max(0,Math.min(1,t))*100)}%`}const Ss={running:"status.phase.running",compacting:"status.phase.compacting",recovering_context:"status.phase.recoveringContext",switching_model:"status.phase.switchingModel",waiting_permission:"status.phase.waitingPermission",error:"status.phase.error",idle:""},Cs={model_changed:"status.cacheBreak.model",system_prompt_changed:"status.cacheBreak.system",tools_changed:"status.cacheBreak.tools",request_policy_changed:"status.cacheBreak.policy",ttl_expired:"status.cacheBreak.ttl",server_side:"status.cacheBreak.server"},O=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),te=t=>{const s=Math.max(0,Math.ceil(t/1e3)),a=Math.floor(s/60),r=s%60;return a>0?`${a}m ${r}s`:`${r}s`};function Es(){const t=F(),s=y(w=>w.tokenUsage),a=y(w=>w.isStreaming),r=y(w=>w.agentPhase),i=y(w=>w.providerAdmission),n=y(w=>w.providerCircuit),d=y(w=>w.providerRetry),f=y(w=>w.providerStall),l=y(w=>w.actionStationarity),c=Ss[r]??"",k=(d==null?void 0:d.delayMs)!==void 0?` · ${Math.max(0,Math.ceil(d.delayMs/1e3))}s`:"",o=l?`${t(l.phase==="halted"?"status.phase.actionStationarityStopped":"status.phase.actionStationarityRecovering")} · ${l.toolName} · ${l.runLength}/${l.haltThreshold}`:n?n.phase==="probe"?"Provider · Recovery probe":`Provider · Circuit open${n.retryAfterMs!==void 0?` · probe in ${te(n.retryAfterMs)}`:""}${n.recoveryRemainingMs!==void 0?` · ${te(n.recoveryRemainingMs)}`:""}`:i?`Provider · Capacity queue ${i.queuePosition}/${Math.max(i.queueDepth,i.queuePosition)} · ${i.scope} · ${te(i.waitMs)}`:d?d.mode==="bounded_foreground"?`Provider · Bounded recovery · ${d.attempt}/${d.maxRetries} · ${te(d.recoveryRemainingMs??0)}`:`Provider · ${t("chat.error.action.retryingTask")} · ${d.attempt}/${d.maxRetries}${k}`:f?`${t("status.phase.providerStall")} · ${Math.ceil(f.durationMs/1e3)}s / ${Math.ceil(f.timeoutMs/1e3)}s`:c?t(c):"",h=s.maxContextTokens>0?Math.round(s.totalTokens/s.maxContextTokens*100):0,u=ws(s),j=Ns(u.hitRate),N=Math.min(h,100),m=h>95?"danger":h>80?"warn":"safe";return e.jsxs("div",{className:"flex items-center gap-2 border-t border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/70 px-3 py-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm sm:gap-4 sm:px-5",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.context")}),e.jsxs("span",{className:"flex gap-1 items-baseline tabular-nums",children:[e.jsx("span",{className:T("text-[12px] font-medium",m==="safe"&&"text-[hsl(var(--deck-ink))]",m==="warn"&&"text-amber-600 dark:text-amber-400",m==="danger"&&"text-red-600 dark:text-red-400"),children:O(s.totalTokens)}),e.jsxs("span",{className:"text-[hsl(var(--deck-ink-faint))]",children:["/ ",O(s.maxContextTokens)]})]}),s.isDefaultMaxTokens&&e.jsx(pe,{children:e.jsxs(fe,{children:[e.jsx(be,{asChild:!0,children:e.jsx(bt,{className:"h-3 w-3 cursor-help text-[hsl(var(--deck-ink-faint))]"})}),e.jsx(re,{side:"top",className:"max-w-[220px]",children:e.jsx("p",{className:"text-xs",children:t("status.tokenLimitTooltip")})})]})}),e.jsxs("div",{className:"relative hidden h-2 w-32 overflow-hidden rounded-sm border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] sm:block","aria-hidden":"true",children:[e.jsx("div",{className:T("absolute inset-y-0 left-0 transition-[width] duration-300",m==="safe"&&"bg-[hsl(var(--deck-accent))]",m==="warn"&&"bg-amber-500",m==="danger"&&"bg-red-500"),style:{width:`${N}%`}}),e.jsx("div",{className:"flex absolute inset-0 pointer-events-none",children:[25,50,75].map(w=>e.jsx("span",{className:"absolute inset-y-0 w-px bg-[hsl(var(--deck-canvas-veil))]/60",style:{left:`${w}%`}},w))})]}),e.jsxs("span",{className:T("w-10 text-right tabular-nums text-[hsl(var(--deck-ink-faint))]",m==="warn"&&"text-amber-600 dark:text-amber-400",m==="danger"&&"text-red-600 dark:text-red-400"),children:[h,"%"]})]}),e.jsx(pe,{children:e.jsxs(fe,{children:[e.jsx(be,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 cursor-help items-baseline gap-2 border-l border-[hsl(var(--deck-hairline))] pl-2 sm:pl-4","data-testid":"prompt-cache-hit-rate","aria-label":`${t("status.cache")} ${j}`,children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.cache")}),e.jsx("span",{className:T("tabular-nums",u.hitRate===void 0?"text-[hsl(var(--deck-ink-faint))]":"font-medium text-[hsl(var(--deck-accent))]"),children:j})]})}),e.jsx(re,{side:"top",className:"max-w-[280px]",children:u.hitRate===void 0?e.jsx("p",{className:"text-xs",children:t("status.cacheUnavailable")}):e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx("p",{children:t("status.cacheTooltip")}),e.jsx("p",{className:"font-mono tabular-nums",children:t("status.cacheDetails",{read:O(u.cacheReadTokens),write:O(u.cacheWriteTokens),uncached:O(u.uncachedInputTokens)})}),s.cacheBreak&&e.jsx("p",{className:"text-[hsl(var(--deck-accent))]",children:t("status.cacheBreak",{reason:t(Cs[s.cacheBreak.reason]??"status.cacheBreak.server"),previous:O(s.cacheBreak.previousCacheReadTokens),current:O(s.cacheBreak.cacheReadTokens)})})]})})]})}),e.jsx("div",{className:"flex-1"}),a&&o&&e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("span",{className:"deck-pulse-dot"}),e.jsx("span",{className:"text-[hsl(var(--deck-accent))]",children:o})]})]})}function Ts(t){const s=[...t].reverse().find(i=>i.role==="user");if(!s)return null;if(typeof s.content=="string")return{content:s.content,attachments:[]};const a=s.content.filter(i=>i.type==="text").map(i=>i.text).join(`
18
- `),r=s.content.filter(i=>i.type==="image_url").map((i,n)=>{var f;const d=((f=i.image_url.url.match(/^data:([^;,]+)[;,]/))==null?void 0:f[1])??"application/octet-stream";return{id:`recovery-${s.id}-${n}`,name:`attachment-${n+1}`,mimeType:d,dataUrl:i.image_url.url}});return{content:a,attachments:r}}function Ds(){var V;const t=F(),s=y(g=>g.messages),a=y(g=>g.currentSessionRef),r=y(g=>g.isStreaming),i=y(g=>g.isStopping),n=y(g=>g.sessionEventConnectionState),d=y(g=>g.pendingSteeringCount),f=y(g=>g.pendingInputDelivery),l=y(g=>g.recoveredSteeringCount),c=y(g=>g.isLoading),k=y(g=>g.error),o=y(g=>g.errorContext),h=y(g=>g.sessions),u=y(g=>g.sendMessage),j=y(g=>g.abortSession),N=y(g=>g.retryTask),m=y(g=>g.retryingTaskKeys),w=ge(g=>g.openSettings),v=y(g=>g.reconnectSessionEvents),p=y(g=>g.clearError),[x,E]=b.useState(null),S=a?h.find(g=>g.sessionId===a.sessionId&&g.projectPath===a.projectPath):void 0,D=!!k&&((o==null?void 0:o.kind)==="navigation"||!(o!=null&&o.sessionRef)||Fe(o.sessionRef,a)),A=(o==null?void 0:o.failureCode)??((V=S==null?void 0:S.taskFailure)==null?void 0:V.code),L=(o==null?void 0:o.kind)==="execution"&&A?t(Nt(A)):k==="queue_full"?t("chat.error.queueFull"):k==="turn_unavailable"||k==="turn_active"?t("chat.error.turnChanged"):k,_=n==="connecting"||n==="reconnecting",C=r&&n!=="connected",B=a?`session:${Q(a)}`:"session:temporary",H=b.useMemo(()=>Ts(s),[s]),ce=a?Q(a):"temporary-session",z=!!(a&&(S!=null&&S.taskRetryAvailable)&&(!A||St(A)))&&((o==null?void 0:o.kind)==="execution"||(o==null?void 0:o.kind)==="task_action"),G=(o==null?void 0:o.kind)==="execution"&&(A==="authentication"||A==="permission"||A==="model_unavailable"),K=a?m.includes(Q(a)):!1;b.useEffect(()=>{E(null)},[ce]);const Y=async g=>u({content:g.content,modelId:g.modelId,reasoningEffort:g.reasoningEffort,serviceTier:g.serviceTier,responseVerbosity:g.responseVerbosity,communicationStyle:g.communicationStyle,...g.outputSchema?{outputSchema:g.outputSchema}:{},attachments:g.attachments.map(I=>({type:"image",content:I.dataUrl,mimeType:I.mimeType,name:I.name}))}),X=()=>j(),M=async()=>{if(G){p(),w("models");return}if(z&&a){p(),await N(a).catch(()=>{});return}if((o==null?void 0:o.kind)==="execution"&&H){E({...H,revision:Date.now()}),p();return}p(),requestAnimationFrame(()=>Xe())},P=z?t(K?"chat.error.action.retryingTask":"chat.error.action.retryTask"):G?t("chat.error.action.checkModels"):(o==null?void 0:o.kind)==="execution"&&H?t("chat.error.action.editResend"):(o==null?void 0:o.kind)==="submission"?t("chat.error.action.returnDraft"):null;return e.jsxs("div",{className:"flex h-full flex-col bg-[hsl(var(--deck-canvas))]",children:[D&&e.jsxs("div",{role:"alert","data-blade-session-error":!0,className:"flex min-h-11 flex-wrap items-center gap-2 border-b border-red-200/60 bg-red-50/80 px-4 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300 sm:px-5",children:[e.jsx(Oe,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1 break-words",children:[e.jsx("span",{className:"font-semibold",children:t((o==null?void 0:o.kind)==="submission"?"chat.error.title.submission":(o==null?void 0:o.kind)==="execution"?"chat.error.title.execution":(o==null?void 0:o.kind)==="navigation"?"chat.error.title.navigation":"chat.error.title.generic")})," ",L]}),P&&e.jsxs("button",{type:"button",onClick:()=>void M(),disabled:K,className:"inline-flex min-h-7 shrink-0 items-center gap-1.5 rounded-md border border-red-300/70 bg-white/65 px-2.5 font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-500 disabled:cursor-wait disabled:opacity-60 dark:border-red-800 dark:bg-red-950/45 dark:hover:bg-red-900/60",children:[z?K?e.jsx(R,{className:"h-3 w-3 animate-spin"}):e.jsx(ke,{className:"h-3 w-3"}):e.jsx(Le,{className:"h-3 w-3"}),P]}),e.jsx("button",{type:"button",onClick:p,"aria-label":t("chat.error.dismiss"),className:"p-1 text-red-500 rounded transition-colors hover:bg-red-100/60 hover:text-red-700 dark:hover:bg-red-950/60 dark:hover:text-red-100",children:"✕"})]}),(_||n==="offline")&&e.jsxs("div",{role:n==="offline"?"alert":"status","aria-live":"polite",className:"flex min-h-10 flex-wrap items-center gap-2 border-b border-amber-300/60 bg-amber-50/80 px-4 py-2 font-mono text-[11px] text-amber-900 dark:border-amber-800/60 dark:bg-amber-950/35 dark:text-amber-200 sm:px-5",children:[_?e.jsx(R,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):e.jsx(gt,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 flex-1",children:t(_?"chat.connection.reconnecting":"chat.connection.offline")}),n==="offline"&&e.jsxs("button",{type:"button",onClick:()=>void v().catch(()=>{}),className:"inline-flex min-h-7 items-center gap-1.5 rounded-md border border-amber-400/70 bg-white/60 px-2.5 font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-700 dark:bg-amber-950/50 dark:hover:bg-amber-900/50",children:[e.jsx(vt,{className:"h-3 w-3"}),t("chat.connection.retry")]})]}),e.jsx(Mt,{}),e.jsx(gs,{messages:s,isLoading:c},a?Q(a):"temporary-session"),e.jsx(ys,{}),e.jsx(js,{}),e.jsx(Ye,{draftKey:B,draft:x==null?void 0:x.content,draftAttachments:x==null?void 0:x.attachments,draftRevision:x==null?void 0:x.revision,onSend:Y,onAbort:X,disabled:c||C,isStreaming:r,isStopping:i,pendingSteeringCount:d,pendingInputDelivery:f,recoveredSteeringCount:l,workspacePath:a==null?void 0:a.projectPath},B),e.jsx(Es,{})]})}export{Ds as ChatView};