dsh-supermesh 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4451 @@
1
+ import { a as project, c as shell, d as singlet, f as setting, g as db, h as channelProxyEnvironment, i as archive, l as inbox, m as DSH_PLUGIN_HOME, n as server, o as worktree, p as defineService, r as worker$1, s as devops, t as channel, u as session } from "./channel-C_93wtiQ.js";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import process from "node:process";
6
+ import { defineTool } from "@deepseek-ai/dsh-tools";
7
+ import { createHash, randomUUID } from "node:crypto";
8
+ import { execFile } from "node:child_process";
9
+ import { createRouteDispatcher } from "@deepseek-ai/dsh-http-proxy";
10
+ import { mkdir, readFile, rename as rename$1, writeFile } from "node:fs/promises";
11
+ import { fetch } from "undici";
12
+ import { Cron } from "croner";
13
+ // src/ai/_shared/prompt-file.ts
14
+ let cached;
15
+ /**
16
+ * 从当前模块往上找 `package.json` 得到包根目录。
17
+ * 不能写死 `../..`:源码在 `src/ai/_shared/`、打包后在 `dist/`,层级不同。
18
+ * 与官方 `infra/paths.ts` 的 `packageRoot` 同一策略。
19
+ */
20
+ function packageRoot() {
21
+ if (cached) return cached;
22
+ let directory = dirname(fileURLToPath(import.meta.url));
23
+ for (let depth = 0; depth < 6; depth++) {
24
+ const manifest = join(directory, "package.json");
25
+ if (existsSync(manifest)) try {
26
+ if (JSON.parse(readFileSync(manifest, "utf8")).name === "dsh-supermesh") return cached = directory;
27
+ } catch {}
28
+ const parent = dirname(directory);
29
+ if (parent === directory) break;
30
+ directory = parent;
31
+ }
32
+ throw new Error("dsh-supermesh package root not found");
33
+ }
34
+ function packaged(name) {
35
+ const path = join(packageRoot(), "assets", "prompts", `${name}.md`);
36
+ let text;
37
+ try {
38
+ text = readFileSync(path, "utf8").replaceAll("\r\n", "\n");
39
+ } catch (error) {
40
+ throw error.code === "ENOENT" ? new Error(`Missing packaged prompt: ${path}`, { cause: error }) : error;
41
+ }
42
+ if (!text.trim()) throw new Error(`Empty packaged prompt: ${path}`);
43
+ return text;
44
+ }
45
+ const cache = /* @__PURE__ */ new Map();
46
+ /**
47
+ * 读 `assets/prompts/<name>.md`,段内换行合并为空格、段间只留单换行。
48
+ * 与官方 `skill-files.ts` 的 `promptFile` 一致:让模型按段落读,不被手写换行干扰。
49
+ */
50
+ function promptFile(name) {
51
+ const hit = cache.get(name);
52
+ if (hit !== void 0) return hit;
53
+ const text = packaged(name).trim().split(/\n(?:[ \t]*\n)+/).map((paragraph) => paragraph.split("\n").map((line) => line.trim()).join(" ")).join("\n");
54
+ cache.set(name, text);
55
+ return text;
56
+ }
57
+ // src/ai/_shared/compose-prompt.ts
58
+ /** 所有角色都读:职责划分 + 话题订阅 + 回复规则。 */
59
+ function common() {
60
+ return [
61
+ promptFile("shared"),
62
+ promptFile("subscriptions"),
63
+ promptFile("replies")
64
+ ];
65
+ }
66
+ /** 团队可改的三个段落:沟通、任务范围、交付要求(含合并与署名规则)。 */
67
+ function teamSections() {
68
+ return [
69
+ promptFile("team/communication"),
70
+ promptFile("team/scope"),
71
+ promptFile("team/delivery")
72
+ ];
73
+ }
74
+ /** 只有编排类角色读:渠道 CLI 用法。 */
75
+ function channelNotes() {
76
+ return [promptFile("cli")];
77
+ }
78
+ /**
79
+ * 组装一个角色的系统提示词,顺序对齐官方 `promptParts`:
80
+ * 共用段 → 角色段 → 团队段落 → 执行细则 → 渠道说明。
81
+ */
82
+ function composePrompt(role) {
83
+ return [
84
+ ...common(),
85
+ promptFile(role),
86
+ ...teamSections(),
87
+ role === "worker" ? promptFile("work") : "",
88
+ ...channelNotes()
89
+ ].filter(Boolean).join("\n\n");
90
+ }
91
+ // src/ai/_shared/plugins/index.ts
92
+ const IS_WINDOWS = process.platform === "win32";
93
+ const agentInstructions = {
94
+ id: "agent-instructions",
95
+ name: "@deepseek-ai/dsh-agent-instructions",
96
+ config: { maxBytes: 65536 }
97
+ };
98
+ const timeContext = {
99
+ id: "time-context",
100
+ name: "@deepseek-ai/dsh-time-context"
101
+ };
102
+ const toolBash = {
103
+ id: "tool-bash",
104
+ name: "@deepseek-ai/dsh-tool-bash",
105
+ disabled: IS_WINDOWS
106
+ };
107
+ const toolPwsh = {
108
+ id: "tool-pwsh",
109
+ name: "@deepseek-ai/dsh-tool-pwsh",
110
+ disabled: !IS_WINDOWS
111
+ };
112
+ const toolFs = {
113
+ id: "tool-fs",
114
+ name: "@deepseek-ai/dsh-tool-fs",
115
+ config: { applyPatch: false }
116
+ };
117
+ const toolFsSearch = {
118
+ id: "tool-fs-search",
119
+ name: "@deepseek-ai/dsh-tool-fs-search",
120
+ config: { sampleOverCapGlobResults: false }
121
+ };
122
+ const toolJobs = {
123
+ id: "tool-jobs",
124
+ name: "@deepseek-ai/dsh-tool-jobs"
125
+ };
126
+ const skillFilesystem = {
127
+ id: "skill-filesystem",
128
+ name: "@deepseek-ai/dsh-skill-filesystem"
129
+ };
130
+ const toolSkill = {
131
+ id: "tool-skill",
132
+ name: "@deepseek-ai/dsh-tool-skill"
133
+ };
134
+ const commandGoal = {
135
+ id: "command-goal",
136
+ name: "@deepseek-ai/dsh-command-goal"
137
+ };
138
+ const compaction = {
139
+ id: "compaction",
140
+ name: "cordis:group",
141
+ group: true,
142
+ isolate: {
143
+ compaction: true,
144
+ toolResultPruner: true
145
+ },
146
+ config: [
147
+ {
148
+ id: "compaction-basic",
149
+ name: "@deepseek-ai/dsh-compaction-basic"
150
+ },
151
+ {
152
+ id: "command-compact",
153
+ name: "@deepseek-ai/dsh-command-compact"
154
+ },
155
+ {
156
+ id: "tool-result-pruner",
157
+ name: "@deepseek-ai/dsh-compaction-tool-result-pruner",
158
+ config: {
159
+ thresholdChars: 8192,
160
+ headChars: 4096,
161
+ tailChars: 1024
162
+ }
163
+ }
164
+ ]
165
+ };
166
+ const delegation = {
167
+ id: "delegation",
168
+ name: "cordis:group",
169
+ group: true,
170
+ isolate: { workflowEngine: true },
171
+ config: [
172
+ {
173
+ id: "tool-subagent-control",
174
+ name: "@deepseek-ai/dsh-tool-subagent-control"
175
+ },
176
+ {
177
+ id: "tool-subagent",
178
+ name: "@deepseek-ai/dsh-tool-subagent",
179
+ config: {
180
+ provider: "spawn",
181
+ toolName: "subagent",
182
+ modelSelection: true,
183
+ modelDiscovery: true
184
+ }
185
+ },
186
+ {
187
+ id: "tool-subagent-fork",
188
+ name: "@deepseek-ai/dsh-tool-subagent",
189
+ config: {
190
+ provider: "fork",
191
+ toolName: "subagent_fork"
192
+ }
193
+ },
194
+ {
195
+ id: "workflow-ptc",
196
+ name: "@deepseek-ai/dsh-workflow-ptc",
197
+ disabled: true,
198
+ config: { provider: "spawn" }
199
+ },
200
+ {
201
+ id: "tool-workflow",
202
+ name: "@deepseek-ai/dsh-tool-workflow",
203
+ disabled: true
204
+ }
205
+ ]
206
+ };
207
+ const toolTodo = {
208
+ id: "tool-todo",
209
+ name: "@deepseek-ai/dsh-tool-todo",
210
+ config: { allowParallelInProgress: true }
211
+ };
212
+ const toolWeb = {
213
+ id: "tool-web",
214
+ name: "@deepseek-ai/dsh-tool-web",
215
+ config: {
216
+ fetch: true,
217
+ searchTimeoutMs: 6e4
218
+ }
219
+ };
220
+ const toolExecutorPtc = {
221
+ id: "tool-executor-ptc",
222
+ name: "@deepseek-ai/dsh-tool-executor-ptc"
223
+ };
224
+ const toolPresent = {
225
+ id: "present",
226
+ name: "@deepseek-ai/dsh-tool-present"
227
+ };
228
+ // src/ai/_shared/tools/channel.utils.ts
229
+ const observed = /* @__PURE__ */ new WeakMap();
230
+ function owner(exec) {
231
+ return exec.agent?.session;
232
+ }
233
+ /** 同一条触发 + 同一正文只入队一次,与官方 `key('reply', triggerId, text)` 同义。 */
234
+ function replyKey(triggerId, body) {
235
+ return `reply:${createHash("sha256").update(JSON.stringify([triggerId, body])).digest("hex").slice(0, 32)}`;
236
+ }
237
+ async function isThreadId(value) {
238
+ if (!/^[\w-]+:[\w./-]+$/.test(value)) return false;
239
+ return Boolean(await db.thread.findById(value));
240
+ }
241
+ function observe(exec, threadId, version) {
242
+ const holder = owner(exec);
243
+ if (!holder) return;
244
+ let byTarget = observed.get(holder);
245
+ if (!byTarget) {
246
+ byTarget = /* @__PURE__ */ new Map();
247
+ observed.set(holder, byTarget);
248
+ }
249
+ byTarget.set(threadId, { version });
250
+ }
251
+ /** 与官方 `requirePresent` 同义:没读过就抛出带错误码的拒绝。 */
252
+ function requireObserved(exec, threadId, verb) {
253
+ const holder = owner(exec);
254
+ const prior = holder ? observed.get(holder)?.get(threadId) : void 0;
255
+ if (!prior) {
256
+ const error = /* @__PURE__ */ new Error(`${verb} 需要先读过这个话题:调用 read_channel,resource 用 thread/<id> 或 trigger/<triggerId>`);
257
+ error.name = "ChannelNotObserved";
258
+ throw error;
259
+ }
260
+ return prior;
261
+ }
262
+ /** 话题的最新消息 id,用于判定「读的是哪一版」。 */
263
+ async function latestVersion(threadId) {
264
+ return (await db.trigger.listRecent(1e3)).filter((item) => item.threadId === threadId).sort((a, b) => b.at.localeCompare(a.at))[0]?.id ?? "empty";
265
+ }
266
+ /** 记下「这个会话读过这个话题」,并把读到的那一版留下来。 */
267
+ async function markThread(exec, threadId) {
268
+ observe(exec, threadId, await latestVersion(threadId));
269
+ }
270
+ // src/channel/_shared/error.ts
271
+ var ChannelError = class extends Error {
272
+ code;
273
+ retryAfterSeconds;
274
+ constructor(code, retryAfterSeconds) {
275
+ super(code);
276
+ this.code = code;
277
+ this.retryAfterSeconds = retryAfterSeconds;
278
+ }
279
+ };
280
+ // src/channel/_shared/primitives.ts
281
+ function record(value) {
282
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ChannelError("invalid_response");
283
+ return value;
284
+ }
285
+ function array(value) {
286
+ if (!Array.isArray(value)) throw new ChannelError("invalid_response");
287
+ return value;
288
+ }
289
+ function text(value) {
290
+ if (typeof value !== "string" || !value) throw new ChannelError("invalid_response");
291
+ return value;
292
+ }
293
+ function number(value) {
294
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new ChannelError("invalid_response");
295
+ return value;
296
+ }
297
+ function identity(value) {
298
+ if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) return String(value);
299
+ if (typeof value === "string" && value) return value;
300
+ throw new ChannelError("invalid_response");
301
+ }
302
+ function timestamp(value) {
303
+ const date = new Date(text(value));
304
+ if (!Number.isFinite(date.getTime())) throw new ChannelError("invalid_response");
305
+ return date.toISOString();
306
+ }
307
+ function now() {
308
+ return (/* @__PURE__ */ new Date()).toISOString();
309
+ }
310
+ function digest(value) {
311
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
312
+ }
313
+ function escapeRegex(value) {
314
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
315
+ }
316
+ /** 游标回退 5 秒,靠确定性 id 去重,避免远程迟到的事件被漏掉(官方 cursorAt)。 */
317
+ function cursorAt(started) {
318
+ return (/* @__PURE__ */ new Date(Date.parse(started) - 5e3)).toISOString();
319
+ }
320
+ // src/channel/_shared/thread.ts
321
+ async function recordThread(input) {
322
+ const existing = await db.thread.findByRef(input.channel, input.refId);
323
+ return db.thread.record({
324
+ id: existing?.id ?? `${input.channel}:${input.refId}`,
325
+ channelId: input.channel,
326
+ refId: input.refId,
327
+ kind: input.kind,
328
+ title: input.title,
329
+ url: input.url,
330
+ createdAt: input.createdAt,
331
+ updatedAt: input.updatedAt,
332
+ projectId: null,
333
+ triage: "pending",
334
+ triagedAt: null
335
+ });
336
+ }
337
+ /** 结单话题;合并时顺带关闭同一项目下已结单票关联的 issue。 */
338
+ async function closeThread(input) {
339
+ const ended = await db.ticket.closeThread(input.thread.id, input.outcome, input.at, input.branch);
340
+ if (input.outcome !== "merged" || !ended.length) return;
341
+ for (const source of await db.thread.listByChannel(input.channel)) {
342
+ if (source.kind !== "issue" || source.projectId !== input.projectId || !source.url) continue;
343
+ if (!(await db.ticketThread.listTicketIds(source.id)).some((id) => ended.includes(id))) continue;
344
+ await input.closeIssue(source.url).catch(() => void 0);
345
+ }
346
+ }
347
+ // src/channel/github/runner.ts
348
+ var GhError = class extends ChannelError {};
349
+ var ExecFileGhRunner = class {
350
+ async request(request) {
351
+ if (request.signal?.aborted) throw new GhError("interrupted");
352
+ const token = await channel.resolveCredential("github");
353
+ if (request.signal?.aborted) throw new GhError("interrupted");
354
+ if (!token?.trim()) throw new GhError("not_logged_in");
355
+ const env = await channelProxyEnvironment(new URL(`https://${request.site}`), shell.commandEnvironment());
356
+ for (const key of Object.keys(env)) if ([
357
+ "GH_TOKEN",
358
+ "GITHUB_TOKEN",
359
+ "GH_ENTERPRISE_TOKEN",
360
+ "GITHUB_ENTERPRISE_TOKEN"
361
+ ].includes(key.toUpperCase())) delete env[key];
362
+ env.GH_TOKEN = token;
363
+ const args = [
364
+ "api",
365
+ "--hostname",
366
+ request.site,
367
+ "--method",
368
+ request.method,
369
+ "--include",
370
+ request.path
371
+ ];
372
+ for (const [key, value] of Object.entries(request.headers ?? {})) args.push("-H", `${key}: ${value}`);
373
+ if (request.body) args.push("--input", "-");
374
+ return new Promise((resolve, reject) => {
375
+ const child = execFile("gh", args, {
376
+ signal: request.signal,
377
+ timeout: 3e4,
378
+ maxBuffer: 16777216,
379
+ env
380
+ }, (error, stdout, stderr) => {
381
+ const response = stdout.replace(/\r\n/g, "\n");
382
+ const status = Number(/^HTTP\/\S+ (\d+)/m.exec(response)?.[1]);
383
+ const retryAfter = /^retry-after: (\d+)/im.exec(response)?.[1];
384
+ if (status === 304) {
385
+ resolve({ notModified: true });
386
+ return;
387
+ }
388
+ if (error) {
389
+ const code = error.code;
390
+ reject(new GhError(code === "ENOENT" ? "gh_missing" : status === 401 || /gh auth login|not logged/i.test(stderr) ? "not_logged_in" : status === 429 || /rate limit/i.test(stderr) ? "rate_limited" : status === 403 ? "forbidden" : status === 404 ? "not_found" : status >= 400 && status < 500 ? "remote_rejected" : code === "ABORT_ERR" ? "interrupted" : "transport_unknown", retryAfter ? Number(retryAfter) : void 0));
391
+ return;
392
+ }
393
+ try {
394
+ const separator = response.indexOf("\n\n");
395
+ if (separator < 0) throw new GhError("invalid_response");
396
+ const body = response.slice(separator + 2).trim();
397
+ resolve(body ? JSON.parse(body) : null);
398
+ } catch {
399
+ reject(new GhError("invalid_response"));
400
+ }
401
+ });
402
+ if (request.body) child.stdin.end(JSON.stringify(request.body));
403
+ });
404
+ }
405
+ };
406
+ // src/channel/_shared/answers.ts
407
+ /** 逐行产出回答候选,跳过围栏代码块里的内容。 */
408
+ function* answerLines(body) {
409
+ let fenced = false;
410
+ for (const line of body.split(/\r?\n/)) {
411
+ if (/^\s*~{3}|^\s*```/.test(line)) {
412
+ fenced = !fenced;
413
+ continue;
414
+ }
415
+ if (fenced) continue;
416
+ yield line;
417
+ }
418
+ }
419
+ // src/channel/_shared/ci.ts
420
+ /** 分支 CI 变更落成 ciWatch、ci 话题、触发与项目通知。silent 为真时首轮不打扰。 */
421
+ async function notifyBranchCi(input) {
422
+ const { row: watch } = await db.ciWatch.recordRevision({
423
+ id: `${input.channel}:${input.ref}`,
424
+ channelId: input.channel,
425
+ kind: "branch",
426
+ ref: input.ref,
427
+ fingerprint: input.fingerprint,
428
+ head: input.head,
429
+ updatedAt: now()
430
+ });
431
+ if (input.silent && watch.revision === 0) return;
432
+ const threadId = `${input.channel}:${input.ref}`;
433
+ await db.thread.record({
434
+ id: threadId,
435
+ channelId: input.channel,
436
+ refId: input.ref,
437
+ kind: "ci",
438
+ title: input.title,
439
+ url: null,
440
+ projectId: input.projectId,
441
+ triage: "claimed",
442
+ triagedAt: now(),
443
+ createdAt: now(),
444
+ updatedAt: now()
445
+ });
446
+ const triggerId = `${watch.id}:revision:${watch.revision}`;
447
+ await db.trigger.ingest({
448
+ id: triggerId,
449
+ channelId: input.channel,
450
+ threadId,
451
+ kind: "ci",
452
+ actorName: null,
453
+ human: 0,
454
+ mentioned: 0,
455
+ text: input.message,
456
+ url: input.url,
457
+ at: now(),
458
+ ref: input.head
459
+ });
460
+ await db.inbox.enqueue({
461
+ id: `${triggerId}:project:${input.projectId}`,
462
+ type: "project",
463
+ origin: "system",
464
+ kind: "notice",
465
+ projectId: input.projectId,
466
+ triggerId,
467
+ threadId,
468
+ title: input.message,
469
+ message: input.message
470
+ });
471
+ }
472
+ // src/channel/github/service/resource.ts
473
+ const resource$1 = defineService({
474
+ of(remoteUrl) {
475
+ if (!remoteUrl) return null;
476
+ const ssh = /^git@github\.com:([\w.-]+\/[\w.-]+?)(?:\.git)?$/i.exec(remoteUrl);
477
+ if (ssh) return ssh[1].toLowerCase();
478
+ try {
479
+ const url = new URL(remoteUrl);
480
+ if (!["https:", "ssh:"].includes(url.protocol) || url.hostname !== "github.com" || url.password || url.search || url.hash || url.port) return null;
481
+ return /^\/([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/i.exec(url.pathname)?.[1]?.toLowerCase() ?? null;
482
+ } catch {
483
+ return null;
484
+ }
485
+ },
486
+ parse(value) {
487
+ const short = /^github:([^/:]+\/[^/:]+):(issue|pull):([1-9]\d*)$/.exec(value);
488
+ if (short) return {
489
+ repository: short[1].toLowerCase(),
490
+ kind: short[2],
491
+ number: Number(short[3])
492
+ };
493
+ let url;
494
+ try {
495
+ url = new URL(value);
496
+ } catch {
497
+ throw new GhError("invalid_resource");
498
+ }
499
+ const match = /^\/([\w.-]+\/[\w.-]+)\/(issues|pull)\/([1-9]\d*)\/?$/i.exec(url.pathname);
500
+ if (url.protocol !== "https:" || url.hostname !== "github.com" || url.username || url.password || url.port || !match) throw new GhError("invalid_resource");
501
+ return {
502
+ repository: match[1].toLowerCase(),
503
+ kind: match[2] === "pull" ? "pull" : "issue",
504
+ number: Number(match[3])
505
+ };
506
+ },
507
+ validate(row, target) {
508
+ const url = resource$1.parse(text(row.html_url));
509
+ if (number(row.number) !== target.number || url.repository !== target.repository || url.kind !== target.kind) throw new GhError("source_repository_mismatch");
510
+ },
511
+ item(row, kind) {
512
+ return {
513
+ id: identity(row.id),
514
+ kind,
515
+ actor: text(record(row.user).login),
516
+ body: typeof row.body === "string" ? row.body : typeof row.state === "string" ? row.state : "",
517
+ url: text(row.html_url),
518
+ createdAt: timestamp(row.created_at ?? row.submitted_at),
519
+ updatedAt: timestamp(row.updated_at ?? row.submitted_at ?? row.created_at)
520
+ };
521
+ }
522
+ });
523
+ // src/channel/_shared/admission.ts
524
+ function acceptsChannelTrigger(input) {
525
+ if (!input.human || input.historical && !input.subscribed) return false;
526
+ return input.subscribed || input.admin && (input.kind === "open" || input.mentioned) && (!input.ignored || input.mentioned);
527
+ }
528
+ // src/service/courier.ts
529
+ /** 没有活票的话题,最后一次活动超过这个时长就不再轮询(官方 POLL_HORIZON_MS)。 */
530
+ const POLL_HORIZON_MS = 12096e5;
531
+ /** 同话题投递串行化:同一时刻只允许一条在途,避免重复发言。 */
532
+ const publishing = /* @__PURE__ */ new Map();
533
+ const courier = defineService({
534
+ async state(channel, scope, name) {
535
+ const row = await db.sourceState.find(channel, `${scope}:${name}`);
536
+ return row ? JSON.parse(row.value) : void 0;
537
+ },
538
+ async record(channel, scope, name, value) {
539
+ await db.sourceState.set(channel, `${scope}:${name}`, JSON.stringify(value), now());
540
+ },
541
+ async pages(fetchPage) {
542
+ const rows = [];
543
+ let etag = null;
544
+ for (let page = 1;; page++) {
545
+ const value = await fetchPage(page);
546
+ if (page === 1) {
547
+ if (value.notModified) return {
548
+ rows: [],
549
+ notModified: true,
550
+ etag: value.etag ?? null
551
+ };
552
+ etag = value.etag ?? null;
553
+ }
554
+ rows.push(...value.rows);
555
+ if (value.rows.length < 100) return {
556
+ rows,
557
+ notModified: false,
558
+ etag
559
+ };
560
+ }
561
+ },
562
+ page(items, offset, limit) {
563
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new ChannelError("invalid_pagination");
564
+ return {
565
+ items: items.slice(offset, offset + limit),
566
+ next_offset: offset + limit < items.length ? offset + limit : null
567
+ };
568
+ },
569
+ async stream(input) {
570
+ const cursor = await courier.state(input.channel, input.scope, `cursor:${input.name}`) ?? input.initial;
571
+ const startedAt = now();
572
+ const value = await input.read(cursor);
573
+ if (value.notModified) return;
574
+ const revisions = [];
575
+ let firstError;
576
+ for (const row of value.rows) {
577
+ input.signal?.throwIfAborted();
578
+ try {
579
+ await input.accept(row);
580
+ } catch (error) {
581
+ if (input.signal?.aborted) throw error;
582
+ firstError ??= error;
583
+ }
584
+ revisions.push(digest(row));
585
+ }
586
+ if (firstError) throw firstError;
587
+ const signature = digest(revisions.sort());
588
+ const next = {
589
+ ...input.advance(cursor, value.rows, startedAt),
590
+ signature,
591
+ through: startedAt
592
+ };
593
+ if (value.etag !== void 0) next.etag = value.etag;
594
+ await courier.record(input.channel, input.scope, `cursor:${input.name}`, next);
595
+ },
596
+ async ingest(port, thread, row, kind, baseline, sourceKind) {
597
+ const bots = await port.bots();
598
+ const actorName = port.actor(row);
599
+ const human = port.human(row, bots);
600
+ const body = port.body(row);
601
+ const mentioned = port.mentioned(body, bots);
602
+ const at = port.at(row);
603
+ const id = `${thread.id}:${sourceKind}:${identity(row.id)}`;
604
+ await db.trigger.ingest({
605
+ id,
606
+ channelId: port.channel,
607
+ threadId: thread.id,
608
+ kind,
609
+ actorName,
610
+ human: Number(human),
611
+ mentioned: Number(mentioned),
612
+ text: body,
613
+ url: port.url(row, sourceKind, thread),
614
+ at,
615
+ ref: port.ref(row)
616
+ });
617
+ const subscriptions = await db.ticketThread.listTicketIds(thread.id);
618
+ const historical = port.createdAt(row) < baseline;
619
+ const admin = (await setting.load()).administrators.some((name) => name.toLowerCase() === actorName.toLowerCase());
620
+ if (!acceptsChannelTrigger({
621
+ human,
622
+ historical,
623
+ subscribed: subscriptions.length > 0,
624
+ admin,
625
+ mentioned,
626
+ kind,
627
+ ignored: thread.triage === "ignored"
628
+ })) return;
629
+ const targets = /* @__PURE__ */ new Map();
630
+ for (const ticketId of subscriptions) {
631
+ const ticket = await db.ticket.findById(ticketId);
632
+ if (!ticket) continue;
633
+ if (["done", "cancelled"].includes(ticket.status)) {
634
+ if (!mentioned) continue;
635
+ if (await db.ticket.reopen(ticketId, at)) {
636
+ await db.worker.queue(ticketId, ticket.projectId);
637
+ targets.set(ticket.projectId, {
638
+ projectId: ticket.projectId,
639
+ ticketId
640
+ });
641
+ }
642
+ continue;
643
+ }
644
+ await port.onSubscribedTicket?.(ticket);
645
+ targets.set(ticket.projectId, {
646
+ projectId: ticket.projectId,
647
+ ticketId
648
+ });
649
+ }
650
+ if (!subscriptions.length) targets.set(thread.projectId ?? "main", {
651
+ projectId: thread.triage === "claimed" ? thread.projectId : null,
652
+ ticketId: null
653
+ });
654
+ for (const [key, target] of targets) await db.inbox.enqueue({
655
+ id: `${id}:inbox:${key}`,
656
+ type: target.projectId ? "project" : "main",
657
+ origin: "channel",
658
+ kind: "trigger",
659
+ message: body,
660
+ title: thread.title,
661
+ projectId: target.projectId,
662
+ ticketId: target.ticketId,
663
+ triggerId: id,
664
+ threadId: thread.id
665
+ });
666
+ },
667
+ async answers(port, thread, row) {
668
+ if (!await port.admin(row)) return;
669
+ const body = typeof row.body === "string" ? row.body : "";
670
+ const { answers: found, conflicts } = await port.parse(body, thread);
671
+ const scope = await port.scope(thread);
672
+ for (const [id, answer] of found) {
673
+ if (conflicts.has(id)) continue;
674
+ const ask = await db.inbox.findById(id);
675
+ if (!ask || ask.kind !== "ask" || ask.type !== "user" || ask.status !== "pending" || timestamp(row.created_at ?? row.submitted_at) < ask.createdAt) continue;
676
+ const trigger = ask.triggerId && await db.trigger.findById(ask.triggerId);
677
+ if (!trigger || trigger.threadId !== thread.id || ask.threadId && ask.threadId !== thread.id) continue;
678
+ if (!await courier.state(port.channel, scope, `comment:${id}`)) continue;
679
+ if (ask.ticketId) {
680
+ const ticket = await db.ticket.findById(ask.ticketId);
681
+ if (!ticket || ["done", "cancelled"].includes(ticket.status)) continue;
682
+ }
683
+ await db.inbox.answerByUser(id, answer, now());
684
+ }
685
+ },
686
+ async publish(port, inboxId, signal) {
687
+ const destination = async (row) => {
688
+ if (row.type !== "user" || !["notice", "ask"].includes(row.kind) || !row.triggerId) throw new ChannelError("invalid_delivery");
689
+ const trigger = await db.trigger.findById(row.triggerId);
690
+ const thread = trigger && await db.thread.findById(trigger.threadId);
691
+ if (!thread?.url || thread.channelId !== port.channel || !["issue", "pull"].includes(thread.kind) || row.threadId && row.threadId !== thread.id) throw new ChannelError("no_reply_address");
692
+ const target = await port.parse(thread.url);
693
+ const project = await port.projectFor(target);
694
+ if (!project) throw new ChannelError("unknown_repository");
695
+ if (row.ticketId) {
696
+ const ticket = await db.ticket.findById(row.ticketId);
697
+ if (row.kind === "ask" && ticket && ["done", "cancelled"].includes(ticket.status)) throw new ChannelError("delivery_superseded");
698
+ if (!ticket || ticket.projectId !== project.id) throw new ChannelError("scope_denied");
699
+ if (ticket.paused) throw new ChannelError("human_paused");
700
+ if (!(await db.ticketThread.listTicketIds(thread.id)).includes(ticket.id)) throw new ChannelError("unsubscribed_thread");
701
+ }
702
+ return {
703
+ thread,
704
+ target
705
+ };
706
+ };
707
+ const deliver = async () => {
708
+ let row = await db.inbox.findById(inboxId);
709
+ if (!row) return {
710
+ ok: false,
711
+ reason: "unknown_delivery"
712
+ };
713
+ if (row.status === "done") return { ok: true };
714
+ let posting = false;
715
+ try {
716
+ const { thread, target } = await destination(row);
717
+ const project = await port.projectFor(target);
718
+ const environment = await port.probe(project.id, signal);
719
+ const scope = port.scope(target);
720
+ const marker = `<!-- supermesh:${row.id} -->`;
721
+ const receipt = await courier.state(port.channel, scope, `comment:${row.id}`);
722
+ if (receipt) {
723
+ if (receipt.providerId !== environment.providerId || receipt.marker !== marker) throw new ChannelError("managed_comment_mismatch");
724
+ if (row.kind === "notice") await db.inbox.markDone(row.id, now());
725
+ return {
726
+ ok: true,
727
+ remoteId: receipt.remoteId
728
+ };
729
+ }
730
+ if (row.nextRetryAt && row.nextRetryAt > now()) return {
731
+ ok: false,
732
+ reason: "retry_pending"
733
+ };
734
+ for (const previous of await db.inbox.listOutgoing()) {
735
+ if (previous.id === row.id || previous.seq >= row.seq || previous.ticketId !== row.ticketId || previous.status === "done") continue;
736
+ if ((previous.threadId ?? (previous.triggerId ? (await db.trigger.findById(previous.triggerId))?.threadId : void 0)) === thread.id && !await courier.state(port.channel, scope, `comment:${previous.id}`)) return {
737
+ ok: false,
738
+ reason: "earlier_delivery_pending"
739
+ };
740
+ }
741
+ const existing = (await port.comments(target, signal)).filter((comment) => port.authorId(comment) === environment.providerId && port.body(comment).includes(marker));
742
+ if (existing.length > 1) throw new ChannelError("ambiguous_delivery");
743
+ let remote = existing[0];
744
+ if (!remote) {
745
+ if (row.status === "stalled" || row.deliveryError === "publishing") {
746
+ await db.inbox.markStalled(row.id, "transport_unknown");
747
+ return {
748
+ ok: false,
749
+ reason: "transport_unknown"
750
+ };
751
+ }
752
+ const current = await db.inbox.findById(row.id);
753
+ if (!current || current.status !== "pending" || current.type !== row.type || current.kind !== row.kind) return {
754
+ ok: false,
755
+ reason: "delivery_superseded"
756
+ };
757
+ await destination(current);
758
+ await db.inbox.recordDeliveryFailure(row.id, "publishing", now());
759
+ posting = true;
760
+ const body = row.kind === "ask" ? port.askPrompt(row) : row.message;
761
+ remote = await port.post(target, `${body}\n\n${marker}`, signal);
762
+ }
763
+ if (port.authorId(remote) !== environment.providerId || !port.body(remote).includes(marker)) throw new ChannelError("managed_comment_mismatch");
764
+ const result = {
765
+ remoteId: identity(remote.id),
766
+ providerId: environment.providerId,
767
+ marker,
768
+ url: port.commentUrl(remote, target)
769
+ };
770
+ await courier.record(port.channel, scope, `comment:${row.id}`, result);
771
+ await db.inbox.resetDelivery(row.id);
772
+ if (row.kind === "notice") await db.inbox.markDone(row.id, now());
773
+ return {
774
+ ok: true,
775
+ remoteId: result.remoteId
776
+ };
777
+ } catch (error) {
778
+ const reason = courier.failure(error, port.detail);
779
+ if (posting && ![
780
+ "rate_limited",
781
+ "forbidden",
782
+ "not_found",
783
+ "not_logged_in",
784
+ "remote_rejected"
785
+ ].includes(reason)) await db.inbox.markStalled(row.id, "transport_unknown");
786
+ else if (![
787
+ "human_paused",
788
+ "project_disabled",
789
+ "channel_disabled",
790
+ "retry_pending",
791
+ ...port.skipReasons
792
+ ].includes(reason)) {
793
+ row = await db.inbox.findById(row.id);
794
+ const settings = await setting.load();
795
+ const attempts = row.deliveryAttempts + (posting ? 0 : 1);
796
+ if (attempts >= settings.deliveryMaxAttempts) await db.inbox.markStalled(row.id, reason);
797
+ else {
798
+ const seconds = courier.retryDelay(error, attempts, settings.deliveryRetryCeilingSeconds);
799
+ const nextRetryAt = new Date(Date.now() + seconds * 1e3).toISOString();
800
+ if (posting) await db.inbox.update(row.id, {
801
+ deliveryError: reason,
802
+ nextRetryAt
803
+ });
804
+ else await db.inbox.recordDeliveryFailure(row.id, reason, nextRetryAt);
805
+ }
806
+ }
807
+ if (signal?.aborted) throw error;
808
+ return {
809
+ ok: false,
810
+ reason: posting && reason === "interrupted" ? "transport_unknown" : reason
811
+ };
812
+ }
813
+ };
814
+ return singlet.immediate(`${port.channel}:exclusive:publish:${inboxId}`, async () => {
815
+ const row = await db.inbox.findById(inboxId);
816
+ const trigger = row?.triggerId ? await db.trigger.findById(row.triggerId) : void 0;
817
+ const key = `${port.channel}:${trigger ? trigger.threadId : inboxId}`;
818
+ const task = (publishing.get(key) ?? Promise.resolve()).then(deliver);
819
+ const barrier = task.then(() => void 0, () => void 0);
820
+ publishing.set(key, barrier);
821
+ try {
822
+ return await task;
823
+ } finally {
824
+ if (publishing.get(key) === barrier) publishing.delete(key);
825
+ }
826
+ });
827
+ },
828
+ async flush(port, signal) {
829
+ signal?.throwIfAborted();
830
+ if (!(await db.channel.findById(port.channel))?.enabled) return [];
831
+ const results = [];
832
+ for (const row of await db.inbox.listOutgoing()) {
833
+ signal?.throwIfAborted();
834
+ if (row.status !== "pending") continue;
835
+ const trigger = row.triggerId && await db.trigger.findById(row.triggerId);
836
+ if (trigger && trigger.channelId === port.channel) results.push({
837
+ id: row.id,
838
+ ...await courier.publish(port, row.id, signal)
839
+ });
840
+ }
841
+ return results;
842
+ },
843
+ async harvest(port, signal) {
844
+ signal?.throwIfAborted();
845
+ if (!(await db.channel.findById(port.channel))?.enabled) return [];
846
+ const results = [];
847
+ for (const project of await db.project.listAll()) {
848
+ signal?.throwIfAborted();
849
+ if (!project.enabled || !await port.scope(project)) continue;
850
+ const outcome = await courier.collect(port, project.id, void 0, signal);
851
+ if (!outcome.ok) port.onFailure?.(project, outcome.reason ?? "channel_operation_failed");
852
+ results.push(outcome);
853
+ }
854
+ return results;
855
+ },
856
+ async collect(port, projectId, branch, signal) {
857
+ if (branch) {
858
+ await port.collectBranch(projectId, branch, signal);
859
+ return {
860
+ projectId,
861
+ ok: true
862
+ };
863
+ }
864
+ return singlet.immediate(`${port.channel}:exclusive:collect:${projectId}`, async () => {
865
+ const errors = [];
866
+ let scope;
867
+ const context = {
868
+ channel: port.channel,
869
+ projectId,
870
+ scope: "",
871
+ baseline: "",
872
+ environment: {
873
+ providerId: "",
874
+ login: "",
875
+ repositoryId: ""
876
+ },
877
+ attempt: async (operation) => {
878
+ try {
879
+ await operation();
880
+ } catch (error) {
881
+ if (signal?.aborted) throw error;
882
+ errors.push(courier.failure(error, port.detail));
883
+ }
884
+ },
885
+ fail: (error) => {
886
+ if (signal?.aborted) throw error;
887
+ errors.push(courier.failure(error, port.detail));
888
+ }
889
+ };
890
+ try {
891
+ const project = await port.project(projectId);
892
+ const environment = await port.probe(projectId, signal);
893
+ const resolved = await port.scope(project);
894
+ if (!resolved) throw new ChannelError("unknown_repository");
895
+ scope = resolved;
896
+ const baseline = await courier.state(port.channel, scope, "baseline") ?? now();
897
+ await courier.record(port.channel, scope, "baseline", baseline);
898
+ context.scope = scope;
899
+ context.baseline = baseline;
900
+ context.environment = environment;
901
+ await port.collect(context, signal);
902
+ } catch (error) {
903
+ if (signal?.aborted) throw error;
904
+ errors.push(courier.failure(error, port.detail));
905
+ }
906
+ if (port.status && scope) await courier.record(port.channel, scope, "collection_status", {
907
+ ok: !errors.length,
908
+ reasons: [...new Set(errors)],
909
+ collectedAt: now()
910
+ });
911
+ return errors.length ? {
912
+ projectId,
913
+ ok: false,
914
+ reason: [...new Set(errors)].join(",")
915
+ } : {
916
+ projectId,
917
+ ok: true
918
+ };
919
+ });
920
+ },
921
+ async polled(ticketIds, updatedAt, at = Date.now()) {
922
+ if (!ticketIds.length) return true;
923
+ const tickets = await Promise.all(ticketIds.map((id) => db.ticket.findById(id)));
924
+ if (tickets.some((ticket) => !!ticket && !["done", "cancelled"].includes(ticket.status))) return true;
925
+ const times = [updatedAt ?? "", ...tickets.map((ticket) => ticket?.endedAt ?? "")].map((value) => Date.parse(value)).filter(Number.isFinite);
926
+ return times.length > 0 && at - Math.max(...times) < POLL_HORIZON_MS;
927
+ },
928
+ failure(error, detail) {
929
+ if (error instanceof ChannelError) return error.code;
930
+ if (error instanceof Error) return error.name === "AbortError" ? "interrupted" : detail ? `transport_unknown(${error.message.slice(0, 120)})` : "transport_unknown";
931
+ return "transport_unknown";
932
+ },
933
+ retryDelay(error, attempts, ceiling) {
934
+ return Math.max(error instanceof ChannelError ? error.retryAfterSeconds ?? 0 : 0, Math.min(ceiling, 2 ** Math.max(1, attempts)));
935
+ }
936
+ });
937
+ // src/channel/github/service/ci.ts
938
+ const ci$1 = defineService({
939
+ async snapshot(remote, root, head, signal) {
940
+ const previous = await courier.state("github", root.slice(6), `ci_runs:${head}`);
941
+ const checks = /* @__PURE__ */ new Map();
942
+ const statuses = /* @__PURE__ */ new Map();
943
+ const acceptCheck = (check) => {
944
+ if (check.head_sha !== head) return;
945
+ const key = `${identity(record(check.app).id)}:${text(check.name)}`;
946
+ const prior = checks.get(key);
947
+ if (!prior || number(check.id) > number(prior.id) || check.id === prior.id && !(prior.status === "completed" && check.status !== "completed") && timestamp(check.completed_at ?? check.started_at ?? check.created_at) >= timestamp(prior.completed_at ?? prior.started_at ?? prior.created_at)) checks.set(key, check);
948
+ };
949
+ const acceptStatus = (status) => {
950
+ const key = text(status.context);
951
+ const prior = statuses.get(key);
952
+ if (!prior || timestamp(status.updated_at ?? status.created_at) > timestamp(prior.updated_at ?? prior.created_at) || timestamp(status.updated_at ?? status.created_at) === timestamp(prior.updated_at ?? prior.created_at) && number(status.id) > number(prior.id)) statuses.set(key, status);
953
+ };
954
+ for (const check of previous?.checks ?? []) acceptCheck(check);
955
+ for (const status of previous?.statuses ?? []) acceptStatus(status);
956
+ for (const kind of ["check-runs", "status"]) for (let page = 1;; page++) {
957
+ const response = record(await remote.request(`${root}/commits/${encodeURIComponent(head)}/${kind}?per_page=100&page=${page}`, signal));
958
+ if (kind === "status" && response.sha !== head) throw new GhError("ci_head_mismatch");
959
+ const rows = array(response[kind === "check-runs" ? "check_runs" : "statuses"]).map(record);
960
+ for (const row of rows) (kind === "check-runs" ? acceptCheck : acceptStatus)(row);
961
+ if (rows.length < 100) break;
962
+ }
963
+ const states = [...checks.values()].map((check) => check.status === "in_progress" ? "running" : check.status !== "completed" ? "pending" : [
964
+ "success",
965
+ "neutral",
966
+ "skipped"
967
+ ].includes(String(check.conclusion)) ? "passing" : "failing");
968
+ states.push(...[...statuses.values()].map((status) => status.state === "success" ? "passing" : status.state === "pending" ? "pending" : "failing"));
969
+ const result = {
970
+ state: states.includes("failing") ? "failing" : states.includes("running") ? "running" : !states.length || states.includes("pending") ? "pending" : "passing",
971
+ checks: [...checks.values()],
972
+ statuses: [...statuses.values()]
973
+ };
974
+ await courier.record("github", root.slice(6), `ci_runs:${head}`, result);
975
+ return result;
976
+ },
977
+ async branch(remote, projectId, branch, signal) {
978
+ const project = await remote.project(projectId);
979
+ await remote.probe(projectId, signal);
980
+ const repository = resource$1.of(project.remoteUrl);
981
+ const head = text(record(await remote.request(`repos/${repository}/commits/${encodeURIComponent(branch)}`, signal)).sha);
982
+ const snapshot = await ci$1.snapshot(remote, `repos/${repository}`, head, signal);
983
+ const failing = snapshot.checks.filter((check) => check.status === "completed" && ![
984
+ "success",
985
+ "neutral",
986
+ "skipped"
987
+ ].includes(String(check.conclusion))).map((check) => text(check.name));
988
+ failing.push(...snapshot.statuses.filter((status) => !["success", "pending"].includes(String(status.state))).map((status) => text(status.context)));
989
+ await notifyBranchCi({
990
+ channel: "github",
991
+ projectId,
992
+ ref: `${repository}:branch:${branch}`,
993
+ fingerprint: digest({
994
+ state: snapshot.state,
995
+ failing: failing.sort()
996
+ }),
997
+ head,
998
+ title: `CI ${branch}`,
999
+ message: `${branch} CI ${snapshot.state}${failing.length ? `: ${failing.join(", ")}` : ""}`,
1000
+ url: `https://github.com/${repository}/commit/${head}`,
1001
+ silent: !failing.length
1002
+ });
1003
+ }
1004
+ });
1005
+ // src/channel/github/service/binding.ts
1006
+ const binding$1 = defineService({ of(channel) {
1007
+ return {
1008
+ delivery: {
1009
+ channel: "github",
1010
+ detail: false,
1011
+ parse: async (value) => resource$1.parse(value),
1012
+ scope: (target) => target.repository,
1013
+ projectFor: (target) => channel.projectForRepository(target.repository),
1014
+ probe: (projectId, signal) => channel.probe(projectId, signal),
1015
+ comments: (target, signal) => channel.pages(`repos/${target.repository}/issues/${target.number}/comments`, signal),
1016
+ authorId: (row) => record(row.user).id != null ? identity(record(row.user).id) : null,
1017
+ body: (row) => typeof row.body === "string" ? row.body : "",
1018
+ post: async (target, body, signal) => record(await channel.request(`repos/${target.repository}/issues/${target.number}/comments`, signal, "POST", { body })),
1019
+ commentUrl: (row, target) => {
1020
+ const url = text(row.html_url);
1021
+ const remote = resource$1.parse(url);
1022
+ if (remote.repository !== target.repository || remote.number !== target.number) throw new GhError("managed_comment_mismatch");
1023
+ return url;
1024
+ },
1025
+ askPrompt: (row) => `${row.message}\n\n回复格式:\`answer: 你的回答\``,
1026
+ skipReasons: []
1027
+ },
1028
+ collector: {
1029
+ channel: "github",
1030
+ detail: false,
1031
+ status: true,
1032
+ scope: async (project) => resource$1.of(project.remoteUrl),
1033
+ project: (projectId) => channel.project(projectId),
1034
+ probe: (projectId, signal) => channel.probe(projectId, signal),
1035
+ collect: (context, signal) => channel.collectProject(context, signal),
1036
+ collectBranch: (projectId, branch, signal) => ci$1.branch(channel, projectId, branch, signal)
1037
+ },
1038
+ ingestor: {
1039
+ channel: "github",
1040
+ bots: async () => (await db.channelAccount.findByChannel("github")).filter((account) => account.role === "bot"),
1041
+ actor: (row) => text(record(row.user).login),
1042
+ human: (row, bots) => {
1043
+ const author = record(row.user);
1044
+ const name = text(author.login);
1045
+ return author.type !== "Bot" && !name.endsWith("[bot]") && !bots.some((bot) => bot.name.toLowerCase() === name.toLowerCase());
1046
+ },
1047
+ body: (row) => typeof row.body === "string" ? row.body : typeof row.state === "string" ? row.state : "",
1048
+ url: (row) => text(row.html_url),
1049
+ ref: (row) => row.head ? text(record(row.head).ref) : null,
1050
+ at: (row) => timestamp(row.updated_at ?? row.submitted_at ?? row.created_at),
1051
+ createdAt: (row) => timestamp(row.created_at ?? row.submitted_at),
1052
+ mentioned: (body, bots) => bots.some((bot) => new RegExp(`@${escapeRegex(bot.name)}(?![a-z0-9-])`, "i").test(body)),
1053
+ onSubscribedTicket: async (ticket) => {
1054
+ if (ticket.status !== "review" || ticket.paused) return;
1055
+ await db.ticket.update(ticket.id, {
1056
+ status: "waiting",
1057
+ updatedAt: now()
1058
+ });
1059
+ await db.worker.queue(ticket.id, ticket.projectId).catch(() => void 0);
1060
+ }
1061
+ },
1062
+ answerer: {
1063
+ channel: "github",
1064
+ admin: async (row) => {
1065
+ const author = record(row.user);
1066
+ const login = text(author.login);
1067
+ const accounts = await db.channelAccount.findByChannel("github");
1068
+ if (author.type !== "User" || login.endsWith("[bot]") || accounts.some((account) => account.role === "bot" && account.name.toLowerCase() === login.toLowerCase())) return false;
1069
+ return (await setting.load()).administrators.some((name) => name.toLowerCase() === login.toLowerCase());
1070
+ },
1071
+ parse: async (body, thread) => {
1072
+ const answers = /* @__PURE__ */ new Map();
1073
+ const conflicts = /* @__PURE__ */ new Set();
1074
+ let anonymous;
1075
+ for (const line of answerLines(body)) {
1076
+ if (!/^answer(?:[ \t::]|$)/i.test(line)) continue;
1077
+ const content = line.slice(6).trim().replace(/^[::]\s*/, "").trim();
1078
+ if (!content) continue;
1079
+ const separator = content.indexOf(": ");
1080
+ const candidate = separator > 0 ? content.slice(0, separator).trim() : "";
1081
+ if (candidate && /^[0-9a-f][\w:-]{7,}$/i.test(candidate) && content.slice(separator + 2).trim()) {
1082
+ const answer = content.slice(separator + 2).trim();
1083
+ if (answers.has(candidate) && answers.get(candidate) !== answer) conflicts.add(candidate);
1084
+ answers.set(candidate, answer);
1085
+ continue;
1086
+ }
1087
+ anonymous ??= content;
1088
+ }
1089
+ if (anonymous !== void 0) {
1090
+ const pending = (await db.inbox.listPendingAsk()).filter((ask) => ask.type === "user");
1091
+ const scoped = pending.filter((ask) => ask.threadId === thread.id);
1092
+ const only = scoped.length === 1 ? scoped[0] : scoped.length === 0 && pending.length === 1 ? pending[0] : void 0;
1093
+ if (only) answers.set(only.id, anonymous);
1094
+ }
1095
+ return {
1096
+ answers,
1097
+ conflicts
1098
+ };
1099
+ },
1100
+ scope: async (thread) => resource$1.parse(thread.url).repository
1101
+ }
1102
+ };
1103
+ } });
1104
+ // src/channel/github/service/pull.ts
1105
+ const pull = defineService({
1106
+ async collect(remote, projectId, threadId, signal) {
1107
+ return singlet.immediate(`github:exclusive:pull:${threadId}`, async () => {
1108
+ const project = await remote.project(projectId);
1109
+ await remote.probe(projectId, signal);
1110
+ const thread = await db.thread.findById(threadId);
1111
+ if (!thread?.url || thread.kind !== "pull") throw new GhError("invalid_pull_request");
1112
+ const target = resource$1.parse(thread.url);
1113
+ if (target.repository !== resource$1.of(project.remoteUrl)) throw new GhError("source_repository_mismatch");
1114
+ const root = `repos/${target.repository}`;
1115
+ const detail = record(await remote.request(`${root}/pulls/${target.number}`, signal));
1116
+ resource$1.validate(detail, target);
1117
+ const head = text(record(detail.head).sha);
1118
+ const base = record(detail.base);
1119
+ if (text(record(base.repo).full_name).toLowerCase() !== target.repository) throw new GhError("pull_request_mismatch");
1120
+ const state = detail.merged === true ? "merged" : detail.state === "open" ? "open" : detail.state === "closed" ? "closed" : null;
1121
+ if (!state) throw new GhError("invalid_response");
1122
+ const previous = await courier.state("github", target.repository, `pr_fact:${target.number}`);
1123
+ const updatedAt = timestamp(detail.updated_at);
1124
+ if (previous && (previous.updatedAt > updatedAt || previous.state === "merged" && state !== "merged")) return {
1125
+ ok: false,
1126
+ reason: "stale_pr_snapshot"
1127
+ };
1128
+ let ciState = previous?.head === head ? previous.ciState : "pending";
1129
+ let ciError;
1130
+ let snapshot;
1131
+ try {
1132
+ snapshot = await ci$1.snapshot(remote, root, head, signal);
1133
+ ciState = snapshot.state;
1134
+ } catch (error) {
1135
+ if (signal?.aborted) throw error;
1136
+ ciError = courier.failure(error, false);
1137
+ }
1138
+ const fact = {
1139
+ head,
1140
+ base: text(base.ref),
1141
+ state,
1142
+ ciState,
1143
+ collectedAt: now(),
1144
+ updatedAt,
1145
+ ciError,
1146
+ url: text(detail.html_url)
1147
+ };
1148
+ await courier.record("github", target.repository, `pr_fact:${target.number}`, fact);
1149
+ const branch = typeof record(detail.head).ref === "string" ? text(record(detail.head).ref) : null;
1150
+ const worker = branch ? await db.worker.findByBranch(branch) : void 0;
1151
+ const owned = worker && await db.ticket.findById(worker.ticketId);
1152
+ if (owned?.projectId === projectId && (!owned.prUrl || owned.prUrl === thread.url)) {
1153
+ await db.ticketThread.link(owned.id, thread.id, now());
1154
+ await db.ticket.setPullRequest(owned.id, thread.url, state, ciState);
1155
+ }
1156
+ const subscriptions = await db.ticketThread.listTicketIds(thread.id);
1157
+ for (const ticketId of subscriptions) {
1158
+ const ticket = await db.ticket.findById(ticketId);
1159
+ if (ticket?.projectId === projectId && ticket.prUrl === thread.url) await db.ticket.setPullRequest(ticketId, thread.url, state, ciState);
1160
+ }
1161
+ if (state === "merged" || state === "closed") await pull.closed(remote, projectId, thread, state, detail.merged === true ? timestamp(detail.merged_at ?? detail.closed_at ?? detail.updated_at) : timestamp(detail.closed_at ?? detail.updated_at), branch);
1162
+ const fingerprint = digest({
1163
+ head,
1164
+ state,
1165
+ ciState,
1166
+ ciError,
1167
+ checks: snapshot?.checks,
1168
+ statuses: snapshot?.statuses
1169
+ });
1170
+ const ref = `${target.repository}:${target.number}`;
1171
+ const { row: watch } = await db.ciWatch.recordRevision({
1172
+ id: `github:pull:${ref}`,
1173
+ channelId: "github",
1174
+ kind: "pull",
1175
+ ref,
1176
+ fingerprint,
1177
+ head,
1178
+ updatedAt: now()
1179
+ });
1180
+ const triggerId = `${watch.id}:revision:${watch.revision}`;
1181
+ const message = `PR #${target.number}: ${state}, CI ${ciState}${ciError ? ` (${ciError})` : ""}`;
1182
+ await db.trigger.ingest({
1183
+ id: triggerId,
1184
+ channelId: "github",
1185
+ threadId,
1186
+ kind: "ci",
1187
+ actorName: null,
1188
+ human: 0,
1189
+ mentioned: 0,
1190
+ text: message,
1191
+ url: thread.url,
1192
+ at: now(),
1193
+ ref: head
1194
+ });
1195
+ for (const ticketId of subscriptions) {
1196
+ const ticket = await db.ticket.findById(ticketId);
1197
+ if (ticket?.projectId === projectId && !["done", "cancelled"].includes(ticket.status)) await db.inbox.enqueue({
1198
+ id: `${triggerId}:ticket:${ticketId}`,
1199
+ type: "project",
1200
+ origin: "system",
1201
+ kind: "notice",
1202
+ projectId,
1203
+ ticketId,
1204
+ triggerId,
1205
+ threadId,
1206
+ title: message,
1207
+ message
1208
+ });
1209
+ }
1210
+ return {
1211
+ ok: !ciError,
1212
+ ...ciError ? { reason: ciError } : {}
1213
+ };
1214
+ });
1215
+ },
1216
+ async closed(remote, projectId, thread, outcome, at, branch) {
1217
+ await closeThread({
1218
+ channel: "github",
1219
+ projectId,
1220
+ thread,
1221
+ outcome,
1222
+ at,
1223
+ branch,
1224
+ closeIssue: async (url) => {
1225
+ const target = resource$1.parse(url);
1226
+ if (target.kind !== "issue") return;
1227
+ await remote.request(`repos/${target.repository}/issues/${target.number}`, void 0, "PATCH", { state: "closed" });
1228
+ }
1229
+ });
1230
+ }
1231
+ });
1232
+ // src/channel/github/channel.ts
1233
+ var GitHubChannel = class {
1234
+ runner;
1235
+ delivery;
1236
+ collector;
1237
+ ingestor;
1238
+ answerer;
1239
+ constructor(runner = new ExecFileGhRunner()) {
1240
+ this.runner = runner;
1241
+ const ports = binding$1.of(this);
1242
+ this.delivery = ports.delivery;
1243
+ this.collector = ports.collector;
1244
+ this.ingestor = ports.ingestor;
1245
+ this.answerer = ports.answerer;
1246
+ }
1247
+ async request(path, signal, method = "GET", body, headers) {
1248
+ signal?.throwIfAborted();
1249
+ return this.runner.request({
1250
+ site: "github.com",
1251
+ path,
1252
+ method,
1253
+ body,
1254
+ headers,
1255
+ signal
1256
+ });
1257
+ }
1258
+ async project(projectId) {
1259
+ const project = await db.project.findById(projectId);
1260
+ if (!project || !resource$1.of(project.remoteUrl)) throw new GhError("unknown_repository");
1261
+ if (!project.enabled) throw new GhError("project_disabled");
1262
+ return project;
1263
+ }
1264
+ async projectForRepository(repository) {
1265
+ const projects = (await db.project.listAll()).filter((project) => resource$1.of(project.remoteUrl) === repository);
1266
+ if (projects.length !== 1) throw new GhError(projects.length ? "ambiguous_repository" : "unknown_repository");
1267
+ return projects[0];
1268
+ }
1269
+ async probe(projectId, signal) {
1270
+ const project = await this.project(projectId);
1271
+ if (!(await db.channel.findById("github"))?.enabled) throw new GhError("channel_disabled");
1272
+ const bots = (await db.channelAccount.findByRole("github", "bot")).filter((account) => account.status === "online");
1273
+ const account = record(await this.request("user", signal));
1274
+ const providerId = identity(account.id);
1275
+ const login = text(account.login);
1276
+ if (!bots.some((bot) => bot.name.toLowerCase() === login.toLowerCase())) throw new GhError("account_mismatch");
1277
+ const repository = resource$1.of(project.remoteUrl);
1278
+ const remote = record(await this.request(`repos/${repository}`, signal));
1279
+ if (text(remote.full_name).toLowerCase() !== repository) throw new GhError("repository_mismatch");
1280
+ const result = {
1281
+ providerId,
1282
+ login,
1283
+ repositoryId: identity(remote.id),
1284
+ defaultBranch: typeof remote.default_branch === "string" ? remote.default_branch : null
1285
+ };
1286
+ const previous = await courier.state("github", repository, "verified_environment");
1287
+ if (previous && (previous.providerId !== providerId || previous.repositoryId !== result.repositoryId)) throw new GhError("environment_identity_changed");
1288
+ await courier.record("github", repository, "verified_environment", result);
1289
+ return result;
1290
+ }
1291
+ async pages(path, signal) {
1292
+ return (await courier.pages(async (page) => ({ rows: array(await this.request(`${path + (path.includes("?") ? "&" : "?")}per_page=100&page=${page}`, signal)).map(record) }))).rows;
1293
+ }
1294
+ async read(value, offset = 0, limit = 50, signal) {
1295
+ const target = resource$1.parse(value);
1296
+ const project = await this.projectForRepository(target.repository);
1297
+ await this.probe(project.id, signal);
1298
+ const root = `repos/${target.repository}`;
1299
+ const main = record(await this.request(root + (target.kind === "pull" ? "/pulls/" : "/issues/") + target.number, signal));
1300
+ resource$1.validate(main, target);
1301
+ const items = [resource$1.item(main, target.kind)];
1302
+ for (const row of await this.pages(`${root}/issues/${target.number}/comments`, signal)) items.push(resource$1.item(row, "comment"));
1303
+ if (target.kind === "pull") {
1304
+ for (const row of await this.pages(`${root}/pulls/${target.number}/reviews`, signal)) items.push(resource$1.item(row, "review"));
1305
+ for (const row of await this.pages(`${root}/pulls/${target.number}/comments`, signal)) items.push(resource$1.item(row, "review_comment"));
1306
+ }
1307
+ items.splice(1, items.length - 1, ...items.slice(1).sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)));
1308
+ return {
1309
+ ...courier.page(items, offset, limit),
1310
+ next_resource: null
1311
+ };
1312
+ }
1313
+ async normalize(value) {
1314
+ const target = resource$1.parse(value);
1315
+ return `https://github.com/${target.repository}/${target.kind === "pull" ? "pull" : "issues"}/${target.number}`;
1316
+ }
1317
+ async readable(value) {
1318
+ try {
1319
+ await this.normalize(value);
1320
+ return true;
1321
+ } catch {
1322
+ return false;
1323
+ }
1324
+ }
1325
+ async harvest(signal) {
1326
+ return courier.harvest(this.collector, signal);
1327
+ }
1328
+ async collect(projectId, branch, signal) {
1329
+ return courier.collect(this.collector, projectId, branch, signal);
1330
+ }
1331
+ async collectProject(context, signal) {
1332
+ const repo = context.scope;
1333
+ const { attempt, baseline, environment } = context;
1334
+ await attempt(() => this.stream(repo, "topics", `repos/${repo}/issues?state=all&sort=updated&direction=asc`, baseline, async (row) => {
1335
+ const target = {
1336
+ repository: repo,
1337
+ number: number(row.number),
1338
+ kind: row.pull_request ? "pull" : "issue"
1339
+ };
1340
+ resource$1.validate(row, target);
1341
+ const thread = await this.ensureThread(target, row);
1342
+ const kind = target.kind === "issue" && row.state === "closed" ? "close" : "open";
1343
+ await courier.ingest(this.ingestor, thread, row, kind, baseline, kind);
1344
+ if (target.kind === "pull") {
1345
+ const result = await this.collectPullRequest(context.projectId, thread.id, signal);
1346
+ if (!result.ok) throw new GhError(result.reason);
1347
+ }
1348
+ }, signal));
1349
+ await attempt(() => this.stream(repo, "comments", `repos/${repo}/issues/comments?sort=updated&direction=asc`, baseline, async (row) => {
1350
+ const match = /^https:\/\/api\.github\.com\/repos\/([^/]+\/[^/]+)\/issues\/(\d+)$/.exec(text(row.issue_url));
1351
+ if (!match || match[1].toLowerCase() !== repo) throw new GhError("source_repository_mismatch");
1352
+ const thread = await db.thread.findByRef("github", `${repo}:${match[2]}`);
1353
+ if (thread) {
1354
+ await courier.answers(this.answerer, thread, row);
1355
+ await courier.ingest(this.ingestor, thread, row, "comment", baseline, "comment");
1356
+ }
1357
+ }, signal));
1358
+ for (const thread of await db.thread.listByChannel("github")) {
1359
+ if (thread.kind !== "pull" || !thread.url) continue;
1360
+ const ticketIds = await db.ticketThread.listTicketIds(thread.id);
1361
+ if (!ticketIds.length) continue;
1362
+ if (!await courier.polled(ticketIds, thread.updatedAt)) continue;
1363
+ if ((await Promise.all(ticketIds.map((id) => db.ticket.findById(id)))).every((ticket) => !!ticket && ["done", "cancelled"].includes(ticket.status) && !!ticket.prState && ["merged", "closed"].includes(ticket.prState))) continue;
1364
+ await attempt(async () => {
1365
+ const target = resource$1.parse(thread.url);
1366
+ if (target.repository !== repo) return;
1367
+ const root = `repos/${repo}/pulls/${target.number}`;
1368
+ for (const [path, kind] of [["reviews", "review"], ["comments", "review_comment"]]) await attempt(async () => {
1369
+ await this.stream(repo, `pull:${target.number}:${path}`, `${root}/${path}?sort=updated&direction=asc`, baseline, async (row) => {
1370
+ await courier.answers(this.answerer, thread, row);
1371
+ await courier.ingest(this.ingestor, thread, row, "comment", baseline, kind);
1372
+ }, signal);
1373
+ });
1374
+ const result = await this.collectPullRequest(context.projectId, thread.id, signal);
1375
+ if (!result.ok) throw new GhError(result.reason);
1376
+ });
1377
+ }
1378
+ if (environment.defaultBranch) await attempt(() => ci$1.branch(this, context.projectId, environment.defaultBranch, signal));
1379
+ }
1380
+ async stream(repository, name, path, baseline, accept, signal) {
1381
+ await courier.stream({
1382
+ channel: "github",
1383
+ scope: repository,
1384
+ name,
1385
+ initial: { since: baseline },
1386
+ read: async (cursor) => {
1387
+ const conditional = cursor.etag && cursor.etagSince === cursor.since ? { "If-None-Match": cursor.etag } : void 0;
1388
+ const value = await this.request(`${path}&since=${encodeURIComponent(cursor.since)}&per_page=100`, signal, "GET", void 0, conditional);
1389
+ if (value && typeof value === "object" && value.notModified) return {
1390
+ rows: [],
1391
+ notModified: true
1392
+ };
1393
+ return {
1394
+ rows: array(value).map(record),
1395
+ notModified: false
1396
+ };
1397
+ },
1398
+ advance: (cursor, rows) => {
1399
+ const newest = Math.max(...rows.map((row) => Date.parse(timestamp(row.updated_at))).filter(Number.isFinite));
1400
+ const moved = Number.isFinite(newest) ? (/* @__PURE__ */ new Date(newest - 5e3)).toISOString() : cursor.since;
1401
+ return { since: moved > cursor.since ? moved : cursor.since };
1402
+ },
1403
+ accept,
1404
+ signal
1405
+ });
1406
+ }
1407
+ async ensureThread(target, row) {
1408
+ return recordThread({
1409
+ channel: "github",
1410
+ refId: `${target.repository}:${target.number}`,
1411
+ kind: target.kind,
1412
+ title: text(row.title),
1413
+ url: text(row.html_url),
1414
+ createdAt: timestamp(row.created_at),
1415
+ updatedAt: timestamp(row.updated_at)
1416
+ });
1417
+ }
1418
+ async collectPullRequest(projectId, threadId, signal) {
1419
+ return pull.collect(this, projectId, threadId, signal);
1420
+ }
1421
+ async publish(inboxId, signal) {
1422
+ return courier.publish(this.delivery, inboxId, signal);
1423
+ }
1424
+ async flush(signal) {
1425
+ return courier.flush(this.delivery, signal);
1426
+ }
1427
+ };
1428
+ const github = new GitHubChannel();
1429
+ // src/channel/gitlab/runner.ts
1430
+ var GitLabError = class extends ChannelError {};
1431
+ var FetchGitLabRunner = class {
1432
+ async request(request) {
1433
+ if (request.signal?.aborted) throw new GitLabError("interrupted");
1434
+ const configured = await channel.connection("gitlab");
1435
+ if (!configured?.enabled) throw new GitLabError("channel_disabled");
1436
+ const site = gitlabSite(configured.host);
1437
+ if (request.site !== site || !/^(?:user$|projects(?:\/|$))/.test(request.path) || request.path.includes("\\") || request.path.includes("#") || /[\r\n]/.test(request.path)) throw new GitLabError("scope_denied");
1438
+ const url = new URL(`${site}/api/v4/${request.path}`);
1439
+ if (url.origin !== site || !url.pathname.startsWith("/api/v4/")) throw new GitLabError("scope_denied");
1440
+ const token = configured.token;
1441
+ if (!token?.trim()) throw new GitLabError("not_logged_in");
1442
+ if (request.signal?.aborted) throw new GitLabError("interrupted");
1443
+ const env = await channelProxyEnvironment(url, process.env);
1444
+ const dispatcher = await createRouteDispatcher({ get: (name) => env[name] === void 0 ? void 0 : { value: env[name] } }, { allowH2: false });
1445
+ try {
1446
+ let response;
1447
+ try {
1448
+ response = await fetch(url.href, {
1449
+ dispatcher,
1450
+ method: request.method,
1451
+ headers: {
1452
+ "private-token": token,
1453
+ "accept": "application/json",
1454
+ ...request.body ? { "content-type": "application/json" } : {},
1455
+ ...request.headers
1456
+ },
1457
+ ...request.body ? { body: JSON.stringify(request.body) } : {},
1458
+ redirect: "follow",
1459
+ signal: request.signal ? AbortSignal.any([request.signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
1460
+ });
1461
+ } catch (error) {
1462
+ const cause = error.cause;
1463
+ const detail = [
1464
+ error instanceof Error ? error.message : String(error),
1465
+ cause?.message,
1466
+ cause?.code
1467
+ ].filter(Boolean).join(" / ");
1468
+ throw new GitLabError(request.signal?.aborted ? "interrupted" : `transport_unknown: ${detail.slice(0, 200)}`);
1469
+ }
1470
+ if (response.status === 304) {
1471
+ await response.body?.cancel();
1472
+ return {
1473
+ body: null,
1474
+ etag: response.headers.get("etag") ?? null,
1475
+ notModified: true
1476
+ };
1477
+ }
1478
+ if (!response.ok) {
1479
+ await response.body?.cancel();
1480
+ const retry = response.headers.get("retry-after");
1481
+ const retryAfter = retry && /^\d+$/.test(retry) ? Number(retry) : retry ? Math.max(0, Math.ceil((Date.parse(retry) - Date.now()) / 1e3)) : void 0;
1482
+ throw new GitLabError(response.status === 401 ? "not_logged_in" : response.status === 429 ? "rate_limited" : response.status === 403 ? "forbidden" : response.status === 404 ? "not_found" : response.status >= 400 && response.status < 500 ? "remote_rejected" : "transport_unknown", Number.isFinite(retryAfter) ? retryAfter : void 0);
1483
+ }
1484
+ let body;
1485
+ try {
1486
+ body = await response.json();
1487
+ } catch {
1488
+ throw new GitLabError("invalid_response");
1489
+ }
1490
+ return request.withEtag ? {
1491
+ body,
1492
+ etag: response.headers.get("etag") ?? null
1493
+ } : body;
1494
+ } finally {
1495
+ await dispatcher.close();
1496
+ }
1497
+ }
1498
+ };
1499
+ function gitlabSite(host) {
1500
+ let url;
1501
+ try {
1502
+ url = new URL(host ?? "https://gitlab.com");
1503
+ } catch {
1504
+ throw new GitLabError("invalid_channel_host");
1505
+ }
1506
+ if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) throw new GitLabError("invalid_channel_host");
1507
+ return url.origin;
1508
+ }
1509
+ // src/channel/gitlab/service/resource.ts
1510
+ const resource = defineService({
1511
+ remote(remoteUrl, host) {
1512
+ if (!remoteUrl) return null;
1513
+ const site = gitlabSite(host);
1514
+ const configured = new URL(site);
1515
+ const scp = /^git@([^/:]+):(.+)$/.exec(remoteUrl);
1516
+ if (scp) {
1517
+ if (scp[1].toLowerCase() !== configured.hostname || configured.port) return null;
1518
+ const repository = resource.path(scp[2].replace(/\.git$/, ""));
1519
+ return repository ? {
1520
+ site,
1521
+ repository
1522
+ } : null;
1523
+ }
1524
+ try {
1525
+ const url = new URL(remoteUrl);
1526
+ if (!["https:", "ssh:"].includes(url.protocol) || url.hostname !== configured.hostname || url.password || url.search || url.hash || (url.protocol === "https:" ? url.origin !== site || Boolean(url.username) : Boolean(url.port) || Boolean(url.username && url.username !== "git"))) return null;
1527
+ const repository = resource.path(url.pathname.replace(/^\//, "").replace(/\/$/, "").replace(/\.git$/, ""));
1528
+ return repository ? {
1529
+ site,
1530
+ repository
1531
+ } : null;
1532
+ } catch {
1533
+ return null;
1534
+ }
1535
+ },
1536
+ path(value) {
1537
+ const segments = value.split("/");
1538
+ return segments.length >= 2 && segments.every((segment) => /^\w[\w.-]*$/.test(segment) && segment !== "." && segment !== "..") ? value : null;
1539
+ },
1540
+ parse(value, site) {
1541
+ const short = /^gitlab:([^:]+):(issue|pull|mr):([1-9]\d*)$/.exec(value);
1542
+ if (short) {
1543
+ const repository = resource.path(short[1]);
1544
+ const number = Number(short[3]);
1545
+ if (repository && Number.isSafeInteger(number)) return {
1546
+ site,
1547
+ repository,
1548
+ kind: short[2] === "issue" ? "issue" : "pull",
1549
+ number
1550
+ };
1551
+ throw new GitLabError("invalid_resource");
1552
+ }
1553
+ let url;
1554
+ try {
1555
+ url = new URL(value.startsWith("gitlab/") ? `${site}/${value.slice(7)}` : value);
1556
+ } catch {
1557
+ throw new GitLabError("invalid_resource");
1558
+ }
1559
+ const match = /^\/(.+?)(?:\/-\/(issues|work_items|merge_requests)|\/(issues|merge_requests))\/([1-9]\d*)\/?$/.exec(url.pathname);
1560
+ const repository = match && resource.path(match[1]);
1561
+ const number = Number(match?.[4]);
1562
+ if (url.origin !== site || url.protocol !== "https:" || url.username || url.password || url.search || url.hash && !/^#note_[1-9]\d*$/.test(url.hash) || !repository || !Number.isSafeInteger(number)) throw new GitLabError("invalid_resource");
1563
+ return {
1564
+ site,
1565
+ repository,
1566
+ kind: (match[2] ?? match[3]) === "merge_requests" ? "pull" : "issue",
1567
+ number
1568
+ };
1569
+ },
1570
+ source(target) {
1571
+ return `${target.site}/${target.repository}`;
1572
+ },
1573
+ url(target) {
1574
+ return `${resource.source(target)}/${target.kind === "issue" ? "issues" : "merge_requests"}/${target.number}`;
1575
+ },
1576
+ apiRoot(target) {
1577
+ return `projects/${encodeURIComponent(target.repository)}/${target.kind === "issue" ? "issues" : "merge_requests"}/${target.number}`;
1578
+ },
1579
+ validateTopic(row, target) {
1580
+ const remote = resource.parse(text(row.web_url), target.site);
1581
+ if (number(row.iid) !== target.number || resource.url(remote) !== resource.url(target)) throw new GitLabError("source_repository_mismatch");
1582
+ },
1583
+ validateNote(row, target) {
1584
+ identity(row.id);
1585
+ if (row.noteable_iid !== void 0 && number(row.noteable_iid) !== target.number) throw new GitLabError("source_repository_mismatch");
1586
+ if (row.noteable_type !== void 0 && row.noteable_type !== (target.kind === "issue" ? "Issue" : "MergeRequest")) throw new GitLabError("source_repository_mismatch");
1587
+ if (row.web_url !== void 0 && resource.url(resource.parse(text(row.web_url), target.site)) !== resource.url(target)) throw new GitLabError("source_repository_mismatch");
1588
+ },
1589
+ item(row, kind, target) {
1590
+ if (kind === "comment") resource.validateNote(row, target);
1591
+ return {
1592
+ id: identity(row.id),
1593
+ kind,
1594
+ actor: text(record(row.author).username),
1595
+ body: typeof row.body === "string" ? row.body : typeof row.description === "string" ? row.description : typeof row.state === "string" ? row.state : "",
1596
+ url: kind === "comment" ? `${resource.url(target)}#note_${identity(row.id)}` : text(row.web_url),
1597
+ createdAt: timestamp(row.created_at),
1598
+ updatedAt: timestamp(row.updated_at ?? row.created_at)
1599
+ };
1600
+ },
1601
+ answers(body) {
1602
+ const answers = /* @__PURE__ */ new Map();
1603
+ const conflicts = /* @__PURE__ */ new Set();
1604
+ for (const line of answerLines(body)) {
1605
+ if (!/^answer[ \t]/i.test(line)) continue;
1606
+ const content = line.slice(7).trim();
1607
+ const separator = content.indexOf(": ");
1608
+ if (separator < 1) continue;
1609
+ const id = content.slice(0, separator).trim();
1610
+ const answer = content.slice(separator + 2).trim();
1611
+ if (!answer || /\s/.test(id)) continue;
1612
+ if (answers.has(id) && answers.get(id) !== answer) conflicts.add(id);
1613
+ answers.set(id, answer);
1614
+ }
1615
+ return {
1616
+ answers,
1617
+ conflicts
1618
+ };
1619
+ }
1620
+ });
1621
+ // src/channel/gitlab/service/ci.ts
1622
+ const ci = defineService({
1623
+ async branch(remote, projectId, branch, signal) {
1624
+ const project = await remote.project(projectId);
1625
+ const site = await remote.site();
1626
+ const target = resource.remote(project.remoteUrl, site);
1627
+ if (!target) return;
1628
+ const path = `projects/${encodeURIComponent(target.repository)}/pipelines?ref=${encodeURIComponent(branch)}&per_page=1`;
1629
+ const latest = array(await remote.request(site, path, signal)).map(record)[0];
1630
+ if (!latest) return;
1631
+ const state = text(latest.status);
1632
+ const head = text(latest.sha);
1633
+ await notifyBranchCi({
1634
+ channel: "gitlab",
1635
+ projectId,
1636
+ ref: `${target.repository}:branch:${branch}`,
1637
+ fingerprint: digest({
1638
+ state,
1639
+ head
1640
+ }),
1641
+ head,
1642
+ title: `CI ${branch}`,
1643
+ message: `${branch} CI ${state}`,
1644
+ url: text(latest.web_url),
1645
+ silent: [
1646
+ "success",
1647
+ "skipped",
1648
+ "manual"
1649
+ ].includes(state)
1650
+ });
1651
+ },
1652
+ async activeBranches(remote, site, repository, signal) {
1653
+ const path = `projects/${encodeURIComponent(repository)}/merge_requests?state=opened&per_page=100`;
1654
+ const rows = array(await remote.request(site, path, signal)).map(record);
1655
+ return [...new Set(rows.map((row) => text(row.source_branch)).filter(Boolean))];
1656
+ },
1657
+ async defaultBranch(remote, site, repository, signal) {
1658
+ const row = record(await remote.request(site, `projects/${encodeURIComponent(repository)}`, signal));
1659
+ return (typeof row.default_branch === "string" ? row.default_branch.trim() : "") || null;
1660
+ }
1661
+ });
1662
+ // src/channel/gitlab/service/binding.ts
1663
+ const binding = defineService({ of(channel) {
1664
+ return {
1665
+ collect: collectPort(channel),
1666
+ delivery: deliveryPort(channel),
1667
+ ingest: ingestPort(),
1668
+ answer: answerPort(channel)
1669
+ };
1670
+ } });
1671
+ function collectPort(channel) {
1672
+ return {
1673
+ channel: "gitlab",
1674
+ detail: true,
1675
+ status: false,
1676
+ scope: (project) => channel.scopeOf(project),
1677
+ project: (projectId) => channel.project(projectId),
1678
+ probe: (projectId, signal) => channel.probe(projectId, signal),
1679
+ collect: (context, signal) => channel.collectProject(context, signal),
1680
+ collectBranch: (projectId, branch, signal) => ci.branch(channel, projectId, branch, signal),
1681
+ onFailure: (project, reason) => console.error(`[gitlab:collect] ${project.name} ${project.remoteUrl} -> ${reason}`)
1682
+ };
1683
+ }
1684
+ function deliveryPort(channel) {
1685
+ return {
1686
+ channel: "gitlab",
1687
+ detail: true,
1688
+ parse: async (value) => resource.parse(value, await channel.site()),
1689
+ scope: (target) => resource.source(target),
1690
+ projectFor: (target) => channel.projectForRepository(resource.source(target)),
1691
+ probe: (projectId, signal) => channel.probe(projectId, signal),
1692
+ comments: async (target, signal) => (await channel.pages(target.site, `${resource.apiRoot(target)}/notes`, signal)).rows,
1693
+ authorId: (row) => {
1694
+ const author = record(row.author);
1695
+ return author.id != null ? identity(author.id) : null;
1696
+ },
1697
+ body: (row) => typeof row.body === "string" ? row.body : "",
1698
+ post: async (target, body, signal) => record(await channel.request(target.site, `${resource.apiRoot(target)}/notes`, signal, "POST", { body })),
1699
+ commentUrl: (row, target) => {
1700
+ resource.validateNote(row, target);
1701
+ return `${resource.url(target)}#note_${identity(row.id)}`;
1702
+ },
1703
+ askPrompt: (row) => `${row.message}\n\n问题编号:${row.id}\n请回复:answer ${row.id}: 你的回答`,
1704
+ skipReasons: ["project_unavailable"]
1705
+ };
1706
+ }
1707
+ function ingestPort() {
1708
+ return {
1709
+ channel: "gitlab",
1710
+ bots: async () => (await db.channelAccount.findByChannel("gitlab")).filter((account) => account.role === "bot"),
1711
+ actor: (row) => text(record(row.author).username),
1712
+ human: (row, bots) => {
1713
+ const author = record(row.author);
1714
+ const login = text(author.username);
1715
+ return author.bot !== true && row.system !== true && !bots.some((bot) => bot.name.toLowerCase() === login.toLowerCase());
1716
+ },
1717
+ body: (row) => typeof row.body === "string" ? row.body : typeof row.description === "string" ? row.description : typeof row.state === "string" ? row.state : "",
1718
+ url: (row, sourceKind, thread) => sourceKind === "note" ? `${thread.url}#note_${identity(row.id)}` : text(row.web_url),
1719
+ ref: (row) => typeof row.source_branch === "string" ? row.source_branch : null,
1720
+ at: (row) => timestamp(row.updated_at ?? row.created_at),
1721
+ createdAt: (row) => timestamp(row.created_at),
1722
+ mentioned: (body, bots) => bots.some((bot) => new RegExp(`(?:^|[^a-z0-9_@])@${escapeRegex(bot.name)}(?![a-z0-9_.-])`, "i").test(body))
1723
+ };
1724
+ }
1725
+ function answerPort(channel) {
1726
+ return {
1727
+ channel: "gitlab",
1728
+ admin: async (row) => {
1729
+ const author = record(row.author);
1730
+ const login = text(author.username);
1731
+ const accounts = await db.channelAccount.findByChannel("gitlab");
1732
+ if (author.bot === true || row.system === true || accounts.some((account) => account.role === "bot" && account.name.toLowerCase() === login.toLowerCase())) return false;
1733
+ return (await setting.load()).administrators.some((name) => name.toLowerCase() === login.toLowerCase());
1734
+ },
1735
+ parse: async (body) => resource.answers(body),
1736
+ scope: async (thread) => resource.source(resource.parse(thread.url, await channel.site()))
1737
+ };
1738
+ }
1739
+ // src/channel/gitlab/service/merge-request.ts
1740
+ const mergeRequest = defineService({ async observe(remote, projectId, thread, row) {
1741
+ const target = resource.parse(thread.url, await remote.site());
1742
+ if (target.kind !== "pull") return;
1743
+ resource.validateTopic(row, target);
1744
+ const state = row.state === "merged" ? "merged" : row.state === "closed" ? "closed" : row.state === "opened" ? "open" : null;
1745
+ if (!state) throw new GitLabError("invalid_response");
1746
+ const branch = typeof row.source_branch === "string" ? text(row.source_branch) : null;
1747
+ const worker = branch ? await db.worker.findByBranch(branch) : void 0;
1748
+ const owned = worker && await db.ticket.findById(worker.ticketId);
1749
+ if (owned?.projectId === projectId && (!owned.prUrl || owned.prUrl === thread.url)) {
1750
+ await db.ticketThread.link(owned.id, thread.id, now());
1751
+ await db.ticket.setPullRequest(owned.id, thread.url, state, owned.ciState);
1752
+ }
1753
+ for (const ticketId of await db.ticketThread.listTicketIds(thread.id)) {
1754
+ const ticket = await db.ticket.findById(ticketId);
1755
+ if (!ticket || ticket.projectId !== projectId || ticket.prUrl !== thread.url || ["done", "cancelled"].includes(ticket.status)) continue;
1756
+ await db.ticket.setPullRequest(ticketId, thread.url, state, ticket.ciState);
1757
+ }
1758
+ if (state === "open") return;
1759
+ await remote.threadClosed(projectId, thread, state, timestamp(row.merged_at ?? row.closed_at ?? row.updated_at), branch);
1760
+ } });
1761
+ // src/channel/gitlab/channel.ts
1762
+ const INITIAL_CURSOR = { since: "1970-01-01T00:00:00.000Z" };
1763
+ var GitLabChannel = class {
1764
+ runner;
1765
+ ports;
1766
+ constructor(runner = new FetchGitLabRunner()) {
1767
+ this.runner = runner;
1768
+ this.ports = binding.of(this);
1769
+ }
1770
+ async site() {
1771
+ return gitlabSite((await db.channel.findById("gitlab"))?.host ?? null);
1772
+ }
1773
+ async normalize(value) {
1774
+ return resource.url(resource.parse(value, await this.site()));
1775
+ }
1776
+ async readable(value) {
1777
+ try {
1778
+ await this.normalize(value);
1779
+ return true;
1780
+ } catch {
1781
+ return false;
1782
+ }
1783
+ }
1784
+ async request(site, path, signal, method = "GET", body) {
1785
+ signal?.throwIfAborted();
1786
+ return this.runner.request({
1787
+ site,
1788
+ path,
1789
+ method,
1790
+ body,
1791
+ signal
1792
+ });
1793
+ }
1794
+ async project(projectId) {
1795
+ const project$1 = (await project.list()).find((project) => project.id === projectId);
1796
+ if (!project$1 || !resource.remote(project$1.remoteUrl, await this.site())) throw new GitLabError("unknown_repository");
1797
+ if (!project$1.enabled) throw new GitLabError("project_disabled");
1798
+ if (project$1.available === false) throw new GitLabError("project_unavailable");
1799
+ return project$1;
1800
+ }
1801
+ async projectForRepository(repository) {
1802
+ const site = await this.site();
1803
+ const matches = (await project.list()).filter((project) => {
1804
+ const remote = resource.remote(project.remoteUrl, site);
1805
+ return remote && resource.source(remote) === repository && project.available !== false;
1806
+ });
1807
+ if (matches.length !== 1) throw new GitLabError(matches.length ? "ambiguous_repository" : "unknown_repository");
1808
+ return matches[0];
1809
+ }
1810
+ async scopeOf(project$2) {
1811
+ const current = "available" in project$2 ? project$2 : (await project.list()).find((row) => row.id === project$2.id);
1812
+ if (!current || current.available === false) return null;
1813
+ const target = resource.remote(current.remoteUrl, await this.site());
1814
+ return target ? resource.source(target) : null;
1815
+ }
1816
+ async probe(projectId, signal) {
1817
+ const project = await this.project(projectId);
1818
+ const channel = await db.channel.findById("gitlab");
1819
+ if (!channel?.enabled) throw new GitLabError("channel_disabled");
1820
+ const site = gitlabSite(channel.host);
1821
+ const target = resource.remote(project.remoteUrl, site);
1822
+ const bots = (await db.channelAccount.findByRole("gitlab", "bot")).filter((account) => account.status === "online");
1823
+ const account = record(await this.request(site, "user", signal));
1824
+ const providerId = identity(account.id);
1825
+ const login = text(account.username);
1826
+ if (!bots.some((bot) => bot.name.toLowerCase() === login.toLowerCase()) || account.state !== void 0 && account.state !== "active") throw new GitLabError("account_mismatch");
1827
+ const remote = record(await this.request(site, `projects/${encodeURIComponent(target.repository)}`, signal));
1828
+ if (text(remote.path_with_namespace) !== target.repository || resource.source(resource.remote(text(remote.web_url), site) ?? {
1829
+ site: "",
1830
+ repository: ""
1831
+ }) !== resource.source(target)) throw new GitLabError("repository_mismatch");
1832
+ const result = {
1833
+ providerId,
1834
+ login,
1835
+ repositoryId: identity(remote.id)
1836
+ };
1837
+ const previous = await courier.state("gitlab", resource.source(target), "verified_environment");
1838
+ if (previous && (previous.providerId !== providerId || previous.repositoryId !== result.repositoryId)) throw new GitLabError("environment_identity_changed");
1839
+ await courier.record("gitlab", resource.source(target), "verified_environment", result);
1840
+ return result;
1841
+ }
1842
+ async requestValue(site, path, signal, headers) {
1843
+ const value = await this.runner.request({
1844
+ site,
1845
+ method: "GET",
1846
+ path,
1847
+ withEtag: true,
1848
+ ...headers ? { headers } : {},
1849
+ ...signal ? { signal } : {}
1850
+ });
1851
+ return {
1852
+ body: value?.body ?? null,
1853
+ etag: value?.etag ?? null,
1854
+ notModified: value?.notModified === true
1855
+ };
1856
+ }
1857
+ async pages(site, path, signal, since, etag) {
1858
+ const stamp = since && /\/projects\/[^/]+\/(?:issues|merge_requests)(?:\?|$)/.test(path) ? `&updated_after=${encodeURIComponent(since)}` : "";
1859
+ return courier.pages(async (page) => {
1860
+ const url = `${path + (path.includes("?") ? "&" : "?")}per_page=100&page=${page}${stamp}`;
1861
+ const headers = page === 1 && etag ? { "if-none-match": etag } : void 0;
1862
+ const value = await this.requestValue(site, url, signal, headers);
1863
+ return {
1864
+ rows: array(value.body).map(record),
1865
+ notModified: value.notModified,
1866
+ etag: value.etag
1867
+ };
1868
+ });
1869
+ }
1870
+ async read(value, offset = 0, limit = 50, signal) {
1871
+ const target = resource.parse(value, await this.site());
1872
+ const project = await this.projectForRepository(resource.source(target));
1873
+ await this.probe(project.id, signal);
1874
+ const main = record(await this.request(target.site, resource.apiRoot(target), signal));
1875
+ resource.validateTopic(main, target);
1876
+ const notes = (await this.pages(target.site, `${resource.apiRoot(target)}/notes?sort=asc&order_by=updated_at`, signal)).rows;
1877
+ const items = [resource.item(main, target.kind, target), ...notes.map((row) => resource.item(row, "comment", target)).sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id))];
1878
+ return {
1879
+ ...courier.page(items, offset, limit),
1880
+ next_resource: null
1881
+ };
1882
+ }
1883
+ async harvest(signal) {
1884
+ return courier.harvest(this.ports.collect, signal);
1885
+ }
1886
+ async collect(projectId, branch, signal) {
1887
+ return courier.collect(this.ports.collect, projectId, branch, signal);
1888
+ }
1889
+ async publish(inboxId, signal) {
1890
+ return courier.publish(this.ports.delivery, inboxId, signal);
1891
+ }
1892
+ async flush(signal) {
1893
+ return courier.flush(this.ports.delivery, signal);
1894
+ }
1895
+ advance(_cursor, _rows, startedAt) {
1896
+ return { since: cursorAt(startedAt) };
1897
+ }
1898
+ async collectProject(context, signal) {
1899
+ const site = await this.site();
1900
+ const repository = context.scope;
1901
+ for (const kind of ["issue", "pull"]) await context.attempt(async () => {
1902
+ await courier.stream({
1903
+ channel: "gitlab",
1904
+ scope: repository,
1905
+ name: kind,
1906
+ initial: INITIAL_CURSOR,
1907
+ read: (cursor) => this.pages(site, `projects/${encodeURIComponent(repository)}/${kind === "issue" ? "issues" : "merge_requests"}?state=all&scope=all&order_by=updated_at&sort=asc`, signal, cursor.since, cursor.etag ?? void 0),
1908
+ advance: (cursor, rows, startedAt) => this.advance(cursor, rows, startedAt),
1909
+ accept: async (row) => {
1910
+ const target = {
1911
+ site,
1912
+ repository,
1913
+ kind,
1914
+ number: number(row.iid)
1915
+ };
1916
+ resource.validateTopic(row, target);
1917
+ const thread = await this.ensureThread(target, row);
1918
+ await courier.ingest(this.ports.ingest, thread, row, row.state === "closed" || row.state === "merged" ? "close" : "open", context.baseline, kind);
1919
+ if (kind === "pull") await mergeRequest.observe(this, context.projectId, thread, row);
1920
+ },
1921
+ signal
1922
+ });
1923
+ });
1924
+ for (const thread of await db.thread.listByChannel("gitlab")) {
1925
+ const url = thread.url;
1926
+ if (!url || !["issue", "pull"].includes(thread.kind)) continue;
1927
+ if (!await courier.polled(await db.ticketThread.listTicketIds(thread.id), thread.updatedAt)) continue;
1928
+ await context.attempt(async () => {
1929
+ const target = resource.parse(url, site);
1930
+ if (resource.source(target) !== repository) return;
1931
+ await courier.stream({
1932
+ channel: "gitlab",
1933
+ scope: repository,
1934
+ name: `notes:${target.kind}:${target.number}`,
1935
+ initial: INITIAL_CURSOR,
1936
+ read: (cursor) => this.pages(site, `${resource.apiRoot(target)}/notes?sort=asc&order_by=updated_at`, signal, cursor.since, cursor.etag ?? void 0),
1937
+ advance: (cursor, rows, startedAt) => this.advance(cursor, rows, startedAt),
1938
+ accept: async (row) => {
1939
+ resource.validateNote(row, target);
1940
+ await courier.answers(this.ports.answer, thread, row);
1941
+ await courier.ingest(this.ports.ingest, thread, row, "comment", context.baseline, "note");
1942
+ },
1943
+ signal
1944
+ });
1945
+ });
1946
+ }
1947
+ const branch = await ci.defaultBranch(this, site, repository, signal);
1948
+ if (branch) await this.ciBranch(context, branch, signal);
1949
+ for (const ref of await ci.activeBranches(this, site, repository, signal)) {
1950
+ if (ref === branch) continue;
1951
+ await this.ciBranch(context, ref, signal);
1952
+ }
1953
+ }
1954
+ async ciBranch(context, branch, signal) {
1955
+ try {
1956
+ await ci.branch(this, context.projectId, branch, signal);
1957
+ } catch (error) {
1958
+ if (signal?.aborted) return;
1959
+ context.fail(new GitLabError(`ci:${courier.failure(error, true)}`));
1960
+ }
1961
+ }
1962
+ async ensureThread(target, row) {
1963
+ return recordThread({
1964
+ channel: "gitlab",
1965
+ refId: `${resource.source(target)}:${target.kind}:${target.number}`,
1966
+ kind: target.kind,
1967
+ title: text(row.title),
1968
+ url: text(row.web_url),
1969
+ createdAt: timestamp(row.created_at),
1970
+ updatedAt: timestamp(row.updated_at)
1971
+ });
1972
+ }
1973
+ async threadClosed(projectId, thread, outcome, at, branch) {
1974
+ await closeThread({
1975
+ channel: "gitlab",
1976
+ projectId,
1977
+ thread,
1978
+ outcome,
1979
+ at,
1980
+ branch,
1981
+ closeIssue: async (url) => {
1982
+ const target = resource.parse(url, await this.site());
1983
+ if (target.kind !== "issue") return;
1984
+ await this.request(target.site, resource.apiRoot(target), void 0, "PUT", { state_event: "close" });
1985
+ }
1986
+ });
1987
+ }
1988
+ };
1989
+ const gitlab = new GitLabChannel();
1990
+ // src/ai/_shared/tools/channel.ts
1991
+ const read_channel = defineTool({
1992
+ name: "read_channel",
1993
+ description: "读渠道原文,靠 resource 路径前缀分发。返回 { items, next_offset, next_resource },两条翻页轴都要跟完。",
1994
+ parameters: {
1995
+ resource: {
1996
+ type: "string",
1997
+ required: true,
1998
+ description: "资源路径,前缀决定分发:github/…、gitlab/…、gitlab:<项目>:issue|pull:<编号>、渠道原文 URL、trigger/<id>、thread/<id>、ticket/<id>。"
1999
+ },
2000
+ offset: {
2001
+ type: "integer",
2002
+ description: "从上一次的 next_offset 续读;0 表示重读同一份快照的开头。"
2003
+ },
2004
+ limit: {
2005
+ type: "integer",
2006
+ description: "本次最多返回多少条;省略则用渠道默认值。"
2007
+ }
2008
+ },
2009
+ output: {
2010
+ schema: {
2011
+ type: "string",
2012
+ description: "本条资源的正文分片,末尾附 next_offset / next_resource。"
2013
+ },
2014
+ render: (_args, value) => [{
2015
+ type: "text",
2016
+ text: value
2017
+ }]
2018
+ },
2019
+ execute: async (args, exec) => {
2020
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2021
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
2022
+ const offset = args.offset ?? 0;
2023
+ const limit = args.limit ?? 50;
2024
+ if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error("offset 必须非负,limit 必须在 1–100");
2025
+ const resource = args.resource.startsWith("github/") ? `https://github.com/${args.resource.slice(7)}` : args.resource;
2026
+ const links = identity.role === "worker" && identity.ticketId ? await db.ticketThread.listByTicket(identity.ticketId) : [];
2027
+ const allowedThreads = new Set(links.map((link) => link.threadId));
2028
+ let items;
2029
+ let nextResource = null;
2030
+ if (resource.startsWith("trigger/")) {
2031
+ const trigger = await db.trigger.findById(resource.slice(8));
2032
+ if (!trigger) throw new Error("触发不存在");
2033
+ if (identity.role === "worker" && !allowedThreads.has(trigger.threadId)) throw new Error("Worker 只能读取本任务来源");
2034
+ await markThread(exec, trigger.threadId);
2035
+ items = [trigger];
2036
+ } else if (resource.startsWith("thread/")) {
2037
+ const thread = await db.thread.findById(resource.slice(7));
2038
+ if (!thread) throw new Error("话题不存在");
2039
+ if (identity.role === "worker" && !allowedThreads.has(thread.id)) throw new Error("Worker 只能读取本任务来源");
2040
+ await markThread(exec, thread.id);
2041
+ items = [thread];
2042
+ nextResource = thread.kind !== "ci" ? thread.url : null;
2043
+ } else if (await isThreadId(resource)) {
2044
+ const thread = await db.thread.findById(resource);
2045
+ if (identity.role === "worker" && !allowedThreads.has(thread.id)) throw new Error("Worker 只能读取本任务来源");
2046
+ await markThread(exec, thread.id);
2047
+ items = [thread];
2048
+ nextResource = thread.kind !== "ci" ? thread.url : null;
2049
+ } else if (resource.startsWith("ticket/")) {
2050
+ const ticket = await db.ticket.findById(resource.slice(7));
2051
+ if (!ticket) throw new Error("工单不存在");
2052
+ if (identity.role === "worker" && ticket.id !== identity.ticketId) throw new Error("Worker 只能读取本任务来源");
2053
+ const threads = await db.ticketThread.listByTicket(ticket.id);
2054
+ for (const link of threads) await markThread(exec, link.threadId);
2055
+ items = [ticket, ...threads.map((link) => ({ resource: `thread/${link.threadId}` }))];
2056
+ } else {
2057
+ const isGitHub = resource.startsWith("github:") || (() => {
2058
+ try {
2059
+ const url = new URL(resource);
2060
+ return url.origin === "https://github.com" && !url.username && !url.password;
2061
+ } catch {
2062
+ return false;
2063
+ }
2064
+ })();
2065
+ const isGitLab = !isGitHub && await gitlab.readable(resource);
2066
+ if (!isGitHub && !isGitLab) throw new Error("不支持的渠道资源");
2067
+ const adapter = isGitLab ? gitlab : github;
2068
+ const target = await adapter.normalize(resource);
2069
+ if (identity.role === "worker") {
2070
+ const threads = await Promise.all(links.map((link) => db.thread.findById(link.threadId)));
2071
+ let allowed = false;
2072
+ for (const thread of threads) {
2073
+ if (!thread?.url || thread.channelId !== (isGitLab ? "gitlab" : "github") || identity.projectId && thread.projectId && thread.projectId !== identity.projectId) continue;
2074
+ if (await adapter.readable(thread.url) && await adapter.normalize(thread.url) === target) allowed = true;
2075
+ }
2076
+ if (!allowed) throw new Error("Worker 只能读取本任务来源");
2077
+ }
2078
+ try {
2079
+ const matched = await db.thread.findByRef(isGitLab ? "gitlab" : "github", resource.replace(/^https?:\/\/[^/]+\//, "").replace(/\/pull\//, ":").replace(/\/issues\//, ":"));
2080
+ if (matched) await markThread(exec, matched.id);
2081
+ } catch {}
2082
+ return JSON.stringify(await adapter.read(target, offset, limit));
2083
+ }
2084
+ const page = items.slice(offset, offset + limit);
2085
+ return JSON.stringify({
2086
+ items: page,
2087
+ next_offset: offset + page.length < items.length ? offset + page.length : null,
2088
+ next_resource: nextResource
2089
+ });
2090
+ }
2091
+ });
2092
+ const reply_channel = defineTool({
2093
+ name: "reply_channel",
2094
+ description: "按触发在对应渠道发言。锚点是 triggerId,不用猜发到哪。排队成功不等于送达。",
2095
+ parameters: {
2096
+ triggerId: {
2097
+ type: "string",
2098
+ required: true,
2099
+ description: "要回复的那条触发 id;回复发到这条触发所在的渠道地址。"
2100
+ },
2101
+ text: {
2102
+ type: "string",
2103
+ required: true,
2104
+ description: "发言正文,像人话。渠道的上限由对应 skill 说明。"
2105
+ }
2106
+ },
2107
+ output: {
2108
+ schema: {
2109
+ type: "string",
2110
+ description: "入队结果,例如 queued 或具体状态。"
2111
+ },
2112
+ render: (_args, value) => [{
2113
+ type: "text",
2114
+ text: value
2115
+ }]
2116
+ },
2117
+ execute: async (args, exec) => {
2118
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2119
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
2120
+ const trigger = await db.trigger.findById(args.triggerId);
2121
+ if (!trigger) throw new Error("触发不存在");
2122
+ const thread = await db.thread.findById(trigger.threadId);
2123
+ if (!thread || thread.kind === "ci" || !thread.url) throw new Error("该触发没有可回复地址");
2124
+ requireObserved(exec, thread.id, "reply");
2125
+ if (identity.role === "worker") {
2126
+ if (!identity.ticketId || !(await db.ticketThread.listByTicket(identity.ticketId)).some((row) => row.threadId === thread.id)) throw new Error("Worker 只能回复本任务来源");
2127
+ await db.ticket.requireOpen(identity.ticketId);
2128
+ }
2129
+ if (identity.role === "project" && thread.projectId !== identity.projectId) {
2130
+ if (!(await Promise.all((await db.ticketThread.listByThread(thread.id)).map((link) => db.ticket.findById(link.ticketId)))).some((ticket) => ticket?.projectId === identity.projectId)) throw new Error("触发不属于当前项目");
2131
+ }
2132
+ if ((await db.inbox.listByThread(thread.id)).some((message) => message.triggerId === trigger.id && message.origin !== identity.role)) return JSON.stringify({
2133
+ status: "suppressed",
2134
+ reason: "another_role_already_replied"
2135
+ });
2136
+ const ticketId = identity.ticketId ?? null;
2137
+ const row = await db.inbox.enqueue({
2138
+ id: replyKey(trigger.id, args.text),
2139
+ type: "user",
2140
+ origin: identity.role,
2141
+ kind: "notice",
2142
+ projectId: identity.projectId ?? thread.projectId,
2143
+ supervisorId: identity.supervisorId ?? null,
2144
+ workerId: identity.workerId ?? null,
2145
+ triggerId: trigger.id,
2146
+ threadId: thread.id,
2147
+ ticketId,
2148
+ message: args.text
2149
+ });
2150
+ return JSON.stringify({
2151
+ id: row.id,
2152
+ status: "queued"
2153
+ });
2154
+ }
2155
+ });
2156
+ // src/ai/_shared/tools/inbox.ts
2157
+ const inbox_list = defineTool({
2158
+ name: "inbox_list",
2159
+ description: "读取当前角色未处理邮件和原渠道任务,包含 pending 和 stalled。读取标为已读但不会完成。",
2160
+ parameters: { detail: {
2161
+ type: "boolean",
2162
+ description: "true 返回完整上下文;默认返回摘要。"
2163
+ } },
2164
+ output: {
2165
+ schema: {
2166
+ type: "string",
2167
+ description: "当前角色未处理邮件。"
2168
+ },
2169
+ render: (_args, value) => [{
2170
+ type: "text",
2171
+ text: value
2172
+ }]
2173
+ },
2174
+ execute: async (args, exec) => {
2175
+ const mailbox = await inbox.read(exec.agent?.session.id ?? "", true);
2176
+ return JSON.stringify(args.detail ? mailbox.messages : mailbox.messages.map((row) => ({
2177
+ id: row.id,
2178
+ kind: row.kind,
2179
+ summary: row.title ?? row.message.split("\n")[0].slice(0, 120)
2180
+ })));
2181
+ }
2182
+ });
2183
+ const read_mailbox = defineTool({
2184
+ name: "read_mailbox",
2185
+ description: "读取当前角色未处理邮件,以及可用项目的 id、仓库地址和本地路径。可传 ids 一次读取指定多条邮件。主编排先用它确定分诊目标;读取标为已读,处理完用 inbox_kill,ask 必须用 answer。",
2186
+ parameters: { ids: {
2187
+ type: "array",
2188
+ items: { type: "string" },
2189
+ description: "只读取这些邮件 id;省略则读取全部未处理邮件。"
2190
+ } },
2191
+ output: {
2192
+ schema: {
2193
+ type: "string",
2194
+ description: "完整角色邮箱,或所选邮件。"
2195
+ },
2196
+ render: (_args, value) => [{
2197
+ type: "text",
2198
+ text: value
2199
+ }]
2200
+ },
2201
+ execute: async (args, exec) => JSON.stringify(await inbox.read(exec.agent?.session.id ?? "", true, args.ids))
2202
+ });
2203
+ const inbox_kill = defineTool({
2204
+ name: "inbox_kill",
2205
+ description: "将自己角色的邮件显式标为 done;未回答的 ask 不能跳过。",
2206
+ parameters: { ids: {
2207
+ type: "array",
2208
+ items: { type: "string" },
2209
+ required: true,
2210
+ description: "已处理邮件的 id。"
2211
+ } },
2212
+ output: {
2213
+ schema: {
2214
+ type: "string",
2215
+ description: "完成数量。"
2216
+ },
2217
+ render: (_args, value) => [{
2218
+ type: "text",
2219
+ text: value
2220
+ }]
2221
+ },
2222
+ execute: async (args, exec) => String(await inbox.complete(exec.agent?.session.id ?? "", args.ids, true))
2223
+ });
2224
+ // src/ai/manager/tools/communicate.ts
2225
+ const report$2 = defineTool({
2226
+ name: "report",
2227
+ description: "向上级报事实:状态 + 一句话摘要。发完继续,不等答复。",
2228
+ parameters: {
2229
+ state: {
2230
+ type: "string",
2231
+ enum: [
2232
+ "progress",
2233
+ "ready",
2234
+ "failed",
2235
+ "dropped"
2236
+ ],
2237
+ required: true,
2238
+ description: "progress 在跑 / ready 干完了 / failed 失败了 / dropped 不用做了。"
2239
+ },
2240
+ summary: {
2241
+ type: "string",
2242
+ required: true,
2243
+ description: "一句话摘要。给机器和面板看,短。"
2244
+ },
2245
+ supervisorId: {
2246
+ type: "string",
2247
+ description: "本票在某个 Supervisor 下且进入终态时必须带,否则那边一直等。不带则报给主编排。"
2248
+ },
2249
+ ticketId: {
2250
+ type: "string",
2251
+ description: "只做溯源,写进 Inbox.ticketId,不参与路由。"
2252
+ }
2253
+ },
2254
+ output: {
2255
+ schema: {
2256
+ type: "string",
2257
+ description: "是否已投递。"
2258
+ },
2259
+ render: (_args, value) => [{
2260
+ type: "text",
2261
+ text: value
2262
+ }]
2263
+ },
2264
+ execute: async (args, exec) => {
2265
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2266
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
2267
+ if (identity.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2268
+ if (args.ticketId) {
2269
+ const ticket = await db.ticket.findById(args.ticketId);
2270
+ if (!ticket || ticket.projectId !== identity.projectId) throw new Error("工单不属于当前项目");
2271
+ }
2272
+ if (args.supervisorId && !await db.supervisor.findById(args.supervisorId)) throw new Error("Supervisor 不存在");
2273
+ return JSON.stringify(await db.inbox.enqueue({
2274
+ type: args.supervisorId ? "supervisor" : "main",
2275
+ projectId: identity.projectId,
2276
+ supervisorId: args.supervisorId ?? null,
2277
+ origin: "project",
2278
+ kind: "ticket",
2279
+ ticketId: args.ticketId ?? null,
2280
+ title: args.state,
2281
+ message: args.summary
2282
+ }));
2283
+ }
2284
+ });
2285
+ const ask$2 = defineTool({
2286
+ name: "ask",
2287
+ description: "向上级提问。发完这条工作线停下,答案到了会被 prompt 回来;会话本身继续处理别的票。",
2288
+ parameters: {
2289
+ question: {
2290
+ type: "string",
2291
+ required: true,
2292
+ description: "要上级回答的问题,一句话说清。"
2293
+ },
2294
+ supervisorId: {
2295
+ type: "string",
2296
+ description: "本票在某个 Supervisor 下时,问题直接进它,不再绕主编排。"
2297
+ },
2298
+ ticketId: {
2299
+ type: "string",
2300
+ description: "只做溯源,写进 Inbox.ticketId,不参与路由。"
2301
+ }
2302
+ },
2303
+ output: {
2304
+ schema: {
2305
+ type: "string",
2306
+ description: "ask 的 id 与投递去向。"
2307
+ },
2308
+ render: (_args, value) => [{
2309
+ type: "text",
2310
+ text: value
2311
+ }]
2312
+ },
2313
+ execute: async (args, exec) => {
2314
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2315
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
2316
+ if (identity.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2317
+ if (args.ticketId) await db.ticket.requireOpen(args.ticketId, identity.projectId);
2318
+ if (args.supervisorId && (await db.supervisor.findById(args.supervisorId))?.status !== "active") throw new Error("Supervisor 不存在或已关闭");
2319
+ return JSON.stringify(await db.inbox.enqueueAsk({
2320
+ type: args.supervisorId ? "supervisor" : "main",
2321
+ projectId: identity.projectId,
2322
+ supervisorId: args.supervisorId ?? null,
2323
+ origin: "project",
2324
+ kind: "ask",
2325
+ ticketId: args.ticketId ?? null,
2326
+ message: args.question
2327
+ }));
2328
+ }
2329
+ });
2330
+ const escalate = defineTool({
2331
+ name: "escalate",
2332
+ description: "把一条已有的 ask 原样上交:问题文本不改,就地改 type 换处理者。",
2333
+ parameters: { askId: {
2334
+ type: "string",
2335
+ required: true,
2336
+ description: "要上交的那条 ask 的 Inbox id。"
2337
+ } },
2338
+ output: {
2339
+ schema: {
2340
+ type: "string",
2341
+ description: "上交后的处理者。"
2342
+ },
2343
+ render: (_args, value) => [{
2344
+ type: "text",
2345
+ text: value
2346
+ }]
2347
+ },
2348
+ execute: async (args, exec) => {
2349
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2350
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
2351
+ if (identity.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2352
+ return JSON.stringify(await db.inbox.escalateScoped(args.askId, {
2353
+ type: "project",
2354
+ projectId: identity.projectId
2355
+ }, (/* @__PURE__ */ new Date()).toISOString()));
2356
+ }
2357
+ });
2358
+ // src/ai/manager/tools/supervisor.ts
2359
+ const supervisor_list$1 = defineTool({
2360
+ name: "supervisor_list",
2361
+ description: "看 Supervisor:本项目相关的给明细,其余只给数量。",
2362
+ parameters: { status: {
2363
+ type: "string",
2364
+ enum: ["active", "closed"],
2365
+ description: "只看在协调中的或已收工的;省略表示只看 active。"
2366
+ } },
2367
+ output: {
2368
+ schema: {
2369
+ type: "string",
2370
+ description: "本项目那一张展开全部字段;其他 Supervisor 只给条数。"
2371
+ },
2372
+ render: (_args, value) => [{
2373
+ type: "text",
2374
+ text: value
2375
+ }]
2376
+ },
2377
+ execute: async (args, exec) => {
2378
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2379
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
2380
+ if (identity.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2381
+ const rows = await db.supervisor.listByStatus(args.status ?? "active");
2382
+ const result = [];
2383
+ let others = 0;
2384
+ for (const row of rows) {
2385
+ const tickets = await Promise.all((await db.supervisorTicket.listBySupervisor(row.id)).map((link) => db.ticket.findById(link.ticketId)));
2386
+ if (tickets.some((ticket) => ticket?.projectId === identity.projectId)) result.push({
2387
+ ...row,
2388
+ tickets
2389
+ });
2390
+ else others++;
2391
+ }
2392
+ return JSON.stringify({
2393
+ supervisors: result,
2394
+ others
2395
+ });
2396
+ }
2397
+ });
2398
+ // src/ai/manager/tools/ticket.ts
2399
+ const list_ticket$2 = defineTool({
2400
+ name: "list_ticket",
2401
+ description: "列本项目的任务。判重时必看。",
2402
+ parameters: {
2403
+ status: {
2404
+ type: "string",
2405
+ enum: [
2406
+ "waiting",
2407
+ "queued",
2408
+ "running",
2409
+ "review",
2410
+ "done",
2411
+ "cancelled"
2412
+ ],
2413
+ description: "只看某个状态;省略表示不含已终态的票。"
2414
+ },
2415
+ attentionOnly: {
2416
+ type: "boolean",
2417
+ description: "true 时只返回存在指向它的 pending ask 的票。"
2418
+ }
2419
+ },
2420
+ output: {
2421
+ schema: {
2422
+ type: "string",
2423
+ description: "本项目任务列表:id、标题、状态、PR 状态、有无 pending ask。"
2424
+ },
2425
+ render: (_args, value) => [{
2426
+ type: "text",
2427
+ text: value
2428
+ }]
2429
+ },
2430
+ execute: async (args, exec) => {
2431
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2432
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
2433
+ if (identity.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2434
+ return JSON.stringify(await db.ticket.listFiltered({
2435
+ ...args,
2436
+ projectId: identity.projectId
2437
+ }));
2438
+ }
2439
+ });
2440
+ const link_ticket$1 = defineTool({
2441
+ name: "link_ticket",
2442
+ description: "建一张工单到另一张工单的关联。限本项目;跨项目依赖由 Supervisor 的 link_dependency 记。",
2443
+ parameters: {
2444
+ ticketId: {
2445
+ type: "string",
2446
+ required: true,
2447
+ description: "发起关联的票,必须是本项目的。"
2448
+ },
2449
+ relatedId: {
2450
+ type: "string",
2451
+ required: true,
2452
+ description: "被指向的那张票。"
2453
+ },
2454
+ kind: {
2455
+ type: "string",
2456
+ enum: ["depends", "relates"],
2457
+ required: true,
2458
+ description: "depends 前置依赖:relatedId 没做完,ticketId 停在 waiting。relates 只是相关,谁都不等谁。"
2459
+ }
2460
+ },
2461
+ output: {
2462
+ schema: {
2463
+ type: "string",
2464
+ description: "关联结果。"
2465
+ },
2466
+ render: (_args, value) => [{
2467
+ type: "text",
2468
+ text: value
2469
+ }]
2470
+ },
2471
+ execute: async (args, exec) => {
2472
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2473
+ if (identity?.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2474
+ const ticket = await db.ticket.requireOpen(args.ticketId, identity.projectId);
2475
+ const related = await db.ticket.findById(args.relatedId);
2476
+ if (!related || related.projectId !== identity.projectId) throw new Error("跨项目关联应由 Supervisor 处理");
2477
+ if (ticket.id === related.id) throw new Error("工单不能关联自己");
2478
+ await db.ticketLink.link(ticket.id, related.id, args.kind, (/* @__PURE__ */ new Date()).toISOString());
2479
+ if (args.kind === "depends" && related.status !== "done" && related.status !== "cancelled") await db.ticket.save(ticket.id, {
2480
+ status: "waiting",
2481
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2482
+ });
2483
+ return JSON.stringify({ linked: true });
2484
+ }
2485
+ });
2486
+ const stop_ticket = defineTool({
2487
+ name: "stop_ticket",
2488
+ description: "按人的明确要求结单为 cancelled。必须绑一条 human=true 的触发 —— 停止是人的决定,不是编排的判断。",
2489
+ parameters: {
2490
+ ticketId: {
2491
+ type: "string",
2492
+ required: true,
2493
+ description: "要停的票。"
2494
+ },
2495
+ triggerId: {
2496
+ type: "string",
2497
+ required: true,
2498
+ description: "人说停的那条触发。必须是 human=true,否则拒绝。"
2499
+ },
2500
+ reason: {
2501
+ type: "string",
2502
+ description: "一句话说明为什么停,写进记录。"
2503
+ }
2504
+ },
2505
+ output: {
2506
+ schema: {
2507
+ type: "string",
2508
+ description: "结单结果。"
2509
+ },
2510
+ render: (_args, value) => [{
2511
+ type: "text",
2512
+ text: value
2513
+ }]
2514
+ },
2515
+ execute: async (args, exec) => {
2516
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2517
+ if (identity?.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2518
+ const ticket = await db.ticket.requireOpen(args.ticketId, identity.projectId);
2519
+ const trigger = await db.trigger.findById(args.triggerId);
2520
+ if (!trigger || trigger.human !== 1) throw new Error("停止工单必须绑定 human=true 的触发");
2521
+ if (!(await db.ticketThread.listByTicket(ticket.id)).some((row) => row.threadId === trigger.threadId)) throw new Error("停止触发不属于当前工单来源");
2522
+ for (const worker of await db.worker.listByTicket(ticket.id)) {
2523
+ if (worker.status === "ended") continue;
2524
+ if (worker.status === "running") await session.cancel(worker.id);
2525
+ await db.worker.end(worker.id, "stopped", (/* @__PURE__ */ new Date()).toISOString());
2526
+ }
2527
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2528
+ await db.ticket.finish(ticket.id, "cancelled", now, now);
2529
+ await db.inbox.returnPendingTicket(ticket.id, args.reason ?? "人类要求停止", now);
2530
+ for (const link of await db.supervisorTicket.listByTicket(ticket.id)) await db.inbox.enqueue({
2531
+ type: "supervisor",
2532
+ supervisorId: link.supervisorId,
2533
+ projectId: ticket.projectId,
2534
+ origin: "project",
2535
+ kind: "ticket",
2536
+ ticketId: ticket.id,
2537
+ title: "dropped",
2538
+ message: args.reason ?? "人类要求停止"
2539
+ });
2540
+ return JSON.stringify({
2541
+ id: ticket.id,
2542
+ status: "cancelled"
2543
+ });
2544
+ }
2545
+ });
2546
+ const retry_ticket = defineTool({
2547
+ name: "retry_ticket",
2548
+ description: "重开卡住的票:结束旧 Worker,开一个新的。只对还开着、卡在 failed 的票有效。",
2549
+ parameters: { ticketId: {
2550
+ type: "string",
2551
+ required: true,
2552
+ description: "要重开的票。已到终态的票不适用 —— 那张只能由插件在人类消息到达时复活。"
2553
+ } },
2554
+ output: {
2555
+ schema: {
2556
+ type: "string",
2557
+ description: "重开结果。"
2558
+ },
2559
+ render: (_args, value) => [{
2560
+ type: "text",
2561
+ text: value
2562
+ }]
2563
+ },
2564
+ execute: async (args, exec) => {
2565
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2566
+ if (identity?.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2567
+ const ticket = await db.ticket.requireOpen(args.ticketId, identity.projectId);
2568
+ const old = (await db.worker.listByTicket(ticket.id)).at(-1);
2569
+ if (!old || old.reportState !== "failed") throw new Error("只允许重试 failed Worker");
2570
+ if (old.status === "running") await session.cancel(old.id);
2571
+ await db.worker.end(old.id, "restarted", (/* @__PURE__ */ new Date()).toISOString());
2572
+ const worker = await db.worker.queue(ticket.id, identity.projectId, old.branch ?? void 0);
2573
+ if (old.branch && old.worktree) await db.worker.update(worker.id, {
2574
+ branch: old.branch,
2575
+ worktree: old.worktree
2576
+ });
2577
+ await db.ticket.setPrepareError(ticket.id, null, (/* @__PURE__ */ new Date()).toISOString());
2578
+ await worker$1.reconcile();
2579
+ return JSON.stringify(await db.worker.findById(worker.id));
2580
+ }
2581
+ });
2582
+ // src/ai/manager/tools/worker.ts
2583
+ const create_worker = defineTool({
2584
+ name: "create_worker",
2585
+ description: "给一张票开 Worker:建 worktree、切分支、起会话一次配好。并发满了就让它留在 queued。",
2586
+ parameters: {
2587
+ ticketId: {
2588
+ type: "string",
2589
+ required: true,
2590
+ description: "要开跑的票,必须是本项目的。"
2591
+ },
2592
+ branch: {
2593
+ type: "string",
2594
+ description: "分支名,省略则用 dsh/<任务号>。末段必须是任务号,PR 归哪张票就靠这个字符串比对。"
2595
+ }
2596
+ },
2597
+ output: {
2598
+ schema: {
2599
+ type: "string",
2600
+ description: "新 Worker 的 id、分支与 worktree 路径。"
2601
+ },
2602
+ render: (_args, value) => [{
2603
+ type: "text",
2604
+ text: value
2605
+ }]
2606
+ },
2607
+ execute: async (args, exec) => {
2608
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2609
+ if (identity?.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2610
+ const worker = await db.worker.queue(args.ticketId, identity.projectId, args.branch);
2611
+ await db.ticket.setPrepareError(args.ticketId, null, (/* @__PURE__ */ new Date()).toISOString());
2612
+ await worker$1.reconcile();
2613
+ return JSON.stringify(await db.worker.findById(worker.id));
2614
+ }
2615
+ });
2616
+ const send = defineTool({
2617
+ name: "send",
2618
+ description: "直接将完整消息交给活跃 Worker,跳过业务排队;只有需要立刻止损才用 interrupt。Worker 没有收件箱。",
2619
+ parameters: {
2620
+ workerId: {
2621
+ type: "string",
2622
+ required: true,
2623
+ description: "目标 Worker。"
2624
+ },
2625
+ text: {
2626
+ type: "string",
2627
+ required: true,
2628
+ description: "要说的话。"
2629
+ },
2630
+ mode: {
2631
+ type: "string",
2632
+ enum: [
2633
+ "queue",
2634
+ "interrupt",
2635
+ "reply"
2636
+ ],
2637
+ required: true,
2638
+ description: "queue 也直接 steer 到最近一步;interrupt 中止当前回合再 steer;reply 回答它的 ask 并直接 steer。"
2639
+ }
2640
+ },
2641
+ output: {
2642
+ schema: {
2643
+ type: "string",
2644
+ description: "投递结果。"
2645
+ },
2646
+ render: (_args, value) => [{
2647
+ type: "text",
2648
+ text: value
2649
+ }]
2650
+ },
2651
+ execute: async (args, exec) => {
2652
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2653
+ if (identity?.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2654
+ const worker = await db.worker.findById(args.workerId);
2655
+ if (!worker) throw new Error("Worker 不存在");
2656
+ const ticket = await db.ticket.findById(worker.ticketId);
2657
+ if (!ticket || ticket.projectId !== identity.projectId) throw new Error("Worker 不属于当前项目");
2658
+ if (worker.status === "ended") throw new Error("Worker 已结束");
2659
+ if (ticket.status === "done" || ticket.status === "cancelled") throw new Error("工单已结束");
2660
+ if (!await session.lookup(worker.id)) throw new Error("Worker 未在运行时加载、已归档或不属于 Supermesh;不能直接发送");
2661
+ if (args.mode === "reply") {
2662
+ const asks = (await db.inbox.listByTicket(ticket.id)).filter((row) => row.workerId === worker.id && row.kind === "ask" && row.status === "pending");
2663
+ if (asks.length !== 1 || !db.inbox.owns(asks[0], {
2664
+ type: "project",
2665
+ projectId: identity.projectId
2666
+ })) throw new Error("reply 必须唯一对应当前项目编排待答的 ask");
2667
+ await db.inbox.answerScoped(asks[0].id, args.text, {
2668
+ type: "project",
2669
+ projectId: identity.projectId
2670
+ }, (/* @__PURE__ */ new Date()).toISOString());
2671
+ await session.send(worker.id, `[Answer ${asks[0].id}] ${args.text}`, "reply", `supermesh:answer:${asks[0].id}`);
2672
+ } else await session.send(worker.id, args.text, args.mode);
2673
+ return JSON.stringify({
2674
+ sent: true,
2675
+ mode: args.mode
2676
+ });
2677
+ }
2678
+ });
2679
+ const view = defineTool({
2680
+ name: "view",
2681
+ description: "读 Worker 会话正文,分片返回。这不是 report —— report 是结构化状态通道。",
2682
+ parameters: {
2683
+ workerId: {
2684
+ type: "string",
2685
+ required: true,
2686
+ description: "要读的 Worker。"
2687
+ },
2688
+ offset: {
2689
+ type: "integer",
2690
+ description: "从上次的 next_offset 续读;0 表示从头读。"
2691
+ }
2692
+ },
2693
+ output: {
2694
+ schema: {
2695
+ type: "string",
2696
+ description: "会话正文分片,末尾附 next_offset。"
2697
+ },
2698
+ render: (_args, value) => [{
2699
+ type: "text",
2700
+ text: value
2701
+ }]
2702
+ },
2703
+ execute: async (args, exec) => {
2704
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2705
+ if (identity?.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2706
+ const worker = await db.worker.findById(args.workerId);
2707
+ if (!worker || (await db.ticket.findById(worker.ticketId))?.projectId !== identity.projectId) throw new Error("Worker 不属于当前项目");
2708
+ if (args.offset !== void 0 && (!Number.isInteger(args.offset) || args.offset < 0)) throw new Error("offset 必须是非负整数");
2709
+ return JSON.stringify(await session.view(worker.id, args.offset));
2710
+ }
2711
+ });
2712
+ const cancel = defineTool({
2713
+ name: "cancel",
2714
+ description: "中止 Worker 当前回合。那一次回合一并作废。",
2715
+ parameters: {
2716
+ workerId: {
2717
+ type: "string",
2718
+ required: true,
2719
+ description: "要中止的 Worker。"
2720
+ },
2721
+ keepInbox: {
2722
+ type: "boolean",
2723
+ description: "true 保留官方 Agent 尚未接收的输入;省略则清除。不涉及业务收件箱。"
2724
+ }
2725
+ },
2726
+ output: {
2727
+ schema: {
2728
+ type: "string",
2729
+ description: "中止结果。"
2730
+ },
2731
+ render: (_args, value) => [{
2732
+ type: "text",
2733
+ text: value
2734
+ }]
2735
+ },
2736
+ execute: async (args, exec) => {
2737
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2738
+ if (identity?.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2739
+ const worker = await db.worker.findById(args.workerId);
2740
+ if (!worker) throw new Error("Worker 不存在");
2741
+ const ticket = await db.ticket.findById(worker.ticketId);
2742
+ if (!ticket || ticket.projectId !== identity.projectId) throw new Error("Worker 不属于当前项目");
2743
+ if (worker.status === "ended") throw new Error("Worker 已结束");
2744
+ await session.cancel(worker.id, args.keepInbox);
2745
+ return JSON.stringify({ cancelled: true });
2746
+ }
2747
+ });
2748
+ const rename = defineTool({
2749
+ name: "rename",
2750
+ description: "改 Worker 会话的标题,方便在会话列表里认出来。",
2751
+ parameters: {
2752
+ workerId: {
2753
+ type: "string",
2754
+ required: true,
2755
+ description: "要改名的 Worker。"
2756
+ },
2757
+ title: {
2758
+ type: "string",
2759
+ required: true,
2760
+ description: "新标题。"
2761
+ }
2762
+ },
2763
+ output: {
2764
+ schema: {
2765
+ type: "string",
2766
+ description: "改名结果。"
2767
+ },
2768
+ render: (_args, value) => [{
2769
+ type: "text",
2770
+ text: value
2771
+ }]
2772
+ },
2773
+ execute: async (args, exec) => {
2774
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2775
+ if (identity?.role !== "project" || !identity.projectId) throw new Error("仅项目编排可调用");
2776
+ const worker = await db.worker.findById(args.workerId);
2777
+ if (!worker) throw new Error("Worker 不存在");
2778
+ const ticket = await db.ticket.findById(worker.ticketId);
2779
+ if (!ticket || ticket.projectId !== identity.projectId) throw new Error("Worker 不属于当前项目");
2780
+ if (worker.status === "ended") throw new Error("Worker 已结束");
2781
+ await session.rename(worker.id, args.title);
2782
+ await db.worker.update(worker.id, { title: args.title });
2783
+ return JSON.stringify({
2784
+ id: worker.id,
2785
+ title: args.title
2786
+ });
2787
+ }
2788
+ });
2789
+ // src/ai/preset.ts
2790
+ function definePreset(definition) {
2791
+ const { tools, ...preset } = definition;
2792
+ return {
2793
+ tools: tools ?? [],
2794
+ preset: {
2795
+ ...preset,
2796
+ plugins: [preset.instruction && {
2797
+ id: "persona",
2798
+ name: "@deepseek-ai/dsh-persona",
2799
+ config: { prefix: preset.instruction }
2800
+ }, ...preset.plugins ?? []].filter(Boolean)
2801
+ }
2802
+ };
2803
+ }
2804
+ // src/ai/manager/index.ts
2805
+ const manager = definePreset({
2806
+ id: "manager",
2807
+ name: "项目编排",
2808
+ description: "一个仓库一个:派 Worker、看汇报、收尾,任务走到哪一步由它推。不写代码。",
2809
+ instruction: composePrompt("manager"),
2810
+ order: 5,
2811
+ tools: [
2812
+ read_channel,
2813
+ reply_channel,
2814
+ read_mailbox,
2815
+ inbox_list,
2816
+ inbox_kill,
2817
+ report$2,
2818
+ ask$2,
2819
+ escalate,
2820
+ supervisor_list$1,
2821
+ list_ticket$2,
2822
+ link_ticket$1,
2823
+ stop_ticket,
2824
+ retry_ticket,
2825
+ create_worker,
2826
+ send,
2827
+ view,
2828
+ cancel,
2829
+ rename
2830
+ ],
2831
+ plugins: [
2832
+ agentInstructions,
2833
+ compaction,
2834
+ commandGoal,
2835
+ skillFilesystem,
2836
+ timeContext,
2837
+ toolBash,
2838
+ toolExecutorPtc,
2839
+ toolFs,
2840
+ toolFsSearch,
2841
+ toolJobs,
2842
+ toolPresent,
2843
+ toolPwsh,
2844
+ toolSkill,
2845
+ toolTodo,
2846
+ toolWeb
2847
+ ]
2848
+ });
2849
+ // src/ai/_shared/tools/communicate.ts
2850
+ const answer = defineTool({
2851
+ name: "answer",
2852
+ description: "回答下面升上来的 ask:填 answer,标 status=done,答案送回发起方。",
2853
+ parameters: {
2854
+ askId: {
2855
+ type: "string",
2856
+ required: true,
2857
+ description: "要回答的那条 ask 的 Inbox id。"
2858
+ },
2859
+ text: {
2860
+ type: "string",
2861
+ required: true,
2862
+ description: "答案正文。发起方会原样收到。"
2863
+ }
2864
+ },
2865
+ output: {
2866
+ schema: {
2867
+ type: "string",
2868
+ description: "是否已回送。"
2869
+ },
2870
+ render: (_args, value) => [{
2871
+ type: "text",
2872
+ text: value
2873
+ }]
2874
+ },
2875
+ execute: async (args, exec) => {
2876
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2877
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
2878
+ if (identity.role === "worker") throw new Error("Worker 没有收件箱");
2879
+ const scope = identity.role === "project" && identity.projectId ? {
2880
+ type: "project",
2881
+ projectId: identity.projectId
2882
+ } : identity.role === "supervisor" && identity.supervisorId ? {
2883
+ type: "supervisor",
2884
+ supervisorId: identity.supervisorId
2885
+ } : identity.role === "main" ? { type: "main" } : null;
2886
+ if (!scope) throw new Error("会话身份不完整");
2887
+ const question = await db.inbox.findById(args.askId);
2888
+ if (question?.origin === "worker") {
2889
+ if (!question.workerId || !await session.lookup(question.workerId)) throw new Error("Worker 未在运行时加载、已归档或不属于 Supermesh;不能直接回答");
2890
+ if ((await db.worker.findById(question.workerId))?.status === "ended") throw new Error("Worker 已结束");
2891
+ }
2892
+ const row = await db.inbox.answerScoped(args.askId, args.text, scope, (/* @__PURE__ */ new Date()).toISOString());
2893
+ if (row.origin === "worker" && row.workerId) await session.send(row.workerId, `[Answer ${row.id}] ${args.text}`, "reply", `supermesh:answer:${row.id}`);
2894
+ return JSON.stringify({
2895
+ id: args.askId,
2896
+ status: "done",
2897
+ delivery: row.origin === "worker" ? "direct" : "queued"
2898
+ });
2899
+ }
2900
+ });
2901
+ // src/ai/_shared/tools/ticket.ts
2902
+ const dispatch_ticket = defineTool({
2903
+ name: "dispatch_ticket",
2904
+ description: "把票派给它的项目编排:写一条 Inbox(type=project, kind=ticket)。",
2905
+ parameters: {
2906
+ ticketId: {
2907
+ type: "string",
2908
+ required: true,
2909
+ description: "要派下去的票。归属由票自己决定,不用另外传项目。"
2910
+ },
2911
+ message: {
2912
+ type: "string",
2913
+ description: "附带给该项目编排的话。派新票时可省;只是提醒或调整时,写清楚要它做什么 —— 只说场景和约束,不要附实现方案。"
2914
+ }
2915
+ },
2916
+ output: {
2917
+ schema: {
2918
+ type: "string",
2919
+ description: "派工结果。"
2920
+ },
2921
+ render: (_args, value) => [{
2922
+ type: "text",
2923
+ text: value
2924
+ }]
2925
+ },
2926
+ execute: async (args, exec) => {
2927
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2928
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
2929
+ if (identity.role !== "main" && identity.role !== "supervisor") throw new Error("仅主编排或 Supervisor 可派票");
2930
+ const ticket = await db.ticket.requireOpen(args.ticketId);
2931
+ if (identity.role === "supervisor" && !(await db.supervisorTicket.listBySupervisor(identity.supervisorId)).some((row) => row.ticketId === ticket.id)) throw new Error("工单不属于当前 Supervisor");
2932
+ return JSON.stringify(await db.inbox.enqueue({
2933
+ type: "project",
2934
+ projectId: ticket.projectId,
2935
+ supervisorId: identity.supervisorId ?? null,
2936
+ origin: identity.role,
2937
+ kind: "ticket",
2938
+ ticketId: ticket.id,
2939
+ message: args.message ?? ticket.title
2940
+ }));
2941
+ }
2942
+ });
2943
+ const note_ticket = defineTool({
2944
+ name: "note_ticket",
2945
+ description: "把在别处得到的事实告诉这张票的项目编排:只传信息,不给授权,不改任何状态。",
2946
+ parameters: {
2947
+ ticketId: {
2948
+ type: "string",
2949
+ required: true,
2950
+ description: "要通知的票。消息进它所属项目编排的收件箱。"
2951
+ },
2952
+ text: {
2953
+ type: "string",
2954
+ required: true,
2955
+ description: "要说的事实,一句话,例如「A 把接口改成了 Y」。只说发生了什么,不要写成任务要求或实现建议。"
2956
+ }
2957
+ },
2958
+ output: {
2959
+ schema: {
2960
+ type: "string",
2961
+ description: "投递结果。"
2962
+ },
2963
+ render: (_args, value) => [{
2964
+ type: "text",
2965
+ text: value
2966
+ }]
2967
+ },
2968
+ execute: async (args, exec) => {
2969
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
2970
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
2971
+ if (identity.role !== "main" && identity.role !== "supervisor") throw new Error("仅主编排或 Supervisor 可通知项目");
2972
+ const ticket = await db.ticket.findById(args.ticketId);
2973
+ if (!ticket) throw new Error("工单不存在");
2974
+ if (identity.role === "supervisor" && !(await db.supervisorTicket.listBySupervisor(identity.supervisorId)).some((row) => row.ticketId === ticket.id)) throw new Error("工单不属于当前 Supervisor");
2975
+ return JSON.stringify(await db.inbox.enqueue({
2976
+ type: "project",
2977
+ projectId: ticket.projectId,
2978
+ supervisorId: identity.supervisorId ?? null,
2979
+ origin: identity.role,
2980
+ kind: "notice",
2981
+ ticketId: ticket.id,
2982
+ message: args.text
2983
+ }));
2984
+ }
2985
+ });
2986
+ // src/ai/orchestrator/tools/communicate.ts
2987
+ const ask_user = defineTool({
2988
+ name: "ask_user",
2989
+ description: "问人。只有主编排能问 —— 它是唯一能触达人类的一层。",
2990
+ parameters: {
2991
+ question: {
2992
+ type: "string",
2993
+ required: true,
2994
+ description: "要人回答的问题。写成人类听得懂的一句话,不要带技术黑话。"
2995
+ },
2996
+ triggerId: {
2997
+ type: "string",
2998
+ description: "问题发到哪个渠道;给了就锚在这条触发上,省略则只留在面板里。"
2999
+ }
3000
+ },
3001
+ output: {
3002
+ schema: {
3003
+ type: "string",
3004
+ description: "ask 的 id 与投递去向。"
3005
+ },
3006
+ render: (_args, value) => [{
3007
+ type: "text",
3008
+ text: value
3009
+ }]
3010
+ },
3011
+ execute: async (args, exec) => {
3012
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3013
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3014
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3015
+ const trigger = args.triggerId ? await db.trigger.findById(args.triggerId) : null;
3016
+ if (args.triggerId && !trigger) throw new Error("触发不存在");
3017
+ const thread = trigger ? await db.thread.findById(trigger.threadId) : null;
3018
+ if (trigger && (!thread || thread.kind === "ci" || !thread.url)) throw new Error("该触发没有可回复地址");
3019
+ const pending = (await db.inbox.listPendingAsk()).find((row) => row.origin === "main" && row.message === args.question && row.triggerId === (args.triggerId ?? null));
3020
+ if (pending) return JSON.stringify({
3021
+ id: pending.id,
3022
+ status: "pending",
3023
+ delivery: pending.triggerId ? "queued" : "panel"
3024
+ });
3025
+ const row = await db.inbox.enqueueAsk({
3026
+ type: "user",
3027
+ origin: "main",
3028
+ kind: "ask",
3029
+ triggerId: trigger?.id ?? null,
3030
+ threadId: thread?.id ?? null,
3031
+ projectId: thread?.projectId ?? null,
3032
+ message: args.question
3033
+ });
3034
+ return JSON.stringify({
3035
+ id: row.id,
3036
+ status: "pending",
3037
+ delivery: row.triggerId ? "queued" : "panel"
3038
+ });
3039
+ }
3040
+ });
3041
+ // src/ai/orchestrator/tools/supervisor.ts
3042
+ const supervisor_list = defineTool({
3043
+ name: "supervisor_list",
3044
+ description: "列全部 Supervisor,字段完整:标题、原因、状态、关联工单、各自进度。",
3045
+ parameters: { status: {
3046
+ type: "string",
3047
+ enum: ["active", "closed"],
3048
+ description: "只看在协调中的或已收工的;省略表示只看 active。"
3049
+ } },
3050
+ output: {
3051
+ schema: {
3052
+ type: "string",
3053
+ description: "Supervisor 列表,含 title / reason / status / 关联工单。"
3054
+ },
3055
+ render: (_args, value) => [{
3056
+ type: "text",
3057
+ text: value
3058
+ }]
3059
+ },
3060
+ execute: async (args, exec) => {
3061
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3062
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3063
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3064
+ const rows = await db.supervisor.listByStatus(args.status ?? "active");
3065
+ return JSON.stringify(await Promise.all(rows.map(async (row) => ({
3066
+ ...row,
3067
+ tickets: await Promise.all((await db.supervisorTicket.listBySupervisor(row.id)).map((link) => db.ticket.findById(link.ticketId)))
3068
+ }))));
3069
+ }
3070
+ });
3071
+ const create_supervisor = defineTool({
3072
+ name: "create_supervisor",
3073
+ description: "跨项目时拉起一个临时协调者:建记录并起会话,把双方上下文写进开场。",
3074
+ parameters: {
3075
+ title: {
3076
+ type: "string",
3077
+ required: true,
3078
+ description: "一句话说明它在协调什么,例如「T-105 需要 B/x 配合」。"
3079
+ },
3080
+ reason: {
3081
+ type: "string",
3082
+ required: true,
3083
+ description: "为什么拉起来,写清卡在哪,方便事后回溯。"
3084
+ },
3085
+ ticketIds: {
3086
+ type: "array",
3087
+ items: { type: "string" },
3088
+ required: true,
3089
+ description: "它协调的那几张票,通常每个项目一张。"
3090
+ }
3091
+ },
3092
+ output: {
3093
+ schema: {
3094
+ type: "string",
3095
+ description: "新 Supervisor 的 id 与关联工单。"
3096
+ },
3097
+ render: (_args, value) => [{
3098
+ type: "text",
3099
+ text: value
3100
+ }]
3101
+ },
3102
+ execute: async (args, exec) => {
3103
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3104
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3105
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3106
+ const ticketIds = [...new Set(args.ticketIds)];
3107
+ if (!ticketIds.length) throw new Error("至少需要一张工单");
3108
+ const tickets = await Promise.all(ticketIds.map((id) => db.ticket.requireOpen(id)));
3109
+ const id = randomUUID();
3110
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3111
+ await db.supervisor.create({
3112
+ id,
3113
+ title: args.title,
3114
+ reason: args.reason,
3115
+ status: "active",
3116
+ sessionId: null,
3117
+ createdAt: now,
3118
+ closedAt: null
3119
+ });
3120
+ for (const ticketId of ticketIds) await db.supervisorTicket.link(id, ticketId, now);
3121
+ const sessionId = await session.create("supervisor", {
3122
+ supervisorId: id,
3123
+ title: args.title
3124
+ });
3125
+ await db.supervisor.attachSession(id, sessionId);
3126
+ await session.send(sessionId, JSON.stringify({
3127
+ title: args.title,
3128
+ reason: args.reason,
3129
+ tickets
3130
+ }), "queue");
3131
+ return JSON.stringify({
3132
+ id,
3133
+ sessionId,
3134
+ ticketIds
3135
+ });
3136
+ }
3137
+ });
3138
+ const close_supervisor = defineTool({
3139
+ name: "close_supervisor",
3140
+ description: "关掉 Supervisor:status=closed,关联工单退回各自项目编排。reason 会原样进每个持票项目编排的收件箱。",
3141
+ parameters: {
3142
+ supervisorId: {
3143
+ type: "string",
3144
+ required: true,
3145
+ description: "要关掉的 Supervisor。"
3146
+ },
3147
+ reason: {
3148
+ type: "string",
3149
+ required: true,
3150
+ description: "为什么关。会原样进每个关联工单所属项目编排的收件箱 —— 它们要凭这句话决定那几张票接下来怎么办。写清是「做完了」还是「不做了、各自收摊」。"
3151
+ }
3152
+ },
3153
+ output: {
3154
+ schema: {
3155
+ type: "string",
3156
+ description: "关闭结果,含通知到哪几个项目编排。"
3157
+ },
3158
+ render: (_args, value) => [{
3159
+ type: "text",
3160
+ text: value
3161
+ }]
3162
+ },
3163
+ execute: async (args, exec) => {
3164
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3165
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3166
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3167
+ const row = await db.supervisor.findById(args.supervisorId);
3168
+ if (!row) throw new Error("Supervisor 不存在");
3169
+ if (row.status === "closed") return JSON.stringify({
3170
+ id: row.id,
3171
+ status: "closed",
3172
+ notified: []
3173
+ });
3174
+ const tickets = await Promise.all((await db.supervisorTicket.listBySupervisor(row.id)).map((link) => db.ticket.findById(link.ticketId)));
3175
+ const projects = [...new Set(tickets.flatMap((ticket) => ticket ? [ticket.projectId] : []))];
3176
+ for (const projectId of projects) await db.inbox.enqueue({
3177
+ id: `supervisor-close:${row.id}:${projectId}`,
3178
+ type: "project",
3179
+ projectId,
3180
+ supervisorId: row.id,
3181
+ origin: "main",
3182
+ kind: "notice",
3183
+ title: row.title,
3184
+ message: `${args.reason}\n${tickets.filter((ticket) => ticket?.projectId === projectId).map((ticket) => ticket.id).join(", ")}`
3185
+ });
3186
+ await db.supervisor.close(row.id, (/* @__PURE__ */ new Date()).toISOString());
3187
+ if (row.sessionId) await archive.session(row.sessionId);
3188
+ return JSON.stringify({
3189
+ id: row.id,
3190
+ status: "closed",
3191
+ notified: projects
3192
+ });
3193
+ }
3194
+ });
3195
+ const attach_tickets_to_supervisor = defineTool({
3196
+ name: "attach_tickets_to_supervisor",
3197
+ description: "扩大 Supervisor 的范围:加关联工单,并自动通知该项目编排。",
3198
+ parameters: {
3199
+ supervisorId: {
3200
+ type: "string",
3201
+ required: true,
3202
+ description: "要扩范围的 Supervisor。"
3203
+ },
3204
+ ticketIds: {
3205
+ type: "array",
3206
+ items: { type: "string" },
3207
+ required: true,
3208
+ description: "要加进去的票。"
3209
+ }
3210
+ },
3211
+ output: {
3212
+ schema: {
3213
+ type: "string",
3214
+ description: "扩范围结果。"
3215
+ },
3216
+ render: (_args, value) => [{
3217
+ type: "text",
3218
+ text: value
3219
+ }]
3220
+ },
3221
+ execute: async (args, exec) => {
3222
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3223
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3224
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3225
+ const row = await db.supervisor.findById(args.supervisorId);
3226
+ if (!row || row.status !== "active") throw new Error("Supervisor 不存在或已关闭");
3227
+ const tickets = await Promise.all([...new Set(args.ticketIds)].map((id) => db.ticket.requireOpen(id)));
3228
+ const existing = await db.supervisorTicket.listBySupervisor(row.id);
3229
+ const added = tickets.filter((ticket) => !existing.some((link) => link.ticketId === ticket.id));
3230
+ for (const ticket of added) await db.supervisorTicket.link(row.id, ticket.id, (/* @__PURE__ */ new Date()).toISOString());
3231
+ for (const projectId of new Set(added.map((ticket) => ticket.projectId))) await db.inbox.enqueue({
3232
+ type: "project",
3233
+ projectId,
3234
+ supervisorId: row.id,
3235
+ origin: "main",
3236
+ kind: "notice",
3237
+ title: row.title,
3238
+ message: `加入 Supervisor ${row.id}: ${added.filter((ticket) => ticket.projectId === projectId).map((ticket) => ticket.id).join(", ")}`
3239
+ });
3240
+ return JSON.stringify({ attached: added.map((ticket) => ticket.id) });
3241
+ }
3242
+ });
3243
+ const detach_tickets_from_supervisor = defineTool({
3244
+ name: "detach_tickets_from_supervisor",
3245
+ description: "缩小 Supervisor 的范围:去掉关联工单,退回原项目,并自动通知该项目编排。**不取消** —— 取消是人的决定。",
3246
+ parameters: {
3247
+ supervisorId: {
3248
+ type: "string",
3249
+ required: true,
3250
+ description: "要缩范围的 Supervisor。"
3251
+ },
3252
+ ticketIds: {
3253
+ type: "array",
3254
+ items: { type: "string" },
3255
+ required: true,
3256
+ description: "要退回原项目的票。"
3257
+ },
3258
+ reason: {
3259
+ type: "string",
3260
+ required: true,
3261
+ description: "为什么摘出来。会进退回票所属项目编排的收件箱 —— 它要凭这句话知道那张票现在归谁管、还要不要继续等。"
3262
+ }
3263
+ },
3264
+ output: {
3265
+ schema: {
3266
+ type: "string",
3267
+ description: "缩范围结果,含通知到哪几个项目编排。"
3268
+ },
3269
+ render: (_args, value) => [{
3270
+ type: "text",
3271
+ text: value
3272
+ }]
3273
+ },
3274
+ execute: async (args, exec) => {
3275
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3276
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3277
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3278
+ const row = await db.supervisor.findById(args.supervisorId);
3279
+ if (!row) throw new Error("Supervisor 不存在");
3280
+ const existing = await db.supervisorTicket.listBySupervisor(row.id);
3281
+ const ids = [...new Set(args.ticketIds)].filter((id) => existing.some((link) => link.ticketId === id));
3282
+ const tickets = await Promise.all(ids.map((id) => db.ticket.findById(id)));
3283
+ for (const ticketId of ids) await db.supervisorTicket.unlink(row.id, ticketId);
3284
+ for (const projectId of new Set(tickets.flatMap((ticket) => ticket ? [ticket.projectId] : []))) await db.inbox.enqueue({
3285
+ type: "project",
3286
+ projectId,
3287
+ supervisorId: row.id,
3288
+ origin: "main",
3289
+ kind: "notice",
3290
+ title: row.title,
3291
+ message: `${args.reason}\n${tickets.filter((ticket) => ticket?.projectId === projectId).map((ticket) => ticket.id).join(", ")}`
3292
+ });
3293
+ return JSON.stringify({ detached: ids });
3294
+ }
3295
+ });
3296
+ // src/ai/orchestrator/tools/thread.ts
3297
+ const triage_thread = defineTool({
3298
+ name: "triage_thread",
3299
+ description: "给一条还没票跟着的话题定归属。判一次就固定,之后不再打扰主编排。",
3300
+ parameters: {
3301
+ threadId: {
3302
+ type: "string",
3303
+ required: true,
3304
+ description: "话题 id,形如 github:42 或 feishu:<chat>:<root>。"
3305
+ },
3306
+ action: {
3307
+ type: "string",
3308
+ enum: ["claim", "ignore"],
3309
+ required: true,
3310
+ description: "claim 归给某个项目;ignore 判为不用处理,之后不投递,除非有人又 @ 了我们。"
3311
+ },
3312
+ projectId: {
3313
+ type: "string",
3314
+ description: "action=claim 时必给:话题归哪个项目。"
3315
+ }
3316
+ },
3317
+ output: {
3318
+ schema: {
3319
+ type: "string",
3320
+ description: "写入后的 triage 结论。"
3321
+ },
3322
+ render: (_args, value) => [{
3323
+ type: "text",
3324
+ text: value
3325
+ }]
3326
+ },
3327
+ execute: async (args, exec) => {
3328
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3329
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3330
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3331
+ const thread = await db.thread.findById(args.threadId);
3332
+ if (!thread) throw new Error("话题不存在");
3333
+ if ((await db.ticketThread.listByThread(thread.id)).length) throw new Error("已有工单订阅的话题不能分诊");
3334
+ if (thread.triage !== "pending") throw new Error("话题已分诊");
3335
+ if (args.action === "claim") {
3336
+ if (!args.projectId || !await db.project.findById(args.projectId)) throw new Error("claim 必须指定存在的 projectId");
3337
+ await db.thread.claim(thread.id, args.projectId, (/* @__PURE__ */ new Date()).toISOString());
3338
+ } else await db.thread.ignore(thread.id, (/* @__PURE__ */ new Date()).toISOString());
3339
+ return JSON.stringify(await db.thread.findById(thread.id));
3340
+ }
3341
+ });
3342
+ const attach_thread_to_ticket = defineTool({
3343
+ name: "attach_thread_to_ticket",
3344
+ description: "让一张已有的票接管一条新话题:建订阅并投递。跨项目也走它。只有消息明确指向那张票才挂。",
3345
+ parameters: {
3346
+ ticketId: {
3347
+ type: "string",
3348
+ required: true,
3349
+ description: "接管这条话题的票。已被人叫停(cancelled)的票挂不上。"
3350
+ },
3351
+ threadId: {
3352
+ type: "string",
3353
+ required: true,
3354
+ description: "要挂上去的话题 id。"
3355
+ },
3356
+ note: {
3357
+ type: "string",
3358
+ description: "一句话路由背景或人给的约束,不要写实现建议,也不要复述原文。"
3359
+ }
3360
+ },
3361
+ output: {
3362
+ schema: {
3363
+ type: "string",
3364
+ description: "挂载结果。"
3365
+ },
3366
+ render: (_args, value) => [{
3367
+ type: "text",
3368
+ text: value
3369
+ }]
3370
+ },
3371
+ execute: async (args, exec) => {
3372
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3373
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3374
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3375
+ const ticket = await db.ticket.findById(args.ticketId);
3376
+ if (!ticket || ticket.status === "cancelled") throw new Error("工单不存在或已 cancelled");
3377
+ const thread = await db.thread.findById(args.threadId);
3378
+ if (!thread) throw new Error("话题不存在");
3379
+ if ((await db.ticketThread.listByTicket(ticket.id)).some((row) => row.threadId === thread.id)) return JSON.stringify({
3380
+ linked: true,
3381
+ existing: true
3382
+ });
3383
+ if (!await db.ticketThread.link(ticket.id, thread.id, (/* @__PURE__ */ new Date()).toISOString())) return JSON.stringify({
3384
+ linked: true,
3385
+ existing: true
3386
+ });
3387
+ await db.inbox.enqueue({
3388
+ type: "project",
3389
+ projectId: ticket.projectId,
3390
+ origin: "main",
3391
+ kind: "ticket",
3392
+ ticketId: ticket.id,
3393
+ threadId: thread.id,
3394
+ message: args.note ?? thread.title
3395
+ });
3396
+ return JSON.stringify({ linked: true });
3397
+ }
3398
+ });
3399
+ const unlink_thread = defineTool({
3400
+ name: "unlink_thread",
3401
+ description: "摘掉挂错的话题,和 attach 严格对称:只删订阅一行,不动话题归属。",
3402
+ parameters: {
3403
+ ticketId: {
3404
+ type: "string",
3405
+ required: true,
3406
+ description: "要摘掉订阅的票。"
3407
+ },
3408
+ threadId: {
3409
+ type: "string",
3410
+ required: true,
3411
+ description: "要摘掉的话题 id。这张票的触发来源那条不许摘。"
3412
+ },
3413
+ reason: {
3414
+ type: "string",
3415
+ required: true,
3416
+ description: "一句话说明为什么不相关,写进记录供回溯。"
3417
+ }
3418
+ },
3419
+ output: {
3420
+ schema: {
3421
+ type: "string",
3422
+ description: "摘除结果。"
3423
+ },
3424
+ render: (_args, value) => [{
3425
+ type: "text",
3426
+ text: value
3427
+ }]
3428
+ },
3429
+ execute: async (args, exec) => {
3430
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3431
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3432
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3433
+ if (!await db.ticket.findById(args.ticketId)) throw new Error("工单不存在");
3434
+ const links = await db.ticketThread.listByTicket(args.ticketId);
3435
+ if (links[0]?.threadId === args.threadId) throw new Error("不能摘掉触发来源话题");
3436
+ if (!links.some((row) => row.threadId === args.threadId)) throw new Error("订阅不存在");
3437
+ await db.ticketThread.unlink(args.ticketId, args.threadId);
3438
+ const ticket = await db.ticket.findById(args.ticketId);
3439
+ await db.inbox.enqueue({
3440
+ type: "project",
3441
+ projectId: ticket.projectId,
3442
+ origin: "main",
3443
+ kind: "notice",
3444
+ ticketId: ticket.id,
3445
+ threadId: args.threadId,
3446
+ message: args.reason
3447
+ });
3448
+ return JSON.stringify({ unlinked: true });
3449
+ }
3450
+ });
3451
+ // src/ai/orchestrator/tools/ticket.ts
3452
+ const create_ticket$1 = defineTool({
3453
+ name: "create_ticket",
3454
+ description: "开一张票。任务一旦存在,projectId 就必须确定。",
3455
+ parameters: {
3456
+ title: {
3457
+ type: "string",
3458
+ required: true,
3459
+ description: "一句话说清要做什么,用发起方的语言。不要加需求、验收标准或实现建议。"
3460
+ },
3461
+ projectId: {
3462
+ type: "string",
3463
+ required: true,
3464
+ description: "这张票归哪个项目。"
3465
+ },
3466
+ threadIds: {
3467
+ type: "array",
3468
+ items: { type: "string" },
3469
+ required: true,
3470
+ description: "触发这张票的话题,至少一条。最早那条是「触发来源」。"
3471
+ },
3472
+ description: {
3473
+ type: "string",
3474
+ description: "需求正文,没有就省略。"
3475
+ }
3476
+ },
3477
+ output: {
3478
+ schema: {
3479
+ type: "string",
3480
+ description: "新票的 id 和状态。"
3481
+ },
3482
+ render: (_args, value) => [{
3483
+ type: "text",
3484
+ text: value
3485
+ }]
3486
+ },
3487
+ execute: async (args, exec) => {
3488
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3489
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3490
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3491
+ return JSON.stringify(await db.ticket.createWithThreads(args.projectId, args.title, args.threadIds, args.description));
3492
+ }
3493
+ });
3494
+ const list_ticket$1 = defineTool({
3495
+ name: "list_ticket",
3496
+ description: "列全部任务,可跨项目筛选。判重、找某张票的现状都靠它。",
3497
+ parameters: {
3498
+ status: {
3499
+ type: "string",
3500
+ enum: [
3501
+ "waiting",
3502
+ "queued",
3503
+ "running",
3504
+ "review",
3505
+ "done",
3506
+ "cancelled"
3507
+ ],
3508
+ description: "只看某个状态;省略表示不含已终态的票。"
3509
+ },
3510
+ projectId: {
3511
+ type: "string",
3512
+ description: "只看某个项目的票。省略表示所有项目。"
3513
+ },
3514
+ attentionOnly: {
3515
+ type: "boolean",
3516
+ description: "true 时只返回存在指向它的 pending ask 的票 —— 也就是需要人介入的那些。"
3517
+ }
3518
+ },
3519
+ output: {
3520
+ schema: {
3521
+ type: "string",
3522
+ description: "任务列表,每张票一行:id、项目、标题、状态、PR 状态、有无 pending ask。"
3523
+ },
3524
+ render: (_args, value) => [{
3525
+ type: "text",
3526
+ text: value
3527
+ }]
3528
+ },
3529
+ execute: async (args, exec) => {
3530
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3531
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3532
+ if (identity.role !== "main") throw new Error("仅主编排可调用");
3533
+ return JSON.stringify(await db.ticket.listFiltered(args));
3534
+ }
3535
+ });
3536
+ // src/ai/orchestrator/index.ts
3537
+ const orchestrator = definePreset({
3538
+ id: "orchestrator",
3539
+ name: "主编排",
3540
+ instruction: composePrompt("orchestrator"),
3541
+ order: 4,
3542
+ tools: [
3543
+ read_channel,
3544
+ reply_channel,
3545
+ answer,
3546
+ read_mailbox,
3547
+ inbox_list,
3548
+ inbox_kill,
3549
+ ask_user,
3550
+ supervisor_list,
3551
+ create_supervisor,
3552
+ close_supervisor,
3553
+ attach_tickets_to_supervisor,
3554
+ detach_tickets_from_supervisor,
3555
+ list_ticket$1,
3556
+ create_ticket$1,
3557
+ dispatch_ticket,
3558
+ note_ticket,
3559
+ triage_thread,
3560
+ attach_thread_to_ticket,
3561
+ unlink_thread
3562
+ ],
3563
+ plugins: [
3564
+ agentInstructions,
3565
+ compaction,
3566
+ commandGoal,
3567
+ skillFilesystem,
3568
+ timeContext,
3569
+ toolBash,
3570
+ toolExecutorPtc,
3571
+ toolFs,
3572
+ toolFsSearch,
3573
+ toolJobs,
3574
+ toolPresent,
3575
+ toolPwsh,
3576
+ toolSkill,
3577
+ toolTodo,
3578
+ toolWeb
3579
+ ]
3580
+ });
3581
+ // src/ai/supervisor/tools/index.ts
3582
+ const list_ticket = defineTool({
3583
+ name: "list_ticket",
3584
+ description: "列自己关联的工单及其进度。每次醒来先看它 —— 不要只信收件箱里那一条转述。",
3585
+ parameters: {},
3586
+ output: {
3587
+ schema: {
3588
+ type: "string",
3589
+ description: "关联工单:id、项目、状态、prState、有无 pending ask。"
3590
+ },
3591
+ render: (_args, value) => [{
3592
+ type: "text",
3593
+ text: value
3594
+ }]
3595
+ },
3596
+ execute: async (args, exec) => {
3597
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3598
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3599
+ if (identity.role !== "supervisor" || !identity.supervisorId) throw new Error("仅 Supervisor 可调用");
3600
+ const links = await db.supervisorTicket.listBySupervisor(identity.supervisorId);
3601
+ return JSON.stringify(await Promise.all(links.map(async (link) => {
3602
+ const ticket = await db.ticket.findById(link.ticketId);
3603
+ if (!ticket) throw new Error("关联工单不存在");
3604
+ return {
3605
+ ...ticket,
3606
+ attention: (await db.inbox.listByTicket(ticket.id)).some((row) => row.kind === "ask" && row.status === "pending")
3607
+ };
3608
+ })));
3609
+ }
3610
+ });
3611
+ const create_ticket = defineTool({
3612
+ name: "create_ticket",
3613
+ description: "在某个项目下开一张票。工单会自动挂到你这个 supervisor 下,受你协调。",
3614
+ parameters: {
3615
+ title: {
3616
+ type: "string",
3617
+ required: true,
3618
+ description: "一句话说清要做什么,用发起方的语言。不要加需求、验收标准或实现建议。"
3619
+ },
3620
+ projectId: {
3621
+ type: "string",
3622
+ required: true,
3623
+ description: "这张票归哪个项目。"
3624
+ },
3625
+ threadIds: {
3626
+ type: "array",
3627
+ items: { type: "string" },
3628
+ required: true,
3629
+ description: "触发这张票的话题,至少一条。最早那条是「触发来源」。"
3630
+ },
3631
+ description: {
3632
+ type: "string",
3633
+ description: "需求正文,没有就省略。"
3634
+ }
3635
+ },
3636
+ output: {
3637
+ schema: {
3638
+ type: "string",
3639
+ description: "新票的 id 和状态。"
3640
+ },
3641
+ render: (_args, value) => [{
3642
+ type: "text",
3643
+ text: value
3644
+ }]
3645
+ },
3646
+ execute: async (args, exec) => {
3647
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3648
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3649
+ if (identity.role !== "supervisor" || !identity.supervisorId) throw new Error("仅 Supervisor 可调用");
3650
+ if (!args.threadIds.length) throw new Error("建票至少要有一条来源话题");
3651
+ for (const threadId of args.threadIds) if (!await db.thread.findById(threadId)) throw new Error("来源话题不存在");
3652
+ const project = await db.project.findById(args.projectId);
3653
+ if (!project) throw new Error("项目不存在");
3654
+ if (!project.enabled) throw new Error("项目未启用");
3655
+ const ticket = await db.ticket.createWithThreads(args.projectId, args.title, args.threadIds, args.description);
3656
+ await db.supervisorTicket.link(identity.supervisorId, ticket.id, (/* @__PURE__ */ new Date()).toISOString());
3657
+ return JSON.stringify({
3658
+ id: ticket.id,
3659
+ status: ticket.status
3660
+ });
3661
+ }
3662
+ });
3663
+ const link_dependency_ticket = defineTool({
3664
+ name: "link_dependency_ticket",
3665
+ description: "记一条跨项目前置依赖。方向是「后来的指向先要做的」。别只记在脑子里 —— 你随时可能被重启。",
3666
+ parameters: {
3667
+ ticketId: {
3668
+ type: "string",
3669
+ required: true,
3670
+ description: "要等的那张票。"
3671
+ },
3672
+ dependsOn: {
3673
+ type: "string",
3674
+ required: true,
3675
+ description: "必须先做完的那张票。"
3676
+ }
3677
+ },
3678
+ output: {
3679
+ schema: {
3680
+ type: "string",
3681
+ description: "依赖记录结果。"
3682
+ },
3683
+ render: (_args, value) => [{
3684
+ type: "text",
3685
+ text: value
3686
+ }]
3687
+ },
3688
+ execute: async (args, exec) => {
3689
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3690
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3691
+ if (identity.role !== "supervisor" || !identity.supervisorId) throw new Error("仅 Supervisor 可调用");
3692
+ const tickets = await Promise.all([args.ticketId, args.dependsOn].map((id) => db.ticket.findById(id)));
3693
+ if (tickets.some((ticket) => !ticket)) throw new Error("工单不存在");
3694
+ await requireScope(identity.supervisorId, tickets.map((ticket) => ticket.projectId));
3695
+ await db.ticket.requireOpen(args.ticketId);
3696
+ if (args.ticketId === args.dependsOn) throw new Error("工单不能依赖自己");
3697
+ await db.ticketLink.link(args.ticketId, args.dependsOn, "depends", (/* @__PURE__ */ new Date()).toISOString());
3698
+ return JSON.stringify({ linked: true });
3699
+ }
3700
+ });
3701
+ const link_ticket = defineTool({
3702
+ name: "link_ticket",
3703
+ description: "记一条相关性关联:两张票有关,但谁都不等谁。限你协调范围内的项目之间。",
3704
+ parameters: {
3705
+ ticketId: {
3706
+ type: "string",
3707
+ required: true,
3708
+ description: "发起关联的票。"
3709
+ },
3710
+ relatedId: {
3711
+ type: "string",
3712
+ required: true,
3713
+ description: "被指向的那张票。"
3714
+ }
3715
+ },
3716
+ output: {
3717
+ schema: {
3718
+ type: "string",
3719
+ description: "关联结果。"
3720
+ },
3721
+ render: (_args, value) => [{
3722
+ type: "text",
3723
+ text: value
3724
+ }]
3725
+ },
3726
+ execute: async (args, exec) => {
3727
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3728
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3729
+ if (identity.role !== "supervisor" || !identity.supervisorId) throw new Error("仅 Supervisor 可调用");
3730
+ if (args.ticketId === args.relatedId) throw new Error("工单不能关联自己");
3731
+ const tickets = await Promise.all([args.ticketId, args.relatedId].map((id) => db.ticket.findById(id)));
3732
+ if (tickets.some((ticket) => !ticket)) throw new Error("工单不存在");
3733
+ await requireScope(identity.supervisorId, tickets.map((ticket) => ticket.projectId));
3734
+ await db.ticketLink.link(args.ticketId, args.relatedId, "relates", (/* @__PURE__ */ new Date()).toISOString());
3735
+ return JSON.stringify({
3736
+ linked: true,
3737
+ kind: "relates"
3738
+ });
3739
+ }
3740
+ });
3741
+ /** 票所属项目必须落在这个 supervisor 的协调范围内(即它已关联票涉及的项目)。 */
3742
+ async function requireScope(supervisorId, projectIds) {
3743
+ const links = await db.supervisorTicket.listBySupervisor(supervisorId);
3744
+ const tickets = await Promise.all(links.map((link) => db.ticket.findById(link.ticketId)));
3745
+ const scope = new Set(tickets.filter(Boolean).map((ticket) => ticket.projectId));
3746
+ for (const projectId of projectIds) if (!scope.has(projectId)) throw new Error("该项目还不在你的协调范围内:先用 create_ticket 在那个项目建票,票会自动挂到名下并带上它的项目");
3747
+ }
3748
+ const report$1 = defineTool({
3749
+ name: "report",
3750
+ description: "报给主编排,不等答复。",
3751
+ parameters: {
3752
+ state: {
3753
+ type: "string",
3754
+ enum: [
3755
+ "progress",
3756
+ "ready",
3757
+ "failed",
3758
+ "dropped"
3759
+ ],
3760
+ required: true,
3761
+ description: "progress 在跑 / ready 做完了 / failed 失败了 / dropped 不用做了。"
3762
+ },
3763
+ summary: {
3764
+ type: "string",
3765
+ required: true,
3766
+ description: "一句话摘要。"
3767
+ }
3768
+ },
3769
+ output: {
3770
+ schema: {
3771
+ type: "string",
3772
+ description: "是否已投递。"
3773
+ },
3774
+ render: (_args, value) => [{
3775
+ type: "text",
3776
+ text: value
3777
+ }]
3778
+ },
3779
+ execute: async (args, exec) => {
3780
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3781
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3782
+ if (identity.role !== "supervisor" || !identity.supervisorId) throw new Error("仅 Supervisor 可调用");
3783
+ return JSON.stringify(await db.inbox.enqueue({
3784
+ type: "main",
3785
+ supervisorId: identity.supervisorId,
3786
+ origin: "supervisor",
3787
+ kind: "notice",
3788
+ title: args.state,
3789
+ message: args.summary
3790
+ }));
3791
+ }
3792
+ });
3793
+ const ask$1 = defineTool({
3794
+ name: "ask",
3795
+ description: "问主编排,这条线停下等答复。要加人、加项目、或需要上级拍板时用它。",
3796
+ parameters: { question: {
3797
+ type: "string",
3798
+ required: true,
3799
+ description: "要主编排回答的问题,一句话说清。"
3800
+ } },
3801
+ output: {
3802
+ schema: {
3803
+ type: "string",
3804
+ description: "ask 的 id。"
3805
+ },
3806
+ render: (_args, value) => [{
3807
+ type: "text",
3808
+ text: value
3809
+ }]
3810
+ },
3811
+ execute: async (args, exec) => {
3812
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3813
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3814
+ if (identity.role !== "supervisor" || !identity.supervisorId) throw new Error("仅 Supervisor 可调用");
3815
+ return JSON.stringify(await db.inbox.enqueueAsk({
3816
+ type: "main",
3817
+ supervisorId: identity.supervisorId,
3818
+ origin: "supervisor",
3819
+ kind: "ask",
3820
+ message: args.question
3821
+ }));
3822
+ }
3823
+ });
3824
+ // src/ai/supervisor/index.ts
3825
+ const supervisor = definePreset({
3826
+ id: "supervisor",
3827
+ name: "临时协调者",
3828
+ instruction: composePrompt("supervisor"),
3829
+ order: 6,
3830
+ tools: [
3831
+ read_channel,
3832
+ answer,
3833
+ read_mailbox,
3834
+ inbox_list,
3835
+ inbox_kill,
3836
+ dispatch_ticket,
3837
+ note_ticket,
3838
+ list_ticket,
3839
+ report$1,
3840
+ ask$1,
3841
+ link_dependency_ticket,
3842
+ link_ticket,
3843
+ create_ticket
3844
+ ],
3845
+ plugins: [
3846
+ agentInstructions,
3847
+ compaction,
3848
+ commandGoal,
3849
+ skillFilesystem,
3850
+ timeContext,
3851
+ toolBash,
3852
+ toolExecutorPtc,
3853
+ toolFs,
3854
+ toolFsSearch,
3855
+ toolJobs,
3856
+ toolPresent,
3857
+ toolPwsh,
3858
+ toolSkill,
3859
+ toolTodo,
3860
+ toolWeb
3861
+ ]
3862
+ });
3863
+ // src/ai/worker/tools/index.ts
3864
+ const report = defineTool({
3865
+ name: "report",
3866
+ description: "报告进度。发完继续干活,不等回复。要对方动脑子的走 ask。",
3867
+ parameters: {
3868
+ state: {
3869
+ type: "string",
3870
+ enum: [
3871
+ "progress",
3872
+ "ready",
3873
+ "failed",
3874
+ "dropped"
3875
+ ],
3876
+ required: true,
3877
+ description: "progress 在跑 / ready 干完了(PR 已开)/ failed 失败了 / dropped 不用做了。「我在等答复」不占状态位。"
3878
+ },
3879
+ summary: {
3880
+ type: "string",
3881
+ required: true,
3882
+ description: "一句话摘要,短。给机器和面板看,详细解释写正文。"
3883
+ }
3884
+ },
3885
+ output: {
3886
+ schema: {
3887
+ type: "string",
3888
+ description: "是否已投递。"
3889
+ },
3890
+ render: (_args, value) => [{
3891
+ type: "text",
3892
+ text: value
3893
+ }]
3894
+ },
3895
+ execute: async (args, exec) => {
3896
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3897
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3898
+ if (identity.role !== "worker" || !identity.workerId || !identity.ticketId) throw new Error("仅 Worker 可调用");
3899
+ const worker = await db.worker.findById(identity.workerId);
3900
+ if (!worker || worker.status === "ended") throw new Error("Worker 已结束");
3901
+ return JSON.stringify(await db.worker.reportProgress(worker.id, args.state, args.summary));
3902
+ }
3903
+ });
3904
+ const ask = defineTool({
3905
+ name: "ask",
3906
+ description: "问项目编排。发完这条工作线停下,等答案被 prompt 回来。不要一边问一边继续做。",
3907
+ parameters: { question: {
3908
+ type: "string",
3909
+ required: true,
3910
+ description: "要问的问题,一句话说清卡在哪。"
3911
+ } },
3912
+ output: {
3913
+ schema: {
3914
+ type: "string",
3915
+ description: "ask 的 id。"
3916
+ },
3917
+ render: (_args, value) => [{
3918
+ type: "text",
3919
+ text: value
3920
+ }]
3921
+ },
3922
+ execute: async (args, exec) => {
3923
+ const identity = await session.resolve(exec.agent?.session.id ?? "");
3924
+ if (!identity) throw new Error("当前会话没有 Supermesh 身份");
3925
+ if (identity.role !== "worker" || !identity.workerId || !identity.ticketId) throw new Error("仅 Worker 可调用");
3926
+ const ticket = await db.ticket.requireOpen(identity.ticketId);
3927
+ const worker = await db.worker.findById(identity.workerId);
3928
+ if (!worker || worker.status === "ended") throw new Error("Worker 已结束");
3929
+ return JSON.stringify(await db.inbox.enqueueAsk({
3930
+ type: "project",
3931
+ projectId: ticket.projectId,
3932
+ origin: "worker",
3933
+ kind: "ask",
3934
+ ticketId: ticket.id,
3935
+ workerId: worker.id,
3936
+ message: args.question
3937
+ }));
3938
+ }
3939
+ });
3940
+ // src/ai/index.ts
3941
+ const agents = {
3942
+ manager,
3943
+ orchestrator,
3944
+ supervisor,
3945
+ worker: definePreset({
3946
+ id: "worker",
3947
+ name: "执行会话",
3948
+ instruction: composePrompt("worker"),
3949
+ order: 7,
3950
+ tools: [
3951
+ read_channel,
3952
+ report,
3953
+ ask
3954
+ ],
3955
+ plugins: [
3956
+ agentInstructions,
3957
+ compaction,
3958
+ commandGoal,
3959
+ delegation,
3960
+ skillFilesystem,
3961
+ timeContext,
3962
+ toolBash,
3963
+ toolExecutorPtc,
3964
+ toolFs,
3965
+ toolFsSearch,
3966
+ toolJobs,
3967
+ toolPresent,
3968
+ toolPwsh,
3969
+ toolSkill,
3970
+ toolTodo,
3971
+ toolWeb
3972
+ ]
3973
+ })
3974
+ };
3975
+ // src/events/agent-created.ts
3976
+ async function handleAgentCreated(ctx, agent) {
3977
+ const id = ctx.agentPresets.composedPreset(agent.ctx);
3978
+ const definition = agents[id];
3979
+ if (definition?.tools.length) ctx.effect(() => agent.ctx.effect(() => {
3980
+ const disposers = definition.tools.map((tool) => agent.ctx.tools.register(tool));
3981
+ return () => disposers.forEach((dispose) => dispose());
3982
+ }, "supermesh:tools"), "supermesh:agent-tools");
3983
+ const role = await session.attach(agent);
3984
+ if (!role) return;
3985
+ if (role === "worker") return;
3986
+ ctx.effect(() => agent.ctx.on("agent/status", ({ status }) => {
3987
+ if (status === "idle") inbox.notify(agent).catch((error) => ctx.logger.error(error));
3988
+ }), "supermesh:mailbox-notice");
3989
+ await inbox.notify(agent, true);
3990
+ }
3991
+ // src/events/session-event.ts
3992
+ async function handleSessionEvent(source, event) {
3993
+ await worker$1.observe(source, event);
3994
+ }
3995
+ // src/runtime/scheduler.ts
3996
+ const RESERVED_KEYS = /* @__PURE__ */ new Set([
3997
+ "id",
3998
+ "cron",
3999
+ "status",
4000
+ "cronSource",
4001
+ "createdAt",
4002
+ "updatedAt",
4003
+ "lastRunAt",
4004
+ "lastError",
4005
+ "runCount",
4006
+ "hasHandler",
4007
+ "nextRunAt"
4008
+ ]);
4009
+ const nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
4010
+ const messageOf = (err) => err instanceof Error ? err.message : String(err);
4011
+ function parseId(val) {
4012
+ if (typeof val === "string" && val.trim()) return val.trim();
4013
+ throw new TypeError("定时任务的 id 不能为空");
4014
+ }
4015
+ const refId = (ref) => parseId(typeof ref === "string" ? ref : ref.id);
4016
+ function parseCron(val, id) {
4017
+ const cron = typeof val === "string" ? val.trim() : "";
4018
+ if (!cron) throw new TypeError(`定时任务 "${id}" 的 cron 不能为空`);
4019
+ try {
4020
+ new Cron(cron, { paused: true }).stop();
4021
+ } catch (e) {
4022
+ throw new Error(`定时任务 "${id}" 的 cron 表达式无效:${cron}`, { cause: e });
4023
+ }
4024
+ return cron;
4025
+ }
4026
+ function pickExtra(input) {
4027
+ const extra = {};
4028
+ for (const [k, v] of Object.entries(input)) if (v !== void 0 && !RESERVED_KEYS.has(k)) extra[k] = v;
4029
+ return extra;
4030
+ }
4031
+ var JsonSchedulerImpl = class {
4032
+ filePath;
4033
+ options;
4034
+ records = /* @__PURE__ */ new Map();
4035
+ hydration;
4036
+ pending = Promise.resolve();
4037
+ saveError;
4038
+ disposed = false;
4039
+ constructor(filePath, options = {}) {
4040
+ this.filePath = resolve(filePath);
4041
+ this.options = options;
4042
+ this.hydration = this.load();
4043
+ }
4044
+ ready = () => this.hydration;
4045
+ use(input, handler) {
4046
+ if (typeof handler !== "function") throw new TypeError("use() 的第二个参数必须是函数");
4047
+ const id = parseId(input.id);
4048
+ const cron = parseCron(input.cron, id);
4049
+ const extra = pickExtra(input);
4050
+ let record = this.records.get(id);
4051
+ if (record) {
4052
+ if (record.cronSource === "use") record.cron = cron;
4053
+ record.handler = handler;
4054
+ Object.assign(record.extra, extra);
4055
+ record.updatedAt = nowIso();
4056
+ } else {
4057
+ const time = nowIso();
4058
+ record = {
4059
+ id,
4060
+ cron,
4061
+ status: "running",
4062
+ cronSource: "use",
4063
+ createdAt: time,
4064
+ updatedAt: time,
4065
+ lastRunAt: null,
4066
+ lastError: null,
4067
+ runCount: 0,
4068
+ extra,
4069
+ handler
4070
+ };
4071
+ this.records.set(id, record);
4072
+ }
4073
+ this.arm(record);
4074
+ this.queueSave();
4075
+ return () => this.remove(id);
4076
+ }
4077
+ update(patch) {
4078
+ const record = this.records.get(parseId(patch.id));
4079
+ if (!record) return false;
4080
+ if (patch.cron !== void 0) {
4081
+ record.cron = parseCron(patch.cron, record.id);
4082
+ record.cronSource = "update";
4083
+ }
4084
+ Object.assign(record.extra, pickExtra(patch));
4085
+ record.updatedAt = nowIso();
4086
+ if (patch.cron !== void 0) this.arm(record);
4087
+ this.queueSave();
4088
+ return true;
4089
+ }
4090
+ remove(ref) {
4091
+ const record = this.records.get(refId(ref));
4092
+ if (!record) return false;
4093
+ this.disarm(record);
4094
+ this.records.delete(record.id);
4095
+ this.queueSave();
4096
+ return true;
4097
+ }
4098
+ async trigger(ref) {
4099
+ const record = this.records.get(refId(ref));
4100
+ if (!record) throw new Error(`定时任务 "${refId(ref)}" 不存在`);
4101
+ if (!record.handler) throw new Error(`定时任务 "${record.id}" 还没有绑定回调`);
4102
+ await this.run(record, "manual");
4103
+ }
4104
+ stop(ref) {
4105
+ return this.setStatus(refId(ref), "paused");
4106
+ }
4107
+ start(ref) {
4108
+ return this.setStatus(refId(ref), "running");
4109
+ }
4110
+ stopAll() {
4111
+ this.setAllStatus("paused");
4112
+ }
4113
+ startAll() {
4114
+ this.setAllStatus("running");
4115
+ }
4116
+ jobs() {
4117
+ return [...this.records.values()].map((r) => ({
4118
+ ...r.extra,
4119
+ id: r.id,
4120
+ cron: r.cron,
4121
+ status: r.status,
4122
+ hasHandler: Boolean(r.handler),
4123
+ nextRunAt: r.status === "running" ? r.job?.nextRun()?.toISOString() ?? null : null,
4124
+ lastRunAt: r.lastRunAt,
4125
+ lastError: r.lastError,
4126
+ runCount: r.runCount,
4127
+ createdAt: r.createdAt,
4128
+ updatedAt: r.updatedAt
4129
+ }));
4130
+ }
4131
+ async flush() {
4132
+ await this.pending;
4133
+ const err = this.saveError;
4134
+ if (err !== void 0) {
4135
+ this.saveError = void 0;
4136
+ throw err;
4137
+ }
4138
+ }
4139
+ async dispose() {
4140
+ this.disposed = true;
4141
+ for (const r of this.records.values()) this.disarm(r);
4142
+ await this.pending;
4143
+ }
4144
+ setStatus(id, status) {
4145
+ const record = this.records.get(id);
4146
+ if (!record || record.status === status) return Boolean(record);
4147
+ record.status = status;
4148
+ record.updatedAt = nowIso();
4149
+ status === "paused" ? this.disarm(record) : this.arm(record);
4150
+ this.queueSave();
4151
+ return true;
4152
+ }
4153
+ setAllStatus(status) {
4154
+ let changed = false;
4155
+ for (const record of this.records.values()) if (record.status !== status) {
4156
+ record.status = status;
4157
+ record.updatedAt = nowIso();
4158
+ status === "paused" ? this.disarm(record) : this.arm(record);
4159
+ changed = true;
4160
+ }
4161
+ if (changed) this.queueSave();
4162
+ }
4163
+ arm(record) {
4164
+ this.disarm(record);
4165
+ if (this.disposed || !record.handler || record.status === "paused") return;
4166
+ try {
4167
+ record.job = new Cron(record.cron, {
4168
+ protect: this.options.protect ?? true,
4169
+ unref: this.options.unref ?? false,
4170
+ timezone: this.options.timezone,
4171
+ catch: true
4172
+ }, () => this.run(record, "schedule"));
4173
+ } catch (e) {
4174
+ record.lastError = messageOf(e);
4175
+ this.report(e, {
4176
+ phase: "run",
4177
+ id: record.id
4178
+ });
4179
+ }
4180
+ }
4181
+ disarm(record) {
4182
+ record.job?.stop();
4183
+ record.job = void 0;
4184
+ }
4185
+ async run(record, reason) {
4186
+ const startedAt = /* @__PURE__ */ new Date();
4187
+ record.lastRunAt = startedAt.toISOString();
4188
+ try {
4189
+ await record.handler({
4190
+ id: record.id,
4191
+ cron: record.cron,
4192
+ reason,
4193
+ startedAt,
4194
+ job: this.jobs().find((j) => j.id === record.id)
4195
+ });
4196
+ record.lastError = null;
4197
+ } catch (e) {
4198
+ record.lastError = messageOf(e);
4199
+ if (reason === "manual") throw e;
4200
+ this.report(e, {
4201
+ phase: "run",
4202
+ id: record.id
4203
+ });
4204
+ } finally {
4205
+ record.runCount++;
4206
+ }
4207
+ }
4208
+ report(error, context) {
4209
+ if (this.options.onError) {
4210
+ try {
4211
+ this.options.onError(error, context);
4212
+ } catch {}
4213
+ return;
4214
+ }
4215
+ console.error(`[json-scheduler] ${context.phase} 失败${context.id ? `(${context.id})` : ""}:`, error);
4216
+ }
4217
+ queueSave() {
4218
+ this.pending = this.pending.then(() => this.write()).then(() => {
4219
+ this.saveError = void 0;
4220
+ }).catch((e) => {
4221
+ this.saveError = e;
4222
+ this.report(e, { phase: "save" });
4223
+ });
4224
+ }
4225
+ async write() {
4226
+ const payload = {
4227
+ version: 1,
4228
+ updatedAt: nowIso(),
4229
+ jobs: [...this.records.values()].map((r) => ({
4230
+ ...r.extra,
4231
+ id: r.id,
4232
+ cron: r.cron,
4233
+ status: r.status,
4234
+ cronSource: r.cronSource,
4235
+ createdAt: r.createdAt,
4236
+ updatedAt: r.updatedAt,
4237
+ lastRunAt: r.lastRunAt,
4238
+ lastError: r.lastError,
4239
+ runCount: r.runCount
4240
+ }))
4241
+ };
4242
+ await mkdir(dirname(this.filePath), { recursive: true });
4243
+ const tmp = `${this.filePath}.${process.pid}.tmp`;
4244
+ await writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
4245
+ await rename$1(tmp, this.filePath);
4246
+ }
4247
+ async load() {
4248
+ let raw;
4249
+ try {
4250
+ raw = await readFile(this.filePath, "utf8");
4251
+ } catch (e) {
4252
+ if (e?.code === "ENOENT") return;
4253
+ throw e;
4254
+ }
4255
+ if (!raw.trim()) return;
4256
+ const parsed = JSON.parse(raw);
4257
+ const list = Array.isArray(parsed) ? parsed : parsed?.jobs ?? [];
4258
+ for (const stored of list) {
4259
+ if (!stored || typeof stored !== "object") continue;
4260
+ const id = typeof stored.id === "string" ? stored.id.trim() : "";
4261
+ const cron = typeof stored.cron === "string" ? stored.cron.trim() : "";
4262
+ if (!id || !cron) continue;
4263
+ const status = stored.status === "paused" ? "paused" : "running";
4264
+ const cronSource = stored.cronSource === "update" ? "update" : "use";
4265
+ const extra = pickExtra(stored);
4266
+ let existing = this.records.get(id);
4267
+ if (!existing) {
4268
+ const time = typeof stored.createdAt === "string" ? stored.createdAt : nowIso();
4269
+ existing = {
4270
+ id,
4271
+ cron,
4272
+ status,
4273
+ cronSource,
4274
+ createdAt: time,
4275
+ updatedAt: typeof stored.updatedAt === "string" ? stored.updatedAt : time,
4276
+ lastRunAt: stored.lastRunAt ?? null,
4277
+ lastError: stored.lastError ?? null,
4278
+ runCount: stored.runCount ?? 0,
4279
+ extra
4280
+ };
4281
+ this.records.set(id, existing);
4282
+ } else {
4283
+ existing.status = status;
4284
+ existing.cronSource = cronSource;
4285
+ if (cronSource === "update") existing.cron = cron;
4286
+ Object.assign(existing.extra, {
4287
+ ...extra,
4288
+ ...existing.extra
4289
+ });
4290
+ }
4291
+ }
4292
+ for (const r of this.records.values()) if (r.handler) this.arm(r);
4293
+ }
4294
+ };
4295
+ const scheduler = new JsonSchedulerImpl(join(DSH_PLUGIN_HOME, "jobs.json"));
4296
+ await scheduler.ready();
4297
+ // src/service/runtime.ts
4298
+ let starting = null;
4299
+ let dispose = null;
4300
+ const runtime = defineService({ start() {
4301
+ if (dispose) return Promise.resolve(dispose);
4302
+ if (starting) return starting;
4303
+ starting = activate().finally(() => {
4304
+ starting = null;
4305
+ });
4306
+ return starting;
4307
+ } });
4308
+ async function closeFinishedSupervisors() {
4309
+ for (const supervisor of await db.supervisor.listActive()) {
4310
+ const tickets = await Promise.all((await db.supervisorTicket.listBySupervisor(supervisor.id)).map((link) => db.ticket.findById(link.ticketId)));
4311
+ if (!tickets.length || tickets.some((ticket) => !ticket || ticket.status !== "done" && ticket.status !== "cancelled")) continue;
4312
+ if ((await db.inbox.listPending("supervisor", null)).some((message) => message.supervisorId === supervisor.id)) continue;
4313
+ await db.supervisor.close(supervisor.id, (/* @__PURE__ */ new Date()).toISOString());
4314
+ if (supervisor.sessionId) {
4315
+ await session.stop(supervisor.sessionId).catch(() => void 0);
4316
+ await archive.session(supervisor.sessionId);
4317
+ }
4318
+ }
4319
+ }
4320
+ async function activate() {
4321
+ const controller = new AbortController();
4322
+ const pending = /* @__PURE__ */ new Set();
4323
+ const unregister = [];
4324
+ const stops = [];
4325
+ let restoreShell;
4326
+ let closing = null;
4327
+ const close = () => {
4328
+ if (closing) return closing;
4329
+ closing = (async () => {
4330
+ controller.abort(/* @__PURE__ */ new Error("runtime_stopped"));
4331
+ for (const remove of unregister) remove();
4332
+ await Promise.allSettled(stops.map((stop) => stop()));
4333
+ await Promise.allSettled([...pending]);
4334
+ await restoreShell?.();
4335
+ dispose = null;
4336
+ })();
4337
+ return closing;
4338
+ };
4339
+ function track(action) {
4340
+ if (controller.signal.aborted) return Promise.resolve();
4341
+ const task = Promise.resolve().then(action).finally(() => pending.delete(task));
4342
+ pending.add(task);
4343
+ return task;
4344
+ }
4345
+ try {
4346
+ stops.push(() => devops.cleanup());
4347
+ stops.push(session.start(), worktree.start(), project.start(), inbox.start(), worker$1.start());
4348
+ await scheduler.ready();
4349
+ await session.workspace();
4350
+ if (await session.findMain()) await session.create("main", {});
4351
+ await project.sync();
4352
+ restoreShell = await shell.start();
4353
+ await worker$1.recover();
4354
+ unregister.push(scheduler.use({
4355
+ id: "supermesh:runtime",
4356
+ cron: "* * * * * *"
4357
+ }, () => track(async () => {
4358
+ await worker$1.rescue();
4359
+ await worker$1.reconcileBackground();
4360
+ await inbox.deliverAnswers();
4361
+ await inbox.deliver();
4362
+ await worker$1.reconcile();
4363
+ await closeFinishedSupervisors();
4364
+ })));
4365
+ unregister.push(scheduler.use({
4366
+ id: "supermesh:projects",
4367
+ cron: "*/5 * * * * *"
4368
+ }, () => track(async () => {
4369
+ await project.sync();
4370
+ await shell.refresh();
4371
+ })));
4372
+ unregister.push(scheduler.use({
4373
+ id: "supermesh:github",
4374
+ cron: "*/30 * * * * *"
4375
+ }, () => track(async () => {
4376
+ await project.sync();
4377
+ const failures = (await github.harvest?.(controller.signal) ?? []).filter((result) => !result.ok);
4378
+ if (failures.length) throw new Error(failures.map((result) => result.reason ?? "channel_operation_failed").join(", "));
4379
+ })));
4380
+ unregister.push(scheduler.use({
4381
+ id: "supermesh:github:flush",
4382
+ cron: "*/10 * * * * *"
4383
+ }, () => track(async () => {
4384
+ const failures = (await github.flush(controller.signal)).filter((result) => !result.ok);
4385
+ if (failures.length) throw new Error(failures.map((result) => result.reason ?? "channel_operation_failed").join(", "));
4386
+ })));
4387
+ unregister.push(scheduler.use({
4388
+ id: "supermesh:gitlab",
4389
+ cron: "*/30 * * * * *"
4390
+ }, () => track(async () => {
4391
+ const failures = (await gitlab.harvest?.(controller.signal) ?? []).filter((result) => !result.ok);
4392
+ if (failures.length) throw new Error(failures.map((result) => result.reason ?? "channel_operation_failed").join(", "));
4393
+ })));
4394
+ unregister.push(scheduler.use({
4395
+ id: "supermesh:gitlab:flush",
4396
+ cron: "*/10 * * * * *"
4397
+ }, () => track(async () => {
4398
+ const failures = (await gitlab.flush(controller.signal)).filter((result) => !result.ok);
4399
+ if (failures.length) throw new Error(failures.map((result) => result.reason ?? "channel_operation_failed").join(", "));
4400
+ })));
4401
+ dispose = close;
4402
+ return close;
4403
+ } catch (error) {
4404
+ await close();
4405
+ throw error;
4406
+ }
4407
+ }
4408
+ // src/service/skill.ts
4409
+ const skill = defineService({
4410
+ roots() {
4411
+ return [join(dirname(fileURLToPath(import.meta.url)), "..", "..", "assets", "skills")].filter((path) => existsSync(path));
4412
+ },
4413
+ async install(ctx) {
4414
+ const roots = skill.roots();
4415
+ if (!roots.length) return () => void 0;
4416
+ const fiber = ctx.plugin(await import("@deepseek-ai/dsh-skill-filesystem"), { customSkillDirs: roots });
4417
+ return () => void fiber.dispose();
4418
+ }
4419
+ });
4420
+ // src/index.ts
4421
+ const inject = [
4422
+ "agents",
4423
+ "agentPresets",
4424
+ "sessionController",
4425
+ "workspaceRegistry",
4426
+ "sessionQuery",
4427
+ "credentials",
4428
+ "connection",
4429
+ "webServer",
4430
+ "worktrees"
4431
+ ];
4432
+ async function apply(ctx) {
4433
+ await ctx.effect(async function* () {
4434
+ for (const definition of Object.values(agents)) {
4435
+ yield await ctx.agentPresets.register(definition.preset);
4436
+ yield session.register(definition.preset.id);
4437
+ }
4438
+ }, "supermesh:presets");
4439
+ ctx.on("agent/created", ({ agent }) => handleAgentCreated(ctx, agent));
4440
+ ctx.on("session/event", handleSessionEvent);
4441
+ await ctx.effect(() => server(ctx, {
4442
+ origin: ctx.webServer.getOrigin(),
4443
+ owner: (event) => {
4444
+ const admission = ctx.connection.admit({ headers: event.req.headers });
4445
+ return !("rejection" in admission) && admission.peer.principal.kind === "owner";
4446
+ }
4447
+ }), "supermesh:routes");
4448
+ await ctx.effect(() => runtime.start(), "supermesh:runtime");
4449
+ await ctx.effect(() => skill.install(ctx), "supermesh:skills");
4450
+ }
4451
+ export { apply, inject };