zen-code 4.7.4 → 4.8.1
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/app.js +271 -0
- package/dist/chunk-0fhpz98a.js +2 -0
- package/dist/chunk-15smn69q.js +31 -0
- package/dist/chunk-3ep2tag7.js +2 -0
- package/dist/chunk-3jek9sxm.js +2 -0
- package/dist/chunk-3n2b4eb4.js +2 -0
- package/dist/chunk-3znrwnd8.js +1 -0
- package/dist/chunk-4b8yaknt.js +1 -0
- package/dist/chunk-5fqt5yg1.js +81 -0
- package/dist/chunk-5nzs0q25.js +1 -0
- package/dist/chunk-5wn1nfqy.js +6 -0
- package/dist/chunk-6ty22kkt.js +4 -0
- package/dist/chunk-70a0e941.js +1 -0
- package/dist/chunk-7dp8kq2f.js +2 -0
- package/dist/chunk-8nhayyat.js +1 -0
- package/dist/chunk-9k57afdm.js +2 -0
- package/dist/chunk-9kc9cea3.js +7 -0
- package/dist/chunk-bgpcx3bm.js +2 -0
- package/dist/chunk-bjywwcgn.js +26 -0
- package/dist/chunk-c9q11tk2.js +88 -0
- package/dist/chunk-cga0m5sy.js +1 -0
- package/dist/chunk-cze71w02.js +2 -0
- package/dist/chunk-czz2fs2w.js +7 -0
- package/dist/chunk-dh3jz71n.js +1 -0
- package/dist/chunk-e0sqjq2h.js +1 -0
- package/dist/chunk-efhkdw2z.js +1 -0
- package/dist/chunk-ew7249h9.js +1 -0
- package/dist/chunk-h5nnz4dy.js +1 -0
- package/dist/chunk-hww94vjn.js +1 -0
- package/dist/chunk-j1n8jp1w.js +253 -0
- package/dist/chunk-j204fejq.js +1 -0
- package/dist/chunk-jkbtx9va.js +2 -0
- package/dist/chunk-k67epfhc.js +1 -0
- package/dist/chunk-kbs4px1b.js +6 -0
- package/dist/chunk-keqk70wm.js +2 -0
- package/dist/chunk-kxk71nn0.js +1 -0
- package/dist/chunk-mg8zpgaz.js +1 -0
- package/dist/chunk-n1d8xx5k.js +2 -0
- package/dist/chunk-ndtwq2zx.js +2 -0
- package/dist/chunk-pdkbrds7.js +1 -0
- package/dist/chunk-q8arjxg1.js +23 -0
- package/dist/chunk-rdc9pxf6.js +1 -0
- package/dist/chunk-rrkzfahh.js +91 -0
- package/dist/chunk-s3fyfrka.js +2 -0
- package/dist/chunk-sft6ep0c.js +310 -0
- package/dist/chunk-vc384abg.js +3 -0
- package/dist/chunk-vjj00e3e.js +6 -0
- package/dist/chunk-vkng13p1.js +424 -0
- package/dist/chunk-wbn1hbxf.js +1 -0
- package/dist/chunk-wwn7gw8g.js +274 -0
- package/dist/chunk-yaa4eesd.js +2 -0
- package/dist/chunk-yvhq458c.js +25 -0
- package/dist/cli.js +2 -0
- package/dist/nonInteractive.js +4 -0
- package/dist/zen-keyboard.js +3 -0
- package/package.json +88 -87
- package/LICENSE +0 -201
- package/dist/FileSystemPluginStore-ChortK7z.mjs +0 -64
- package/dist/FileSystemSkillStore-Dl5briBv.mjs +0 -108
- package/dist/MultiLineTextInput-CL8nm9nv.mjs +0 -24492
- package/dist/_commonjsHelpers-DQNKXVTB.mjs +0 -33
- package/dist/app-CK3nD8Gj.mjs +0 -22428
- package/dist/checkpoint-C5AFBYE--CczNxXBB.mjs +0 -355
- package/dist/checkpoint-DxiUsHMy-B5iaccT2.mjs +0 -394
- package/dist/cli.mjs +0 -57
- package/dist/devtools-CzaVuYnh.mjs +0 -2667
- package/dist/graphBuilder-DJoMXf6J.mjs +0 -28909
- package/dist/index-BPG5Np-8.mjs +0 -144
- package/dist/index-Dxfhvdx8.mjs +0 -23
- package/dist/index-F6_SKYUd.mjs +0 -463
- package/dist/load-iYJqYrjn.mjs +0 -119
- package/dist/memories-CaHDnBK1.mjs +0 -115
- package/dist/metadata-XVTVXthy.mjs +0 -6
- package/dist/nonInteractive.mjs +0 -55
- package/dist/pg-adapter-BFtir1GE-BbUXBpaX.mjs +0 -60
- package/dist/queue-DySatFkr-CG2GdO4P.mjs +0 -106
- package/dist/remote-threads-CrG03ZS7-C9duTCnB.mjs +0 -157
- package/dist/shallow-G4eKoZ7M.mjs +0 -331
- package/dist/shallow-checkpoint-BEhTdp7z-DfHxnfoU.mjs +0 -383
- package/dist/sqlite-adapter-oBA95xba-BrBWorSV.mjs +0 -82
- package/dist/subTasks-DNjIN4eU.mjs +0 -18
- package/dist/zen-code.mjs +0 -3
- package/dist/zen-keyboard.mjs +0 -13
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import{xa as Q}from"./chunk-n1d8xx5k.js";import{SystemMessage as U}from"@langchain/core/messages";var V=`## Memory System
|
|
2
|
+
|
|
3
|
+
你可以访问一个包含之前任务和经验知识的记忆库。
|
|
4
|
+
|
|
5
|
+
{memories_locations}
|
|
6
|
+
|
|
7
|
+
**可用的记忆:**
|
|
8
|
+
|
|
9
|
+
{memories_list}
|
|
10
|
+
|
|
11
|
+
**如何使用记忆:**
|
|
12
|
+
|
|
13
|
+
记忆采用 **渐进式披露** 模式 - 你知道它们存在(上面有元数据),但只在需要时才读取完整内容:
|
|
14
|
+
|
|
15
|
+
1. **识别适用的记忆**: 检查当前任务是否匹配任何记忆的描述或标签
|
|
16
|
+
2. **读取完整记忆内容**: 使用 read_file 工具,路径见上面的列表
|
|
17
|
+
3. **应用知识**: 使用记忆中的信息来指导当前任务
|
|
18
|
+
|
|
19
|
+
**何时使用记忆:**
|
|
20
|
+
- 遇到与之前任务类似的问题时
|
|
21
|
+
- 需要回忆项目特定的约定或模式时
|
|
22
|
+
- 需要参考之前的解决方案或决策时
|
|
23
|
+
- 需要记住配置或设置细节时
|
|
24
|
+
|
|
25
|
+
记住:记忆是帮助你变得更强大和一致的工具。有疑问时,检查是否有相关的记忆存在!
|
|
26
|
+
`;class W{name="MemoriesMiddleware";stateSchema=void 0;contextSchema=void 0;tools=[];memoriesDir;assistantId;projectMemoriesDir;userMemoriesDisplay;systemPromptTemplate;constructor(k={}){if(this.memoriesDir=k.memoriesDir,this.assistantId=k.assistantId,this.projectMemoriesDir=k.projectMemoriesDir||"./.claude/memories",this.memoriesDir&&!this.assistantId)console.warn("user memories directory is provided, but assistant id is not provided");if(this.assistantId)this.userMemoriesDisplay=`~/.claude/${this.assistantId}/memories`;this.systemPromptTemplate=V}formatMemoriesLocations(){let k=[];if(this.userMemoriesDisplay)k.push(`**User Memories**: \`${this.userMemoriesDisplay}\``);if(this.projectMemoriesDir)k.push(`**Project Memories**: \`${this.projectMemoriesDir}\` (overrides user memories)`);return k.join(`
|
|
27
|
+
`)}formatMemoriesList(k){if(!k.length){let v=[`${this.userMemoriesDisplay}/`];if(this.projectMemoriesDir)v.push(`${this.projectMemoriesDir}/`);return`(No memories available yet. You can create memories in ${v.join(" or ")})`}let J=["architecture","bug-fix","workflow","configuration","optimization"],F=new Map;for(let v of k){if(!F.has(v.category))F.set(v.category,[]);F.get(v.category).push(v)}let z=[];for(let v of J){let D=F.get(v);if(!D||D.length===0)continue;z.push(`**${v.charAt(0).toUpperCase()+v.slice(1)} Memories:**`);let G={high:0,medium:1,low:2};D.sort((x,H)=>{let K=G[x.priority||"medium"]??1,N=G[H.priority||"medium"]??1;if(K!==N)return K-N;return x.name.localeCompare(H.name)});for(let x of D){let H=x.tags.length>0?` [${x.tags.join(", ")}]`:"";z.push(`- **${x.name}**: ${x.description}${H}`),z.push(` → Read \`${x.path}\` for full content`)}z.push("")}return z.join(`
|
|
28
|
+
`)}async wrapModelCall(k,J){let F=Q(this.memoriesDir,this.projectMemoriesDir),z=this.formatMemoriesLocations(),v=this.formatMemoriesList(F),D=this.systemPromptTemplate.replace("{memories_locations}",z).replace("{memories_list}",v),G;if(k.systemPrompt)G=k.systemPrompt+`
|
|
29
|
+
|
|
30
|
+
`+D;else G=D;let x=new U(G),H={...k,systemMessage:x};return await J(H)}}
|
|
31
|
+
export{W as wa};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{M as c}from"./chunk-keqk70wm.js";import{R,T as D}from"./chunk-9kc9cea3.js";import{ca as t,da as B,ea as q,ka as x,la as E,ma as m}from"./chunk-wwn7gw8g.js";import{nb as S}from"./chunk-cze71w02.js";var i=30000;function V(){let z=new AbortController,G=setTimeout(()=>{z.abort(),G=null},i);return{controller:z,cleanup:()=>{if(G!==null)clearTimeout(G),G=null}}}async function a(z,G){let{controller:N,cleanup:Q}=V();try{let H=await fetch(`${G}/models`,{method:"GET",headers:{Authorization:`Bearer ${z}`,"Content-Type":"application/json"},signal:N.signal});if(!H.ok){let Z=await H.text();throw Error(`OpenAI API error (${H.status}): ${H.statusText}`)}return(await H.json()).data.map((Z)=>({id:Z.id,name:Z.id,provider:"openai"})).sort((Z,g)=>Z.id.localeCompare(g.id))}catch(H){if(H.name==="AbortError")throw Error("OpenAI API request timeout (30s)");throw H}finally{Q()}}async function n(z,G){let{controller:N,cleanup:Q}=V();try{let H=await fetch(`${G}/v1/models`,{method:"GET",headers:{"x-api-key":z,"anthropic-version":"2023-06-01","Content-Type":"application/json"},signal:N.signal});if(!H.ok){let Z=await H.text();throw Error(`Anthropic API error (${H.status}): ${H.statusText}`)}return(await H.json()).data.map((Z)=>({id:Z.id,name:Z.display_name||Z.id,provider:"anthropic"}))}catch(H){if(H.name==="AbortError")throw Error("Anthropic API request timeout (30s)");throw H}finally{Q()}}async function d(z,G){let{controller:N,cleanup:Q}=V();try{let H=await fetch(G+"/v1beta/models",{method:"GET",headers:{Authorization:"Bearer "+z},signal:N.signal});if(!H.ok)throw Error(`Gemini API error (${H.status}): Invalid API key`);return(await H.json()).models.map((Z)=>({id:Z.name,name:Z.displayName||Z.name,provider:"gemini"}))}catch(H){if(H.name==="AbortError")throw Error("Gemini API request timeout (30s)");throw H}finally{Q()}}function zz({provider:z,enabled:G=!0}){return R({queryKey:D.models.list(z?.id||"unknown"),queryFn:async()=>{if(!z||!z.apiKey||!z.baseUrl)return[];try{if(z.type==="openai")return await a(z.apiKey,z.baseUrl);else if(z.type==="anthropic")return await n(z.apiKey,z.baseUrl);else if(z.type==="gemini")return await d(z.apiKey,z.baseUrl);return[]}catch(N){throw N}},enabled:G&&!!z&&!!z.apiKey&&!!z.baseUrl,staleTime:600000,retry:(N,Q)=>{if(Q?.message?.includes("timeout"))return N<2;if(Q?.name==="TypeError"||Q?.message?.includes("fetch"))return N<2;return!1}})}var J=S(t(),1);var $=S(E(),1),L=[{id:"openai",label:"OpenAI",defaultUrl:"https://api.openai.com/v1"},{id:"anthropic",label:"Anthropic",defaultUrl:"https://api.anthropic.com"},{id:"gemini",label:"Gemini",defaultUrl:"https://generativelanguage.googleapis.com/v1beta"}],_=[{key:"id",label:"ID",placeholder:"my-provider"},{key:"name",label:"Name",placeholder:"My Provider"},{key:"apiKey",label:"API Key",placeholder:"sk-xxx..."},{key:"url",label:"URL",placeholder:"https://api.xxx.com"}],o=({provider:z,onCancel:G,onSave:N})=>{let{config:Q}=c(),[H,O]=J.useState({id:z?.id||"",type:z?.type||"openai",name:z?.id||"",apiKey:z?.apiKey||"",baseUrl:z?.baseUrl||L[0].defaultUrl}),[Z,g]=J.useState({}),[U,v]=J.useState(0),w=J.useRef(H),C=J.useRef(U),f=J.useRef(Z);J.useEffect(()=>{w.current=H},[H]),J.useEffect(()=>{C.current=U},[U]),J.useEffect(()=>{f.current=Z},[Z]);let u=J.useMemo(()=>{return L.find((X)=>X.id===H.type)||L[0]},[H.type]),k=J.useCallback(()=>{let X=w.current,W={},A=Q?.providers||[];if(!X.id||X.id.length<3||X.id.length>32)W.id="ID 必须为 3-32 个字符";else if(!/^[a-zA-Z0-9_]+$/.test(X.id))W.id="ID 只能包含字母、数字和下划线";else if(A.some((M)=>M.id===X.id&&M.id!==z?.id))W.id="ID 已存在";if(!X.name||X.name.length<2||X.name.length>50)W.name="名称必须为 2-50 个字符";if(!X.apiKey)W.apiKey="API Key 不能为空";if(!X.baseUrl)W.baseUrl="Base URL 不能为空";else if(!X.baseUrl.startsWith("https://"))W.baseUrl="Base URL 必须以 https:// 开头";return g(W),Object.keys(W).length===0},[Q?.providers,z?.id]),h=J.useRef(k);J.useEffect(()=>{h.current=k},[k]);let K=J.useCallback(()=>{if(h.current())N(w.current)},[N]),P=J.useCallback(()=>{let X=w.current.type,A=(L.findIndex((Y)=>Y.id===X)+1)%L.length,M=L[A];O((Y)=>({...Y,type:M.id,baseUrl:Y.baseUrl||M.defaultUrl}))},[]),b=J.useCallback((X)=>{let W=C.current,A=X==="next"?(W+1)%_.length:(W-1+_.length)%_.length;v(A)},[]),p=(X)=>{let W=_[X];if(W.key==="url")return"baseUrl";return W.key},I=J.useRef(K),T=J.useRef(b),F=J.useRef(P),y=J.useRef(G);J.useEffect(()=>{I.current=K},[K]),J.useEffect(()=>{T.current=b},[b]),J.useEffect(()=>{F.current=P},[P]),J.useEffect(()=>{y.current=G},[G]),x((X,W)=>{if(W.return)I.current();else if(W.escape)y.current();else if(W.tab)T.current(W.shift?"prev":"next");else if(X===" ")F.current()},{isActive:!0});let j=(X)=>{let W=_[X],A=p(X),M=Z[A],Y=U===X;return $.jsxDEV(B,{marginBottom:0,children:[$.jsxDEV(q,{color:Y?"cyan":M?"red":"gray",children:[W.label,": "]},void 0,!0,void 0,this),Y?$.jsxDEV(B,{width:50,children:$.jsxDEV(m,{value:H[A],onChange:(l)=>O((s)=>({...s,[A]:l})),onSubmit:K,placeholder:W.placeholder,maxVisibleLines:1,showCursor:!0},void 0,!1,void 0,this)},void 0,!1,void 0,this):$.jsxDEV(q,{children:H[A]||W.placeholder},void 0,!1,void 0,this),M&&$.jsxDEV(q,{color:"red",children:[" ",M]},void 0,!0,void 0,this)]},W.key,!0,void 0,this)};return $.jsxDEV(B,{flexDirection:"column",paddingX:2,children:[$.jsxDEV(B,{marginTop:1,flexDirection:"column",gap:1,children:[j(0),$.jsxDEV(B,{marginBottom:0,children:[$.jsxDEV(q,{color:U===0?"cyan":"gray",children:"Type: "},void 0,!1,void 0,this),$.jsxDEV(q,{color:"cyan",bold:!0,children:u.label},void 0,!1,void 0,this),$.jsxDEV(q,{color:"gray",children:" [空格切换]"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j(1),j(2),j(3)]},void 0,!0,void 0,this),$.jsxDEV(B,{marginTop:1,children:$.jsxDEV(q,{color:"gray",dimColor:!0,children:[$.jsxDEV(q,{color:"cyan",children:"Enter"},void 0,!1,void 0,this)," 保存 ",$.jsxDEV(q,{color:"cyan",children:"Tab"},void 0,!1,void 0,this)," 切换字段"," ",$.jsxDEV(q,{color:"cyan",children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},Nz=o;
|
|
2
|
+
export{zz as D,Nz as E};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ca as JJ}from"./chunk-wwn7gw8g.js";import{nb as g,ob as y}from"./chunk-cze71w02.js";var C=y((XJ,E)=>{var f="Expected a function",w=NaN,V="[object Symbol]",S=/^\s+|\s+$/g,v=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,d=/^0o[0-7]+$/i,c=parseInt,r=typeof global=="object"&&global&&global.Object===Object&&global,u=typeof self=="object"&&self&&self.Object===Object&&self,o=r||u||Function("return this")(),s=Object.prototype,n=s.toString,l=Math.max,i=Math.min,N=function(){return o.Date.now()};function a(J,Z,$){var Y,j,G,B,Q,P,q=0,F=!1,U=!1,W=!0;if(typeof J!="function")throw TypeError(f);if(Z=I(Z)||0,L($))F=!!$.leading,U="maxWait"in $,G=U?l(I($.maxWait)||0,Z):G,W="trailing"in $?!!$.trailing:W;function _(K){var H=Y,A=j;return Y=j=void 0,q=K,B=J.apply(A,H),B}function h(K){return q=K,Q=setTimeout(D,Z),F?_(K):B}function b(K){var H=K-P,A=K-q,R=Z-H;return U?i(R,G-A):R}function T(K){var H=K-P,A=K-q;return P===void 0||H>=Z||H<0||U&&A>=G}function D(){var K=N();if(T(K))return z(K);Q=setTimeout(D,b(K))}function z(K){if(Q=void 0,W&&Y)return _(K);return Y=j=void 0,B}function m(){if(Q!==void 0)clearTimeout(Q);q=0,Y=P=j=Q=void 0}function k(){return Q===void 0?B:z(N())}function O(){var K=N(),H=T(K);if(Y=arguments,j=this,P=K,H){if(Q===void 0)return h(P);if(U)return Q=setTimeout(D,Z),_(P)}if(Q===void 0)Q=setTimeout(D,Z);return B}return O.cancel=m,O.flush=k,O}function L(J){var Z=typeof J;return!!J&&(Z=="object"||Z=="function")}function t(J){return!!J&&typeof J=="object"}function e(J){return typeof J=="symbol"||t(J)&&n.call(J)==V}function I(J){if(typeof J=="number")return J;if(e(J))return w;if(L(J)){var Z=typeof J.valueOf=="function"?J.valueOf():J;J=L(Z)?Z+"":Z}if(typeof J!="string")return J===0?J:+J;J=J.replace(S,"");var $=p.test(J);return $||d.test(J)?c(J.slice(2),$?2:8):v.test(J)?w:+J}E.exports=a});var X=g(JJ(),1),M=g(C(),1);function YJ(J=!1){if(typeof J!=="boolean")throw Error("defaultValue must be `true` or `false`");let[Z,$]=X.useState(J),Y=X.useCallback(()=>{$(!0)},[]),j=X.useCallback(()=>{$(!1)},[]),G=X.useCallback(()=>{$((B)=>!B)},[]);return{value:Z,setValue:$,setTrue:Y,setFalse:j,toggle:G}}var x=typeof window<"u"?X.useLayoutEffect:X.useEffect;function KJ(J,Z){let $=X.useRef(J);x(()=>{$.current=J},[J]),X.useEffect(()=>{if(Z===null)return;let Y=setInterval(()=>{$.current()},Z);return()=>{clearInterval(Y)}},[Z])}function QJ(J){let Z=X.useRef(()=>{throw Error("Cannot call an event handler while rendering.")});return x(()=>{Z.current=J},[J]),X.useCallback((...$)=>{var Y;return(Y=Z.current)==null?void 0:Y.call(Z,...$)},[Z])}function ZJ(J){let Z=X.useRef(J);Z.current=J,X.useEffect(()=>()=>{Z.current()},[])}function $J(J,Z=500,$){let Y=X.useRef();ZJ(()=>{if(Y.current)Y.current.cancel()});let j=X.useMemo(()=>{let G=M.default(J,Z,$),B=(...Q)=>{return G(...Q)};return B.cancel=()=>{G.cancel()},B.isPending=()=>{return!!Y.current},B.flush=()=>{return G.flush()},B},[J,Z,$]);return X.useEffect(()=>{Y.current=M.default(J,Z,$)},[J,Z,$]),j}function jJ(J,Z,$){let Y=($==null?void 0:$.equalityFn)??((q,F)=>q===F),j=J instanceof Function?J():J,[G,B]=X.useState(j),Q=X.useRef(j),P=$J(B,Z,$);if(!Y(Q.current,j))P(j),Q.current=j;return[G,P]}function BJ(){let J=X.useRef(!1);return X.useEffect(()=>{return J.current=!0,()=>{J.current=!1}},[]),X.useCallback(()=>J.current,[])}function GJ(J,Z){let $=X.useRef(J);x(()=>{$.current=J},[J]),X.useEffect(()=>{if(!Z&&Z!==0)return;let Y=setTimeout(()=>{$.current()},Z);return()=>{clearTimeout(Y)}},[Z])}
|
|
2
|
+
export{YJ as F,KJ as G,QJ as H,ZJ as I,jJ as J,BJ as K,GJ as L};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{q as U}from"./chunk-vjj00e3e.js";import"./chunk-s3fyfrka.js";import{R as g,T as D}from"./chunk-9kc9cea3.js";import{ca as f,da as w,ea as X,la as L,pa as V}from"./chunk-wwn7gw8g.js";import{nb as v}from"./chunk-cze71w02.js";var A=v(f(),1);function E(J){let{historyList:O,refreshHistoryList:Y,setHistoryFilter:Z}=U(),W=J?JSON.stringify(J):null,_=W?["history","list",W]:D.history.list();return g({queryKey:_,queryFn:async()=>{if(J)Z(J);return await Y(),O},staleTime:60000})}var G=v(L(),1),C=({onClose:J})=>{let{currentChatId:O,toHistoryChat:Y,createNewChat:Z,refreshHistoryList:W,historyFilter:_}=U(),b=A.useMemo(()=>({metadata:{path:process.cwd()}}),[]),{data:B=[],refetch:y}=E(b),p=A.useRef(W);A.default.useEffect(()=>{p.current=W},[W]);let j=(z)=>z.toLocaleTimeString(),H=(z)=>{switch(z){case"idle":return{emoji:"\uD83D\uDFE2",color:"green",text:"空闲"};case"busy":return{emoji:"\uD83D\uDFE1",color:"yellow",text:"忙碌"};case"interrupted":return{emoji:"\uD83D\uDFE0",color:"orange",text:"中断"};case"error":return{emoji:"\uD83D\uDD34",color:"red",text:"错误"};default:return{emoji:"⚪",color:"gray",text:z}}},N=A.useCallback(async()=>{return B},[B]),P=A.useCallback((z,$,Q)=>{let S=H(z.status),M=z.thread_id===O,m=j(new Date(z.updated_at)),k=Q?">":" ",x=M?"▶":" ",T=(()=>{if(M)return{color:"green",bold:!0};else if(Q)return{color:"cyanBright",bold:!0};else return{color:S.color,bold:!1}})();return G.jsxDEV(w,{children:[G.jsxDEV(X,{bold:T.bold,color:T.color,children:[k,x," ",$+1,". ",z.thread_id.slice(-8)]},void 0,!0,void 0,this),G.jsxDEV(w,{flexGrow:1},void 0,!1,void 0,this),G.jsxDEV(X,{dimColor:!0,children:m},void 0,!1,void 0,this)]},z.thread_id,!0,void 0,this)},[O]),F=A.useCallback((z)=>{return z.thread_id===O},[O]),R=A.useCallback(async(z)=>{if(z.value==="new_chat")Z({});else Y(z);J()},[Z,Y,J]),q=A.useCallback((z)=>{let $=z.find((Q)=>Q.thread_id===O);return $?G.jsxDEV(X,{color:"gray",dimColor:!0,children:["当前: ",G.jsxDEV(X,{color:"green",children:$.thread_id.substring(0,8)},void 0,!1,void 0,this),G.jsxDEV(X,{children:[" ",_?.metadata?.path]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):null},[O,_]),K=A.useMemo(()=>({}),[]),I=A.useMemo(()=>({id:"history",title:"历史记录",icon:"\uD83D\uDCDC",dataSource:N,searchable:!0,searchFields:["thread_id"],searchPlaceholder:"搜索对话 ID...",filterable:!1,filters:[],defaultFilter:"all",itemHeight:1,visibleCount:10,renderItem:P,isSelected:F,onSelect:R,showCount:!0,statusInfo:q,keyMap:K}),[N,P,F,R,q,K]);return G.jsxDEV(V,{config:I,onClose:J},void 0,!1,void 0,this)},e=C;export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{M as k}from"./chunk-keqk70wm.js";import"./chunk-9kc9cea3.js";import{ca as R,da as g,ea as r,ka as B,la as b}from"./chunk-wwn7gw8g.js";import"./chunk-dh3jz71n.js";import"./chunk-yaa4eesd.js";import"./chunk-jkbtx9va.js";import"./chunk-kbs4px1b.js";import"./chunk-9k57afdm.js";import{nb as m}from"./chunk-cze71w02.js";var w=m(R(),1);var u=m(R(),1);var n=m(b(),1),H=({field:e,value:t,isFocused:o})=>n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:t?"green":"gray",bold:o,children:t?"ON":"OFF"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J=({field:e,value:t,isFocused:o})=>n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:o?"yellow":void 0,bold:o,children:t??e.min??0},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:" ms"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L=({field:e,value:t,isFocused:o})=>{let a=e.options?.find((y)=>y.value===t);return n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:o?"yellow":void 0,bold:o,children:a?.label||t},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},Y=({field:e,value:t,isFocused:o})=>n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:o?"yellow":"gray",bold:o,children:t||e.placeholder||"-"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q=(e)=>{switch(e.field.type){case"toggle":return n.jsxDEV(H,{...e},void 0,!1,void 0,this);case"number":return n.jsxDEV(J,{...e},void 0,!1,void 0,this);case"select":return n.jsxDEV(L,{...e},void 0,!1,void 0,this);case"input":return n.jsxDEV(Y,{...e},void 0,!1,void 0,this);default:return n.jsxDEV(r,{color:"red",children:"Unknown"},void 0,!1,void 0,this)}},M=q;var x=[{key:"compact_mode",label:"紧凑模式",type:"toggle",group:"显示",tab:"General",help:"紧凑显示消息 (Ctrl+O)"},{key:"show_detailed_info",label:"系统信息",type:"toggle",group:"显示",tab:"General",help:"显示系统资源信息"},{key:"enable_thinking",label:"思考模式",type:"toggle",group:"模型",tab:"General",help:"启用模型思考"},{key:"stream_refresh_interval",label:"流刷新间隔",type:"number",group:"模型",tab:"General",min:50,max:1000,step:50,help:"流刷新间隔 (ms)"}],S=(()=>{let e=new Map;return x.forEach((t)=>{let o=t.tab||"General";if(!e.has(o))e.set(o,{id:o,label:o,icon:"⚙"})}),Array.from(e.values())})(),D=(()=>{let e=new Map;return x.forEach((t)=>{if(!e.has(t.group))e.set(t.group,{id:t.group,label:t.group,fields:[]});e.get(t.group).fields.push(t)}),Array.from(e.values())})();function z(e){return x.filter((t)=>(t.tab||"General")===e)}function _(e){let t=z(e),o=new Map;return t.forEach((a)=>{if(!o.has(a.group))o.set(a.group,{id:a.group,label:a.group,fields:[]});o.get(a.group).fields.push(a)}),Array.from(o.values())}var f=m(b(),1);function K(e){switch(e.type){case"toggle":return!1;case"number":return e.min??0;case"select":return e.options?.[0]?.value;case"input":return"";default:return}}var Q=({schema:e,config:t,onUpdate:o,activeTab:a="General"})=>{let y=u.useMemo(()=>_(a),[a]),T=u.useMemo(()=>y.flatMap((l)=>l.fields),[y]),[P,h]=u.useState(0),p=T[P],c=u.useCallback((l,i)=>{o(l.key,i)},[o]),G=u.useCallback((l)=>{c(l,!t[l.key])},[t,c]),A=u.useCallback((l,i)=>{let d=t[l.key]??K(l),F=l.step||1,C=l.min??-1/0,I=l.max??1/0;c(l,Math.max(C,Math.min(I,d+i*F)))},[t,c]),U=u.useCallback((l,i)=>{let d=l.options||[];if(!d.length)return;let C=(d.findIndex((I)=>I.value===t[l.key])+i+d.length)%d.length;c(l,d[C].value)},[t,c]);B((l,i)=>{if(i.upArrow)h((d)=>Math.max(0,d-1));else if(i.downArrow)h((d)=>Math.min(T.length-1,d+1));else if(i.leftArrow||i.rightArrow){let d=i.leftArrow?-1:1;if(p?.type==="toggle")G(p);else if(p?.type==="number")A(p,d);else if(p?.type==="select")U(p,d)}},{isActive:!0});let X=0;return f.jsxDEV(g,{flexDirection:"column",paddingX:2,paddingY:1,children:[y.map((l)=>f.jsxDEV(g,{flexDirection:"column",marginBottom:1,children:[f.jsxDEV(r,{bold:!0,color:"gray",children:["[",l.label,"]"]},void 0,!0,void 0,this),l.fields.map((i)=>{let F=X++===P;return f.jsxDEV(g,{flexDirection:"column",children:[f.jsxDEV(M,{field:i,value:t[i.key],onChange:(C)=>c(i,C),isFocused:F},void 0,!1,void 0,this),F&&i.help&&f.jsxDEV(r,{dimColor:!0,color:"yellow",children:[" ","→ ",i.help]},void 0,!0,void 0,this)]},i.key,!0,void 0,this)})]},l.id,!0,void 0,this)),f.jsxDEV(g,{marginTop:1,children:f.jsxDEV(r,{dimColor:!0,children:"↑↓ 导航 | ←→ 修改"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},v=Q;var s=m(b(),1),W=({onClose:e})=>{let{config:t,updateConfig:o}=k(),[a,y]=w.useState("General"),T=S.length>1,P=w.useCallback(async(p,c)=>{await o({[p]:c})},[o]),h=w.useCallback((p)=>{if(!T)return;let G=(S.findIndex((A)=>A.id===a)+p+S.length)%S.length;y(S[G].id)},[a,T]);if(B((p,c)=>{if(c.escape)e();else if(c.leftArrow&&c.alt)h(-1);else if(c.rightArrow&&c.alt)h(1)},{isActive:t!==null}),!t)return s.jsxDEV(g,{padding:2,children:s.jsxDEV(r,{children:"Loading..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);return s.jsxDEV(g,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",children:[s.jsxDEV(g,{paddingX:2,borderBottom:!0,borderColor:"gray",children:s.jsxDEV(r,{bold:!0,color:"cyan",children:"⚙ Settings"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T&&s.jsxDEV(g,{flexDirection:"row",gap:2,paddingX:2,borderBottom:!0,borderColor:"gray",children:S.map((p)=>s.jsxDEV(r,{bold:a===p.id,color:a===p.id?"cyan":"gray",children:[p.icon," ",p.label]},p.id,!0,void 0,this))},void 0,!1,void 0,this),s.jsxDEV(v,{schema:x,config:t,onUpdate:P,activeTab:a},void 0,!1,void 0,this),s.jsxDEV(g,{paddingX:2,borderTop:!0,borderColor:"gray",children:s.jsxDEV(r,{dimColor:!0,children:"Esc: Close | Auto-save | Global: Ctrl+O (Compact)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},N=W;var O=m(b(),1),Z=({onClose:e})=>{return O.jsxDEV(N,{onClose:e},void 0,!1,void 0,this)},ue=Z;export{ue as default};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import{U as R,V as Q,W as b,X as x,Y as _,Z as C,_ as f}from"./chunk-bgpcx3bm.js";import{rb as j}from"./chunk-cze71w02.js";import{Kysely as q,sql as A}from"kysely";var K={maxRetries:3,baseDelayMs:100,nonRetryablePatterns:["database disk image is malformed","database is malformed","cannot rollback","no transaction is active","database or disk is full"],isRetryableError:(J)=>{let $=J?.message?.toLowerCase()||"";for(let B of K.nonRetryablePatterns)if($.includes(B.toLowerCase()))return!1;return $.includes("sqlite_busy")||$.includes("database is locked")||$==="sqlite_busy"||$==="database is locked"}};async function T(J,$){let B=null;for(let H=0;H<K.maxRetries;H++)try{return await J()}catch(Z){B=Z;let U=Z?.message?.toLowerCase()||"";if(!K.isRetryableError(Z)){if(U.includes("malformed")){let D=Error(`SQLite database is corrupted: ${Z.message}
|
|
2
|
+
|
|
3
|
+
Context: ${$||"unknown"}
|
|
4
|
+
|
|
5
|
+
Possible causes:
|
|
6
|
+
1. Database file was manually deleted or modified
|
|
7
|
+
2. Disk I/O errors during write operations
|
|
8
|
+
3. Concurrent access without proper locking
|
|
9
|
+
|
|
10
|
+
Recovery options:
|
|
11
|
+
- Delete the database file to start fresh (data will be lost)
|
|
12
|
+
- Use SQLite recovery tools: sqlite3 <db> ".recover" > recover.sql
|
|
13
|
+
- Switch to PostgreSQL/Redis for production use`);throw D.name="SQLiteCorruptError",D.cause=Z,D}throw Z}if(H<K.maxRetries-1){let D=K.baseDelayMs*Math.pow(2,H);console.warn(`SQLite lock detected${$?` (${$})`:""}, retrying in ${D}ms (attempt ${H+1}/${K.maxRetries})`),await new Promise((X)=>setTimeout(X,D))}}throw B}function E(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return JSON.stringify(J.map((H)=>E(H)));let $={},B=Object.keys(J).sort();for(let H of B)$[H]=J[H];return JSON.stringify($,(H,Z)=>{if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)){let U={},D=Object.keys(Z).sort();for(let X of D)U[X]=Z[X];return U}return Z})}class N extends x{db;isSetup;constructor(J,$){super($);this.db=new q({dialect:J}),this.isSetup=!1}static async fromConnStringAsync(J){let $;if(globalThis.Bun){console.log("LG | Using BunSqliteDialect "+J);let{BunSqliteDialect:B}=await import("kysely-bun-worker/normal");$=new N(new B({url:J}))}else{console.log("LG | Using NodeWasmDialect");let{default:B}=await import("node-sqlite3-wasm"),{NodeWasmDialect:H}=await import("kysely-wasm");console.log(J);let Z=new H({database:new B.Database(J)});$=new N(Z)}return await $.setup(),$}async setup(){if(this.isSetup)return;await A`PRAGMA busy_timeout = 5000`.execute(this.db),await A`PRAGMA journal_mode = WAL`.execute(this.db),await A`PRAGMA synchronous = NORMAL`.execute(this.db),await A`PRAGMA wal_autocheckpoint = 1000`.execute(this.db),await A`
|
|
14
|
+
CREATE TABLE IF NOT EXISTS shallow_checkpoints (
|
|
15
|
+
thread_id TEXT NOT NULL,
|
|
16
|
+
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
17
|
+
checkpoint_id TEXT NOT NULL,
|
|
18
|
+
parent_checkpoint_id TEXT,
|
|
19
|
+
type TEXT,
|
|
20
|
+
checkpoint BLOB,
|
|
21
|
+
metadata BLOB,
|
|
22
|
+
checkpoint_ts INTEGER NOT NULL DEFAULT 0,
|
|
23
|
+
PRIMARY KEY (thread_id, checkpoint_ns)
|
|
24
|
+
)`.execute(this.db),await A`
|
|
25
|
+
CREATE INDEX IF NOT EXISTS idx_shallow_checkpoints_ts
|
|
26
|
+
ON shallow_checkpoints(checkpoint_ts DESC)`.execute(this.db),await A`
|
|
27
|
+
CREATE TABLE IF NOT EXISTS writes (
|
|
28
|
+
thread_id TEXT NOT NULL,
|
|
29
|
+
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
30
|
+
checkpoint_id TEXT NOT NULL,
|
|
31
|
+
task_id TEXT NOT NULL,
|
|
32
|
+
idx INTEGER NOT NULL,
|
|
33
|
+
channel TEXT NOT NULL,
|
|
34
|
+
type TEXT,
|
|
35
|
+
value BLOB,
|
|
36
|
+
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
|
37
|
+
)`.execute(this.db),this.isSetup=!0}async get(J){return(await this.getTuple(J))?.checkpoint}async getTuple(J){await this.setup();let $=J.configurable?.thread_id,B=J.configurable?.checkpoint_ns??"",H=f(J);if($===void 0)return;let Z=this.db.selectFrom("shallow_checkpoints").select(["thread_id","checkpoint_ns","checkpoint_id","parent_checkpoint_id","type","checkpoint","metadata","checkpoint_ts",A`(
|
|
38
|
+
SELECT json_group_array(
|
|
39
|
+
json_object(
|
|
40
|
+
'task_id', pw.task_id,
|
|
41
|
+
'channel', pw.channel,
|
|
42
|
+
'type', pw.type,
|
|
43
|
+
'value', CAST(pw.value AS TEXT)
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
FROM writes as pw
|
|
47
|
+
WHERE pw.thread_id = shallow_checkpoints.thread_id
|
|
48
|
+
AND pw.checkpoint_ns = shallow_checkpoints.checkpoint_ns
|
|
49
|
+
AND pw.checkpoint_id = shallow_checkpoints.checkpoint_id
|
|
50
|
+
)`.as("pending_writes"),A`(
|
|
51
|
+
SELECT json_group_array(
|
|
52
|
+
json_object(
|
|
53
|
+
'type', ps.type,
|
|
54
|
+
'value', CAST(ps.value AS TEXT)
|
|
55
|
+
)
|
|
56
|
+
)
|
|
57
|
+
FROM writes as ps
|
|
58
|
+
WHERE ps.thread_id = shallow_checkpoints.thread_id
|
|
59
|
+
AND ps.checkpoint_ns = shallow_checkpoints.checkpoint_ns
|
|
60
|
+
AND ps.checkpoint_id = shallow_checkpoints.parent_checkpoint_id
|
|
61
|
+
AND ps.channel = ${Q}
|
|
62
|
+
ORDER BY ps.idx
|
|
63
|
+
)`.as("pending_sends")]).where("thread_id","=",$).where("checkpoint_ns","=",B);if(H)Z=Z.where("checkpoint_id","=",H);let U=await Z.executeTakeFirst();if(!U)return;if(H&&U.checkpoint_id!==H)return;let D=await Promise.all(JSON.parse(U.pending_writes||"[]").map(async(z)=>{return[z.task_id,z.channel,await this.serde.loadsTyped(z.type??"json",z.value??"")]})),X=await this.serde.loadsTyped(U.type??"json",new TextDecoder().decode(U.checkpoint));if(X.v<4&&U.parent_checkpoint_id!=null)await this.migratePendingSends(X,U.thread_id,U.parent_checkpoint_id);let W={configurable:{thread_id:U.thread_id,checkpoint_ns:U.checkpoint_ns,checkpoint_id:U.checkpoint_id}};return{checkpoint:X,config:W,metadata:await this.serde.loadsTyped(U.type??"json",new TextDecoder().decode(U.metadata)),parentConfig:U.parent_checkpoint_id?{configurable:{thread_id:U.thread_id,checkpoint_ns:U.checkpoint_ns,checkpoint_id:U.parent_checkpoint_id}}:void 0,pendingWrites:D}}async*list(J,$){await this.setup();let{limit:B,before:H,filter:Z}=$??{},U=J.configurable?.thread_id,D=J.configurable?.checkpoint_ns,X=this.db.selectFrom("shallow_checkpoints").select(["thread_id","checkpoint_ns","checkpoint_id","parent_checkpoint_id","type","checkpoint","metadata","checkpoint_ts",A`(
|
|
64
|
+
SELECT json_group_array(
|
|
65
|
+
json_object(
|
|
66
|
+
'task_id', pw.task_id,
|
|
67
|
+
'channel', pw.channel,
|
|
68
|
+
'type', pw.type,
|
|
69
|
+
'value', CAST(pw.value AS TEXT)
|
|
70
|
+
)
|
|
71
|
+
)
|
|
72
|
+
FROM writes as pw
|
|
73
|
+
WHERE pw.thread_id = shallow_checkpoints.thread_id
|
|
74
|
+
AND pw.checkpoint_ns = shallow_checkpoints.checkpoint_ns
|
|
75
|
+
AND pw.checkpoint_id = shallow_checkpoints.checkpoint_id
|
|
76
|
+
)`.as("pending_writes")]);if(U)X=X.where("thread_id","=",U);if(D!==void 0&&D!==null)X=X.where("checkpoint_ns","=",D);if(H?.configurable?.checkpoint_id!==void 0)X=X.where("checkpoint_id","<",H.configurable.checkpoint_id);X=X.orderBy("checkpoint_ts","desc");let W=await X.execute(),z=0;for(let M of W){let V=await this.serde.loadsTyped(M.type??"json",new TextDecoder().decode(M.metadata));if(Z&&!this._checkMetadataFilterMatch(V,Z))continue;if(B!==void 0&&z>=B)return;let Y=await Promise.all(JSON.parse(M.pending_writes||"[]").map(async(F)=>{return[F.task_id,F.channel,await this.serde.loadsTyped(F.type??"json",F.value??"")]})),G=await this.serde.loadsTyped(M.type??"json",new TextDecoder().decode(M.checkpoint));if(G.v<4&&M.parent_checkpoint_id!=null)await this.migratePendingSends(G,M.thread_id,M.parent_checkpoint_id);z++,yield{config:{configurable:{thread_id:M.thread_id,checkpoint_ns:M.checkpoint_ns,checkpoint_id:M.checkpoint_id}},checkpoint:G,metadata:V,parentConfig:M.parent_checkpoint_id?{configurable:{thread_id:M.thread_id,checkpoint_ns:M.checkpoint_ns,checkpoint_id:M.parent_checkpoint_id}}:void 0,pendingWrites:Y}}}_checkMetadataFilterMatch(J,$){for(let[B,H]of Object.entries($)){let Z=J?.[B];if(H===null){if(!(B in(J||{}))||Z!==null)return!1}else if(typeof H==="object"&&!Array.isArray(H)){if(typeof Z!=="object"||Z===null)return!1;if(E(H)!==E(Z))return!1}else if(Z!==H)return!1}return!0}async put(J,$,B,H){await this.setup();let Z=J.configurable?.thread_id,U=J.configurable?.checkpoint_ns??"",D=J.configurable?.checkpoint_id;if(!Z)throw Error("thread_id is required");let X=$.id||R(0),W=b($),[[z,M],[V,Y]]=await Promise.all([this.serde.dumpsTyped(W),this.serde.dumpsTyped(B)]);if(z!==V)throw Error("Failed to serialize checkpoint and metadata to the same type.");let G=Z,F=U,P=X;return await T(async()=>{await this.db.transaction().execute(async(L)=>{let O=await L.selectFrom("shallow_checkpoints").select(["checkpoint_id"]).where("thread_id","=",G).where("checkpoint_ns","=",F).executeTakeFirst();if(O&&O.checkpoint_id!==P)await L.deleteFrom("writes").where("thread_id","=",G).where("checkpoint_ns","=",F).where("checkpoint_id","=",O.checkpoint_id).execute();await L.insertInto("shallow_checkpoints").values({thread_id:G,checkpoint_ns:F,checkpoint_id:P,parent_checkpoint_id:D??null,type:z,checkpoint:new Uint8Array(Buffer.from(M)),metadata:new Uint8Array(Buffer.from(Y)),checkpoint_ts:Date.now()}).onConflict((v)=>v.columns(["thread_id","checkpoint_ns"]).doUpdateSet({checkpoint_id:P,parent_checkpoint_id:D??null,type:z,checkpoint:new Uint8Array(Buffer.from(M)),metadata:new Uint8Array(Buffer.from(Y)),checkpoint_ts:Date.now()})).execute()})},`put(${Z}/${X})`),{configurable:{thread_id:Z,checkpoint_ns:U,checkpoint_id:X}}}async putWrites(J,$,B){await this.setup();let H=J.configurable?.thread_id,Z=J.configurable?.checkpoint_ns??"",U=J.configurable?.checkpoint_id;if(!H||!U)throw Error("thread_id and checkpoint_id are required");let D=await Promise.all($.map(async(X,W)=>{let[z,M]=await this.serde.dumpsTyped(X[1]);return{thread_id:H,checkpoint_ns:Z,checkpoint_id:U,task_id:B,idx:C[X[0]]??W,channel:X[0],type:z,value:new Uint8Array(Buffer.from(M))}}));if(D.length===0)return;await T(async()=>{await this.db.transaction().execute(async(X)=>{await X.deleteFrom("writes").where("thread_id","=",H).where("checkpoint_ns","=",Z).where("checkpoint_id","=",U).where("task_id","=",B).execute();for(let W of D)await X.insertInto("writes").values(W).execute()})},`putWrites(${H}/${U}/${B})`)}async deleteThread(J){await T(async()=>{await this.db.transaction().execute(async($)=>{await $.deleteFrom("shallow_checkpoints").where("thread_id","=",J).execute(),await $.deleteFrom("writes").where("thread_id","=",J).execute()})},`deleteThread(${J})`)}async migratePendingSends(J,$,B){let H=await this.db.selectFrom("writes as ps").select(["ps.checkpoint_id",A`json_group_array(
|
|
77
|
+
json_object(
|
|
78
|
+
'type', ps.type,
|
|
79
|
+
'value', CAST(ps.value AS TEXT)
|
|
80
|
+
)
|
|
81
|
+
)`.as("pending_sends")]).where("ps.thread_id","=",$).where("ps.checkpoint_id","=",B).where("ps.channel","=",Q).orderBy("ps.idx").executeTakeFirst();if(!H)return;let Z=J;Z.channel_values??={},Z.channel_values[Q]=await Promise.all(JSON.parse(H.pending_sends||"[]").map(({type:U,value:D})=>this.serde.loadsTyped(U,D))),Z.channel_versions[Q]=Object.keys(J.channel_versions).length>0?_(...Object.values(J.channel_versions)):this.getNextVersion(void 0)}}export{N as SqliteShallowSaver};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{G as M,I,L as u}from"./chunk-3n2b4eb4.js";import{ca as A,la as V}from"./chunk-wwn7gw8g.js";import{nb as y}from"./chunk-cze71w02.js";function QP(G){return G?.replace(process.cwd(),".")||G||""}var S=y(A(),1);function o(){let[G,X]=S.useState({width:process.stdout.columns,height:process.stdout.rows}),W=S.useCallback(()=>{X({width:process.stdout.columns,height:process.stdout.rows})},[]);return S.useEffect(()=>{return process.stdout.on("resize",W),()=>{process.stdout.off("resize",W)}},[W]),G}var q=y(A(),1);var s=()=>{return process.env.TERM?.includes("256color")||process.env.TERM==="xterm-256color"||process.env.WT_SESSION!==void 0||process.platform==="darwin"||process.env.TERM_PROGRAM==="vscode"||process.env.TERM_PROGRAM==="iTerm.app"},xP=()=>{if(process.env.TERM_PROGRAM==="iTerm.app")return"iTerm2";if(process.env.WT_SESSION!==void 0)return"Windows Terminal";if(process.env.TERM_PROGRAM==="vscode")return"VSCode";if(process.env.TERM?.includes("screen"))return"GNU Screen";if(process.env.TERM?.includes("tmux"))return"tmux";return process.env.TERM||"unknown"},C={success:{hex:"#4fd6be",fallback:"green"},warning:{hex:"#ffdb95",fallback:"yellow"},error:{hex:"#f7768e",fallback:"red"},info:{hex:"#7dcfff",fallback:"cyan"},muted:{hex:"#565f89",fallback:"gray"},highlight:{hex:"#7dcfff",fallback:"cyanBright"},accent:{hex:"#bb9af7",fallback:"magentaBright"},border:{hex:"#414868",fallback:"gray"},primary:{hex:"#7aa2f7",fallback:"cyan"},secondary:{hex:"#bb9af7",fallback:"magenta"},keyword:{hex:"#bb9af7",fallback:"magenta"},function:{hex:"#7aa2f7",fallback:"blue"},string:{hex:"#9ece6a",fallback:"green"},number:{hex:"#ff9e64",fallback:"yellow"},comment:{hex:"#565f89",fallback:"gray"},variable:{hex:"#c0caf5",fallback:"white"},type:{hex:"#0db9d7",fallback:"cyan"},constant:{hex:"#e0af68",fallback:"yellow"},textPrimary:{hex:"#c0caf5",fallback:"white"},textSecondary:{hex:"#9aa5ce",fallback:"whiteBright"},textMuted:{hex:"#565f89",fallback:"gray"},bg:{hex:"#1a1b26",fallback:"black"},bgCard:{hex:"#24283b",fallback:"black"},indigo:{hex:"#6366f1",fallback:"blue"},purple:{hex:"#a855f7",fallback:"magenta"},pink:{hex:"#ec4899",fallback:"redBright"},rose:{hex:"#f43f5e",fallback:"red"},orange:{hex:"#f97316",fallback:"yellowBright"},amber:{hex:"#f59e0b",fallback:"yellow"},emerald:{hex:"#10b981",fallback:"green"},teal:{hex:"#14b8a6",fallback:"cyan"},sky:{hex:"#0ea5e9",fallback:"blue"}},TP=(G)=>{if(!(G in C))G="sky";return s()?C[G].hex:C[G].fallback};import n from"os";function AP(){try{return n.userInfo().username}catch(G){return process.env.USER||process.env.USERNAME||"User"}}var Q=y(A(),1);var g=y(V(),1),t=50,e=1800000,PP=300000,HP=Q.createContext(null);var uP=({children:G})=>{let[X,W]=Q.useState([]),[F,D]=Q.useState(null),z=Q.useCallback(async($)=>{let J=$.tool;if(!J)return;let{status:Y,editedArgs:K}=$;if(Y==="approved")J.sendResumeData({type:"approve"});else if(Y==="edited"){let H={name:J.message.name,args:K};J.sendResumeData({type:"edit",edited_action:H})}else if(Y==="rejected")J.sendResumeData({type:"reject",message:"User rejected to run this tool"});else console.error("[ChatWrapper] Unknown approval status:",Y)},[]),w=Q.useCallback(()=>{return`approval_${Date.now()}_${Math.random().toString(36).substring(2,9)}`},[]),j=Q.useCallback(($)=>{let J={...$,id:w(),status:"pending",createdAt:new Date};return W((Y)=>{let K=[...Y,J];if(K.length>t){let H=K.filter((P)=>P.status!=="pending");if(H.length>0)return K.filter((P)=>P.id!==H[0].id)}if(Y.length===0)D(J.id);return K}),J.id},[w]),N=Q.useCallback(($,J)=>{W((Y)=>Y.map((K)=>K.id===$?{...K,...J}:K))},[]),h=Q.useCallback(($)=>{W((J)=>{let Y=J.filter((K)=>K.id!==$);if(F===$)D(Y.length>0?Y[0].id:null);return Y})},[F]),_=Q.useCallback(()=>{W(($)=>{let J=$.filter((Y)=>Y.status==="pending");if(J.length===0)D(null);else if(F&&!J.find((Y)=>Y.id===F))D(J[0].id);return J})},[F]),L=Q.useCallback(async()=>{let $=X.filter((J)=>J.status==="approved"||J.status==="edited"||J.status==="rejected");if($.length===0)return;for(let J of $)try{await z(J)}catch(Y){console.error(`[ApprovalContext] Execute approval request failed: ${J.id}`,Y)}_()},[X,z,_]),b=Q.useCallback(async($)=>{await z($)},[z]),B=Q.useMemo(()=>X.some(($)=>$.status==="pending"),[X]),x=Q.useMemo(()=>X.length>0&&!B,[X.length,B]),f=Q.useCallback(()=>{let $=Date.now();W((J)=>J.filter((Y)=>Y.createdAt.getTime()>$-e))},[]);M(()=>{f()},PP),I(()=>{W(($)=>$.map((J)=>({...J,tool:void 0})))}),Q.useEffect(()=>{if(x)L()},[x,L]);let R=Q.useMemo(()=>({requests:X,addApprovalRequest:j,updateApprovalRequest:N,removeApprovalRequest:h,clearCompletedApprovals:_,executeRequest:b,executeApproved:L,hasPendingRequests:B,allRequestsProcessed:x}),[X,j,N,h,_,b,L,B,x]);return g.jsxDEV(HP.Provider,{value:R,children:G},void 0,!1,void 0,this)};var O=y(A(),1);var c=y(V(),1),JP=1800000,WP=300000,d=O.createContext(null),nP=({children:G})=>{let[X,W]=O.useState(""),F=O.useRef(Date.now()),D=O.useCallback(()=>{W("")},[]),z=O.useCallback((j)=>{F.current=Date.now(),W(j)},[]);M(()=>{if(Date.now()-F.current>JP)D()},WP);let w={bufferedMessage:X,setBufferedMessage:z,clearBuffer:D};return c.jsxDEV(d.Provider,{value:w,children:G},void 0,!1,void 0,this)},aP=()=>{let G=O.useContext(d);if(!G)throw Error("useChatInputBuffer must be used within ChatInputBufferProvider");return G};var T=y(A(),1);var YP=y(V(),1),PH=T.createContext(void 0);var Z=y(A(),1);var i=y(V(),1),ZP=100,$P=1800000,GP=300000,l=Z.createContext(null),GH=()=>{let G=Z.useContext(l);if(!G)throw Error("useInteractionContext must be used within InteractionProvider");return G},QH=({children:G,onInteractionSubmit:X})=>{let[W,F]=Z.useState([]),[D,z]=Z.useState(0),w=Z.useCallback(()=>{return`interaction_${Date.now()}_${Math.random().toString(36).substring(2,9)}`},[]),j=Z.useCallback((H,P)=>{let U=new Date,E={id:w(),category:"panel",state:"idle",metadata:{title:P?.metadata?.title,description:P?.metadata?.description,icon:P?.metadata?.icon,priority:P?.metadata?.priority??"medium",groupKey:P?.metadata?.groupKey,messageIndex:P?.metadata?.messageIndex},tool:P?.tool,config:{layout:{border:!0,padding:1,...P?.config?.layout},interaction:{autoSubmit:!1,allowSkip:!1,showPreview:!0,...P?.config?.interaction},style:P?.config?.style??{}},content:H,createdAt:U,updatedAt:U};return F((m)=>{let v=[...m,E];if(v.length>ZP){let p=v.filter((k)=>k.state==="submitted"||k.state==="edited"||k.state==="cancelled");if(p.length>0){let k=p[0].id;return v.filter((r)=>r.id!==k)}}return v}),z((m)=>m+1),E},[w]),N=Z.useCallback((H,P)=>{F((U)=>U.map((E)=>E.id===H?{...E,...P,updatedAt:new Date}:E)),z((U)=>U+1)},[]),h=Z.useCallback((H)=>{F((P)=>P.filter((U)=>U.id!==H)),z((P)=>P+1)},[]),_=Z.useCallback(()=>{F([]),z((H)=>H+1)},[]),L=Z.useCallback((H)=>{return W.find((P)=>P.id===H)},[W]),b=Z.useCallback(()=>{return[...W]},[W]),B=Z.useCallback((H)=>{return W.filter((P)=>P.state===H)},[W]),x=Z.useCallback((H)=>{return W.filter((P)=>P.content.type===H)},[W]),f=Z.useCallback(async()=>{let H=W.filter((P)=>P.state==="submitted"||P.state==="edited"||P.state==="cancelled");for(let P of H)if(!P.resultSent&&X)await X(P),N(P.id,{resultSent:!0})},[W,X,N]),R=Z.useCallback(()=>{F((H)=>H.filter((P)=>P.state==="idle"||P.state==="active")),z((H)=>H+1)},[]),$=Z.useCallback(()=>{let H=Date.now();F((P)=>P.filter((U)=>U.updatedAt.getTime()>H-$P))},[]);M(()=>{$()},GP),I(()=>{F((H)=>H.map((P)=>({...P,tool:void 0})))});let J=Z.useMemo(()=>W.some((H)=>H.state==="idle"||H.state==="active"),[W]),Y=Z.useMemo(()=>W.length>0&&W.every((H)=>H.state==="submitted"||H.state==="edited"||H.state==="cancelled"),[W]);u(()=>{R()},Y&&J===!1?100:null),Z.useEffect(()=>{if(Y&&J===!1)f()},[Y,J,f]);let K=Z.useMemo(()=>({addInteraction:j,updateInteraction:N,removeInteraction:h,clearAll:_,getInteraction:L,getInteractions:b,getInteractionsByState:B,getInteractionsByContent:x,submitInteractions:f,clearCompleted:R,interactions:W,updateCount:D,hasPendingInteractions:J,allInteractionsProcessed:Y}),[j,N,h,_,L,b,B,x,f,R,W,D,J,Y]);return i.jsxDEV(l.Provider,{value:K,children:G},void 0,!1,void 0,this)};export{o as t,QP as u,xP as v,TP as w,AP as x,uP as y,nP as z,aP as A,GH as B,QH as C};
|