zen-code 4.10.2 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/app.js +149 -239
  2. package/dist/{chunk-vbb3m0vz.js → chunk-069q9hkz.js} +1 -1
  3. package/dist/chunk-06trk066.js +1 -0
  4. package/dist/chunk-0kfw8bwn.js +2 -0
  5. package/dist/chunk-0mq8786q.js +281 -0
  6. package/dist/{chunk-mmx0k2yq.js → chunk-0qz8rr2k.js} +1 -1
  7. package/dist/chunk-1d47g6nc.js +2 -0
  8. package/dist/{chunk-nqh1pptf.js → chunk-1gssqf6g.js} +1 -1
  9. package/dist/{chunk-s5cqejr6.js → chunk-1rcc9xzn.js} +1 -1
  10. package/dist/{chunk-tjvhqr94.js → chunk-2bjeg40f.js} +1 -1
  11. package/dist/chunk-2gd8vzrf.js +2 -0
  12. package/dist/{chunk-spx7nn8t.js → chunk-2gprcgep.js} +2 -2
  13. package/dist/chunk-3k3c686f.js +1 -0
  14. package/dist/chunk-43h0n2td.js +1 -0
  15. package/dist/{chunk-8f19qk9r.js → chunk-492hjs9k.js} +1 -1
  16. package/dist/{chunk-pe8mzxwn.js → chunk-4eaqmt3c.js} +11 -11
  17. package/dist/{chunk-y8qhrx11.js → chunk-4fs853nh.js} +1 -1
  18. package/dist/chunk-5fe27s34.js +2 -0
  19. package/dist/{chunk-4wnmk2tj.js → chunk-5hqvapp1.js} +3 -3
  20. package/dist/chunk-6b3vfr39.js +2 -0
  21. package/dist/{chunk-t6440ajd.js → chunk-6j695pam.js} +2 -2
  22. package/dist/{chunk-pzb224c5.js → chunk-6saqxa3z.js} +2 -2
  23. package/dist/{chunk-tjg2e8v3.js → chunk-78ksrp8v.js} +2 -2
  24. package/dist/chunk-7cx9kda0.js +228 -0
  25. package/dist/chunk-7qba2raw.js +2 -0
  26. package/dist/chunk-81b2s97q.js +1 -0
  27. package/dist/chunk-88w3txtb.js +160 -0
  28. package/dist/chunk-8ygdre0g.js +1 -0
  29. package/dist/{chunk-fzh0v6r0.js → chunk-9011y634.js} +2 -2
  30. package/dist/chunk-9zcr1qh6.js +1 -0
  31. package/dist/chunk-a0nr8jva.js +2 -0
  32. package/dist/{chunk-5c3bpcpm.js → chunk-agevsn2e.js} +1 -1
  33. package/dist/{chunk-8tbtavry.js → chunk-akc3s5aw.js} +2 -2
  34. package/dist/{chunk-spa69h7p.js → chunk-b0beqmg2.js} +2 -2
  35. package/dist/{chunk-zg54h6gy.js → chunk-b175s7dm.js} +1 -1
  36. package/dist/chunk-bk32cwxa.js +5 -0
  37. package/dist/{chunk-vrnj0659.js → chunk-bn077sjq.js} +15 -15
  38. package/dist/{chunk-qxebn3jw.js → chunk-c9yrpb3g.js} +3 -3
  39. package/dist/{chunk-hnnwbfqk.js → chunk-cb0f54ar.js} +2 -2
  40. package/dist/chunk-ctqtahz4.js +1 -0
  41. package/dist/{chunk-gt8c6dne.js → chunk-d2sr8fnm.js} +1 -1
  42. package/dist/chunk-d5gzkkgg.js +1 -0
  43. package/dist/{chunk-bzgznka5.js → chunk-dh2f4xyb.js} +1 -1
  44. package/dist/chunk-dr32dt9y.js +1 -0
  45. package/dist/chunk-dv1vt080.js +1 -0
  46. package/dist/{chunk-vfxjbdz4.js → chunk-dz9sqfph.js} +1 -1
  47. package/dist/chunk-e7mbewmw.js +1 -0
  48. package/dist/chunk-em03xqy9.js +1 -0
  49. package/dist/chunk-fkt5b511.js +1 -0
  50. package/dist/{chunk-k4q8j7pg.js → chunk-gphssgy6.js} +1 -1
  51. package/dist/chunk-h2hk7vx4.js +1 -0
  52. package/dist/{chunk-c7kd2qrp.js → chunk-h7ypcqp3.js} +112 -111
  53. package/dist/{chunk-nsw5168d.js → chunk-j8tq0e8m.js} +2 -2
  54. package/dist/{chunk-40ht9pe1.js → chunk-jd1razfg.js} +2 -2
  55. package/dist/chunk-jhxvctg5.js +8 -0
  56. package/dist/chunk-kada5fyh.js +1 -0
  57. package/dist/chunk-kgc6ws03.js +1 -0
  58. package/dist/chunk-mk8ggmt8.js +17 -0
  59. package/dist/{chunk-e8kxa5vj.js → chunk-mv5m8bf4.js} +2 -2
  60. package/dist/chunk-mv8a5svx.js +1 -0
  61. package/dist/chunk-n61yv4t5.js +2 -0
  62. package/dist/chunk-nt2yp4jh.js +1 -0
  63. package/dist/chunk-p7ew4trx.js +1 -0
  64. package/dist/{chunk-s1tbdcs8.js → chunk-pgnhcznr.js} +1 -1
  65. package/dist/chunk-q8cfxky4.js +8 -0
  66. package/dist/{chunk-g2zskge5.js → chunk-q8zsxwd8.js} +2 -2
  67. package/dist/{chunk-nmzx5nmt.js → chunk-qfa5v4n5.js} +1 -1
  68. package/dist/chunk-qhzztj83.js +1 -0
  69. package/dist/chunk-snmkgfbe.js +15 -0
  70. package/dist/chunk-ss4bh5wb.js +2 -0
  71. package/dist/chunk-sv0k2v66.js +1 -0
  72. package/dist/{chunk-wmyc17aa.js → chunk-tbav8trq.js} +1 -1
  73. package/dist/chunk-tmyzfvsy.js +1 -0
  74. package/dist/chunk-ts4jreym.js +7 -0
  75. package/dist/chunk-tws3wcnm.js +2 -0
  76. package/dist/chunk-v0e9bsvt.js +89 -0
  77. package/dist/{chunk-n9rpnke9.js → chunk-vwj4n000.js} +1 -1
  78. package/dist/{chunk-gfhmzpy7.js → chunk-wd6s7gg7.js} +2 -3
  79. package/dist/{chunk-f0m4532p.js → chunk-y524zd2h.js} +5 -5
  80. package/dist/{chunk-hve2a279.js → chunk-yb71zqvt.js} +2 -2
  81. package/dist/{chunk-n7s6my89.js → chunk-yejgw2hm.js} +32 -32
  82. package/dist/{chunk-g974hxbz.js → chunk-yfjs6pf8.js} +1 -1
  83. package/dist/chunk-zhqdp4ak.js +2 -0
  84. package/dist/chunk-zkd3m39v.js +1 -0
  85. package/dist/cli.js +1 -1
  86. package/dist/nonInteractive.js +80 -80
  87. package/dist/zen-core.js +644 -0
  88. package/dist/zen-keyboard.js +1 -1
  89. package/package.json +5 -3
  90. package/dist/chunk-0ddrb30y.js +0 -1
  91. package/dist/chunk-215an3fz.js +0 -1
  92. package/dist/chunk-4z0w0ng1.js +0 -2
  93. package/dist/chunk-57bj89e2.js +0 -1
  94. package/dist/chunk-5a5mepqj.js +0 -1
  95. package/dist/chunk-7kw7ss8d.js +0 -1
  96. package/dist/chunk-86m0rmtc.js +0 -1
  97. package/dist/chunk-9rayxazs.js +0 -8
  98. package/dist/chunk-a9gpb2tx.js +0 -2
  99. package/dist/chunk-a9tw6d68.js +0 -1
  100. package/dist/chunk-anbtppz1.js +0 -294
  101. package/dist/chunk-bca8tkkr.js +0 -1
  102. package/dist/chunk-bdqds8vh.js +0 -1
  103. package/dist/chunk-dvbb3dd1.js +0 -233
  104. package/dist/chunk-ehmmd8qc.js +0 -1
  105. package/dist/chunk-ejfa95sm.js +0 -1
  106. package/dist/chunk-f7cps5x1.js +0 -1
  107. package/dist/chunk-fbemqjck.js +0 -2
  108. package/dist/chunk-feeqtzv5.js +0 -1
  109. package/dist/chunk-g9911ymn.js +0 -1
  110. package/dist/chunk-h8fdexm4.js +0 -2
  111. package/dist/chunk-hp2jzn9x.js +0 -166
  112. package/dist/chunk-js4qp900.js +0 -2
  113. package/dist/chunk-m21hvv91.js +0 -2
  114. package/dist/chunk-mnnyjmgw.js +0 -224
  115. package/dist/chunk-mw7x6xqp.js +0 -1
  116. package/dist/chunk-nk62q95g.js +0 -93
  117. package/dist/chunk-pg1ppq4y.js +0 -1
  118. package/dist/chunk-q1cxrg0x.js +0 -2
  119. package/dist/chunk-swc7se71.js +0 -2
  120. package/dist/chunk-swyc15ym.js +0 -1
  121. package/dist/chunk-t2s3s6af.js +0 -1
  122. package/dist/chunk-vdmq9d9x.js +0 -4
  123. package/dist/chunk-wt3p1w1g.js +0 -1
  124. package/dist/chunk-y5ry5c7v.js +0 -1
  125. package/dist/chunk-yy8p9zph.js +0 -2
  126. package/dist/chunk-z61m3anh.js +0 -1
  127. package/dist/chunk-zr90qp47.js +0 -1
  128. package/dist/chunk-zsa62xr0.js +0 -2
@@ -1 +0,0 @@
1
- import{gf as a}from"./chunk-spx7nn8t.js";import"./chunk-e8kxa5vj.js";import"./chunk-y8qhrx11.js";export{a as FileSystemSkillStore};
@@ -1 +0,0 @@
1
- import{U as R,W as v,X as _,Y as b}from"./chunk-4wnmk2tj.js";import{Ae as W,Ie as q,Je as h,we as S,ze as J}from"./chunk-c7kd2qrp.js";import{kf as U}from"./chunk-bzgznka5.js";import{Dl as w}from"./chunk-y8qhrx11.js";var G=w(S(),1);function M({limit:X=100,enabled:H=!0}={}){return v({queryKey:b.errors.list(),queryFn:async()=>{return U.getRecentErrors(X)},enabled:H,staleTime:5000,refetchInterval:5000})}function O(){let X=R();return _({mutationFn:async(H)=>{return U.deleteError(H)},onSuccess:()=>{X.invalidateQueries({queryKey:b.errors.all})}})}function Q(){let X=R();return _({mutationFn:async()=>{U.clearAll()},onSuccess:()=>{X.invalidateQueries({queryKey:b.errors.all})}})}var z=w(h(),1);import{join as B}from"node:path";var T={error:{emoji:"❌",color:"red",label:"错误"},warning:{emoji:"⚠️",color:"yellow",label:"警告"}},p={Agent:{emoji:"\uD83E\uDD16",label:"Agent"},Tool:{emoji:"\uD83D\uDD27",label:"Tool"},Terminal:{emoji:"\uD83D\uDCBB",label:"Terminal"},System:{emoji:"⚙️",label:"System"},Unknown:{emoji:"❓",label:"Unknown"}};function g(X){let H=new Date(X),Z=new Date,P=Z.getTime()-H.getTime();if(P<60000)return"刚刚";if(P<3600000)return`${Math.floor(P/60000)}分钟前`;if(H.toDateString()===Z.toDateString())return H.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"});return H.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})}function c(X,H=80){if(X.length<=H)return X;return X.slice(0,H-3)+"..."}var d=({onClose:X})=>{let{data:H=[],isLoading:Z}=M({limit:50}),P=O(),N=Q(),L=G.useCallback(async()=>{await N.mutateAsync()},[N]);q((Y,A)=>{if(A.escape)X();if(A.ctrl&&Y==="l")L()},{isActive:!0});let f=B(process.cwd(),".zen-code","errors.json"),F=G.default.useMemo(()=>{let Y=H.filter(($)=>$.level==="error").length,A=H.filter(($)=>$.level==="warning").length;return{errorCount:Y,warningCount:A}},[H]);return z.jsxDEV(J,{flexDirection:"column",paddingX:1,paddingY:1,children:[z.jsxDEV(J,{marginBottom:1,children:[z.jsxDEV(W,{bold:!0,color:"cyan",children:"\uD83D\uDCCB 错误日志"},void 0,!1,void 0,this),z.jsxDEV(J,{marginLeft:2,children:[z.jsxDEV(W,{color:"red",children:["❌ ",F.errorCount]},void 0,!0,void 0,this),z.jsxDEV(W,{children:" "},void 0,!1,void 0,this),z.jsxDEV(W,{color:"yellow",children:["⚠️ ",F.warningCount]},void 0,!0,void 0,this),z.jsxDEV(W,{dimColor:!0,children:["| Total: ",H.length]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Z&&z.jsxDEV(J,{marginBottom:1,children:z.jsxDEV(W,{dimColor:!0,children:"加载中..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),!Z&&H.length>0&&z.jsxDEV(J,{flexDirection:"column",children:H.slice(0,20).map((Y,A)=>{let $=T[Y.level],K=p[Y.source]||p.Unknown,k=g(Y.timestamp),I=c(Y.message);return z.jsxDEV(J,{flexDirection:"column",marginBottom:1,children:[z.jsxDEV(J,{children:z.jsxDEV(W,{color:$.color,children:[$.emoji," ",I]},void 0,!0,void 0,this)},void 0,!1,void 0,this),z.jsxDEV(J,{marginLeft:2,children:[z.jsxDEV(W,{dimColor:!0,children:[K.emoji," ",K.label," | ",k]},void 0,!0,void 0,this),Y.file&&z.jsxDEV(W,{dimColor:!0,color:"gray",children:[" ","| \uD83D\uDCC4 ",Y.file,Y.line&&`:${Y.line}`]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},Y.id,!0,void 0,this)})},void 0,!1,void 0,this),!Z&&H.length===0&&z.jsxDEV(J,{flexDirection:"column",marginBottom:1,children:[z.jsxDEV(J,{marginBottom:1,children:z.jsxDEV(W,{dimColor:!0,children:"暂无错误记录"},void 0,!1,void 0,this)},void 0,!1,void 0,this),z.jsxDEV(J,{marginBottom:1,children:z.jsxDEV(W,{dimColor:!0,children:"错误将自动收集到:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),z.jsxDEV(J,{marginBottom:1,children:z.jsxDEV(W,{color:"yellow",children:f},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),z.jsxDEV(J,{marginTop:1,children:z.jsxDEV(W,{dimColor:!0,children:"按 ESC 返回 | Ctrl+L 清空所有"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},E=d;export{E as default};
@@ -1,233 +0,0 @@
1
- import{cf as y,ef as p}from"./chunk-vrnj0659.js";import{vf as f}from"./chunk-yy8p9zph.js";import{Jf as v,Lf as x}from"./chunk-mnnyjmgw.js";import{Il as s}from"./chunk-y8qhrx11.js";async function w(e){let o=(t)=>{return t.stateSchema=f,t},a={id:"filesystem",name:"filesystem",description:"File and directory operations (read, write, search, glob)",execute:async()=>{return o(new y)}};await e.addMiddleware(a),e.middlewares.registerImplementation(a);let i={id:"terminal",name:"terminal",description:"Terminal command execution (Bash/CMD, background processes)",execute:async()=>{return o(new p)}};await e.addMiddleware(i),e.middlewares.registerImplementation(i);let r={id:"subagents",name:"subagents",description:"Task delegation to specialized agents",execute:async()=>{let{createSubAgentsMiddleware:t}=await import("./chunk-swyc15ym.js");return await t(e)}};await e.addMiddleware(r),e.middlewares.registerImplementation(r);let l={id:"skills",name:"skills",description:"Progressive skills disclosure",execute:async(t)=>{if(t.projectSkillsDir=t.projectSkillsDir||"./.claude/skills",!t.skillsDir){let R=await import("os"),Y=await import("path");t.skillsDir=Y.join(R.homedir(),".claude","skills")}let{SkillsMiddleware:n}=await import("./chunk-7kw7ss8d.js");return new n(t)}};await e.addMiddleware(l),e.middlewares.registerImplementation(l);let u={id:"agents_md",name:"agents_md",description:"Inject agent documentation",execute:async(t)=>{let{AgentsMdMiddleware:n}=await import("./chunk-7kw7ss8d.js");return new n({projectRoot:t?.projectRoot})}};await e.addMiddleware(u),e.middlewares.registerImplementation(u);let h={id:"interactive",name:"interactive",description:"User interaction for approval and input",execute:async()=>{let{InteractiveMiddleware:t}=await import("./chunk-ehmmd8qc.js");return t}};await e.addMiddleware(h),e.middlewares.registerImplementation(h);let c={id:"task",name:"task",description:"Task management for todo lists",execute:async()=>{let{taskMiddleware:t}=await import("./chunk-zr90qp47.js");return t}};await e.addMiddleware(c),e.middlewares.registerImplementation(c);let d={id:"mcp",name:"mcp",description:"Task management for todo lists",execute:async()=>{let{MCPWithConfigMiddleware:t}=await import("./chunk-z61m3anh.js");return new t}};await e.addMiddleware(d),e.middlewares.registerImplementation(d);let m={id:"web",name:"web",description:"Fetch and extract readable content from URLs",execute:async()=>{let{WebMiddleware:t}=await import("./chunk-t2s3s6af.js");return t}};await e.addMiddleware(m),e.middlewares.registerImplementation(m)}var g=`# 架构师 - 任务派发协调者
2
-
3
- 你是一位**任务派发架构师**,核心职责是将用户需求分析并拆解为子任务,然后委派给合适的子 agent 执行。
4
-
5
- ## 核心职责
6
-
7
- **你的唯一任务**:
8
- 1. 理解用户需求
9
- 2. 拆解为可执行的子任务
10
- 3. 委派给合适的子 agent
11
- 4. 跟踪和汇总结果
12
-
13
- **不要做的事**:
14
- - ❌ 不要自己编写代码
15
- - ❌ 不要自己读取文件或搜索代码
16
- - ❌ 不要自己执行终端命令
17
- - ❌ 不要做具体的架构分析或设计文档
18
-
19
- ## 工作流程
20
-
21
- ### 步骤 1:需求分析
22
-
23
- 当收到用户请求时,快速判断:
24
-
25
- 1. **任务类型**:
26
- - 代码实现/修改 → 委派给 \`agents/default\`
27
- - 任务规划/协调 → 委派给 \`agents/manager\`
28
- - 复杂任务 → 先由 \`agents/manager\` 规划,再由 \`agents/default\` 执行
29
-
30
- 2. **任务规模**:
31
- - 单一任务 → 直接委派
32
- - 多任务 → 拆分后分别委派
33
-
34
- ### 步骤 2:任务拆解
35
-
36
- 使用 \`task\` 工具委派任务:
37
-
38
- \`\`\`typescript
39
- // 示例:委派代码实现任务
40
- {
41
- subagent_id: "agents/default",
42
- task_description: "实现用户认证功能,包括登录、注册、登出三个接口",
43
- data_transfer: {
44
- requirements: "使用 JWT 认证,密码需要加密存储",
45
- constraints: "使用现有的数据库连接池"
46
- }
47
- }
48
- \`\`\`
49
-
50
- ### 步骤 3:结果汇总
51
-
52
- 子 agent 完成后:
53
- 1. 检查执行结果
54
- 2. 如果有多个子任务,协调依赖关系
55
- 3. 向用户汇报整体进度和结果
56
-
57
- ## 委派策略
58
-
59
- ### 简单任务
60
-
61
- 用户请求单一功能时,直接委派:
62
-
63
- > 用户:添加一个日志工具函数
64
-
65
- → 委派给 \`agents/default\`,任务描述清晰完整
66
-
67
- ### 复杂任务
68
-
69
- 用户请求多功能时,拆分后委派:
70
-
71
- > 用户:重构用户模块并添加测试
72
-
73
- → 拆分为:
74
- 1. 委派 \`agents/default\`:重构用户模块代码
75
- 2. 等第一步完成后,委派 \`agents/default\`:为用户模块编写测试
76
-
77
- ### 规划任务
78
-
79
- 用户需要方案设计时:
80
-
81
- > 用户:设计一个新的权限系统
82
-
83
- → 委派 \`agents/manager\` 进行任务规划,然后按规划执行
84
-
85
- ## 输出格式
86
-
87
- ### 委派时
88
-
89
- \`\`\`markdown
90
- ## 任务分析
91
-
92
- **用户需求**:{用户原始请求}
93
-
94
- **任务拆解**:
95
- 1. 任务 A → 委派给 agents/default
96
- 2. 任务 B → 委派给 agents/manager
97
-
98
- **开始执行**...
99
- \`\`\`
100
-
101
- ### 汇报时
102
-
103
- \`\`\`markdown
104
- ## 执行结果
105
-
106
- **已完成**:
107
- - ✅ 任务 A:{简要结果}
108
- - ✅ 任务 B:{简要结果}
109
-
110
- **总结**:{整体结果摘要}
111
- \`\`\`
112
-
113
- ## 重要约束
114
-
115
- 1. **立即委派**:收到任务后,不要犹豫,立即分析并委派
116
- 2. **清晰描述**:给子 agent 的任务描述要完整、清晰
117
- 3. **传递上下文**:使用 \`data_transfer\` 传递必要的背景信息
118
- 4. **不要插手**:相信子 agent 的能力,不要自己动手做具体工作
119
- 5. **保持简洁**:你的输出应该简短,重点是协调和汇总
120
-
121
- ---
122
-
123
- **记住**:你是协调者,不是执行者。快速分析需求,立即委派任务,高效汇总结果。`;var b=({cwd:e,env:o})=>`You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
124
-
125
- IMPORTANT: Assist with defensive security tasks only. Refuse to create, modify, or improve code that may be used maliciously. Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation.
126
- IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
127
-
128
- # Tone and style
129
- You should be concise, direct, and to the point.
130
- You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail.
131
- IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
132
- IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
133
- Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
134
- Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
135
-
136
- <example>
137
- user: 2 + 2
138
- assistant: 4
139
- </example>
140
-
141
- <example>
142
- user: what is 2+2?
143
- assistant: 4
144
- </example>
145
-
146
- <example>
147
- user: is 11 a prime number?
148
- assistant: Yes
149
- </example>
150
-
151
- <example>
152
- user: what command should I run to list files in the current directory?
153
- assistant: ls
154
- </example>
155
-
156
- <example>
157
- user: what command should I run to watch files in the current directory?
158
- assistant: [runs ls to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
159
- npm run dev
160
- </example>
161
-
162
- <example>
163
- user: How many golf balls fit inside a jetta?
164
- assistant: 150000
165
- </example>
166
-
167
- <example>
168
- user: what files are in the directory src/?
169
- assistant: [runs ls and sees foo.c, bar.c, baz.c]
170
- user: which file contains the implementation of foo?
171
- assistant: src/foo.c
172
- </example>
173
-
174
- When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
175
-
176
- Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
177
-
178
- Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
179
-
180
- If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
181
-
182
- Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
183
-
184
- IMPORTANT: Keep your responses short, since they will be displayed on a command line interface.
185
-
186
- # Proactiveness
187
- You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
188
- - Doing the right thing when asked, including taking actions and follow-up actions
189
- - Not surprising the user with actions you take without asking
190
- For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
191
-
192
- # Following conventions
193
- When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
194
- - NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
195
- - When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
196
- - When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
197
- - Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
198
-
199
- # Doing tasks
200
- The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
201
- - Use the TodoWrite tool to plan the task if required
202
- - Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
203
- - Implement the solution using all tools available to you
204
- - Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
205
- - VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to CLAUDE.md so that you will know to run it next time.
206
- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
207
-
208
- # Tool usage policy
209
- - When doing file search, prefer to use the Task tool in order to reduce context usage.
210
- - You should proactively use the Task tool with specialized agents when the task at hand matches the agent's description.
211
- - When WebFetch returns a message about a redirect to a different host, you should immediately make a new WebFetch request with the redirect URL provided in the response.
212
- - You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
213
-
214
- Here is useful information about the environment you are running in:
215
-
216
- <env>
217
- Working directory: ${e}
218
- Is directory a git repo: ${o.isGitRepo?"Yes":"No"}
219
- Platform: ${o.platform}
220
- OS Version: ${o.osVersion}
221
- Today's date: ${o.date}
222
- </env>
223
-
224
- # Code References
225
-
226
- When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` to allow the user to easily navigate to the source code location.
227
-
228
- <example>
229
- user: Where are errors from the client handled?
230
- assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
231
- </example>
232
- `;async function T(){let e=new x,o=new v(e);return await o.addModel({id:"glm-4.7",model_name:"glm-4.7",provider_id:process.env.MODEL_PROVIDER||"openai",stream_usage:!0,enable_thinking:!0,temperature:0.7,max_tokens:4096,top_p:1,frequency_penalty:0,presence_penalty:0}),await o.addPrompt({id:"prompts/default",name:"default"},b({cwd:process.cwd(),env:{isGitRepo:!0,platform:process.platform,osVersion:process.version,date:new Date().toISOString().split("T")[0]}})),await o.addPrompt({id:"prompts/manager",name:"manager"},g),await w(o),await o.addAgent({id:"agents/default",name:"Jarvis",description:"代码实现助手",system_prompt:"prompts/default",model:"glm-4.7",middlewares:{filesystem:!0,terminal:!0,agents_md:!0,skills:!0,subagents:!0,interactive:!0,task:!0,mcp:!0,web:!0}}),await o.addAgent({id:"agents/manager",name:"Manager",description:"任务管理员",system_prompt:"prompts/manager",model:"glm-4.7",middlewares:{filesystem:!0,terminal:!0,agents_md:!0,skills:!0,subagents:!0,interactive:!0,task:!0,mcp:!0,web:!0}}),o}var N=await T(),B=N;
233
- export{B as Te};
@@ -1 +0,0 @@
1
- import"./chunk-f0m4532p.js";import"./chunk-pe8mzxwn.js";import"./chunk-hp2jzn9x.js";import{Ek as t}from"./chunk-nk62q95g.js";import"./chunk-nmzx5nmt.js";import"./chunk-q1cxrg0x.js";import{tl as e}from"./chunk-tjg2e8v3.js";import"./chunk-hve2a279.js";import"./chunk-y8qhrx11.js";var o=e.object({label:e.string().min(1).max(50).describe("选项显示文本,简洁明了(1-50 字符)")}),i=e.object({description:e.string().min(1).describe("向用户提出的问题,清晰具体,包含必要的上下文"),type:e.enum(["single_select","multi_select"]).describe("选择类型:single_select(单选)或 multi_select(多选)"),options:e.array(o).min(2).max(6).describe("选项列表,至少 2 个,最多 6 个"),allow_custom_input:e.boolean().default(!0).describe("是否允许用户输入自定义文本,默认 true"),placeholder:e.string().optional().describe("自定义输入框的占位符文本")}),s=t(()=>{},{name:"ask_user_questions",description:"Ask the user a question with selectable options",schema:i});var m={name:"interactive",tools:[s]};export{m as InteractiveMiddleware};
@@ -1 +0,0 @@
1
- import{D as f}from"./chunk-pg1ppq4y.js";import"./chunk-m21hvv91.js";import{W as C,Y as _}from"./chunk-4wnmk2tj.js";import{Ae as Y,Je as K,Ne as M,we as g,ze as X}from"./chunk-c7kd2qrp.js";import{Qf as w,Sf as A}from"./chunk-mnnyjmgw.js";import"./chunk-fzh0v6r0.js";import"./chunk-t6440ajd.js";import"./chunk-f0m4532p.js";import"./chunk-pe8mzxwn.js";import"./chunk-hp2jzn9x.js";import"./chunk-nk62q95g.js";import"./chunk-nmzx5nmt.js";import"./chunk-e8kxa5vj.js";import"./chunk-q1cxrg0x.js";import"./chunk-tjg2e8v3.js";import"./chunk-nsw5168d.js";import"./chunk-hve2a279.js";import{Dl as Q}from"./chunk-y8qhrx11.js";var F=Q(g(),1);import{join as R}from"path";function $({type:G,enabled:J=!0}){return C({queryKey:G==="memories"?_.knowledge.memories():_.knowledge.skills(),queryFn:async()=>{let L=R(process.cwd(),".claude",G),N=R(process.env.HOME||"",".deepagents/code",G);try{if(G==="memories")return A(N,L).map((W)=>({...W,type:"memory"}));else return w(N,L).map((W)=>({...W,type:"skill"}))}catch(O){return console.warn(`Failed to load ${G}:`,O),[]}},enabled:J,staleTime:120000})}var H=Q(K(),1),S=(G)=>{return G.length>80?G.slice(0,80)+"...":G},v=({onClose:G})=>{let[J,L]=F.useState("memories"),N=F.useRef(L);F.default.useEffect(()=>{N.current=L},[L]);let{data:O=[]}=$({type:"memories",enabled:J==="memories"}),{data:W=[]}=$({type:"skills",enabled:J==="skills"}),U=F.useCallback(async()=>{return J==="memories"?O:W},[J,O,W]),I=F.useCallback((z,E,Z)=>{let V=S(z.description);return H.jsxDEV(X,{flexDirection:"column",paddingY:1,children:[H.jsxDEV(X,{children:H.jsxDEV(Y,{bold:!0,color:Z?"cyan":"gray",children:[E+1,". ",z.name]},void 0,!0,void 0,this)},void 0,!1,void 0,this),H.jsxDEV(X,{paddingY:1,children:H.jsxDEV(Y,{color:Z?"white":"gray",children:V},void 0,!1,void 0,this)},void 0,!1,void 0,this),H.jsxDEV(X,{children:H.jsxDEV(Y,{color:"cyan",dimColor:!Z,children:[f(z.path),z.category&&H.jsxDEV(Y,{color:"yellow",children:[" ",z.category]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},z.path,!0,void 0,this)},[]),P=F.useCallback((z)=>{console.log("Selected knowledge item:",z.name)},[]),q=F.useMemo(()=>[{id:"memory",label:"记忆",predicate:(z)=>z.type==="memory"},{id:"skill",label:"技能",predicate:(z)=>z.type==="skill"}],[]),B=F.useMemo(()=>({h:(z)=>{N.current("memories"),z.setActiveFilter("memory")},s:(z)=>{N.current("skills"),z.setActiveFilter("skill")}}),[]),h=F.useMemo(()=>({id:"knowledge",title:"知识库",icon:"\uD83D\uDCDA",dataSource:U,searchable:!0,searchFields:["name","description"],searchPlaceholder:"搜索知识库 (名称/描述/分类)...",filterable:!0,filters:q,defaultFilter:J==="memories"?"memory":"skill",itemHeight:8,visibleCount:3,renderItem:I,showCount:!0,onSelect:P,keyMap:B}),[U,q,I,P,B,J]);return H.jsxDEV(M,{config:h,onClose:G},void 0,!1,void 0,this)},m=v;export{m as default};
@@ -1 +0,0 @@
1
- import{a as A,b as W}from"./chunk-8tbtavry.js";import"./chunk-spa69h7p.js";import{Dg as q,Yg as R}from"./chunk-hp2jzn9x.js";import"./chunk-nk62q95g.js";import"./chunk-nmzx5nmt.js";import"./chunk-tjg2e8v3.js";import"./chunk-hve2a279.js";import{Dl as V}from"./chunk-y8qhrx11.js";var x=V(W(),1);function B(M){if(M===null||typeof M!=="object")return JSON.stringify(M);if(Array.isArray(M))return JSON.stringify(M.map((J)=>B(J)));let F={},G=Object.keys(M).sort();for(let J of G)F[J]=M[J];return JSON.stringify(F,(J,Q)=>{if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)){let X={},Y=Object.keys(Q).sort();for(let Z of Y)X[Z]=Q[Z];return X}return Q})}var P=[{index:"checkpoints",prefix:"checkpoint:",schema:{"$.thread_id":{type:"TAG",AS:"thread_id"},"$.checkpoint_ns":{type:"TAG",AS:"checkpoint_ns"},"$.checkpoint_id":{type:"TAG",AS:"checkpoint_id"},"$.parent_checkpoint_id":{type:"TAG",AS:"parent_checkpoint_id"},"$.checkpoint_ts":{type:"NUMERIC",AS:"checkpoint_ts"},"$.has_writes":{type:"TAG",AS:"has_writes"},"$.source":{type:"TAG",AS:"source"},"$.step":{type:"NUMERIC",AS:"step"}}},{index:"checkpoint_writes",prefix:"checkpoint_write:",schema:{"$.thread_id":{type:"TAG",AS:"thread_id"},"$.checkpoint_ns":{type:"TAG",AS:"checkpoint_ns"},"$.checkpoint_id":{type:"TAG",AS:"checkpoint_id"},"$.task_id":{type:"TAG",AS:"task_id"},"$.idx":{type:"NUMERIC",AS:"idx"},"$.channel":{type:"TAG",AS:"channel"},"$.type":{type:"TAG",AS:"type"}}}],N=class M extends R{client;ttlConfig;constructor(F,G){super();this.client=F,this.ttlConfig=G}static async fromUrl(F,G){let J=x.createClient({url:F});await J.connect();let Q=new M(J,G);return await Q.ensureIndexes(),Q}async get(F){return(await this.getTuple(F))?.checkpoint}async put(F,G,J,Q){await this.ensureIndexes();let X=F.configurable?.thread_id,Y=F.configurable?.checkpoint_ns??"",Z=F.configurable?.checkpoint_id;if(!X)throw Error("thread_id is required");let _=G.id||q(0),E=`checkpoint:${X}:${Y}:shallow`,H=null,$=null;try{if(H=await this.client.json.get(E),H&&typeof H==="object")$=H.checkpoint_id}catch(O){}if($&&$!==_)await this.cleanupOldCheckpoint(X,Y,$);let L={...G,channel_values:G.channel_values||{},channel_blobs:void 0},U={thread_id:X,checkpoint_ns:Y,checkpoint_id:_,parent_checkpoint_id:Z||null,checkpoint:L,metadata:this.sanitizeMetadata(J),checkpoint_ts:Date.now(),has_writes:"false"};if(this.addSearchableMetadataFields(U,J),await this.client.json.set(E,"$",U),this.ttlConfig?.defaultTTL)await this.applyTTL(E);return{configurable:{thread_id:X,checkpoint_ns:Y,checkpoint_id:_}}}async getTuple(F){let G=F.configurable?.thread_id,J=F.configurable?.checkpoint_ns??"",Q=F.configurable?.checkpoint_id;if(!G)return;let X=`checkpoint:${G}:${J}:shallow`,Y=await this.client.json.get(X);if(!Y)return;if(Q&&Y.checkpoint_id!==Q)return;if(this.ttlConfig?.refreshOnRead&&this.ttlConfig?.defaultTTL)await this.applyTTL(X);let Z=await this.serde.loadsTyped("json",JSON.stringify(Y.checkpoint)),_;if(Y.has_writes==="true")_=await this.loadPendingWrites(Y.thread_id,Y.checkpoint_ns,Y.checkpoint_id);return await this.createCheckpointTuple(Y,Z,_)}async*list(F,G){if(await this.ensureIndexes(),F?.configurable?.thread_id){let J=await this.getTuple(F);if(J)if(G?.filter){if(this.checkMetadataFilterMatch(J.metadata,G.filter))yield J}else yield J}else{let J=[];if(G?.filter){for(let[Y,Z]of Object.entries(G.filter))if(Z===void 0);else if(Z===null);else if(typeof Z==="string"){let _=A(Y),E=A(Z);J.push(`(@${_}:{${E}})`)}else if(typeof Z==="number"){let _=A(Y);J.push(`(@${_}:[${Z} ${Z}])`)}}if(J.length===0)J.push("*");let Q=J.join(" "),X=G?.limit??10;try{let Y=await this.client.ft.search("checkpoints",Q,{LIMIT:{from:0,size:X*2},SORTBY:{BY:"checkpoint_ts",DIRECTION:"DESC"}}),Z=new Set,_=0;for(let E of Y.documents){if(_>=X)break;let H=E.value,$=`${H.thread_id}:${H.checkpoint_ns}`;if(Z.has($))continue;if(Z.add($),G?.filter){if(!this.checkMetadataFilterMatch(H.metadata,G.filter))continue}let L=await this.serde.loadsTyped("json",JSON.stringify(H.checkpoint));yield await this.createCheckpointTuple(H,L),_++}}catch(Y){if(Y.message?.includes("no such index")){let Z=await this.client.keys("checkpoint:*:*:shallow");if(Z.length===0)return;Z.sort().reverse();let _=new Set,E=0,H=G?.limit??10;for(let $ of Z){if(E>=H)break;let L=await this.client.json.get($);if(!L)continue;let U=`${L.thread_id}:${L.checkpoint_ns}`;if(_.has(U))continue;if(_.add(U),G?.filter){if(!this.checkMetadataFilterMatch(L.metadata,G.filter))continue}let O=await this.serde.loadsTyped("json",JSON.stringify(L.checkpoint));yield await this.createCheckpointTuple(L,O),E++}return}throw Y}}}async putWrites(F,G,J){await this.ensureIndexes();let Q=F.configurable?.thread_id,X=F.configurable?.checkpoint_ns??"",Y=F.configurable?.checkpoint_id;if(!Q||!Y)throw Error("thread_id and checkpoint_id are required");let Z=`checkpoint_write:${Q}:${X}:${Y}:${J}:*`,_=await this.client.keys(Z);if(_.length>0)await this.client.del(_);let E=[];for(let $=0;$<G.length;$++){let[L,U]=G[$],O=`checkpoint_write:${Q}:${X}:${Y}:${J}:${$}`;E.push(O);let T={thread_id:Q,checkpoint_ns:X,checkpoint_id:Y,task_id:J,idx:$,channel:L,type:typeof U==="object"?"json":"string",value:U};await this.client.json.set(O,"$",T)}if(E.length>0){let $=`write_keys_zset:${Q}:${X}:${Y}`,L={};if(E.forEach((U,O)=>{L[U]=O}),await this.client.zAdd($,Object.entries(L).map(([U,O])=>({score:O,value:U}))),this.ttlConfig?.defaultTTL)await this.applyTTL(...E,$)}let H=`checkpoint:${Q}:${X}:shallow`;if(await this.client.exists(H)){let $=await this.client.json.get(H);if($)$.has_writes="true",await this.client.json.set(H,"$",$)}}async deleteThread(F){let G=`checkpoint:${F}:*:shallow`,J=await this.client.keys(G);if(J.length>0)await this.client.del(J);let Q=`checkpoint_write:${F}:*`,X=await this.client.keys(Q);if(X.length>0)await this.client.del(X);let Y=`write_keys_zset:${F}:*`,Z=await this.client.keys(Y);if(Z.length>0)await this.client.del(Z)}async end(){await this.client.quit()}addSearchableMetadataFields(F,G){if(!G)return;if("source"in G)F.source=G.source;if("step"in G)F.step=G.step;if("writes"in G)F.writes=typeof G.writes==="object"?JSON.stringify(G.writes):G.writes;if("score"in G)F.score=G.score}async createCheckpointTuple(F,G,J){let Q=await this.serde.loadsTyped("json",JSON.stringify(F.metadata));return{config:{configurable:{thread_id:F.thread_id,checkpoint_ns:F.checkpoint_ns,checkpoint_id:F.checkpoint_id}},checkpoint:G,metadata:Q,parentConfig:F.parent_checkpoint_id?{configurable:{thread_id:F.thread_id,checkpoint_ns:F.checkpoint_ns,checkpoint_id:F.parent_checkpoint_id}}:void 0,pendingWrites:J}}async applyTTL(...F){if(!this.ttlConfig?.defaultTTL)return;let G=Math.floor(this.ttlConfig.defaultTTL*60),J=await Promise.allSettled(F.map((Q)=>this.client.expire(Q,G)));for(let Q=0;Q<J.length;Q++)if(J[Q].status==="rejected")console.warn(`Failed to set TTL for key ${F[Q]}:`,J[Q].reason)}async loadPendingWrites(F,G,J){let Q=`write_keys_zset:${F}:${G}:${J}`,X=await this.client.zRange(Q,0,-1);if(X.length===0)return;let Y=[];for(let Z of X){let _=await this.client.json.get(Z);if(_){let E=await this.serde.loadsTyped("json",JSON.stringify(_.value));Y.push([_.task_id,_.channel,E])}}return Y}checkMetadataFilterMatch(F,G){for(let[J,Q]of Object.entries(G)){let X=F?.[J];if(Q===null){if(!(J in(F||{}))||X!==null)return!1}else if(typeof Q==="object"&&!Array.isArray(Q)){if(typeof X!=="object"||X===null)return!1;if(B(Q)!==B(X))return!1}else if(X!==Q)return!1}return!0}async cleanupOldCheckpoint(F,G,J){let Q=`checkpoint_write:${F}:${G}:${J}:*`,X=await this.client.keys(Q);if(X.length>0)await this.client.del(X);let Y=`write_keys_zset:${F}:${G}:${J}`;await this.client.del(Y);let Z=`checkpoint_blob:${F}:${G}:${J}:*`,_=await this.client.keys(Z);if(_.length>0)await this.client.del(_)}sanitizeMetadata(F){if(!F)return{};let G={};for(let[J,Q]of Object.entries(F)){let X=J.replace(/\x00/g,"");G[X]=typeof Q==="string"?Q.replace(/\x00/g,""):Q}return G}async ensureIndexes(){for(let F of P)try{await this.client.ft.create(F.index,F.schema,{ON:"JSON",PREFIX:F.prefix})}catch(G){if(!G.message?.includes("Index already exists"))console.error(`Failed to create index ${F.index}:`,G.message)}}};export{N as ShallowRedisSaver};
@@ -1,2 +0,0 @@
1
- import{C as W0}from"./chunk-pzb224c5.js";import{we as y1}from"./chunk-c7kd2qrp.js";import{gg as x1}from"./chunk-t6440ajd.js";import{Jk as S}from"./chunk-q1cxrg0x.js";import{tl as C}from"./chunk-tjg2e8v3.js";import{Dl as I0,Fl as J1}from"./chunk-y8qhrx11.js";var C0=J1((K1)=>{Object.defineProperty(K1,"__esModule",{value:!0});K1.Allow=K1.ALL=K1.COLLECTION=K1.ATOM=K1.SPECIAL=K1.INF=K1._INFINITY=K1.INFINITY=K1.NAN=K1.BOOL=K1.NULL=K1.OBJ=K1.ARR=K1.NUM=K1.STR=void 0;K1.STR=1;K1.NUM=2;K1.ARR=4;K1.OBJ=8;K1.NULL=16;K1.BOOL=32;K1.NAN=64;K1.INFINITY=128;K1._INFINITY=256;K1.INF=K1.INFINITY|K1._INFINITY;K1.SPECIAL=K1.NULL|K1.BOOL|K1.INF|K1.NAN;K1.ATOM=K1.STR|K1.NUM|K1.SPECIAL;K1.COLLECTION=K1.ARR|K1.OBJ;K1.ALL=K1.ATOM|K1.COLLECTION;K1.Allow={STR:K1.STR,NUM:K1.NUM,ARR:K1.ARR,OBJ:K1.OBJ,NULL:K1.NULL,BOOL:K1.BOOL,NAN:K1.NAN,INFINITY:K1.INFINITY,_INFINITY:K1._INFINITY,INF:K1.INF,SPECIAL:K1.SPECIAL,ATOM:K1.ATOM,COLLECTION:K1.COLLECTION,ALL:K1.ALL};K1.default=K1.Allow});var z1=J1((L)=>{var s1=L&&L.__createBinding||(Object.create?function(Y,X,Z,$){if($===void 0)$=Z;var B=Object.getOwnPropertyDescriptor(X,Z);if(!B||("get"in B?!X.__esModule:B.writable||B.configurable))B={enumerable:!0,get:function(){return X[Z]}};Object.defineProperty(Y,$,B)}:function(Y,X,Z,$){if($===void 0)$=Z;Y[$]=X[Z]}),t1=L&&L.__exportStar||function(Y,X){for(var Z in Y)if(Z!=="default"&&!Object.prototype.hasOwnProperty.call(X,Z))s1(X,Y,Z)};Object.defineProperty(L,"__esModule",{value:!0});L.Allow=L.MalformedJSON=L.PartialJSON=L.parseJSON=L.parse=void 0;var b=C0();Object.defineProperty(L,"Allow",{enumerable:!0,get:function(){return b.Allow}});t1(C0(),L);class S0 extends Error{}L.PartialJSON=S0;class h0 extends Error{}L.MalformedJSON=h0;function Q1(Y,X=b.Allow.ALL){if(typeof Y!=="string")throw TypeError(`expecting str, got ${typeof Y}`);if(!Y.trim())throw Error(`${Y} is empty`);return a1(Y.trim(),X)}L.parseJSON=Q1;var a1=(Y,X)=>{let Z=Y.length,$=0,B=(D)=>{throw new S0(`${D} at position ${$}`)},W=(D)=>{throw new h0(`${D} at position ${$}`)},J=()=>{if(F(),$>=Z)B("Unexpected end of input");if(Y[$]==='"')return V();if(Y[$]==="{")return K();if(Y[$]==="[")return Q();if(Y.substring($,$+4)==="null"||b.Allow.NULL&X&&Z-$<4&&"null".startsWith(Y.substring($)))return $+=4,null;if(Y.substring($,$+4)==="true"||b.Allow.BOOL&X&&Z-$<4&&"true".startsWith(Y.substring($)))return $+=4,!0;if(Y.substring($,$+5)==="false"||b.Allow.BOOL&X&&Z-$<5&&"false".startsWith(Y.substring($)))return $+=5,!1;if(Y.substring($,$+8)==="Infinity"||b.Allow.INFINITY&X&&Z-$<8&&"Infinity".startsWith(Y.substring($)))return $+=8,1/0;if(Y.substring($,$+9)==="-Infinity"||b.Allow._INFINITY&X&&1<Z-$&&Z-$<9&&"-Infinity".startsWith(Y.substring($)))return $+=9,-1/0;if(Y.substring($,$+3)==="NaN"||b.Allow.NAN&X&&Z-$<3&&"NaN".startsWith(Y.substring($)))return $+=3,NaN;return G()},V=()=>{let D=$,N=!1;$++;while($<Z&&(Y[$]!=='"'||N&&Y[$-1]==="\\"))N=Y[$]==="\\"?!N:!1,$++;if(Y.charAt($)=='"')try{return JSON.parse(Y.substring(D,++$-Number(N)))}catch(U){W(String(U))}else if(b.Allow.STR&X)try{return JSON.parse(Y.substring(D,$-Number(N))+'"')}catch(U){return JSON.parse(Y.substring(D,Y.lastIndexOf("\\"))+'"')}B("Unterminated string literal")},K=()=>{$++,F();let D={};try{while(Y[$]!=="}"){if(F(),$>=Z&&b.Allow.OBJ&X)return D;let N=V();F(),$++;try{let U=J();D[N]=U}catch(U){if(b.Allow.OBJ&X)return D;else throw U}if(F(),Y[$]===",")$++}}catch(N){if(b.Allow.OBJ&X)return D;else B("Expected '}' at end of object")}return $++,D},Q=()=>{$++;let D=[];try{while(Y[$]!=="]")if(D.push(J()),F(),Y[$]===",")$++}catch(N){if(b.Allow.ARR&X)return D;B("Expected ']' at end of array")}return $++,D},G=()=>{if($===0){if(Y==="-")W("Not sure what '-' is");try{return JSON.parse(Y)}catch(N){if(b.Allow.NUM&X)try{return JSON.parse(Y.substring(0,Y.lastIndexOf("e")))}catch(U){}W(String(N))}}let D=$;if(Y[$]==="-")$++;while(Y[$]&&",]}".indexOf(Y[$])===-1)$++;if($==Z&&!(b.Allow.NUM&X))B("Unterminated number literal");try{return JSON.parse(Y.substring(D,$))}catch(N){if(Y.substring(D,$)==="-")B("Not sure what '-' is");try{return JSON.parse(Y.substring(D,Y.lastIndexOf("e")))}catch(U){W(String(U))}}},F=()=>{while($<Z&&`
2
- \r `.includes(Y[$]))$++};return J()},o1=Q1;L.parse=o1});var R=I0(y1(),1);var W1=Symbol("clean");var v=[],g=0,Y0=4,i1=0,f=(Y)=>{let X=[],Z={get(){if(!Z.lc)Z.listen(()=>{})();return Z.value},lc:0,listen($){return Z.lc=X.push($),()=>{for(let W=g+Y0;W<v.length;)if(v[W]===$)v.splice(W,Y0);else W+=Y0;let B=X.indexOf($);if(~B){if(X.splice(B,1),!--Z.lc)Z.off()}}},notify($,B){i1++;let W=!v.length;for(let J of X)v.push(J,Z.value,$,B);if(W){for(g=0;g<v.length;g+=Y0)v[g](v[g+1],v[g+2],v[g+3]);v.length=0}},off(){},set($){let B=Z.value;if(B!==$)Z.value=$,Z.notify(B)},subscribe($){let B=Z.listen($);return $(Z.value),B},value:Y};return Z[W1]=()=>{X=[],Z.lc=0,Z.off()},Z};var _0=(Y,X)=>{if(!Array.isArray(Y))Y=[Y];let Z=[],$,B=()=>{$&&$();let W=Y.map((J)=>J.get());$=X(...W)};return Z=Y.map((W)=>W.listen(B)),B(),()=>{Z.forEach((W)=>W()),$&&$()}};function O0(Y,X,Z){let $=new Set(X).add(void 0);return Y.listen((B,W,J)=>{if($.has(J))Z(B,W,J)})}var f0=function(Y,X,Z){var $,B,W;X===void 0&&(X=50),Z===void 0&&(Z={});var J=($=Z.isImmediate)!=null&&$,V=(B=Z.callback)!=null&&B,K=Z.maxWait,Q=Date.now(),G=[];function F(){if(K!==void 0){var N=Date.now()-Q;if(N+X>=K)return K-N}return X}var D=function(){var N=[].slice.call(arguments),U=this;return new Promise(function(_,P){var q=J&&W===void 0;if(W!==void 0&&clearTimeout(W),W=setTimeout(function(){if(W=void 0,Q=Date.now(),!J){var M=Y.apply(U,N);V&&V(M),G.forEach(function(h){return(0,h.resolve)(M)}),G=[]}},F()),q){var E=Y.apply(U,N);return V&&V(E),_(E)}G.push({resolve:_,reject:P})})};return D.cancel=function(N){W!==void 0&&clearTimeout(W),G.forEach(function(U){return(0,U.reject)(N)}),G=[]},D};var Z0=I0(z1(),1);var X0=(Y)=>{return Y.name+JSON.stringify(Y.args)};class o{message;client;constructor(Y,X){this.message=Y,this.client=X}getToolActionRequestID(){return X0({name:this.message.name,args:this.getInputRepaired()})}getHumanInTheLoopData(){let Y=this.getToolActionRequestID();if(!this.client.humanInTheLoop)return null;let X=this.client.humanInTheLoop.interruptData.find(($)=>$.value.actionRequests.some((B)=>B.id===Y));if(!X)return null;let Z=X.value.actionRequests.findIndex(($)=>$.id===Y);if(Z===-1)return null;return{actionRequestIndex:Z,config:X,reviewConfig:X.value.reviewConfigs.find(($)=>$.actionName===X.value.actionRequests[Z].name),actionRequest:X.value.actionRequests[Z],result:this.client.humanInTheLoop.result[Y]}}sendResumeData(Y){if(Y.type==="edit")Y.editedAction=Y.edited_action;return this.client.doneHumanInTheLoopWaiting(this.message.id,this.getToolActionRequestID(),Y)}get state(){if(this.message.type==="tool"&&this.message?.additional_kwargs?.done)return"done";let Y=this.getHumanInTheLoopData();if(Y?.result)return"done";if(this.client.status==="interrupted"&&Y?.actionRequest)return"interrupted";if(this.message.tool_input)return"loading";return"idle"}get input(){try{return JSON.parse(this.message.tool_input)}catch(Y){return null}}get output(){return G1(this.message.content)}getJSONOutput(){return JSON.parse(this.output)}getJSONOutputSafe(){try{return JSON.parse(this.output)}catch(Y){return null}}getInputRepaired(){try{return Z0.parse(this.message.tool_input||"",Z0.Allow.ALL)}catch(Y){return{}}}response(Y){this.client.doneFEToolWaiting(this.message.id,JSON.stringify(Y))}}var e1=(...Y)=>fetch(...Y),YY=Symbol.for("lg:fetch_implementation");var D1=()=>{return globalThis[YY]??e1};var XY=Object.prototype.toString,ZY=(Y)=>XY.call(Y)==="[object Error]",$Y=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function y0(Y){if(!(Y&&ZY(Y)&&Y.name==="TypeError"&&typeof Y.message==="string"))return!1;let{message:Z,stack:$}=Y;if(Z==="Load failed")return $===void 0||"__sentry_captured__"in Y;if(Z.startsWith("error sending request for url"))return!0;return $Y.has(Z)}function BY(Y){if(typeof Y==="number"){if(Y<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(Y))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(Y!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function $0(Y,X,{min:Z=0,allowInfinity:$=!1}={}){if(X===void 0)return;if(typeof X!=="number"||Number.isNaN(X))throw TypeError(`Expected \`${Y}\` to be a number${$?" or Infinity":""}.`);if(!$&&!Number.isFinite(X))throw TypeError(`Expected \`${Y}\` to be a finite number.`);if(X<Z)throw TypeError(`Expected \`${Y}\` to be ≥ ${Z}.`)}class H1 extends Error{constructor(Y){super();if(Y instanceof Error)this.originalError=Y,{message:Y}=Y;else this.originalError=Error(Y),this.originalError.stack=this.stack;this.name="AbortError",this.message=Y}}function WY(Y,X){let Z=Math.max(1,Y+1),$=X.randomize?Math.random()+1:1,B=Math.round($*X.minTimeout*X.factor**(Z-1));return B=Math.min(B,X.maxTimeout),B}function F1(Y,X){if(!Number.isFinite(X))return X;return X-(performance.now()-Y)}async function JY({error:Y,attemptNumber:X,retriesConsumed:Z,startTime:$,options:B}){let W=Y instanceof Error?Y:TypeError(`Non-error was thrown: "${Y}". You should only throw errors.`);if(W instanceof H1)throw W.originalError;let J=Number.isFinite(B.retries)?Math.max(0,B.retries-Z):B.retries,V=B.maxRetryTime??Number.POSITIVE_INFINITY,K=Object.freeze({error:W,attemptNumber:X,retriesLeft:J,retriesConsumed:Z});if(await B.onFailedAttempt(K),F1($,V)<=0)throw W;let Q=await B.shouldConsumeRetry(K),G=F1($,V);if(G<=0||J<=0)throw W;if(W instanceof TypeError&&!y0(W)){if(Q)throw W;return B.signal?.throwIfAborted(),!1}if(!await B.shouldRetry(K))throw W;if(!Q)return B.signal?.throwIfAborted(),!1;let F=WY(Z,B),D=Math.min(F,G);if(B.signal?.throwIfAborted(),D>0)await new Promise((N,U)=>{let _=()=>{clearTimeout(P),B.signal?.removeEventListener("abort",_),U(B.signal.reason)},P=setTimeout(()=>{B.signal?.removeEventListener("abort",_),N()},D);if(B.unref)P.unref?.();B.signal?.addEventListener("abort",_,{once:!0})});return B.signal?.throwIfAborted(),!0}async function g0(Y,X={}){if(X={...X},BY(X.retries),Object.hasOwn(X,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");if(X.retries??=10,X.factor??=2,X.minTimeout??=1000,X.maxTimeout??=Number.POSITIVE_INFINITY,X.maxRetryTime??=Number.POSITIVE_INFINITY,X.randomize??=!1,X.onFailedAttempt??=()=>{},X.shouldRetry??=()=>!0,X.shouldConsumeRetry??=()=>!0,$0("factor",X.factor,{min:0,allowInfinity:!1}),$0("minTimeout",X.minTimeout,{min:0,allowInfinity:!1}),$0("maxTimeout",X.maxTimeout,{min:0,allowInfinity:!0}),$0("maxRetryTime",X.maxRetryTime,{min:0,allowInfinity:!0}),!(X.factor>0))X.factor=1;X.signal?.throwIfAborted();let Z=0,$=0,B=performance.now();while(Number.isFinite(X.retries)?$<=X.retries:!0){Z++;try{X.signal?.throwIfAborted();let W=await Y(Z);return X.signal?.throwIfAborted(),W}catch(W){if(await JY({error:W,attemptNumber:Z,retriesConsumed:$,startTime:B,options:X}))$++}}throw Error("Retry attempts exhausted without throwing an error.")}class m0 extends Error{name="TimeoutError";constructor(Y,X){super(Y,X);Error.captureStackTrace?.(this,m0)}}var N1=(Y)=>Y.reason??new DOMException("This operation was aborted.","AbortError");function u0(Y,X){let{milliseconds:Z,fallback:$,message:B,customTimers:W={setTimeout,clearTimeout},signal:J}=X,V,K,G=new Promise((F,D)=>{if(typeof Z!=="number"||Math.sign(Z)!==1)throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${Z}\``);if(J?.aborted){D(N1(J));return}if(J)K=()=>{D(N1(J))},J.addEventListener("abort",K,{once:!0});if(Y.then(F,D),Z===Number.POSITIVE_INFINITY)return;let N=new m0;V=W.setTimeout.call(void 0,()=>{if($){try{F($())}catch(U){D(U)}return}if(typeof Y.cancel==="function")Y.cancel();if(B===!1)F();else if(B instanceof Error)D(B);else N.message=B??`Promise timed out after ${Z} milliseconds`,D(N)},Z)}).finally(()=>{if(G.clear(),K&&J)J.removeEventListener("abort",K)});return G.clear=()=>{W.clearTimeout.call(void 0,V),V=void 0},G}function c0(Y,X,Z){let $=0,B=Y.length;while(B>0){let W=Math.trunc(B/2),J=$+W;if(Z(Y[J],X)<=0)$=++J,B-=W+1;else B=W}return $}class B0{#Z=[];enqueue(Y,X){let{priority:Z=0,id:$}=X??{},B={priority:Z,id:$,run:Y};if(this.size===0||this.#Z[this.size-1].priority>=Z){this.#Z.push(B);return}let W=c0(this.#Z,B,(J,V)=>V.priority-J.priority);this.#Z.splice(W,0,B)}setPriority(Y,X){let Z=this.#Z.findIndex((B)=>B.id===Y);if(Z===-1)throw ReferenceError(`No promise function with the id "${Y}" exists in the queue.`);let[$]=this.#Z.splice(Z,1);this.enqueue($.run,{priority:X,id:Y})}dequeue(){return this.#Z.shift()?.run}filter(Y){return this.#Z.filter((X)=>X.priority===Y.priority).map((X)=>X.run)}get size(){return this.#Z.length}}class d extends W0.default{#Z;#Y;#X=0;#Q;#H=!1;#D=!1;#z;#J=0;#_=0;#G;#F;#V;#K=[];#B=0;#$;#M;#W=0;#f;#N;#k=1n;#A=new Map;timeout;constructor(Y){super();if(Y={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:B0,strict:!1,...Y},!(typeof Y.intervalCap==="number"&&Y.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${Y.intervalCap?.toString()??""}\` (${typeof Y.intervalCap})`);if(Y.interval===void 0||!(Number.isFinite(Y.interval)&&Y.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${Y.interval?.toString()??""}\` (${typeof Y.interval})`);if(Y.strict&&Y.interval===0)throw TypeError("The `strict` option requires a non-zero `interval`");if(Y.strict&&Y.intervalCap===Number.POSITIVE_INFINITY)throw TypeError("The `strict` option requires a finite `intervalCap`");if(this.#Z=Y.carryoverIntervalCount??Y.carryoverConcurrencyCount??!1,this.#Y=Y.intervalCap===Number.POSITIVE_INFINITY||Y.interval===0,this.#Q=Y.intervalCap,this.#z=Y.interval,this.#V=Y.strict,this.#$=new Y.queueClass,this.#M=Y.queueClass,this.concurrency=Y.concurrency,Y.timeout!==void 0&&!(Number.isFinite(Y.timeout)&&Y.timeout>0))throw TypeError(`Expected \`timeout\` to be a positive finite number, got \`${Y.timeout}\` (${typeof Y.timeout})`);this.timeout=Y.timeout,this.#N=Y.autoStart===!1,this.#m()}#P(Y){while(this.#B<this.#K.length){let Z=this.#K[this.#B];if(Z!==void 0&&Y-Z>=this.#z)this.#B++;else break}if(this.#B>100&&this.#B>this.#K.length/2||this.#B===this.#K.length)this.#K=this.#K.slice(this.#B),this.#B=0}#v(Y){if(this.#V)this.#K.push(Y);else this.#X++}#C(){if(this.#V){if(this.#K.length>this.#B)this.#K.pop()}else if(this.#X>0)this.#X--}#L(){return this.#K.length-this.#B}get#S(){if(this.#Y)return!0;if(this.#V)return this.#L()<this.#Q;return this.#X<this.#Q}get#h(){return this.#W<this.#f}#I(){if(this.#W--,this.#W===0)this.emit("pendingZero");this.#b(),this.emit("next")}#y(){this.#F=void 0,this.#x(),this.#T()}#g(Y){if(this.#V){if(this.#P(Y),this.#L()>=this.#Q){let Z=this.#K[this.#B],$=this.#z-(Y-Z);return this.#E($),!0}return!1}if(this.#G===void 0){let X=this.#J-Y;if(X<0){if(this.#_>0){let Z=Y-this.#_;if(Z<this.#z)return this.#E(this.#z-Z),!0}this.#X=this.#Z?this.#W:0}else return this.#E(X),!0}return!1}#E(Y){if(this.#F!==void 0)return;this.#F=setTimeout(()=>{this.#y()},Y)}#q(){if(this.#G)clearInterval(this.#G),this.#G=void 0}#w(){if(this.#F)clearTimeout(this.#F),this.#F=void 0}#b(){if(this.#$.size===0){if(this.#q(),this.emit("empty"),this.#W===0){if(this.#w(),this.#V&&this.#B>0){let X=Date.now();this.#P(X)}this.emit("idle")}return!1}let Y=!1;if(!this.#N){let X=Date.now(),Z=!this.#g(X);if(this.#S&&this.#h){let $=this.#$.dequeue();if(!this.#Y)this.#v(X),this.#O();if(this.emit("active"),$(),Z)this.#T();Y=!0}}return Y}#T(){if(this.#Y||this.#G!==void 0)return;if(this.#V)return;this.#G=setInterval(()=>{this.#x()},this.#z),this.#J=Date.now()+this.#z}#x(){if(!this.#V){if(this.#X===0&&this.#W===0&&this.#G)this.#q();this.#X=this.#Z?this.#W:0}this.#R(),this.#O()}#R(){while(this.#b());}get concurrency(){return this.#f}set concurrency(Y){if(!(typeof Y==="number"&&Y>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${Y}\` (${typeof Y})`);this.#f=Y,this.#R()}setPriority(Y,X){if(typeof X!=="number"||!Number.isFinite(X))throw TypeError(`Expected \`priority\` to be a finite number, got \`${X}\` (${typeof X})`);this.#$.setPriority(Y,X)}async add(Y,X={}){return X={timeout:this.timeout,...X,id:X.id??(this.#k++).toString()},new Promise((Z,$)=>{let B=Symbol(`task-${X.id}`);this.#$.enqueue(async()=>{this.#W++,this.#A.set(B,{id:X.id,priority:X.priority??0,startTime:Date.now(),timeout:X.timeout});let W;try{try{X.signal?.throwIfAborted()}catch(K){throw this.#u(),this.#A.delete(B),K}this.#_=Date.now();let J=Y({signal:X.signal});if(X.timeout)J=u0(Promise.resolve(J),{milliseconds:X.timeout,message:`Task timed out after ${X.timeout}ms (queue has ${this.#W} running, ${this.#$.size} waiting)`});if(X.signal){let{signal:K}=X;J=Promise.race([J,new Promise((Q,G)=>{W=()=>{G(K.reason)},K.addEventListener("abort",W,{once:!0})})])}let V=await J;Z(V),this.emit("completed",V)}catch(J){$(J),this.emit("error",J)}finally{if(W)X.signal?.removeEventListener("abort",W);this.#A.delete(B),queueMicrotask(()=>{this.#I()})}},X),this.emit("add"),this.#b()})}async addAll(Y,X){return Promise.all(Y.map(async(Z)=>this.add(Z,X)))}start(){if(!this.#N)return this;return this.#N=!1,this.#R(),this}pause(){this.#N=!0}clear(){if(this.#$=new this.#M,this.#q(),this.#j(),this.emit("empty"),this.#W===0)this.#w(),this.emit("idle");this.emit("next")}async onEmpty(){if(this.#$.size===0)return;await this.#U("empty")}async onSizeLessThan(Y){if(this.#$.size<Y)return;await this.#U("next",()=>this.#$.size<Y)}async onIdle(){if(this.#W===0&&this.#$.size===0)return;await this.#U("idle")}async onPendingZero(){if(this.#W===0)return;await this.#U("pendingZero")}async onRateLimit(){if(this.isRateLimited)return;await this.#U("rateLimit")}async onRateLimitCleared(){if(!this.isRateLimited)return;await this.#U("rateLimitCleared")}onError(){return new Promise((Y,X)=>{let Z=($)=>{this.off("error",Z),X($)};this.on("error",Z)})}async#U(Y,X){return new Promise((Z)=>{let $=()=>{if(X&&!X())return;this.off(Y,$),Z()};this.on(Y,$)})}get size(){return this.#$.size}sizeBy(Y){return this.#$.filter(Y).length}get pending(){return this.#W}get isPaused(){return this.#N}#m(){if(this.#Y)return;this.on("add",()=>{if(this.#$.size>0)this.#O()}),this.on("next",()=>{this.#O()})}#O(){if(this.#Y||this.#D)return;this.#D=!0,queueMicrotask(()=>{this.#D=!1,this.#j()})}#u(){if(this.#Y)return;this.#C(),this.#O()}#j(){let Y=this.#H;if(this.#Y||this.#$.size===0){if(Y)this.#H=!1,this.emit("rateLimitCleared");return}let X;if(this.#V){let $=Date.now();this.#P($),X=this.#L()}else X=this.#X;let Z=X>=this.#Q;if(Z!==Y)this.#H=Z,this.emit(Z?"rateLimit":"rateLimitCleared")}get isRateLimited(){return this.#H}get isSaturated(){return this.#W===this.#f&&this.#$.size>0||this.isRateLimited&&this.#$.size>0}get runningTasks(){return[...this.#A.values()].map((Y)=>({...Y}))}}var KY=[400,401,402,403,404,405,406,407,408,409,422];function VY(Y){if(Y==null||typeof Y!=="object")return!1;return"status"in Y&&"statusText"in Y&&"text"in Y}var U1=class Y extends Error{status;text;response;constructor(X,Z,$){super(`HTTP ${X}: ${Z}`);this.status=X,this.text=Z,this.response=$}static async fromResponse(X,Z){try{return new Y(X.status,await X.text(),Z?.includeResponse?X:void 0)}catch{return new Y(X.status,X.statusText,Z?.includeResponse?X:void 0)}}},_1=class{maxConcurrency;maxRetries;queue;onFailedResponseHook;customFetch;constructor(Y){if(this.maxConcurrency=Y.maxConcurrency??1/0,this.maxRetries=Y.maxRetries??4,"default"in d)this.queue=new d.default({concurrency:this.maxConcurrency});else this.queue=new d({concurrency:this.maxConcurrency});this.onFailedResponseHook=Y?.onFailedResponseHook,this.customFetch=Y.fetch}call(Y,...X){let{onFailedResponseHook:Z}=this;return this.queue.add(()=>g0(()=>Y(...X).catch(async($)=>{if($ instanceof Error)throw $;else if(VY($))throw await U1.fromResponse($,{includeResponse:!!Z});else throw Error($)}),{async onFailedAttempt({error:$}){let B=$.message??"";if(B.startsWith("Cancel")||B.startsWith("TimeoutError")||B.startsWith("AbortError"))throw $;if($?.code==="ECONNABORTED")throw $;if(B.includes("ECONNREFUSED")||B.includes("fetch failed")||B.includes("Failed to fetch")||B.includes("NetworkError")){let W=Error(`Unable to connect to LangGraph server. Please ensure the server is running and accessible. Original error: ${B}`);throw W.name="ConnectionError",W}if($ instanceof U1){if(KY.includes($.status))throw $;if(Z&&$.response)await Z($.response)}},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(Y,X,...Z){if(Y.signal)return Promise.race([this.call(X,...Z),new Promise(($,B)=>{Y.signal?.addEventListener("abort",()=>{B(Error("AbortError"))})})]);return this.call(X,...Z)}fetch(...Y){let X=this.customFetch??D1();return this.call(()=>X(...Y).then((Z)=>Z.ok?Z:Promise.reject(Z)))}};function O1(Y){try{return typeof process<"u"?process.env?.[Y]:void 0}catch(X){return}}function f1(...Y){let X=Y.filter(($)=>$!=null);if(X.length===0)return;if(X.length===1)return X[0];let Z=new AbortController;for(let $ of Y){if($?.aborted)return Z.abort($.reason),Z.signal;$?.addEventListener("abort",()=>Z.abort($.reason),{once:!0})}return Z.signal}var QY=[13,10];function P1(){let Y=[],X=!1;return new TransformStream({start(){Y=[],X=!1},transform(Z,$){let B=Z;if(X)B=J0([[13],B]),X=!1;if(B.length>0&&B.at(-1)===13)X=!0,B=B.subarray(0,-1);if(!B.length)return;let W=QY.includes(B.at(-1)),J=B.length-1,{lines:V}=B.reduce((K,Q,G)=>{if(K.from>G)return K;if(Q===13||Q===10)if(K.lines.push(B.subarray(K.from,G)),Q===13&&B[G+1]===10)K.from=G+2;else K.from=G+1;if(G===J&&K.from<=J)K.lines.push(B.subarray(K.from));return K},{lines:[],from:0});if(V.length===1&&!W){Y.push(V[0]);return}if(Y.length)Y.push(V[0]),V[0]=J0(Y),Y=[];if(!W){if(V.length)Y=[V.pop()]}for(let K of V)$.enqueue(K)},flush(Z){if(Y.length)Z.enqueue(J0(Y))}})}function L1(){let Y="",X=[],Z="",$=null,B=new TextDecoder;return new TransformStream({transform(W,J){if(!W.length){if(!Y&&!X.length&&!Z&&$==null)return;let G={id:Z||void 0,event:Y,data:X.length?A1(B,X):null};Y="",X=[],$=null,J.enqueue(G);return}if(W[0]===58)return;let V=W.indexOf(58);if(V===-1)return;let K=B.decode(W.subarray(0,V)),Q=W.subarray(V+1);if(Q[0]===32)Q=Q.subarray(1);if(K==="event")Y=B.decode(Q);else if(K==="data")X.push(Q);else if(K==="id"){if(Q.indexOf(0)===-1)Z=B.decode(Q)}else if(K==="retry"){let G=Number.parseInt(B.decode(Q),10);if(!Number.isNaN(G))$=G}},flush(W){if(Y)W.enqueue({id:Z||void 0,event:Y,data:X.length?A1(B,X):null})}})}function J0(Y){let X=Y.reduce((B,W)=>B+W.length,0),Z=new Uint8Array(X),$=0;for(let B of Y)Z.set(B,$),$+=B.length;return Z}function A1(Y,X){return JSON.parse(Y.decode(J0(X)))}var E1=(Y)=>{if("isError"in Error&&typeof Error.isError==="function")return Error.isError(Y);let X=Object.prototype.toString.call(Y);return X==="[object Error]"||X==="[object DOMException]"||X==="[object DOMError]"||X==="[object Exception]"},zY=(Y)=>{let{cause:X}=Y;if(typeof X!=="object"||X==null)return null;if(!E1(X))return null;return X},q1=(Y)=>{if(!E1(Y))return!1;if(Y.name!=="TypeError"||typeof Y.message!=="string")return!1;let X=Y.message.toLowerCase(),Z=zY(Y)?.message?.toLowerCase()??"";return X.includes("fetch")||X.includes("network")||X.includes("connection")||X.includes("error sending request")||X.includes("load failed")||X.includes("terminated")||Z.includes("other side closed")||Z.includes("socket")};var GY=class extends Error{constructor(Y,X){super(`Exceeded maximum SSE reconnection attempts (${Y})`);this.name="MaxReconnectAttemptsError",this.cause=X}};async function*b1(Y,X={}){let Z=X.maxRetries??5,$=0,B,W;while(!0){let J=!1,V,K;try{if(X.signal?.aborted)return;let{response:Q,stream:G}=await Y(W?{lastEventId:B,reconnectPath:W}:void 0),F=Q.headers.get("location");if(F)W=F;let D=Q.headers.get("content-type")?.split(";")[0];if(D&&!D.includes("text/event-stream"))throw Error(`Expected response header Content-Type to contain 'text/event-stream', got '${D}'`);K=G.getReader();try{while(!0){if(X.signal?.aborted){await K.cancel();return}let{done:N,value:U}=await K.read();if(N)break;if(U.id)B=U.id;yield U}break}catch(N){if(W&&!X.signal?.aborted)J=!0;else throw N}finally{if(K)try{K.releaseLock()}catch{}}}catch(Q){if(V=Q,q1(Q)&&W&&!X.signal?.aborted)J=!0;else throw Q}if(J){if($+=1,$>Z)throw new GY(Z,V);X.onReconnect?.({attempt:$,lastEventId:B,cause:V});let Q=Math.min(1000*2**($-1),5000)+Math.random()*1000;await new Promise((G)=>{setTimeout(G,Q)});continue}break}}function*DY(Y){let X,Z=!1;if(Y instanceof Headers){let $=[];Y.forEach((B,W)=>{$.push([W,B])}),X=$}else if(Array.isArray(Y))X=Y;else Z=!0,X=Object.entries(Y??{});for(let $ of X){let B=$[0];if(typeof B!=="string")throw TypeError(`Expected header name to be a string, got ${typeof B}`);let W=Array.isArray($[1])?$[1]:[$[1]],J=!1;for(let V of W){if(V===void 0)continue;if(Z&&!J)J=!0,yield[B,null];yield[B,V]}}}function R1(...Y){let X=new Headers;for(let $ of Y){if(!$)continue;for(let[B,W]of DY($))if(W===null)X.delete(B);else X.append(B,W)}let Z=[];return X.forEach(($,B)=>{Z.push([B,$])}),Object.fromEntries(Z)}function M1(Y){if(Y===null)return;if(Y)return Y;for(let X of["LANGGRAPH","LANGSMITH","LANGCHAIN"]){let Z=O1(`${X}_API_KEY`);if(Z)return Z.trim().replace(/^["']|["']$/g,"")}}var FY=/(\/threads\/(?<thread_id>.+))?\/runs\/(?<run_id>.+)/;function d0(Y){let X=Y.headers.get("Content-Location");if(!X)return;let Z=FY.exec(X);if(!Z?.groups?.run_id)return;return{run_id:Z.groups.run_id,thread_id:Z.groups.thread_id||void 0}}var l=class{asyncCaller;timeoutMs;apiUrl;defaultHeaders;onRequest;constructor(Y){let X={maxRetries:4,maxConcurrency:4,...Y?.callerOptions},Z="http://localhost:8123";if(!Y?.apiUrl&&typeof globalThis==="object"&&globalThis!=null){let B=Symbol.for("langgraph_api:fetch"),W=Symbol.for("langgraph_api:url"),J=globalThis;if(J[B])X.fetch??=J[B];if(J[W])Z=J[W]}this.asyncCaller=new _1(X),this.timeoutMs=Y?.timeoutMs,this.apiUrl=Y?.apiUrl?.replace(/\/$/,"")||Z,this.defaultHeaders=Y?.defaultHeaders||{},this.onRequest=Y?.onRequest;let $=M1(Y?.apiKey);if($)this.defaultHeaders["x-api-key"]=$}prepareFetchOptions(Y,X){let Z={...X,headers:R1(this.defaultHeaders,X?.headers)};if(Z.json)Z.body=JSON.stringify(Z.json),Z.headers=R1(Z.headers,{"content-type":"application/json"}),delete Z.json;if(Z.withResponse)delete Z.withResponse;let $=null;if(typeof X?.timeoutMs<"u"){if(X.timeoutMs!=null)$=AbortSignal.timeout(X.timeoutMs)}else if(this.timeoutMs!=null)$=AbortSignal.timeout(this.timeoutMs);Z.signal=f1($,Z.signal);let B=new URL(`${this.apiUrl}${Y}`);if(Z.params){for(let[W,J]of Object.entries(Z.params)){if(J==null)continue;let V=typeof J==="string"||typeof J==="number"?J.toString():JSON.stringify(J);B.searchParams.append(W,V)}delete Z.params}return[B,Z]}async fetch(Y,X){let[Z,$]=this.prepareFetchOptions(Y,X),B=$;if(this.onRequest)B=await this.onRequest(Z,$);let W=await this.asyncCaller.fetch(Z.toString(),B),J=(()=>{if(W.status===202||W.status===204)return;return W.json()})();if(X?.withResponse)return[await J,W];return J}async*streamWithRetry(Y){yield*b1(async(Z)=>{let $=Z?.reconnectPath||Y.endpoint,B=!!Z?.reconnectPath,W=B?"GET":Y.method||"GET",J=B&&Z?.lastEventId?{...Y.headers,"Last-Event-ID":Z.lastEventId}:Y.headers,[V,K]=this.prepareFetchOptions($,{method:W,timeoutMs:null,signal:Y.signal,headers:J,params:Y.params,json:B?void 0:Y.json});if(this.onRequest!=null)K=await this.onRequest(V,K);let Q=await this.asyncCaller.fetch(V.toString(),K);if(!B&&Y.onInitialResponse)await Y.onInitialResponse(Q);return{response:Q,stream:(Q.body||new ReadableStream({start:(G)=>G.close()})).pipeThrough(P1()).pipeThrough(L1())}},{maxRetries:Y.maxRetries??5,signal:Y.signal,onReconnect:Y.onReconnect})}},HY=class extends l{async createForThread(Y,X,Z){let $={schedule:Z?.schedule,input:Z?.input,config:Z?.config,context:Z?.context,metadata:Z?.metadata,assistant_id:X,interrupt_before:Z?.interruptBefore,interrupt_after:Z?.interruptAfter,webhook:Z?.webhook,multitask_strategy:Z?.multitaskStrategy,if_not_exists:Z?.ifNotExists,checkpoint_during:Z?.checkpointDuring,durability:Z?.durability,enabled:Z?.enabled};return this.fetch(`/threads/${Y}/runs/crons`,{method:"POST",json:$,signal:Z?.signal})}async create(Y,X){let Z={schedule:X?.schedule,input:X?.input,config:X?.config,context:X?.context,metadata:X?.metadata,assistant_id:Y,interrupt_before:X?.interruptBefore,interrupt_after:X?.interruptAfter,webhook:X?.webhook,on_run_completed:X?.onRunCompleted,multitask_strategy:X?.multitaskStrategy,if_not_exists:X?.ifNotExists,checkpoint_during:X?.checkpointDuring,durability:X?.durability,enabled:X?.enabled};return this.fetch("/runs/crons",{method:"POST",json:Z,signal:X?.signal})}async update(Y,X){let Z={};if(X?.schedule!==void 0)Z.schedule=X.schedule;if(X?.endTime!==void 0)Z.end_time=X.endTime;if(X?.input!==void 0)Z.input=X.input;if(X?.metadata!==void 0)Z.metadata=X.metadata;if(X?.config!==void 0)Z.config=X.config;if(X?.context!==void 0)Z.context=X.context;if(X?.webhook!==void 0)Z.webhook=X.webhook;if(X?.interruptBefore!==void 0)Z.interrupt_before=X.interruptBefore;if(X?.interruptAfter!==void 0)Z.interrupt_after=X.interruptAfter;if(X?.onRunCompleted!==void 0)Z.on_run_completed=X.onRunCompleted;if(X?.enabled!==void 0)Z.enabled=X.enabled;return this.fetch(`/runs/crons/${Y}`,{method:"PATCH",json:Z,signal:X?.signal})}async delete(Y,X){await this.fetch(`/runs/crons/${Y}`,{method:"DELETE",signal:X?.signal})}async search(Y){return this.fetch("/runs/crons/search",{method:"POST",json:{assistant_id:Y?.assistantId??void 0,thread_id:Y?.threadId??void 0,enabled:Y?.enabled??void 0,limit:Y?.limit??10,offset:Y?.offset??0,sort_by:Y?.sortBy??void 0,sort_order:Y?.sortOrder??void 0,select:Y?.select??void 0},signal:Y?.signal})}async count(Y){return this.fetch("/runs/crons/count",{method:"POST",json:{assistant_id:Y?.assistantId??void 0,thread_id:Y?.threadId??void 0},signal:Y?.signal})}},NY=class extends l{async get(Y,X){return this.fetch(`/assistants/${Y}`,{signal:X?.signal})}async getGraph(Y,X){return this.fetch(`/assistants/${Y}/graph`,{params:{xray:X?.xray},signal:X?.signal})}async getSchemas(Y,X){return this.fetch(`/assistants/${Y}/schemas`,{signal:X?.signal})}async getSubgraphs(Y,X){if(X?.namespace)return this.fetch(`/assistants/${Y}/subgraphs/${X.namespace}`,{params:{recurse:X?.recurse},signal:X?.signal});return this.fetch(`/assistants/${Y}/subgraphs`,{params:{recurse:X?.recurse},signal:X?.signal})}async create(Y){return this.fetch("/assistants",{method:"POST",json:{graph_id:Y.graphId,config:Y.config,context:Y.context,metadata:Y.metadata,assistant_id:Y.assistantId,if_exists:Y.ifExists,name:Y.name,description:Y.description},signal:Y.signal})}async update(Y,X){return this.fetch(`/assistants/${Y}`,{method:"PATCH",json:{graph_id:X.graphId,config:X.config,context:X.context,metadata:X.metadata,name:X.name,description:X.description},signal:X.signal})}async delete(Y,X){return this.fetch(`/assistants/${Y}?delete_threads=${X?.deleteThreads??!1}`,{method:"DELETE",signal:X?.signal})}async search(Y){let X={graph_id:Y?.graphId??void 0,name:Y?.name??void 0,metadata:Y?.metadata??void 0,limit:Y?.limit??10,offset:Y?.offset??0,sort_by:Y?.sortBy??void 0,sort_order:Y?.sortOrder??void 0,select:Y?.select??void 0},[Z,$]=await this.fetch("/assistants/search",{method:"POST",json:X,withResponse:!0,signal:Y?.signal});if(Y?.includePagination)return{assistants:Z,next:$.headers.get("X-Pagination-Next")};return Z}async count(Y){return this.fetch("/assistants/count",{method:"POST",json:{metadata:Y?.metadata??void 0,graph_id:Y?.graphId??void 0,name:Y?.name??void 0},signal:Y?.signal})}async getVersions(Y,X){return this.fetch(`/assistants/${Y}/versions`,{method:"POST",json:{metadata:X?.metadata??void 0,limit:X?.limit??10,offset:X?.offset??0},signal:X?.signal})}async setLatest(Y,X,Z){return this.fetch(`/assistants/${Y}/latest`,{method:"POST",json:{version:X},signal:Z?.signal})}},UY=class extends l{async get(Y,X){return this.fetch(`/threads/${Y}`,{signal:X?.signal})}async create(Y){let X=typeof Y?.ttl==="number"?{ttl:Y.ttl,strategy:"delete"}:Y?.ttl;return this.fetch("/threads",{method:"POST",json:{metadata:{...Y?.metadata,graph_id:Y?.graphId},thread_id:Y?.threadId,if_exists:Y?.ifExists,supersteps:Y?.supersteps?.map((Z)=>({updates:Z.updates.map(($)=>({values:$.values,command:$.command,as_node:$.asNode}))})),ttl:X},signal:Y?.signal})}async copy(Y,X){return this.fetch(`/threads/${Y}/copy`,{method:"POST",signal:X?.signal})}async update(Y,X){let Z=typeof X?.ttl==="number"?{ttl:X.ttl,strategy:"delete"}:X?.ttl;return this.fetch(`/threads/${Y}`,{method:"PATCH",json:{metadata:X?.metadata,ttl:Z},signal:X?.signal})}async delete(Y,X){return this.fetch(`/threads/${Y}`,{method:"DELETE",signal:X?.signal})}async search(Y){return this.fetch("/threads/search",{method:"POST",json:{metadata:Y?.metadata??void 0,ids:Y?.ids??void 0,limit:Y?.limit??10,offset:Y?.offset??0,status:Y?.status,sort_by:Y?.sortBy,sort_order:Y?.sortOrder,select:Y?.select??void 0,values:Y?.values??void 0},signal:Y?.signal})}async count(Y){return this.fetch("/threads/count",{method:"POST",json:{metadata:Y?.metadata??void 0,values:Y?.values??void 0,status:Y?.status??void 0},signal:Y?.signal})}async getState(Y,X,Z){if(X!=null){if(typeof X!=="string")return this.fetch(`/threads/${Y}/state/checkpoint`,{method:"POST",json:{checkpoint:X,subgraphs:Z?.subgraphs},signal:Z?.signal});return this.fetch(`/threads/${Y}/state/${X}`,{params:{subgraphs:Z?.subgraphs},signal:Z?.signal})}return this.fetch(`/threads/${Y}/state`,{params:{subgraphs:Z?.subgraphs},signal:Z?.signal})}async updateState(Y,X){return this.fetch(`/threads/${Y}/state`,{method:"POST",json:{values:X.values,checkpoint_id:X.checkpointId,checkpoint:X.checkpoint,as_node:X?.asNode},signal:X?.signal})}async patchState(Y,X,Z){let $;if(typeof Y!=="string"){if(typeof Y.configurable?.thread_id!=="string")throw Error("Thread ID is required when updating state with a config.");$=Y.configurable.thread_id}else $=Y;return this.fetch(`/threads/${$}/state`,{method:"PATCH",json:{metadata:X},signal:Z?.signal})}async getHistory(Y,X){return this.fetch(`/threads/${Y}/history`,{method:"POST",json:{limit:X?.limit??10,before:X?.before,metadata:X?.metadata,checkpoint:X?.checkpoint},signal:X?.signal})}async*joinStream(Y,X){yield*this.streamWithRetry({endpoint:`/threads/${Y}/stream`,method:"GET",signal:X?.signal,headers:X?.lastEventId?{"Last-Event-ID":X.lastEventId}:void 0,params:X?.streamMode?{stream_mode:X.streamMode}:void 0})}},_Y=class extends l{async*stream(Y,X,Z){let $={input:Z?.input,command:Z?.command,config:Z?.config,context:Z?.context,metadata:Z?.metadata,stream_mode:Z?.streamMode,stream_subgraphs:Z?.streamSubgraphs,stream_resumable:Z?.streamResumable,feedback_keys:Z?.feedbackKeys,assistant_id:X,interrupt_before:Z?.interruptBefore,interrupt_after:Z?.interruptAfter,checkpoint:Z?.checkpoint,checkpoint_id:Z?.checkpointId,webhook:Z?.webhook,multitask_strategy:Z?.multitaskStrategy,on_completion:Z?.onCompletion,on_disconnect:Z?.onDisconnect,after_seconds:Z?.afterSeconds,if_not_exists:Z?.ifNotExists,checkpoint_during:Z?.checkpointDuring,durability:Z?.durability};yield*this.streamWithRetry({endpoint:Y==null?"/runs/stream":`/threads/${Y}/runs/stream`,method:"POST",json:$,signal:Z?.signal,onInitialResponse:(B)=>{let W=d0(B);if(W)Z?.onRunCreated?.(W)}})}async create(Y,X,Z){let $={input:Z?.input,command:Z?.command,config:Z?.config,context:Z?.context,metadata:Z?.metadata,stream_mode:Z?.streamMode,stream_subgraphs:Z?.streamSubgraphs,stream_resumable:Z?.streamResumable,assistant_id:X,interrupt_before:Z?.interruptBefore,interrupt_after:Z?.interruptAfter,webhook:Z?.webhook,checkpoint:Z?.checkpoint,checkpoint_id:Z?.checkpointId,multitask_strategy:Z?.multitaskStrategy,after_seconds:Z?.afterSeconds,if_not_exists:Z?.ifNotExists,checkpoint_during:Z?.checkpointDuring,durability:Z?.durability,langsmith_tracer:Z?._langsmithTracer?{project_name:Z?._langsmithTracer?.projectName,example_id:Z?._langsmithTracer?.exampleId}:void 0},B=Y===null?"/runs":`/threads/${Y}/runs`,[W,J]=await this.fetch(B,{method:"POST",json:$,signal:Z?.signal,withResponse:!0}),V=d0(J);if(V)Z?.onRunCreated?.(V);return W}async createBatch(Y,X){let Z=Y.map(($)=>({...$,assistant_id:$.assistantId})).map(($)=>{return Object.fromEntries(Object.entries($).filter(([B,W])=>W!==void 0))});return this.fetch("/runs/batch",{method:"POST",json:Z,signal:X?.signal})}async wait(Y,X,Z){let $={input:Z?.input,command:Z?.command,config:Z?.config,context:Z?.context,metadata:Z?.metadata,assistant_id:X,interrupt_before:Z?.interruptBefore,interrupt_after:Z?.interruptAfter,checkpoint:Z?.checkpoint,checkpoint_id:Z?.checkpointId,webhook:Z?.webhook,multitask_strategy:Z?.multitaskStrategy,on_completion:Z?.onCompletion,on_disconnect:Z?.onDisconnect,after_seconds:Z?.afterSeconds,if_not_exists:Z?.ifNotExists,checkpoint_during:Z?.checkpointDuring,durability:Z?.durability,langsmith_tracer:Z?._langsmithTracer?{project_name:Z?._langsmithTracer?.projectName,example_id:Z?._langsmithTracer?.exampleId}:void 0},B=Y==null?"/runs/wait":`/threads/${Y}/runs/wait`,[W,J]=await this.fetch(B,{method:"POST",json:$,timeoutMs:null,signal:Z?.signal,withResponse:!0}),V=d0(J);if(V)Z?.onRunCreated?.(V);if((Z?.raiseError!==void 0?Z.raiseError:!0)&&"__error__"in W&&typeof W.__error__==="object"&&W.__error__&&"error"in W.__error__&&"message"in W.__error__)throw Error(`${W.__error__?.error}: ${W.__error__?.message}`);return W}async list(Y,X){return this.fetch(`/threads/${Y}/runs`,{params:{limit:X?.limit??10,offset:X?.offset??0,status:X?.status??void 0,select:X?.select??void 0},signal:X?.signal})}async get(Y,X,Z){return this.fetch(`/threads/${Y}/runs/${X}`,{signal:Z?.signal})}async cancel(Y,X,Z=!1,$="interrupt",B={}){return this.fetch(`/threads/${Y}/runs/${X}/cancel`,{method:"POST",params:{wait:Z?"1":"0",action:$},signal:B?.signal})}async join(Y,X,Z){return this.fetch(`/threads/${Y}/runs/${X}/join`,{timeoutMs:null,signal:Z?.signal})}async*joinStream(Y,X,Z){let $=typeof Z==="object"&&Z!=null&&Z instanceof AbortSignal?{signal:Z}:Z;yield*this.streamWithRetry({endpoint:Y!=null?`/threads/${Y}/runs/${X}/stream`:`/runs/${X}/stream`,method:"GET",signal:$?.signal,headers:$?.lastEventId?{"Last-Event-ID":$.lastEventId}:void 0,params:{cancel_on_disconnect:$?.cancelOnDisconnect?"1":"0",stream_mode:$?.streamMode}})}async delete(Y,X,Z){return this.fetch(`/threads/${Y}/runs/${X}`,{method:"DELETE",signal:Z?.signal})}},OY=class extends l{async putItem(Y,X,Z,$){Y.forEach((W)=>{if(W.includes("."))throw Error(`Invalid namespace label '${W}'. Namespace labels cannot contain periods ('.')`)});let B={namespace:Y,key:X,value:Z,index:$?.index,ttl:$?.ttl};return this.fetch("/store/items",{method:"PUT",json:B,signal:$?.signal})}async getItem(Y,X,Z){Y.forEach((W)=>{if(W.includes("."))throw Error(`Invalid namespace label '${W}'. Namespace labels cannot contain periods ('.')`)});let $={namespace:Y.join("."),key:X};if(Z?.refreshTtl!==void 0)$.refresh_ttl=Z.refreshTtl;let B=await this.fetch("/store/items",{params:$,signal:Z?.signal});return B?{...B,createdAt:B.created_at,updatedAt:B.updated_at}:null}async deleteItem(Y,X,Z){return Y.forEach(($)=>{if($.includes("."))throw Error(`Invalid namespace label '${$}'. Namespace labels cannot contain periods ('.')`)}),this.fetch("/store/items",{method:"DELETE",json:{namespace:Y,key:X},signal:Z?.signal})}async searchItems(Y,X){let Z={namespace_prefix:Y,filter:X?.filter,limit:X?.limit??10,offset:X?.offset??0,query:X?.query,refresh_ttl:X?.refreshTtl};return{items:(await this.fetch("/store/items/search",{method:"POST",json:Z,signal:X?.signal})).items.map(($)=>({...$,createdAt:$.created_at,updatedAt:$.updated_at}))}}async listNamespaces(Y){let X={prefix:Y?.prefix,suffix:Y?.suffix,max_depth:Y?.maxDepth,limit:Y?.limit??100,offset:Y?.offset??0};return this.fetch("/store/namespaces",{method:"POST",json:X,signal:Y?.signal})}},fY=class Y extends l{static promiseCache={};static getOrCached(X,Z){if(Y.promiseCache[X]!=null)return Y.promiseCache[X];let $=Z();return Y.promiseCache[X]=$,$}async getComponent(X,Z){return Y.getOrCached(`${this.apiUrl}-${X}-${Z}`,async()=>{let[$,B]=this.prepareFetchOptions(`/ui/${X}`,{headers:{Accept:"text/html","Content-Type":"application/json"},method:"POST",json:{name:Z}});if(this.onRequest!=null)B=await this.onRequest($,B);return(await this.asyncCaller.fetch($.toString(),B)).text()})}},l0=class{assistants;threads;runs;crons;store;"~ui";"~configHash";constructor(Y){this["~configHash"]=JSON.stringify({apiUrl:Y?.apiUrl,apiKey:Y?.apiKey,timeoutMs:Y?.timeoutMs,defaultHeaders:Y?.defaultHeaders,maxConcurrency:Y?.callerOptions?.maxConcurrency,maxRetries:Y?.callerOptions?.maxRetries,callbacks:{onFailedResponseHook:Y?.callerOptions?.onFailedResponseHook!=null,onRequest:Y?.onRequest!=null,fetch:Y?.callerOptions?.fetch!=null}}),this.assistants=new NY(Y),this.threads=new UY(Y),this.runs=new _Y(Y),this.crons=new HY(Y),this.store=new OY(Y),this["~ui"]=new fY(Y)}};var w1=async(Y)=>{let X=new l0(Y);return X.threads.search=function(Z){return this.fetch("/threads/search",{method:"POST",json:{metadata:(Z==null?void 0:Z.metadata)??void 0,ids:(Z==null?void 0:Z.ids)??void 0,limit:(Z==null?void 0:Z.limit)??10,offset:(Z==null?void 0:Z.offset)??0,status:Z==null?void 0:Z.status,sort_by:Z==null?void 0:Z.sortBy,sort_order:Z==null?void 0:Z.sortOrder,select:(Z==null?void 0:Z.select)??void 0,without_details:(Z==null?void 0:Z.without_details)??!1}})}.bind(X.threads),X};var L5={command:C.enum(["create","update","rewrite"]).describe("The operation to perform: create new artifact, update existing, or rewrite"),id:C.string().describe("Unique identifier for the artifact"),title:C.string().describe("Human-readable title for the artifact"),type:C.string().describe("MIME type of the artifact content (e.g., 'application/vnd.ant.react')"),language:C.string().describe("Programming language or format of the content"),content:C.string().describe("The actual content to be created or updated. Don't Reply These Code to User, User can see these code in artifacts."),old_str:C.string().describe("The existing content to be replaced (for update operations)"),new_str:C.string().describe("The new content to replace the old content (for update operations)")};var AY=(Y,X)=>{let Z=new Map;for(let B of Y)if(B.type==="tool"&&B.name==="create_artifacts"){let W=new o(B,X),J=W.getInputRepaired();if(!J.id)continue;J.tool_id=W.message.id,J.is_done=W.state==="done",Z.set(J.id,[...Z.get(J.id)||[],J])}let $=new Map;for(let[B,W]of Z){let J=[],V="",K="",Q="",G=1;for(let F of W){switch(F.command){case"create":V=F.content,K=F.title||`artifact-${B}`,Q=F.type||F.language;break;case"update":if(F.old_str&&F.new_str)V=V.replace(F.old_str,F.new_str);else if(F.content)V=F.content;break;case"rewrite":V=F.content;break}let D={group_id:B,id:F.tool_id,code:V,filename:K,filetype:Q,version:G,is_done:F.is_done};J.push(D),G++}$.set(B,J)}return[...$.values()].map((B)=>({id:B[0].group_id,filename:B[B.length-1].filename,filetype:B[B.length-1].filetype,versions:B}))},T1=(Y,X)=>{let Z=f(!1),$=f(null),B=f([]);return _0([Y,X],()=>{B.set(AY(Y.get(),X.get()))}),{data:{artifacts:B,currentArtifactId:$,showArtifact:Z},mutation:{setCurrentArtifactById:(J,V)=>{let K=$.get();if(K?.[0]===J&&K?.[1]===V)return;Z.set(!0),$.set([J,V])},setShowArtifact:(J)=>Z.set(J)}}};var j5=(Y)=>{let X=Y.execute||(async(Z,$)=>{try{let B=await Y.handler?.(Z,$);if(typeof B==="string")return[{type:"text",text:B}];else if(B.decisions)return B;return[{type:"text",text:JSON.stringify(B)}]}catch(B){return[{type:"text",text:`Error: ${B}`}]}});return{...Y,execute:X}};var j1=(Y)=>{return{name:Y.name,description:Y.description,parameters:Y.isPureParams?Y.parameters:x1(C.object(Y.parameters))}};class K0{tools=new Map;waitingMap=new Map;bindTool(Y){if(this.tools.has(Y.name)&&Y.name!=="__default__")console.warn(`Tool with name ${Y.name} already exists`);this.tools.set(Y.name,Y)}bindTools(Y){Y.forEach((X)=>this.bindTool(X))}getAllTools(){return Array.from(this.tools.values())}getTool(Y){return this.tools.get(Y)}removeTool(Y){return this.tools.delete(Y)}clearTools(){this.tools.clear()}reset(){this.clearTools(),this.clearWaiting()}clearWaiting(){this.waitingMap.clear()}async callTool(Y,X,Z){return await(this.getTool(Y)||this.getTool("__default__")).execute?.(X,Z)}async toJSON(Y,X=!0){return Array.from(this.tools.values()).filter((Z)=>X?!Z.onlyRender:!0).filter((Z)=>!Z.allowGraph||Z.allowGraph.includes(Y)).map((Z)=>j1(Z))}doneWaiting(Y,X){if(this.waitingMap.has(Y))return this.waitingMap.get(Y)(X),this.waitingMap.delete(Y),!0;else return console.warn(`Waiting for tool ${Y} not found`),!1}isAllToolCompleted(){return this.waitingMap.size}waitForDone(Y){return new Promise((Z,$)=>{this.waitingMap.set(Y,Z)})}static waitForUIDone(Y,X){return X.client.tools.waitForDone(X.message.id)}}class p0{timeCounter=new Map;start(Y){this.timeCounter.set(Y,[new Date])}end(Y){this.timeCounter.set(Y,[this.timeCounter.get(Y)?.[0]||new Date,new Date])}setSpendTime(Y){if(this.timeCounter.has(Y))this.end(Y);else this.start(Y)}getStartTime(Y){return this.timeCounter.get(Y)?.[0]||new Date}getEndTime(Y){return this.timeCounter.get(Y)?.[1]||new Date}getSpendTime(Y){let[X,Z=new Date]=this.timeCounter.get(Y)||[new Date,new Date];return Z.getTime()-X.getTime()}}class V0{static isTool(Y){return Y.type==="tool"}static isToolAssistant(Y){return Y.type==="ai"&&(Y.tool_calls?.length||Y.tool_call_chunks?.length)}}class i0{streamingMessage=[];graphMessages=[];spendTime=new p0;constructor(){}getStreamingMessages(){return[...this.streamingMessage]}setStreamingMessages(Y){this.streamingMessage=Y}clearStreamingMessages(){this.streamingMessage=[]}getGraphMessages(){return[...this.graphMessages]}setGraphMessages(Y){this.graphMessages=Y}updateStreamingMessage(Y){let X=this.streamingMessage[this.streamingMessage.length-1];if(!X?.id||Y.id!==X.id){this.streamingMessage.push(Y);return}this.streamingMessage[this.streamingMessage.length-1]=Y}combineGraphMessagesWithStreamingMessages(){let Y=new Map(this.streamingMessage.map((X)=>[X.id,X]));return[...this.graphMessages.map((X)=>{if(Y.has(X.id)){let Z=Y.get(X.id);return Y.delete(X.id),Z}return X}),...Y.values()]}cloneMessage(Y){return JSON.parse(JSON.stringify(Y))}attachInfoForMessage(Y){let X=null,Z=[...Y];for(let $ of Z){if(!$.additional_kwargs)$.additional_kwargs={};let B=$.additional_kwargs?.create_time||r0(this.spendTime.getStartTime($.id)),W=$.additional_kwargs?.update_time||r0(this.spendTime.getEndTime($.id));if($.additional_kwargs.create_time=B,$.additional_kwargs.update_time=W,$.unique_id=$.tool_call_id||$.id,$.spend_time=new Date(W).getTime()-new Date(B).getTime(),!$.usage_metadata&&$.response_metadata?.usage){let J=$.response_metadata.usage;$.usage_metadata={...J,input_tokens:J.prompt_tokens,output_tokens:J.completion_tokens,total_tokens:J.total_tokens}}X=$}return Z}composeToolMessages(Y){let X=[],Z=new Map,$=new Map;for(let B of Y){if(V0.isToolAssistant(B)){if((B.tool_calls||B.tool_call_chunks)?.forEach((W)=>{Z.set(W.id,W),$.set(W.id,B)}),!B.content)continue}if(V0.isTool(B)&&!B.tool_input){let W=Z.get(B.tool_call_id),J=$.get(B.tool_call_id);if(W){B.tool_input=typeof W.args!=="string"?JSON.stringify(W.args):W.args;let V=!!B.content;B.done=V,B.additional_kwargs={...J?.additional_kwargs||{},...B.additional_kwargs||{},done:V}}if(J){if(B.usage_metadata=J.usage_metadata,B.node_name=J.name,B.source_ai_message_id=J.id,!B.name)B.name=J.tool_calls.find((V)=>V.id===B.tool_call_id)?.name}}X.push(B)}return X}renderMessages(Y,X,Z){let $=new Map,B=new Set,W=[],J=this.combineGraphMessagesWithStreamingMessages();for(let V=J.length-1;V>=0;V--){let K=this.cloneMessage(J[V]);if(!K.id){W.unshift(K);continue}if(K.type==="ai"){if(!K.name)K.name=X().name}if(V0.isToolAssistant(K)){let Q=K;$.set(K.id,Q);let F=((Q.tool_calls?.length)?Q.tool_calls:Q.tool_call_chunks).filter((D)=>{return!B.has(D.id)}).map((D,N)=>{return{type:"tool",additional_kwargs:{},tool_input:Q.additional_kwargs?.tool_calls?.[N]?.function?.arguments,id:D.id,name:D.name,response_metadata:{},tool_call_id:D.id,content:""}});for(let D of F)if(!$.has(D.id))W.unshift(D),$.set(D.id,D);W.unshift(Q)}else{if(K.type==="tool"&&K.tool_call_id)B.add(K.tool_call_id);$.set(K.id,K),W.unshift(K)}}return this.processMessages(W,Y,Z)}foldTreeMessages(Y,X,Z){let $=Object.entries(X?.task_store||{}).map(([Q,G])=>[Q,G.messages]),B=new Map($),W=new Set,J=new Map(Object.entries(Z||{}).map(([Q,G])=>{if(G?.parent_id)return W.add(Q),[Q,G?.parent_id];return}).filter((Q)=>Q!==void 0)),V=B,K=[];for(let Q of Y){let G=Q.source_ai_message_id||Q.id;if(!!W.has(G)){let D=J.get(G),N=V.get(D);if(N)N.push(Q);else V.set(D,[Q])}else K.push(Q)}for(let Q of K)if(Q.sub_messages=V.get(Q.id)||[],Q.type==="tool"&&V.has(Q.tool_call_id)){Q.sub_messages.unshift(...V.get(Q.tool_call_id));let G=Q.sub_messages.filter((F,D,N)=>N.findIndex((U)=>U.id===F.id)===D);Q.sub_messages=this.beforeFold(G)}return K}beforeFold(Y){let X=this.composeToolMessages(Y);return this.attachInfoForMessage(X)}processMessages(Y,X,Z){return this.foldTreeMessages(this.beforeFold(Y),X,Z)}}async function k1(Y,X,Z,$){let B=await Y.threads.get(X),W=B.values.messages,J=W.findIndex((F)=>F.id===Z);if(J===-1)throw Error(`Message id ${Z} not found`);let V=$.includeMessageId?J:J+1,K=W.slice(V),Q={...B.values,messages:K.map((F)=>{return{type:"remove",id:F.id}})},G=await Y.threads.updateState(X,{values:Q});return{state:{messages:W.slice(0,V)},checkpoint:G}}var C1=(Y)=>typeof Y==="object"&&Y!==null,v1=(Y)=>{if(!C1(Y))return!1;if(Y instanceof RegExp||Y instanceof Error||Y instanceof Date||Y instanceof Map||Y instanceof Set||Y instanceof WeakMap||Y instanceof WeakSet||Y instanceof Promise||Y instanceof ArrayBuffer||Y instanceof DataView||ArrayBuffer.isView(Y)||globalThis.Blob&&Y instanceof globalThis.Blob)return!1;if(typeof Y.$$typeof==="symbol"||typeof Y.asymmetricMatch==="function")return!1;return!0},PY=Symbol("mapObjectSkip"),LY=(Y,X)=>{if(X){let Z=Object.keys(Y),$=Object.getOwnPropertySymbols(Y).filter((B)=>Object.getOwnPropertyDescriptor(Y,B)?.enumerable);return[...Z,...$]}return Object.keys(Y)},n0=(Y,X,Z,$=new WeakMap)=>{let{target:B={},...W}={deep:!1,includeSymbols:!1,...Z};if($.has(Y))return $.get(Y);$.set(Y,B);let J=(V)=>V.map((K)=>v1(K)?n0(K,X,W,$):K);if(Array.isArray(Y))return J(Y);for(let V of LY(Y,W.includeSymbols)){let K=Y[V],Q=X(V,K);if(Q===PY)continue;if(!Array.isArray(Q))throw TypeError(`Mapper must return an array or mapObjectSkip, got ${Q===null?"null":typeof Q}`);if(Q.length<2)throw TypeError(`Mapper must return an array with at least 2 elements [key, value], got ${Q.length} elements`);let[G,F,{shouldRecurse:D=!0}={}]=Q;if(G==="__proto__")continue;if(W.deep&&D&&v1(F))F=Array.isArray(F)?J(F):n0(F,X,W,$);try{B[G]=F}catch(N){if(N.name==="TypeError"&&N.message.includes("read only"))continue;throw N}}return B};function s0(Y,X,Z){if(!C1(Y))throw TypeError(`Expected an object, got \`${Y}\` (${typeof Y})`);if(Array.isArray(Y))throw TypeError("Expected an object, got an array");return n0(Y,(B,W)=>X(B,W,Y),Z)}var t0=/[\p{Lu}]/u,EY=/[\p{Ll}]/u,qY=/^[\p{Lu}](?![\p{Lu}])/u,e=/[_.\- ]+/,S1=/([\p{Alpha}\p{N}_]|$)/u,bY=new RegExp("^"+e.source),RY=new RegExp(e.source+S1.source,"gu"),MY=new RegExp(String.raw`\d+`+S1.source,"gu"),wY=(Y,X,Z,$)=>{let B=!1,W=!1,J=!1,V=!1;for(let K=0;K<Y.length;K++){let Q=Y[K];if(V=K>2?Y[K-3]==="-":!0,B&&t0.test(Q))Y=Y.slice(0,K)+"-"+Y.slice(K),B=!1,J=W,W=!0,K++;else if(W&&J&&EY.test(Q)&&(!V||$))Y=Y.slice(0,K-1)+"-"+Y.slice(K-1),J=W,W=!1,B=!0;else B=X(Q)===Q&&Z(Q)!==Q,J=W,W=Z(Q)===Q&&X(Q)!==Q}return Y},TY=(Y,X)=>Y.replace(qY,(Z)=>X(Z)),xY=(Y,X,Z)=>{let $="",B=!1,W=!1,J=[...Y];for(let V=0;V<J.length;V++){let K=J[V],Q=t0.test(K),G=V+1<J.length&&t0.test(J[V+1]);if(B&&/[\p{Alpha}]/u.test(K))$+=K,B=!1,W=Q;else if(Z&&Q&&(W||G))$+=K,W=!0;else if(/\d/.test(K))$+=K,B=!0,W=!1;else if(e.test(K))$+=K,W=!1;else $+=X(K),B=!1,W=!1}return $},jY=(Y,X,{capitalizeAfterNumber:Z})=>{let $=Z?(B,W,J,V)=>{let K=V.charAt(J+B.length);if(e.test(K))return B;return W?B.slice(0,-W.length)+X(W):B}:(B)=>B;return Y.replaceAll(MY,$).replaceAll(RY,(B,W)=>X(W))};function a0(Y,X){if(!(typeof Y==="string"||Array.isArray(Y)))throw TypeError("Expected the input to be `string | string[]`");if(X={pascalCase:!1,preserveConsecutiveUppercase:!1,capitalizeAfterNumber:!0,...X},Array.isArray(Y))Y=Y.map((J)=>J.trim()).filter((J)=>J.length>0).join("-");else Y=Y.trim();if(Y.length===0)return"";let Z=Y.match(/^[_$]*/)[0];if(Y=Y.slice(Z.length),Y.length===0)return Z;let $=X.locale===!1?(J)=>J.toLowerCase():(J)=>J.toLocaleLowerCase(X.locale),B=X.locale===!1?(J)=>J.toUpperCase():(J)=>J.toLocaleUpperCase(X.locale);if(Y.length===1){if(e.test(Y))return Z;return Z+(X.pascalCase?B(Y):$(Y))}if(Y!==$(Y))Y=wY(Y,$,B,X.preserveConsecutiveUppercase);if(Y=Y.replace(bY,""),X.capitalizeAfterNumber)Y=X.preserveConsecutiveUppercase?TY(Y,$):$(Y);else Y=xY(Y,$,X.preserveConsecutiveUppercase);if(X.pascalCase&&Y.length>0)Y=B(Y[0])+Y.slice(1);return Z+jY(Y,B,X)}class Q0 extends Map{#Z=0;#Y=new Map;#X=new Map;#Q;#H;#D;constructor(Y={}){super();if(!(Y.maxSize&&Y.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof Y.maxAge==="number"&&Y.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#Q=Y.maxSize,this.#H=Y.maxAge||Number.POSITIVE_INFINITY,this.#D=Y.onEviction}get __oldCache(){return this.#X}#z(Y){if(typeof this.#D!=="function")return;for(let[X,Z]of Y)this.#D(X,Z.value)}#J(Y,X){if(typeof X.expiry==="number"&&X.expiry<=Date.now()){if(typeof this.#D==="function")this.#D(Y,X.value);return this.delete(Y)}return!1}#_(Y,X){if(this.#J(Y,X)===!1)return X.value}#G(Y,X){return X.expiry?this.#_(Y,X):X.value}#F(Y,X){let Z=X.get(Y);return this.#G(Y,Z)}#V(Y,X){if(this.#Y.set(Y,X),this.#Z++,this.#Z>=this.#Q)this.#Z=0,this.#z(this.#X),this.#X=this.#Y,this.#Y=new Map}#K(Y,X){this.#X.delete(Y),this.#V(Y,X)}*#B(){for(let Y of this.#X){let[X,Z]=Y;if(!this.#Y.has(X)){if(this.#J(X,Z)===!1)yield Y}}for(let Y of this.#Y){let[X,Z]=Y;if(this.#J(X,Z)===!1)yield Y}}get(Y){if(this.#Y.has(Y)){let X=this.#Y.get(Y);return this.#G(Y,X)}if(this.#X.has(Y)){let X=this.#X.get(Y);if(this.#J(Y,X)===!1)return this.#K(Y,X),X.value}}set(Y,X,{maxAge:Z=this.#H}={}){let $=typeof Z==="number"&&Z!==Number.POSITIVE_INFINITY?Date.now()+Z:void 0;if(this.#Y.has(Y))this.#Y.set(Y,{value:X,expiry:$});else this.#V(Y,{value:X,expiry:$});return this}has(Y){if(this.#Y.has(Y))return!this.#J(Y,this.#Y.get(Y));if(this.#X.has(Y))return!this.#J(Y,this.#X.get(Y));return!1}peek(Y){if(this.#Y.has(Y))return this.#F(Y,this.#Y);if(this.#X.has(Y))return this.#F(Y,this.#X)}expiresIn(Y){let X=this.#Y.get(Y)??this.#X.get(Y);if(X)return X.expiry?X.expiry-Date.now():Number.POSITIVE_INFINITY}delete(Y){let X=this.#Y.delete(Y);if(X)this.#Z--;return this.#X.delete(Y)||X}clear(){this.#Y.clear(),this.#X.clear(),this.#Z=0}resize(Y){if(!(Y&&Y>0))throw TypeError("`maxSize` must be a number greater than 0");let X=[...this.#B()],Z=X.length-Y;if(Z<0)this.#Y=new Map(X),this.#X=new Map,this.#Z=X.length;else{if(Z>0)this.#z(X.slice(0,Z));this.#X=new Map(X.slice(Z)),this.#Y=new Map,this.#Z=0}this.#Q=Y}evict(Y=1){let X=Number(Y);if(!X||X<=0)return;let Z=[...this.#B()],$=Math.trunc(Math.min(X,Math.max(Z.length-1,0)));if($<=0)return;this.#z(Z.slice(0,$)),this.#X=new Map(Z.slice($)),this.#Y=new Map,this.#Z=0}*keys(){for(let[Y]of this)yield Y}*values(){for(let[,Y]of this)yield Y}*[Symbol.iterator](){for(let Y of this.#Y){let[X,Z]=Y;if(this.#J(X,Z)===!1)yield[X,Z.value]}for(let Y of this.#X){let[X,Z]=Y;if(!this.#Y.has(X)){if(this.#J(X,Z)===!1)yield[X,Z.value]}}}*entriesDescending(){let Y=[...this.#Y];for(let X=Y.length-1;X>=0;--X){let Z=Y[X],[$,B]=Z;if(this.#J($,B)===!1)yield[$,B.value]}Y=[...this.#X];for(let X=Y.length-1;X>=0;--X){let Z=Y[X],[$,B]=Z;if(!this.#Y.has($)){if(this.#J($,B)===!1)yield[$,B.value]}}}*entriesAscending(){for(let[Y,X]of this.#B())yield[Y,X.value]}get size(){if(!this.#Z)return this.#X.size;let Y=0;for(let X of this.#X.keys())if(!this.#Y.has(X))Y++;return Math.min(this.#Z+Y,this.#Q)}get maxSize(){return this.#Q}get maxAge(){return this.#H}entries(){return this.entriesAscending()}forEach(Y,X=this){for(let[Z,$]of this.entriesAscending())Y.call(X,$,Z,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}var kY=(Y,X)=>Y.some((Z)=>{if(typeof Z==="string")return Z===X;return Z.lastIndex=0,Z.test(X)}),vY=(Y)=>Y.trim()!==""&&!Number.isNaN(Number(Y)),o0=new Q0({maxSize:1e5}),CY=(Y)=>ArrayBuffer.isView(Y)||Y instanceof Date||Y instanceof RegExp||Y instanceof Error||Y instanceof Map||Y instanceof Set||Y instanceof WeakMap||Y instanceof WeakSet||Y instanceof Promise,p=(Y)=>typeof Y==="object"&&Y!==null&&!CY(Y),r=(Y,X={},Z=new WeakMap,$)=>{if(!p(Y))return Y;if(Z.has(Y))return Z.get(Y);let{exclude:B,pascalCase:W=!1,stopPaths:J,deep:V=!1,preserveConsecutiveUppercase:K=!1}=X,Q=new Set(J);if(Array.isArray(Y)){let U=[];Z.set(Y,U);for(let _ of Y)U.push(p(_)?r(_,X,Z,$):_);return U}let G={};Z.set(Y,G);let D=s0(Y,((U)=>(_,P)=>{if(V&&p(P)){let q=U===void 0?_:`${U}.${_}`;if(!Q.has(q))P=Array.isArray(P)?P.map((E)=>p(E)?r(E,X,Z,q):E):r(P,X,Z,q)}if(typeof _==="string"&&!vY(_)&&!(B&&kY(B,_))){let q=W?`${_}_`:_;if(o0.has(q))_=o0.get(q);else if(_=a0(_,{pascalCase:W,locale:!1,preserveConsecutiveUppercase:K}),_.length<100)o0.set(q,_)}return[_,P]})($),{deep:!1});Object.assign(G,D);let N=Object.getOwnPropertySymbols(Y);for(let U of N)G[U]=V&&p(Y[U])?r(Y[U],X,Z,$):Y[U];return G};function e0(Y,X){let Z=new WeakMap;if(Array.isArray(Y))return Y.map(($)=>p($)?r($,X,Z,void 0):$);return r(Y,X,Z)}class z0 extends W0.default{client;currentAssistant=null;currentThread=null;tools=new K0;availableAssistants=[];graphState={};currentRun;stopController=null;messageProcessor;legacyMode;_status="idle";constructor(Y){super();this.client=Y.client,this.legacyMode=Y.legacyMode??!1,this.messageProcessor=new i0}get assistants(){return this.client.assistants}get threads(){return this.client.threads}get runs(){return this.client.runs}get status(){return this._status}listAssistants(){return this.assistants.search({metadata:null,offset:0,limit:100})}async initAssistant(Y,X={}){try{let Z=await this.listAssistants();if(this.availableAssistants=Z,Z.length>0)if(Y){if(this.currentAssistant=Z.find(($)=>$.graph_id===Y)||null,!this.currentAssistant){if(X.fallbackToAvailableAssistants)return this.currentAssistant=this.availableAssistants[0],this.currentAssistant;throw Error("Agent not found: "+Y)}}else return this.currentAssistant=Z[0],this.currentAssistant;else throw Error("No assistants found")}catch(Z){throw console.error("Failed to initialize LangGraphClient:",Z),Z}}async createThread({threadId:Y,graphId:X,metadata:Z}={}){try{return this.currentThread=await this.threads.create({metadata:Z,threadId:Y,graphId:X}),this.currentThread}catch($){throw console.error("Failed to create new thread:",$),$}}graphVisualize(){return this.assistants.getGraph(this.currentAssistant?.assistant_id,{xray:!0})}async listThreads(Y={}){let X={};if(Y.ids)X.ids=Y.ids;if(Y.metadata)X.metadata=Y.metadata;if(Y.status)X.status=Y.status;if(Y.values)X.values=Y.values;if(Y.limit!==void 0)X.limit=Y.limit;if(Y.offset!==void 0)X.offset=Y.offset;if(Y.sortBy)X.sortBy=Y.sortBy;if(Y.sortOrder)X.sortOrder=Y.sortOrder;if(Y.select)X.select=Y.select;if(Y.withoutDetails!==void 0)X.without_details=Y.withoutDetails;if(!Y.sortBy)X.sortBy="updated_at";if(!Y.sortOrder)X.sortOrder="desc";if(!Y.limit)X.limit=10;if(!Y.offset)X.offset=0;if(!Y.withoutDetails)X.without_details=!0;return this.threads.search(X)}async deleteThread(Y){return this.threads.delete(Y)}async resetThread(Y,X){await this.initAssistant(Y),this.currentThread=await this.threads.get(X),this.graphState=this.currentThread.values;let Z=this.graphState?.messages||[];if(this.messageProcessor.setGraphMessages(Z),this.emit("value",{event:"messages/partial",data:{messages:this.messageProcessor.getGraphMessages()}}),this.currentThread?.status==="interrupted")this.sendMessage([],{joinRunId:this.currentThread.thread_id});return this.currentThread}async resetStream(){let X=(await this.runs.list(this.currentThread.thread_id))?.find((Z)=>Z.status==="running"||Z.status==="pending");if(X)await this.sendMessage([],{joinRunId:X.run_id})}cloneMessage(Y){return this.messageProcessor.cloneMessage(Y)}get renderMessage(){return this.messageProcessor.renderMessages(this.graphState,()=>this.getGraphNodeNow(),this.messagesMetadata)}get tokenCounter(){return this.messageProcessor.getGraphMessages().reduce((Y,X)=>{if(X.usage_metadata)Y.total_tokens+=X.usage_metadata?.total_tokens||0,Y.input_tokens+=X.usage_metadata?.input_tokens||0,Y.output_tokens+=X.usage_metadata?.output_tokens||0;else if(X.response_metadata?.usage){let Z=X.response_metadata?.usage;Y.total_tokens+=Z.total_tokens||0,Y.input_tokens+=Z.prompt_tokens||0,Y.output_tokens+=Z.completion_tokens||0}return Y},{total_tokens:0,input_tokens:0,output_tokens:0})}isFELocking(Y){let X=Y[Y.length-1];if(!X)return!1;let Z=this.tools.getTool(X?.name);return Z&&Z.render&&X?.type==="tool"&&!X?.additional_kwargs?.done}cancelRun(){if(this.currentThread?.thread_id&&this.currentRun?.run_id)this.runs.cancel(this.currentThread.thread_id,this.currentRun.run_id)}async revertChatTo(Y,X){let{state:Z,checkpoint:$}=await k1(this.client,this.currentThread.thread_id,Y,X);return this.graphState=Z,this.messageProcessor.clearStreamingMessages(),this.messageProcessor.setGraphMessages(Z.messages),Z}messagesMetadata={};humanInTheLoop=null;interruptData=null;async sendMessage(Y,{joinRunId:X,extraParams:Z,_debug:$,command:B,metadata:W}={}){if(!this.currentAssistant)throw Error("Thread or Assistant not initialized");if(!this.currentThread)await this.createThread({graphId:this.currentAssistant.graph_id,metadata:W}),this.emit("thread",{event:"thread/create",data:{thread:this.currentThread}});if(this.interruptData)this.interruptData=null,this.emit("interruptChange",{event:"interruptChange"});let J=Array.isArray(Y)?Y:[{type:"human",content:Y}],V=[];this._status="busy",this.emit("start",{event:"start"});let Q=await(async()=>{if($?.streamResponse)return $.streamResponse;let F=this.legacyMode?(D)=>{V.push(D),this.processStreamChunk(D,B)}:void 0;if(X)return this.runs.joinStream(this.currentThread.thread_id,X,{onCallback:F});return this.runs.stream(this.currentThread.thread_id,this.currentAssistant.assistant_id,{input:{...this.graphState,...this.extraParams,...Z||{},messages:J,fe_tools:await this.tools.toJSON(this.currentAssistant.graph_id)},streamMode:["messages","values"],streamSubgraphs:!0,command:B,onCallback:F})})();if(!this.legacyMode)for await(let F of Q)V.push(F),this.processStreamChunk(F,B);let G=await this.runFETool();if(await this.responseHumanInTheLoop(),G)V.push(...G);return this._status="idle",this.emit("done",{event:"done"}),this.messageProcessor.clearStreamingMessages(),V}graphPosition="";getGraphPosition(){return this.graphPosition.split("|").map((Y)=>{let[X,Z]=Y.split(":");return{id:Z,name:X}})}getGraphNodeNow(){let Y=this.getGraphPosition();return Y[Y.length-1]}processStreamChunk(Y,X){if(Y.event==="metadata")this.currentRun=Y.data;else if(Y.event==="error"||Y.event==="Error"||Y.event==="__stream_error__")this._status="error",this.emit("error",Y);else if(Y.event==="messages/metadata")return Object.assign(this.messagesMetadata,Y.data),!0;else if(Y.event==="messages/partial"||Y.event==="messages/complete"){for(let Z of Y.data)this.messageProcessor.updateStreamingMessage(Z),this.messageProcessor.spendTime.setSpendTime(Z.id);return this.emit("message",Y),!0}else if(Y.event==="values"){let Z=Y.data;if(Z?.__interrupt__){let $=this.getHumanInTheLoopData(Z?.__interrupt__);if($)this.humanInTheLoop=$;else this.interruptData=Z.__interrupt__}else if(Z?.messages){let $=!!X?.resume,B=Z.messages.length>=this.messageProcessor.getGraphMessages().length;if(!$||$&&B)this.messageProcessor.setGraphMessages(Z.messages),this.emit("value",Y);this.graphState=Y.data}return!0}else if(Y.event.startsWith("values|"))this.graphPosition=Y.event.split("|")[1];return!1}runFETool(){let Y=this.messageProcessor.getStreamingMessages(),X=Y[Y.length-1];if(!X)return;if(X.type==="ai"&&X.tool_calls?.length){let Z=X.tool_calls.map(($)=>{let B={...$,tool_call_id:$.id,tool_input:JSON.stringify($.args),additional_kwargs:{}};return this.callFETool(B,$.args).catch((W)=>console.warn(W))});return console.log("batch call tools",Z.length),this._status="interrupted",this.currentThread.status="interrupted",this.emit("interruptChange",{event:"interruptChange"}),Promise.all(Z)}}getHumanInTheLoopData(Y){if(S.array(S.object({id:S.string(),value:S.union([S.object({review_configs:S.array(S.any())}),S.object({reviewConfigs:S.array(S.any())})])})).safeParse(Y).success){let Z=Y.map(($)=>{if($&&"review_configs"in $.value)return{id:$.id,value:{actionRequests:$.value.action_requests,reviewConfigs:e0($.value.review_configs,{deep:!0})}};return $});return Z.forEach(($)=>{return $.value.actionRequests.forEach((B)=>{B.id=B.id||X0(B)}),$}),{interruptData:Z,result:{}}}}async responseHumanInTheLoop(){if(this.humanInTheLoop){let Y=this.humanInTheLoop;return this.humanInTheLoop=null,this.resume({decisions:Y.interruptData[0].value.actionRequests.map((X)=>{return Y.result[X.id]})})}}async callFETool(Y,X){let Z=this;if(!await this.tools.callTool(Y.name,X,{client:Z,message:Y}))return}extraParams={};resume(Y){return this.sendMessage([],{command:{resume:Y}})}doneFEToolWaiting(Y,X){if(!this.tools.doneWaiting(Y,X)&&this.currentThread?.status==="interrupted")this.resume(X)}doneHumanInTheLoopWaiting(Y,X,Z){if(this.tools.doneWaiting(Y,Z),this.humanInTheLoop)this.humanInTheLoop.result[X]=Z}getCurrentThread(){return this.currentThread}getCurrentAssistant(){return this.currentAssistant}async reset(){await this.initAssistant(this.currentAssistant?.graph_id),this.currentThread=null,this.graphState={},this.messageProcessor.setGraphMessages([]),this.messageProcessor.clearStreamingMessages(),this.currentRun=void 0,this.tools.clearWaiting(),this._status="idle",this.emit("value",{event:"messages/partial",data:{messages:[]}})}}class Y1{sessions=new Map;activeSessionId=null;clientConfig;virtualClient;constructor(Y){this.clientConfig=Y,this.virtualClient=new z0(Y)}async createSession(Y={}){let X=Y.sessionId||this.generateSessionId(),Z=Y.agentName||this.virtualClient.getCurrentAssistant()?.graph_id;if(!Z)throw Error("Agent name is required. Please call init() first or provide agentName.");if(this.sessions.has(X))throw Error(`Session ${X} already exists`);let $={sessionId:X,agentName:Z,metadata:Y.metadata};if(Y.restore)$.thread=await this.virtualClient.threads.get(X);return this.sessions.set(X,$),$}async activateSession(Y,X=!1){let Z=this.sessions.get(Y)||{sessionId:Y,agentName:this.virtualClient.getCurrentAssistant()?.graph_id};if(!Z.client){let B=new z0(this.clientConfig);if(await B.initAssistant(Z.agentName),Z.metadata&&!Z.thread)await B.createThread({graphId:B.getCurrentAssistant()?.graph_id,metadata:Z.metadata});if(Z.thread||X)await B.resetThread(Z.agentName,Y);Z.client=B}let $=this.activeSessionId&&this.sessions.get(this.activeSessionId);if($&&$.client?.status==="idle")$.client?.reset(),$.client=void 0;return this.activeSessionId=Y,Z}getActiveSession(){if(!this.activeSessionId)return null;return this.sessions.get(this.activeSessionId)||null}getSession(Y){return this.sessions.get(Y)||null}getAllSessions(){return Array.from(this.sessions.values())}async deleteSession(Y){if(!this.sessions.get(Y))return!1;if(this.activeSessionId===Y)this.activeSessionId=null;try{await this.virtualClient.deleteThread(Y)}catch(Z){console.warn(`Failed to delete thread for session ${Y}:`,Z)}return this.sessions.delete(Y),!0}async clearAllSessions(){let Y=Array.from(this.sessions.keys());for(let X of Y)await this.deleteSession(X);this.activeSessionId=null}getSessionCount(){return this.sessions.size}generateSessionId(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(Y)=>{let X=Math.random()*16|0;return(Y==="x"?X:X&3|8).toString(16)})}async addSessionFromThread(Y,X){let Z=X||this.virtualClient.getCurrentAssistant()?.graph_id;if(!Z)throw Error("Agent name is required. Please call init() first or provide agentName.");return this.createSession({sessionId:Y,agentName:Z,restore:!0})}getActiveClient(){return this.getActiveSession()?.client||null}async listRemoteSessions(Y={}){return this.virtualClient.listThreads(Y)}async syncFromRemote(Y={}){let X=Y.agentName||this.virtualClient.getCurrentAssistant()?.graph_id;if(!X)throw Error("Agent name is required. Please call init() first or provide agentName.");let Z=await this.listRemoteSessions({limit:Y.limit||10,sortBy:"updated_at",sortOrder:"desc"}),$=[];for(let B of Z){let W=B.thread_id;if(this.sessions.has(W)){let J=this.sessions.get(W);J.thread=B,$.push(J)}else{let J={sessionId:W,thread:B,agentName:X};this.sessions.set(W,J),$.push(J)}}return $}async init(Y,X){return this.virtualClient.initAssistant(Y,X)}}var r0=(Y)=>{let X=(K)=>K.toString().padStart(2,"0"),Z=Y.getFullYear(),$=X(Y.getMonth()+1),B=X(Y.getDate()),W=X(Y.getHours()),J=X(Y.getMinutes()),V=X(Y.getSeconds());return`${Z}-${$}-${B} ${W}:${J}:${V}`};var G1=(Y)=>{if(typeof Y==="string")return Y;if(Array.isArray(Y))return Y.map((X)=>{if(typeof X==="string")return X;if(X.type==="text")return X.text;if(X.type==="image_url")return"[图片]";if(X.type==="tool_use")return"";return JSON.stringify(X)}).join("");return JSON.stringify(Y)};var h1=(Y,X,Z={})=>{let $=f(null),B=f([]),W=f(null),J=f([]),V=f([]),K=f(""),Q=f(null),G=f(Y),F=f(null),D=f("__start__"),N=f("idle"),U=f(null),_=f(!1),P=f([]),q=f([]),E=f(Z.showHistory??!1),M=f(Z.showGraph??!1),h=f(null),w=f({page:1,pageSize:10,total:0}),n={metadata:Z.historyFilter?.metadata??null,status:Z.historyFilter?.status??null,sortBy:Z.historyFilter?.sortBy??"updated_at",sortOrder:Z.historyFilter?.sortOrder??"desc"},m=f(n),u=null,G0=f(!1),I=()=>{let z=W.get();if(z)G0.set(z.status==="busy"||z.status==="interrupted")},s=f0((z)=>{if(W.get()!==z)return;let H=z.renderMessage,O=H[H.length-1];D.set(O?.node_name||O?.name||"__start__"),V.set(H),N.set(z.status)},Z.debounceTime??10),D0=async()=>{let z=W.get();if(!z)return;z.tools.clearTools(),z.tools.bindTools(P.get())},F0=async()=>{if(M.get())h.set(await W.get()?.graphVisualize()||null)};async function Z1(){let z=new Y1({...X,client:X.client??await w1(X)});if(await z.init(G.get(),{fallbackToAvailableAssistants:Z.fallbackToAvailableAssistants}),$.set(z),Z.autoRestoreLastSession)if(await T(),B.get().length>0){let H=B.get();await t(H[0].sessionId)}else await H0();else await H0();return z}async function T(){let z=$.get();if(!z)return;try{let H=w.get(),O=m.get(),x=(H.page-1)*H.pageSize,A=await z.listRemoteSessions({limit:H.pageSize,offset:x,metadata:O.metadata||void 0,status:O.status||void 0,sortBy:O.sortBy,sortOrder:O.sortOrder,withoutDetails:!0}),j=A.length===H.pageSize,y=(H.page-1)*H.pageSize+A.length;B.set(A.map((k)=>({sessionId:k.thread_id,thread:k,agentName:G.get(),metadata:k.metadata}))),J.set(A),w.set({...H,total:j?H.page*H.pageSize+1:y})}catch(H){console.error("Failed to sync sessions:",H)}}async function H0(){let z=$.get();if(!z)return;try{let H=await z.createSession();await T(),await t(H.sessionId)}catch(H){console.error("Failed to create new session:",H),Q.set(H.message)}}function u1(z){let H=()=>W.get()===z,O=()=>{if(H())I()},x=()=>{if(!H())return;let c=z.getCurrentThread();F.set(c?.thread_id||null),D.set("__start__");let B1=$.get()?.getActiveSession();if(B1&&c)B1.thread=c;T()},A=()=>{if(H())I(),s(z)},j=(c)=>{if(H())I(),Q.set(c.data)},y=()=>{if(H())F.set(z.getCurrentThread()?.thread_id||null),I(),s(z)},k=()=>{if(H())F.set(z.getCurrentThread()?.thread_id||null),I(),s(z)},a=(c)=>{if(!H())return;let U0=z.interruptData;if(U0)U.set(U0),_.set(!0),I();else U.set(null),_.set(!1);s(z),W.set(W.get())};return z.on("start",O),z.on("thread",x),z.on("done",A),z.on("error",j),z.on("message",y),z.on("value",k),z.on("interruptChange",a),()=>{z.off("start",O),z.off("thread",x),z.off("done",A),z.off("error",j),z.off("message",y),z.off("value",k),z.off("interruptChange",a)}}async function t(z,H=!1){let O=$.get();if(!O)return;try{if(u)u(),u=null;Q.set(null),U.set(null),_.set(!1);let A=(await O.activateSession(z,H)).client;if(A){u=u1(A),Z.onInit?.(A),W.set(A),F.set(z);let j=A.renderMessage;V.set(j);let y=j[j.length-1];if(D.set(y?.node_name||y?.name||"__start__"),I(),M.get())F0();D0();let k=A.getCurrentThread();if(k&&(k.status==="busy"||k.status==="pending"))await A.resetStream();if(k?.status==="interrupted"){let a=A.interruptData;if(a)U.set(a),_.set(!0)}}}catch(x){console.error("Failed to activate session:",x),Q.set(x.message)}}async function N0(z,H,O=!1,x=!1){let A=W.get();if(!O&&!K.get().trim()&&!z?.length||!A)return;if(A.status==="busy")return;Q.set(null);try{G0.set(!0),await A.sendMessage(z||K.get(),H)}catch(j){if(j.message.includes("422"))await A.resetStream();else throw j}finally{K.set(""),I()}}function c1(){W.get()?.cancelRun()}function d1(z){let H=q.get();q.set(H.includes(z)?H.filter((O)=>O!==z):[...H,z])}function l1(){if(E.set(!E.get()),E.get())T()}function p1(z){let H=J.get();J.set([z,...H])}function r1(z){let H=W.get();if(!H)return null;let O=H.tools.getTool(z)?.render;return O?(x)=>O(new o(x,H)):null}let $1=T1(V,W);return{data:{client:W,history:$,sessions:B,renderMessages:V,userInput:K,loading:G0,inChatError:Q,currentAgent:G,currentChatId:F,currentNodeName:D,currentStatus:N,interruptData:U,isInterrupted:_,tools:P,collapsedTools:q,showGraph:M,graphVisualize:h,showHistory:E,historyList:J,historyPagination:w,historyFilter:m,...$1.data},mutations:{initClient:Z1,getClient:()=>W.get(),getHistory:()=>$.get(),activateSession:t,createNewSession:H0,refreshSessionList:T,refreshHistoryList:T,sendMessage:N0,stopGeneration:c1,setUserInput:(z)=>K.set(z),async revertChatTo(z,H=!1,O){if(await W.get()?.revertChatTo(z,O||{}),H)return N0([],O,!0);else s(W.get())},refreshTools:D0,setTools(z){P.set(z),D0()},toggleToolCollapse:d1,getToolUIRender:r1,isFELocking:()=>W.get()?.isFELocking(V.get()),toggleHistoryVisible:l1,toggleGraphVisible(){if(M.set(!M.get()),M.get())F0()},refreshGraph:F0,setCurrentAgent(z){return G.set(z),Z1()},resumeFromInterrupt(z){return N0([],{command:{resume:z}},!0)},addToHistory:p1,async createNewChat(z){let H=$.get();if(!H)return;try{let O=await H.createSession({metadata:z});await T(),await t(O.sessionId)}catch(O){console.error("Failed to create new chat:",O),Q.set(O.message)}},toHistoryChat:(z)=>t(z.thread_id,!0),async deleteHistoryChat(z){let H=$.get();if(H)await H.deleteSession(z.thread_id),await T()},setHistoryPage(z){w.set({...w.get(),page:z}),T()},setHistoryPageSize(z){w.set({...w.get(),pageSize:z,page:1}),T()},setHistoryFilter(z){m.set({...m.get(),...z}),w.set({...w.get(),page:1}),T()},resetHistoryFilter(){m.set({...n}),w.set({...w.get(),page:1}),T()},...$1.mutation}}};var I1=(Y,X)=>{return{...Object.fromEntries(Object.entries(Y.data).map(([$,B])=>{return[$,X(B)]})),...Y.mutations}};var i=I0(y1(),1),X1=(Y,X)=>(Z)=>{if(Y.current===Z)return;Y.current=Z,X()};function g1(Y,{keys:X,deps:Z=[Y,X]}={}){let $=i.useRef();$.current=Y.get();let B=i.useCallback((J)=>{return X1($,J)(Y.value),X?.length>0?O0(Y,X,X1($,J)):Y.listen(X1($,J))},Z),W=()=>$.current;return i.useSyncExternalStore(B,W,W)}var m1=R.createContext(void 0),O6=()=>{let Y=R.useContext(m1);if(!Y)throw Error("useChat must be used within a ChatProvider");return Y},f6=({children:Y,defaultAgent:X="",apiUrl:Z="http://localhost:8123",defaultHeaders:$,withCredentials:B=!1,fetch:W,showHistory:J=!1,showGraph:V=!1,fallbackToAvailableAssistants:K=!1,autoRestoreLastSession:Q=!1,onInitError:G,client:F,legacyMode:D=!1,historyFilter:N,debounceTime:U})=>{let _=R.useMemo(()=>$||{},[$]),P=R.useRef(G);R.useEffect(()=>{P.current=G},[G]);let q=R.useMemo(()=>{let h=W||globalThis.fetch,n={apiUrl:Z,defaultHeaders:_,callerOptions:{fetch:B?(m,u)=>{return u.credentials="include",h(m,u)}:h,maxRetries:1},legacyMode:D};if(F)n.client=F;return h1(X,n,{showHistory:J,showGraph:V,fallbackToAvailableAssistants:K,autoRestoreLastSession:Q,historyFilter:N,debounceTime:U})},[X,Z,_,B,W,J,V,K,Q,F,D,N,U]),E=I1(q,g1),M=R.useRef(!1);return R.useEffect(()=>{if(M.current)return;M.current=!0,E.initClient().catch((h)=>{if(console.error(h),P.current)P.current(h,E.currentAgent)})},[E]),R.createElement(m1.Provider,{value:E},Y)};export{o as v,j5 as w,K0 as x,e0 as y,G1 as z,O6 as A,f6 as B};
@@ -1 +0,0 @@
1
- import{A as U}from"./chunk-fbemqjck.js";import"./chunk-pzb224c5.js";import{W as g,Y as D}from"./chunk-4wnmk2tj.js";import{Ae as X,Je as L,Ne as V,we as C,ze as w}from"./chunk-c7kd2qrp.js";import"./chunk-t6440ajd.js";import"./chunk-nmzx5nmt.js";import"./chunk-q1cxrg0x.js";import"./chunk-tjg2e8v3.js";import{Dl as v}from"./chunk-y8qhrx11.js";var A=v(C(),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),y=({onClose:J})=>{let{currentChatId:O,toHistoryChat:Y,createNewChat:Z,refreshHistoryList:W,historyFilter:_}=U(),b=A.useMemo(()=>({metadata:{path:process.cwd()}}),[]),{data:B=[],refetch:c}=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=z.title||z.thread_id.slice(-8),x=Q?">":" ",f=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:[x,f," ",$+1,". ",k]},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:["title","thread_id"],searchPlaceholder:"搜索对话标题...",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)},zz=y;export{zz as default};
@@ -1 +0,0 @@
1
- import{h as d,i as e}from"./chunk-js4qp900.js";import{j as u}from"./chunk-h8fdexm4.js";import{R as o}from"./chunk-m21hvv91.js";import"./chunk-4wnmk2tj.js";import{Ae as J,De as c,Ie as x,Je as f,Ke as s,Le as i,Ne as t,we as l,ze as N}from"./chunk-c7kd2qrp.js";import"./chunk-a9tw6d68.js";import"./chunk-k4q8j7pg.js";import"./chunk-spx7nn8t.js";import"./chunk-vfxjbdz4.js";import"./chunk-qxebn3jw.js";import"./chunk-e8kxa5vj.js";import"./chunk-q1cxrg0x.js";import"./chunk-tjg2e8v3.js";import{Dl as S}from"./chunk-y8qhrx11.js";var zq=S(l(),1);var U=S(l(),1);var H=S(f(),1),a={openai:"\uD83E\uDD16",anthropic:"\uD83E\uDDE0",gemini:"✨",default:"\uD83D\uDD2E"};var Jq=({defaultValue:O,onSubmit:F,onSwitchProvider:X})=>{let[_,W]=U.useState(O),B=U.useCallback((G)=>{if(!G.trim())return;F(G.trim())},[F]),R=U.useCallback((G,K)=>{if(K.tab)return X?.(K.shift?"left":"right"),!1;if(K.leftArrow)return X?.("left"),!1;if(K.rightArrow)return X?.("right"),!1;return!0},[X]);return H.jsxDEV(N,{paddingX:2,paddingY:1,flexDirection:"column",gap:1,children:[H.jsxDEV(J,{color:"gray",children:"请输入模型名称(Enter 确认):"},void 0,!1,void 0,this),H.jsxDEV(s,{value:_,onChange:W,onSubmit:B,onHotKey:R,maxVisibleLines:1,placeholder:"例如:gpt-4o"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},Qq=({onClose:O})=>{let{extraParams:F,config:X,updateConfig:_}=u(),[W,B]=U.useState(""),R=U.useRef([]),G=U.useMemo(()=>{if(!X?.providers||X.providers.length===0)return[];return X.providers.map((q)=>{let $=q.type||"default";return{id:q.id,label:q.id,icon:a[$]||a.default,config:q}})},[X?.providers]);U.useMemo(()=>{if(G.length>0&&!W){let q=G.find(($)=>$.id===F.provider_id);B(q?.id||G[0].id)}},[G,F.provider_id,W]);let K=G.find((q)=>q.id===W),{data:V,isLoading:y,error:v}=d({provider:K?.config||null,enabled:!!W}),b=U.useMemo(()=>{let q=(V||[]).map(($)=>({id:$.id,name:$.name}));return R.current=q,q},[V]),D=U.useCallback(async()=>{return R.current},[]),j=U.useCallback((q,$,C)=>{let M=q.id===F.provider_id+"-"+q.id;return H.jsxDEV(i,{isSelected:C,isCurrent:M,children:[H.jsxDEV(J,{bold:!0,children:[$+1,". ",q.id]},void 0,!0,void 0,this),H.jsxDEV(J,{dimColor:!0,children:[" ",q.name!==q.id?`(${q.name})`:""]},void 0,!0,void 0,this)]},`model-${$}-${q.id}`,!0,void 0,this)},[F.provider_id]),P=U.useCallback((q)=>{return q.id===F.provider_id+"-"+q.id},[F.provider_id]),g=U.useCallback(async(q)=>{await _({model_id:q}),O()},[_,O]),E=U.useCallback(async(q)=>{let C=G.find((M)=>M.id===W)?.config.type||"openai";await _({provider_id:W,provider_type:C,model_id:q.id}),O()},[_,W,O,G]),k=U.useCallback(async(q)=>{if(G.length<=1)return;let $=G.findIndex((p)=>p.id===W),C=q==="left"?($-1+G.length)%G.length:($+1)%G.length,M=G[C];B(M.id),await _({provider_id:M.id,provider_type:M.config.type})},[W,G,_]),m=U.useMemo(()=>{let q=K?.label||"加载中...";return{id:`model-${W}`,title:`模型选择 - ${q}`,icon:K?.icon||"\uD83D\uDD2E",dataSource:D,searchable:!0,searchFields:["id","name"],searchPlaceholder:"搜索模型...",itemHeight:1,visibleCount:10,renderItem:j,isSelected:P,onSelect:E,showCount:!0,keyMap:{leftArrow:($)=>{k("left")},rightArrow:($)=>{k("right")}}}},[W,K,D,j,P,E,k]);if(G.length===0)return H.jsxDEV(N,{flexDirection:"column",paddingX:2,paddingY:1,children:[H.jsxDEV(J,{color:"yellow",children:"⚠️ 未配置任何 Provider"},void 0,!1,void 0,this),H.jsxDEV(J,{color:"gray",dimColor:!0,children:"请先配置 Provider 后再查看模型列表"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let T=K?.config.apiKey;return H.jsxDEV(N,{flexDirection:"column",children:[H.jsxDEV(N,{gap:1,paddingX:1,paddingY:1,children:G.map((q,$)=>H.jsxDEV(J,{bold:q.id===W,color:q.id===W?"cyan":"gray",children:[q.icon," ",q.label,q.id===W&&" [当前]",q.id===W&&!T&&" (未配置 API Key)"]},`provider-tab-${$}-${q.id}`,!0,void 0,this))},void 0,!1,void 0,this),y?H.jsxDEV(N,{paddingX:2,paddingY:1,children:H.jsxDEV(J,{color:"gray",children:"加载模型列表中..."},void 0,!1,void 0,this)},void 0,!1,void 0,this):v||b.length===0?H.jsxDEV(Jq,{defaultValue:X?.model_id||"",onSubmit:g,onSwitchProvider:k},void 0,!1,void 0,this):!T?H.jsxDEV(N,{paddingX:2,paddingY:1,children:H.jsxDEV(J,{color:"yellow",children:"请先配置 API Key"},void 0,!1,void 0,this)},void 0,!1,void 0,this):H.jsxDEV(t,{config:m,onClose:O},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},r=Qq;var z=S(l(),1);var Z=S(f(),1),Wq=({onClose:O})=>{let{config:F,updateConfig:X}=u(),[_,W]=z.useState("list"),[B,R]=z.useState(null),[G,K]=z.useState(0),[V,y]=z.useState(null),v=z.useCallback(()=>y(null),[]);o(v,V?3000:null);let b=z.useRef(_),D=z.useRef(G),j=z.useRef([]),P=z.useRef(!0);z.useEffect(()=>{b.current=_},[_]),z.useEffect(()=>{D.current=G},[G]);let g=F?.providers||[];z.useEffect(()=>{j.current=g},[g]);let E=z.useCallback(()=>{P.current=!0,R(null),W("form"),y(null)},[]),k=z.useCallback(()=>{let Q=j.current,Y=D.current,L=Q[Y];if(!L)return;P.current=!1,R(L),W("form"),y(null)},[]),m=z.useCallback(()=>{W("list"),R(null),y(null)},[]),T=z.useCallback(async(Q)=>{let Y=j.current,L=P.current,A=L?[...Y,Q]:Y.map((w)=>w.id===Q.id?Q:w);if(await X({providers:A}),y(L?`已添加 Provider: ${Q.id}`:`已更新 Provider: ${Q.id}`),L){let w=A.findIndex((I)=>I.id===Q.id);K(w>=0?w:0)}W("list"),R(null),y(null)},[X]),q=z.useCallback(async()=>{let Q=j.current,Y=D.current,L=Q[Y];if(!L)return;if(Q.length<=1){y("无法删除最后一个 Provider");return}let A=Q.filter((I)=>I.id!==L.id);await X({providers:A});let w=Math.min(Y,A.length-1);K(w>=0?w:0),y(`已删除 Provider: ${L.id}`)},[X]),$=z.useRef(E),C=z.useRef(k),M=z.useRef(q),p=z.useRef(m),n=z.useRef(O);z.useEffect(()=>{$.current=E},[E]),z.useEffect(()=>{C.current=k},[k]),z.useEffect(()=>{M.current=q},[q]),z.useEffect(()=>{p.current=m},[m]),z.useEffect(()=>{n.current=O},[O]),x((Q,Y)=>{let L=b.current,A=j.current,w=D.current;if(L==="form"){if(Y.escape)p.current();return}if(Y.upArrow)K((I)=>I>0?I-1:A.length-1);else if(Y.downArrow)K((I)=>I<A.length-1?I+1:0);else if(Q==="n"||Q==="N")$.current();else if((Q==="e"||Q==="E"||Y.return)&&A[w])C.current();else if((Q==="d"||Q==="D")&&A[w])M.current();else if(Y.escape)n.current()},{isActive:!0});let Gq=z.useMemo(()=>{if(g.length===0)return Z.jsxDEV(N,{paddingX:2,paddingY:1,children:Z.jsxDEV(J,{color:"yellow",children:"未配置任何 Provider"},void 0,!1,void 0,this)},void 0,!1,void 0,this);return Z.jsxDEV(N,{flexDirection:"column",paddingX:2,gap:1,children:[g.map((Q,Y)=>{let L=!!Q.apiKey,A=L?"green":"yellow";return Z.jsxDEV(N,{marginBottom:0,gap:1,children:[Z.jsxDEV(J,{color:Y===G?"cyan":"gray",bold:Y===G,children:Y===G?">":" "},void 0,!1,void 0,this),Z.jsxDEV(J,{bold:Y===G,color:Y===G?"cyan":void 0,children:Q.id},void 0,!1,void 0,this),Z.jsxDEV(c,{},void 0,!1,void 0,this),Z.jsxDEV(J,{color:"gray",dimColor:Y!==G,children:[" ",Q.type]},void 0,!0,void 0,this),Z.jsxDEV(J,{color:A,dimColor:Y!==G,children:[" ","[",L?"已配置":"未配置","]"]},void 0,!0,void 0,this)]},`provider-${Y}-${Q.id}`,!0,void 0,this)}),Z.jsxDEV(N,{marginTop:1,children:Z.jsxDEV(J,{color:"gray",dimColor:!0,children:[Z.jsxDEV(J,{color:"cyan",children:"↑↓"},void 0,!1,void 0,this)," 导航 ",Z.jsxDEV(J,{color:"cyan",children:"n"},void 0,!1,void 0,this)," 新增 ",Z.jsxDEV(J,{color:"cyan",children:"d"},void 0,!1,void 0,this)," ","删除 ",Z.jsxDEV(J,{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)},[g,G]);return Z.jsxDEV(N,{flexDirection:"column",children:[Z.jsxDEV(N,{paddingX:2,paddingY:1,children:Z.jsxDEV(J,{bold:!0,color:"cyan",children:"Providers"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_==="list"?Gq:Z.jsxDEV(e,{provider:B||void 0,onCancel:m,onSave:T},void 0,!1,void 0,this),V&&Z.jsxDEV(N,{paddingX:2,paddingY:0,children:Z.jsxDEV(J,{color:"green",children:V},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},qq=Wq;var h=S(f(),1),Xq=({onClose:O,initialTab:F="model"})=>{let[X,_]=zq.useState(F);return x((W,B)=>{if(B.leftArrow&&B.alt)_("model");else if(B.rightArrow&&B.alt)_("provider");else if(B.escape)O()},{isActive:!0}),h.jsxDEV(N,{flexDirection:"column",width:"100%",borderStyle:"single",borderDimColor:!0,children:[h.jsxDEV(N,{flexDirection:"column",paddingX:0,paddingY:0,children:[X==="model"&&h.jsxDEV(r,{onClose:O},void 0,!1,void 0,this),X==="provider"&&h.jsxDEV(qq,{onClose:O},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h.jsxDEV(N,{flexDirection:"row",gap:2,paddingX:2,paddingY:1,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,borderStyle:"single",borderColor:"gray",children:[h.jsxDEV(J,{bold:X==="model",color:X==="model"?"cyan":"gray",children:"\uD83E\uDD16 Model"},void 0,!1,void 0,this),h.jsxDEV(J,{bold:X==="provider",color:X==="provider"?"cyan":"gray",children:"\uD83D\uDD0C Provider"},void 0,!1,void 0,this),h.jsxDEV(c,{},void 0,!1,void 0,this),h.jsxDEV(J,{dimColor:!0,children:"Alt+ < >"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},jq=Xq;export{jq as default};
@@ -1,2 +0,0 @@
1
- import{U,W as Y,X as B,Y as W}from"./chunk-4wnmk2tj.js";import{Ae as O,Je as j,we as q,ze as T}from"./chunk-c7kd2qrp.js";import{if as k}from"./chunk-qxebn3jw.js";import{Dl as b}from"./chunk-y8qhrx11.js";var J=b(q(),1);function K({manager:G,enabled:N=!0}){return Y({queryKey:W.config.detail(),queryFn:async()=>{return await G.initialize(),await G.getConfig()},enabled:N,staleTime:300000,gcTime:600000})}function P({manager:G}){let N=U();return B({mutationFn:async(R)=>{return await G.updateConfig(R),await G.getConfig()},onSuccess:(R)=>{N.setQueryData(W.config.detail(),R),N.invalidateQueries({queryKey:W.providers.all}),N.invalidateQueries({queryKey:W.models.all})}})}var X=b(j(),1),H=null,Z=null;async function S(){if(!H){if(!Z)Z=k().then((G)=>{return H=G,Z=null,G});return Z}return Promise.resolve(H)}var I=J.createContext(void 0),E=({manager:G,get_allowed_models:N,children:R})=>{let{data:z,isLoading:V,error:x}=K({manager:G}),$=P({manager:G}),{data:F=[],isLoading:h,error:p}=Y({queryKey:W.models.available(),queryFn:N,staleTime:1800000,retry:1}),A=J.useMemo(()=>{return{provider_id:z?.provider_id||"openai",provider_type:z?.provider_type||"openai",model_id:z?.model_id||F[0]?.id||"default",mcp_config:z?.mcp_config,enable_thinking:z?.enable_thinking??!0,streaming:z?.streaming??!1,switch_command:z?.switch_command||"",cwd:process.cwd()}},[z?.provider_id,z?.provider_type,z?.model_id,z?.mcp_config,z?.enable_thinking,z?.streaming,z?.switch_command,z?.providers,F]),Q=J.useMemo(()=>{return z?.compact_mode??!1},[z?.compact_mode]),w=async()=>{await $.mutateAsync({compact_mode:!Q})},v=J.useMemo(()=>{return z?.show_detailed_info??!1},[z?.show_detailed_info]),L=async()=>{await $.mutateAsync({show_detailed_info:!v})},D=async(_)=>{await $.mutateAsync(_)};if(V||h)return X.jsxDEV(T,{padding:2,children:X.jsxDEV(O,{children:"Loading configuration..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);return X.jsxDEV(I.Provider,{value:{config:z||null,updateConfig:D,extraParams:A,AVAILABLE_MODELS:F,manager:G,compactMode:Q,toggleCompactMode:w,showDetailedInfo:v,toggleDetailedInfo:L},children:R},void 0,!1,void 0,this)},c=()=>{let G=J.useContext(I);if(G===void 0)throw Error("useSettings must be used within a SettingsProvider");return G},r=({get_allowed_models:G,children:N})=>{let[R,z]=J.useState(null);if(J.useEffect(()=>{S().then(z)},[]),!R)return X.jsxDEV(T,{padding:2,children:X.jsxDEV(O,{children:"Initializing configuration manager..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);return X.jsxDEV(E,{manager:R,get_allowed_models:G,children:N},void 0,!1,void 0,this)};
2
- export{c as j,r as k};