blade-code 0.10.128 → 0.10.130
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/chunk-0z9nqbd0.js +2 -0
- package/dist/chunk-1bb4h5gf.js +1 -0
- package/dist/chunk-2bnpn8be.js +1 -0
- package/dist/{chunk-xzfc1s6k.js → chunk-2y1qngw7.js} +1 -1
- package/dist/{chunk-jy0vfp8a.js → chunk-42h7kj6p.js} +1 -1
- package/dist/{chunk-ted1hyvb.js → chunk-44jtpg8y.js} +1 -1
- package/dist/chunk-4sxxvtn4.js +1 -0
- package/dist/chunk-51qc7n8t.js +1 -0
- package/dist/{chunk-z3hpstky.js → chunk-53h87fmt.js} +1 -1
- package/dist/{chunk-y93nqyqd.js → chunk-55hq1ps4.js} +2 -2
- package/dist/{chunk-9n90djh7.js → chunk-5a17mdjd.js} +2 -2
- package/dist/{chunk-pq6g92cz.js → chunk-6p6ts4kv.js} +2 -2
- package/dist/{chunk-sca5q3tt.js → chunk-77efqpdc.js} +1 -1
- package/dist/chunk-7jj607dg.js +94 -0
- package/dist/{chunk-yqqeh12b.js → chunk-8a6nrqdc.js} +2 -2
- package/dist/{chunk-10w2pj3r.js → chunk-93x9xbew.js} +1 -1
- package/dist/{chunk-1aw643j2.js → chunk-9et78e3v.js} +2 -2
- package/dist/chunk-9gs4eqt8.js +1 -0
- package/dist/chunk-9s8saznq.js +1 -0
- package/dist/{chunk-fa0pyv9k.js → chunk-9yqadjea.js} +2 -2
- package/dist/{chunk-a7gghhvn.js → chunk-a4jetpj8.js} +18 -18
- package/dist/{chunk-yqpej45c.js → chunk-a60cmnmz.js} +2 -2
- package/dist/{chunk-8hd4vd20.js → chunk-aaxc81jc.js} +1 -1
- package/dist/{chunk-xejvs1fk.js → chunk-agda17kj.js} +1 -1
- package/dist/{chunk-c47db31j.js → chunk-ajsw4te2.js} +2 -2
- package/dist/{chunk-r04vwtej.js → chunk-ar5np5h5.js} +2 -2
- package/dist/chunk-b8m7zc7t.js +170 -0
- package/dist/chunk-bcre3557.js +1 -0
- package/dist/{chunk-atema2rc.js → chunk-dfjmvj3d.js} +2 -2
- package/dist/chunk-dkgaxmsp.js +10 -0
- package/dist/{chunk-mkvvyq49.js → chunk-e1d0e6t6.js} +2 -2
- package/dist/{chunk-s7axaw78.js → chunk-edtxcqxa.js} +1 -1
- package/dist/chunk-f8gb685p.js +2 -0
- package/dist/chunk-fjv2vede.js +1 -0
- package/dist/{chunk-zfyg3888.js → chunk-g4xny949.js} +1 -1
- package/dist/chunk-gfbkrk60.js +338 -0
- package/dist/{chunk-12hdakw4.js → chunk-gmqpfm52.js} +2 -2
- package/dist/{chunk-skv2gb99.js → chunk-grhsv55v.js} +2 -2
- package/dist/chunk-gzz0gnmv.js +1 -0
- package/dist/chunk-h1wphqkc.js +1 -0
- package/dist/{chunk-6v2hhgka.js → chunk-hhg1zcbq.js} +2 -2
- package/dist/{chunk-9hnfz9bx.js → chunk-hw1gbr11.js} +1 -1
- package/dist/{chunk-nx8xb7dm.js → chunk-jkfkyedn.js} +1 -1
- package/dist/chunk-kd3k1q9z.js +1 -0
- package/dist/{chunk-n8w1jxsh.js → chunk-kfkvdj49.js} +1 -1
- package/dist/chunk-m9mw8ppy.js +1 -0
- package/dist/{chunk-xshrj2nd.js → chunk-mdew58v9.js} +1 -1
- package/dist/{chunk-n4q6fvqe.js → chunk-mvm1rzc4.js} +2 -2
- package/dist/{chunk-qm632an7.js → chunk-p00f53yq.js} +1 -1
- package/dist/{chunk-p7349xay.js → chunk-p2sp2e0a.js} +2 -2
- package/dist/chunk-pj69j4zp.js +2 -0
- package/dist/{chunk-41byj2h8.js → chunk-pk11fexz.js} +2 -2
- package/dist/chunk-qahz5x5c.js +14 -0
- package/dist/{chunk-6m4sqwj0.js → chunk-qcvxff27.js} +2 -2
- package/dist/{chunk-p2rxrxct.js → chunk-r9tawy93.js} +3 -3
- package/dist/{chunk-rz2wc93t.js → chunk-s2atpv23.js} +4 -4
- package/dist/chunk-saedy6bj.js +1 -0
- package/dist/{chunk-fgbqm2jh.js → chunk-sfe4810k.js} +1 -1
- package/dist/{chunk-96w8ay2h.js → chunk-sj1dzeta.js} +1 -1
- package/dist/chunk-sn71fsm5.js +1 -0
- package/dist/{chunk-yysqw1cq.js → chunk-ss4sncn3.js} +2 -2
- package/dist/chunk-ss86eq2h.js +23 -0
- package/dist/{chunk-ektgnqmh.js → chunk-sx77dpxw.js} +1 -1
- package/dist/chunk-t4apxzp1.js +2 -0
- package/dist/chunk-te6203yf.js +1 -0
- package/dist/{chunk-gxwkwkhp.js → chunk-tkydv9k8.js} +1 -1
- package/dist/{chunk-60he05xs.js → chunk-tw5fr07c.js} +2 -2
- package/dist/{chunk-q3y3s16v.js → chunk-v52wc8yg.js} +2 -2
- package/dist/{chunk-b408cqg1.js → chunk-v5hzk7j2.js} +2 -2
- package/dist/{chunk-v4nqv1pr.js → chunk-v94ztjtp.js} +385 -385
- package/dist/{chunk-85jv1sr7.js → chunk-xa9k5pjt.js} +2 -2
- package/dist/{chunk-mvgmsjwq.js → chunk-z03dtyh6.js} +1 -1
- package/dist/{chunk-jxc67ydz.js → chunk-zc91c7b5.js} +2 -2
- package/dist/{chunk-mm05y2c5.js → chunk-zkzhm39s.js} +1 -1
- package/dist/{chunk-1xg7qx35.js → chunk-zwjrensv.js} +1 -1
- package/dist/web/assets/ChatView-Bg36FUaj.js +53 -0
- package/dist/web/assets/{CodeBlockHighlighter-0VOa5Mes.js → CodeBlockHighlighter-D5rB73Eo.js} +2 -2
- package/dist/web/assets/FilePreview-BxaBSmap.js +65 -0
- package/dist/web/assets/KanbanBoard-B4gx3JMo.js +16 -0
- package/dist/web/assets/{MarkdownRenderer-3g4TPTeI.js → MarkdownRenderer-BRH7LHhN.js} +3 -3
- package/dist/web/assets/ScrollArea-DikU3QeQ.js +1 -0
- package/dist/web/assets/SessionHistorySurface-DG80d6-F.js +6 -0
- package/dist/web/assets/{SettingsModal-3GMy6V-E.js → SettingsModal-Bxqkok81.js} +3 -3
- package/dist/web/assets/Sidebar-DGaHGcHx.js +31 -0
- package/dist/web/assets/TaskSwitcher-DOnLPurk.js +26 -0
- package/dist/web/assets/TerminalPanel-BzhCF9vw.js +6 -0
- package/dist/web/assets/archive-BiDGrqry.js +6 -0
- package/dist/web/assets/{arrow-left-03GxbYI7.js → arrow-left-BY-esOAP.js} +1 -1
- package/dist/web/assets/{calendar-clock-8W4ostX1.js → calendar-clock-BCyxvfVt.js} +1 -1
- package/dist/web/assets/chevron-right-Bg-10yuN.js +6 -0
- package/dist/web/assets/{chevrons-up-down-BboZzEAk.js → chevrons-up-down-M5SAJq7T.js} +1 -1
- package/dist/web/assets/{clock-3-aXgeptZP.js → clock-3-v-nHTA0A.js} +1 -1
- package/dist/web/assets/copy-p1zc_rjZ.js +6 -0
- package/dist/web/assets/download-D_-kbJXR.js +6 -0
- package/dist/web/assets/{external-link-UkIIC2ds.js → external-link-wSGTIqe3.js} +1 -1
- package/dist/web/assets/{folder-BOCc5dv2.js → folder-Ltm9jCS5.js} +1 -1
- package/dist/web/assets/index-B4186fIT.css +1 -0
- package/dist/web/assets/index-_xnlrekR.js +210 -0
- package/dist/web/assets/{pause-DVIT6IIr.js → pause-_LvCZkxM.js} +1 -1
- package/dist/web/assets/pencil-DB6ICr_h.js +6 -0
- package/dist/web/assets/{play-DsdF5dji.js → play-BRXP1rHJ.js} +1 -1
- package/dist/web/assets/plus-BqvjEpLw.js +6 -0
- package/dist/web/assets/session-events-AGMXvPey.js +22 -0
- package/dist/web/assets/settings-LfQbDvBA.js +6 -0
- package/dist/web/assets/teamService-B5FnUcet.js +1 -0
- package/dist/web/assets/terminal-By4sO9Gw.js +6 -0
- package/dist/web/assets/vendor-radix-D6QrtXqd.js +45 -0
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/dist/chunk-0ktte40x.js +0 -185
- package/dist/chunk-1acb8fwq.js +0 -120
- package/dist/chunk-3pwqqk7w.js +0 -1
- package/dist/chunk-3q7g9206.js +0 -1
- package/dist/chunk-562w5zc6.js +0 -2
- package/dist/chunk-5x56nka1.js +0 -1
- package/dist/chunk-7hajkvde.js +0 -1
- package/dist/chunk-9wptwfmg.js +0 -1
- package/dist/chunk-ap01rwg0.js +0 -169
- package/dist/chunk-cm8fy1jn.js +0 -1
- package/dist/chunk-dp4r5bay.js +0 -1
- package/dist/chunk-dtxza4zh.js +0 -1
- package/dist/chunk-hd7bxzvy.js +0 -1
- package/dist/chunk-hks48s9k.js +0 -1
- package/dist/chunk-hmncnf7p.js +0 -1
- package/dist/chunk-j6fj679p.js +0 -10
- package/dist/chunk-m8czdpyg.js +0 -1
- package/dist/chunk-p5awnndq.js +0 -8
- package/dist/chunk-s7peh6kf.js +0 -2
- package/dist/chunk-ws6gtw33.js +0 -1
- package/dist/chunk-wtmhqy5s.js +0 -1
- package/dist/chunk-xnstybjm.js +0 -2
- package/dist/chunk-xpdtg9h9.js +0 -23
- package/dist/chunk-z2jwm4s8.js +0 -1
- package/dist/web/assets/ChatView-DCHnicTP.js +0 -58
- package/dist/web/assets/FilePreview-C_3KHzzj.js +0 -65
- package/dist/web/assets/KanbanBoard-D_NTkUnD.js +0 -16
- package/dist/web/assets/TaskSwitcher-eCdxu5Eo.js +0 -26
- package/dist/web/assets/TerminalPanel-9q9Trmv9.js +0 -6
- package/dist/web/assets/index-DGf6Z2kM.css +0 -1
- package/dist/web/assets/index-DaiT-mmo.js +0 -275
- package/dist/web/assets/session-events-CWzF04l4.js +0 -22
- package/dist/web/assets/teamService-BliaDj1Z.js +0 -1
- package/dist/web/assets/vendor-radix-Bc1_Q9tz.js +0 -45
package/dist/chunk-xnstybjm.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import*as z from"node:os";import*as x from"node:path";function H(){return process.env.BLADE_STORAGE_ROOT||x.join(z.homedir(),".blade")}import{AsyncLocalStorage as Bq}from"node:async_hooks";import{createHash as Lq}from"node:crypto";import{lstat as L,mkdir as Tq,readdir as Nq,realpath as b}from"node:fs/promises";import Y from"node:path";import{createHash as qq}from"node:crypto";var E=new WeakSet,j=new WeakSet,Gq={"not-absolute":"ACP remote file path must be absolute","style-mismatch":"ACP remote file path does not match the expected style","drive-relative":"ACP remote file path cannot be drive-relative","root-relative":"ACP remote file path cannot be root-relative","unc-not-supported":"ACP remote file path must be absolute; UNC paths are not supported","device-namespace-not-supported":"ACP remote file path device namespaces are not supported","trailing-dot-or-space":"ACP remote file path components cannot end with a dot or space","alternate-data-stream":"ACP remote file path alternate data streams are not supported","reserved-device-name":"ACP remote file path reserved device names are not supported","short-name-alias":"ACP remote file path short-name aliases are not supported","invalid-character":"ACP remote file path contains characters that are not supported"},Jq=new Set(["CON","PRN","AUX","NUL","CONIN$","CONOUT$","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9","COM¹","COM²","COM³","LPT¹","LPT²","LPT³"]);class Z extends Error{reason;style;name="AcpRemotePathError";code="acp_remote_path_invalid";constructor(q,G){super(Gq[q]);this.reason=q;this.style=G;Object.setPrototypeOf(this,new.target.prototype)}toJSON(){return{name:this.name,code:this.code,reason:this.reason,style:this.style,message:this.message}}}class T extends Error{name="AcpRemotePathIdentityError";code="acp_remote_path_identity_invalid";constructor(){super("ACP remote path identity is invalid");Object.setPrototypeOf(this,new.target.prototype)}}function Oq(q){if(!E.has(q))throw new T}function Qq(q){if(!j.has(q))throw new T;if(Oq(q.workspace),q.style!==q.workspace.style)throw new T}function kq(q){Qq(q);let G=Object.freeze({style:q.style,workspace:q.workspace});return j.add(G),G}function fq(q){let G=N(q),J=Object.freeze({style:G.style,workspace:G});return j.add(J),J}function N(q,G){let J=W(q,G);if(J.kind==="error")throw new Z(J.reason,J.style);let O=J.style==="win32"?Xq(q):Uq(q);return A(J.style,O)}function gq(q,G){let J=N(q),O=J.style==="win32"?$q(J.wirePath,G):Zq(J.wirePath,G);return A(J.style,O)}function W(q,G){if(R(q))return{kind:"error",reason:"device-namespace-not-supported",style:"win32"};if(g(q))return{kind:"error",reason:"unc-not-supported",style:G==="posix"?"posix":"win32"};if(S(q))return{kind:"error",reason:"unc-not-supported",style:"win32"};if(P(q)){if(G==="posix")return{kind:"error",reason:"style-mismatch",style:"posix"};return{kind:"absolute",style:"win32"}}if(Kq(q))return{kind:"error",reason:"drive-relative",style:"win32"};if(q.startsWith("\\"))return{kind:"error",reason:"root-relative",style:"win32"};if(q.startsWith("/")){if(G==="win32")return{kind:"error",reason:"style-mismatch",style:"win32"};return{kind:"absolute",style:"posix"}}return{kind:"error",reason:"not-absolute",style:"unknown"}}function A(q,G){let J=q==="win32"?G.toUpperCase():G,O=Object.freeze({style:q,wirePath:G,exactIdentity:I("acp-remote-exact-path",q,G),collisionIdentity:I("acp-remote-collision-path",q,J)});return E.add(O),O}function I(q,G,J){return`${q}:${qq("sha256").update(`${G}\x00${J}`).digest("hex")}`}function Uq(q){let G=q.split("/"),J=[];for(let O of G.slice(1)){if(O.length===0||O===".")continue;if(O===".."){if(J.length>0)J.pop();continue}k(O),J.push(O)}return J.length===0?"/":`/${J.join("/")}`}function Xq(q){let G=q[0].toUpperCase(),J=Mq(q),O=[],Q="";for(let U of q.slice(2)){if(m(U)){if(Q.length>0)v(O,Q),Q="";continue}Q+=U}if(Q.length>0)v(O,Q);if(J&&O.length>0)throw new Z("trailing-dot-or-space","win32");if(O.length===0)return`${G}:\\`;return`${G}:\\${O.join("\\")}`}function Yq(q,G){let J=q==="/"?[]:q.slice(1).split("/"),O=[...J];for(let Q of G.split("/")){if(Q.length===0||Q===".")continue;if(Q===".."){if(O.length===J.length)throw new Z("not-absolute","posix");O.pop();continue}k(Q),O.push(Q)}return O.length===0?"/":`/${O.join("/")}`}function Zq(q,G){if(R(G))throw new Z("device-namespace-not-supported","win32");if(g(G))throw new Z("unc-not-supported","posix");if(S(G))throw new Z("unc-not-supported","win32");if(P(G)||G.startsWith("/"))throw new Z("style-mismatch","posix");return Yq(q,G)}function _q(q,G){let J=q.indexOf("\\"),O=J===q.length-1?[]:q.slice(J+1).split("\\"),Q=[...O],U="";for(let K of G){if(m(K)){if(U.length>0)y(O.length,Q,U),U="";continue}U+=K}if(U.length>0)y(O.length,Q,U);let $=q.slice(0,J+1);if(Q.length===0)return $;return`${$}${Q.join("\\")}`}function $q(q,G){let J=W(G,"win32");if(J.kind==="absolute")throw new Z("style-mismatch","win32");if(J.reason!=="not-absolute")throw new Z(J.reason,J.style);return _q(q,G)}function y(q,G,J){if(J===".")return;if(J===".."){if(G.length===q)throw new Z("not-absolute","win32");G.pop();return}f(J),G.push(J)}function v(q,G){if(G===".")return;if(G===".."){if(q.length>0)q.pop();return}f(G),q.push(G)}function k(q){if(q.includes("\x00"))throw new Z("invalid-character","posix")}function f(q){let G=Fq(q),J=Hq(G);if(J!==void 0&&Jq.has(J.toUpperCase()))throw new Z("reserved-device-name","win32");if(G!==q)throw new Z("trailing-dot-or-space","win32");if(q.includes(":"))throw new Z("alternate-data-stream","win32");if(/~\d/u.test(q))throw new Z("short-name-alias","win32");for(let O of q){let Q=O.codePointAt(0);if(Q===void 0||Q===0||Q>=1&&Q<=31||'<>"|?*'.includes(O))throw new Z("invalid-character","win32")}}function Fq(q){let G=q.length;while(G>0){let J=q[G-1];if(J!=="."&&J!==" ")break;G-=1}return q.slice(0,G)}function Hq(q){if(q.length===0)return;let G=q.indexOf(".");return G===-1?q:q.slice(0,G)}function g(q){return q.startsWith("//")||q.startsWith("/\\")}function R(q){return/^([\\/]){2}[?.][\\/]/u.test(q)}function S(q){return/^[\\/]{2}/u.test(q)}function P(q){return/^[A-Za-z]:[\\/]/u.test(q)}function Kq(q){return/^[A-Za-z]:(?![\\/])/u.test(q)}function m(q){return q==="\\"||q==="/"}function Mq(q){if(q.length<=3)return!1;let G=q[q.length-1];return G==="\\"||G==="/"}var F="acp-remote-workspaces",d=/^[a-f0-9]{64}$/,V=new Map,h=new Bq,Vq;class X extends Error{name="AcpRemoteWorkspaceStateError";code="acp_remote_workspace_state_invalid";constructor(q){super(`ACP remote workspace durable state is invalid (${q})`);Object.setPrototypeOf(this,new.target.prototype)}}function nq(q){return{version:1,kind:"acp-remote",style:q.style,wirePath:q.workspace.wirePath,exactIdentity:q.workspace.exactIdentity,collisionIdentity:q.workspace.collisionIdentity}}function bq(q){if(!q||typeof q!=="object"||Array.isArray(q))throw new X("descriptor-shape");let G=q;if(G.version!==1)throw new X("descriptor-version");if(G.kind!=="acp-remote")throw new X("descriptor-kind");if(G.style!=="posix"&&G.style!=="win32")throw new X("descriptor-style");if(typeof G.wirePath!=="string"||typeof G.exactIdentity!=="string"||typeof G.collisionIdentity!=="string")throw new X("descriptor-shape");let J;try{J=N(G.wirePath,G.style)}catch{throw new X("descriptor-wire-path")}if(J.exactIdentity!==G.exactIdentity||J.collisionIdentity!==G.collisionIdentity)throw new X("descriptor-identity");return{version:1,kind:"acp-remote",style:G.style,wirePath:J.wirePath,exactIdentity:J.exactIdentity,collisionIdentity:J.collisionIdentity}}function pq(q,G=H()){if(typeof q!=="string"||!/^acp-remote-collision-path:[a-f0-9]{64}$/.test(q))throw new X("descriptor-collision-identity");let J=Y.resolve(G),O=Lq("sha256").update(`acp-remote-host-state\x00${q}`).digest("hex");return Y.join(J,F,O)}async function iq(q){let G=Y.resolve(H());await Cq(q,G)}async function cq(q,G){let J=Y.resolve(H());return s(q,J,G)}async function sq(q,G){let J=String(q);if(Y.dirname(G)!==J)throw new X("state-file-path");let O=await L(G);if(O.isSymbolicLink()||!O.isFile())throw new X("state-file-type");if(typeof process.getuid==="function"&&O.uid!==process.getuid())throw new X("state-file-owner");let Q=typeof O.mode==="bigint"?Number(O.mode&BigInt(511)):O.mode&511;if(process.platform!=="win32"&&Q!==384)throw new X("state-file-mode");await M(G,J,Y.basename(G))}async function rq(q,G,J){let O=String(q);if(Y.dirname(G)!==O)throw new X("state-file-path");let[Q,U]=await Promise.all([J.stat({bigint:!0}),L(G,{bigint:!0})]);if(U.isSymbolicLink()||!U.isFile()||!Q.isFile()||U.dev!==Q.dev||U.ino!==Q.ino)throw new X("state-file-replaced");if(typeof process.getuid==="function"&&(Number(U.uid)!==process.getuid()||Number(Q.uid)!==process.getuid()))throw new X("state-file-owner");let $=Number(U.mode&BigInt(511)),K=Number(Q.mode&BigInt(511));if(process.platform!=="win32"&&($!==384||K!==384))throw new X("state-file-mode");await M(G,O,Y.basename(G))}function aq(q,G,J,O){let Q=q[0];if(Q?.type!=="session_created"||Q.sessionId!==G||Q.data.sessionId!==G||Q.cwd!==J||Q.projectPath!==J)throw new X("remote-session-identity");if(O){let U=bq(Q.data.remoteWorkspace);if(U.version!==O.version||U.kind!==O.kind||U.style!==O.style||U.wirePath!==O.wirePath||U.exactIdentity!==O.exactIdentity||U.collisionIdentity!==O.collisionIdentity)throw new X("remote-session-workspace")}for(let U of q)if(U.sessionId!==G||U.cwd!==J||U.projectPath!==J)throw new X("remote-session-event-identity");return Q}function n(q){return d.test(q)}async function p(q=H()){let G=Y.resolve(q);return u(`${G}\x00${F}`,async()=>{let J=Y.join(G,F),O;try{O=await c(G,(U)=>Nq(U,{withFileTypes:!0}))}catch(U){if(U.code==="ENOENT")return[];throw U}await Vq?.();let Q=[];for(let U of O){if(!n(U.name))continue;let $=Y.join(J,U.name);try{let K=await s($,G,async(e)=>e);Q.push(K)}catch(K){if(K.code==="ENOENT")throw new X("protected-root-missing");throw K}}return Q.sort((U,$)=>U.localeCompare($))})}function i(q,G){if(typeof q!=="string"||!Y.isAbsolute(q))throw new X("protected-root-shape");let J=Y.resolve(q);if(J!==q)throw new X("protected-root-shape");let O=Y.relative(G,J),Q=`${F}${Y.sep}`;if(O===""||O===F||!O.startsWith(Q)||O.includes(`${Y.sep}..`)||O.startsWith(`..${Y.sep}`)||Y.isAbsolute(O))throw new X("protected-root-shape");let U=O.split(Y.sep);if(U.length!==2||U[0]!==F)throw new X("protected-root-shape");if(!d.test(U[1]??""))throw new X("protected-root-digest");return{storageRoot:G,digest:U[1]}}async function c(q,G){await r(q,q);let J=Y.join(q,F);try{await D(J,q),await M(J,q,F)}catch(O){if(O.code==="ENOENT")throw O;throw O}return G(J)}async function Cq(q,G){await u(q,async()=>{let J=i(q,G);if(J.storageRoot!==G)throw new X("storage-root-mismatch");await r(J.storageRoot,G);let O=Y.join(J.storageRoot,F);await l(O,J.storageRoot),await M(O,G,F);let Q=Y.join(O,J.digest);await l(Q,O),await M(Q,O,J.digest)})}async function s(q,G,J){return u(q,async()=>{let O=i(q,G);if(O.storageRoot!==G)throw new X("storage-root-mismatch");let Q=Y.join(O.storageRoot,F);await c(G,async($)=>{if($!==Q)throw new X("protected-root-shape")});let U=Y.join(Q,O.digest);return await D(U,Q),await M(U,Q,O.digest),J(U)})}async function l(q,G){try{let J=await L(q);a(J,q)}catch(J){if(J.code!=="ENOENT")throw J;await Tq(q,{recursive:!1,mode:448})}await D(q,G)}async function D(q,G){let J=await L(q);a(J,q),await M(q,G,Y.basename(q))}async function r(q,G){let J=await L(q);jq(J,q),await Dq(q,G)}function jq(q,G){o(q,G);let J=t(q);if(process.platform!=="win32"&&((J&448)!==448||(J&18)!==0))throw new X("protected-root-mode")}function a(q,G){o(q,G);let J=t(q);if(process.platform!=="win32"&&J!==448)throw new X("protected-root-mode")}function o(q,G){if(q.isSymbolicLink()||!q.isDirectory())throw new X("protected-root-symlink");if(typeof process.getuid==="function"&&q.uid!==process.getuid())throw new X("protected-root-owner");if(G.includes(`..${Y.sep}`))throw new X("protected-root-shape")}function t(q){return typeof q.mode==="bigint"?Number(q.mode&BigInt(511)):q.mode&511}async function M(q,G,J){let O=await b(q),Q=await b(G),U=Y.join(Q,J);if(O!==U)throw new X("protected-root-realpath")}async function Dq(q,G){let J=await b(q),O=await b(G);if(J!==O)throw new X("protected-root-realpath")}async function u(q,G){let J=h.getStore();if(J?.has(q))throw new X("state-root-reentry");let O=V.get(q)??Promise.resolve(),Q=new Set(J??[]);Q.add(q);let U=O.catch(()=>{return}).then(()=>h.run(Q,G)),$=U.then(()=>{return},()=>{return});V.set(q,$);try{return await U}finally{if(V.get(q)===$)V.delete(q)}}import{execSync as uq}from"node:child_process";import{createHash as wq}from"node:crypto";import{readdir as zq}from"node:fs/promises";import*as _ from"node:path";function xq(q){return _.resolve(q).replace(/[/\\]/g,"-").replace(/:/g,"_")}function Iq(q){let G=q.replace(/_/g,":");if(G.startsWith("-"))G="/"+G.slice(1);return G.replace(/-/g,"/")}function yq(q){let G=xq(q);return _.join(H(),"projects",G)}function w(q){return yq(q)}function C(q){return String(q)}function vq(q){return typeof q==="string"&&q!=="."&&q!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(q)}function B(q){if(!vq(q))throw Error(`Invalid session ID: ${q}`)}function OG(q,G){return B(G),_.join(w(q),`${G}.jsonl`)}function QG(q,G){return B(G),_.join(C(q),`${G}.jsonl`)}function UG(q,G){return B(G),_.join(w(q),`${G}.inbox.json`)}function XG(q,G){return B(G),_.join(C(q),`${G}.inbox.json`)}function YG(q,G){return B(G),_.join(w(q),`${G}.goal.json`)}function ZG(q,G){return B(G),_.join(C(q),`${G}.goal.json`)}function _G(q,G){B(G);let J=wq("sha256").update(G).digest("hex");return _.join(C(q),`.session-lease-${J}.lock`)}function $G(q){try{return uq("git rev-parse --abbrev-ref HEAD",{cwd:q,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}async function Eq(){try{let q=_.join(H(),"projects");return(await zq(q,{withFileTypes:!0})).filter((J)=>J.isDirectory()).map((J)=>J.name)}catch{return[]}}async function FG(){let q=_.resolve(H()),G=await Eq().then((O)=>O.map((Q)=>({storagePath:_.join(q,"projects",Q),projectPath:Iq(Q),kind:"local"}))).catch(()=>[]),J=await p().then((O)=>O.map((Q)=>({storagePath:String(Q),projectPath:String(Q),kind:"acp-remote"})));return[...G,...J]}
|
|
2
|
-
export{H as qj,Z as rj,Oq as sj,Qq as tj,kq as uj,fq as vj,N as wj,gq as xj,X as yj,nq as zj,bq as Aj,pq as Bj,iq as Cj,cq as Dj,sq as Ej,rq as Fj,aq as Gj,p as Hj,Iq as Ij,yq as Jj,vq as Kj,B as Lj,OG as Mj,QG as Nj,UG as Oj,XG as Pj,YG as Qj,ZG as Rj,_G as Sj,$G as Tj,Eq as Uj,FG as Vj};
|
package/dist/chunk-xpdtg9h9.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{s as tz,t as ez}from"./chunk-85jv1sr7.js";import{u as yz,v as Iz,w as kz,x as R}from"./chunk-9n90djh7.js";import{A as Ez,B as Tz,C as xz,D as bz,y as sz,z as Pz}from"./chunk-fa0pyv9k.js";import{K as b,T as wz,U as Fz,Z as Oz,aa as Nz,ba as Az,ea as qz,ua as Rz,va as Sz,wa as hz,xa as Mz}from"./chunk-v4nqv1pr.js";import"./chunk-pq6g92cz.js";import{La as nz}from"./chunk-60he05xs.js";import{Na as Dz}from"./chunk-q3y3s16v.js";import{Hb as Kz,Qb as v,vb as _z}from"./chunk-rz2wc93t.js";import{$b as p}from"./chunk-sca5q3tt.js";import{Ad as Xz,Dd as Bz,Fd as Uz,Md as d,Nd as jz,Pd as S,Sd as Gz,Xd as Vz,_d as K,jd as Wz,td as h,ud as m,vd as Hz}from"./chunk-1acb8fwq.js";import"./chunk-z3hpstky.js";import"./chunk-0ktte40x.js";import{Ne as zJ}from"./chunk-1aw643j2.js";import"./chunk-yqpej45c.js";import{gf as iz,hf as az}from"./chunk-jxc67ydz.js";import"./chunk-v508x7cg.js";import{sf as o}from"./chunk-xshrj2nd.js";import{xf as Lz}from"./chunk-c47db31j.js";import"./chunk-n4q6fvqe.js";import{If as rz}from"./chunk-s7axaw78.js";import"./chunk-yqqeh12b.js";import"./chunk-a7gghhvn.js";import"./chunk-ektgnqmh.js";import{Cg as oz}from"./chunk-8hd4vd20.js";import"./chunk-10w2pj3r.js";import"./chunk-p2rxrxct.js";import"./chunk-zfyg3888.js";import{Fh as dz,Ih as lz}from"./chunk-6v2hhgka.js";import"./chunk-nx8xb7dm.js";import"./chunk-96w8ay2h.js";import{ki as u,li as Yz,ni as g,oi as c}from"./chunk-s7peh6kf.js";import{si as r}from"./chunk-ted1hyvb.js";import"./chunk-xzfc1s6k.js";import{Ui as M}from"./chunk-r04vwtej.js";import"./chunk-atema2rc.js";import{$i as mz,cj as vz}from"./chunk-gxwkwkhp.js";import"./chunk-b408cqg1.js";import"./chunk-6m4sqwj0.js";import"./chunk-1xg7qx35.js";import{Aj as pz,Bj as t,qj as Qz,rj as cz,vj as n,zj as s}from"./chunk-xnstybjm.js";import"./chunk-mm05y2c5.js";import{Readable as VJ,Writable as _J}from"node:stream";import*as C from"@agentclientprotocol/sdk";import l from"node:path";import{PROTOCOL_VERSION as XJ,RequestError as k}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as f}from"nanoid";var G=M("Agent");function E(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function $z(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function $J(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:$z(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:$z("headers"in z?z.headers:void 0)};return null}function QJ(z){let J={};for(let Z of z){let Y=$J(Z);if(Y)J[Z.name]=Y}return J}function fz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let Z=J.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Z);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function YJ(z){let J=jz(z.metadata);return J?[{type:"text",text:d(J)}]:fz(z.content)}function LJ(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
-
`)}function WJ(z){if(!Lz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...h("capacity"),resource:z.resource}}function HJ(z){if(!(z instanceof Cz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Hz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}class T{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,Z,Y,W={}){this.id=z;this.roots=J;this.connection=Z;this.clientCapabilities=Y;this.options=W;this.messages=[...W.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(W.permissionMode),this.updateEgress=new bz({maxPendingItems:Pz,maxPendingBytes:Ez,writeTimeoutMs:Tz,signal:Z.signal,sizeOf:(H)=>Buffer.byteLength(JSON.stringify(H)),write:async(H)=>{await Z.sessionUpdate(H)},onFailure:(H)=>this.handleUpdateEgressFailure(H)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await this.loadPersistedModelContext();return J.length>0?J:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?K.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?K.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,J=z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await K.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(Z){if(!(Z instanceof Vz)&&Z.code!=="ENOENT")throw Z;await K.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...J})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await K.setSessionPermissionMode(this.id,this.roots.hostStateRoot,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 qz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default"),b.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async(L)=>{await this.sendUpdateAndWait(L)},this.roots.kind==="acp-remote"?this.roots.profile:void 0),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await v.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(L)=>this.requestPermission(L)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?QJ(this.options.mcpServers):void 0,Z=b.getInstance().getTerminalService(this.id),Y=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Oz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...Y?{workspace:Y}:{},permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(L,X)=>{let U=await Z.execute(L,{cwd:X.cwd,env:X.env,timeout:X.timeoutMs,signal:X.signal,allowLocalFallback:!1,onOutput:(j)=>X.onOutput?.("stdout",j)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await R.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await Sz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=_z.subscribe((L)=>{if(L.sessionId!==this.id||L.projectPath!==this.roots.hostStateRoot)return;if(L.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":L.properties}}),this.requestPendingResume();return}if(L.type==="task.delivery"){if(!L.properties.taskDelivery||typeof L.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof L.properties.updatedAt==="string"?L.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":L.properties.taskDelivery,...L.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(L.type.startsWith("team.")){let{teamName:X,messageId:U,content:j}=L.properties,V=L.properties.metadata;if(L.type==="team.message.received"&&typeof X==="string"&&typeof U==="string"&&typeof j==="string"&&Fz(V,{messageId:U,teamName:X}))(async()=>{let q=await this.runtime?.enqueueSteering(j,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:V});if(!q?.accepted)return;if(await new wz(X,Qz()).markDelivered([U]),q.delivery==="next_turn")this.requestPendingResume()})().catch((q)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,q)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:L.type,...L.properties}}});return}if(L.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof L.properties.updatedAt==="string"?L.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":L.properties.taskStatus,...typeof L.properties.taskStatusReason==="string"?{"blade/taskStatusReason":L.properties.taskStatusReason}:{},...L.properties.taskFailure&&typeof L.properties.taskFailure==="object"?{"blade/taskFailure":L.properties.taskFailure}:{},...typeof L.properties.taskStartedAt==="string"?{"blade/taskStartedAt":L.properties.taskStartedAt}:{},...typeof L.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":L.properties.taskCompletedAt}:{},...L.properties.taskDiffStat&&typeof L.properties.taskDiffStat==="object"?{"blade/taskDiffStat":L.properties.taskDiffStat}:{},...typeof L.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":L.properties.taskQueuePosition}:{},...typeof L.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":L.properties.taskQueueDepth}:{},...typeof L.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":L.properties.taskConcurrencyLimit}:{},...typeof L.properties.taskInFlight==="number"?{"blade/taskInFlight":L.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal(),Q=this.runtime.getPendingSteeringCount()>0,B=H?.status==="active"||H?.status==="verifying";if(Q||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Uz(J))continue;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Y of YJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let Z={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,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 B=await this.runtime.rewindSession(Q);return this.messages=[...B.messages],this.contextMessages=await this.loadModelContextOr(B.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),B}},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()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let L=!1,X,U=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},j=this.runtime.resumeSubagent({agentId:Q,prompt:B,onCompleted:(V)=>{if(L)U(V);else X=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j.session.id,status:"in_progress",title:`Resuming ${j.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${j.source.id} at depth ${j.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),L=!0,X)U(X);return j}}}:{},...this.roots.kind==="local"?{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,B,L)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,B,L)},complete:async(Q,B,L)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,B,L)},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,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,B)},getLogs:async(Q,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,B)},setLoggingLevel:async(Q,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,B)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:B})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let L=await R.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:B,onEvent:(j)=>{if(j.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j.toolCall.id,status:"in_progress",title:`Review: ${j.toolCall.function.name}`,content:[],kind:this.mapToolKind(j.toolKind)});else if(j.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:j.toolCall.id,status:j.result.success?"completed":"failed",content:[]})}}),X=await L.completion,U=(await R.list(this.roots.hostStateRoot,this.id)).find((j)=>j.start.reviewId===L.reviewId);if(!U)throw Error(`Review not found: ${L.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:L.reviewId,status:X.status,findings:X.findings.length,content:Wz(U.start,X)}}}}:{},signal:J,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,B,L)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,U=this.mapToolKind(L);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(B,null,2)}}],kind:U})},sendToolResult:(Q,B)=>{if(B.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:B.summary}})}}},Y=await hz(z,Z),W=Y.data?.action;if(W==="start_goal"||W==="resume_goal")this.requestPendingResume();if(W==="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 this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let H=Y.content||Y.message;if(H)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:H}});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(Z){if(J.aborted||Z instanceof Error&&Z.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,Z),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,Z,Y=new Promise((W)=>{Z=W});this.pendingSideConversation=J,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,J.signal)}catch(W){if(J.signal.aborted||W instanceof Error&&W.name==="AbortError")return{stopReason:"cancelled"};throw W}finally{if(Z(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Mz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),J=["model","permissions","theme","config","exit","ide"],Y=z.filter((W)=>!J.includes(W.name)&&(W.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((W)=>{let H;if(W.usage){let Q=W.usage.replace(/^\/\w+\s*/,"").trim();if(Q)H=Q}if(W.aliases?.length){let Q=`Aliases: ${W.aliases.join(", ")}`;H=H?`${H} | ${Q}`:Q}return{name:W.name,description:W.description,input:H?{hint:H}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((W)=>W.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(b.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Z=this.resolvePrompt(z.prompt),Y=Z.content,W=Z.displayText,H=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((D)=>D.outputSchema)?.outputSchema:void 0),Q;if(H!==void 0)Q=Gz(H).schema;if(W.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(W)}let B=Dz(W);if(B){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((D)=>D.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(B.question?`/btw ${B.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(W.trim()))return this.handleSlashCommand(W,this.pendingPrompt.signal);let D=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!D.accepted)throw Error(D.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${D.queued})`),D.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let L=new AbortController,X=()=>{L.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)X();else J.abortSignal?.addEventListener("abort",X,{once:!0});let U=!1,j=!1,V=!1,q,zz=new Promise((D)=>{q=D});this.pendingPrompt=L,this.pendingPromptCompletion=zz;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${W.slice(0,100)}...`),Rz(W)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(W,L.signal)}let D={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:L.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($)}}},O=await Kz(this.agent.chatStream(Y,D,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;if($.delta.length>0)j=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)j=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{V=!0;let _=$.toolCall,N=_.function.name;if(N===S)break;let P=this.mapToolKind($.toolKind),w=`Executing ${N}`;if(N==="Task"&&"function"in _)try{let x=JSON.parse(_.function.arguments),F=x.resume_from??x.resume;if(typeof F==="string")w=`Resuming ${String(x.subagent_type||"subagent")} from ${F}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:_.id,status:"in_progress",title:w,content:[],kind:P});break}case"tool_progress":{V=!0;let _=$.toolCall;if(_.function.name===S)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{V=!0;let _=$.toolCall;if(_.function.name===S)break;let N=$.result,P=[],w=N.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let F of w.changes){if(!F||typeof F!=="object"||!("path"in F)||typeof F.path!=="string")continue;P.push({type:"diff",path:F.path,oldText:"oldContent"in F&&typeof F.oldContent==="string"?F.oldContent:null,newText:"newContent"in F&&typeof F.newContent==="string"?F.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))P.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let F=_.function.name,JJ=Az(Bz(Nz(F,N),Xz));P.push({type:"content",content:{type:"text",text:JJ}})}if(_.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))P.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let x=N.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:x,content:P});break}case"structured_output":j=!0,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":U=$.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"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$.assessment}});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"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:$.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:$.goal.goalId,status:$.goal.status,taskListId:$.frontier.taskListId,total:$.frontier.total,completed:$.frontier.completed,inProgress:$.frontier.inProgress,pending:$.frontier.pending,blocked:$.frontier.blocked,nextTask:$.frontier.nextTask,digestSha256:$.frontier.digestSha256,...$.goal.frontierStall?{stall:{category:$.goal.frontierStall.category,consecutiveCount:$.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate($.tasks);break;case"steering_applied":break;case"follow_up_started":{let _=0;for(let N of $.messages){if(!N.recovered||N.persisted)continue;if(J.projectedRecoveredInputIds?.has(N.id))continue;for(let P of fz(N.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:P});J.projectedRecoveredInputIds?.add(N.id),_++}if(_>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${_} queued instruction${_===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":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:$.goal.goalId,continuation:$.continuation,...$.prematureStopPattern?{prematureStopPattern:$.prematureStopPattern}:{},...$.prematureStopCount!==void 0?{prematureStopCount:$.prematureStopCount}:{}}}});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}:{},...$.preTokenSource?{preTokenSource:$.preTokenSource}:{},...$.estimatedPendingTokens!==void 0?{estimatedPendingTokens:$.estimatedPendingTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{},...$.sampleAttempts!==void 0?{sampleAttempts:$.sampleAttempts}:{},...$.inputReductions!==void 0?{inputReductions:$.inputReductions}:{},...$.messagesOmitted!==void 0?{messagesOmitted:$.messagesOmitted}:{},...$.filesOmitted!==void 0?{filesOmitted:$.filesOmitted}:{},...$.imagesOmitted!==void 0?{imagesOmitted:$.imagesOmitted}:{},...$.fallbackTargetTokens!==void 0?{fallbackTargetTokens:$.fallbackTargetTokens}:{},...$.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:$.fallbackMessagesOmitted}:{},...$.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:$.fallbackMessagesTruncated}:{},...$.failureReason?{failureReason:$.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())L.abort("acp-egress-failed")});if(!await this.flushUpdates())L.abort("acp-egress-failed");this.contextMessages=[...D.messages];let Jz=await this.loadPersistedMessages();if(this.messages=Jz.length>0?Jz:[...D.messages],!O.success){let $=O.error?.type??"unknown",_=O.error?.details??O.error?.message??"Agent execution failed",N=WJ(_)??m(_);throw Cz.internalError({failureType:$,modelId:this.runtime.getCurrentModelId(),taskFailure:N,outputStarted:j,toolExecutionStarted:V,...Number.isInteger(O.metadata?.toolCallsCount)?{toolCallsCount:O.metadata.toolCallsCount}:{}},`Agent turn failed (${$})`)}if(L.signal.aborted)return{stopReason:"cancelled"};let Zz={...O.metadata?.structuredOutput?{structuredOutput:O.metadata.structuredOutput,outputSchemaDigest:O.metadata.structuredOutputSchemaDigest}:{},...O.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:O.metadata.goalVerificationVerdict,...O.metadata.goalVerifierSessionId?{verifierSessionId:O.metadata.goalVerifierSessionId}:{},...O.metadata.goalVerificationEvidenceSha256?{evidenceSha256:O.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(Zz).length>0?{_meta:Zz}:{}}}catch(D){if(L.signal.aborted||D instanceof Error&&D.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,D),D}finally{if(J.abortSignal?.removeEventListener("abort",X),U&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(q(),this.pendingPromptCompletion===zz)this.pendingPromptCompletion=null;if(this.pendingPrompt===L){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let Z=new AbortController,Y,W=new Promise((B)=>{Y=B});this.pendingUserShell=Z,this.pendingUserShellCompletion=W;let H,Q="";try{let B=await this.runtime.executeUserShellCommand(J,{signal:Z.signal,onEvent:async(X)=>{if(H=X.executionId,X.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.executionId,status:"in_progress",title:`! ${X.command}`,content:[],kind:"execute"});return}if(X.type==="output"){Q+=X.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:X.chunk}}]});return}let U=d(X.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.executionId,status:X.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?LJ(X.record):U}}]})}}),L={role:"user",content:B.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(B.record))}};if(this.messages.push(L),this.contextMessages.push(L),B.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return Z.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:B.record.status==="aborted"?"cancelled":"end_turn"}}catch(B){if(H)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H,status:"failed",content:[{type:"content",content:{type:"text",text:B instanceof Error?B.message:String(B)}}]});if(Z.signal.aborted)return{stopReason:"cancelled"};throw B}finally{if(Y(),this.pendingUserShellCompletion===W)this.pendingUserShellCompletion=null;if(this.pendingUserShell===Z){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let J=this.pendingResumeGeneration,Z=()=>{if(J!==this.pendingResumeGeneration)return;this.startPendingResumeRun(J)};if(z>0)this.pendingResumeTimer=setTimeout(Z,z),this.pendingResumeTimer.unref?.();else queueMicrotask(Z)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let J=this.resumePendingIfIdle();this.pendingResumeCompletion=J,J.then(()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}},()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:yz,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let Z="preflight",Y=!1,W,H=null;try{let Q=this.runtime.getPendingSteeringCount()>0,B=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let L=B?.status==="active"||B?.status==="verifying",X=this.runtime.getTurnRecoveryAssessment();if(X.state!=="none"&&(X.state==="requires_attention"||!Q&&!L))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":X}});if(!Q&&!L){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(X.state==="requires_attention"){this.clearPendingResumeRequest();return}Z=Q?"pending_input":"goal",Y=!0;let U=Iz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(U<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:h("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}let j=new AbortController;H=setTimeout(()=>{j.abort("acp-pending-resume-budget-exhausted")},U),H.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:L,projectedRecoveredInputIds:Z==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:j.signal});if(z!==this.pendingResumeGeneration)return;if(j.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:h("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:Z})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let B=Y?HJ(Q):{taskFailure:m(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},L=Z==="preflight"||Z==="pending_input"&&this.runtime.getPendingSteeringCount()>0,X=kz({sessionIdentity:this.id,failedAttempt:J,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:L,evidence:B});if(X.phase==="retry_scheduled")this.pendingResumeRequested=!0,W=X.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:Z,taskFailure:B?.taskFailure,delayMs:X.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${X.delayMs}ms`);else{let U=X.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(U,{attempt:J,kind:Z,taskFailure:B?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${X.retryable}, phase=${U})`,Q),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest()}}finally{if(H!==null)clearTimeout(H);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=W??0}}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let Z=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(Z);await this.persistPermissionMode(Y),this.mode=Z,G.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(G.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(Z){if(J&&J!==z)await this.agent.switchModel(J).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw Z}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(Z){throw await this.runtime.refresh({reasoningEffort:J.selection}),Z}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(Z){throw await this.runtime.refresh({serviceTier:J.selection}),Z}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(Z){throw await this.runtime.refresh({responseVerbosity:J.selection}),Z}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),Z=this.runtime.resolveCommunicationStyleConfiguration(z);if(Z.source!=="built-in"&&!Z.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:Z.source==="built-in"?null:Z.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...Z.source!=="built-in"&&Z.contentSha256?{communicationStyleDigest:Z.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:J.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new xz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime,Y=this.pendingPromptCompletion,W=this.pendingUserShellCompletion,H=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let B,L=async(X)=>{try{await X()}catch(U){B??=U}};if(await L(()=>this.cancel()),Y)await L(()=>Y);if(W)await L(()=>W);if(H)await L(()=>H);if(Q)await L(()=>Q);if(z&&Y&&Z)await L(()=>Z.discardPendingInput());if(J)await L(()=>J.destroy());if(Z)await L(()=>Z.dispose());if(await L(()=>b.destroySession(this.id)),G.debug(`[AcpSession ${this.id}] Destroyed`),B!==void 0)throw B}resolvePrompt(z){let J=[],Z=[],Y=0,W=0,H=0,Q=(X)=>{if(Z.length>0)Z.push({type:"text",text:`
|
|
13
|
-
`}),H+=1;if(Z.push(X),X.type==="text")H+=X.text.length};for(let X of z)if(X.type==="text")J.push(X.text),Q({type:"text",text:X.text});else if(X.type==="image"){let U=`data:${X.mimeType};base64,${X.data}`;Y+=1,W+=U.length,J.push(`[Image: ${X.mimeType}]`),Q({type:"image_url",image_url:{url:U}})}else if(X.type==="resource"){let U=X.resource;if("text"in U){let j=`<file path="${U.uri}">
|
|
14
|
-
${U.text}
|
|
15
|
-
</file>`;J.push(j),Q({type:"text",text:j})}}else if(X.type==="resource_link"){let U=`[Resource: ${X.uri}]`;J.push(U),Q({type:"text",text:U})}if(Y>u)throw Error(`ACP prompt contains more than ${u} images`);if(W>Yz)throw Error("ACP prompt images exceed the 5 MiB limit");if(H>g)throw Error(`ACP prompt text exceeds ${g} characters`);if(Buffer.byteLength(J.join(`
|
|
16
|
-
`),"utf8")>c)throw Error(`ACP prompt text exceeds ${c} bytes`);let L=J.join(`
|
|
17
|
-
`);return{content:Y>0?Z:L,displayText:L}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;G.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let J=z.map((Z)=>({content:Z.subject,priority:Z.priority,status:Z.status}));G.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let Z=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(Z))return G.debug(`[AcpSession ${this.id}] Auto-approving ${Z} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Z==="write"||Z==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${Z} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=f(),W=[];if(z.message)W.push({type:"content",content:{type:"text",text:z.message}});if(z.details)W.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)W.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
-
- ${z.risks.join(`
|
|
19
|
-
- `)}`}});let H=this.mapToolKind(Z),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:W,kind:H}},B=await this.waitForClientInteraction(this.connection.requestPermission(Q),J);if(!B)return{approved:!1,reason:p};let L=B.outcome;if(L.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let X=L.optionId;if(X==="allow_always")return{approved:!0,scope:"project"};if(X==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let U=X==="allow_once";return{approved:U,scope:"once",reason:U?void 0:"User denied the operation"}}catch(Y){return G.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let Z=z.questions??[];if(Z.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Z.some((W)=>W.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[W,H]of Z.entries()){let Q=H.options.map((U,j)=>`answer:${W}:${j}`),B=`answer:${W}:cancel`,L=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.options.map((U,j)=>({optionId:Q[j],name:U.label,kind:"allow_once"})),{optionId:B,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:f(),status:"pending",title:H.header,kind:"think",content:[{type:"content",content:{type:"text",text:[H.question,...H.options.map((U)=>`${U.label}: ${U.description}`)].join(`
|
|
20
|
-
`)}}]}}),J);if(!L)return{approved:!1,reason:p};if(L.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let X=Q.indexOf(L.outcome.optionId);if(X<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[H.header]=H.options[X].label}return{approved:!0,answers:Y}}catch(W){return G.warn(`[AcpSession ${this.id}] Question request failed:`,W),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let Z=z.mcpElicitation;if(!Z)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Z.mode==="url"){let W=await this.requestElicitationChoice("MCP external authorization",[Z.message,`Server: ${Z.serverName}`,`Domain: ${Z.domain??"unknown"}`,`URL: ${Z.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
21
|
-
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],J);if(W==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:W==="decline"?"User declined URL":"User cancelled",elicitation:{action:W==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let W of Z.fields??[]){let H=await this.collectAcpElicitationField(W,J);if(H.cancelled)return{approved:!1,reason:H.reason,elicitation:{action:"cancel"}};if(H.value!==void 0)Y[W.name]=H.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return G.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let Z=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((H,Q)=>({id:`option:${Q}`,label:H.label,value:H.value})),Y=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
-
`),[...Z.map((H)=>({id:H.id,label:H.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(Y==="skip")return{cancelled:!1};let W=Z.find((H)=>H.id===Y);if(!W)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:W.value}}if(z.defaultValue!==void 0){let Z=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
23
|
-
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(Z==="default")return{cancelled:!1,value:z.defaultValue};if(Z==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,Z,Y){let W=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Z.map((H)=>({optionId:H.id,name:H.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:f(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),Y);return W?.outcome.outcome==="selected"?W.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((Z,Y)=>{let W=!1,H=(B)=>{if(W)return;W=!0,J.removeEventListener("abort",Q),B()},Q=()=>H(()=>Z(void 0));if(J.addEventListener("abort",Q,{once:!0}),J.aborted)Q();z.then((B)=>H(()=>Z(B)),(B)=>H(()=>Y(B)))})}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 A=M("Agent"),BJ="remote task isolation is not supported";function y(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function UJ(z){return k.invalidParams({code:z.code,reason:z.reason})}function jJ(){return k.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:BJ})}function uz(){return k.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function gz(z){return z instanceof Error&&"code"in z&&z.code==="acp_remote_workspace_mismatch"&&"reason"in z&&z.reason==="exact-identity-mismatch"}function I(z){try{return n(z)}catch(J){if(J instanceof cz)throw UJ(J);throw J}}function i(z,J){let Z=s(z);return Object.freeze({kind:"acp-remote",hostStateRoot:t(Z.collisionIdentity),executionRoot:Z.wirePath,hostResourceRoot:J,profile:z,descriptor:Z})}function a(z,J){let Z=pz(z.remoteWorkspace),Y=t(Z.collisionIdentity);if(z.projectPath!==Y)throw Error("ACP remote workspace durable state is invalid");let W=n(Z.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:Y,executionRoot:Z.wirePath,hostResourceRoot:J,profile:W,descriptor:Z})}function GJ(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class e{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=l.resolve(r())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=iz();this.runtimeResidencyValue=new ez({maxResident:z?.maxResidentSessionRuntimes??dz,idleMs:z?.sessionRuntimeIdleMs??lz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof tz)throw k.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await az(),{protocolVersion:XJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=o("acp"),Z=z.cwd||r(),Y=y(this.clientCapabilities),W=Y?I(Z):void 0,H=z._meta?.["blade/taskIsolation"],Q=H==="local"||H==="worktree"?H:void 0;if(Y&&Q)throw jJ();let B=z._meta?.["blade/taskPrompt"],L=await this.reserveSessionRuntime(J),X;try{let U,j;if(W){let q=i(W,this.hostResourceRoot);U=await K.createRemoteSessionMetadata(J,q.hostStateRoot,q.descriptor,{}),j=a(U,this.hostResourceRoot)}else j=E(Z);let V=!Y&&Q?await sz.createSessionTask({sessionId:J,prompt:typeof B==="string"&&B.trim()?B:"ACP task session",sourceProjectPath:Z,isolation:Q}):void 0;if(V)j=E(V.metadata.projectPath);return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session kind: ${j.kind}`),X=new T(J,j,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...V?.taskWorktree?{taskWorktree:V.taskWorktree}:{},...V?.metadata.taskIsolation?{taskIsolation:V.metadata.taskIsolation}:{}}),await X.initialize(),this.assertNotDestroyed(),this.commitSession(J,X,L),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),X.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,V?.metadata,X.getModelConfiguration())}catch(U){throw L.cancel(),await X?.destroy().catch(()=>{return}),U}}async listSessions(z){let J=y(this.clientCapabilities);if(!J&&z.cwd!=null&&!l.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let Z=J?await K.listRemoteSessionPage({...z.cwd!=null?{descriptor:s(I(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await K.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Y)=>({sessionId:Y.sessionId,cwd:J?GJ(Y):Y.projectPath,title:Y.title??null,updatedAt:Y.lastMessageTime,_meta:{"blade/taskStatus":Y.taskStatus,...Y.taskStatusReason?{"blade/taskStatusReason":Y.taskStatusReason}:{},...Y.taskFailure?{"blade/taskFailure":Y.taskFailure}:{},...Y.taskStartedAt?{"blade/taskStartedAt":Y.taskStartedAt}:{},...Y.taskCompletedAt?{"blade/taskCompletedAt":Y.taskCompletedAt}:{},...Y.taskModelId?{"blade/taskModelId":Y.taskModelId}:{},...Y.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Y.taskRetriedFrom?{"blade/taskRetriedFrom":Y.taskRetriedFrom}:{},...Y.taskDelivery?{"blade/taskDelivery":Y.taskDelivery}:{},...Y.taskIsolation?{"blade/taskIsolation":Y.taskIsolation}:{},...Y.taskSourceProjectPath?{"blade/taskSourceProjectPath":Y.taskSourceProjectPath}:{},...Y.taskWorktreeBranch?{"blade/taskWorktreeBranch":Y.taskWorktreeBranch}:{},...Y.taskBaseCommit?{"blade/taskBaseCommit":Y.taskBaseCommit}:{},...Y.taskDiffStat?{"blade/taskDiffStat":Y.taskDiffStat}:{},...Y.taskQueuePosition?{"blade/taskQueuePosition":Y.taskQueuePosition}:{},...Y.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Y.taskQueueDepth}:{},...Y.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Y.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let J=y(this.clientCapabilities),Z=J?i(I(z.cwd),this.hostResourceRoot):void 0;if(!J&&!l.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Y=o("fork"),W=await this.reserveSessionRuntime(Y),H;try{let Q;try{Q=await K.forkSession(z.sessionId,{sourceProjectPath:Z?.hostStateRoot??z.cwd,targetProjectPath:Z?.hostStateRoot??z.cwd,newSessionId:Y,...Z?{remote:{expectedDescriptor:Z.descriptor}}:{}})}catch(L){if(gz(L))throw uz();throw L}this.assertNotDestroyed();let B=J?a(Q.metadata,this.hostResourceRoot):E(Q.projectPath??z.cwd);return H=new T(Q.sessionId,B,this.connection,this.clientCapabilities,{initialMessages:Q.messages,permissionMode:Q.metadata.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),this.assertNotDestroyed(),this.commitSession(Q.sessionId,H,W),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Q.sessionId,J?void 0:Q.metadata,H.getModelConfiguration())}catch(Q){throw W.cancel(),await H?.destroy().catch(()=>{return}),Q}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!y(this.clientCapabilities)){await K.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let B=await this.reserveSessionRuntime(z.sessionId),L;try{let[X,U]=await Promise.all([K.loadSession(z.sessionId,z.cwd),K.findSessionMetadata(z.sessionId,z.cwd)]);if(!U)throw Error(`Session not found: ${z.sessionId}`);return L=new T(z.sessionId,E(z.cwd),this.connection,this.clientCapabilities,{initialMessages:X,permissionMode:U.permissionMode,mcpServers:z.mcpServers}),await L.initialize(),await L.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,L,B),L.sendAvailableCommandsDelayed(),this.buildSessionSetup(L.getModelConfiguration(),L.getMode())}catch(X){throw B.cancel(),await L?.destroy().catch(()=>{return}),X}}let Z=i(I(z.cwd),this.hostResourceRoot),Y;try{Y=await K.assertRemoteSessionWritable(z.sessionId,Z.hostStateRoot,Z.descriptor)}catch(B){if(gz(B))throw uz();throw B}let W=a(Y,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let H=await this.reserveSessionRuntime(z.sessionId),Q;try{let B=await K.loadRemoteSession(z.sessionId,W.hostStateRoot,W.descriptor);return Q=new T(z.sessionId,W,this.connection,this.clientCapabilities,{initialMessages:B,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,Q,H),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup(Q.getModelConfiguration(),Q.getMode())}catch(B){throw H.cancel(),await Q?.destroy().catch(()=>{return}),B}}commitSession(z,J,Z){let Y=Z.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),Y.release()}async closeResidentSession(z,J={}){let Z=this.sessions.get(z);if(!Z)return;let Y=this.runtimeResidency.owns(z,Z),W;try{await Z.destroy(J)}catch(Q){W=Q}let H=await this.runtimeResidency.forget(z,Z);if(this.sessions.get(z)===Z)this.sessions.delete(z);if(Y&&!H&&W===void 0)throw Error(`ACP Session is still active: ${z}`);if(W!==void 0)throw W}buildChildSessionResponse(z,J,Z){return{sessionId:z,...this.buildSessionSetup(Z,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let Z=z?.models??[],Y=(z?.currentModelId&&Z.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??Z[0]?.id,W=[{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"}],H=[];if(Z.length>0)H.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:Z.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)H.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)H.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)H.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)H.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:W,currentModeId:J},configOptions:H.length>0?H:void 0}}async closeSession(z){this.assertNotDestroyed();let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let Z=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await Z.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&rz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await Z.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&vz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await Z.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&mz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await Z.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&oz(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await Z.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(Z){z??=Z}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await nz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function GZ(){let z=_J.toWeb(process.stdout),J=VJ.toWeb(process.stdin),Z=C.ndJsonStream(z,J),Y,W=new C.AgentSideConnection((Q)=>{return Y=new e(Q),Y},Z),H=zJ(async()=>{await Y?.destroy()});try{await W.closed}finally{H(),await Y?.destroy()}}export{GZ as runAcpIntegration,E as createLocalAcpSessionRoots};
|
package/dist/chunk-z2jwm4s8.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{lj as a,mj as b,nj as c}from"./chunk-6m4sqwj0.js";import"./chunk-1xg7qx35.js";import"./chunk-xnstybjm.js";import"./chunk-mm05y2c5.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
|
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-3g4TPTeI.js","assets/index-DaiT-mmo.js","assets/vendor-react-DofNRwfy.js","assets/vendor-radix-Bc1_Q9tz.js","assets/session-events-CWzF04l4.js","assets/index-DGf6Z2kM.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as m,j as e}from"./vendor-react-DofNRwfy.js";import{c as W,u as P,a as N,s as Be,b as tt,d as se,H as Ce,P as st,G as _e,L as _,S as Pe,T as ae,C as ue,D as Le,e as Ve,f as at,g as Oe,h as Ue,i as He,j as F,k as rt,l as X,B as nt,m as ve,n as re,o as ne,R as le,F as it,_ as qe,p as ot,q as lt,r as ze,t as ct,v as Ke,X as Ge,w as dt,A as ye,x as ut,W as mt,y as ht,z as xt,E as pt}from"./index-DaiT-mmo.js";import{l as we,m as ft,g as bt,n as vt,f as gt,t as kt,k as jt}from"./session-events-CWzF04l4.js";import{A as yt,E as wt}from"./external-link-UkIIC2ds.js";import{A as We,C as Nt}from"./chevrons-up-down-BboZzEAk.js";import{j as St,k as Ct,l as Et,m as Je}from"./vendor-radix-Bc1_Q9tz.js";import{P as Tt}from"./pause-DVIT6IIr.js";import{P as Mt}from"./play-DsdF5dji.js";import{C as At}from"./clock-3-aXgeptZP.js";import{t as I}from"./team-QZ9byb3E.js";import{teamService as Ee}from"./teamService-BliaDj1Z.js";/**
|
|
3
|
-
* @license lucide-react v0.300.0 - ISC
|
|
4
|
-
*
|
|
5
|
-
* This source code is licensed under the ISC license.
|
|
6
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
7
|
-
*/const Qe=W("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
|
|
8
|
-
* @license lucide-react v0.300.0 - ISC
|
|
9
|
-
*
|
|
10
|
-
* This source code is licensed under the ISC license.
|
|
11
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
12
|
-
*/const Rt=W("Files",[["path",{d:"M15.5 2H8.6c-.4 0-.8.2-1.1.5-.3.3-.5.7-.5 1.1v12.8c0 .4.2.8.5 1.1.3.3.7.5 1.1.5h9.8c.4 0 .8-.2 1.1-.5.3-.3.5-.7.5-1.1V6.5L15.5 2z",key:"cennsq"}],["path",{d:"M3 7.6v12.8c0 .4.2.8.5 1.1.3.3.7.5 1.1.5h9.8",key:"ms809a"}],["path",{d:"M15 2v5h5",key:"qq6kwv"}]]);/**
|
|
13
|
-
* @license lucide-react v0.300.0 - ISC
|
|
14
|
-
*
|
|
15
|
-
* This source code is licensed under the ISC license.
|
|
16
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/const Ft=W("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/**
|
|
18
|
-
* @license lucide-react v0.300.0 - ISC
|
|
19
|
-
*
|
|
20
|
-
* This source code is licensed under the ISC license.
|
|
21
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
22
|
-
*/const $t=W("HelpCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
|
|
23
|
-
* @license lucide-react v0.300.0 - ISC
|
|
24
|
-
*
|
|
25
|
-
* This source code is licensed under the ISC license.
|
|
26
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
27
|
-
*/const Dt=W("MessageCircleQuestion",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
|
|
28
|
-
* @license lucide-react v0.300.0 - ISC
|
|
29
|
-
*
|
|
30
|
-
* This source code is licensed under the ISC license.
|
|
31
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
32
|
-
*/const It=W("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/**
|
|
33
|
-
* @license lucide-react v0.300.0 - ISC
|
|
34
|
-
*
|
|
35
|
-
* This source code is licensed under the ISC license.
|
|
36
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
-
*/const Bt=W("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/**
|
|
38
|
-
* @license lucide-react v0.300.0 - ISC
|
|
39
|
-
*
|
|
40
|
-
* This source code is licensed under the ISC license.
|
|
41
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
42
|
-
*/const _t=W("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Te(t){return t.split("/").filter(Boolean).at(-1)||t}function Pt(){const t=P(),s=N(v=>v.sessions),a=N(v=>v.currentSessionRef),r=N(v=>v.taskDeliveryActions),i=N(v=>v.deliverTask),n=we(v=>v.openFilePreview),[l,h]=m.useState(!1),d=s.find(v=>Be({sessionId:v.sessionId,projectPath:v.projectPath},a));if(!(d!=null&&d.taskIsolation))return null;const c=d.taskDiffStat,k=d.taskIsolation==="worktree",o=tt(d),f=r[se(o)],p=d.taskDelivery,y=(p==null?void 0:p.status)==="conflicted",S=!!(c&&(c.changedFiles>0||c.commits>0)),x=!["queued","running"].includes(d.taskStatus),E=(p==null?void 0:p.status)==="applied"||(p==null?void 0:p.status)==="discarded",g=k&&S&&x&&!E,u=c?c.additions+c.deletions:0,b=u>0&&c?c.additions/u*100:0,A=v=>{i(o,v).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(Ce,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:Te(d.taskSourceProjectPath||d.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(st,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx(Ce,{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")})]}),d.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:d.taskWorktreeBranch,children:[e.jsx(_e,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:d.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(Rt,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:c.changedFiles})]}),u>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:`${b}%`}}),e.jsx("span",{className:"h-full bg-red-500/80",style:{width:`${100-b}%`}})]}),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})}),S&&(p==null?void 0:p.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")}),g&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!f,onClick:()=>A("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:[f==="apply"?e.jsx(_,{className:"h-3 w-3 animate-spin"}):e.jsx(Pe,{className:"h-3 w-3"}),t(f==="apply"?"artifact.applying":y?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!f,onClick:()=>h(!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:f==="discard"?e.jsx(_,{className:"h-3 w-3 animate-spin"}):e.jsx(ae,{className:"h-3 w-3"})})]}),(p==null?void 0:p.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(ue,{className:"h-3 w-3"}),t("artifact.applied")]}),(p==null?void 0:p.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(ae,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(p==null?void 0:p.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(yt,{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:p.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx(Le,{open:l,onOpenChange:h,children:e.jsxs(Ve,{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(at,{children:[e.jsx(Oe,{children:t("artifact.discardDialog.title")}),e.jsx(Ue,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:Te(d.taskSourceProjectPath||d.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(He,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>h(!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:()=>{h(!1),A("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(ae,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}const Lt=new Set(["completed","stale","failed","aborted","interrupted"]),Vt={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"},Ot={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 ce(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Ut(t){const s=ce(t),a=ce(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,l=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(l)))return{title:s.title,body:s.body,priority:r,confidenceScore:i,codeLocation:{path:a.path,lineStart:n,lineEnd:l}}}function Ht(t){const s=ce(t),a=ce(s==null?void 0:s.target);if((s==null?void 0:s.phase)!=="completed"||typeof s.status!="string"||!Lt.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(Ut);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 qt(t){const{path:s,lineStart:a,lineEnd:r}=t.codeLocation;return a===r?`${s}:L${a}`:`${s}:L${a}-${r}`}function zt({report:t}){const s=P(),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:F("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",Ot[t.status]),children:[s("chat.review.status"),": ",s(Vt[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:qt(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 Kt({elicitation:t,messageId:s}){const a=P(),r=N(g=>g.currentSessionRef),i=N(g=>g.setElicitation),[n,l]=m.useState(()=>Wt(t.details.fields??[])),[h,d]=m.useState(()=>Jt(t.details.fields??[])),[c,k]=m.useState(!1),[o,f]=m.useState(),p=t.details.fields??[],y=m.useMemo(()=>p.every(g=>{var b;if(!g.required)return!0;if(me(g))return!!((b=h[g.name])!=null&&b.trim()||g.defaultValue!==void 0);const u=n[g.name]??g.defaultValue;return Array.isArray(u)?u.length>0:u!==void 0}),[p,h,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 S=async(g,u)=>{if(!(!r||c)){k(!0),f(void 0);try{await X.respondToElicitation(r,t.toolCallId,{action:g,...u?{content:u}:{}}),i(s,{...t,status:"responded"})}catch(b){f(b instanceof Error?b.message:a("interaction.elicitation.failed"))}finally{k(!1)}}},x=async()=>{try{await S("accept",Qt(p,n,h))}catch(g){f(g instanceof Error?g.message:String(g))}},E=()=>{const g=t.details.url;if(!g){f("MCP URL is unavailable");return}if(!window.open(g,"_blank","noopener,noreferrer")){f("The browser blocked the external window");return}S("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(Z,{onClick:E,disabled:c,primary:!0,label:a("interaction.elicitation.open"),icon:e.jsx(wt,{className:"h-3.5 w-3.5"})}),e.jsx(Z,{onClick:()=>void S("decline"),disabled:c,label:a("interaction.elicitation.decline")}),e.jsx(Z,{onClick:()=>void S("cancel"),disabled:c,label:a("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[p.map(g=>e.jsx(Gt,{field:g,value:n[g.name],rawValue:h[g.name]??"",onValueChange:u=>l(b=>({...b,[g.name]:u})),onRawChange:u=>d(b=>({...b,[g.name]:u}))},g.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Z,{onClick:()=>void x(),disabled:c||!y,primary:!0,label:a("interaction.elicitation.submit"),icon:c?e.jsx(_,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(Z,{onClick:()=>void S("decline"),disabled:c,label:a("interaction.elicitation.decline")}),e.jsx(Z,{onClick:()=>void S("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 Gt({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:Yt(t).map(n=>{const l=Array.isArray(s)?s.includes(n.value):s===n.typedValue;return e.jsx("button",{type:"button","aria-pressed":l,onClick:()=>{if(t.type==="multi-select"){const h=Array.isArray(s)?s:[];r(h.includes(n.value)?h.filter(d=>d!==n.value):[...h,n.value])}else r(n.typedValue)},className:F("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",l?"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:Xt(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 Z({onClick:t,disabled:s,primary:a=!1,label:r,icon:i}){return e.jsxs("button",{type:"button",onClick:t,disabled:s,className:F("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 Wt(t){return Object.fromEntries(t.filter(s=>!me(s)&&s.defaultValue!==void 0).map(s=>[s.name,Array.isArray(s.defaultValue)?[...s.defaultValue]:s.defaultValue]))}function Jt(t){return Object.fromEntries(t.filter(s=>me(s)&&s.defaultValue!==void 0).map(s=>[s.name,String(s.defaultValue)]))}function Qt(t,s,a){var i;const r={};for(const n of t){if(me(n)){const h=((i=a[n.name])==null?void 0:i.trim())??"";if(!h){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 d=Number(h);if(!Number.isFinite(d))throw new Error(`${n.title} must be a finite number`);if(n.type==="integer"&&!Number.isSafeInteger(d))throw new Error(`${n.title} must be a safe integer`);r[n.name]=d}else r[n.name]=h;continue}const l=s[n.name]??n.defaultValue;if(l===void 0){if(n.required)throw new Error(`${n.title} is required`);continue}if(Array.isArray(l)){if(n.minItems!==void 0&&l.length<n.minItems)throw new Error(`${n.title} requires at least ${n.minItems} choices`);if(n.maxItems!==void 0&&l.length>n.maxItems)throw new Error(`${n.title} allows at most ${n.maxItems} choices`)}r[n.name]=l}return r}function Yt(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 me(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function Xt(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 Zt(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 es({report:t}){const s=P(),[a,r]=m.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(nt,{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(ue,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(Qe,{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 ts=m.lazy(()=>qe(()=>import("./MarkdownRenderer-3g4TPTeI.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.MarkdownRenderer})));function Me({text:t,label:s}){const[a,r]=m.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(ue,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(Qe,{className:"h-3.5 w-3.5"})})}function ss(){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(ve,{size:20,pulse:!1})})}function as(){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 Ae(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 rs(t){if(typeof t=="string")return{text:Ae(t),images:[]};const s=t.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
43
|
-
`),a=t.filter(r=>r.type==="image_url").map(r=>r.image_url.url);return{text:Ae(s),images:a}}function Ne(t){return typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.text).join(`
|
|
44
|
-
`)}function ns(t){const s=t.agentContent;return s?ft(s):Ne(t.content)}function Re({content:t,syntaxHighlight:s=!0}){return e.jsx(m.Suspense,{fallback:e.jsx("pre",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono whitespace-pre-wrap",children:t}),children:e.jsx(ts,{content:t,syntaxHighlight:s})})}function Se({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:F("text-[11px] px-2 py-0.5 rounded-full font-mono",s[t]),children:a[t]})}function is(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 Fe=500;function Ye(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 $e(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 xe(t,s){if(t.length<=s)return t;if(s<=0)return"";const a=`
|
|
45
|
-
... (display clipped) ...
|
|
46
|
-
`,r=s-a.length;if(r<=0)return $e(t,s);const i=Math.floor(r/3);return`${Ye(t,i)}${a}${$e(t,r-i)}`}function os(t){const s=t.split(`
|
|
47
|
-
`),a=s.at(-1),r=a!=null&&a.startsWith("Output truncated")?a:void 0,i=r?s.slice(0,-1).join(`
|
|
48
|
-
`):t,n=r?`
|
|
49
|
-
${r}`:"",l=Math.max(0,Fe-n.length),d=i.indexOf(`
|
|
50
|
-
stderr:
|
|
51
|
-
`);let c;if(d>=0&&i.includes(`
|
|
52
|
-
stdout:
|
|
53
|
-
`)){const k=i.slice(0,d),o=i.slice(d+1),f=Math.max(0,l-1),p=Math.floor(f/2);c=`${xe(k,p)}
|
|
54
|
-
${xe(o,f-p)}`}else c=xe(i,l);return{body:Ye(c,l),...r?{notice:r}:{},truncated:!!r||t.length>Fe}}function ls({tool:t}){const[s,a]=m.useState(!1),r=is(t.arguments),i=t.output?os(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(re,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}):e.jsx(ne,{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(Se,{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:[`
|
|
55
|
-
`,e.jsx("span",{"data-tool-truncation-notice":!0,children:i.notice})]})]})]})]})]})}function Xe({toolCalls:t}){return t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map(s=>e.jsx(ls,{tool:s},s.toolCallId))})}function cs({toolCalls:t,toolCallIds:s}){const a=P(),[r,i]=m.useState(!1),n=m.useMemo(()=>new Map(t.map(o=>[o.toolCallId,o])),[t]),l=s.flatMap(o=>{const f=n.get(o);return f?[f]:[]});if(l.length===0)return null;const h=l.filter(o=>o.status==="running").length,d=l.filter(o=>o.status==="error").length,c=[...l].reverse().find(o=>o.status==="running"&&!!o.progressMessage),k=h>0?a(l.length===1?"chat.timeline.tools.runningOne":"chat.timeline.tools.running",{count:l.length}):d>0?a(l.length===1?"chat.timeline.tools.completedOneWithError":"chat.timeline.tools.completedWithErrors",{count:l.length,errors:d}):a(l.length===1?"chat.timeline.tools.completedOne":"chat.timeline.tools.completed",{count:l.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(re,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(ne,{className:"h-3.5 w-3.5 shrink-0"}),h>0&&e.jsx(_,{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(Xe,{toolCalls:l})})]})}function ds({content:t}){const s=P(),[a,r]=m.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(re,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}):e.jsx(ne,{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 us({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 ms({toolCalls:t}){const s=we(r=>r.openFilePreview),a=m.useMemo(()=>{const r=new Map,i=["Write","SearchReplace","Edit","ApplyPatch"];for(const n of t){if(n.status!=="success")continue;const l=n.metadata;if(n.toolName==="ApplyPatch"&&Array.isArray(l==null?void 0:l.changes)){for(const d of l.changes)d&&typeof d=="object"&&"path"in d&&typeof d.path=="string"&&r.set(d.path,{path:d.path,toolName:n.toolName});continue}const h=l==null?void 0:l.file_path;h&&i.includes(n.toolName)&&r.set(h,{path:h,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(it,{className:"w-3 h-3"}),i]},r)})})]})}function hs({subagent:t}){var G,K,J,Q;const s=P(),[a,r]=m.useState(null),[i,n]=m.useState(!1),[l,h]=m.useState(null),[d,c]=m.useState(!1),[k,o]=m.useState(""),[f,p]=m.useState(!1),[y,S]=m.useState(null),[x,E]=m.useState(null),[g,u]=m.useState(null),b=N(R=>R.currentSessionRef),A=N(R=>R.isStreaming),v=N(R=>R.isTemporarySession);if(!t)return null;const C=t.status==="running",D=a!==null?a:C,z=t.toolCalls||l||[],O=t.output||t.thinking||z.length>0||t.sessionId,w=x&&x.status!=="running"?x:g,M=(w==null?void 0:w.id)??t.sessionId,$=((G=w==null?void 0:w.restartRecovery)==null?void 0:G.outcome)==="failed",B=!C&&!A&&!v&&!$&&(x==null?void 0:x.status)!=="running"&&!!(M&&b);m.useEffect(()=>{if(!D||C||!t.sessionId||!(b!=null&&b.projectPath)||l!==null||t.toolCalls&&t.toolCalls.length>0)return;let R=!0;return n(!0),X.getMessages({sessionId:t.sessionId,projectPath:b.projectPath}).then(U=>{var L,T;if(!R)return;const H=gt(U),j=new Map;for(const q of H)if((T=(L=q.agentContent)==null?void 0:L.toolCalls)!=null&&T.length)for(const he of q.agentContent.toolCalls)j.has(he.toolCallId)||j.set(he.toolCallId,he);h(Array.from(j.values()))}).finally(()=>{R&&n(!1)}),()=>{R=!1}},[D,C,t.sessionId,t.toolCalls,l,b==null?void 0:b.projectPath]),m.useEffect(()=>{if(!t.sessionId||!b)return;let R=!0;const U=t.rootAgentId??t.sessionId,H=t.resumeDepth??0;return X.listSubagents(b).then(j=>{if(!R)return;u(j.find(T=>T.id===t.sessionId)??null);const L=j.filter(T=>T.id!==t.sessionId&&T.rootAgentId===U&&T.resumeDepth>H).sort((T,q)=>q.resumeDepth-T.resumeDepth||q.lastActiveAt-T.lastActiveAt)[0];L&&E(L)}).catch(()=>{}),()=>{R=!1}},[b==null?void 0:b.sessionId,b==null?void 0:b.projectPath,t.sessionId,t.rootAgentId,t.resumeDepth]),m.useEffect(()=>{if(!x||x.status!=="running"||!b)return;let R=!0;const U=async()=>{try{const L=(await X.listSubagents(b)).find(T=>T.id===x.id);R&&L&&E(L)}catch{}},H=window.setInterval(()=>{U()},1e3);return()=>{R=!1,window.clearInterval(H)}},[b,x==null?void 0:x.id,x==null?void 0:x.status]);const V=async()=>{if(!(!b||!M||!k.trim()||f)){p(!0),S(null);try{const R=await X.resumeSubagent(b,M,k.trim());E(R.session),o(""),c(!1),r(!0)}catch(R){S(R instanceof Error?R.message:s("chat.subagent.resumeFailed"))}finally{p(!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(!D),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:[C&&e.jsx(_,{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(Se,{status:t.status==="completed"?"success":t.status==="failed"?"error":"running"}),t.type==="verification"&&t.verificationVerdict&&e.jsx("span",{"data-verification-verdict":t.verificationVerdict,className:F("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})})]}),O&&e.jsx(re,{className:F("h-3.5 w-3.5 text-[hsl(var(--deck-ink-muted))] transition-transform",D&&"rotate-180")})]}),!D&&!C&&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}),D&&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(_,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.loadingLogs")]}),!i&&z.length>0&&e.jsx(Xe,{toolCalls:z}),x&&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:x.id,status:x.status,depth:x.resumeDepth??1})}),(((K=x.result)==null?void 0:K.message)||((J=x.result)==null?void 0:J.error))&&e.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[hsl(var(--deck-ink))]",children:x.result.message||x.result.error})]}),$&&((Q=w==null?void 0:w.result)==null?void 0:Q.error)&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:w.result.error}),B&&e.jsxs("div",{className:"space-y-2",children:[d?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:R=>o(R.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),S(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 V(),disabled:!k.trim()||f,className:"flex items-center gap-1 rounded bg-[#7C3AED] px-2 py-1 text-[11px] font-medium text-white disabled:opacity-50",children:[f&&e.jsx(_,{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(le,{className:"w-3 h-3"}),s("chat.subagent.resume")]}),y&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:y})]})]})]})}function xs({confirmation:t,messageId:s}){const a=P(),[r,i]=m.useState(!1),[n,l]=m.useState(null),h=N(k=>k.currentSessionRef),d=N(k=>k.setConfirmation);if(!t)return null;const c=async(k,o)=>{if(!(!h||r)){i(!0),l(null);try{await X.respondPermission(h,t.toolCallId,{approved:k,scope:o}),d(s,{...t,status:k?"approved":"denied"})}catch(f){l(f instanceof Error?f.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(_,{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 ps({question:t,messageId:s}){const a=P(),[r,i]=m.useState({}),[n,l]=m.useState({}),[h,d]=m.useState(!1),[c,k]=m.useState(null),o=N(x=>x.currentSessionRef),f=N(x=>x.setQuestion),p=m.useMemo(()=>t?t.questions.reduce((x,E)=>{var A;const g=(A=n[E.header])==null?void 0:A.trim(),u=r[E.header];if(E.multiSelect){const v=Array.isArray(u)?[...u]:[];return g&&v.push(g),v.length>0&&(x[E.header]=v),x}const b=g||(typeof u=="string"?u:"");return b&&(x[E.header]=b),x},{}):{},[r,n,t]),y=(t==null?void 0:t.questions.every(x=>x.header in p))??!1;if(!t)return null;const S=async()=>{if(!(!o||h||!y)){d(!0),k(null);try{await X.respondToQuestion(o,t.toolCallId,p),f(s,{...t,status:"answered",answers:p})}catch(x){k(x instanceof Error?x.message:a("interaction.question.failed"))}finally{d(!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((x,E)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:x.question}),e.jsxs("div",{className:"space-y-1",children:[x.options.map((g,u)=>e.jsxs("button",{type:"button",onClick:()=>{if(x.multiSelect){const b=r[x.header]||[],A=b.includes(g.label)?b.filter(v=>v!==g.label):[...b,g.label];i({...r,[x.header]:A})}else i({...r,[x.header]:g.label}),l({...n,[x.header]:""})},className:F("w-full text-left px-3 py-2 rounded-md border text-[12px] font-mono transition-colors","border-[hsl(var(--deck-border))]",(x.multiSelect?(r[x.header]||[]).includes(g.label):r[x.header]===g.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:g.label}),e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-faint))] mt-1",children:g.description})]},u)),e.jsx("input",{"aria-label":`${x.header} other response`,value:n[x.header]??"",onChange:g=>l({...n,[x.header]:g.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]"})]})]},E)),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 S(),disabled:h||!y,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:[h&&e.jsx(_,{className:"h-3.5 w-3.5 animate-spin"}),a("interaction.question.submit")]})]})}function fs({message:t}){const s=t.agentContent,a=N(y=>y.isStreaming&&y.currentAssistantMessageId===t.id);if(!s){const y=Ne(t.content);return y?e.jsx(Re,{content:y}):null}const{toolCalls:r,tasks:i,confirmation:n,question:l,elicitation:h}=s,d=bt(s),c=vt(s);if(!(c.length>0||i.length>0||d.length>0||n||l||h)&&a)return e.jsxs("div",{className:"flex items-center gap-2 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(_,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-[12px] font-mono",children:"Thinking..."})]});const f=r.length>0&&r.every(y=>y.status==="success"||y.status==="error")&&!a,p=!a;return e.jsxs("div",{className:"space-y-3",children:[c.map(y=>y.type==="thinking"?e.jsx("div",{"data-agent-timeline-block":"thinking",children:e.jsx(ds,{content:y.content})},y.id):y.type==="text"?e.jsx("div",{"data-agent-timeline-block":"text",children:e.jsx(Re,{content:y.content,syntaxHighlight:p})},y.id):e.jsx("div",{"data-agent-timeline-block":"tool_group",children:e.jsx(cs,{toolCalls:r,toolCallIds:y.toolCallIds})},y.id)),i.length>0&&e.jsx(us,{tasks:i}),d.map(y=>e.jsx(hs,{subagent:y},y.id)),n&&e.jsx(xs,{confirmation:n,messageId:t.id}),l&&e.jsx(ps,{question:l,messageId:t.id}),h&&e.jsx(Kt,{elicitation:h,messageId:t.id}),f&&e.jsx(ms,{toolCalls:r})]})}function bs({message:t,showAvatar:s=!0}){var h,d,c,k;const a=t.role==="user";if(t.role==="system"){const o=Ne(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=(h=t.metadata)!=null&&h.userShellCommand&&typeof t.metadata.userShellCommand=="object"?t.metadata.userShellCommand:(d=t.metadata)!=null&&d.userShellExecution&&typeof t.metadata.userShellExecution=="object"?t.metadata.userShellExecution:void 0;if(o){const y=typeof o.command=="string"?o.command:"",S=o.status==="running"?"running":o.status==="completed"?"success":"error",x=typeof o.output=="string"?o.output:[typeof o.stdout=="string"?o.stdout:"",typeof o.stderr=="string"&&o.stderr?`stderr:
|
|
56
|
-
${o.stderr}`:""].filter(Boolean).join(`
|
|
57
|
-
`);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:"$"}),y]}),e.jsx(Se,{status:S})]}),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:x||"(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:f,images:p}=rs(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(Me,{text:f,label:"Copy message"})}),e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] rounded-lg px-4 py-3 max-w-[85%]",children:[f&&e.jsx("p",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono leading-relaxed whitespace-pre-wrap",children:f}),p.length>0&&e.jsx("div",{className:F("grid gap-2",p.length===1?"grid-cols-1 mt-0":"grid-cols-2 mt-3"),children:p.map((y,S)=>e.jsx("img",{src:y,alt:`attachment-${S+1}`,className:"object-cover w-full max-h-64 rounded-md"},`${y}-${S}`))})]}),e.jsx(as,{})]})}const i=ns(t),n=Ht((c=t.metadata)==null?void 0:c.codeReview),l=Zt((k=t.metadata)==null?void 0:k.structuredOutput);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"assistant",className:F("group flex gap-4 justify-start w-full",s?"p-4":"px-4 pt-0 pb-3"),children:[s?e.jsx(ss,{}):e.jsx("div",{className:"w-8 shrink-0"}),e.jsxs("div",{className:"overflow-hidden flex-1 min-w-0",children:[n?e.jsx(zt,{report:n}):l?e.jsx(es,{report:l}):e.jsx(fs,{message:t}),!l&&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(Me,{text:i,label:"Copy response"})})]})]})}const vs=m.memo(bs);function gs(t,s,a){return Math.max(0,t+(a-s))}function ks(t,s,a){return Math.min(s,Math.max(0,t)+Math.max(0,a))}function js(t,s,a,r){const i=new Map(t.filter(l=>!!l.id).map(l=>[l.id,l])),n=new Set(a);for(const l of s){if(!l.id)continue;const h=i.get(l.id);h!==l&&(!h||!r||r(h)!==r(l))&&n.add(l.id)}return n}function De(t,s){return t?t.querySelector(`[data-chat-message-id="${CSS.escape(s)}"]`):null}function ys({turns:t,viewportRef:s,containerRef:a,onRevealTurn:r}){const i=P(),[n,l]=m.useState(null),[h,d]=m.useState(!1),c=m.useRef(null),k=m.useCallback(()=>{var x;const f=s.current,p=a.current;if(!f||!p||t.length===0)return;const y=f.getBoundingClientRect().top;let S=((x=t[0])==null?void 0:x.id)??null;for(const E of t){const g=De(p,E.id);if(g)if(g.getBoundingClientRect().top-y<=24)S=E.id;else break}l(S)},[t,s,a]);m.useEffect(()=>{const f=s.current;if(!f)return;const p=()=>{c.current===null&&(c.current=window.requestAnimationFrame(()=>{c.current=null,k()}))};return k(),f.addEventListener("scroll",p,{passive:!0}),()=>{f.removeEventListener("scroll",p),c.current!==null&&(window.cancelAnimationFrame(c.current),c.current=null)}},[k,s]);const o=m.useCallback(f=>{const p=()=>{const S=De(a.current,f.id);S&&(S.scrollIntoView({behavior:"smooth",block:"start"}),l(f.id))};r(f.index)?p():window.requestAnimationFrame(()=>window.requestAnimationFrame(p))},[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:()=>d(!0),onMouseLeave:()=>d(!1),onFocusCapture:()=>d(!0),onBlurCapture:f=>{f.currentTarget.contains(f.relatedTarget)||d(!1)},children:e.jsxs("div",{className:"relative flex items-center justify-end",children:[e.jsx("ul",{className:F("flex flex-col items-center gap-2 py-2 transition-opacity",h?"opacity-0":"opacity-100"),"aria-hidden":h,children:t.map(f=>e.jsx("li",{children:e.jsx("span",{className:F("block rounded-full transition-all",f.id===n?"h-2 w-2 bg-[hsl(var(--deck-accent))]":"h-1.5 w-1.5 bg-[hsl(var(--deck-ink-faint))]/40")})},f.id))}),e.jsx("div",{className:F("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",h?"pointer-events-auto translate-x-0 opacity-100":"pointer-events-none translate-x-2 opacity-0"),children:t.map((f,p)=>e.jsxs("button",{type:"button",onClick:()=>o(f),className:F("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors",f.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:F("mt-1 h-1.5 w-1.5 shrink-0 rounded-full",f.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:p+1})}),e.jsx("span",{className:"line-clamp-2 text-[12px] leading-4",children:f.preview})]})]},f.id))})]})})}const Ie=80;function ws(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>s.type==="text").map(s=>s.text).join(" "):""}function Ns(t){const s=ws(t).replace(/\s+/g," ").trim();return s?s.length>Ie?`${s.slice(0,Ie-1)}…`:s:""}function Ss(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=Ns(r.content);i&&s.push({id:r.id,index:a,preview:i})}return s}const pe=120,fe=80,Cs=96;function ee(t){return(t==null?void 0:t.querySelector("[data-radix-scroll-area-viewport]"))??null}function Es(t){return JSON.stringify([t.role,t.content,t.metadata,t.agentContent])}function Ts({messages:t,isLoading:s}){const a=P(),r=m.useRef(null),i=m.useRef(null),n=m.useRef(!0),l=m.useRef(!1),h=m.useRef(t),d=m.useRef(t),c=m.useRef(new Set),k=m.useRef(t.length),o=m.useRef(null),[f,p]=m.useState(pe),[y,S]=m.useState(!1),[x,E]=m.useState(0),g=t.length>0;h.current=t,m.useEffect(()=>{const w=ee(r.current);if(!w||l.current&&!n.current)return;const M=window.requestAnimationFrame(()=>{w.scrollTop=w.scrollHeight,l.current=!0,n.current=!0,c.current=new Set,E(0),S(!1)});return()=>window.cancelAnimationFrame(M)},[t]),m.useEffect(()=>{const w=ee(r.current);if(!w)return;i.current=w;const M=()=>{if(!l.current)return;const B=w.scrollHeight-w.scrollTop-w.clientHeight<=Cs,V=n.current;n.current=B,S(!B),B?(c.current=new Set,E(0)):V&&(d.current=h.current,c.current=new Set,E(0))};return M(),w.addEventListener("scroll",M,{passive:!0}),()=>w.removeEventListener("scroll",M)},[g,s]),m.useEffect(()=>{const w=d.current;if(d.current=t,n.current){c.current.size>0&&(c.current=new Set,E(0));return}const M=js(w,t,c.current,Es);c.current=M,E(M.size)},[t]),m.useEffect(()=>{const w=k.current;k.current=t.length,p(M=>M>=w&&t.length>w?t.length:Math.min(Math.max(M,pe),t.length||pe))},[t.length]);const u=Math.max(t.length-f,0),b=u,A=m.useMemo(()=>t.slice(b),[t,b]),v=m.useMemo(()=>Ss(t),[t]);if(m.useLayoutEffect(()=>{var $;const w=o.current;if(!w)return;const M=ee(r.current);if(o.current=null,!!M){if(($=w.element)!=null&&$.isConnected){const B=w.element.getBoundingClientRect().top-w.viewportTop;M.scrollTop+=B;return}M.scrollTop=gs(w.scrollTop,w.scrollHeight,M.scrollHeight)}},[f]),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(ve,{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(ot,{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((w,M)=>e.jsxs("div",{className:F("flex gap-3",M%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:`${w}%`,animationDelay:`${M*120}ms`}})]},w))})]})});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(ve,{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 C=()=>{const w=ee(r.current);w&&(w.scrollTop=w.scrollHeight,n.current=!0,l.current=!0,c.current=new Set,E(0),S(!1))},D=()=>{var M;const w=ee(r.current);if(w){const $=((M=r.current)==null?void 0:M.querySelector("[data-chat-message-id]"))??null;o.current={element:$,viewportTop:($==null?void 0:$.getBoundingClientRect().top)??0,scrollHeight:w.scrollHeight,scrollTop:w.scrollTop}}p($=>ks($,t.length,fe))},z=w=>w>=b?!0:(p(t.length),!1),O=x===1?a("chat.list.unreadMessage"):a("chat.list.unreadMessages",{count:x});return e.jsxs("div",{ref:r,className:"relative flex-1 min-h-0",children:[e.jsx(lt,{className:"h-full",children:e.jsxs("div",{className:"flex flex-col px-4 pb-4 w-full md:px-6",children:[u>0&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsx("button",{type:"button",onClick:D,"aria-label":a("chat.list.showEarlierWithRemaining",{count:Math.min(u,fe),remaining:u}),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(u,fe)})})}),A.map((w,M)=>{const $=b+M,B=$>0?t[$-1]:null,V=!B||B.role!==w.role||B.role==="user";return e.jsx(vs,{message:w,showAvatar:V},w.id||`msg-${$}`)})]})}),e.jsx(ys,{turns:v,viewportRef:i,containerRef:r,onRevealTurn:z}),y&&e.jsxs("button",{type:"button",onClick:C,"aria-live":"polite","aria-label":x>0?O:a("chat.list.jumpLatest"),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(We,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}),x>0?O:a("chat.list.jumpLatest")]})]})}const Ze=m.memo(Ts),ge=St,ke=Ct,je=Et,de=m.forwardRef(({className:t,sideOffset:s=4,...a},r)=>e.jsx(Je,{ref:r,sideOffset:s,className:F("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}));de.displayName=Je.displayName;const Ms={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 ie(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function As(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 Rs(){var O,w,M,$,B,V,G,K,J,Q,R,U,H,j,L;const t=P(),{locale:s}=ze(),a=N(T=>T.goal),r=N(T=>T.pauseGoal),i=N(T=>T.resumeGoal),n=N(T=>T.editGoal),l=N(T=>T.clearGoal),[h,d]=m.useState(!1),[c,k]=m.useState(!1),[o,f]=m.useState(""),[p,y]=m.useState(null),[S,x]=m.useState(!1);if(m.useEffect(()=>{d(!1),k(!1),f((a==null?void 0:a.objective)??""),x(!1)},[a==null?void 0:a.goalId]),!a)return null;const E=Ms[a.status],g=["active","verifying","paused","blocked"].includes(a.status),u=a.status==="active"||a.status==="verifying",b=a.status==="paused"||a.status==="blocked",A=p!==null,v=async(T,q)=>{y(T);try{await q()}finally{y(null)}},C=()=>{f(a.objective),k(!0),d(!0)},D=async T=>{T.preventDefault();const q=o.trim();if(!q||q===a.objective){k(!1);return}await v("edit",()=>n(q)),k(!1)},z=async()=>{await v("delete",l),x(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(ge,{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,"data-blade-goal-recovery":(O=a.prematureStop)==null?void 0:O.consecutiveCount,"data-blade-goal-recovery-pattern":(w=a.prematureStop)==null?void 0:w.pattern,"data-blade-goal-verification-stall":(M=a.verificationStall)==null?void 0:M.consecutiveCount,"data-blade-goal-frontier-task-list":($=a.executionFrontier)==null?void 0:$.taskListId,"data-blade-goal-frontier-total":(B=a.executionFrontier)==null?void 0:B.total,"data-blade-goal-frontier-completed":(V=a.executionFrontier)==null?void 0:V.completed,"data-blade-goal-frontier-in-progress":(G=a.executionFrontier)==null?void 0:G.inProgress,"data-blade-goal-frontier-pending":(K=a.executionFrontier)==null?void 0:K.pending,"data-blade-goal-frontier-blocked":(J=a.executionFrontier)==null?void 0:J.blocked,"data-blade-goal-frontier-next-task":(R=(Q=a.executionFrontier)==null?void 0:Q.nextTask)==null?void 0:R.id,"data-blade-goal-frontier-digest":(U=a.executionFrontier)==null?void 0:U.digestSha256.slice(0,16),"data-blade-goal-frontier-stall":(H=a.frontierStall)==null?void 0:H.category,"data-blade-goal-frontier-stall-count":(j=a.frontierStall)==null?void 0:j.consecutiveCount,children:[e.jsxs("div",{className:F("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",h&&"rounded-b-none border-b-0"),children:[a.status==="complete"?e.jsx(ct,{className:"h-3.5 w-3.5 shrink-0 text-emerald-500"}):e.jsx(It,{className:F("h-3.5 w-3.5 shrink-0",E.accent)}),e.jsx("span",{className:F("h-1.5 w-1.5 shrink-0 rounded-full",E.dot)}),e.jsx("span",{className:F("shrink-0 text-[10px] font-medium leading-none",E.accent),children:a.status==="verifying"?s==="zh"?"验证中":"Verifying":t(E.labelKey)}),e.jsx("span",{className:"h-3 w-px shrink-0 bg-[hsl(var(--deck-hairline))]"}),e.jsx("button",{type:"button","aria-label":t(h?"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:()=>d(T=>!T),"aria-expanded":h,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:[ie(a.tokensUsed),a.tokenBudget!==void 0&&`/${ie(a.tokenBudget)}`]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[u&&e.jsx(oe,{label:t("goal.action.pause"),disabled:A,onClick:()=>void v("pause",r),children:p==="pause"?e.jsx(_,{className:"animate-spin"}):e.jsx(Tt,{})}),b&&e.jsx(oe,{label:t("goal.action.resume"),disabled:A,onClick:()=>void v("resume",i),children:p==="resume"?e.jsx(_,{className:"animate-spin"}):e.jsx(Mt,{})}),e.jsx(oe,{label:t(g?"goal.action.edit":"goal.action.expand"),disabled:!g&&!h,onClick:g?C:()=>d(T=>!T),children:g?e.jsx(Ke,{}):e.jsx(Nt,{})}),e.jsx(oe,{label:t("goal.action.delete"),disabled:A,destructive:!0,onClick:()=>x(!0),children:e.jsx(ae,{})})]})]}),h&&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:D,children:[e.jsx("textarea",{id:"goal-objective",value:o,onChange:T=>f(T.target.value),onKeyDown:T=>{T.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(Ge,{className:"h-3 w-3"}),t("goal.action.cancel")]}),e.jsxs("button",{type:"submit",disabled:!o.trim()||p==="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:[p==="edit"?e.jsx(_,{className:"h-3 w-3 animate-spin"}):e.jsx(ue,{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(Ft,{className:"h-3 w-3"}),ie(a.tokensUsed),a.tokenBudget!==void 0&&` / ${ie(a.tokenBudget)}`," ",t("goal.metrics.tokens")]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Bt,{className:"h-3 w-3"}),As(a.timeUsedSeconds)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(le,{className:"h-3 w-3"}),a.continuationCount===1?t("goal.metrics.continuationOne",{n:a.continuationCount}):t("goal.metrics.continuationMany",{n:a.continuationCount})]})]}),a.prematureStop&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 font-mono text-[10px] text-amber-700 dark:text-amber-300",children:[e.jsx(le,{className:"h-3 w-3"}),s==="zh"?"恢复提示":"Recovery nudge"," ",a.prematureStop.consecutiveCount," ·"," ",a.prematureStop.pattern.replaceAll("_"," ")]}),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()," ·"," ",((L=a.completionVerification.verifierSessionId)==null?void 0:L.slice(0,12))??"-",a.verificationStall?s==="zh"?` · 重复 ${a.verificationStall.consecutiveCount}/3`:` · repeat ${a.verificationStall.consecutiveCount}/3`:""]}),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(Le,{open:S,onOpenChange:x,children:e.jsxs(Ve,{className:"max-w-[400px] border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsx(Oe,{children:t("goal.dialog.title")}),e.jsx(Ue,{children:t("goal.dialog.description")}),e.jsxs(He,{className:"mt-2",children:[e.jsx("button",{type:"button",onClick:()=>x(!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:p==="delete",onClick:()=>void z(),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:[p==="delete"&&e.jsx(_,{className:"w-3.5 h-3.5 animate-spin"}),t("goal.action.delete")]})]})]})})]})}function oe({label:t,children:s,disabled:a,destructive:r,onClick:i}){return e.jsxs(ke,{children:[e.jsx(je,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":t,disabled:a,onClick:i,className:F("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(de,{side:"top",className:"text-[10px]",children:t})]})}function Fs(){const t=P(),s=N(d=>d.currentSessionRef),a=N(d=>d.sessions),r=N(d=>d.messages),i=m.useMemo(()=>{var c,k,o,f,p;const d=s?(c=dt(a,s))==null?void 0:c.pendingInteraction:void 0;if(d)return d.type;for(let y=r.length-1;y>=0;y-=1){const S=(k=r[y])==null?void 0:k.agentContent;if(((o=S==null?void 0:S.confirmation)==null?void 0:o.status)==="pending")return"permission";if(((f=S==null?void 0:S.question)==null?void 0:f.status)==="pending")return"question";if(((p=S==null?void 0:S.elicitation)==null?void 0:p.status)==="pending")return"elicitation"}return null},[s,r,a]);if(!i)return null;const n=()=>{const d=document.querySelector(`[data-pending-interaction="${i}"]`);d==null||d.scrollIntoView({block:"center",behavior:"smooth"}),window.setTimeout(()=>d==null?void 0:d.focus(),250)},l=i==="question",h=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(ye,{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(l?"interaction.bar.questionTitle":h?"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(l?"interaction.bar.questionHint":h?"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(We,{className:"h-3 w-3"}),t("interaction.bar.review")]})]})}const $s=m.lazy(()=>qe(()=>import("./MarkdownRenderer-3g4TPTeI.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.MarkdownRenderer})));function Ds(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Is(){const t=P(),s=N(r=>r.sideConversation),a=N(r=>r.dismissSideConversation);return s?e.jsx("section",{"aria-label":t("chat.side.title"),"data-blade-side-conversation":!0,"data-status":s.status,className:"shrink-0 border-y border-[hsl(var(--deck-accent)/0.28)] bg-[hsl(var(--deck-accent-soft)/0.42)]",children:e.jsxs("div",{className:"px-4 py-3 md:px-6",children:[e.jsxs("header",{className:"flex min-h-7 items-start gap-2",children:[e.jsx(Dt,{"aria-hidden":!0,className:"mt-0.5 h-4 w-4 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[e.jsx("h2",{className:"font-mono text-[11px] font-semibold uppercase text-[hsl(var(--deck-accent))]",children:t("chat.side.title")}),s.durationMs!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 font-mono text-[9.5px] text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(At,{"aria-hidden":!0,className:"h-3 w-3"}),Ds(s.durationMs)]})]}),e.jsx("p",{className:"mt-0.5 break-words font-mono text-[11px] leading-4 text-[hsl(var(--deck-ink-muted))]",children:s.question})]}),e.jsx("button",{type:"button",onClick:a,"aria-label":t("chat.side.dismiss"),title:t("chat.side.dismiss"),className:"flex h-7 w-7 shrink-0 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:e.jsx(Ge,{"aria-hidden":!0,className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{"aria-live":"polite","aria-busy":s.status==="loading",className:"mt-2 max-h-[min(36vh,320px)] overflow-y-auto border-l-2 border-[hsl(var(--deck-accent)/0.42)] pl-3 pr-1",children:[s.status==="loading"&&e.jsxs("div",{role:"status",className:"flex min-h-9 items-center gap-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(_,{"aria-hidden":!0,className:"h-3.5 w-3.5 animate-spin text-[hsl(var(--deck-accent))]"}),t("chat.side.loading")]}),s.status==="error"&&e.jsxs("div",{role:"alert",className:"flex min-h-9 items-start gap-2 font-mono text-[11px] leading-5 text-red-700 dark:text-red-300",children:[e.jsx(ye,{"aria-hidden":!0,className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"break-words",children:s.error??t("chat.side.failed")})]}),s.status==="completed"&&s.response&&e.jsx(m.Suspense,{fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words font-mono text-[12px] leading-5 text-[hsl(var(--deck-ink))]",children:s.response}),children:e.jsx($s,{content:s.response,className:"text-[12px] leading-5 [&_h1]:text-[14px] [&_h2]:text-[13px] [&_h3]:text-[12px]"})})]})]})}):null}function be(t){return Number.isFinite(t)?Math.max(0,t):0}function Bs(t){const s=be(t.totalInputTokens),a=be(t.cacheReadTokens),r=be(t.cacheWriteTokens),i=Math.min(a,s),n=Math.min(r,Math.max(0,s-i)),l=Math.max(0,s-i-n),h=s>0&&(a>0||r>0);return{totalInputTokens:s,cacheReadTokens:i,cacheWriteTokens:n,uncachedInputTokens:l,...h?{hitRate:i/s}:{}}}function _s(t){return t===void 0||!Number.isFinite(t)?"—":`${Math.round(Math.max(0,Math.min(1,t))*100)}%`}const Ps={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:""},Ls={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"},Y=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 et(){const t=P(),s=N(v=>v.tokenUsage),a=N(v=>v.isStreaming),r=N(v=>v.agentPhase),i=N(v=>v.providerAdmission),n=N(v=>v.providerCircuit),l=N(v=>v.providerRetry),h=N(v=>v.pendingResume),d=N(v=>v.providerStall),c=N(v=>v.actionStationarity),k=N(v=>v.turnRecovery),o=Ps[r]??"",f=(l==null?void 0:l.delayMs)!==void 0?` · ${Math.max(0,Math.ceil(l.delayMs/1e3))}s`:"",p=(h==null?void 0:h.delayMs)!==void 0?` · retry in ${te(h.delayMs)}`:"",y=(k==null?void 0:k.state)==="requires_attention"?t("status.recovery.review"):"",S=(k==null?void 0:k.state)==="requires_attention"?t(k.reason==="interrupted_tool_call"?"status.recovery.interruptedTool":"status.recovery.successfulTool"):"",x=y||(c?`${t(c.phase==="halted"?"status.phase.actionStationarityStopped":"status.phase.actionStationarityRecovering")} · ${c.toolName} · ${c.runLength}/${c.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)}`:l?l.mode==="bounded_foreground"?`Provider · Bounded recovery · ${l.attempt}/${l.maxRetries} · ${te(l.recoveryRemainingMs??0)}`:`Provider · ${t("chat.error.action.retryingTask")} · ${l.attempt}/${l.maxRetries}${f}`:h?`Recovery attempt ${h.attempt}/${h.maxAttempts}${p}`:d?`${t("status.phase.providerStall")} · ${Math.ceil(d.durationMs/1e3)}s / ${Math.ceil(d.timeoutMs/1e3)}s`:o?t(o):""),E=s.maxContextTokens>0?Math.round(s.totalTokens/s.maxContextTokens*100):0,g=Bs(s),u=_s(g.hitRate),b=Math.min(E,100),A=E>95?"danger":E>80?"warn":"safe";return e.jsxs("div",{"data-chat-status-bar":!0,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:F("text-[12px] font-medium",A==="safe"&&"text-[hsl(var(--deck-ink))]",A==="warn"&&"text-amber-600 dark:text-amber-400",A==="danger"&&"text-red-600 dark:text-red-400"),children:Y(s.totalTokens)}),e.jsxs("span",{className:"text-[hsl(var(--deck-ink-faint))]",children:["/ ",Y(s.maxContextTokens)]})]}),s.isDefaultMaxTokens&&e.jsx(ge,{children:e.jsxs(ke,{children:[e.jsx(je,{asChild:!0,children:e.jsx($t,{className:"h-3 w-3 cursor-help text-[hsl(var(--deck-ink-faint))]"})}),e.jsx(de,{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:F("absolute inset-y-0 left-0 transition-[width] duration-300",A==="safe"&&"bg-[hsl(var(--deck-accent))]",A==="warn"&&"bg-amber-500",A==="danger"&&"bg-red-500"),style:{width:`${b}%`}}),e.jsx("div",{className:"flex absolute inset-0 pointer-events-none",children:[25,50,75].map(v=>e.jsx("span",{className:"absolute inset-y-0 w-px bg-[hsl(var(--deck-canvas-veil))]/60",style:{left:`${v}%`}},v))})]}),e.jsxs("span",{className:F("w-10 text-right tabular-nums text-[hsl(var(--deck-ink-faint))]",A==="warn"&&"text-amber-600 dark:text-amber-400",A==="danger"&&"text-red-600 dark:text-red-400"),children:[E,"%"]})]}),e.jsx(ge,{children:e.jsxs(ke,{children:[e.jsx(je,{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")} ${u}`,children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.cache")}),e.jsx("span",{className:F("tabular-nums",g.hitRate===void 0?"text-[hsl(var(--deck-ink-faint))]":"font-medium text-[hsl(var(--deck-accent))]"),children:u})]})}),e.jsx(de,{side:"top",className:"max-w-[280px]",children:g.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:Y(g.cacheReadTokens),write:Y(g.cacheWriteTokens),uncached:Y(g.uncachedInputTokens)})}),s.cacheBreak&&e.jsx("p",{className:"text-[hsl(var(--deck-accent))]",children:t("status.cacheBreak",{reason:t(Ls[s.cacheBreak.reason]??"status.cacheBreak.server"),previous:Y(s.cacheBreak.previousCacheReadTokens),current:Y(s.cacheBreak.cacheReadTokens)})})]})})]})}),e.jsx("div",{className:"flex-1"}),(y||a&&x)&&e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:F("shrink-0",y?"h-2 w-2 rounded-sm bg-amber-500":"deck-pulse-dot")}),e.jsxs("span",{className:F("truncate",y?"text-amber-600 dark:text-amber-400":"text-[hsl(var(--deck-accent))]"),children:[x,S?e.jsxs("span",{className:"hidden sm:inline",children:[" · ",S]}):null]})]})]})}function Vs(){const{locale:t}=ze(),s=ut(u=>u.agentTeamsEnabled),a=N(u=>u.teams),r=N(u=>u.currentSessionRef),i=N(u=>u.loadTeams),[n,l]=m.useState({}),[h,d]=m.useState({}),[c,k]=m.useState({}),[o,f]=m.useState(null),[p,y]=m.useState(null),[S,x]=m.useState(null);if(m.useEffect(()=>{i(r??void 0)},[s,r,i]),!s||!r||a.length===0)return null;const E=async u=>{var A;const b=(A=c[u])==null?void 0:A.trim();if(!(!b||o)){f(u),x(null);try{await Ee.sendMessage(r,u,h[u]??"*",b),k(v=>({...v,[u]:""})),await i(r)}catch(v){x(v instanceof Error?v.message:I(t,"actionFailed"))}finally{f(null)}}},g=async u=>{if(!p){y(u),x(null);try{await Ee.delete(r,u),await i(r)}catch(b){x(b instanceof Error?b.message:I(t,"actionFailed"))}finally{y(null)}}};return e.jsxs("section",{"aria-label":I(t,"title"),"data-blade-team-panel":!0,className:"shrink-0 border-y border-emerald-300/50 bg-emerald-50/55 dark:border-emerald-800/55 dark:bg-emerald-950/20",children:[S&&e.jsx("div",{role:"alert",className:"border-b border-red-200 bg-red-50 px-4 py-2 font-mono text-[10px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300 md:px-6",children:S}),a.filter(u=>u.status!=="deleted").map(u=>{var v;const b=n[u.name]??u.status==="running",A=u.tasks.filter(C=>C.status==="completed").length;return e.jsxs("div",{className:"border-b border-emerald-200/40 last:border-0 dark:border-emerald-900/40",children:[e.jsxs("div",{className:"flex min-h-11 items-center gap-2 px-4 py-2 md:px-6",children:[e.jsx("button",{type:"button",onClick:()=>l(C=>({...C,[u.name]:!b})),"aria-label":b?I(t,"collapse"):I(t,"expand"),className:"flex h-7 w-7 items-center justify-center rounded-md text-emerald-700 hover:bg-emerald-100 dark:text-emerald-300 dark:hover:bg-emerald-900/50",children:b?e.jsx(re,{className:"h-4 w-4"}):e.jsx(ne,{className:"h-4 w-4"})}),e.jsx(_t,{className:"h-4 w-4 shrink-0 text-emerald-700 dark:text-emerald-300"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[e.jsx("h2",{className:"truncate font-mono text-[11px] font-semibold uppercase text-emerald-800 dark:text-emerald-200",children:u.name}),e.jsxs("span",{className:"font-mono text-[9.5px] text-[hsl(var(--deck-ink-faint))]",children:[u.status," · ",u.members.length-1," ",I(t,"members")," · ",A,"/",u.tasks.length," ",I(t,"tasks")]})]}),u.description&&e.jsx("p",{className:"truncate font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:u.description})]}),e.jsx("button",{type:"button",onClick:()=>void g(u.name),disabled:p===u.name,"aria-label":I(t,"delete"),title:I(t,"delete"),className:"flex h-7 w-7 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] hover:bg-red-50 hover:text-red-600 disabled:opacity-40 dark:hover:bg-red-950/40",children:e.jsx(ae,{className:"h-3.5 w-3.5"})})]}),b&&e.jsxs("div",{className:"max-h-[min(40vh,360px)] overflow-y-auto border-t border-emerald-200/40 px-4 py-3 md:px-6 dark:border-emerald-900/40",children:[e.jsxs("div",{className:"grid gap-x-6 gap-y-2 lg:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1 font-mono text-[9.5px] font-semibold uppercase text-[hsl(var(--deck-ink-faint))]",children:I(t,"members")}),u.members.map(C=>e.jsxs("div",{className:"flex min-h-7 items-center gap-2 border-b border-[hsl(var(--deck-hairline)/0.55)] py-1 last:border-0",children:[e.jsx("span",{"aria-label":C.status,className:`h-1.5 w-1.5 shrink-0 rounded-full ${C.status==="running"?"bg-emerald-500":C.status==="completed"||C.status==="leader"?"bg-sky-500":C.status==="failed"?"bg-red-500":"bg-zinc-400"}`}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-[hsl(var(--deck-ink))]",children:C.name}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:C.subagentType}),C.worktreePath&&e.jsx(_e,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]","aria-label":I(t,"worktree")})]},C.id))]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1 font-mono text-[9.5px] font-semibold uppercase text-[hsl(var(--deck-ink-faint))]",children:I(t,"tasks")}),u.tasks.length===0?e.jsx("p",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:I(t,"noTasks")}):u.tasks.map(C=>e.jsxs("div",{className:"flex min-h-7 items-center gap-2 border-b border-[hsl(var(--deck-hairline)/0.55)] py-1 last:border-0",children:[e.jsxs("span",{className:"w-5 shrink-0 font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:["#",C.id]}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-[hsl(var(--deck-ink))]",children:C.subject}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:C.status})]},C.id))]})]}),u.peerMessagingEnabled&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 border-t border-emerald-200/40 pt-3 dark:border-emerald-900/40",children:[e.jsxs("select",{"aria-label":I(t,"recipient"),value:h[u.name]??"*",onChange:C=>d(D=>({...D,[u.name]:C.target.value})),className:"h-8 max-w-32 rounded-md border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))] px-2 font-mono text-[10px]",children:[e.jsx("option",{value:"*",children:I(t,"broadcast")}),u.members.filter(C=>C.status!=="leader").map(C=>e.jsx("option",{value:C.name,children:C.name},C.id))]}),e.jsx("input",{value:c[u.name]??"",onChange:C=>k(D=>({...D,[u.name]:C.target.value})),onKeyDown:C=>{C.key==="Enter"&&E(u.name)},placeholder:I(t,"messagePlaceholder"),className:"h-8 min-w-0 flex-1 rounded-md border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))] px-2 font-mono text-[10.5px] outline-none focus:border-emerald-500"}),e.jsx("button",{type:"button",onClick:()=>void E(u.name),disabled:!((v=c[u.name])!=null&&v.trim())||o===u.name,"aria-label":I(t,"send"),title:I(t,"send"),className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-emerald-700 text-white hover:bg-emerald-800 disabled:opacity-40 dark:bg-emerald-600",children:e.jsx(Pe,{className:"h-3.5 w-3.5"})})]})]})]},u.name)})]})}function Os(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(`
|
|
58
|
-
`),r=s.content.filter(i=>i.type==="image_url").map((i,n)=>{var h;const l=((h=i.image_url.url.match(/^data:([^;,]+)[;,]/))==null?void 0:h[1])??"application/octet-stream";return{id:`recovery-${s.id}-${n}`,name:`attachment-${n+1}`,mimeType:l,dataUrl:i.image_url.url}});return{content:a,attachments:r}}function Us({messages:t,isLoading:s,isStreaming:a,isStopping:r,errorMessage:i}){const n=P(),[l,h]=m.useState(!1),d=n(i?"status.phase.error":r?"chat.input.action.stopping":a?"status.phase.running":"preview.files.status.ready");return e.jsxs("details",{"data-preview-status-disclosure":!0,open:l,onToggle:c=>h(c.currentTarget.open),className:"group hidden",children:[e.jsxs("summary",{className:"flex h-9 cursor-pointer list-none items-center gap-2 px-3 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[hsl(var(--deck-accent))]",children:[a&&e.jsx("span",{className:"deck-pulse-dot"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:d}),e.jsx(ne,{className:"h-3.5 w-3.5 shrink-0 transition-transform group-open:rotate-90"})]}),l&&e.jsxs("div",{"data-preview-activity-details":!0,className:"flex h-[min(44vh,420px)] min-h-0 flex-col border-t border-[hsl(var(--deck-hairline))]",children:[i&&e.jsx("div",{role:"alert",className:"border-b border-red-200/60 bg-red-50/80 px-3 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300",children:i}),e.jsx(Ze,{messages:t,isLoading:s}),e.jsx(et,{})]})]})}function Hs(){var H;const t=P(),s=N(j=>j.messages),a=N(j=>j.currentSessionRef),r=N(j=>j.isStreaming),i=N(j=>j.isStopping),n=N(j=>j.sessionEventConnectionState),l=N(j=>j.pendingSteeringCount),h=N(j=>j.pendingInputDelivery),d=N(j=>j.recoveredSteeringCount),c=N(j=>j.isLoading),k=N(j=>j.error),o=N(j=>j.errorContext),f=N(j=>j.sessions),p=N(j=>j.sendMessage),y=N(j=>j.abortSession),S=N(j=>j.retryTask),x=N(j=>j.retryingTaskKeys),E=we(j=>j.openSettings),g=N(j=>j.reconnectSessionEvents),u=N(j=>j.clearError),[b,A]=m.useState(null),v=a?f.find(j=>j.sessionId===a.sessionId&&j.projectPath===a.projectPath):void 0,C=!!k&&((o==null?void 0:o.kind)==="navigation"||!(o!=null&&o.sessionRef)||Be(o.sessionRef,a)),D=(o==null?void 0:o.failureCode)??((H=v==null?void 0:v.taskFailure)==null?void 0:H.code),z=((o==null?void 0:o.kind)==="execution"||o!=null&&o.failureCode)&&D?t(kt(D)):k==="queue_full"?t("chat.error.queueFull"):k==="turn_unavailable"||k==="turn_active"?t("chat.error.turnChanged"):k,O=n==="connecting"||n==="reconnecting",w=r&&n!=="connected",M=a?`session:${se(a)}`:"session:temporary",$=m.useMemo(()=>Os(s),[s]),B=a?se(a):"temporary-session",V=!!(a&&(v!=null&&v.taskRetryAvailable)&&(!D||jt(D)))&&((o==null?void 0:o.kind)==="execution"||(o==null?void 0:o.kind)==="task_action"),G=(o==null?void 0:o.kind)==="execution"&&(D==="authentication"||D==="permission"||D==="model_unavailable"),K=a?x.includes(se(a)):!1;m.useEffect(()=>{A(null)},[B]);const J=async j=>p({content:j.content,modelId:j.modelId,reasoningEffort:j.reasoningEffort,serviceTier:j.serviceTier,responseVerbosity:j.responseVerbosity,communicationStyle:j.communicationStyle,...j.outputSchema?{outputSchema:j.outputSchema}:{},attachments:j.attachments.map(L=>({type:"image",content:L.dataUrl,mimeType:L.mimeType,name:L.name}))}),Q=()=>y(),R=async()=>{if(G){u(),E("models");return}if(V&&a){u(),await S(a).catch(()=>{});return}if((o==null?void 0:o.kind)==="execution"&&$){A({...$,revision:Date.now()}),u();return}u(),requestAnimationFrame(()=>pt())},U=V?t(K?"chat.error.action.retryingTask":"chat.error.action.retryTask"):G?t("chat.error.action.checkModels"):(o==null?void 0:o.kind)==="execution"&&$?t("chat.error.action.editResend"):(o==null?void 0:o.kind)==="submission"?t("chat.error.action.returnDraft"):null;return e.jsxs("div",{"data-chat-view":!0,className:"flex h-full flex-col bg-[hsl(var(--deck-canvas))]",children:[e.jsxs("div",{"data-chat-history":!0,className:"contents",children:[C&&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(ye,{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")})," ",z]}),U&&e.jsxs("button",{type:"button",onClick:()=>void R(),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:[V?K?e.jsx(_,{className:"h-3 w-3 animate-spin"}):e.jsx(le,{className:"h-3 w-3"}):e.jsx(Ke,{className:"h-3 w-3"}),U]}),e.jsx("button",{type:"button",onClick:u,"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:"✕"})]}),(O||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:[O?e.jsx(_,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):e.jsx(mt,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 flex-1",children:t(O?"chat.connection.reconnecting":"chat.connection.offline")}),n==="offline"&&e.jsxs("button",{type:"button",onClick:()=>void g().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(ht,{className:"h-3 w-3"}),t("chat.connection.retry")]})]}),e.jsx(Pt,{}),e.jsx(Ze,{messages:s,isLoading:c},a?se(a):"temporary-session"),e.jsx(Vs,{}),e.jsx(Is,{})]}),e.jsxs("div",{"data-chat-composer-dock":!0,className:"contents",children:[e.jsx(Us,{messages:s,isLoading:c,isStreaming:r,isStopping:i,errorMessage:C?z:null},B),e.jsx(Fs,{}),e.jsx(Rs,{}),e.jsx(xt,{draftKey:M,draft:b==null?void 0:b.content,draftAttachments:b==null?void 0:b.attachments,draftRevision:b==null?void 0:b.revision,onSend:J,onAbort:Q,disabled:c||w,isStreaming:r,isStopping:i,pendingSteeringCount:l,pendingInputDelivery:h,recoveredSteeringCount:d,workspacePath:a==null?void 0:a.projectPath},M),e.jsx("div",{"data-chat-primary-status":!0,className:"contents",children:e.jsx(et,{})})]})]})}const ta=Object.freeze(Object.defineProperty({__proto__:null,ChatView:Hs},Symbol.toStringTag,{value:"Module"}));export{Qe as C,ta as a};
|