blade-code 0.10.46 → 0.10.63
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-0d1197b9.js +1 -0
- package/dist/chunk-0ft3egjr.js +710 -0
- package/dist/chunk-0jxh2zq5.js +5 -0
- package/dist/{chunk-4dthhzfe.js → chunk-1hb0rt7n.js} +1 -1
- package/dist/{chunk-26wse17p.js → chunk-1jc7d3nt.js} +2 -2
- package/dist/{chunk-sqd5ge5s.js → chunk-2xbmkyb2.js} +1 -1
- package/dist/chunk-2xsrqsk9.js +44 -0
- package/dist/chunk-2yws8pqt.js +1 -0
- package/dist/{chunk-0qsssahq.js → chunk-2z3xe3rw.js} +1 -1
- package/dist/{chunk-fk4wbmv6.js → chunk-3tednchw.js} +2 -2
- package/dist/chunk-5sk6v1et.js +10 -0
- package/dist/{chunk-qp2z1r7y.js → chunk-69rc9hw6.js} +1 -1
- package/dist/chunk-6fdvffcc.js +2 -0
- package/dist/{chunk-c9s4n31b.js → chunk-6g3qzz9h.js} +1 -1
- package/dist/{chunk-2eddqgnh.js → chunk-6rg6mngq.js} +1 -1
- package/dist/{chunk-8y3skwtt.js → chunk-6x1g554w.js} +1 -1
- package/dist/{chunk-m8ss9rmx.js → chunk-7b467h8k.js} +1 -1
- package/dist/{chunk-8vtyatd6.js → chunk-83wm4akj.js} +1 -1
- package/dist/chunk-86gc2mqb.js +1 -0
- package/dist/{chunk-cxzx7j0p.js → chunk-87jz5600.js} +1 -1
- package/dist/{chunk-1atpfmpe.js → chunk-8an49nbn.js} +53 -53
- package/dist/chunk-8b1ehxzh.js +45 -0
- package/dist/{chunk-yk9pxkc1.js → chunk-8ekk8pa7.js} +1 -1
- package/dist/{chunk-xes0szvj.js → chunk-94d8hhqc.js} +2 -2
- package/dist/{chunk-s5205dnv.js → chunk-95hvy6dn.js} +2 -2
- package/dist/chunk-9c31jemm.js +1 -0
- package/dist/chunk-9kmtcgm6.js +2 -0
- package/dist/{chunk-mrsc4a55.js → chunk-9r0yebs1.js} +1 -1
- package/dist/{chunk-szdcprq7.js → chunk-9rjaem5f.js} +2 -2
- package/dist/{chunk-t4y3h47y.js → chunk-adz2756v.js} +2 -2
- package/dist/{chunk-ssymrsyx.js → chunk-atqnan6x.js} +2 -2
- package/dist/{chunk-hfrcwkc8.js → chunk-av10vmxk.js} +1 -1
- package/dist/{chunk-9rrced3b.js → chunk-b19f55s7.js} +1 -1
- package/dist/{chunk-q78s028m.js → chunk-cm9mph7j.js} +1 -1
- package/dist/chunk-cq77ah56.js +6 -0
- package/dist/{chunk-qmxfkkgn.js → chunk-cr154zrx.js} +2 -2
- package/dist/chunk-cx05we7e.js +1 -0
- package/dist/{chunk-qb0sqh29.js → chunk-cz68x56m.js} +2 -2
- package/dist/{chunk-tpa75y39.js → chunk-d1t91jgz.js} +1 -1
- package/dist/{chunk-2yvte5a7.js → chunk-detkh4dd.js} +1 -1
- package/dist/chunk-dpzx4mgb.js +1 -0
- package/dist/chunk-dq9ya06q.js +1 -0
- package/dist/{chunk-f4sp074f.js → chunk-eeac8teg.js} +1 -1
- package/dist/chunk-ej6h16ae.js +3 -0
- package/dist/{chunk-hcm55r3d.js → chunk-fp1h8wdh.js} +1 -1
- package/dist/{chunk-ecf8dh3c.js → chunk-fp2fh7cn.js} +16 -16
- package/dist/chunk-g0n88mhg.js +1 -0
- package/dist/{chunk-j66r48pz.js → chunk-hpehkz2x.js} +2 -2
- package/dist/{chunk-jmksywff.js → chunk-j8akkmc8.js} +1 -1
- package/dist/{chunk-7fqsgdee.js → chunk-j9snkjpe.js} +2 -2
- package/dist/{chunk-v9tzhe90.js → chunk-jk8bqc5b.js} +2 -2
- package/dist/{chunk-67zpsrst.js → chunk-k4ermznt.js} +1 -1
- package/dist/chunk-khkhsaan.js +2 -0
- package/dist/{chunk-kfpzrmq7.js → chunk-kjvntyr5.js} +1 -1
- package/dist/{chunk-4qvna4m2.js → chunk-kxrss9sv.js} +1 -1
- package/dist/chunk-m0t7g2vg.js +1 -0
- package/dist/{chunk-8kzdhgys.js → chunk-ng0tkmrn.js} +2 -2
- package/dist/chunk-nnbfk60b.js +1 -0
- package/dist/chunk-nnc1abkf.js +1 -0
- package/dist/{chunk-2yjm55cb.js → chunk-pdrqnywp.js} +1 -1
- package/dist/chunk-q7pznpyh.js +1 -0
- package/dist/{chunk-y6tkxqjx.js → chunk-qs4erqd0.js} +2 -2
- package/dist/chunk-rwy763tf.js +160 -0
- package/dist/chunk-tf4p1778.js +1 -0
- package/dist/{chunk-5vbrcvxg.js → chunk-ttkwrqtp.js} +1 -1
- package/dist/chunk-vhckw5e7.js +1 -0
- package/dist/{chunk-yrd794kb.js → chunk-w4sp56dn.js} +1 -1
- package/dist/{chunk-56qew7w0.js → chunk-wwsg165p.js} +2 -2
- package/dist/{chunk-wwvb6znp.js → chunk-wy4pn9sk.js} +1 -1
- package/dist/chunk-xsx1av03.js +1621 -0
- package/dist/{chunk-fhnkyqfb.js → chunk-y8r2knxm.js} +2 -2
- package/dist/chunk-yagna3ws.js +8 -0
- package/dist/web/assets/ChatView-B6IO9U-D.js +18 -0
- package/dist/web/assets/{CodeBlockHighlighter-Bb3gIeQv.js → CodeBlockHighlighter-DVGtFQgX.js} +1 -1
- package/dist/web/assets/{FilePreview-BXg9VaTv.js → FilePreview-C-8_o7yw.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-vxpqGt4L.js → MarkdownRenderer-D04IKQhF.js} +3 -3
- package/dist/web/assets/{SettingsModal-4L1nPkh0.js → SettingsModal-BMoZLVEe.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-DKSqTLK1.js → TaskSwitcher-CIuCEbvU.js} +1 -1
- package/dist/web/assets/{TerminalPanel-Bv9PDclr.js → TerminalPanel-fTk9D5hU.js} +1 -1
- package/dist/web/assets/{index-Bz4W1-8a.js → index-CO5sUiJn.js} +6 -6
- package/dist/web/assets/index-Dxdnbd79.css +1 -0
- package/dist/web/assets/{session-events-DJh6SZcl.js → session-events-BvtUOaNG.js} +8 -8
- package/dist/web/index.html +3 -3
- package/package.json +12 -2
- package/dist/chunk-3y784b9c.js +0 -1
- package/dist/chunk-54d7545y.js +0 -1
- package/dist/chunk-6cx4t8r6.js +0 -1
- package/dist/chunk-6h28xs47.js +0 -8
- package/dist/chunk-7qpbtnsa.js +0 -6
- package/dist/chunk-7sna3js9.js +0 -2
- package/dist/chunk-807x1cw8.js +0 -2
- package/dist/chunk-9mnbnyrc.js +0 -1
- package/dist/chunk-aarwre5y.js +0 -1
- package/dist/chunk-bvf9syb2.js +0 -3
- package/dist/chunk-cyw6cpac.js +0 -44
- package/dist/chunk-egczvfsv.js +0 -5
- package/dist/chunk-fer18bbe.js +0 -1
- package/dist/chunk-fz91aw1w.js +0 -10
- package/dist/chunk-j7edwwg1.js +0 -2
- package/dist/chunk-mqmf40p2.js +0 -1
- package/dist/chunk-n5dkq98k.js +0 -160
- package/dist/chunk-qbvm38ba.js +0 -1
- package/dist/chunk-sh58bey1.js +0 -1
- package/dist/chunk-sjtbp01y.js +0 -710
- package/dist/chunk-sztrmhgd.js +0 -1
- package/dist/chunk-v6ydjg9c.js +0 -1
- package/dist/chunk-vhamhbej.js +0 -1612
- package/dist/chunk-vhxtzacr.js +0 -1
- package/dist/chunk-yha9fpc7.js +0 -1
- package/dist/chunk-yvyqhw5q.js +0 -45
- package/dist/chunk-z1aqe7ms.js +0 -1
- package/dist/web/assets/ChatView-CyxiCTbL.js +0 -18
- package/dist/web/assets/index-7zaeanZL.css +0 -1
package/dist/chunk-vhxtzacr.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Xc as a,Yc as b}from"./chunk-s5205dnv.js";import"./chunk-807x1cw8.js";import"./chunk-hfrcwkc8.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-yha9fpc7.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ac as g,uc as a,vc as b,wc as c,xc as d,yc as e,zc as f}from"./chunk-t4y3h47y.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import"./chunk-qp2z1r7y.js";import"./chunk-2yvte5a7.js";import"./chunk-cxzx7j0p.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-fhnkyqfb.js";import"./chunk-hcm55r3d.js";import"./chunk-807x1cw8.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
package/dist/chunk-yvyqhw5q.js
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import{Ne as YO}from"./chunk-cxzx7j0p.js";import{Tf as qO,Vf as S,Yf as y}from"./chunk-m8ss9rmx.js";import{dg as K}from"./chunk-kfpzrmq7.js";import{Eg as XO}from"./chunk-fhnkyqfb.js";import{Yg as n}from"./chunk-q78s028m.js";import{fh as r}from"./chunk-qb0sqh29.js";import{hh as w}from"./chunk-hfrcwkc8.js";var N;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(N||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import _ from"node:path";import{nanoid as z}from"nanoid";var C={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import jO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import h from"node:path";import{Mutex as WO}from"async-mutex";import SO from"write-file-atomic";var k=1,GO=1048576,VO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function LO(O){let q={};for(let Q of Object.values(N)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(N))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(LO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new WO;filePath;constructor(O=h.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let J;try{J=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let W=J.projects[Z];if(!W)return{...X,state:"untrusted"};return{...X,state:W.digest===$?"trusted":"modified",trustedDigest:W.digest,trustedAt:W.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:k,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>GO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==k)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!h.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!VO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:k,projects:Z}}async writeStore(O){let q=h.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await SO(this.filePath,`${JSON.stringify(O,null,2)}
|
|
2
|
-
`,{mode:384}),await j.chmod(this.filePath,384)}}class T extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function e(O,q={}){let Q;try{Q=new URL(O)}catch{throw new T(`Invalid URL: ${O}`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw new T(`Only http/https supported, got: ${Q.protocol}`);let Z=Q.hostname.toLowerCase();if(zO(Z,q.allowedHosts))return;if(Q.protocol==="http:"&&!q.allowHttp)throw new T(`HTTP (non-TLS) blocked for ${Z}; use https:// or add to allowedHosts`);if(BO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(AO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function zO(O,q){if(!q||q.length===0)return!1;return q.some((Q)=>{let Z=Q.toLowerCase();if(Z===O)return!0;if(Z.startsWith("*.")){let Y=Z.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function BO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function AO(O){let q=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!q)return!1;let[Q,Z]=q.slice(1).map(Number);if(Q===10)return!0;if(Q===172&&Z>=16&&Z<=31)return!0;if(Q===192&&Z===168)return!0;if(Q===169&&Z===254)return!0;return!1}function OO(O){if(!O)return{};let q={};for(let[Q,Z]of Object.entries(O))q[Q]=Z.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,$)=>{return process.env[$]??`\${${$}}`});return q}var KO=S.Object({hookEventName:S.Literal("PreToolUse"),permissionDecision:S.Optional(S.Enum(m)),permissionDecisionReason:S.Optional(S.String()),updatedInput:S.Optional(S.Record(S.String(),S.Unknown()))}),PO=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),_O=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),UO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),bO=S.Object({hookEventName:S.Literal("PermissionRequest"),permissionDecision:S.Optional(y(["approve","deny","ask"])),permissionDecisionReason:S.Optional(S.String())}),QO=S.Record(S.String(),S.Union([S.String(),S.Number(),S.Boolean(),S.Array(S.String(),{maxItems:100})]),{maxProperties:32}),NO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),MO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),wO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),CO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),EO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([KO,PO,_O,UO,bO,NO,MO,TO,wO,CO])),suppressOutput:S.Optional(S.Boolean())});function ZO(O){return qO(EO,O)}class p{parse(O,q,Q){if(O.timedOut){let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let Z=this.tryParseJSON(O.stdout);if(Z){let Y=ZO(Z);if(!Y.success){let X="error"in Y?Y.error.message:"Unknown validation error",J=Q?.failureBehavior||"ignore",W=`Invalid hook output JSON: ${X}`;if(J==="deny")return{success:!1,blocking:!0,error:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(J==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${W}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let $=Y.data;if($.decision?.behavior==="block")return{success:!1,blocking:!0,error:$.systemMessage||"Hook blocked execution",output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};if($.decision?.behavior==="async")return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}return this.parseByExitCode(O,q,Q)}parseByExitCode(O,q,Q){let Z=O.exitCode;switch(Z){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 124:{let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}default:{let Y=Q?.failureBehavior||"ignore",$=O.stderr||O.stdout||`Hook failed with exit code ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${$}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}}}tryParseJSON(O){try{let q=O.trim();if(!q)return null;let Q=q.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Q)return null;return JSON.parse(Q[1])}catch{return null}}}class l{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let q=this.maxSize-this.content.length;this.content+=O.substring(0,q)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class u{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,q,Q,Z){let Y=JSON.stringify(q);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let $=this.createSafeEnv(q,Q.environment),{child:X,processTree:J}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),W=new l(this.MAX_STDOUT_SIZE),G=new l(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{W.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await J.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,R)=>{let F=!1,V=!1,B,P=()=>{return B??=J.terminate(),B},b=null,H=()=>{if(b&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",b),b=null},I=setTimeout(()=>{F=!0,P()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(I),H(),F)await P();L({stdout:W.getContent(),stderr:G.getContent(),exitCode:F?124:f??1,timedOut:F})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(I),H(),R(f)}),Q.abortSignal){if(b=()=>{if(V)return;V=!0,clearTimeout(I),H(),P().then(()=>{L({stdout:W.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",b),Q.abortSignal.aborted)b()}})}createSafeEnv(O,q={}){return{...q,PATH:q.PATH??process.env.PATH??"",HOME:q.HOME??process.env.HOME??"",USER:q.USER??process.env.USER??"",SHELL:q.SHELL??process.env.SHELL??"/bin/sh",BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:""}}}var $O=XO("Execution"),DO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',Elicitation:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',ElicitationResult:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class x{processExecutor=new u;outputParser=new p;chatServiceCache=new Map;sessionModelResources=new Map;sessionEnvironments=new Map;trustWarnings=new Set;bindSessionModelResources(O,q,Q){for(let Z of q)this.sessionModelResources.set(this.sessionResourceKey(O,Z),Q),this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q.config.env)}bindSessionEnvironment(O,q,Q){for(let Z of q)this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q)}async unbindSessionModelResources(O,q){for(let Q of q){let Z=this.sessionResourceKey(O,Q);this.sessionModelResources.delete(Z),this.sessionEnvironments.delete(Z);let Y=`${Z}\x00`;for(let[$,X]of this.chatServiceCache){if(!$.startsWith(Y))continue;this.chatServiceCache.delete($),await X.dispose?.()}}}async executePreToolHooks(O,q,Q){if(O.length===0)return{decision:"allow"};let Z="tool_input"in q?q.tool_input:{},Y=[];for(let $ of O)try{let X={...q,...Z&&{tool_input:Z}},J=await this.executeHook($,X,Q);if(!J.success){if(J.blocking)return{decision:"deny",reason:J.error};if(J.needsConfirmation)return{decision:"ask",reason:J.warning||J.error};if(J.warning)Y.push(J.warning);continue}let W=J.output?.hookSpecificOutput;if(W&&"permissionDecision"in W){switch(W.permissionDecision){case"deny":return{decision:"deny",reason:W.permissionDecisionReason};case"ask":return{decision:"ask",reason:W.permissionDecisionReason};case"allow":break}if("updatedInput"in W&&W.updatedInput)Z={...Z,...W.updatedInput}}}catch(X){let J=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${J}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:J};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${J}. Continue?`}}return{decision:"allow",modifiedInput:Z,warning:Y.length>0?Y.join(`
|
|
3
|
-
`):void 0}}async executePostToolHooks(O,q,Q){if(O.length===0)return{};let Z=Q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,q,Q,Z),$=[],X=void 0,J=[];for(let W of Y){if(!W.success&&W.warning){J.push(W.warning);continue}let G=W.output?.hookSpecificOutput;if(G&&"additionalContext"in G){if(G.additionalContext)$.push(G.additionalContext);if("updatedOutput"in G&&G.updatedOutput!==void 0)X=G.updatedOutput}}return{additionalContext:$.length>0?$.join(`
|
|
4
|
-
|
|
5
|
-
`):void 0,modifiedOutput:X,warning:J.length>0?J.join(`
|
|
6
|
-
`):void 0}}async executeStopHooks(O,q,Q){if(O.length===0)return{shouldStop:!0};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"continue"in X&&X.continue===!1)return{shouldStop:!1,continueReason:X.continueReason,warning:Z.length>0?Z.join(`
|
|
7
|
-
`):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{shouldStop:!0,warning:Z.length>0?Z.join(`
|
|
8
|
-
`):void 0}}async executeSubagentStopHooks(O,q,Q){if(O.length===0)return{shouldStop:!0};let Z=[],Y=[];for(let $ of O)try{let X=await this.executeHook($,q,Q);if(!X.success){if(X.warning)Z.push(X.warning);continue}let J=X.output?.hookSpecificOutput;if(J&&"continue"in J){if(J.continue===!1)return{shouldStop:!1,continueReason:J.continueReason,warning:Z.length>0?Z.join(`
|
|
9
|
-
`):void 0};if("additionalContext"in J&&J.additionalContext)Y.push(J.additionalContext)}}catch(X){let J=X instanceof Error?X.message:String(X);Z.push(`Hook failed: ${J}`)}return{shouldStop:!0,additionalContext:Y.length>0?Y.join(`
|
|
10
|
-
|
|
11
|
-
`):void 0,warning:Z.length>0?Z.join(`
|
|
12
|
-
`):void 0}}async executePermissionRequestHooks(O,q,Q){if(O.length===0)return{decision:"ask"};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"permissionDecision"in X){let J=X.permissionDecision;if(J==="approve"||J==="deny")return{decision:J,reason:X.permissionDecisionReason,warning:Z.length>0?Z.join(`
|
|
13
|
-
`):void 0}}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{decision:"ask",warning:Z.length>0?Z.join(`
|
|
14
|
-
`):void 0}}async executeElicitationHooks(O,q,Q){if(O.length===0)return{};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.blocking)return{blockedReason:$.error??"Elicitation blocked by hook",warning:Z.length>0?Z.join(`
|
|
15
|
-
`):void 0};if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"action"in X&&(X.action==="accept"||X.action==="decline"||X.action==="cancel"))return{response:{action:X.action,..."content"in X&&X.content?{content:X.content}:{}},warning:Z.length>0?Z.join(`
|
|
16
|
-
`):void 0}}catch($){Z.push(`Hook failed: ${$ instanceof Error?$.message:String($)}`)}return{warning:Z.length>0?Z.join(`
|
|
17
|
-
`):void 0}}async executeUserPromptSubmitHooks(O,q,Q){if(O.length===0)return{proceed:!0};let Z=[],Y=[],$;for(let X of O)try{let J=await this.executeHook(X,q,Q);if(!J.success){if(J.blocking)return{proceed:!1,warning:J.error};if(J.warning)Z.push(J.warning);continue}if(J.stdout&&J.stdout.trim())Y.push(J.stdout.trim());let W=J.output?.hookSpecificOutput;if(W&&"updatedPrompt"in W){if(W.updatedPrompt)$=W.updatedPrompt;if(W.contextInjection)Y.push(W.contextInjection)}}catch(J){let W=J instanceof Error?J.message:String(J);Z.push(`Hook failed: ${W}`)}return{proceed:!0,updatedPrompt:$,contextInjection:Y.length>0?Y.join(`
|
|
18
|
-
|
|
19
|
-
`):void 0,warning:Z.length>0?Z.join(`
|
|
20
|
-
`):void 0}}async executeSessionStartHooks(O,q,Q){if(O.length===0)return{proceed:!0};let Z=[],Y={};for(let $ of O)try{let X=await this.executeHook($,q,Q);if(!X.success){if(X.blocking)return{proceed:!1,warning:X.error};if(X.warning)Z.push(X.warning);continue}let J=X.output?.hookSpecificOutput;if(J&&"env"in J&&J.env)Object.assign(Y,J.env)}catch(X){let J=X instanceof Error?X.message:String(X);Z.push(`Hook failed: ${J}`)}return{proceed:!0,env:Object.keys(Y).length>0?Y:void 0,warning:Z.length>0?Z.join(`
|
|
21
|
-
`):void 0}}async executeSessionEndHooks(O,q,Q){if(O.length===0)return{};let Z=[],Y=Q.config.maxConcurrentHooks||5,$=await this.executeHooksConcurrently(O,q,Q,Y);for(let X of $)if(!X.success&&X.warning)Z.push(X.warning);return{warning:Z.length>0?Z.join(`
|
|
22
|
-
`):void 0}}async executePostToolUseFailureHooks(O,q,Q){if(O.length===0)return{};let Z=[],Y=[],$=Q.config.maxConcurrentHooks||5,X=await this.executeHooksConcurrently(O,q,Q,$);for(let J of X){if(!J.success&&J.warning){Z.push(J.warning);continue}if(J.stdout&&J.stdout.trim())Y.push(J.stdout.trim())}return{additionalContext:Y.length>0?Y.join(`
|
|
23
|
-
|
|
24
|
-
`):void 0,warning:Z.length>0?Z.join(`
|
|
25
|
-
`):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let J of O)try{let W=await this.executeHook(J,q,Q);if(!W.success){if(W.warning)Y.push(W.warning);continue}if(W.output?.suppressOutput){$=!0;break}if(W.stdout&&W.stdout.trim())X=W.stdout.trim()}catch(W){let G=W instanceof Error?W.message:String(W);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
|
|
26
|
-
`):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
|
|
27
|
-
`):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
|
|
28
|
-
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-sztrmhgd.js"),{createChatServiceAsync:J}=await import("./chunk-6cx4t8r6.js"),{resolveModelConfig:W}=await import("./chunk-fer18bbe.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-9mnbnyrc.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
|
|
29
|
-
|
|
30
|
-
`+`## 评估指令
|
|
31
|
-
${O.prompt}
|
|
32
|
-
|
|
33
|
-
`+`## 输出格式
|
|
34
|
-
`+`必须返回一个 JSON 对象(不要包含任何其他文本):
|
|
35
|
-
`+`{
|
|
36
|
-
"decision": { "behavior": "approve" | "block" },
|
|
37
|
-
`+` "systemMessage": "可选的说明信息",
|
|
38
|
-
`+` "hookSpecificOutput": ${Q}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
`+`重要规则:
|
|
42
|
-
`+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
|
|
43
|
-
`+`- 如果没有发现问题,使用 "approve"
|
|
44
|
-
`+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(O){let q=O.trim(),Q=q.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(Q)return Q[1].trim();return q}async executeHooksConcurrently(O,q,Q,Z){let Y=[],$=new Set;for(let X of O){if($.size>=Z)await Promise.race($);let J=this.executeHook(X,q,Q).catch((G)=>({success:!1,blocking:!1,error:G instanceof Error?G.message:String(G),hook:X})),W=J.then(()=>{$.delete(W)}).catch(()=>{$.delete(W)});$.add(W),Y.push(J)}return Promise.all(Y)}}async function yO(O,q){let Q=O.body?.getReader();if(!Q)return"";let Z=new TextDecoder,Y=0,$="";while(!0){let{value:X,done:J}=await Q.read();if(J)break;if(Y+=X.byteLength,Y>q){try{Q.cancel()}catch{}$+=Z.decode(X.slice(0,q-(Y-X.byteLength)));break}$+=Z.decode(X,{stream:!0})}return $+=Z.decode(),$}import a from"picomatch";var HO=/^([A-Za-z0-9_|]+)\((.+)\)$/;class i{matches(O,q){if(!O)return!0;if(O.tools&&q.toolName){if(!this.matchTools(O.tools,q))return!1}if(O.paths){let Q=q.filePaths??(q.filePath?[q.filePath]:[]);if(Q.length===0||!Q.some((Z)=>this.matchPaths(O.paths,Z)))return!1}if(O.commands&&q.command){if(!this.matchCommands(O.commands,q.command))return!1}return!0}matchTools(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchToolWithParams(Q,q));return this.matchToolWithParams(O,q)}matchPaths(O,q){if(Array.isArray(O))return O.some((Z)=>{return a(Z)(q)});return a(O)(q)}matchCommands(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchPattern(q,Q));return this.matchPattern(q,O)}matchToolWithParams(O,q){let{toolName:Q,command:Z,filePath:Y}=q,$=HO.exec(O);if(!$)return this.matchPattern(Q,O);let[,X,J]=$;if(!this.matchPattern(Q,X))return!1;let W=this.getArgValues(Q,Z,q.filePaths??(Y?[Y]:[]));if(W.length===0)return!1;return W.some((G)=>this.matchGlobOrPattern(G,J))}getArgValues(O,q,Q=[]){if(O==="Bash"||O==="BashTool")return q?[q]:[];if(["Read","Edit","Write","ApplyPatch","Glob","Grep"].includes(O))return Q;return q?[q]:Q}matchGlobOrPattern(O,q){if(/[*?[\]{}!]/.test(q))try{return a(q,{bash:!0,dot:!0})(O)}catch{}if(q.endsWith("*")){let Q=q.slice(0,-1);return O.startsWith(Q)}return O===q}matchPattern(O,q){if(q==="*")return!0;if(!q.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(q))return O===q;if(q.includes("|"))return q.split("|").map((Z)=>Z.trim()).includes(O);try{return new RegExp(q).test(O)}catch{return O===q}}}class U{static instance=null;config=C;executor=new x;guard=new d;matcher=new i;processDisabled=!1;disabledSessions=new Set;sessionStateAliases=new Map;projectConfigs=new Map;sessionConfigs=new Map;managedFunctionMatchers={};constructor(){}static getInstance(){if(!U.instance)U.instance=new U;return U.instance}bindSessionModelResources(O,q,Q){this.executor.bindSessionModelResources(O,q,Q)}bindSessionEnvironment(O,q,Q){this.executor.bindSessionEnvironment(O,q,Q)}bindSessionConfig(O,q,Q){let Z=this.sessionConfigKey(O,q[0]??K()),Y=this.disabledSessions.has(Z);for(let $ of q){let X=this.sessionConfigKey(O,$);if(Y||=this.disabledSessions.has(X),this.sessionStateAliases.set(X,Z),this.sessionConfigs.set(X,this.snapshotConfig(Q)),X!==Z)this.disabledSessions.delete(X)}if(Y)this.disabledSessions.add(Z)}async unbindSessionModelResources(O,q){let Q=new Set;for(let Z of q){let Y=this.sessionConfigKey(O,Z);Q.add(this.sessionStateAliases.get(Y)??Y),this.sessionConfigs.delete(Y),this.sessionStateAliases.delete(Y),this.disabledSessions.delete(Y)}for(let Z of Q)this.disabledSessions.delete(Z);await this.executor.unbindSessionModelResources(O,q)}static resetInstance(){U.instance?.cleanup(),U.instance=null}loadConfig(O,q=K()){let Q=E(C,O),Z=c();Q=E(Q,Z);let Y=_.resolve(q);if(Y===_.resolve(K()))this.config=Q;this.projectConfigs.set(Y,Q)}isEnabled(O=K(),q){if(!(q?this.getExecutionConfig(q,O):this.getConfig(O)).enabled)return!1;if(this.processDisabled)return!1;if(q&&this.disabledSessions.has(this.sessionStateKey(q,O)))return!1;return!0}disable(){this.processDisabled=!0,console.log("[HookManager] Hooks disabled for this process")}enable(){this.processDisabled=!1,console.log("[HookManager] Hooks enabled for this process")}disableSession(O,q){this.disabledSessions.add(this.sessionStateKey(O,q))}enableSession(O,q){this.disabledSessions.delete(this.sessionStateKey(O,q))}isSessionEnabled(O,q){return this.isEnabled(q,O)}isSessionPaused(O,q){return this.disabledSessions.has(this.sessionStateKey(O,q))}getConfig(O=K()){let q=_.resolve(O),Q=this.projectConfigs.get(q);if(Q)return Q;if(q===_.resolve(K()))return this.config;return{...C,enabled:!1}}getExecutionConfig(O,q){return this.sessionConfigs.get(this.sessionConfigKey(O,q))??this.getConfig(q)}isExecutionEnabled(O,q,Q){return O.enabled===!0&&!this.processDisabled&&!this.disabledSessions.has(this.sessionStateKey(q,Q))}sessionStateKey(O,q){let Q=this.sessionConfigKey(O,q);return this.sessionStateAliases.get(Q)??Q}sessionConfigKey(O,q){return`${O}\x00${_.resolve(q)}`}snapshotConfig(O){let q=E(C,O);for(let Q of Object.values(N))q[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((Y)=>({...Y}))}));return q}inheritProjectConfig(O,q){this.projectConfigs.set(_.resolve(q),this.getConfig(O))}getTrustStatus(O=K()){return A.getInstance().getStatus(O,this.getConfig(O))}trustProject(O=K(),q){return A.getInstance().trust(O,this.getConfig(O),q)}revokeProjectTrust(O=K()){return A.getInstance().revoke(O,this.getConfig(O))}registerFunction(O,q,Q,Z){let Y={type:"function",handler:Q,timeout:Z?.timeout},$={name:Z?.name??`inline-${O}-${Date.now()}`,matcher:q,hooks:[Y]};if(Z?.projectDir){let J=_.resolve(Z.projectDir),W=this.getConfig(J),G=W[O]??[];return W[O]=[...G,$],this.projectConfigs.set(J,W),()=>{let L=W[O];if(!L)return;W[O]=L.filter((R)=>R!==$)}}let X=this.managedFunctionMatchers[O]??[];return this.managedFunctionMatchers[O]=[...X,$],()=>{let J=this.managedFunctionMatchers[O]??[];this.managedFunctionMatchers[O]=J.filter((W)=>W!==$)}}async reloadConfig(O=K()){let q=await import("node:fs/promises"),Q=await import("node:path");try{let Z=Q.join(O,".blade","settings.local.json"),Y=await q.readFile(Z,"utf-8"),$=JSON.parse(Y);if($.hooks)this.loadConfig($.hooks,O)}catch{}}async executePreToolHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"allow"};if(Z.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(q,"PreToolUse"))return{decision:"allow"};let $={hook_event_name:"PreToolUse",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"allow"};let J={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{let W=await this.executor.executePreToolHooks(X,$,J);if(this.guard.markExecuted(q,"PreToolUse"),Z.permissionMode==="yolo"){if(W.decision==="deny")return W;return{decision:"allow",modifiedInput:W.modifiedInput,warning:W.warning,reason:W.reason}}return W}catch(W){return console.error("[HookManager] Error executing PreToolUse hooks:",W),{decision:"allow",warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executePostToolHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(q,"PostToolUse"))return{};let X={hook_event_name:"PostToolUse",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,tool_response:Z,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(J.length===0)return{};let W={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{let G=await this.executor.executePostToolHooks(J,X,W);return this.guard.markExecuted(q,"PostToolUse"),G}catch(G){return console.error("[HookManager] Error executing PostToolUse hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}finally{this.guard.cleanup(q)}}async executeStopHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{shouldStop:!0};let Q={hook_event_name:"Stop",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},Z=this.getMatchingHooks("Stop",{},q);if(Z.length===0)return{shouldStop:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing Stop hooks:",$),{shouldStop:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSubagentStopHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{shouldStop:!0};let Z={hook_event_name:"SubagentStop",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,agent_type:O,task_description:q.taskDescription,success:q.success,result_summary:q.resultSummary,error:q.error},Y=this.getMatchingHooks("SubagentStop",{},Q);if(Y.length===0)return{shouldStop:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing SubagentStop hooks:",X),{shouldStop:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePermissionRequestHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"ask"};let $={hook_event_name:"PermissionRequest",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"ask"};let J={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,J)}catch(W){return console.error("[HookManager] Error executing PermissionRequest hooks:",W),{decision:"ask",warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeUserPromptSubmitHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{proceed:!0};let Z={hook_event_name:"UserPromptSubmit",hook_execution_id:z(),timestamp:new Date().toISOString(),user_prompt:O,has_images:q.hasImages,image_count:q.imageCount,project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{},Q);if(Y.length===0)return{proceed:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",X),{proceed:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeSessionStartHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{proceed:!0};let Q={hook_event_name:"SessionStart",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},Z=this.getMatchingHooks("SessionStart",{},q);if(Z.length===0)return{proceed:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing SessionStart hooks:",$),{proceed:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSessionEndHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"SessionEnd",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,reason:O},Y=this.getMatchingHooks("SessionEnd",{},Q);if(Y.length===0)return{};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,Z,$),{}}catch(X){return console.error("[HookManager] Error executing SessionEnd hooks:",X),{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolUseFailureHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};let X={hook_event_name:"PostToolUseFailure",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,error:Z,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(J.length===0)return{};let W={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(J,X,W)}catch(G){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeNotificationHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{suppress:!1,message:q};let Y={hook_event_name:"Notification",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,notification_type:O,title:Q.title,message:q},$=this.getMatchingHooks("Notification",{},Z);if($.length===0)return{suppress:!1,message:q};let X={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeNotificationHooks($,Y,X)}catch(J){return console.error("[HookManager] Error executing Notification hooks:",J),{suppress:!1,message:q,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeElicitationHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"Elicitation",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,server_name:O.serverName,mode:O.mode,message:O.message,requested_schema:O.requestedSchema,url:O.url,elicitation_id:O.elicitationId};return this.executeElicitationHookChain("Elicitation",Z,q,Q)}async executeElicitationResultHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{};let Y={hook_event_name:"ElicitationResult",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,server_name:O.serverName,mode:O.mode,elicitation_id:O.elicitationId,action:q.action,content:q.content};return this.executeElicitationHookChain("ElicitationResult",Y,Q,Z)}async executeElicitationHookChain(O,q,Q,Z){let Y=this.getMatchingHooks(O,{},Z);if(Y.length===0)return{};let $={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeElicitationHooks(Y,q,$)}catch(X){return{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeCompactionHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{blockCompaction:!1};let Z={hook_event_name:"Compaction",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,trigger:O,messages_before:q.messagesBefore,tokens_before:q.tokensBefore},Y=this.getMatchingHooks("Compaction",{},Q);if(Y.length===0)return{blockCompaction:!1};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeCompactionHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing Compaction hooks:",X),{blockCompaction:!1,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}getMatchingHooks(O,q,Q){let Z=[...Q[O]??[],...this.managedFunctionMatchers[O]??[]],Y=[];for(let $ of Z)if(this.matcher.matches($.matcher,q))Y.push(...$.hooks);return Y}extractFilePaths(O){let q=[],Q=["file_path","path","filePath","source","target"];for(let Z of Q){let Y=O[Z];if(typeof Y==="string")q.push(Y)}if(typeof O.patch==="string"){for(let Z of O.patch.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm))if(Z[1])q.push(Z[1]);for(let Z of O.patch.matchAll(/^\*\*\* Move to: (.+)$/gm))if(Z[1])q.push(Z[1])}return[...new Set(q)]}extractCommand(O,q){if(O==="Bash"||O==="BashTool"){let Q=q.command;if(typeof Q==="string")return Q}return}cleanup(){this.guard.cleanupAll(),this.disabledSessions.clear(),this.sessionStateAliases.clear()}}
|
|
45
|
-
export{N as He,o as Ie,U as Je};
|
package/dist/chunk-z1aqe7ms.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Pc as a,Qc as b,Rc as c,Sc as d,Tc as e,Uc as f,Vc as g,Wc as h}from"./chunk-56qew7w0.js";import"./chunk-fhnkyqfb.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-vxpqGt4L.js","assets/index-Bz4W1-8a.js","assets/vendor-react-DG5dkZ_t.js","assets/vendor-radix-DXRuAJHH.js","assets/vendor-icons-ICv1v-tf.js","assets/session-events-DJh6SZcl.js","assets/index-7zaeanZL.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as b,j as e}from"./vendor-react-DG5dkZ_t.js";import{u as R,a as w,b as me,s as Te,c as Ke,d as J,D as Ae,e as Me,f as qe,g as Fe,h as Re,i as De,j as A,k as O,B as ue,_ as ze,S as Ge,l as We,m as Je,C as Qe,n as Ye}from"./index-Bz4W1-8a.js";import{Q as ge,O as Xe,G as Ze,Y as et,L as F,z as tt,T as te,C as re,Z as st,v as rt,_ as at,B as nt,$ as $e,y as ae,m as he,R as xe,s as it,H as ot,a0 as Ie,U as lt,a1 as ct,a2 as dt,a3 as ut,P as Be,a4 as mt,X as ht,a5 as xt,a6 as pt,f as Pe,a7 as ft,W as bt,a as gt}from"./vendor-icons-ICv1v-tf.js";import{k as vt,g as kt,l as jt,e as yt,t as wt,j as Nt}from"./session-events-DJh6SZcl.js";import{j as St,k as Ct,l as Et,m as _e}from"./vendor-radix-DXRuAJHH.js";function ve(t){return t.split("/").filter(Boolean).at(-1)||t}function Tt(){const t=R(),s=w(N=>N.sessions),r=w(N=>N.currentSessionRef),a=w(N=>N.taskDeliveryActions),o=w(N=>N.deliverTask),n=me(N=>N.openFilePreview),[d,f]=b.useState(!1),c=s.find(N=>Te({sessionId:N.sessionId,projectPath:N.projectPath},r));if(!(c!=null&&c.taskIsolation))return null;const l=c.taskDiffStat,y=c.taskIsolation==="worktree",i=Ke(c),u=a[J(i)],h=c.taskDelivery,v=(h==null?void 0:h.status)==="conflicted",g=!!(l&&(l.changedFiles>0||l.commits>0)),p=!["queued","running"].includes(c.taskStatus),E=(h==null?void 0:h.status)==="applied"||(h==null?void 0:h.status)==="discarded",j=y&&g&&p&&!E,x=l?l.additions+l.deletions:0,m=x>0&&l?l.additions/x*100:0,C=N=>{o(i,N).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(ge,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:ve(c.taskSourceProjectPath||c.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:[y?e.jsx(Xe,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx(ge,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:y?"text-[hsl(var(--deck-accent))]":void 0,children:t(y?"artifact.env.isolated":"artifact.env.local")})]}),c.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:c.taskWorktreeBranch,children:[e.jsx(Ze,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:c.taskWorktreeBranch})]})]})]}),l&&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(et,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:l.changedFiles})]}),x>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:`${m}%`}}),e.jsx("span",{className:"h-full bg-red-500/80",style:{width:`${100-m}%`}})]}),e.jsxs("span",{className:"tabular-nums text-[hsl(var(--deck-accent))]",children:["+",l.additions]}),e.jsxs("span",{className:"tabular-nums text-red-600 dark:text-red-400",children:["-",l.deletions]}),l.commits>0&&e.jsx("span",{className:"hidden tabular-nums text-[hsl(var(--deck-ink-faint))] sm:inline",children:t("artifact.commits",{count:l.commits})}),g&&(h==null?void 0:h.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")}),j&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!u,onClick:()=>C("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:[u==="apply"?e.jsx(F,{className:"h-3 w-3 animate-spin"}):e.jsx(tt,{className:"h-3 w-3"}),t(u==="apply"?"artifact.applying":v?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!u,onClick:()=>f(!0),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-[hsl(var(--deck-ink-faint))] transition hover:bg-red-500/10 hover:text-red-600 disabled:cursor-wait disabled:opacity-50 dark:hover:text-red-400","aria-label":t("artifact.discard"),title:t("artifact.discard"),children:u==="discard"?e.jsx(F,{className:"h-3 w-3 animate-spin"}):e.jsx(te,{className:"h-3 w-3"})})]}),(h==null?void 0:h.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(re,{className:"h-3 w-3"}),t("artifact.applied")]}),(h==null?void 0:h.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(te,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(h==null?void 0:h.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(st,{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:h.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx(Ae,{open:d,onOpenChange:f,children:e.jsxs(Me,{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(qe,{children:[e.jsx(Fe,{children:t("artifact.discardDialog.title")}),e.jsx(Re,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:ve(c.taskSourceProjectPath||c.projectPath),count:(l==null?void 0:l.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(De,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>f(!1),className:"rounded-md border border-[hsl(var(--deck-border))] px-3 py-2 text-sm hover:bg-[hsl(var(--deck-surface-2))]",children:t("artifact.discardDialog.cancel")}),e.jsxs("button",{type:"button",onClick:()=>{f(!1),C("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(te,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}const At=new Set(["completed","stale","failed","aborted","interrupted"]),Mt={completed:"chat.review.status.completed",stale:"chat.review.status.stale",failed:"chat.review.status.failed",aborted:"chat.review.status.aborted",interrupted:"chat.review.status.interrupted"},Ft={completed:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",stale:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20",failed:"bg-red-500/10 text-red-700 dark:text-red-300 border-red-500/20",aborted:"bg-zinc-500/10 text-zinc-700 dark:text-zinc-300 border-zinc-500/20",interrupted:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20"};function se(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Rt(t){const s=se(t),r=se(s==null?void 0:s.codeLocation),a=s==null?void 0:s.priority,o=s==null?void 0:s.confidenceScore,n=r==null?void 0:r.lineStart,d=r==null?void 0:r.lineEnd;if(!(typeof(s==null?void 0:s.title)!="string"||typeof s.body!="string"||a!==0&&a!==1&&a!==2&&a!==3||typeof o!="number"||!Number.isFinite(o)||typeof(r==null?void 0:r.path)!="string"||!Number.isInteger(n)||!Number.isInteger(d)))return{title:s.title,body:s.body,priority:a,confidenceScore:o,codeLocation:{path:r.path,lineStart:n,lineEnd:d}}}function Dt(t){const s=se(t),r=se(s==null?void 0:s.target);if((s==null?void 0:s.phase)!=="completed"||typeof s.status!="string"||!At.has(s.status)||typeof(r==null?void 0:r.label)!="string"||r.kind!=="uncommitted"&&r.kind!=="base"&&r.kind!=="commit"||typeof s.overallExplanation!="string"||!Array.isArray(s.findings))return;const a=s.findings.map(Rt);if(!a.some(o=>o===void 0))return{status:s.status,target:{kind:r.kind,label:r.label,...typeof r.reference=="string"?{reference:r.reference}:{}},overallExplanation:s.overallExplanation,findings:a,...typeof s.error=="string"?{error:s.error}:{}}}function $t(t){const{path:s,lineStart:r,lineEnd:a}=t.codeLocation;return r===a?`${s}:L${r}`:`${s}:L${r}-${a}`}function It({report:t}){const s=R(),r=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"),": ",r]})]}),e.jsxs("span",{className:A("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",Ft[t.status]),children:[s("chat.review.status"),": ",s(Mt[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((a,o)=>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:a.title}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.confidence",{value:a.confidenceScore.toFixed(2)})})]}),e.jsx("code",{className:"mt-1 block text-[10.5px] text-[hsl(var(--deck-accent))]",children:$t(a)}),e.jsx("p",{className:"mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:a.body})]},`${a.codeLocation.path}:${a.codeLocation.lineStart}:${o}`))})]}),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 Bt({elicitation:t,messageId:s}){const r=R(),a=w(j=>j.currentSessionRef),o=w(j=>j.setElicitation),[n,d]=b.useState(()=>_t(t.details.fields??[])),[f,c]=b.useState(()=>Lt(t.details.fields??[])),[l,y]=b.useState(!1),[i,u]=b.useState(),h=t.details.fields??[],v=b.useMemo(()=>h.every(j=>{var m;if(!j.required)return!0;if(ne(j))return!!((m=f[j.name])!=null&&m.trim()||j.defaultValue!==void 0);const x=n[j.name]??j.defaultValue;return Array.isArray(x)?x.length>0:x!==void 0}),[h,f,n]);if(t.status!=="pending")return e.jsx("div",{className:"rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:r(t.status==="cancelled"?"interaction.elicitation.cancelled":"interaction.elicitation.responded")});const g=async(j,x)=>{if(!(!a||l)){y(!0),u(void 0);try{await O.respondToElicitation(a,t.toolCallId,{action:j,...x?{content:x}:{}}),o(s,{...t,status:"responded"})}catch(m){u(m instanceof Error?m.message:r("interaction.elicitation.failed"))}finally{y(!1)}}},p=async()=>{try{await g("accept",Vt(h,n,f))}catch(j){u(j instanceof Error?j.message:String(j))}},E=()=>{const j=t.details.url;if(!j){u("MCP URL is unavailable");return}if(!window.open(j,"_blank","noopener,noreferrer")){u("The browser blocked the external window");return}g("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:[r("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:r("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(K,{onClick:E,disabled:l,primary:!0,label:r("interaction.elicitation.open"),icon:e.jsx(at,{className:"h-3.5 w-3.5"})}),e.jsx(K,{onClick:()=>void g("decline"),disabled:l,label:r("interaction.elicitation.decline")}),e.jsx(K,{onClick:()=>void g("cancel"),disabled:l,label:r("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[h.map(j=>e.jsx(Pt,{field:j,value:n[j.name],rawValue:f[j.name]??"",onValueChange:x=>d(m=>({...m,[j.name]:x})),onRawChange:x=>c(m=>({...m,[j.name]:x}))},j.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(K,{onClick:()=>void p(),disabled:l||!v,primary:!0,label:r("interaction.elicitation.submit"),icon:l?e.jsx(F,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(K,{onClick:()=>void g("decline"),disabled:l,label:r("interaction.elicitation.decline")}),e.jsx(K,{onClick:()=>void g("cancel"),disabled:l,label:r("interaction.elicitation.cancel")})]})]}),i&&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:i})]})}function Pt({field:t,value:s,rawValue:r,onValueChange:a,onRawChange:o}){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:Ot(t).map(n=>{const d=Array.isArray(s)?s.includes(n.value):s===n.typedValue;return e.jsx("button",{type:"button","aria-pressed":d,onClick:()=>{if(t.type==="multi-select"){const f=Array.isArray(s)?s:[];a(f.includes(n.value)?f.filter(c=>c!==n.value):[...f,n.value])}else a(n.typedValue)},className:A("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",d?"border-emerald-500 bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200":"border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:n.label},n.value)})}):e.jsx("input",{id:`mcp-elicitation-${t.name}`,type:Ut(t),value:r,onChange:n=>o(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 K({onClick:t,disabled:s,primary:r=!1,label:a,icon:o}){return e.jsxs("button",{type:"button",onClick:t,disabled:s,className:A("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",r?"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:[o,a]})}function _t(t){return Object.fromEntries(t.filter(s=>!ne(s)&&s.defaultValue!==void 0).map(s=>[s.name,Array.isArray(s.defaultValue)?[...s.defaultValue]:s.defaultValue]))}function Lt(t){return Object.fromEntries(t.filter(s=>ne(s)&&s.defaultValue!==void 0).map(s=>[s.name,String(s.defaultValue)]))}function Vt(t,s,r){var o;const a={};for(const n of t){if(ne(n)){const f=((o=r[n.name])==null?void 0:o.trim())??"";if(!f){if(n.defaultValue!==void 0)a[n.name]=n.defaultValue;else if(n.required)throw new Error(`${n.title} is required`);continue}if(n.type==="number"||n.type==="integer"){const c=Number(f);if(!Number.isFinite(c))throw new Error(`${n.title} must be a finite number`);if(n.type==="integer"&&!Number.isSafeInteger(c))throw new Error(`${n.title} must be a safe integer`);a[n.name]=c}else a[n.name]=f;continue}const d=s[n.name]??n.defaultValue;if(d===void 0){if(n.required)throw new Error(`${n.title} is required`);continue}if(Array.isArray(d)){if(n.minItems!==void 0&&d.length<n.minItems)throw new Error(`${n.title} requires at least ${n.minItems} choices`);if(n.maxItems!==void 0&&d.length>n.maxItems)throw new Error(`${n.title} allows at most ${n.maxItems} choices`)}a[n.name]=d}return a}function Ot(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 ne(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function Ut(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 Ht(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 Kt({report:t}){const s=R(),[r,a]=b.useState(!1),o=JSON.stringify(t.output,null,2),n=async()=>{try{await navigator.clipboard.writeText(o),a(!0),window.setTimeout(()=>a(!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:r?e.jsx(re,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx($e,{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:o})]})}const qt=b.lazy(()=>ze(()=>import("./MarkdownRenderer-vxpqGt4L.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function ke({text:t,label:s}){const[r,a]=b.useState(!1);if(!t.trim())return null;const o=async()=>{try{await navigator.clipboard.writeText(t),a(!0),window.setTimeout(()=>a(!1),1400)}catch{}};return e.jsx("button",{type:"button","aria-label":s,title:s,onClick:o,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:r?e.jsx(re,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx($e,{className:"h-3.5 w-3.5"})})}function zt(){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(ue,{size:20,pulse:!1})})}function Gt(){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 je(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 Wt(t){if(typeof t=="string")return{text:je(t),images:[]};const s=t.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
3
|
-
`),r=t.filter(a=>a.type==="image_url").map(a=>a.image_url.url);return{text:je(s),images:r}}function pe(t){return typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.text).join(`
|
|
4
|
-
`)}function Jt(t){const s=t.agentContent;return s?vt(s):pe(t.content)}function ye({content:t,syntaxHighlight:s=!0}){return e.jsx(b.Suspense,{fallback:e.jsx("pre",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono whitespace-pre-wrap",children:t}),children:e.jsx(qt,{content:t,syntaxHighlight:s})})}function fe({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]"},r={running:"Running",success:"Success",error:"Error",pending:"Pending",info:"Info"};return e.jsx("span",{className:A("text-[11px] px-2 py-0.5 rounded-full font-mono",s[t]),children:r[t]})}function Qt(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 we=500;function Le(t,s){if(t.length<=s)return t;let r=Math.max(0,s);return r>0&&/[\uD800-\uDBFF]/.test(t.charAt(r-1))&&(r-=1),t.slice(0,r)}function Ne(t,s){if(t.length<=s)return t;let r=Math.max(0,t.length-s);return/[\uDC00-\uDFFF]/.test(t.charAt(r))&&(r+=1),t.slice(r)}function le(t,s){if(t.length<=s)return t;if(s<=0)return"";const r=`
|
|
5
|
-
... (display clipped) ...
|
|
6
|
-
`,a=s-r.length;if(a<=0)return Ne(t,s);const o=Math.floor(a/3);return`${Le(t,o)}${r}${Ne(t,a-o)}`}function Yt(t){const s=t.split(`
|
|
7
|
-
`),r=s.at(-1),a=r!=null&&r.startsWith("Output truncated")?r:void 0,o=a?s.slice(0,-1).join(`
|
|
8
|
-
`):t,n=a?`
|
|
9
|
-
${a}`:"",d=Math.max(0,we-n.length),c=o.indexOf(`
|
|
10
|
-
stderr:
|
|
11
|
-
`);let l;if(c>=0&&o.includes(`
|
|
12
|
-
stdout:
|
|
13
|
-
`)){const y=o.slice(0,c),i=o.slice(c+1),u=Math.max(0,d-1),h=Math.floor(u/2);l=`${le(y,h)}
|
|
14
|
-
${le(i,u-h)}`}else l=le(o,d);return{body:Le(l,d),...a?{notice:a}:{},truncated:!!a||t.length>we}}function Xt({tool:t}){const[s,r]=b.useState(!1),a=Qt(t.arguments),o=t.output?Yt(t.output):void 0;return e.jsxs("div",{"data-tool-name":t.toolName,"data-tool-status":t.status,"data-tool-truncated":o!=null&&o.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:()=>r(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(ae,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}):e.jsx(he,{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(fe,{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:[a&&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:a})]}),o&&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:[o.body,o.notice&&e.jsxs(e.Fragment,{children:[`
|
|
15
|
-
`,e.jsx("span",{"data-tool-truncation-notice":!0,children:o.notice})]})]})]})]})]})}function Ve({toolCalls:t}){return t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map(s=>e.jsx(Xt,{tool:s},s.toolCallId))})}function Zt({toolCalls:t,toolCallIds:s}){const r=R(),[a,o]=b.useState(!1),n=b.useMemo(()=>new Map(t.map(i=>[i.toolCallId,i])),[t]),d=s.flatMap(i=>{const u=n.get(i);return u?[u]:[]});if(d.length===0)return null;const f=d.filter(i=>i.status==="running").length,c=d.filter(i=>i.status==="error").length,l=[...d].reverse().find(i=>i.status==="running"&&!!i.progressMessage),y=f>0?r(d.length===1?"chat.timeline.tools.runningOne":"chat.timeline.tools.running",{count:d.length}):c>0?r(d.length===1?"chat.timeline.tools.completedOneWithError":"chat.timeline.tools.completedWithErrors",{count:d.length,errors:c}):r(d.length===1?"chat.timeline.tools.completedOne":"chat.timeline.tools.completed",{count:d.length});return e.jsxs("div",{"data-agent-tool-group":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":a,onClick:()=>o(i=>!i),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:[a?e.jsx(ae,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(he,{className:"h-3.5 w-3.5 shrink-0"}),f>0&&e.jsx(F,{className:"h-3 w-3 shrink-0 animate-spin text-[hsl(var(--deck-accent))]"}),e.jsx("span",{children:y}),(l==null?void 0:l.progressMessage)&&e.jsxs("span",{className:"min-w-0 truncate text-[10.5px] text-[hsl(var(--deck-ink-muted))]",children:[l.progressMessage,l.progress!==void 0&&l.progressTotal!==void 0&&` · ${Math.max(0,Math.min(100,Math.round(l.progress/l.progressTotal*100)))}%`]})]}),(l==null?void 0:l.progress)!==void 0&&l.progressTotal!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${l.toolName} progress`,"aria-valuemin":0,"aria-valuemax":l.progressTotal,"aria-valuenow":Math.min(l.progress,l.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,l.progress/l.progressTotal*100))}%`}})}),a&&e.jsx("div",{"data-agent-tool-group-details":!0,className:"mt-2 space-y-2 pl-1",children:e.jsx(Ve,{toolCalls:d})})]})}function es({content:t}){const s=R(),[r,a]=b.useState(!1);return t?e.jsxs("div",{"data-agent-thinking":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>a(o=>!o),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:[r?e.jsx(ae,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}):e.jsx(he,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{children:s("chat.timeline.thinking")})]}),r&&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 ts({tasks:t}){if(t.length===0)return null;const s=t.filter(a=>a.status==="completed").length,r=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:r?"✓ All tasks done":`Tasks: ${s}/${t.length}`})})})}function ss({toolCalls:t}){const s=me(a=>a.openFilePreview),r=b.useMemo(()=>{const a=new Map,o=["Write","SearchReplace","Edit","ApplyPatch"];for(const n of t){if(n.status!=="success")continue;const d=n.metadata;if(n.toolName==="ApplyPatch"&&Array.isArray(d==null?void 0:d.changes)){for(const c of d.changes)c&&typeof c=="object"&&"path"in c&&typeof c.path=="string"&&a.set(c.path,{path:c.path,toolName:n.toolName});continue}const f=d==null?void 0:d.file_path;f&&o.includes(n.toolName)&&a.set(f,{path:f,toolName:n.toolName})}return Array.from(a.values())},[t]);return r.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 (",r.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(({path:a})=>{const o=a.split("/").pop()||a;return e.jsxs("button",{onClick:()=>s({tab:"diff",targetPath:a}),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:a,children:[e.jsx(it,{className:"w-3 h-3"}),o]},a)})})]})}function rs({subagent:t}){var z,H,Q,Y;const s=R(),[r,a]=b.useState(null),[o,n]=b.useState(!1),[d,f]=b.useState(null),[c,l]=b.useState(!1),[y,i]=b.useState(""),[u,h]=b.useState(!1),[v,g]=b.useState(null),[p,E]=b.useState(null),[j,x]=b.useState(null),m=w(T=>T.currentSessionRef),C=w(T=>T.isStreaming),N=w(T=>T.isTemporarySession);if(!t)return null;const $=t.status==="running",M=r!==null?r:$,V=t.toolCalls||d||[],P=t.output||t.thinking||V.length>0||t.sessionId,S=p&&p.status!=="running"?p:j,I=(S==null?void 0:S.id)??t.sessionId,U=((z=S==null?void 0:S.restartRecovery)==null?void 0:z.outcome)==="failed",ie=!$&&!C&&!N&&!U&&(p==null?void 0:p.status)!=="running"&&!!(I&&m);b.useEffect(()=>{if(!M||$||!t.sessionId||!(m!=null&&m.projectPath)||d!==null||t.toolCalls&&t.toolCalls.length>0)return;let T=!0;return n(!0),O.getMessages({sessionId:t.sessionId,projectPath:m.projectPath}).then(_=>{var B,D;if(!T)return;const L=yt(_),k=new Map;for(const G of L)if((D=(B=G.agentContent)==null?void 0:B.toolCalls)!=null&&D.length)for(const oe of G.agentContent.toolCalls)k.has(oe.toolCallId)||k.set(oe.toolCallId,oe);f(Array.from(k.values()))}).finally(()=>{T&&n(!1)}),()=>{T=!1}},[M,$,t.sessionId,t.toolCalls,d,m==null?void 0:m.projectPath]),b.useEffect(()=>{if(!t.sessionId||!m)return;let T=!0;const _=t.rootAgentId??t.sessionId,L=t.resumeDepth??0;return O.listSubagents(m).then(k=>{if(!T)return;x(k.find(D=>D.id===t.sessionId)??null);const B=k.filter(D=>D.id!==t.sessionId&&D.rootAgentId===_&&D.resumeDepth>L).sort((D,G)=>G.resumeDepth-D.resumeDepth||G.lastActiveAt-D.lastActiveAt)[0];B&&E(B)}).catch(()=>{}),()=>{T=!1}},[m==null?void 0:m.sessionId,m==null?void 0:m.projectPath,t.sessionId,t.rootAgentId,t.resumeDepth]),b.useEffect(()=>{if(!p||p.status!=="running"||!m)return;let T=!0;const _=async()=>{try{const B=(await O.listSubagents(m)).find(D=>D.id===p.id);T&&B&&E(B)}catch{}},L=window.setInterval(()=>{_()},1e3);return()=>{T=!1,window.clearInterval(L)}},[m,p==null?void 0:p.id,p==null?void 0:p.status]);const q=async()=>{if(!(!m||!I||!y.trim()||u)){h(!0),g(null);try{const T=await O.resumeSubagent(m,I,y.trim());E(T.session),i(""),l(!1),a(!0)}catch(T){g(T instanceof Error?T.message:s("chat.subagent.resumeFailed"))}finally{h(!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:()=>a(!M),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:[$&&e.jsx(F,{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(fe,{status:t.status==="completed"?"success":t.status==="failed"?"error":"running"}),t.type==="verification"&&t.verificationVerdict&&e.jsx("span",{"data-verification-verdict":t.verificationVerdict,className:A("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})})]}),P&&e.jsx(ae,{className:A("h-3.5 w-3.5 text-[hsl(var(--deck-ink-muted))] transition-transform",M&&"rotate-180")})]}),!M&&!$&&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}),M&&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})]}),o&&e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[e.jsx(F,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.loadingLogs")]}),!o&&V.length>0&&e.jsx(Ve,{toolCalls:V}),p&&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:p.id,status:p.status,depth:p.resumeDepth??1})}),(((H=p.result)==null?void 0:H.message)||((Q=p.result)==null?void 0:Q.error))&&e.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[hsl(var(--deck-ink))]",children:p.result.message||p.result.error})]}),U&&((Y=S==null?void 0:S.result)==null?void 0:Y.error)&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:S.result.error}),ie&&e.jsxs("div",{className:"space-y-2",children:[c?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:y,onChange:T=>i(T.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:()=>{l(!1),g(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 q(),disabled:!y.trim()||u,className:"flex items-center gap-1 rounded bg-[#7C3AED] px-2 py-1 text-[11px] font-medium text-white disabled:opacity-50",children:[u&&e.jsx(F,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.resumeAgent")]})]})]}):e.jsxs("button",{type:"button","aria-label":s("chat.subagent.resumeAria"),onClick:()=>l(!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(xe,{className:"w-3 h-3"}),s("chat.subagent.resume")]}),v&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:v})]})]})]})}function as({confirmation:t,messageId:s}){const r=R(),[a,o]=b.useState(!1),[n,d]=b.useState(null),f=w(y=>y.currentSessionRef),c=w(y=>y.setConfirmation);if(!t)return null;const l=async(y,i)=>{if(!(!f||a)){o(!0),d(null);try{await O.respondPermission(f,t.toolCallId,{approved:y,scope:i}),c(s,{...t,status:y?"approved":"denied"})}catch(u){d(u instanceof Error?u.message:r("interaction.permission.failed"))}finally{o(!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:r("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 l(!0,"once"),disabled:a,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:a?e.jsx(F,{className:"h-3.5 w-3.5 animate-spin"}):r("interaction.permission.once")}),t.allowRemember!==!1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>void l(!0,"session"),disabled:a,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:r("interaction.permission.session")}),e.jsx("button",{type:"button",onClick:()=>void l(!0,"project"),disabled:a,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:r("interaction.permission.project")})]}),e.jsx("button",{type:"button",onClick:()=>void l(!1),disabled:a,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:r("interaction.permission.deny")})]})]})}function ns({question:t,messageId:s}){const r=R(),[a,o]=b.useState({}),[n,d]=b.useState({}),[f,c]=b.useState(!1),[l,y]=b.useState(null),i=w(p=>p.currentSessionRef),u=w(p=>p.setQuestion),h=b.useMemo(()=>t?t.questions.reduce((p,E)=>{var C;const j=(C=n[E.header])==null?void 0:C.trim(),x=a[E.header];if(E.multiSelect){const N=Array.isArray(x)?[...x]:[];return j&&N.push(j),N.length>0&&(p[E.header]=N),p}const m=j||(typeof x=="string"?x:"");return m&&(p[E.header]=m),p},{}):{},[a,n,t]),v=(t==null?void 0:t.questions.every(p=>p.header in h))??!1;if(!t)return null;const g=async()=>{if(!(!i||f||!v)){c(!0),y(null);try{await O.respondToQuestion(i,t.toolCallId,h),u(s,{...t,status:"answered",answers:h})}catch(p){y(p instanceof Error?p.message:r("interaction.question.failed"))}finally{c(!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:r("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((p,E)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:p.question}),e.jsxs("div",{className:"space-y-1",children:[p.options.map((j,x)=>e.jsxs("button",{type:"button",onClick:()=>{if(p.multiSelect){const m=a[p.header]||[],C=m.includes(j.label)?m.filter(N=>N!==j.label):[...m,j.label];o({...a,[p.header]:C})}else o({...a,[p.header]:j.label}),d({...n,[p.header]:""})},className:A("w-full text-left px-3 py-2 rounded-md border text-[12px] font-mono transition-colors","border-[hsl(var(--deck-border))]",(p.multiSelect?(a[p.header]||[]).includes(j.label):a[p.header]===j.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:j.label}),e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-faint))] mt-1",children:j.description})]},x)),e.jsx("input",{"aria-label":`${p.header} other response`,value:n[p.header]??"",onChange:j=>d({...n,[p.header]:j.target.value}),placeholder:r("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)),l&&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:l}),e.jsxs("button",{type:"button",onClick:()=>void g(),disabled:f||!v,className:"inline-flex min-h-8 items-center gap-1.5 px-3 py-1.5 text-[12px] font-mono bg-[#22C55E] text-white rounded-md hover:bg-[#16A34A] disabled:cursor-wait disabled:opacity-50",children:[f&&e.jsx(F,{className:"h-3.5 w-3.5 animate-spin"}),r("interaction.question.submit")]})]})}function is({message:t}){const s=t.agentContent,r=w(v=>v.isStreaming&&v.currentAssistantMessageId===t.id);if(!s){const v=pe(t.content);return v?e.jsx(ye,{content:v}):null}const{toolCalls:a,tasks:o,confirmation:n,question:d,elicitation:f}=s,c=kt(s),l=jt(s);if(!(l.length>0||o.length>0||c.length>0||n||d||f)&&r)return e.jsxs("div",{className:"flex items-center gap-2 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(F,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-[12px] font-mono",children:"Thinking..."})]});const u=a.length>0&&a.every(v=>v.status==="success"||v.status==="error")&&!r,h=!r;return e.jsxs("div",{className:"space-y-3",children:[l.map(v=>v.type==="thinking"?e.jsx("div",{"data-agent-timeline-block":"thinking",children:e.jsx(es,{content:v.content})},v.id):v.type==="text"?e.jsx("div",{"data-agent-timeline-block":"text",children:e.jsx(ye,{content:v.content,syntaxHighlight:h})},v.id):e.jsx("div",{"data-agent-timeline-block":"tool_group",children:e.jsx(Zt,{toolCalls:a,toolCallIds:v.toolCallIds})},v.id)),o.length>0&&e.jsx(ts,{tasks:o}),c.map(v=>e.jsx(rs,{subagent:v},v.id)),n&&e.jsx(as,{confirmation:n,messageId:t.id}),d&&e.jsx(ns,{question:d,messageId:t.id}),f&&e.jsx(Bt,{elicitation:f,messageId:t.id}),u&&e.jsx(ss,{toolCalls:a})]})}function os({message:t,showAvatar:s=!0}){var f,c,l,y;const r=t.role==="user";if(t.role==="system"){const i=pe(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:i})})}if(r){const i=(f=t.metadata)!=null&&f.userShellCommand&&typeof t.metadata.userShellCommand=="object"?t.metadata.userShellCommand:(c=t.metadata)!=null&&c.userShellExecution&&typeof t.metadata.userShellExecution=="object"?t.metadata.userShellExecution:void 0;if(i){const v=typeof i.command=="string"?i.command:"",g=i.status==="running"?"running":i.status==="completed"?"success":"error",p=typeof i.output=="string"?i.output:[typeof i.stdout=="string"?i.stdout:"",typeof i.stderr=="string"&&i.stderr?`stderr:
|
|
16
|
-
${i.stderr}`:""].filter(Boolean).join(`
|
|
17
|
-
`);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"user","data-user-shell-command":!0,className:"flex w-full justify-end p-4",children:e.jsxs("div",{className:"w-full max-w-[85%] overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 truncate font-mono text-[12px] text-[hsl(var(--deck-ink))]",children:[e.jsx("span",{className:"mr-2 text-amber-600 dark:text-amber-400",children:"$"}),v]}),e.jsx(fe,{status:g})]}),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:p||"(no output)"}),typeof i.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 ",i.exitCode,typeof i.durationMs=="number"?` · ${(i.durationMs/1e3).toFixed(3)}s`:"",i.truncated===!0?" · truncated":""]})]})})}const{text:u,images:h}=Wt(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(ke,{text:u,label:"Copy message"})}),e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] rounded-lg px-4 py-3 max-w-[85%]",children:[u&&e.jsx("p",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono leading-relaxed whitespace-pre-wrap",children:u}),h.length>0&&e.jsx("div",{className:A("grid gap-2",h.length===1?"grid-cols-1 mt-0":"grid-cols-2 mt-3"),children:h.map((v,g)=>e.jsx("img",{src:v,alt:`attachment-${g+1}`,className:"object-cover w-full max-h-64 rounded-md"},`${v}-${g}`))})]}),e.jsx(Gt,{})]})}const o=Jt(t),n=Dt((l=t.metadata)==null?void 0:l.codeReview),d=Ht((y=t.metadata)==null?void 0:y.structuredOutput);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"assistant",className:A("group flex gap-4 justify-start w-full",s?"p-4":"px-4 pt-0 pb-3"),children:[s?e.jsx(zt,{}):e.jsx("div",{className:"w-8 shrink-0"}),e.jsxs("div",{className:"overflow-hidden flex-1 min-w-0",children:[n?e.jsx(It,{report:n}):d?e.jsx(Kt,{report:d}):e.jsx(is,{message:t}),!d&&o.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(ke,{text:o,label:"Copy response"})})]})]})}const ls=b.memo(os);function cs(t,s,r){return Math.max(0,t+(r-s))}function ds(t,s,r){return Math.min(s,Math.max(0,t)+Math.max(0,r))}function Se(t,s){return t?t.querySelector(`[data-chat-message-id="${CSS.escape(s)}"]`):null}function us({turns:t,viewportRef:s,containerRef:r,onRevealTurn:a}){const o=R(),[n,d]=b.useState(null),[f,c]=b.useState(!1),l=b.useRef(null),y=b.useCallback(()=>{var p;const u=s.current,h=r.current;if(!u||!h||t.length===0)return;const v=u.getBoundingClientRect().top;let g=((p=t[0])==null?void 0:p.id)??null;for(const E of t){const j=Se(h,E.id);if(j)if(j.getBoundingClientRect().top-v<=24)g=E.id;else break}d(g)},[t,s,r]);b.useEffect(()=>{const u=s.current;if(!u)return;const h=()=>{l.current===null&&(l.current=window.requestAnimationFrame(()=>{l.current=null,y()}))};return y(),u.addEventListener("scroll",h,{passive:!0}),()=>{u.removeEventListener("scroll",h),l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null)}},[y,s]);const i=b.useCallback(u=>{const h=()=>{const g=Se(r.current,u.id);g&&(g.scrollIntoView({behavior:"smooth",block:"start"}),d(u.id))};a(u.index)?h():window.requestAnimationFrame(()=>window.requestAnimationFrame(h))},[r,a]);return t.length<2?null:e.jsx("nav",{"aria-label":o("chat.turns.aria"),className:"absolute right-1 top-1/2 z-20 hidden -translate-y-1/2 sm:block",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocusCapture:()=>c(!0),onBlurCapture:u=>{u.currentTarget.contains(u.relatedTarget)||c(!1)},children:e.jsxs("div",{className:"relative flex items-center justify-end",children:[e.jsx("ul",{className:A("flex flex-col items-center gap-2 py-2 transition-opacity",f?"opacity-0":"opacity-100"),"aria-hidden":f,children:t.map(u=>e.jsx("li",{children:e.jsx("span",{className:A("block rounded-full transition-all",u.id===n?"h-2 w-2 bg-[hsl(var(--deck-accent))]":"h-1.5 w-1.5 bg-[hsl(var(--deck-ink-faint))]/40")})},u.id))}),e.jsx("div",{className:A("absolute right-0 max-h-[min(70vh,520px)] w-[280px] overflow-y-auto rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]/95 p-1 shadow-xl backdrop-blur transition-all",f?"pointer-events-auto translate-x-0 opacity-100":"pointer-events-none translate-x-2 opacity-0"),children:t.map((u,h)=>e.jsxs("button",{type:"button",onClick:()=>i(u),className:A("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors",u.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:A("mt-1 h-1.5 w-1.5 shrink-0 rounded-full",u.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:o("chat.turns.label",{n:h+1})}),e.jsx("span",{className:"line-clamp-2 text-[12px] leading-4",children:u.preview})]})]},u.id))})]})})}const Ce=80;function ms(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>s.type==="text").map(s=>s.text).join(" "):""}function hs(t){const s=ms(t).replace(/\s+/g," ").trim();return s?s.length>Ce?`${s.slice(0,Ce-1)}…`:s:""}function xs(t){const s=[];for(let r=0;r<t.length;r+=1){const a=t[r];if(a.role!=="user"||!a.id)continue;const o=hs(a.content);o&&s.push({id:a.id,index:r,preview:o})}return s}const ce=120,de=80,ps=96;function W(t){return(t==null?void 0:t.querySelector("[data-radix-scroll-area-viewport]"))??null}function fs({messages:t,isLoading:s}){const r=R(),a=b.useRef(null),o=b.useRef(null),n=b.useRef(!0),d=b.useRef(t.length),f=b.useRef(null),[c,l]=b.useState(ce),[y,i]=b.useState(!1);b.useEffect(()=>{const x=W(a.current);if(!x||!n.current)return;const m=window.requestAnimationFrame(()=>{x.scrollTop=x.scrollHeight});return()=>window.cancelAnimationFrame(m)},[t]),b.useEffect(()=>{const x=W(a.current);if(!x)return;o.current=x;const m=()=>{const N=x.scrollHeight-x.scrollTop-x.clientHeight<=ps;n.current=N,i(!N)};return m(),x.addEventListener("scroll",m,{passive:!0}),()=>x.removeEventListener("scroll",m)},[]),b.useEffect(()=>{const x=d.current;d.current=t.length,l(m=>m>=x&&t.length>x?t.length:Math.min(Math.max(m,ce),t.length||ce))},[t.length]);const u=Math.max(t.length-c,0),h=u,v=b.useMemo(()=>t.slice(h),[t,h]),g=b.useMemo(()=>xs(t),[t]);if(b.useLayoutEffect(()=>{var C;const x=f.current;if(!x)return;const m=W(a.current);if(f.current=null,!!m){if((C=x.element)!=null&&C.isConnected){const N=x.element.getBoundingClientRect().top-x.viewportTop;m.scrollTop+=N;return}m.scrollTop=cs(x.scrollTop,x.scrollHeight,m.scrollHeight)}},[c]),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(ue,{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"}),r("chat.list.loading.eyebrow")]}),e.jsx("h2",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:r("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:r("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((x,m)=>e.jsxs("div",{className:A("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:`${x}%`,animationDelay:`${m*120}ms`}})]},x))})]})});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(ue,{size:44}),e.jsxs("div",{children:[e.jsx("div",{className:"deck-eyebrow text-[hsl(var(--deck-accent))]",children:r("chat.list.empty.eyebrow")}),e.jsx("div",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:r("chat.list.empty.title")}),e.jsx("div",{className:"mt-1 max-w-xs text-[12px] text-[hsl(var(--deck-ink-muted))]",children:r("chat.list.empty.hint")})]})]})});const p=()=>{const x=W(a.current);x&&(n.current=!0,i(!1),x.scrollTo({top:x.scrollHeight,behavior:"smooth"}))},E=()=>{var m;const x=W(a.current);if(x){const C=((m=a.current)==null?void 0:m.querySelector("[data-chat-message-id]"))??null;f.current={element:C,viewportTop:(C==null?void 0:C.getBoundingClientRect().top)??0,scrollHeight:x.scrollHeight,scrollTop:x.scrollTop}}l(C=>ds(C,t.length,de))},j=x=>x>=h?!0:(l(t.length),!1);return e.jsxs("div",{ref:a,className:"relative flex-1 min-h-0",children:[e.jsx(Ge,{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:E,"aria-label":r("chat.list.showEarlierWithRemaining",{count:Math.min(u,de),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:r("chat.list.showEarlier",{count:Math.min(u,de)})})}),v.map((x,m)=>{const C=h+m,N=C>0?t[C-1]:null,$=!N||N.role!==x.role||N.role==="user";return e.jsx(ls,{message:x,showAvatar:$},x.id||`msg-${C}`)})]})}),e.jsx(us,{turns:g,viewportRef:o,containerRef:a,onRevealTurn:j}),y&&e.jsxs("button",{type:"button",onClick:p,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(Ie,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}),r("chat.list.jumpLatest")]})]})}const bs=b.memo(fs),Oe=St,Ue=Ct,He=Et,be=b.forwardRef(({className:t,sideOffset:s=4,...r},a)=>e.jsx(_e,{ref:a,sideOffset:s,className:A("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),...r}));be.displayName=_e.displayName;const gs={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 X(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function vs(t){if(t<60)return`${t}s`;const s=Math.floor(t/60),r=t%60;return r===0?`${s}m`:`${s}m ${r}s`}function ks(){var P;const t=R(),{locale:s}=We(),r=w(S=>S.goal),a=w(S=>S.pauseGoal),o=w(S=>S.resumeGoal),n=w(S=>S.editGoal),d=w(S=>S.clearGoal),[f,c]=b.useState(!1),[l,y]=b.useState(!1),[i,u]=b.useState(""),[h,v]=b.useState(null),[g,p]=b.useState(!1);if(b.useEffect(()=>{c(!1),y(!1),u((r==null?void 0:r.objective)??""),p(!1)},[r==null?void 0:r.goalId]),!r)return null;const E=gs[r.status],j=["active","verifying","paused","blocked"].includes(r.status),x=r.status==="active"||r.status==="verifying",m=r.status==="paused"||r.status==="blocked",C=h!==null,N=async(S,I)=>{v(S);try{await I()}finally{v(null)}},$=()=>{u(r.objective),y(!0),c(!0)},M=async S=>{S.preventDefault();const I=i.trim();if(!I||I===r.objective){y(!1);return}await N("edit",()=>n(I)),y(!1)},V=async()=>{await N("delete",d),p(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(Oe,{delayDuration:250,children:e.jsxs("section",{"aria-label":t("goal.aria.section"),className:"mx-3 mb-1 shrink-0","data-blade-goal-status":r.status,children:[e.jsxs("div",{className:A("flex h-9 items-center gap-2 rounded-lg border px-3 transition-colors","border-[hsl(var(--deck-border))]/60 bg-[hsl(var(--deck-surface))]/80 backdrop-blur-sm",f&&"rounded-b-none border-b-0"),children:[r.status==="complete"?e.jsx(lt,{className:"h-3.5 w-3.5 shrink-0 text-emerald-500"}):e.jsx(ct,{className:A("h-3.5 w-3.5 shrink-0",E.accent)}),e.jsx("span",{className:A("h-1.5 w-1.5 shrink-0 rounded-full",E.dot)}),e.jsx("span",{className:A("shrink-0 text-[10px] font-medium leading-none",E.accent),children:r.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(f?"goal.action.collapse":"goal.action.expand"),className:"min-w-0 flex-1 truncate text-left text-[12px] leading-5 text-[hsl(var(--deck-ink))]/85 outline-none transition-colors hover:text-[hsl(var(--deck-ink))]",onClick:()=>c(S=>!S),"aria-expanded":f,title:r.objective,children:r.objective}),r.tokensUsed>0&&e.jsxs("span",{className:"hidden shrink-0 text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))] sm:inline",children:[X(r.tokensUsed),r.tokenBudget!==void 0&&`/${X(r.tokenBudget)}`]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[x&&e.jsx(Z,{label:t("goal.action.pause"),disabled:C,onClick:()=>void N("pause",a),children:h==="pause"?e.jsx(F,{className:"animate-spin"}):e.jsx(dt,{})}),m&&e.jsx(Z,{label:t("goal.action.resume"),disabled:C,onClick:()=>void N("resume",o),children:h==="resume"?e.jsx(F,{className:"animate-spin"}):e.jsx(ut,{})}),e.jsx(Z,{label:t(j?"goal.action.edit":"goal.action.expand"),disabled:!j&&!f,onClick:j?$:()=>c(S=>!S),children:j?e.jsx(Be,{}):e.jsx(mt,{})}),e.jsx(Z,{label:t("goal.action.delete"),disabled:C,destructive:!0,onClick:()=>p(!0),children:e.jsx(te,{})})]})]}),f&&e.jsx("div",{className:"rounded-b-lg border border-t-0 border-[hsl(var(--deck-border))]/60 bg-[hsl(var(--deck-surface))]/80 px-4 py-3 backdrop-blur-sm",children:l?e.jsxs("form",{onSubmit:M,children:[e.jsx("textarea",{id:"goal-objective",value:i,onChange:S=>u(S.target.value),onKeyDown:S=>{S.key==="Escape"&&y(!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:()=>y(!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(ht,{className:"h-3 w-3"}),t("goal.action.cancel")]}),e.jsxs("button",{type:"submit",disabled:!i.trim()||h==="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:[h==="edit"?e.jsx(F,{className:"h-3 w-3 animate-spin"}):e.jsx(re,{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:r.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(xt,{className:"h-3 w-3"}),X(r.tokensUsed),r.tokenBudget!==void 0&&` / ${X(r.tokenBudget)}`," ",t("goal.metrics.tokens")]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(pt,{className:"h-3 w-3"}),vs(r.timeUsedSeconds)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(xe,{className:"h-3 w-3"}),r.continuationCount===1?t("goal.metrics.continuationOne",{n:r.continuationCount}):t("goal.metrics.continuationMany",{n:r.continuationCount})]})]}),r.completionVerification&&e.jsxs("div",{"data-goal-verification":r.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:["#",r.completionVerification.attempt," ·"," ",r.completionVerification.status.toUpperCase()," ·"," ",((P=r.completionVerification.verifierSessionId)==null?void 0:P.slice(0,12))??"-"]}),r.completionVerification.summary&&e.jsx("p",{className:"mt-1 line-clamp-3 whitespace-pre-wrap opacity-80",children:r.completionVerification.summary}),r.completionVerification.evidenceSha256&&e.jsxs("p",{className:"mt-1 font-mono text-[10px] opacity-60",children:["sha256:",r.completionVerification.evidenceSha256.slice(0,12)]})]}),r.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:r.statusReason})]})})]})}),e.jsx(Ae,{open:g,onOpenChange:p,children:e.jsxs(Me,{className:"max-w-[400px] border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsx(Fe,{children:t("goal.dialog.title")}),e.jsx(Re,{children:t("goal.dialog.description")}),e.jsxs(De,{className:"mt-2",children:[e.jsx("button",{type:"button",onClick:()=>p(!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:h==="delete",onClick:()=>void V(),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:[h==="delete"&&e.jsx(F,{className:"w-3.5 h-3.5 animate-spin"}),t("goal.action.delete")]})]})]})})]})}function Z({label:t,children:s,disabled:r,destructive:a,onClick:o}){return e.jsxs(Ue,{children:[e.jsx(He,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":t,disabled:r,onClick:o,className:A("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",a?"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(be,{side:"top",className:"text-[10px]",children:t})]})}function js(){const t=R(),s=w(c=>c.currentSessionRef),r=w(c=>c.sessions),a=w(c=>c.messages),o=b.useMemo(()=>{var l,y,i,u,h;const c=s?(l=Je(r,s))==null?void 0:l.pendingInteraction:void 0;if(c)return c.type;for(let v=a.length-1;v>=0;v-=1){const g=(y=a[v])==null?void 0:y.agentContent;if(((i=g==null?void 0:g.confirmation)==null?void 0:i.status)==="pending")return"permission";if(((u=g==null?void 0:g.question)==null?void 0:u.status)==="pending")return"question";if(((h=g==null?void 0:g.elicitation)==null?void 0:h.status)==="pending")return"elicitation"}return null},[s,a,r]);if(!o)return null;const n=()=>{const c=document.querySelector(`[data-pending-interaction="${o}"]`);c==null||c.scrollIntoView({block:"center",behavior:"smooth"}),window.setTimeout(()=>c==null?void 0:c.focus(),250)},d=o==="question",f=o==="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(Pe,{className:"h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-[180px] flex-1",children:[e.jsx("div",{className:"text-[11.5px] font-semibold",children:t(d?"interaction.bar.questionTitle":f?"interaction.bar.elicitationTitle":"interaction.bar.permissionTitle")}),e.jsx("div",{className:"mt-0.5 text-[10px] leading-4 text-amber-800 dark:text-amber-300",children:t(d?"interaction.bar.questionHint":f?"interaction.bar.elicitationHint":"interaction.bar.permissionHint")})]}),e.jsxs("button",{type:"button",onClick:n,className:"inline-flex min-h-8 shrink-0 items-center gap-1.5 rounded-md border border-amber-400/80 bg-white/80 px-2.5 text-[10.5px] font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-700 dark:bg-amber-950/70 dark:hover:bg-amber-900",children:[e.jsx(Ie,{className:"h-3 w-3"}),t("interaction.bar.review")]})]})}const ys={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:""},Ee=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),ee=t=>{const s=Math.max(0,Math.ceil(t/1e3)),r=Math.floor(s/60),a=s%60;return r>0?`${r}m ${a}s`:`${a}s`};function ws(){const t=R(),s=w(g=>g.tokenUsage),r=w(g=>g.isStreaming),a=w(g=>g.agentPhase),o=w(g=>g.providerAdmission),n=w(g=>g.providerCircuit),d=w(g=>g.providerRetry),f=w(g=>g.providerStall),c=w(g=>g.actionStationarity),l=ys[a]??"",y=(d==null?void 0:d.delayMs)!==void 0?` · ${Math.max(0,Math.ceil(d.delayMs/1e3))}s`:"",i=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 ${ee(n.retryAfterMs)}`:""}${n.recoveryRemainingMs!==void 0?` · ${ee(n.recoveryRemainingMs)}`:""}`:o?`Provider · Capacity queue ${o.queuePosition}/${Math.max(o.queueDepth,o.queuePosition)} · ${o.scope} · ${ee(o.waitMs)}`:d?d.mode==="bounded_foreground"?`Provider · Bounded recovery · ${d.attempt}/${d.maxRetries} · ${ee(d.recoveryRemainingMs??0)}`:`Provider · ${t("chat.error.action.retryingTask")} · ${d.attempt}/${d.maxRetries}${y}`:f?`${t("status.phase.providerStall")} · ${Math.ceil(f.durationMs/1e3)}s / ${Math.ceil(f.timeoutMs/1e3)}s`:l?t(l):"",u=s.maxContextTokens>0?Math.round(s.totalTokens/s.maxContextTokens*100):0,h=Math.min(u,100),v=u>95?"danger":u>80?"warn":"safe";return e.jsxs("div",{className:"flex items-center gap-4 border-t border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/70 px-5 py-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm",children:[e.jsxs("div",{className:"flex gap-3 items-center",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:A("text-[12px] font-medium",v==="safe"&&"text-[hsl(var(--deck-ink))]",v==="warn"&&"text-amber-600 dark:text-amber-400",v==="danger"&&"text-red-600 dark:text-red-400"),children:Ee(s.totalTokens)}),e.jsxs("span",{className:"text-[hsl(var(--deck-ink-faint))]",children:["/ ",Ee(s.maxContextTokens)]})]}),s.isDefaultMaxTokens&&e.jsx(Oe,{children:e.jsxs(Ue,{children:[e.jsx(He,{asChild:!0,children:e.jsx(ft,{className:"h-3 w-3 cursor-help text-[hsl(var(--deck-ink-faint))]"})}),e.jsx(be,{side:"top",className:"max-w-[220px]",children:e.jsx("p",{className:"text-xs",children:t("status.tokenLimitTooltip")})})]})}),e.jsxs("div",{className:"relative h-2 w-32 overflow-hidden rounded-sm border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]","aria-hidden":"true",children:[e.jsx("div",{className:A("absolute inset-y-0 left-0 transition-[width] duration-300",v==="safe"&&"bg-[hsl(var(--deck-accent))]",v==="warn"&&"bg-amber-500",v==="danger"&&"bg-red-500"),style:{width:`${h}%`}}),e.jsx("div",{className:"flex absolute inset-0 pointer-events-none",children:[25,50,75].map(g=>e.jsx("span",{className:"absolute inset-y-0 w-px bg-[hsl(var(--deck-canvas-veil))]/60",style:{left:`${g}%`}},g))})]}),e.jsxs("span",{className:A("w-10 text-right tabular-nums text-[hsl(var(--deck-ink-faint))]",v==="warn"&&"text-amber-600 dark:text-amber-400",v==="danger"&&"text-red-600 dark:text-red-400"),children:[u,"%"]})]}),e.jsx("div",{className:"flex-1"}),r&&i&&e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("span",{className:"deck-pulse-dot"}),e.jsx("span",{className:"text-[hsl(var(--deck-accent))]",children:i})]})]})}function Ns(t){const s=[...t].reverse().find(o=>o.role==="user");if(!s)return null;if(typeof s.content=="string")return{content:s.content,attachments:[]};const r=s.content.filter(o=>o.type==="text").map(o=>o.text).join(`
|
|
18
|
-
`),a=s.content.filter(o=>o.type==="image_url").map((o,n)=>{var f;const d=((f=o.image_url.url.match(/^data:([^;,]+)[;,]/))==null?void 0:f[1])??"application/octet-stream";return{id:`recovery-${s.id}-${n}`,name:`attachment-${n+1}`,mimeType:d,dataUrl:o.image_url.url}});return{content:r,attachments:a}}function Ms(){var L;const t=R(),s=w(k=>k.messages),r=w(k=>k.currentSessionRef),a=w(k=>k.isStreaming),o=w(k=>k.isStopping),n=w(k=>k.sessionEventConnectionState),d=w(k=>k.pendingSteeringCount),f=w(k=>k.pendingInputDelivery),c=w(k=>k.recoveredSteeringCount),l=w(k=>k.isLoading),y=w(k=>k.error),i=w(k=>k.errorContext),u=w(k=>k.sessions),h=w(k=>k.sendMessage),v=w(k=>k.abortSession),g=w(k=>k.retryTask),p=w(k=>k.retryingTaskKeys),E=me(k=>k.openSettings),j=w(k=>k.reconnectSessionEvents),x=w(k=>k.clearError),[m,C]=b.useState(null),N=r?u.find(k=>k.sessionId===r.sessionId&&k.projectPath===r.projectPath):void 0,$=!!y&&((i==null?void 0:i.kind)==="navigation"||!(i!=null&&i.sessionRef)||Te(i.sessionRef,r)),M=(i==null?void 0:i.failureCode)??((L=N==null?void 0:N.taskFailure)==null?void 0:L.code),V=(i==null?void 0:i.kind)==="execution"&&M?t(wt(M)):y==="queue_full"?t("chat.error.queueFull"):y==="turn_unavailable"||y==="turn_active"?t("chat.error.turnChanged"):y,P=n==="connecting"||n==="reconnecting",S=a&&n!=="connected",I=r?`session:${J(r)}`:"session:temporary",U=b.useMemo(()=>Ns(s),[s]),ie=r?J(r):"temporary-session",q=!!(r&&(N!=null&&N.taskRetryAvailable)&&(!M||Nt(M)))&&((i==null?void 0:i.kind)==="execution"||(i==null?void 0:i.kind)==="task_action"),z=(i==null?void 0:i.kind)==="execution"&&(M==="authentication"||M==="permission"||M==="model_unavailable"),H=r?p.includes(J(r)):!1;b.useEffect(()=>{C(null)},[ie]);const Q=async k=>h({content:k.content,modelId:k.modelId,reasoningEffort:k.reasoningEffort,serviceTier:k.serviceTier,responseVerbosity:k.responseVerbosity,communicationStyle:k.communicationStyle,...k.outputSchema?{outputSchema:k.outputSchema}:{},attachments:k.attachments.map(B=>({type:"image",content:B.dataUrl,mimeType:B.mimeType,name:B.name}))}),Y=()=>v(),T=async()=>{if(z){x(),E("models");return}if(q&&r){x(),await g(r).catch(()=>{});return}if((i==null?void 0:i.kind)==="execution"&&U){C({...U,revision:Date.now()}),x();return}x(),requestAnimationFrame(()=>Ye())},_=q?t(H?"chat.error.action.retryingTask":"chat.error.action.retryTask"):z?t("chat.error.action.checkModels"):(i==null?void 0:i.kind)==="execution"&&U?t("chat.error.action.editResend"):(i==null?void 0:i.kind)==="submission"?t("chat.error.action.returnDraft"):null;return e.jsxs("div",{className:"flex h-full flex-col bg-[hsl(var(--deck-canvas))]",children:[$&&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(Pe,{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((i==null?void 0:i.kind)==="submission"?"chat.error.title.submission":(i==null?void 0:i.kind)==="execution"?"chat.error.title.execution":(i==null?void 0:i.kind)==="navigation"?"chat.error.title.navigation":"chat.error.title.generic")})," ",V]}),_&&e.jsxs("button",{type:"button",onClick:()=>void T(),disabled:H,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:[q?H?e.jsx(F,{className:"h-3 w-3 animate-spin"}):e.jsx(xe,{className:"h-3 w-3"}):e.jsx(Be,{className:"h-3 w-3"}),_]}),e.jsx("button",{type:"button",onClick:x,"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:"✕"})]}),(P||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:[P?e.jsx(F,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):e.jsx(bt,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 flex-1",children:t(P?"chat.connection.reconnecting":"chat.connection.offline")}),n==="offline"&&e.jsxs("button",{type:"button",onClick:()=>void j().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(gt,{className:"h-3 w-3"}),t("chat.connection.retry")]})]}),e.jsx(Tt,{}),e.jsx(bs,{messages:s,isLoading:l},r?J(r):"temporary-session"),e.jsx(js,{}),e.jsx(ks,{}),e.jsx(Qe,{draftKey:I,draft:m==null?void 0:m.content,draftAttachments:m==null?void 0:m.attachments,draftRevision:m==null?void 0:m.revision,onSend:Q,onAbort:Y,disabled:l||S,isStreaming:a,isStopping:o,pendingSteeringCount:d,pendingInputDelivery:f,recoveredSteeringCount:c,workspacePath:r==null?void 0:r.projectPath},I),e.jsx(ws,{})]})}export{Ms as ChatView};
|