zen-code 4.7.3 → 4.8.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 (83) hide show
  1. package/dist/app.js +271 -0
  2. package/dist/chunk-0fhpz98a.js +2 -0
  3. package/dist/chunk-15smn69q.js +31 -0
  4. package/dist/chunk-3ep2tag7.js +2 -0
  5. package/dist/chunk-3jek9sxm.js +2 -0
  6. package/dist/chunk-3n2b4eb4.js +2 -0
  7. package/dist/chunk-3znrwnd8.js +1 -0
  8. package/dist/chunk-4b8yaknt.js +1 -0
  9. package/dist/chunk-5fqt5yg1.js +81 -0
  10. package/dist/chunk-5nzs0q25.js +1 -0
  11. package/dist/chunk-5wn1nfqy.js +6 -0
  12. package/dist/chunk-6ty22kkt.js +4 -0
  13. package/dist/chunk-70a0e941.js +1 -0
  14. package/dist/chunk-7dp8kq2f.js +2 -0
  15. package/dist/chunk-8nhayyat.js +1 -0
  16. package/dist/chunk-9k57afdm.js +2 -0
  17. package/dist/chunk-9kc9cea3.js +7 -0
  18. package/dist/chunk-bgpcx3bm.js +2 -0
  19. package/dist/chunk-bjywwcgn.js +26 -0
  20. package/dist/chunk-c9q11tk2.js +88 -0
  21. package/dist/chunk-cga0m5sy.js +1 -0
  22. package/dist/chunk-cze71w02.js +2 -0
  23. package/dist/chunk-czz2fs2w.js +7 -0
  24. package/dist/chunk-dh3jz71n.js +1 -0
  25. package/dist/chunk-e0sqjq2h.js +1 -0
  26. package/dist/chunk-efhkdw2z.js +1 -0
  27. package/dist/chunk-ew7249h9.js +1 -0
  28. package/dist/chunk-h5nnz4dy.js +1 -0
  29. package/dist/chunk-hww94vjn.js +1 -0
  30. package/dist/chunk-j1n8jp1w.js +253 -0
  31. package/dist/chunk-j204fejq.js +1 -0
  32. package/dist/chunk-jkbtx9va.js +2 -0
  33. package/dist/chunk-k67epfhc.js +1 -0
  34. package/dist/chunk-kbs4px1b.js +6 -0
  35. package/dist/chunk-keqk70wm.js +2 -0
  36. package/dist/chunk-kxk71nn0.js +1 -0
  37. package/dist/chunk-mg8zpgaz.js +1 -0
  38. package/dist/chunk-n1d8xx5k.js +2 -0
  39. package/dist/chunk-ndtwq2zx.js +2 -0
  40. package/dist/chunk-pdkbrds7.js +1 -0
  41. package/dist/chunk-q8arjxg1.js +23 -0
  42. package/dist/chunk-rdc9pxf6.js +1 -0
  43. package/dist/chunk-rrkzfahh.js +91 -0
  44. package/dist/chunk-s3fyfrka.js +2 -0
  45. package/dist/chunk-sft6ep0c.js +310 -0
  46. package/dist/chunk-vc384abg.js +3 -0
  47. package/dist/chunk-vjj00e3e.js +6 -0
  48. package/dist/chunk-vkng13p1.js +424 -0
  49. package/dist/chunk-wbn1hbxf.js +1 -0
  50. package/dist/chunk-wwn7gw8g.js +274 -0
  51. package/dist/chunk-yaa4eesd.js +2 -0
  52. package/dist/chunk-yvhq458c.js +25 -0
  53. package/dist/cli.js +2 -0
  54. package/dist/nonInteractive.js +4 -0
  55. package/dist/zen-keyboard.js +3 -0
  56. package/package.json +88 -87
  57. package/LICENSE +0 -201
  58. package/dist/FileSystemPluginStore-ChortK7z.mjs +0 -64
  59. package/dist/FileSystemSkillStore-Dl5briBv.mjs +0 -108
  60. package/dist/MultiLineTextInput-CL8nm9nv.mjs +0 -24492
  61. package/dist/_commonjsHelpers-DQNKXVTB.mjs +0 -33
  62. package/dist/app-CK3nD8Gj.mjs +0 -22428
  63. package/dist/checkpoint-C5AFBYE--CczNxXBB.mjs +0 -355
  64. package/dist/checkpoint-DxiUsHMy-B5iaccT2.mjs +0 -394
  65. package/dist/cli.mjs +0 -57
  66. package/dist/devtools-CzaVuYnh.mjs +0 -2667
  67. package/dist/graphBuilder-DJoMXf6J.mjs +0 -28909
  68. package/dist/index-BPG5Np-8.mjs +0 -144
  69. package/dist/index-Dxfhvdx8.mjs +0 -23
  70. package/dist/index-F6_SKYUd.mjs +0 -463
  71. package/dist/load-iYJqYrjn.mjs +0 -119
  72. package/dist/memories-CaHDnBK1.mjs +0 -115
  73. package/dist/metadata-XVTVXthy.mjs +0 -6
  74. package/dist/nonInteractive.mjs +0 -55
  75. package/dist/pg-adapter-BFtir1GE-BbUXBpaX.mjs +0 -60
  76. package/dist/queue-DySatFkr-CG2GdO4P.mjs +0 -106
  77. package/dist/remote-threads-CrG03ZS7-C9duTCnB.mjs +0 -157
  78. package/dist/shallow-G4eKoZ7M.mjs +0 -331
  79. package/dist/shallow-checkpoint-BEhTdp7z-DfHxnfoU.mjs +0 -383
  80. package/dist/sqlite-adapter-oBA95xba-BrBWorSV.mjs +0 -82
  81. package/dist/subTasks-DNjIN4eU.mjs +0 -18
  82. package/dist/zen-code.mjs +0 -3
  83. package/dist/zen-keyboard.mjs +0 -13
@@ -1,119 +0,0 @@
1
- import { existsSync as d, readdirSync as A, lstatSync as b, statSync as k, readFileSync as x } from "node:fs";
2
- import { resolve as m, join as y } from "node:path";
3
- import { parse as N } from "yaml";
4
- const Y = 10 * 1024 * 1024, j = 64, p = 1024;
5
- function S(t, o) {
6
- try {
7
- const n = m(t), i = m(o), e = n.substring(i.length);
8
- return n === i || e.startsWith("/") || e === "";
9
- } catch {
10
- return !1;
11
- }
12
- }
13
- function z(t) {
14
- return t ? t.length > j ? [!1, "name exceeds 64 characters"] : /^[a-z0-9]+(-[a-z0-9]+)*$/.test(t) ? [!0, ""] : [!1, "name must be lowercase alphanumeric with single hyphens only"] : [!1, "name is required"];
15
- }
16
- function C(t) {
17
- const o = ["architecture", "bug-fix", "workflow", "configuration", "optimization"];
18
- return t ? o.includes(t) ? [!0, ""] : [!1, `category must be one of: ${o.join(", ")}`] : [!1, "category is required"];
19
- }
20
- function I(t, o) {
21
- try {
22
- const n = k(t);
23
- if (n.size > Y)
24
- return console.warn(`Skipping ${t}: file too large (${n.size} bytes)`), null;
25
- const i = x(t, "utf-8"), e = /^---\s*\n([\s\S]*?)\n---\s*\n/, a = i.match(e);
26
- if (!a)
27
- return console.warn(`Skipping ${t}: no valid YAML frontmatter found`), null;
28
- const c = a[1];
29
- let r;
30
- try {
31
- r = N(c);
32
- } catch (M) {
33
- return console.warn(`Invalid YAML in ${t}: ${M}`), null;
34
- }
35
- if (typeof r != "object" || r === null)
36
- return console.warn(`Skipping ${t}: frontmatter is not a mapping`), null;
37
- const s = r.name, l = r.description, u = r.tags, g = r.category;
38
- if (!s || !l || !u || !g)
39
- return console.warn(`Skipping ${t}: missing required fields (name, description, tags, category)`), null;
40
- const [_, w] = z(String(s));
41
- _ || console.warn(
42
- `Memory '${s}' in ${t} does not follow naming convention: ${w}. Consider renaming to be compliant.`
43
- );
44
- const [h, E] = C(String(g));
45
- if (!h)
46
- return console.warn(`Skipping ${t}: ${E}`), null;
47
- let f = String(l);
48
- if (f.length > p && (console.warn(`Description exceeds ${p} chars in ${t}, truncating`), f = f.substring(0, p)), !Array.isArray(u))
49
- return console.warn(`Skipping ${t}: tags must be an array`), null;
50
- const v = u.map(String);
51
- return {
52
- name: String(s),
53
- description: f,
54
- tags: v,
55
- category: String(g),
56
- path: t,
57
- source: o,
58
- created: r.created,
59
- last_updated: r.last_updated,
60
- priority: r.priority || "medium",
61
- context_scope: r.context_scope || "project"
62
- };
63
- } catch (n) {
64
- return console.warn(`Error reading ${t}: ${n.message}`), null;
65
- }
66
- }
67
- function $(t, o) {
68
- if (!d(t))
69
- return [];
70
- let n;
71
- try {
72
- n = m(t);
73
- } catch {
74
- return [];
75
- }
76
- const i = [];
77
- let e;
78
- try {
79
- e = A(t);
80
- } catch {
81
- return [];
82
- }
83
- for (const a of e) {
84
- const c = y(t, a);
85
- if (!S(c, n))
86
- continue;
87
- let r;
88
- try {
89
- r = b(c);
90
- } catch {
91
- continue;
92
- }
93
- if (!r.isDirectory())
94
- continue;
95
- const s = y(c, "MEMORY.md");
96
- if (!d(s) || !S(s, n))
97
- continue;
98
- const l = I(s, o);
99
- l && i.push(l);
100
- }
101
- return i;
102
- }
103
- function q(t, o) {
104
- const n = /* @__PURE__ */ new Map();
105
- if (t) {
106
- const i = $(t, "user");
107
- for (const e of i)
108
- n.set(e.name, e);
109
- }
110
- if (o) {
111
- const i = $(o, "project");
112
- for (const e of i)
113
- n.set(e.name, e);
114
- }
115
- return Array.from(n.values());
116
- }
117
- export {
118
- q as l
119
- };
@@ -1,115 +0,0 @@
1
- import { l } from "./load-iYJqYrjn.mjs";
2
- import { n as h } from "./graphBuilder-DJoMXf6J.mjs";
3
- const M = `## Memory System
4
-
5
- 你可以访问一个包含之前任务和经验知识的记忆库。
6
-
7
- {memories_locations}
8
-
9
- **可用的记忆:**
10
-
11
- {memories_list}
12
-
13
- **如何使用记忆:**
14
-
15
- 记忆采用 **渐进式披露** 模式 - 你知道它们存在(上面有元数据),但只在需要时才读取完整内容:
16
-
17
- 1. **识别适用的记忆**: 检查当前任务是否匹配任何记忆的描述或标签
18
- 2. **读取完整记忆内容**: 使用 read_file 工具,路径见上面的列表
19
- 3. **应用知识**: 使用记忆中的信息来指导当前任务
20
-
21
- **何时使用记忆:**
22
- - 遇到与之前任务类似的问题时
23
- - 需要回忆项目特定的约定或模式时
24
- - 需要参考之前的解决方案或决策时
25
- - 需要记住配置或设置细节时
26
-
27
- 记住:记忆是帮助你变得更强大和一致的工具。有疑问时,检查是否有相关的记忆存在!
28
- `;
29
- class f {
30
- name = "MemoriesMiddleware";
31
- // No context schema needed
32
- stateSchema = void 0;
33
- // No context schema needed
34
- contextSchema = void 0;
35
- // No additional tools
36
- tools = [];
37
- memoriesDir;
38
- assistantId;
39
- projectMemoriesDir;
40
- userMemoriesDisplay;
41
- systemPromptTemplate;
42
- /**
43
- * Initialize the memories middleware.
44
- *
45
- * @param memoriesDir - Path to the user-level memories directory (per-agent)
46
- * @param assistantId - The agent identifier for path references in prompts
47
- * @param projectMemoriesDir - Optional path to project-level memories directory
48
- */
49
- constructor(e = {}) {
50
- this.memoriesDir = e.memoriesDir, this.assistantId = e.assistantId, this.projectMemoriesDir = e.projectMemoriesDir || "./.claude/memories", this.memoriesDir && !this.assistantId && console.warn("user memories directory is provided, but assistant id is not provided"), this.assistantId && (this.userMemoriesDisplay = `~/.claude/${this.assistantId}/memories`), this.systemPromptTemplate = M;
51
- }
52
- /**
53
- * Format memories locations for display in system prompt.
54
- */
55
- formatMemoriesLocations() {
56
- const e = [];
57
- return this.userMemoriesDisplay && e.push(`**User Memories**: \`${this.userMemoriesDisplay}\``), this.projectMemoriesDir && e.push(`**Project Memories**: \`${this.projectMemoriesDir}\` (overrides user memories)`), e.join(`
58
- `);
59
- }
60
- /**
61
- * Format memories metadata for display in system prompt.
62
- */
63
- formatMemoriesList(e) {
64
- if (!e.length) {
65
- const s = [`${this.userMemoriesDisplay}/`];
66
- return this.projectMemoriesDir && s.push(`${this.projectMemoriesDir}/`), `(No memories available yet. You can create memories in ${s.join(" or ")})`;
67
- }
68
- const n = ["architecture", "bug-fix", "workflow", "configuration", "optimization"], r = /* @__PURE__ */ new Map();
69
- for (const s of e)
70
- r.has(s.category) || r.set(s.category, []), r.get(s.category).push(s);
71
- const t = [];
72
- for (const s of n) {
73
- const o = r.get(s);
74
- if (!o || o.length === 0)
75
- continue;
76
- t.push(`**${s.charAt(0).toUpperCase() + s.slice(1)} Memories:**`);
77
- const m = { high: 0, medium: 1, low: 2 };
78
- o.sort((i, a) => {
79
- const c = m[i.priority || "medium"] ?? 1, p = m[a.priority || "medium"] ?? 1;
80
- return c !== p ? c - p : i.name.localeCompare(a.name);
81
- });
82
- for (const i of o) {
83
- const a = i.tags.length > 0 ? ` [${i.tags.join(", ")}]` : "";
84
- t.push(`- **${i.name}**: ${i.description}${a}`), t.push(` → Read \`${i.path}\` for full content`);
85
- }
86
- t.push("");
87
- }
88
- return t.join(`
89
- `);
90
- }
91
- /**
92
- * Inject memories documentation into the system prompt.
93
- *
94
- * This runs on every model call to ensure memories info is always available.
95
- *
96
- * @param request - The model request being processed
97
- * @param handler - The handler function to call with the modified request
98
- * @returns The model response from the handler
99
- */
100
- async wrapModelCall(e, n) {
101
- const r = l(this.memoriesDir, this.projectMemoriesDir), t = this.formatMemoriesLocations(), s = this.formatMemoriesList(r), o = this.systemPromptTemplate.replace("{memories_locations}", t).replace("{memories_list}", s);
102
- let m;
103
- e.systemPrompt ? m = e.systemPrompt + `
104
-
105
- ` + o : m = o;
106
- const i = new h(m), a = {
107
- ...e,
108
- systemMessage: i
109
- };
110
- return await n(a);
111
- }
112
- }
113
- export {
114
- f as MemoriesMiddleware
115
- };
@@ -1,6 +0,0 @@
1
- const a = {
2
- path: process.cwd()
3
- };
4
- export {
5
- a as m
6
- };
@@ -1,55 +0,0 @@
1
- import { HumanMessage as c } from "langchain";
2
- import { i as m, j as d, k as p } from "./graphBuilder-DJoMXf6J.mjs";
3
- import "@langchain/langgraph";
4
- import "zod";
5
- import "@langchain/openai";
6
- import "@langchain/anthropic";
7
- import "@langchain/google-genai";
8
- import "yaml";
9
- import "@langgraph-js/standard-agent";
10
- import "micromatch";
11
- import "lowdb";
12
- import "lowdb/node";
13
- async function l() {
14
- return new Promise((t, n) => {
15
- let e = "";
16
- process.stdin.setEncoding("utf8"), process.stdin.on("data", (r) => {
17
- e += r;
18
- }), process.stdin.on("end", () => {
19
- t(e);
20
- }), process.stdin.on("error", (r) => {
21
- n(r);
22
- });
23
- });
24
- }
25
- async function S(t, n = !1) {
26
- await m();
27
- const e = await d();
28
- let r = t || "";
29
- if (n)
30
- try {
31
- r = (await l()).trim();
32
- } catch (o) {
33
- throw console.error("❌ 读取 stdin 失败:", o), o;
34
- }
35
- r || (console.error("❌ 错误: 未提供输入内容"), console.error(`
36
- 用法:`), console.error(' zen-code -p "你的任务描述"'), console.error(' echo "内容" | zen-code'), process.exit(1));
37
- try {
38
- const o = {
39
- messages: [new c(r)],
40
- provider_id: e.provider_id,
41
- model_id: e.model_id,
42
- enable_thinking: e.enable_thinking
43
- }, i = await p.invoke(o, {
44
- recursionLimit: 500
45
- }), s = i.messages || [], a = s[s.length - 1];
46
- return a && console.log(a.text), i;
47
- } catch (o) {
48
- throw console.error(`
49
- ❌ 执行失败: ${o instanceof Error ? o.message : String(o)}
50
- `), o;
51
- }
52
- }
53
- export {
54
- S as runNonInteractive
55
- };
@@ -1,60 +0,0 @@
1
- import { Kysely as r, PostgresDialect as s, sql as e } from "kysely";
2
- class i {
3
- constructor(t) {
4
- this.pool = t, this.db = new r({
5
- dialect: new s({
6
- pool: t
7
- })
8
- });
9
- }
10
- db;
11
- dateToDb(t) {
12
- return t;
13
- }
14
- dbToDate(t) {
15
- return t instanceof Date ? t : new Date(t);
16
- }
17
- jsonToDb(t) {
18
- return t;
19
- }
20
- dbToJson(t) {
21
- return t;
22
- }
23
- buildJsonQuery(t, a, T, E) {
24
- return e`${e.ref(a)}->>${e.lit(T)} = ${e.lit(JSON.stringify(E))}`;
25
- }
26
- now() {
27
- return /* @__PURE__ */ new Date();
28
- }
29
- async createTables(t) {
30
- await e`
31
- CREATE TABLE IF NOT EXISTS threads (
32
- thread_id TEXT PRIMARY KEY,
33
- created_at TIMESTAMP NOT NULL,
34
- updated_at TIMESTAMP NOT NULL,
35
- metadata JSONB NOT NULL DEFAULT '{}',
36
- status TEXT NOT NULL DEFAULT 'idle',
37
- values JSONB,
38
- interrupts JSONB NOT NULL DEFAULT '{}'
39
- )
40
- `.execute(t), await e`
41
- CREATE TABLE IF NOT EXISTS runs (
42
- run_id TEXT PRIMARY KEY,
43
- thread_id TEXT NOT NULL,
44
- assistant_id TEXT NOT NULL,
45
- created_at TIMESTAMP NOT NULL,
46
- updated_at TIMESTAMP NOT NULL,
47
- status TEXT NOT NULL DEFAULT 'pending',
48
- metadata JSONB NOT NULL DEFAULT '{}',
49
- multitask_strategy TEXT NOT NULL DEFAULT 'reject',
50
- FOREIGN KEY (thread_id) REFERENCES threads(thread_id) ON DELETE CASCADE
51
- )
52
- `.execute(t);
53
- }
54
- async createIndexes(t) {
55
- await e`CREATE INDEX IF NOT EXISTS idx_threads_status ON threads(status)`.execute(t), await e`CREATE INDEX IF NOT EXISTS idx_threads_created_at ON threads(created_at)`.execute(t), await e`CREATE INDEX IF NOT EXISTS idx_threads_updated_at ON threads(updated_at)`.execute(t), await e`CREATE INDEX IF NOT EXISTS idx_runs_thread_id ON runs(thread_id)`.execute(t), await e`CREATE INDEX IF NOT EXISTS idx_runs_status ON runs(status)`.execute(t);
56
- }
57
- }
58
- export {
59
- i as PostgresAdapter
60
- };
@@ -1,106 +0,0 @@
1
- import { a as h, C as d } from "./app-CK3nD8Gj.mjs";
2
- import { createClient as m } from "redis";
3
- class o extends h {
4
- // 轮询间隔(毫秒)
5
- constructor(e, t = !0, s = 300) {
6
- super(e, !0, s), this.id = e, this.compressMessages = t, this.ttl = s, this.streamKey = `stream:${this.id}`, this.listKey = `queue:${this.id}`, this.redis = m({
7
- url: process.env.REDIS_URL
8
- }), this.cancelSignal = new AbortController(), this.redis.isOpen || this.redis.connect(), this.isConnected = !0;
9
- }
10
- redis;
11
- streamKey;
12
- listKey;
13
- isConnected = !1;
14
- cancelSignal;
15
- lastStreamId = "0";
16
- // 最后读取的 Stream ID
17
- pollInterval = 100;
18
- /**
19
- * 推送消息到 Redis Stream 和 List
20
- * - Stream: 用于实时推送(集群友好)
21
- * - List: 用于 getAll() 批量获取历史数据
22
- */
23
- async push(e) {
24
- const t = await this.encodeData(e), s = Buffer.from(t).toString("base64"), a = Buffer.from(t);
25
- await this.redis.xAdd(this.streamKey, "*", { data: s }), await this.redis.expire(this.streamKey, this.ttl), await this.redis.rPush(this.listKey, a), await this.redis.expire(this.listKey, this.ttl), this.emit("dataChange", s);
26
- }
27
- /**
28
- * 异步生成器:使用 Redis Streams XREAD 轮询消费队列数据
29
- */
30
- async *onDataReceive() {
31
- let e = !1;
32
- if (this.cancelSignal.signal.aborted)
33
- return;
34
- const t = () => {
35
- e = !0;
36
- };
37
- this.cancelSignal.signal.addEventListener("abort", t);
38
- try {
39
- for (; !e && !this.cancelSignal.signal.aborted; ) {
40
- const s = await this.redis.xRead([{ key: this.streamKey, id: this.lastStreamId }], {
41
- BLOCK: this.pollInterval,
42
- COUNT: 10
43
- });
44
- if (s && s.length > 0)
45
- for (const a of s) {
46
- for (const r of a.messages) {
47
- this.lastStreamId = r.id;
48
- const n = r.message.data, l = Buffer.from(n, "base64"), i = await this.decodeData(l);
49
- if ((i.event === "__stream_end__" || i.event === "__stream_error__" || i.event === "__stream_cancel__") && (await new Promise((c) => setTimeout(c, 300)), e = !0, i.event === "__stream_cancel__" && await this.cancel()), yield i, e)
50
- break;
51
- }
52
- if (e)
53
- break;
54
- }
55
- !e && !this.cancelSignal.signal.aborted && await new Promise((a) => setTimeout(a, this.pollInterval));
56
- }
57
- } finally {
58
- this.cancelSignal.signal.removeEventListener("abort", t);
59
- }
60
- }
61
- /**
62
- * 获取队列中的所有数据(从 List 获取历史数据)
63
- */
64
- async getAll() {
65
- const e = await this.redis.lRange(this.listKey, 0, -1);
66
- return !e || e.length === 0 ? [] : this.compressMessages ? await Promise.all(
67
- e.map((t) => {
68
- const s = typeof t == "string" ? Buffer.from(t, "binary") : t;
69
- return this.decodeData(s);
70
- })
71
- ) : e.map((t) => JSON.parse(t));
72
- }
73
- /**
74
- * 清空队列
75
- */
76
- clear() {
77
- this.isConnected && (this.redis.del(this.streamKey), this.redis.del(this.listKey));
78
- }
79
- /**
80
- * 取消操作
81
- */
82
- async cancel() {
83
- this.cancelSignal.abort("user cancel this run"), await this.push(new d());
84
- }
85
- /**
86
- * 复制队列到另一个队列
87
- */
88
- async copyToQueue(e, t) {
89
- const s = new o(e, this.compressMessages, t ?? this.ttl);
90
- await this.redis.copy(this.listKey, s.listKey), await this.redis.expire(s.listKey, t ?? this.ttl);
91
- const a = await this.redis.xRange(this.streamKey, "-", "+");
92
- if (a && a.length > 0) {
93
- for (const r of a) {
94
- const n = {};
95
- for (const [l, i] of Object.entries(r.message))
96
- n[l] = String(i);
97
- await this.redis.xAdd(s.streamKey, "*", n);
98
- }
99
- await this.redis.expire(s.streamKey, t ?? this.ttl);
100
- }
101
- return s;
102
- }
103
- }
104
- export {
105
- o as RedisStreamQueue
106
- };
@@ -1,157 +0,0 @@
1
- var h = /* @__PURE__ */ ((a) => (a.NETWORK_ERROR = "NETWORK_ERROR", a.CONNECTION_TIMEOUT = "CONNECTION_TIMEOUT", a.INTERNAL_ERROR = "INTERNAL_ERROR", a.THREAD_NOT_FOUND = "THREAD_NOT_FOUND", a.THREAD_BUSY = "THREAD_BUSY", a.RUN_NOT_FOUND = "RUN_NOT_FOUND", a.GRAPH_NOT_FOUND = "GRAPH_NOT_FOUND", a.INVALID_REQUEST = "INVALID_REQUEST", a))(h || {});
2
- class d extends Error {
3
- constructor(s, t, e) {
4
- super(t), this.code = s, this.statusCode = e, this.name = "RemoteApiError";
5
- }
6
- }
7
- async function c(a, s, t) {
8
- try {
9
- let e = a;
10
- if (t?.query) {
11
- const f = new URLSearchParams();
12
- Object.entries(t.query).forEach(([v, N]) => {
13
- f.append(v, String(N));
14
- }), e += `?${f.toString()}`;
15
- }
16
- const i = await fetch(e, {
17
- method: s,
18
- headers: {
19
- "Content-Type": "application/json"
20
- },
21
- body: t?.body ? JSON.stringify(t.body) : void 0
22
- }), n = await i.json();
23
- if (!i.ok || !n.success)
24
- throw new d(
25
- n.error?.code || h.INTERNAL_ERROR,
26
- n.error?.message || "Unknown error",
27
- i.status
28
- );
29
- return n;
30
- } catch (e) {
31
- throw e instanceof d ? e : new d(
32
- h.NETWORK_ERROR,
33
- `Network error: ${e instanceof Error ? e.message : "Unknown error"}`
34
- );
35
- }
36
- }
37
- async function o(a, s) {
38
- return c(a, "GET", { query: s });
39
- }
40
- async function r(a, s, t) {
41
- return c(a, "POST", { body: s, query: t });
42
- }
43
- async function l(a, s, t) {
44
- return c(a, "PUT", { body: s, query: t });
45
- }
46
- async function O(a, s) {
47
- return c(a, "DELETE", { query: s });
48
- }
49
- class p {
50
- constructor(s, t) {
51
- this.serverUrl = s, this.httpClient = t, this.serverUrl = s.replace(/\/$/, ""), this.httpClient = t || fetch;
52
- }
53
- /**
54
- * 初始化数据库
55
- */
56
- async setup() {
57
- await r(`${this.serverUrl}/setup`);
58
- }
59
- /**
60
- * 创建线程
61
- */
62
- async create(s) {
63
- return (await r(`${this.serverUrl}/threads`, s)).data;
64
- }
65
- /**
66
- * 搜索线程
67
- */
68
- async search(s) {
69
- const t = {};
70
- return s?.ids !== void 0 && s.ids.length > 0 && (t.ids = JSON.stringify(s.ids)), s?.metadata !== void 0 && (t.metadata = JSON.stringify(s.metadata)), s?.limit !== void 0 && (t.limit = s.limit), s?.offset !== void 0 && (t.offset = s.offset), s?.status !== void 0 && (t.status = s.status), s?.sortBy !== void 0 && (t.sortBy = s.sortBy), s?.sortOrder !== void 0 && (t.sortOrder = s.sortOrder), s?.values !== void 0 && (t.values = JSON.stringify(s.values)), s?.select !== void 0 && (t.select = JSON.stringify(s.select)), s?.withoutDetails !== void 0 && (t.withoutDetails = s.withoutDetails), (await o(`${this.serverUrl}/threads`, t)).data;
71
- }
72
- /**
73
- * 获取线程
74
- */
75
- async get(s) {
76
- return (await o(`${this.serverUrl}/threads/${s}`)).data;
77
- }
78
- /**
79
- * 更新线程
80
- */
81
- async set(s, t) {
82
- await l(`${this.serverUrl}/threads/${s}`, t);
83
- }
84
- /**
85
- * 删除线程
86
- */
87
- async delete(s) {
88
- await O(`${this.serverUrl}/threads/${s}`);
89
- }
90
- /**
91
- * 更新状态
92
- */
93
- async updateState(s, t) {
94
- return (await r(
95
- `${this.serverUrl}/threads/${s}/state`,
96
- t
97
- )).data;
98
- }
99
- /**
100
- * 创建运行
101
- */
102
- async createRun(s, t, e) {
103
- return (await r(`${this.serverUrl}/threads/${s}/runs`, e || {}, {
104
- assistantId: t
105
- })).data;
106
- }
107
- /**
108
- * 列出运行
109
- */
110
- async listRuns(s, t) {
111
- const e = {};
112
- return t?.limit !== void 0 && (e.limit = t.limit), t?.offset !== void 0 && (e.offset = t.offset), t?.status !== void 0 && (e.status = t.status), (await o(`${this.serverUrl}/threads/${s}/runs`, e)).data;
113
- }
114
- /**
115
- * 更新运行
116
- */
117
- async updateRun(s, t) {
118
- await l(`${this.serverUrl}/runs/${s}`, t);
119
- }
120
- // New methods for Threads API
121
- /**
122
- * 计算线程数量
123
- */
124
- async count(s) {
125
- const t = {};
126
- return s?.ids !== void 0 && s.ids.length > 0 && (t.ids = JSON.stringify(s.ids)), s?.metadata !== void 0 && (t.metadata = JSON.stringify(s.metadata)), s?.status !== void 0 && (t.status = s.status), s?.values !== void 0 && (t.values = JSON.stringify(s.values)), (await o(`${this.serverUrl}/threads/count`, t)).data;
127
- }
128
- /**
129
- * 更新线程元数据
130
- */
131
- async patch(s, t) {
132
- return (await r(`${this.serverUrl}/threads/${s}`, t)).data;
133
- }
134
- /**
135
- * 获取线程状态
136
- */
137
- async getState(s, t) {
138
- const e = {};
139
- return t?.subgraphs !== void 0 && (e.subgraphs = t.subgraphs), t?.checkpointId !== void 0 && (e.checkpointId = t.checkpointId), (await r(`${this.serverUrl}/threads/${s}/state`, e)).data;
140
- }
141
- /**
142
- * 获取线程历史
143
- */
144
- async getStateHistory(s, t) {
145
- const e = {};
146
- return t?.limit !== void 0 && (e.limit = t.limit), t?.before !== void 0 && (e.before = t.before), (await r(`${this.serverUrl}/threads/${s}/history`, e)).data;
147
- }
148
- /**
149
- * 复制线程
150
- */
151
- async copy(s) {
152
- return (await r(`${this.serverUrl}/threads/${s}/copy`)).data;
153
- }
154
- }
155
- export {
156
- p as RemoteKyselyThreadsManager
157
- };