dsh-netchat 0.0.0-stage → 0.3.19

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.
@@ -0,0 +1,803 @@
1
+ import * as C from "./consts.mjs";
2
+ import { NetChatError, clip } from "./util.mjs";
3
+
4
+ const s = (description) => ({ type: "string", description });
5
+ const i = (description, min, max) => ({ type: "integer", minimum: min, maximum: max, description });
6
+ const b = (description) => ({ type: "boolean", description });
7
+ const idList = { type: "array", items: { type: "string" }, description: "要标记的条目 id" };
8
+
9
+ function ok(structured, text) {
10
+ return { content: [{ type: "text", text }], structuredContent: structured };
11
+ }
12
+
13
+ /** Inbox items still waiting on this machine; everything else counts as handled. */
14
+ const OPEN_STATUSES = new Set(["new", "accepted", "starting", "running"]);
15
+
16
+ /** Uniform failure shape for the model, the panel and the loopback client. */
17
+ export function errorResult(error) {
18
+ if (!(error instanceof NetChatError)) {
19
+ const code = typeof error?.code === "string" ? error.code : "internal_error";
20
+ const message = error instanceof Error ? error.message : String(error);
21
+ return { isError: true, content: [{ type: "text", text: `[${code}] ${message}` }], structuredContent: { error: { code, message } } };
22
+ }
23
+ const { code, message, name, stack, ...extra } = error;
24
+ return { isError: true, content: [{ type: "text", text: `[${code}] ${message}` }], structuredContent: { error: { code, message, ...extra } } };
25
+ }
26
+
27
+ /** One tool: what the model sees, whether the panel may call it, and how it runs. */
28
+ const TOOLS = {
29
+ net_chat_status: {
30
+ description: "查看 NetChat 服务状态:本机身份、在线 Agent 数量、未读数、可用能力与已授予的权限。",
31
+ input: {},
32
+ visibility: ["model", "app"],
33
+ readOnly: true,
34
+ async run(netChat, args, meta) {
35
+ const status = await netChat.status(meta);
36
+ const current = await netChat.currentSession(meta).catch(() => null);
37
+ const result = { ...status, currentSession: current };
38
+ const ability = Object.entries(status.capabilities)
39
+ .filter(([, enabled]) => enabled)
40
+ .map(([name]) => name)
41
+ .join(", ");
42
+ return ok(
43
+ result,
44
+ [
45
+ `NetChat 运行中(${status.owner},端口 ${status.port})。`,
46
+ `本机:${status.identity.name}${status.identity.role ? `(${status.identity.role})` : ""},id=${status.identity.id}。`,
47
+ `在线 Agent ${status.online} 个(已知 ${status.known} 个),未读 ${status.unread} 条${status.openQuestions ? `,待回答的提问 ${status.openQuestions} 个` : ""}。`,
48
+ `能力:${ability || "无"}。权限:读取=${status.grants.read ?? "未知"},写入=${status.grants.write ?? "未知"}。`,
49
+ current ? `当前会话:${current.sessionId}` : "",
50
+ ]
51
+ .filter(Boolean)
52
+ .join("\n"),
53
+ );
54
+ },
55
+ },
56
+
57
+ net_chat_list_agents: {
58
+ description:
59
+ "列出局域网内已发现、装有 NetChat 插件的 ZCode Agent(通常是同事的机器):名称、角色、在线状态与是否通过团队密钥验证。发任务前先用它确认目标。",
60
+ input: {},
61
+ visibility: ["model", "app"],
62
+ readOnly: true,
63
+ async run(netChat) {
64
+ const agents = netChat.listAgents();
65
+ // The parties the user took off the list travel with the answer: the panel builds its list
66
+ // from old records too, and has to leave those off as well.
67
+ const hidden = netChat.hiddenAgents();
68
+ if (agents.length === 0) {
69
+ return ok({ agents, hidden }, hidden.length ? "已发现的 Agent 都被移除了;它们再次上线时会重新出现。" : "还没有发现任何局域网 Agent。请确认同事的 ZCode 已安装并启用 NetChat,且在同一个网络内。");
70
+ }
71
+ const lines = agents.map((agent) => {
72
+ const state = agent.online ? "在线" : `离线(${ago(agent.lastSeenAgo)})`;
73
+ const trust = agent.trust === "team" ? "已验证" : agent.trust === "foreign" ? "未验证(非同组)" : "未验证(未设置团队密钥)";
74
+ return `- ${agent.name}${agent.role ? `(${agent.role})` : ""} id=${agent.id} ${agent.host} ${state} ${trust}`;
75
+ });
76
+ return ok({ agents, hidden }, lines.join("\n"));
77
+ },
78
+ },
79
+
80
+ net_chat_send_task: {
81
+ description:
82
+ "把一项开发需求(例如需要前端或后端同事修改的功能)发送给局域网内指定的 Agent 去执行。这是对外发送的操作:发送前必须先把标题、正文和目标 Agent 念给用户确认。body 中写清背景、要改什么、涉及文件与验收标准;attachSession 会把最近几轮会话记录作为背景一并发送。",
83
+ input: {
84
+ agent: s("目标 Agent 的 id 或名称"),
85
+ title: s("一句话标题(不超过 200 字)"),
86
+ body: s("需求说明:背景、要改什么、涉及文件、验收标准"),
87
+ workspaceHint: s("发起方机器上的项目路径或名称,帮助对方选择本地项目"),
88
+ priority: s("normal 或 high"),
89
+ attachSession: b("是否附带会话记录作为背景"),
90
+ sessionId: s("要附带的会话 id;默认使用当前会话"),
91
+ sessionMessages: i("附带最近多少条消息", 1, 200),
92
+ },
93
+ required: ["agent", "title", "body"],
94
+ visibility: ["model", "app"],
95
+ readOnly: false,
96
+ async run(netChat, args, meta) {
97
+ const agent = netChat.resolveAgent(args.agent);
98
+ const title = text(args.title, "title", 1, C.MAX_TITLE_CHARS);
99
+ const payload = {
100
+ title,
101
+ body: text(args.body, "body", 1, C.MAX_BODY_CHARS),
102
+ priority: optionalEnum(args.priority, "priority", C.PRIORITIES, "normal"),
103
+ };
104
+ if (args.workspaceHint !== undefined && args.workspaceHint !== "") {
105
+ payload.workspaceHint = text(args.workspaceHint, "workspaceHint", 1, C.MAX_HINT_CHARS);
106
+ }
107
+ if (args.attachSession === true) {
108
+ const sessionId = args.sessionId ?? (await netChat.currentSession(meta))?.sessionId;
109
+ if (!sessionId) {
110
+ throw new NetChatError("session_required", "没有可附带的会话:请提供 sessionId,或在没有打开会话时不要设置 attachSession");
111
+ }
112
+ payload.session = await netChat.readTranscript(sessionId, {
113
+ meta,
114
+ maxMessages: int(args.sessionMessages, 1, 200, 20),
115
+ title: (await netChat.sessionInfo(sessionId, meta)).title,
116
+ });
117
+ }
118
+ // The task remembers which session sent it, so a question about it can come back here.
119
+ const originSessionId = (await netChat.currentSession(meta).catch(() => null))?.sessionId ?? null;
120
+ // The directory that session works in goes by a name, once the owner gave it one (see
121
+ // setProjectName): the party doing the task then opens on the directory of theirs that goes
122
+ // by the same name.
123
+ const originWorkspacePath = originSessionId ? await netChat.sessionWorkspacePath(originSessionId, meta).catch(() => "") : "";
124
+ const projectName = netChat.nameForPath(originWorkspacePath);
125
+ if (projectName) payload.projectName = projectName;
126
+ const { item, delivered } = await netChat.send("task", agent.id, payload, { originSessionId, meta });
127
+ const target = `${agent.name}${agent.role ? `(${agent.role})` : ""}`;
128
+ return ok(
129
+ { item: netChat.publicSentItem(item), delivered },
130
+ delivered
131
+ ? `任务已送达 ${target}:「${title}」。对方确认或开始执行后,可用 net_chat_outbox 查看进度。任务 id=${item.id}`
132
+ : `任务未能送达 ${target}:「${title}」。原因:${item.error}。可稍后用 net_chat_resend 重试。任务 id=${item.id}`,
133
+ );
134
+ },
135
+ },
136
+
137
+ net_chat_read_session: {
138
+ description: "预览一个本地会话最近的用户消息与助手回复,以便在把会话作为任务背景附上之前确认将发出什么内容。",
139
+ input: { sessionId: s("会话 id;默认使用当前会话"), maxMessages: i("最近多少条消息", 1, 200) },
140
+ visibility: ["model", "app"],
141
+ readOnly: true,
142
+ async run(netChat, args, meta) {
143
+ const sessionId = args.sessionId ?? (await netChat.currentSession(meta))?.sessionId;
144
+ if (!sessionId) throw new NetChatError("session_required", "没有可读取的会话:请提供 sessionId");
145
+ const session = await netChat.readTranscript(sessionId, { maxMessages: int(args.maxMessages, 1, 200, 20), title: "", meta });
146
+ const rendered = session.messages.map((entry) => `[${entry.role === "user" ? "用户" : "助手"}] ${entry.text}`).join("\n\n");
147
+ const header = `会话 ${sessionId}:共 ${session.total} 条,显示最近 ${session.messages.length} 条${session.truncated ? "(已截断)" : ""}。\n\n`;
148
+ return ok({ sessionId, ...session }, header + clip(rendered, 200_000));
149
+ },
150
+ },
151
+
152
+ net_chat_inbox: {
153
+ description: "查看本机通过 NetChat 收到的任务、消息和会话分享。默认只看未完成的(待处理、已接手、执行中);需要包含已完成、已拒绝的记录时设 includeHandled。",
154
+ input: { limit: i("最多返回多少条", 1, 100), includeHandled: b("是否包含已完成、已拒绝、已失败的条目") },
155
+ visibility: ["model", "app"],
156
+ readOnly: true,
157
+ async run(netChat, args) {
158
+ const items = netChat.inbox.filter((item) => item.kind === "task" && (args.includeHandled === true || OPEN_STATUSES.has(item.status))).slice(0, int(args.limit, 1, 100, 20));
159
+ const lines = items.map((item) => `- ${projectTag(item)}${labelOf(item)} 来自 ${item.from.name}(${item.status})${threadSummary(item)} id=${item.id}`);
160
+ return ok({ items: items.map((item) => netChat.publicInboxItem(item)) }, items.length ? lines.join("\n") : "没有未完成的任务。");
161
+ },
162
+ },
163
+
164
+ net_chat_outbox: {
165
+ description: "查看本机通过 NetChat 发出的任务,以及对方的回执和任务线程里的往来消息。",
166
+ input: { limit: i("最多返回多少条", 1, 100) },
167
+ visibility: ["model", "app"],
168
+ readOnly: true,
169
+ async run(netChat, args) {
170
+ // Thread messages and receipts are kept with their task; only the tasks themselves are listed.
171
+ const items = netChat.outbox.filter((item) => item.kind === "task").slice(0, int(args.limit, 1, 100, 20));
172
+ const lines = items.map((item) => {
173
+ const last = item.receipts.at(-1);
174
+ const state = last ? `${item.status}${last.detail ? `:${last.detail}` : ""}` : item.status === "failed" ? `发送失败:${item.error}` : item.status;
175
+ return `- ${projectTag(item)}${labelOf(item)} 发给 ${item.to.name}(${state})${threadSummary(item)} id=${item.id}`;
176
+ });
177
+ return ok({ items: items.map((item) => netChat.publicSentItem(item)) }, items.length ? lines.join("\n") : "还没有发送过任何任务。");
178
+ },
179
+ },
180
+
181
+ net_chat_open_tasks: {
182
+ description: "查看当前仍未完成的 NetChat 任务一览(本机执行的 + 本机发出的),每条带可跳转的本地会话 id。供面板角标与列表使用。",
183
+ input: {},
184
+ visibility: ["app"],
185
+ readOnly: true,
186
+ async run(netChat) {
187
+ const tasks = openTasks(netChat);
188
+ const lines = tasks.map((entry) => {
189
+ const where = entry.direction === "in" ? `来自 ${entry.peer}` : `发给 ${entry.peer}`;
190
+ const session = entry.sessionId ? ` sessionId=${entry.sessionId}` : "";
191
+ return `- [${entry.state}] ${entry.title}(${where})${session} id=${entry.id}`;
192
+ });
193
+ return ok({ tasks, total: tasks.length }, tasks.length ? lines.join("\n") : "没有未完成的任务。");
194
+ },
195
+ },
196
+
197
+ net_chat_get_item: {
198
+ description: "查看一条任务的完整内容:需求说明、附带的会话记录(分页返回)以及任务线程里的全部消息。",
199
+ input: { id: s("任务 id"), box: s("inbox(本机执行的)或 outbox(本机发起的)"), offset: i("会话记录的起始下标", 0), limit: i("返回多少条会话消息", 1, 200) },
200
+ required: ["id"],
201
+ visibility: ["model", "app"],
202
+ readOnly: true,
203
+ async run(netChat, args) {
204
+ const id = text(args.id, "id", 1, 80);
205
+ const item =
206
+ optionalEnum(args.box, "box", ["inbox", "outbox"], "inbox") === "outbox"
207
+ ? sentDetail(netChat.outbox, id, args)
208
+ : netChat.inboxDetail(id, { offset: args.offset, limit: args.limit });
209
+ return ok({ item }, describeDetail(item));
210
+ },
211
+ },
212
+
213
+ net_chat_respond: {
214
+ description:
215
+ "处理收到的一条任务。action:execute=在本机新建会话开始执行;accept=接手并在当前会话处理;decline=拒绝;done / failed=完成或无法完成,并在 text 里说明结果。" +
216
+ "reply=在任务线程里给发起人发消息:需要对方做选择时在 options 里给出选项;回答对方的提问时在 answerOf 里带上那条提问的 id。除 reply 外都会给发起方发送回执。",
217
+ input: {
218
+ itemId: s("收件箱里的任务 id"),
219
+ action: s("execute、accept、decline、reply、done 或 failed"),
220
+ text: s("回复内容、提问内容或结果说明"),
221
+ options: { type: "array", items: { type: "string" }, description: `仅 reply:让对方从中选择的选项(1-${C.MAX_OPTION_COUNT} 个)`, maxItems: C.MAX_OPTION_COUNT },
222
+ answerOf: s("仅 reply:要回答的那条消息的 id"),
223
+ projectId: s("execute 时指定本地项目 id;不填则按项目提示或默认项目选择"),
224
+ model: s("execute 时指定这次新建会话所用的模型 id(见 net_chat_list_models);不填则用设置里的默认模型,再没有就用宿主自己的默认"),
225
+ sessionId: s("execute 时把任务放进这个已有会话执行(见 net_chat_list_sessions),而不是新建会话;会话保留自己的标题和模型"),
226
+ noProject: b("execute 时不指定项目,让 ZCode 在 NetChat 插件自己的项目里执行(用户选择“不在项目中执行”时用)"),
227
+ projectName: s("execute 时确认这个本地项目所属的项目名。确认后会记到执行所用的本地项目上,并随回执带给发起人:任务带了所属项目(net_chat_get_item 能看到)就原样传它;任务没带时传用户给的名字;传空字符串表示去掉该项目的名字。不传则不改"),
228
+ open: b("execute 时是否打开新会话(默认 true)"),
229
+ },
230
+ required: ["itemId", "action"],
231
+ visibility: ["model", "app"],
232
+ readOnly: false,
233
+ async run(netChat, args, meta) {
234
+ const itemId = text(args.itemId, "itemId", 1, 80);
235
+ const action = enumValue(args.action, "action", ["execute", "accept", "decline", "reply", "done", "failed"]);
236
+ const item = await netChat.respond(itemId, action, {
237
+ text: args.text === undefined ? "" : clip(String(args.text), C.MAX_REPLY_CHARS),
238
+ options: args.options ?? null,
239
+ answerOf: optionalText(args.answerOf, 80),
240
+ project: args.noProject === true ? { none: true } : args.projectId ? { projectId: text(args.projectId, "projectId", 1, 200) } : null,
241
+ model: optionalText(args.model, C.MAX_MODEL_ID_CHARS),
242
+ sessionId: optionalText(args.sessionId, 200),
243
+ // May be empty, which takes the project's name away; left out, which leaves it as it is.
244
+ projectName: args.projectName === undefined ? undefined : text(args.projectName, "projectName", 0, C.MAX_PROJECT_NAME_CHARS),
245
+ open: args.open !== false,
246
+ meta,
247
+ });
248
+ const sent = item.message;
249
+ const message = {
250
+ execute: item.sessionId
251
+ ? item.reusedSession
252
+ ? `已把任务放进已有会话执行:${item.sessionTitle ?? ""}(${item.sessionId})`
253
+ : `已在本机新建会话并开始执行:${item.sessionTitle ?? ""}(${item.sessionId})`
254
+ : "已开始执行。",
255
+ accept: "已接手,并已通知发起方。",
256
+ decline: "已拒绝,并已通知发起方。",
257
+ // Name the message's id: it is what an answer and a wait refer to.
258
+ reply: sent?.options?.length
259
+ ? `提问已发送给 ${item.from.name},提问 id=${sent.id}。对方回答后可用 net_chat_wait_answer(questionId 填这个 id)等待,或用 net_chat_get_item 查看。`
260
+ : sent
261
+ ? `消息已发送给 ${item.from.name},消息 id=${sent.id}。`
262
+ : "消息已发送。",
263
+ done: "已标记为完成,并已通知发起方。",
264
+ failed: "已标记为无法完成,并已通知发起方。",
265
+ }[action];
266
+ return ok(sent ? { item, message: sent } : { item }, message);
267
+ },
268
+ },
269
+
270
+ net_chat_write_thread: {
271
+ description:
272
+ "在一条已有任务的线程里给对方发消息:补充或修正需求、回答对方在执行中提出的问题(answerOf 填那条提问的 id,text 填所选选项或说明)、或向对方提问(在 options 里给出选项)。" +
273
+ "消息只在任务线程内传递,不能脱离任务单独发送。对方正在执行的任务会直接收到这条消息并据此继续。",
274
+ input: {
275
+ taskId: s("任务 id(本机发起的或本机执行的)"),
276
+ text: s("消息内容"),
277
+ options: { type: "array", items: { type: "string" }, description: `让对方从中选择的选项(1-${C.MAX_OPTION_COUNT} 个),不填则是普通消息`, maxItems: C.MAX_OPTION_COUNT },
278
+ answerOf: s("要回答的那条提问的 id"),
279
+ },
280
+ required: ["taskId", "text"],
281
+ visibility: ["model", "app"],
282
+ readOnly: false,
283
+ async run(netChat, args) {
284
+ const taskId = text(args.taskId, "taskId", 1, 80);
285
+ const textValue = text(args.text, "text", 1, C.MAX_REPLY_CHARS);
286
+ const answerOf = optionalText(args.answerOf, 80);
287
+ // The task is this machine's own when it arrived here; otherwise it was sent from here.
288
+ const message = netChat.inbox.some((item) => item.id === taskId && item.kind === "task")
289
+ ? await netChat.respond(taskId, "reply", { text: textValue, options: args.options ?? null, answerOf })
290
+ : await netChat.writeThread(taskId, { text: textValue, options: args.options ?? null, answerOf });
291
+ const task = netChat.inbox.find((item) => item.id === taskId) ?? netChat.outbox.find((item) => item.id === taskId);
292
+ const other = task.from?.name ?? task.to?.name;
293
+ return ok(
294
+ { message, task: netChat.publicSentItem(task) },
295
+ message.delivery === "failed"
296
+ ? `消息未能送达 ${other}:${message.error}`
297
+ : message.options?.length
298
+ ? `提问已发送给 ${other},提问 id=${message.id}。对方回答后可用 net_chat_get_item 查看。`
299
+ : `消息已送达 ${other} 的任务线程。`,
300
+ );
301
+ },
302
+ },
303
+
304
+ net_chat_wait_answer: {
305
+ description:
306
+ "等待自己在某条任务线程里提出的提问被对方回答。执行任务时如果需要发起人做选择:先用 net_chat_respond(action=reply,带 options)提问,再调用本工具等待,返回后按所选选项继续。",
307
+ input: { itemId: s("任务 id"), questionId: s("要等待的那条提问的消息 id;不填则等该任务线程里最新的未回答提问"), timeoutMs: i("最长等待多少毫秒", 1000, 300000) },
308
+ required: ["itemId"],
309
+ visibility: ["model"],
310
+ readOnly: true,
311
+ async run(netChat, args, meta, { waitMs = 120_000, signal } = {}) {
312
+ const itemId = text(args.itemId, "itemId", 1, 80);
313
+ const timeoutMs = int(args.timeoutMs, 1000, 300_000, waitMs);
314
+ const questionId = optionalText(args.questionId, 80);
315
+ const task = netChat.inbox.find((item) => item.id === itemId && item.kind === "task");
316
+ if (!task) throw new NetChatError("not_found", "找不到这条本机执行的任务");
317
+ const answer = await netChat.waitAnswer(task, { questionId, timeoutMs, signal });
318
+ if (!answer) return ok({ answered: false }, "等待超时,对方还没有回答。可以继续等待,或按自己的判断处理并在结果里说明。");
319
+ return ok(
320
+ { answered: true, question: answer.question, answer: answer.text, ts: answer.ts },
321
+ `对方选择了:「${answer.text}」。\n问题:${answer.question.text}\n请按这个回答继续处理当前任务。`,
322
+ );
323
+ },
324
+ },
325
+
326
+ net_chat_resend: {
327
+ description: "重发一条发送失败的任务。",
328
+ input: { itemId: s("发件箱条目 id") },
329
+ required: ["itemId"],
330
+ visibility: ["model", "app"],
331
+ readOnly: false,
332
+ async run(netChat, args) {
333
+ const item = await netChat.resend(text(args.itemId, "itemId", 1, 80));
334
+ return ok({ item }, item.status === "delivered" ? `已重新送达 ${item.to.name}。` : `仍然未能送达 ${item.to.name}:${item.error}`);
335
+ },
336
+ },
337
+
338
+ net_chat_list_projects: {
339
+ description: "列出本机 ZCode 中可用的项目,用于为收到的任务选择执行项目。",
340
+ input: {},
341
+ visibility: ["model", "app"],
342
+ readOnly: true,
343
+ async run(netChat, args, meta) {
344
+ const projects = (await netChat.listProjects(meta)).map(({ project, ...rest }) => rest);
345
+ return ok(
346
+ { projects },
347
+ projects.length ? projects.map((entry) => `- ${entry.title}${entry.name ? `(所属项目 ${entry.name})` : ""} id=${entry.projectId}`).join("\n") : "没有可用的项目(或尚未授予会话读取权限)。",
348
+ );
349
+ },
350
+ },
351
+
352
+ net_chat_list_models: {
353
+ description: "列出本机宿主可以用来新建会话的模型(id 与显示名),以及设置里的默认模型。改默认模型用 net_chat_update_profile 的 defaultModel。",
354
+ input: {},
355
+ visibility: ["model", "app"],
356
+ readOnly: true,
357
+ async run(netChat, args, meta) {
358
+ const models = await netChat.listModels(meta);
359
+ const defaultModel = netChat.settings.defaultModel;
360
+ // A setting the host no longer offers is reported as such, rather than silently as the default.
361
+ const stale = Boolean(defaultModel) && !models.some((model) => model.id === defaultModel);
362
+ const lines = models.length
363
+ ? [
364
+ `默认模型:${defaultModel ? (stale ? `${defaultModel}(宿主已不再提供这个模型,执行时会用宿主自己的默认)` : defaultModel) : "(未设置,用宿主自己的默认)"}`,
365
+ ...models.map((model) => `- ${model.label} id=${model.id}${model.id === defaultModel ? "(默认)" : ""}`),
366
+ ]
367
+ : ["这个宿主没有列出可用模型(或当前无权读取);执行时用宿主自己的默认模型。"];
368
+ return ok({ models, defaultModel, defaultModelStale: stale }, lines.join("\n"));
369
+ },
370
+ },
371
+
372
+ net_chat_list_sessions: {
373
+ description: "列出本机宿主里可以把任务放进去执行的已有会话(id、标题、是否在运行),可按项目筛选用 projectId。配合 net_chat_respond 的 execute + sessionId 使用;不传 sessionId 则新建会话。",
374
+ input: { projectId: s("只列这个项目下的会话(见 net_chat_list_projects);不填列全部"), },
375
+ visibility: ["model", "app"],
376
+ readOnly: true,
377
+ async run(netChat, args, meta) {
378
+ const projects = await netChat.listProjects(meta);
379
+ const project = args.projectId ? projects.find((entry) => entry.projectId === text(args.projectId, "projectId", 1, 200)) ?? null : null;
380
+ if (args.projectId && !project) throw new NetChatError("project_not_found", "That project is not available on this machine");
381
+ const sessions = await netChat.listSessions({ project, meta });
382
+ // The host's own description of each session is for handing back to the host, not for reading.
383
+ const shown = sessions.map(({ target, ...entry }) => entry);
384
+ const lines = shown.length
385
+ ? shown.map((entry) => `- ${entry.title || "(无标题)"} id=${entry.sessionId} ${entry.running ? "运行中" : "空闲"}`).join("\n")
386
+ : "这个宿主没有列出可用的会话(或当前无权读取);执行时将新建会话。";
387
+ return ok({ sessions: shown }, lines);
388
+ },
389
+ },
390
+
391
+ net_chat_update_profile: {
392
+ description:
393
+ "修改本机在局域网中的显示名称、角色(如“前端”“后端”)与 NetChat 设置。teamKey 是团队共享密钥:双方一致时相互标记为已验证。autoExecute 为 trusted 时,已验证发件人发来的任务会自动新建会话执行——改动前先征得用户同意。" +
394
+ " autoAnswer 为 on 时,发出去的任务里对方提的问题(带选项)由发任务的会话自己选最优项回答;feishuNotify 为 true 时,这类提问提醒到本机主人的飞书,由他回复作答(或在面板里选)。两者只能开一个。" +
395
+ " defaultModel 是执行任务时新建会话所用的模型 id(先 net_chat_list_models 查看),空字符串表示用宿主自己的默认。",
396
+ input: {
397
+ name: s("显示名称"),
398
+ role: s("角色标签"),
399
+ teamKey: s("团队共享密钥(空字符串表示关闭验证)"),
400
+ autoExecute: s("off 或 trusted"),
401
+ autoAnswer: s("off 或 on:对方提问由 Agent 自动选(on)还是等用户选(off)"),
402
+ feishuNotify: b("是否把等你选择的提问提醒到已绑定的飞书(与 autoAnswer=on 互斥)"),
403
+ defaultProject: s("收到任务时默认使用的项目 id"),
404
+ defaultModel: s("执行任务时新建会话所用的模型 id(见 net_chat_list_models);空字符串表示用宿主自己的默认"),
405
+ announce: b("是否在局域网中广播自己的存在"),
406
+ },
407
+ visibility: ["model", "app"],
408
+ readOnly: false,
409
+ async run(netChat, args) {
410
+ const touched = Object.keys(args).filter((key) => args[key] !== undefined);
411
+ const identity = await netChat.updateIdentity({ name: args.name, role: args.role });
412
+ const settings = await netChat.updateSettings({
413
+ teamKey: args.teamKey,
414
+ autoExecute: args.autoExecute,
415
+ autoAnswer: args.autoAnswer,
416
+ feishuNotify: args.feishuNotify,
417
+ defaultProject: args.defaultProject,
418
+ defaultModel: args.defaultModel,
419
+ announce: args.announce,
420
+ });
421
+ return ok({ identity, settings }, `已更新:${touched.join(", ") || "无改动"}。`);
422
+ },
423
+ },
424
+
425
+ net_chat_mark_read: {
426
+ description: "把任务标记为已读:任务本身,以及对方在它的往来里说过的消息。收件箱和发件箱里的任务都可以。",
427
+ input: { ids: idList, all: b("标记全部") },
428
+ visibility: ["app"],
429
+ readOnly: false,
430
+ async run(netChat, args) {
431
+ const ids = Array.isArray(args.ids) ? args.ids.filter((id) => typeof id === "string") : null;
432
+ return ok(await netChat.markRead({ ids, all: args.all === true }), "ok");
433
+ },
434
+ },
435
+
436
+ net_chat_poll: {
437
+ description: "等待 NetChat 状态变化(长轮询),返回 since 之后的事件。",
438
+ input: { since: i("上次看到的事件序号", 0) },
439
+ visibility: ["app"],
440
+ readOnly: true,
441
+ async run(netChat, args, meta, { pollMs = 20_000, signal } = {}) {
442
+ return ok(await netChat.waitEvents(args.since, pollMs, signal), "ok");
443
+ },
444
+ },
445
+
446
+ net_chat_request_grants: {
447
+ description: "请求用户授予 NetChat 扩展读取会话、创建会话与发送通知的权限。",
448
+ input: {},
449
+ visibility: ["app"],
450
+ readOnly: false,
451
+ async run(netChat) {
452
+ if (!netChat.can.requestGrants) throw new NetChatError("extension_required", "需要启用 NetChat 扩展后才能请求权限");
453
+ const result = await netChat.host.requestGrants();
454
+ const granted = Array.isArray(result?.granted) ? result.granted : [];
455
+ netChat.grantState = {
456
+ read: granted.includes("sessions.read") ? true : netChat.grantState.read,
457
+ write: granted.includes("sessions.write"),
458
+ notifications: granted.includes("notifications"),
459
+ };
460
+ await netChat.updateSettings({ grantPromptDone: true });
461
+ return ok({ granted, grants: netChat.grantState }, granted.length ? `已授予:${granted.join(", ")}` : "尚未授予权限。");
462
+ },
463
+ },
464
+
465
+ net_chat_open_session: {
466
+ description: "在界面中打开某个本地会话。",
467
+ input: { sessionId: s("会话 id") },
468
+ required: ["sessionId"],
469
+ visibility: ["app"],
470
+ readOnly: false,
471
+ async run(netChat, args) {
472
+ if (!netChat.can.openSession) throw new NetChatError("extension_required", "需要启用 NetChat 扩展后才能打开会话");
473
+ const sessionId = text(args.sessionId, "sessionId", 1, 200);
474
+ await netChat.host.openSession(sessionId);
475
+ return ok({ sessionId }, "ok");
476
+ },
477
+ },
478
+
479
+ net_chat_forget_agent: {
480
+ description: "把一个 Agent 从列表里移除。与它的往来记录保留;它下次上线时会重新出现在列表里。",
481
+ input: { agentId: s("Agent id") },
482
+ required: ["agentId"],
483
+ visibility: ["app"],
484
+ readOnly: false,
485
+ async run(netChat, args) {
486
+ const agentId = text(args.agentId, "agentId", 1, 80);
487
+ const { forgotten } = await netChat.forgetAgent(agentId);
488
+ return ok({ forgotten, hidden: netChat.hiddenAgents() }, "ok");
489
+ },
490
+ },
491
+
492
+ // ---- Feishu -----------------------------------------------------------------------------------
493
+
494
+ net_chat_feishu: {
495
+ description:
496
+ "查看飞书桥接的状态:是否已填写企业自建应用的 App ID / Secret、是否在监听单聊、已绑定的飞书用户(本机主人的飞书,用绑定码绑上的;开了“通知飞书”时,发出去的任务里有等你选择的提问会提醒到他,他在飞书里回复那条提醒即可作答;任务完成或失败时也会发一条 100 字内的简短通知),以及等待绑定的人及其绑定码。",
497
+ input: {},
498
+ visibility: ["model", "app"],
499
+ readOnly: true,
500
+ async run(netChat) {
501
+ const status = netChat.feishuStatus();
502
+ const bindings = status.bindingsList ?? [];
503
+ const pending = status.pendingList ?? [];
504
+ const state = {
505
+ off: "桥接没有运行",
506
+ stopped: "已停止",
507
+ connecting: "正在连接",
508
+ listening: "正在监听单聊消息",
509
+ reconnecting: "连接断开,正在重连",
510
+ unconfigured: "还没有填写飞书应用的 App ID / App Secret(net_chat_feishu_configure)",
511
+ }[status.state] ?? status.state;
512
+ const lines = [`飞书桥接:${state}${status.lastError ? `(${status.lastError})` : ""}`, `通知飞书:${status.feishuNotify ? "开" : "关"};自动回答:${status.autoAnswer === "on" ? "开" : "关"}`];
513
+ if (status.appId) lines.push(`应用:${status.appId}(Secret ${status.hasSecret ? "已保存" : "未填写"})`);
514
+ if (bindings.length) lines.push("", "已绑定:", ...bindings.map((entry) => `- ${entry.name} (${entry.openId})`));
515
+ else lines.push("", "还没有绑定任何飞书用户。");
516
+ if (pending.length) lines.push("", "等待绑定(绑定用下面列表里的码,不要用用户口头念的——念的常把 B/8、Z/2、S/5、G/6、U/V 听混):", ...pending.map((entry) => `- ${entry.name} 绑定码 ${entry.code} (${entry.openId})`));
517
+ return ok({ status }, lines.join("\n"));
518
+ },
519
+ },
520
+
521
+ net_chat_feishu_configure: {
522
+ description:
523
+ "换成自己企业的飞书应用凭据(开放平台 → 凭据与基础信息)。构建自带一个应用、装好即连,通常不必调用;调了就立刻用它重连;两者都传空字符串则关闭桥接。应用需开通 im:message.p2p_msg:readonly(接收单聊消息)、im:message:send_as_bot、im:resource,事件订阅选长连接并添加 im.message.receive_v1。",
524
+ input: { appId: s("cli_ 开头的 App ID"), appSecret: s("App Secret;空字符串表示清除") },
525
+ visibility: ["model", "app"],
526
+ readOnly: false,
527
+ async run(netChat, args) {
528
+ if (args.appId === undefined && args.appSecret === undefined) throw new NetChatError("invalid_input", "appId 和 appSecret 至少给一个");
529
+ const result = await netChat.feishuConfigure({
530
+ appId: args.appId === undefined ? undefined : text(args.appId, "appId", 1, 64),
531
+ appSecret: args.appSecret === undefined ? undefined : (args.appSecret === "" ? "" : text(args.appSecret, "appSecret", 8, 128)),
532
+ });
533
+ return ok({ ...result, status: netChat.feishuStatus() }, result.configured ? `已保存飞书应用 ${result.appId},桥接正在用它连接。` : `已保存 App ID ${result.appId},还缺 App Secret。`);
534
+ },
535
+ },
536
+
537
+ net_chat_feishu_bind: {
538
+ description:
539
+ "把一个飞书用户绑定到本机:他是这台机器的主人。流程是他先在飞书里给机器人发一句话,机器人回一个 6 位绑定码,这个码在 net_chat_feishu 的“等待绑定”里也看得到。code 里可以有别的东西:用户把机器人那条消息整条贴过来、带上前面的冒号或文字,都认得出来,服务会从里面找出码。绑定用 net_chat_feishu 列表里的码或用户贴来的原文,不要用用户口头念的(念的常把 B/8、Z/2、S/5、G/6、U/V 听混):先调 net_chat_feishu,把等待的人念给用户确认是哪位,再绑定。绑定码在绑定成功前不会变,code_not_found 是贴来的内容里没有等待中的码,不用让用户重新取码;ambiguous_code 是等待的人不止一个、内容里能对上不止一个码,把名单念给用户选。绑定本身只是登记;之后在设置里开“通知飞书”,发出去的任务里有等你选择的提问时会提醒到他,他在飞书里回复那条提醒即可作答(多个提问同时等着时回复对应那条;只有一个时直接回也行),答案经局域网送到执行方的会话。这是对外授权的操作,先把要绑的人念给用户确认。",
540
+ input: { code: s("6 位绑定码;也可以直接贴机器人回复的那条消息,服务会从里面找出码"), openId: s("(面板用)待绑定列表里的 open_id,与 code 二选一"), name: s("显示名字,留空则用飞书里的名字") },
541
+ visibility: ["model", "app"],
542
+ readOnly: false,
543
+ async run(netChat, args) {
544
+ // Long enough for the whole message the bot sends (about 150 characters): the code is found
545
+ // inside it, so a paste is taken as it comes.
546
+ const code = args.code === undefined || args.code === null || args.code === "" ? "" : text(args.code, "code", 4, 1000);
547
+ const openId = args.openId === undefined || args.openId === null || args.openId === "" ? "" : text(args.openId, "openId", 3, 80);
548
+ if (!code && !openId) throw new NetChatError("invalid_input", "code 和 openId 至少给一个");
549
+ const entry = await netChat.feishuBind({ code, openId, name: args.name === undefined ? "" : clip(String(args.name), C.MAX_NAME_CHARS) });
550
+ return ok({ binding: entry }, `已绑定飞书用户 ${entry.name}(${entry.openId})到本机。`);
551
+ },
552
+ },
553
+
554
+ net_chat_feishu_unbind: {
555
+ description: "解除一个飞书用户的绑定;之后不再向他发送提醒。",
556
+ input: { openId: s("飞书用户的 open_id") },
557
+ required: ["openId"],
558
+ visibility: ["model", "app"],
559
+ readOnly: false,
560
+ async run(netChat, args) {
561
+ const { unbound } = await netChat.feishuUnbind(text(args.openId, "openId", 3, 80));
562
+ return ok({ unbound }, `已解除绑定 ${unbound}。`);
563
+ },
564
+ },
565
+
566
+ net_chat_feishu_forget: {
567
+ description: "把一个飞书用户从“等待确认绑定”列表里移除,不绑定。",
568
+ input: { openId: s("飞书用户的 open_id") },
569
+ required: ["openId"],
570
+ visibility: ["model", "app"],
571
+ readOnly: false,
572
+ async run(netChat, args) {
573
+ const { forgotten } = await netChat.feishuForgetPending(text(args.openId, "openId", 3, 80));
574
+ return ok({ forgotten }, `已移除 ${forgotten}。`);
575
+ },
576
+ },
577
+
578
+ net_chat_send_feishu: {
579
+ description:
580
+ "以机器人身份给一个已绑定的飞书用户发单聊消息:纯文本、markdown,或一个本地文件;也可以把当前会话最近的记录(attachSession)作为文本带上。这是对外发送的操作:发送前把收件人和内容念给用户确认。user 可以是 open_id 或已绑定的名字。",
581
+ input: {
582
+ user: s("已绑定飞书用户的 open_id 或名字"),
583
+ text: s("纯文本内容"),
584
+ markdown: s("markdown 内容(与 text 二选一)"),
585
+ file: s("本地文件的绝对路径"),
586
+ attachSession: b("是否把当前会话最近的记录作为文本附在消息里"),
587
+ sessionId: s("要附带的会话 id;默认使用当前会话"),
588
+ sessionMessages: i("附带最近多少条消息", 1, 200),
589
+ },
590
+ required: ["user"],
591
+ visibility: ["model", "app"],
592
+ readOnly: false,
593
+ async run(netChat, args, meta) {
594
+ const binding = netChat.feishuBook().resolve(args.user);
595
+ const parts = [];
596
+ if (args.text !== undefined) parts.push(text(args.text, "text", 1, C.MAX_BODY_CHARS));
597
+ if (args.markdown !== undefined) parts.push(text(args.markdown, "markdown", 1, C.MAX_BODY_CHARS));
598
+ if (args.attachSession === true) {
599
+ const sessionId = args.sessionId ?? (await netChat.currentSession(meta))?.sessionId;
600
+ if (!sessionId) throw new NetChatError("session_required", "没有可附带的会话:请提供 sessionId,或不要设置 attachSession");
601
+ const transcript = await netChat.readTranscript(sessionId, { meta, maxMessages: int(args.sessionMessages, 1, 200, 20), title: (await netChat.sessionInfo(sessionId, meta)).title });
602
+ parts.push(`会话记录(${transcript.title || "无标题"},最近 ${transcript.messages.length} 条):\n\n${transcript.messages.map((entry) => `[${entry.role === "user" ? "用户" : "助手"}] ${entry.text}`).join("\n\n")}`);
603
+ }
604
+ if (!parts.length && !args.file) throw new NetChatError("invalid_input", "text、markdown、attachSession、file 至少给一个");
605
+ const body = parts.join("\n\n---\n\n");
606
+ let sent;
607
+ if (args.file) {
608
+ sent = await netChat.feishuSend(binding.openId, { file: text(args.file, "file", 1, 1024) });
609
+ } else {
610
+ sent = await netChat.feishuSend(binding.openId, args.markdown !== undefined || args.attachSession === true ? { markdown: body } : { text: body });
611
+ }
612
+ return ok({ sent, to: binding }, `已发送到飞书用户 ${binding.name}${sent.messageId ? `(消息 ${sent.messageId})` : ""}。`);
613
+ },
614
+ },
615
+ };
616
+
617
+ function text(value, name, min, max) {
618
+ if (typeof value !== "string" || value.trim().length < min || value.length > max) {
619
+ throw new NetChatError("invalid_input", `${name} 必须是 ${min}-${max} 个字符的文本`);
620
+ }
621
+ return value;
622
+ }
623
+
624
+ function optionalText(value, max) {
625
+ if (value === undefined || value === null || value === "") return null;
626
+ return text(value, "threadId", 1, max);
627
+ }
628
+
629
+ function enumValue(value, name, allowed) {
630
+ if (!allowed.includes(value)) throw new NetChatError("invalid_input", `${name} 必须是 ${allowed.join(" / ")}`);
631
+ return value;
632
+ }
633
+
634
+ function optionalEnum(value, name, allowed, fallback) {
635
+ if (value === undefined || value === null || value === "") return fallback;
636
+ return enumValue(value, name, allowed);
637
+ }
638
+
639
+ function int(value, min, max, fallback) {
640
+ if (value === undefined || value === null || value === "") return fallback;
641
+ if (!Number.isInteger(value) || value < min || value > max) throw new NetChatError("invalid_input", `取值必须是 ${min}-${max} 的整数`);
642
+ return value;
643
+ }
644
+
645
+ /** The name a task's project goes by, as the executor last confirmed it: "" when it has none. */
646
+ const projectNameOf = (item) => String((item.projectName ?? item.payload?.projectName) ?? "");
647
+
648
+ /** The name as a lead-in to a task's line, so tasks of one project are told from another's at a glance. */
649
+ const projectTag = (item) => {
650
+ const name = projectNameOf(item);
651
+ return name ? `[${name}] ` : "";
652
+ };
653
+
654
+ /** A sent task that the other side has finished: done, declined, or failed on their side. */
655
+ const SENT_CLOSED_STATUSES = new Set(["done", "declined", "failed"]);
656
+
657
+ /**
658
+ * Every task that still waits on someone, with the local session a panel can jump to.
659
+ * Inbox tasks are this machine's work (the session the host started for them); sent tasks
660
+ * point back at the session they were sent from, which is where questions about them go.
661
+ * Tasks of hidden parties and pre-0.3.4 Feishu tasks are left out. The party is looked up
662
+ * by direction rather than through `visibleItems`, whose `from ?? to` order names this
663
+ * machine for a sent task and so would keep a hidden party's.
664
+ */
665
+ export function openTasks(netChat) {
666
+ const hidden = netChat.hidden instanceof Set ? netChat.hidden : new Set(netChat.hiddenAgents());
667
+ const shown = (item, party) => item.via !== "feishu" && !hidden.has(party?.id ?? "");
668
+ const tasks = [];
669
+ for (const item of netChat.inbox) {
670
+ if (item.kind !== "task" || !OPEN_STATUSES.has(item.status) || !shown(item, item.from)) continue;
671
+ const questions = openQuestions(threadOf(item)).length;
672
+ tasks.push({
673
+ id: item.id,
674
+ direction: "in",
675
+ state: item.status,
676
+ title: labelOf(item),
677
+ peer: item.from.name,
678
+ sessionId: item.sessionId ?? null,
679
+ questions,
680
+ updatedAt: item.receivedAt ?? item.ts ?? null,
681
+ });
682
+ }
683
+ for (const item of netChat.outbox) {
684
+ if (item.kind !== "task" || SENT_CLOSED_STATUSES.has(item.status) || !shown(item, item.to)) continue;
685
+ const questions = openQuestions(threadOf(item)).length;
686
+ tasks.push({
687
+ id: item.id,
688
+ direction: "out",
689
+ state: item.status,
690
+ title: labelOf(item),
691
+ peer: item.to.name,
692
+ sessionId: item.originSessionId ?? null,
693
+ questions,
694
+ updatedAt: item.receipts.at(-1)?.ts ?? item.ts ?? null,
695
+ });
696
+ }
697
+ return tasks;
698
+ }
699
+
700
+ function ago(ms) {
701
+ if (ms === null || ms === undefined) return "从未上线";
702
+ if (ms < 60_000) return `${Math.max(1, Math.round(ms / 1000))} 秒前`;
703
+ if (ms < 3_600_000) return `${Math.round(ms / 60_000)} 分钟前`;
704
+ return `${Math.round(ms / 3_600_000)} 小时前`;
705
+ }
706
+
707
+ function labelOf(item) {
708
+ return `「${item.payload.title ?? ""}」`;
709
+ }
710
+
711
+ /** The thread of a task in list lines: how many messages, and whether a question is still waiting for an answer. */
712
+ function threadSummary(item) {
713
+ const thread = threadOf(item);
714
+ if (!thread.length) return "";
715
+ const open = openQuestions(thread).length;
716
+ return `;线程 ${thread.length} 条消息${open ? `,其中 ${open} 个提问待回答` : ""}`;
717
+ }
718
+
719
+ /** The thread of a task as stored on either side; older storage kept it as `replies`. */
720
+ function threadOf(item) {
721
+ return Array.isArray(item.thread) ? item.thread : (item.replies ?? []).map((entry, index) => ({ id: `legacy_${index}`, text: entry.text, from: entry.to ? "me" : "peer" }));
722
+ }
723
+
724
+ /** Questions offered with options that nobody has answered yet. */
725
+ function openQuestions(thread) {
726
+ return thread.filter((entry) => entry.options?.length && !entry.answer);
727
+ }
728
+
729
+ /** The thread as the model reads it: who said what, which messages were questions, and what was chosen. */
730
+ function threadLines(item) {
731
+ const thread = threadOf(item);
732
+ if (!thread.length) return [];
733
+ const lines = ["", "任务线程(按时间顺序):"];
734
+ for (const entry of thread) {
735
+ const who = entry.from === "me" ? "我" : `对方(${entry.fromName ?? item.from?.name ?? item.to?.name ?? ""})`;
736
+ lines.push("", `[${who} ${entry.ts}] ${entry.text}`);
737
+ if (entry.options?.length) {
738
+ lines.push(` 可选项:${entry.options.map((option, index) => `${index + 1}. ${option}`).join(";")}`);
739
+ lines.push(entry.answer ? ` 已回答:${entry.answer.text}` : " 尚未回答");
740
+ }
741
+ if (entry.delivery === "failed") lines.push(` (未能送达:${entry.error})`);
742
+ }
743
+ return lines;
744
+ }
745
+
746
+ /** A sent item with a window of its transcript, for the detail view. */
747
+ function sentDetail(source, id, args) {
748
+ const item = source.find((entry) => entry.id === id);
749
+ if (!item) throw new NetChatError("not_found", "找不到这条记录");
750
+ const messages = Array.isArray(item.payload?.session?.messages) ? item.payload.session.messages : [];
751
+ const start = Math.max(0, Math.min(args.offset ?? 0, messages.length));
752
+ const count = Math.max(1, Math.min(args.limit ?? 50, 200));
753
+ const detail = { ...item, payload: { ...item.payload } };
754
+ if (item.payload?.session) {
755
+ const { messages: _dropped, ...rest } = item.payload.session;
756
+ detail.payload.session = { ...rest, offset: start, total: messages.length, messages: messages.slice(start, start + count) };
757
+ }
758
+ return detail;
759
+ }
760
+
761
+ function describeDetail(item) {
762
+ const who = item.from ? `来自 ${item.from.name}` : `发给 ${item.to.name}`;
763
+ const lines = [`任务 ${labelOf(item)} ${who},状态 ${item.status}。`];
764
+ if (item.payload.body) lines.push("", "需求说明:", item.payload.body);
765
+ if (item.payload.workspaceHint) lines.push("", `相关项目:${item.payload.workspaceHint}`);
766
+ const projectName = projectNameOf(item);
767
+ if (projectName) lines.push("", `所属项目:${projectName}`);
768
+ if (item.error) lines.push("", `错误:${item.error}`);
769
+ if (item.result) lines.push("", `结果:${item.result}`);
770
+ lines.push(...threadLines(item));
771
+ for (const entry of item.receipts ?? []) lines.push("", `回执 ${entry.status}${entry.detail ? `:${entry.detail}` : ""}`);
772
+ for (const entry of item.payload.session?.messages ?? []) lines.push("", `[${entry.role === "user" ? "用户" : "助手"}] ${entry.text}`);
773
+ return lines.join("\n");
774
+ }
775
+
776
+
777
+ /** Tool table in MCP shape; `visibility` is ZCode's `_meta.ui.visibility`. */
778
+ export function toolDefinitions() {
779
+ return Object.entries(TOOLS).map(([name, tool]) => ({
780
+ name,
781
+ description: tool.description,
782
+ inputSchema: {
783
+ type: "object",
784
+ properties: tool.input,
785
+ ...(tool.required ? { required: tool.required } : {}),
786
+ additionalProperties: false,
787
+ },
788
+ annotations: { readOnlyHint: tool.readOnly },
789
+ visibility: tool.visibility,
790
+ }));
791
+ }
792
+
793
+ export function createOps(netChat) {
794
+ return {
795
+ async call(name, args = {}, meta = {}, options = {}) {
796
+ const tool = TOOLS[name];
797
+ if (!tool) throw new NetChatError("unknown_op", `Unknown operation: ${name}`);
798
+ if (typeof args !== "object" || args === null || Array.isArray(args)) throw new NetChatError("invalid_input", "arguments must be an object");
799
+ const result = await tool.run(netChat, args, meta ?? {}, options);
800
+ return result ?? ok({}, "ok");
801
+ },
802
+ };
803
+ }