@az-zephyr/slate 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +107 -0
  3. package/README.md +106 -2
  4. package/bin/slate.mjs +226 -0
  5. package/dist/agent/chunk-BVWXAL54.js +3654 -0
  6. package/dist/agent/cli.js +6 -0
  7. package/dist/agent/multi.js +59 -0
  8. package/dist/api/001_initial.sql +127 -0
  9. package/dist/api/002_project_assistant.sql +24 -0
  10. package/dist/api/003_card_decisions.sql +20 -0
  11. package/dist/api/004_card_default_agent.sql +3 -0
  12. package/dist/api/005_card_attachments.sql +24 -0
  13. package/dist/api/006_comment_attachments.sql +7 -0
  14. package/dist/api/007_participant_last_outcome.sql +6 -0
  15. package/dist/api/008_output_attachments.sql +7 -0
  16. package/dist/api/009_card_agent_runs.sql +23 -0
  17. package/dist/api/server.js +4567 -0
  18. package/dist/api/server.js.map +1 -0
  19. package/dist/web/assets/abnfDiagram-XWFEHMT6-DmNFXSdi.js +1 -0
  20. package/dist/web/assets/architectureDiagram-CSQXQB3N-BTCN41JR.js +36 -0
  21. package/dist/web/assets/blockDiagram-BEDRHYPZ-BUJZDqr0.js +140 -0
  22. package/dist/web/assets/bpmnIcons-APHXDYXF-ByGoYv9M.js +1 -0
  23. package/dist/web/assets/c4Diagram-M2UUVUY5-CoTmMGy5.js +38 -0
  24. package/dist/web/assets/chunk-2Q5K7J3B-DN1oTl6j.js +1 -0
  25. package/dist/web/assets/chunk-3BJB4PZV-f0-m4Ag2.js +1 -0
  26. package/dist/web/assets/chunk-3GCGMST5-79GFiiwz.js +1 -0
  27. package/dist/web/assets/chunk-5VM5RSS4-D8XyNr_K.js +15 -0
  28. package/dist/web/assets/chunk-7U7NFRK5-CwjNfj8w.js +88 -0
  29. package/dist/web/assets/chunk-CNRTWJTD-CrX82YZ2.js +1 -0
  30. package/dist/web/assets/chunk-D5HYT7QG-DLlJaHjh.js +1 -0
  31. package/dist/web/assets/chunk-EBZ3SEQC-DYMBSe-a.js +2 -0
  32. package/dist/web/assets/chunk-JWPE2WC7-D7hN7LFG.js +1 -0
  33. package/dist/web/assets/chunk-KTR4FSNJ-DNqOwqFL.js +1 -0
  34. package/dist/web/assets/chunk-XXDRQBXY-ZgzK0pt4.js +1 -0
  35. package/dist/web/assets/classDiagram-v2-IZLYA2OM-CA7bnKxc.js +217 -0
  36. package/dist/web/assets/cose-bilkent-JH36ORCC-DOKkzmxA.js +1 -0
  37. package/dist/web/assets/cynefin-EF2NZ3EQ-C-bSVtsc.js +141 -0
  38. package/dist/web/assets/cynefinDiagram-NJNITYFG-C37MEEtf.js +62 -0
  39. package/dist/web/assets/cytoscape.esm-Bw5aGq32.js +332 -0
  40. package/dist/web/assets/d3-scale-4DPf7zan.js +1 -0
  41. package/dist/web/assets/dagre-KIHZ2IZ3-9ncwFAl9.js +4 -0
  42. package/dist/web/assets/diagram-7YQZDPLS-B5nOmdUq.js +41 -0
  43. package/dist/web/assets/diagram-QBROCOUO-C2R6lDiO.js +200 -0
  44. package/dist/web/assets/diagram-RJJCUUZO-C6CCweHA.js +30 -0
  45. package/dist/web/assets/diagram-WERXNKYE-BMvmqzmc.js +24 -0
  46. package/dist/web/assets/diagram-YHHI257C-mq9rFYCr.js +3 -0
  47. package/dist/web/assets/diagram-YR4HJLHV-GnLZxfuk.js +24 -0
  48. package/dist/web/assets/ebnfDiagram-N527522P-BD49AZHw.js +1 -0
  49. package/dist/web/assets/elk-O5DQBFGD-BPi3gK_q.js +27 -0
  50. package/dist/web/assets/erDiagram-GT5GOJPG-v00zB8rw.js +99 -0
  51. package/dist/web/assets/flowDiagram-JAYNFW54-DIf4aoDB.js +213 -0
  52. package/dist/web/assets/ganttDiagram-3PRQTZWP-DRl_shHP.js +292 -0
  53. package/dist/web/assets/gitGraphDiagram-VXDFKS5L-2RrHppJt.js +106 -0
  54. package/dist/web/assets/graph-Bn3Yngep.js +1 -0
  55. package/dist/web/assets/grid-E2QIVN74-BuI-3sqA.js +1 -0
  56. package/dist/web/assets/index-5BTf4y0R.css +1 -0
  57. package/dist/web/assets/index-CtfDl2Kw.js +358 -0
  58. package/dist/web/assets/infoDiagram-ATMJ4U3S-afgUHtXU.js +2 -0
  59. package/dist/web/assets/ishikawaDiagram-S3EKX5GW-BsIUfApm.js +70 -0
  60. package/dist/web/assets/journeyDiagram-POQNLL5X-BM1Liuxy.js +139 -0
  61. package/dist/web/assets/kanban-definition-BH5XI6FM-Bz439vDv.js +89 -0
  62. package/dist/web/assets/katex-Be3d8Y4U.js +257 -0
  63. package/dist/web/assets/mermaid.core-CDkqDmQh.js +314 -0
  64. package/dist/web/assets/mindmap-definition-WVAN44T4-DcgvDd37.js +98 -0
  65. package/dist/web/assets/pegDiagram-D4NLKWP3-Bs1FcfRL.js +1 -0
  66. package/dist/web/assets/pieDiagram-36ENHN4W-CX3-kIFy.js +39 -0
  67. package/dist/web/assets/quadrantDiagram-ZQUDMS73-CrSg-66H.js +7 -0
  68. package/dist/web/assets/railroadDiagram-JIZHGYPL-DBm7mKc_.js +1 -0
  69. package/dist/web/assets/render-VIF2ZAQL-CjnzRbOQ.js +2 -0
  70. package/dist/web/assets/requirementDiagram-AXW2TVFA--vkT5OaJ.js +84 -0
  71. package/dist/web/assets/sankeyDiagram-FBCJTAIF-CXyuNpgP.js +40 -0
  72. package/dist/web/assets/sequenceDiagram-3LA2ROMG-Cfn5c7T5.js +169 -0
  73. package/dist/web/assets/sizeCapture-2Q2CQKSF-CQJexuw3.js +1 -0
  74. package/dist/web/assets/stateDiagram-v2-XZFR63ZJ-W23Y_4Yd.js +291 -0
  75. package/dist/web/assets/swimlanes-YQL5WMAO-B8ymV9uv.js +1 -0
  76. package/dist/web/assets/swimlanesDiagram-BA3ZWDFA-ClHf-9J2.js +8 -0
  77. package/dist/web/assets/timeline-definition-7Z437IG3-BElgSf_v.js +120 -0
  78. package/dist/web/assets/usecaseDiagram-RDK6N6HP-BfopeYcl.js +370 -0
  79. package/dist/web/assets/vennDiagram-SHRQU5PJ-034PLwGh.js +34 -0
  80. package/dist/web/assets/wardleyDiagram-F3OXNVQS-Cmiyei3a.js +78 -0
  81. package/dist/web/assets/xychartDiagram-GDYJKCDI-DxF4glgl.js +7 -0
  82. package/dist/web/index.html +13 -0
  83. package/package.json +42 -4
  84. package/scripts/git-worktree.mjs +63 -0
  85. package/scripts/slate-cli.mjs +851 -0
  86. package/skills/slate-card/SKILL.md +109 -0
@@ -0,0 +1,4567 @@
1
+ // src/app.ts
2
+ import Fastify from "fastify";
3
+ import { ZodError } from "zod";
4
+
5
+ // src/auth/context.ts
6
+ import { createHash } from "crypto";
7
+
8
+ // src/http/errors.ts
9
+ var HttpError = class extends Error {
10
+ constructor(statusCode, message, details = {}) {
11
+ super(message);
12
+ this.statusCode = statusCode;
13
+ this.details = details;
14
+ }
15
+ statusCode;
16
+ details;
17
+ };
18
+
19
+ // src/auth/context.ts
20
+ var sha256 = (value) => createHash("sha256").update(value).digest("hex");
21
+ var LOCAL_HUMAN = { kind: "human", id: "local-user", name: "\u6211" };
22
+ var MUTATING = /* @__PURE__ */ new Set(["POST", "PATCH", "PUT", "DELETE"]);
23
+ function buildAllowedOrigins(webOrigin) {
24
+ const origins = /* @__PURE__ */ new Set([webOrigin]);
25
+ try {
26
+ const parsed = new URL(webOrigin);
27
+ if (parsed.protocol === "http:" && (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1")) {
28
+ const altHost = parsed.hostname === "localhost" ? "127.0.0.1" : "localhost";
29
+ origins.add(`http://${altHost}${parsed.port ? `:${parsed.port}` : ""}`);
30
+ }
31
+ } catch {
32
+ }
33
+ return origins;
34
+ }
35
+ async function registerAuthContext(app2, pool2, webOrigin) {
36
+ const allowedOrigins = buildAllowedOrigins(webOrigin);
37
+ app2.decorateRequest("agent", void 0);
38
+ app2.decorateRequest("actor", null);
39
+ app2.addHook("preHandler", async (request) => {
40
+ if (request.url === "/health") {
41
+ request.actor = LOCAL_HUMAN;
42
+ return;
43
+ }
44
+ const auth = request.headers.authorization;
45
+ if (auth !== void 0) {
46
+ const match = /^Bearer\s+([A-Za-z0-9_-]{16,256})$/.exec(auth);
47
+ if (!match) throw new HttpError(401, "\u65E0\u6548\u7684 Agent \u51ED\u636E\u683C\u5F0F");
48
+ const tokenHash = sha256(match[1]);
49
+ const row = (await pool2.query(`SELECT id, name, driver, auth_mode, project_id, enabled FROM agents WHERE token_hash = $1`, [tokenHash])).rows[0];
50
+ if (!row) throw new HttpError(401, "Agent \u51ED\u636E\u65E0\u6548\u6216\u5DF2\u5220\u9664");
51
+ request.agent = {
52
+ id: row.id,
53
+ name: row.name,
54
+ driver: row.driver,
55
+ authMode: row.auth_mode,
56
+ projectId: row.project_id,
57
+ enabled: !!row.enabled
58
+ };
59
+ request.actor = {
60
+ kind: "agent",
61
+ id: row.id,
62
+ name: row.name,
63
+ driver: row.driver,
64
+ projectId: row.project_id
65
+ };
66
+ return;
67
+ }
68
+ if (MUTATING.has(request.method)) {
69
+ const origin = request.headers.origin;
70
+ if (origin && !allowedOrigins.has(origin)) {
71
+ throw new HttpError(403, "\u8BF7\u6C42\u6765\u6E90\u4E0D\u5339\u914D");
72
+ }
73
+ }
74
+ request.actor = LOCAL_HUMAN;
75
+ });
76
+ }
77
+
78
+ // src/config.ts
79
+ import { dirname, resolve } from "path";
80
+ import { fileURLToPath } from "url";
81
+ import { config as dotenv } from "dotenv";
82
+ var repositoryRoot = fileURLToPath(new URL("../../../", import.meta.url));
83
+ dotenv({ path: resolve(repositoryRoot, ".env"), quiet: true });
84
+ var slateHome = process.env.SLATE_HOME ? resolve(process.env.SLATE_HOME) : null;
85
+ var databasePath = process.env.SQLITE_PATH ? resolve(slateHome ?? repositoryRoot, process.env.SQLITE_PATH) : slateHome ? resolve(slateHome, "slate.sqlite") : resolve(repositoryRoot, ".local/slate.sqlite");
86
+ var port = Number(process.env.API_PORT ?? 3100);
87
+ var webDistDir = process.env.SLATE_WEB_DIST ? resolve(process.env.SLATE_WEB_DIST) : null;
88
+ var config = {
89
+ databasePath,
90
+ uploadsDir: process.env.SLATE_UPLOADS_DIR ? resolve(slateHome ?? repositoryRoot, process.env.SLATE_UPLOADS_DIR) : resolve(dirname(databasePath), "uploads"),
91
+ port,
92
+ webOrigin: process.env.WEB_ORIGIN ?? (webDistDir ? `http://127.0.0.1:${port}` : "http://localhost:5173"),
93
+ webDistDir,
94
+ sandboxRoot: process.env.SLATE_SANDBOX ? resolve(slateHome ?? repositoryRoot, process.env.SLATE_SANDBOX) : slateHome ? resolve(slateHome, "sandbox") : resolve(repositoryRoot, "../slate-agent-sandbox")
95
+ };
96
+
97
+ // src/http/event-stream.ts
98
+ var heartbeatMs = 15e3;
99
+ var BoardEventStreams = class {
100
+ stopped = false;
101
+ streams = /* @__PURE__ */ new Map();
102
+ heartbeat = setInterval(() => {
103
+ for (const response of this.streams.keys()) this.write(response, "heartbeat", {});
104
+ }, heartbeatMs);
105
+ publish = (notification) => {
106
+ for (const [response, scope] of this.streams) {
107
+ if (notification.type === "wake") {
108
+ if (scope.projectId && scope.projectId !== notification.projectId) continue;
109
+ this.write(response, "wake", notification);
110
+ } else if (notification.type === "board_updated") {
111
+ if (scope.projectId && notification.projectId && scope.projectId !== notification.projectId) continue;
112
+ this.write(response, "board_updated", notification);
113
+ } else if (notification.type === "assistant_delta") {
114
+ if (scope.agentId) continue;
115
+ if (scope.projectId && scope.projectId !== notification.projectId) continue;
116
+ this.write(response, "assistant_delta", notification);
117
+ } else if (notification.type === "card_run_step") {
118
+ if (scope.agentId) continue;
119
+ if (scope.projectId && scope.projectId !== notification.projectId) continue;
120
+ this.write(response, "card_run_step", notification);
121
+ } else if (notification.type === "command") {
122
+ if (scope.agentId && scope.agentId !== notification.agentId) continue;
123
+ this.write(response, "command", notification);
124
+ }
125
+ }
126
+ };
127
+ subscribe(response, scope = {}) {
128
+ if (this.stopped) return false;
129
+ this.streams.set(response, scope);
130
+ response.on("close", () => this.streams.delete(response));
131
+ response.on("error", () => this.disconnect(response));
132
+ this.write(response, "ready", {});
133
+ return true;
134
+ }
135
+ disconnect(response) {
136
+ this.streams.delete(response);
137
+ response.destroy();
138
+ }
139
+ write(response, event, data) {
140
+ try {
141
+ if (!response.destroyed && response.write(`event: ${event}
142
+ data: ${JSON.stringify(data)}
143
+
144
+ `)) return;
145
+ } catch {
146
+ }
147
+ this.disconnect(response);
148
+ }
149
+ close() {
150
+ this.stopped = true;
151
+ clearInterval(this.heartbeat);
152
+ for (const response of this.streams.keys()) response.end();
153
+ this.streams.clear();
154
+ }
155
+ };
156
+
157
+ // src/http/routes.ts
158
+ import { randomUUID as randomUUID8 } from "crypto";
159
+ import { createReadStream } from "fs";
160
+
161
+ // ../../packages/contracts/src/index.ts
162
+ import { z } from "zod";
163
+ var cardStatusSchema = z.enum(["todo", "doing", "review", "done"]);
164
+ var agentAllowedStatusSchema = z.enum(["todo", "doing", "review"]);
165
+ var prioritySchema = z.enum(["high", "medium", "low"]);
166
+ var driverTypeSchema = z.enum(["codex", "claude-code", "antigravity"]);
167
+ var authModeSchema = z.enum(["device_flow", "local_session", "api_key", "none"]);
168
+ var loginStateSchema = z.enum(["unknown", "logged_in", "logged_out", "expired", "error"]);
169
+ var loginRequestStatusSchema = z.enum([
170
+ "pending",
171
+ "starting",
172
+ "waiting_user",
173
+ "succeeded",
174
+ "failed",
175
+ "cancelled",
176
+ "expired"
177
+ ]);
178
+ var parallelModeSchema = z.enum(["auto", "worktree", "isolated_dir", "shared"]);
179
+ var shortText = z.string().trim().min(1).max(200);
180
+ var optionalShortText = z.string().trim().max(200).default("");
181
+ var tagSchema = z.string().trim().min(1).max(40);
182
+ var pathText = z.string().trim().max(1e3);
183
+ var longText = z.string().trim().max(5e4);
184
+ var checklistItemSchema = z.object({
185
+ id: z.string().trim().min(1).max(64),
186
+ text: z.string().trim().min(1).max(500),
187
+ done: z.boolean().default(false),
188
+ updatedBy: z.string().trim().max(200).optional()
189
+ }).strict();
190
+ var checklistSchema = z.array(checklistItemSchema).max(100).refine((items) => new Set(items.map((i) => i.id)).size === items.length, "\u6E05\u5355\u9879 ID \u4E0D\u80FD\u91CD\u590D");
191
+ var httpUrlSchema = (max) => z.string().trim().url().max(max).refine((v) => /^https?:\/\//i.test(v), "\u4EC5\u652F\u6301 http/https \u94FE\u63A5");
192
+ var ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024;
193
+ var CARD_MAX_ATTACHMENTS = 20;
194
+ var COMMENT_MAX_ATTACHMENTS = 10;
195
+ var IMAGE_ATTACHMENT_MIME_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
196
+ var IMAGE_ATTACHMENT_ACCEPT = IMAGE_ATTACHMENT_MIME_TYPES.join(",");
197
+ var attachmentKindSchema = z.enum(["image", "file"]);
198
+ var attachmentCloneSchema = z.object({
199
+ projectId: z.string().uuid(),
200
+ attachmentIds: z.array(z.string().uuid()).min(1).max(CARD_MAX_ATTACHMENTS)
201
+ }).strict();
202
+ var OUTPUT_CONTENT_MAX_CHARS = 2e5;
203
+ var cardOutputInputSchema = z.object({
204
+ label: shortText.optional(),
205
+ path: pathText.optional(),
206
+ branch: z.string().trim().max(200).optional(),
207
+ summary: z.string().trim().max(2e3).optional(),
208
+ url: httpUrlSchema(2e3).optional(),
209
+ content: z.string().max(OUTPUT_CONTENT_MAX_CHARS).optional(),
210
+ filename: z.string().trim().min(1).max(255).optional(),
211
+ mimeType: z.string().trim().min(1).max(128).optional(),
212
+ attachmentId: z.string().uuid().optional()
213
+ }).strict().superRefine((val, ctx) => {
214
+ const hasIdentity = Boolean(
215
+ val.label || val.filename || val.attachmentId || val.path?.trim() || val.branch?.trim() || val.url
216
+ );
217
+ if (!hasIdentity) {
218
+ ctx.addIssue({
219
+ code: z.ZodIssueCode.custom,
220
+ path: ["filename"],
221
+ message: "\u8BF7\u81F3\u5C11\u63D0\u4F9B filename\u3001label\u3001attachmentId\u3001path\u3001branch \u6216 url \u4E4B\u4E00"
222
+ });
223
+ }
224
+ if (val.content !== void 0 && val.attachmentId !== void 0) {
225
+ ctx.addIssue({
226
+ code: z.ZodIssueCode.custom,
227
+ path: ["content"],
228
+ message: "content \u4E0E attachmentId \u4E0D\u80FD\u540C\u65F6\u4F20\u5165"
229
+ });
230
+ }
231
+ if (val.content !== void 0 && val.content.trim().length === 0) {
232
+ ctx.addIssue({
233
+ code: z.ZodIssueCode.custom,
234
+ path: ["content"],
235
+ message: "content \u4E0D\u80FD\u4E3A\u7A7A"
236
+ });
237
+ }
238
+ if (val.content === void 0 && (val.filename !== void 0 || val.mimeType !== void 0)) {
239
+ ctx.addIssue({
240
+ code: z.ZodIssueCode.custom,
241
+ path: [val.filename !== void 0 ? "filename" : "mimeType"],
242
+ message: "filename / mimeType \u4EC5\u5728\u4F20\u5165 content \u65F6\u53EF\u7528"
243
+ });
244
+ }
245
+ });
246
+ var projectCreateSchema = z.object({
247
+ name: shortText,
248
+ description: z.string().trim().max(2e3).default(""),
249
+ rootPath: pathText.default(""),
250
+ defaultAgentId: z.string().uuid().nullable().optional(),
251
+ parallelMode: parallelModeSchema.default("auto")
252
+ }).strict();
253
+ var projectUpdateSchema = z.object({
254
+ name: shortText.optional(),
255
+ description: z.string().trim().max(2e3).optional(),
256
+ rootPath: pathText.optional(),
257
+ defaultAgentId: z.string().uuid().nullable().optional(),
258
+ parallelMode: parallelModeSchema.optional()
259
+ }).strict();
260
+ var agentRegisterSchema = z.object({
261
+ name: shortText,
262
+ driver: driverTypeSchema,
263
+ authMode: authModeSchema.optional(),
264
+ projectId: z.string().uuid().nullable().optional()
265
+ }).strict();
266
+ var agentUpdateSchema = z.object({
267
+ name: shortText.optional(),
268
+ enabled: z.boolean().optional(),
269
+ projectId: z.string().uuid().nullable().optional()
270
+ }).strict();
271
+ var agentPresenceReportSchema = z.object({
272
+ adapterInstanceId: z.string().trim().min(1).max(80),
273
+ hostLabel: z.string().trim().min(1).max(200),
274
+ sseConnected: z.boolean(),
275
+ lastEventCursor: z.string().regex(/^\d+$/),
276
+ driver: driverTypeSchema.optional(),
277
+ authMode: authModeSchema.optional(),
278
+ loginState: loginStateSchema,
279
+ loginMessage: z.string().trim().max(500).optional()
280
+ }).strict();
281
+ var agentLoginProgressSchema = z.object({
282
+ status: z.enum(["starting", "waiting_user", "succeeded", "failed", "cancelled", "expired"]),
283
+ verificationUri: httpUrlSchema(500).optional(),
284
+ userCode: z.string().trim().min(1).max(40).optional(),
285
+ expiresAt: z.string().trim().datetime({ offset: true }).max(40).optional(),
286
+ message: z.string().trim().max(500).optional()
287
+ }).strict();
288
+ var cardCreateSchema = z.object({
289
+ projectId: z.string().uuid(),
290
+ parentId: z.string().uuid().nullable().optional(),
291
+ defaultAgentId: z.string().uuid().nullable().optional(),
292
+ title: shortText,
293
+ body: longText.default(""),
294
+ status: cardStatusSchema.default("todo"),
295
+ priority: prioritySchema.default("medium"),
296
+ tags: z.array(tagSchema).max(20).default([]),
297
+ checklist: checklistSchema.default([]),
298
+ mentions: z.array(z.string().uuid()).max(10).default([]),
299
+ attachmentIds: z.array(z.string().uuid()).max(CARD_MAX_ATTACHMENTS).default([]),
300
+ skipDefaultAgent: z.boolean().default(false)
301
+ }).strict();
302
+ var checklistOpAddSchema = z.object({
303
+ op: z.literal("add"),
304
+ id: z.string().trim().min(1).max(64).optional(),
305
+ text: z.string().trim().min(1).max(500),
306
+ done: z.boolean().default(false)
307
+ }).strict();
308
+ var checklistOpUpdateSchema = z.object({
309
+ op: z.literal("update"),
310
+ id: z.string().trim().min(1).max(64),
311
+ text: z.string().trim().min(1).max(500).optional(),
312
+ done: z.boolean().optional()
313
+ }).strict();
314
+ var checklistOpRemoveSchema = z.object({
315
+ op: z.literal("remove"),
316
+ id: z.string().trim().min(1).max(64)
317
+ }).strict();
318
+ var checklistOpSchema = z.discriminatedUnion("op", [checklistOpAddSchema, checklistOpUpdateSchema, checklistOpRemoveSchema]).superRefine((op, ctx) => {
319
+ if (op.op === "update" && op.text === void 0 && op.done === void 0) {
320
+ ctx.addIssue({
321
+ code: z.ZodIssueCode.custom,
322
+ message: "update \u64CD\u4F5C\u81F3\u5C11\u9700\u8981\u63D0\u4F9B text \u6216 done \u4E4B\u4E00"
323
+ });
324
+ }
325
+ });
326
+ var cardUpdateSchema = z.object({
327
+ title: shortText.optional(),
328
+ body: longText.optional(),
329
+ priority: prioritySchema.optional(),
330
+ tags: z.array(tagSchema).max(20).optional(),
331
+ checklist: checklistSchema.optional(),
332
+ checklistOps: z.array(checklistOpSchema).min(1).max(50).optional(),
333
+ expectedVersion: z.number().int().min(1).optional(),
334
+ parentId: z.string().uuid().nullable().optional(),
335
+ defaultAgentId: z.string().uuid().nullable().optional(),
336
+ position: z.number().int().min(0).optional(),
337
+ summary: optionalShortText.optional()
338
+ }).strict().refine((v) => !(v.checklist !== void 0 && v.checklistOps !== void 0), {
339
+ message: "checklist \u4E0E checklistOps \u4E0D\u80FD\u540C\u65F6\u4F20\u5165\uFF0C\u8BF7\u4E8C\u9009\u4E00\uFF08\u5E76\u53D1\u573A\u666F\u63A8\u8350 checklistOps\uFF09",
340
+ path: ["checklistOps"]
341
+ });
342
+ var cardStatusChangeSchema = z.object({
343
+ status: cardStatusSchema,
344
+ position: z.number().int().min(0).optional(),
345
+ note: z.string().trim().max(2e3).optional()
346
+ }).strict();
347
+ var commentCreateSchema = z.object({
348
+ text: z.string().trim().max(2e4).default(""),
349
+ mentions: z.array(z.string().uuid()).max(10).default([]),
350
+ attachmentIds: z.array(z.string().uuid()).max(COMMENT_MAX_ATTACHMENTS).default([]),
351
+ replyTo: z.string().uuid().optional(),
352
+ relatesTo: z.string().uuid().optional()
353
+ }).strict().refine((v) => v.text.length > 0 || v.attachmentIds.length > 0, "\u8BF7\u8F93\u5165\u8BC4\u8BBA\u5185\u5BB9\u6216\u6DFB\u52A0\u9644\u4EF6");
354
+ var participantOutcomeSchema = z.enum(["completed", "no_write", "failed", "stopped"]);
355
+ var cardRunStatusSchema = z.enum(["running", "completed", "no_write", "failed", "stopped"]);
356
+ var cardRunStepKindSchema = z.enum(["slate", "command", "tool", "message", "status"]);
357
+ var CARD_RUN_MAX_STEPS = 80;
358
+ var CARD_RUN_STEP_BATCH_MAX = 20;
359
+ var cardRunStepInputSchema = z.object({
360
+ kind: cardRunStepKindSchema,
361
+ title: z.string().trim().min(1).max(200),
362
+ detail: z.string().trim().max(400).optional(),
363
+ at: z.string().trim().datetime({ offset: true }).max(40).optional()
364
+ }).strict();
365
+ var cardRunStepsAppendSchema = z.object({
366
+ runId: z.string().uuid(),
367
+ eventId: z.string().uuid().optional(),
368
+ steps: z.array(cardRunStepInputSchema).min(1).max(CARD_RUN_STEP_BATCH_MAX)
369
+ }).strict();
370
+ var processingReportSchema = z.object({
371
+ runId: z.string().uuid().optional(),
372
+ eventId: z.string().uuid().optional(),
373
+ activityText: z.string().trim().max(300).default(""),
374
+ workDir: pathText.optional(),
375
+ branch: z.string().trim().max(200).optional()
376
+ }).strict();
377
+ var processingClearSchema = z.object({
378
+ runId: z.string().uuid().optional(),
379
+ eventId: z.string().uuid().optional(),
380
+ outcome: participantOutcomeSchema.optional(),
381
+ summary: z.string().trim().max(300).optional()
382
+ }).strict();
383
+ var decisionOptionSchema = z.object({
384
+ id: z.string().trim().min(1).max(64),
385
+ label: z.string().trim().min(1).max(120),
386
+ description: z.string().trim().max(400).optional(),
387
+ recommended: z.boolean().default(false)
388
+ }).strict();
389
+ var cardDecisionCreateSchema = z.object({
390
+ question: z.string().trim().min(1).max(2e3),
391
+ context: z.string().trim().max(2e3).optional(),
392
+ options: z.array(decisionOptionSchema).min(2).max(6).refine((opts) => new Set(opts.map((o) => o.id)).size === opts.length, "\u51B3\u7B56\u9009\u9879 ID \u4E0D\u80FD\u91CD\u590D").optional()
393
+ }).strict();
394
+ var cardDecisionResolveSchema = z.object({
395
+ optionId: z.string().trim().min(1).max(64).optional(),
396
+ note: z.string().trim().max(4e3).optional(),
397
+ wakeAgent: z.boolean().default(true)
398
+ }).strict().refine((v) => Boolean(v.optionId || v.note?.trim()), "\u8BF7\u9009\u62E9\u4E00\u4E2A\u9009\u9879\u6216\u586B\u5199\u56DE\u590D\u5185\u5BB9");
399
+ var assistantRunKindSchema = z.enum(["card_draft", "assistant_chat"]);
400
+ var assistantPresetSchema = z.enum(["focus", "risk", "cleanup", "summary"]);
401
+ var assistantRunStatusSchema = z.enum(["queued", "running", "succeeded", "failed", "cancelled"]);
402
+ var assistantRunOptionsSchema = z.object({
403
+ includeExistingCards: z.boolean().default(true),
404
+ readWorkspace: z.boolean().default(true),
405
+ allowMultipleCards: z.boolean().default(false)
406
+ }).strict();
407
+ var assistantCardDraftSchema = z.object({
408
+ title: shortText,
409
+ body: longText.default(""),
410
+ status: agentAllowedStatusSchema.default("todo"),
411
+ priority: prioritySchema.default("medium"),
412
+ tags: z.array(tagSchema).max(20).default([]),
413
+ checklist: z.array(z.string().trim().min(1).max(500)).max(50).default([]),
414
+ suggestedAgentIds: z.array(z.string().uuid()).max(10).default([]),
415
+ parentId: z.string().uuid().nullable().optional(),
416
+ duplicateOfCardId: z.string().uuid().nullable().optional(),
417
+ duplicateReason: z.string().trim().max(500).optional()
418
+ }).strict();
419
+ var assistantCardRefSchema = z.object({
420
+ cardId: z.string().uuid(),
421
+ title: shortText,
422
+ status: cardStatusSchema,
423
+ note: z.string().trim().max(200).optional()
424
+ }).strict();
425
+ var assistantProposalActionSchema = z.discriminatedUnion("type", [
426
+ z.object({
427
+ id: z.string().trim().min(1).max(64),
428
+ type: z.literal("create_card"),
429
+ summary: shortText,
430
+ draft: assistantCardDraftSchema,
431
+ mentions: z.array(z.string().uuid()).max(10).default([]),
432
+ skipDefaultAgent: z.boolean().default(false)
433
+ }).strict(),
434
+ z.object({
435
+ id: z.string().trim().min(1).max(64),
436
+ type: z.literal("update_card"),
437
+ cardId: z.string().uuid(),
438
+ cardTitle: shortText,
439
+ summary: shortText,
440
+ patch: z.object({
441
+ title: shortText.optional(),
442
+ priority: prioritySchema.optional(),
443
+ tags: z.array(tagSchema).max(20).optional(),
444
+ status: cardStatusSchema.optional()
445
+ }).strict()
446
+ }).strict(),
447
+ z.object({
448
+ id: z.string().trim().min(1).max(64),
449
+ type: z.literal("archive_card"),
450
+ cardId: z.string().uuid(),
451
+ cardTitle: shortText,
452
+ summary: shortText
453
+ }).strict()
454
+ ]);
455
+ var assistantRunResultSchema = z.object({
456
+ reply: z.string().trim().max(5e4).default(""),
457
+ clarifyQuestion: z.string().trim().max(1e3).optional(),
458
+ splitSuggestion: z.string().trim().max(500).optional(),
459
+ cardRefs: z.array(assistantCardRefSchema).max(30).refine((refs) => new Set(refs.map((r) => r.cardId)).size === refs.length, "\u5F15\u7528\u5361\u7247 ID \u4E0D\u80FD\u91CD\u590D").default([]),
460
+ drafts: z.array(assistantCardDraftSchema).max(20).default([]),
461
+ proposals: z.array(assistantProposalActionSchema).max(30).refine((items) => new Set(items.map((i) => i.id)).size === items.length, "\u63D0\u6848 ID \u4E0D\u80FD\u91CD\u590D").default([])
462
+ }).strict();
463
+ var assistantRunCreateSchema = z.object({
464
+ projectId: z.string().uuid(),
465
+ agentId: z.string().uuid(),
466
+ kind: assistantRunKindSchema,
467
+ prompt: z.string().trim().min(1).max(2e4),
468
+ threadId: z.string().uuid().optional(),
469
+ preset: assistantPresetSchema.optional(),
470
+ options: assistantRunOptionsSchema.optional(),
471
+ attachmentIds: z.array(z.string().uuid()).max(CARD_MAX_ATTACHMENTS).default([])
472
+ }).strict();
473
+ var assistantRunProgressSchema = z.object({
474
+ status: z.enum(["running", "succeeded", "failed", "cancelled"]),
475
+ activityText: z.string().trim().max(300).optional(),
476
+ sessionId: z.string().trim().max(200).optional(),
477
+ result: assistantRunResultSchema.optional(),
478
+ errorMessage: z.string().trim().max(2e3).optional()
479
+ }).strict();
480
+ var assistantRunStreamSchema = z.object({
481
+ text: z.string().max(5e4),
482
+ stage: z.enum(["streaming", "structuring"]).default("streaming"),
483
+ activityText: z.string().trim().max(300).optional()
484
+ }).strict();
485
+ var assistantProposalApplySchema = z.object({
486
+ actions: z.array(assistantProposalActionSchema).min(1).max(30)
487
+ }).strict();
488
+
489
+ // src/http/routes.ts
490
+ import { z as z2 } from "zod";
491
+
492
+ // src/db/pool.ts
493
+ import { closeSync, mkdirSync, openSync, statSync } from "fs";
494
+ import { dirname as dirname2 } from "path";
495
+ import { DatabaseSync } from "node:sqlite";
496
+ var sqliteTimestamp = (value) => value.toISOString().replace(/Z$/, "000Z");
497
+ function bind(value) {
498
+ if (value == null || typeof value === "string" || typeof value === "number" || typeof value === "bigint")
499
+ return value ?? null;
500
+ if (typeof value === "boolean") return Number(value);
501
+ if (value instanceof Date) return sqliteTimestamp(value);
502
+ if (typeof value === "object") return JSON.stringify(value);
503
+ throw new TypeError("Unsupported SQLite parameter");
504
+ }
505
+ var Pool = class {
506
+ db;
507
+ tail = Promise.resolve();
508
+ constructor(file) {
509
+ mkdirSync(dirname2(file), { recursive: true, mode: 448 });
510
+ try {
511
+ closeSync(openSync(file, "wx", 384));
512
+ } catch (error) {
513
+ if (error.code !== "EEXIST") throw error;
514
+ }
515
+ const info = statSync(file);
516
+ if (!info.isFile() || info.mode & 63)
517
+ throw new Error("SQLite \u6587\u4EF6\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\uFF0C\u4E14\u4E0D\u80FD\u5141\u8BB8\u7EC4\u6216\u5176\u4ED6\u7528\u6237\u8BBF\u95EE\uFF08\u5EFA\u8BAE chmod 600\uFF09");
518
+ this.db = new DatabaseSync(file, { enableForeignKeyConstraints: true, enableDoubleQuotedStringLiterals: false });
519
+ try {
520
+ this.db.exec("PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA recursive_triggers=ON;");
521
+ } catch (error) {
522
+ this.db.close();
523
+ throw error;
524
+ }
525
+ }
526
+ enqueue(run) {
527
+ const result = this.tail.then(run);
528
+ this.tail = result.then(
529
+ () => {
530
+ },
531
+ () => {
532
+ }
533
+ );
534
+ return result;
535
+ }
536
+ run(sql, params = []) {
537
+ const statement = this.db.prepare(sql);
538
+ const bindings = params.length ? Object.fromEntries(params.map((v, i) => [`$${i + 1}`, bind(v)])) : void 0;
539
+ if (statement.columns().length) {
540
+ const rows = (bindings ? statement.all(bindings) : statement.all()).map((row) => ({ ...row }));
541
+ return { rows, rowCount: rows.length };
542
+ }
543
+ return { rows: [], rowCount: Number((bindings ? statement.run(bindings) : statement.run()).changes) };
544
+ }
545
+ query = (sql, params) => this.enqueue(() => this.run(sql, params));
546
+ transact(run, readOnly) {
547
+ return this.enqueue(async () => {
548
+ const pending = [];
549
+ let active = true;
550
+ const assertActive = () => {
551
+ if (!active) throw new Error("SQLite transaction is closed");
552
+ };
553
+ const client = {
554
+ query: async (sql, params) => {
555
+ assertActive();
556
+ return this.run(sql, params);
557
+ },
558
+ exec: (sql) => {
559
+ assertActive();
560
+ this.db.exec(sql);
561
+ },
562
+ afterCommit: (publish) => {
563
+ assertActive();
564
+ pending.push(publish);
565
+ }
566
+ };
567
+ this.db.exec(readOnly ? "BEGIN" : "BEGIN IMMEDIATE");
568
+ let result;
569
+ try {
570
+ result = await run(client);
571
+ this.db.exec("COMMIT");
572
+ } catch (error) {
573
+ if (this.db.isTransaction) this.db.exec("ROLLBACK");
574
+ throw error;
575
+ } finally {
576
+ active = false;
577
+ }
578
+ for (const publish of pending) {
579
+ try {
580
+ publish();
581
+ } catch {
582
+ }
583
+ }
584
+ return result;
585
+ });
586
+ }
587
+ end() {
588
+ return this.enqueue(() => this.db.close());
589
+ }
590
+ };
591
+ var createPool = (file) => new Pool(file);
592
+ function transaction(pool2, run, options) {
593
+ return pool2.transact(run, options?.readOnly ?? false);
594
+ }
595
+
596
+ // src/domain/agents.ts
597
+ import { randomBytes, randomUUID } from "crypto";
598
+
599
+ // src/domain/notifications.ts
600
+ function notifyAfterCommit(client, publish, notification) {
601
+ if (publish) client.afterCommit(() => publish(notification));
602
+ }
603
+
604
+ // src/domain/agents.ts
605
+ var ACTIVE_LOGIN_STATUSES = ["pending", "starting", "waiting_user"];
606
+ var iso = (value) => new Date(value).toISOString();
607
+ function mapLogin(row) {
608
+ return {
609
+ id: row.id,
610
+ status: row.status,
611
+ expiresAt: iso(row.expires_at),
612
+ createdAt: iso(row.created_at),
613
+ updatedAt: iso(row.updated_at),
614
+ ...row.message ? { message: row.message } : {},
615
+ ...row.verification_uri ? { verificationUri: row.verification_uri } : {},
616
+ ...row.user_code ? { userCode: row.user_code } : {}
617
+ };
618
+ }
619
+ function defaultAuthModeForDriver(driver) {
620
+ return driver === "codex" ? "device_flow" : "local_session";
621
+ }
622
+ function validateVerificationUri(driver, value) {
623
+ if (!value) return null;
624
+ try {
625
+ const url = new URL(value);
626
+ if (url.protocol !== "https:" || url.username || url.password) return null;
627
+ if (driver === "codex") return url.pathname.endsWith("/codex/device") ? url.href : null;
628
+ return url.href;
629
+ } catch {
630
+ return null;
631
+ }
632
+ }
633
+ async function expireLogins(db, agentId) {
634
+ await db.query(
635
+ `UPDATE agent_login_requests
636
+ SET status = 'expired', message = '\u767B\u5F55\u8BF7\u6C42\u5DF2\u8FC7\u671F', updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
637
+ WHERE ($1 IS NULL OR agent_id = $1)
638
+ AND status IN ('pending', 'starting', 'waiting_user')
639
+ AND expires_at <= strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')`,
640
+ [agentId ?? null]
641
+ );
642
+ }
643
+ async function listAgents(pool2, projectId) {
644
+ await expireLogins(pool2);
645
+ const { rows } = await pool2.query(
646
+ `SELECT a.*,
647
+ (a.last_heartbeat_at IS NOT NULL AND a.last_heartbeat_at >= strftime('%Y-%m-%dT%H:%M:%f000Z', 'now', '-30 seconds')) AS online,
648
+ lr.id AS request_id, lr.status AS request_status, lr.verification_uri AS request_verification_uri,
649
+ lr.user_code AS request_user_code, lr.expires_at AS request_expires_at, lr.message AS request_message,
650
+ lr.created_at AS request_created_at, lr.updated_at AS request_updated_at
651
+ FROM agents a
652
+ LEFT JOIN agent_login_requests lr ON lr.id = (
653
+ SELECT r.id FROM agent_login_requests r
654
+ WHERE r.agent_id = a.id
655
+ AND (r.status IN ('pending', 'starting', 'waiting_user') OR r.updated_at >= strftime('%Y-%m-%dT%H:%M:%f000Z', 'now', '-5 minutes'))
656
+ ORDER BY (r.status IN ('pending', 'starting', 'waiting_user')) DESC, r.updated_at DESC, r.id
657
+ LIMIT 1
658
+ )
659
+ WHERE ($1 IS NULL OR a.project_id IS NULL OR a.project_id = $1)
660
+ ORDER BY a.created_at, a.name, a.id`,
661
+ [projectId ?? null]
662
+ );
663
+ const activeRows = (await pool2.query(
664
+ `SELECT cp.agent_id, cp.card_id, c.title, cp.activity_text, cp.work_dir, cp.branch, cp.processing_until
665
+ FROM card_participants cp
666
+ JOIN cards c ON c.id = cp.card_id
667
+ WHERE cp.processing_until > strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
668
+ AND ($1 IS NULL OR c.project_id = $1)
669
+ ORDER BY cp.updated_at DESC`,
670
+ [projectId ?? null]
671
+ )).rows;
672
+ const activeByAgent = /* @__PURE__ */ new Map();
673
+ for (const r of activeRows) {
674
+ const list = activeByAgent.get(r.agent_id) ?? [];
675
+ list.push({
676
+ cardId: r.card_id,
677
+ title: r.title,
678
+ activityText: r.activity_text,
679
+ workDir: r.work_dir,
680
+ branch: r.branch,
681
+ leaseUntil: iso(r.processing_until)
682
+ });
683
+ activeByAgent.set(r.agent_id, list);
684
+ }
685
+ return rows.map((row) => ({
686
+ id: row.id,
687
+ name: row.name,
688
+ driver: row.driver,
689
+ authMode: row.auth_mode,
690
+ projectId: row.project_id,
691
+ enabled: !!row.enabled,
692
+ online: !!row.online,
693
+ sseConnected: !!row.sse_connected,
694
+ hostLabel: row.host_label,
695
+ adapterInstanceId: row.adapter_instance_id,
696
+ lastHeartbeatAt: row.last_heartbeat_at ? iso(row.last_heartbeat_at) : null,
697
+ lastEventCursor: row.last_event_cursor,
698
+ loginState: row.login_state,
699
+ loginMessage: row.login_message,
700
+ loginReportedAt: row.login_reported_at ? iso(row.login_reported_at) : null,
701
+ activeCards: activeByAgent.get(row.id) ?? [],
702
+ loginRequest: row.request_id && row.request_status && row.request_expires_at && row.request_created_at && row.request_updated_at ? mapLogin({
703
+ id: row.request_id,
704
+ status: row.request_status,
705
+ verification_uri: row.request_verification_uri,
706
+ user_code: row.request_user_code,
707
+ expires_at: row.request_expires_at,
708
+ message: row.request_message,
709
+ created_at: row.request_created_at,
710
+ updated_at: row.request_updated_at
711
+ }) : null,
712
+ createdAt: iso(row.created_at)
713
+ }));
714
+ }
715
+ async function registerAgent(pool2, input, publish) {
716
+ const id = randomUUID();
717
+ const token = randomBytes(32).toString("base64url");
718
+ const authMode = input.authMode ?? defaultAuthModeForDriver(input.driver);
719
+ await transaction(pool2, async (client) => {
720
+ if (input.projectId) {
721
+ const exists = await client.query("SELECT 1 FROM projects WHERE id = $1", [input.projectId]);
722
+ if (!exists.rowCount) throw new HttpError(404, "\u9879\u76EE\u4E0D\u5B58\u5728");
723
+ }
724
+ await client.query(
725
+ `INSERT INTO agents(id, project_id, name, driver, auth_mode, token_hash)
726
+ VALUES($1, $2, $3, $4, $5, $6)`,
727
+ [id, input.projectId ?? null, input.name, input.driver, authMode, sha256(token)]
728
+ );
729
+ notifyAfterCommit(client, publish, {
730
+ type: "board_updated",
731
+ projectId: input.projectId ?? void 0,
732
+ reason: "agent_registered"
733
+ });
734
+ });
735
+ const agents = await listAgents(pool2);
736
+ return { agent: agents.find((a) => a.id === id), token };
737
+ }
738
+ async function updateAgent(pool2, agentId, input, publish) {
739
+ await transaction(pool2, async (client) => {
740
+ const existing = (await client.query("SELECT id FROM agents WHERE id = $1", [agentId])).rows[0];
741
+ if (!existing) throw new HttpError(404, "Agent \u4E0D\u5B58\u5728");
742
+ if (input.projectId) {
743
+ const proj = await client.query("SELECT 1 FROM projects WHERE id = $1", [input.projectId]);
744
+ if (!proj.rowCount) throw new HttpError(404, "\u9879\u76EE\u4E0D\u5B58\u5728");
745
+ }
746
+ await client.query(
747
+ `UPDATE agents SET
748
+ name = COALESCE($2, name),
749
+ enabled = COALESCE($3, enabled),
750
+ project_id = CASE WHEN $4 = 1 THEN $5 ELSE project_id END
751
+ WHERE id = $1`,
752
+ [
753
+ agentId,
754
+ input.name ?? null,
755
+ input.enabled === void 0 ? null : Number(input.enabled),
756
+ input.projectId !== void 0 ? 1 : 0,
757
+ input.projectId ?? null
758
+ ]
759
+ );
760
+ if (input.projectId) {
761
+ await client.query("UPDATE projects SET default_agent_id = NULL WHERE default_agent_id = $1 AND id <> $2", [
762
+ agentId,
763
+ input.projectId
764
+ ]);
765
+ await client.query("UPDATE cards SET default_agent_id = NULL WHERE default_agent_id = $1 AND project_id <> $2", [
766
+ agentId,
767
+ input.projectId
768
+ ]);
769
+ }
770
+ notifyAfterCommit(client, publish, { type: "board_updated", reason: "agent_updated" });
771
+ });
772
+ const agents = await listAgents(pool2);
773
+ return agents.find((a) => a.id === agentId);
774
+ }
775
+ async function deleteAgent(pool2, agentId, publish) {
776
+ await transaction(pool2, async (client) => {
777
+ const res = await client.query("DELETE FROM agents WHERE id = $1", [agentId]);
778
+ if (!res.rowCount) throw new HttpError(404, "Agent \u4E0D\u5B58\u5728");
779
+ await client.query("UPDATE projects SET default_agent_id = NULL WHERE default_agent_id = $1", [agentId]);
780
+ await client.query("UPDATE cards SET default_agent_id = NULL WHERE default_agent_id = $1", [agentId]);
781
+ notifyAfterCommit(client, publish, { type: "board_updated", reason: "agent_deleted" });
782
+ });
783
+ return { ok: true };
784
+ }
785
+ async function reportPresence(pool2, agent, report, publish) {
786
+ await transaction(pool2, async (client) => {
787
+ const prev = (await client.query(
788
+ `SELECT
789
+ (last_heartbeat_at IS NOT NULL AND last_heartbeat_at >= strftime('%Y-%m-%dT%H:%M:%f000Z', 'now', '-30 seconds')) AS online,
790
+ sse_connected, login_state, login_message, driver, auth_mode
791
+ FROM agents WHERE id = $1`,
792
+ [agent.id]
793
+ )).rows[0];
794
+ await client.query(
795
+ `UPDATE agents SET
796
+ adapter_instance_id = $2,
797
+ host_label = $3,
798
+ sse_connected = $4,
799
+ last_event_cursor = $5,
800
+ driver = COALESCE($6, driver),
801
+ auth_mode = COALESCE($7, auth_mode),
802
+ login_state = $8,
803
+ login_message = $9,
804
+ login_reported_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now'),
805
+ last_heartbeat_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
806
+ WHERE id = $1`,
807
+ [
808
+ agent.id,
809
+ report.adapterInstanceId,
810
+ report.hostLabel,
811
+ Number(report.sseConnected),
812
+ report.lastEventCursor,
813
+ report.driver ?? null,
814
+ report.authMode ?? null,
815
+ report.loginState,
816
+ report.loginMessage ?? null
817
+ ]
818
+ );
819
+ await expireLogins(client, agent.id);
820
+ const changed = !prev?.online || Boolean(prev.sse_connected) !== report.sseConnected || prev.login_state !== report.loginState || (prev.login_message ?? null) !== (report.loginMessage ?? null) || report.driver !== void 0 && prev.driver !== report.driver || report.authMode !== void 0 && prev.auth_mode !== report.authMode;
821
+ if (changed) {
822
+ notifyAfterCommit(client, publish, { type: "board_updated", reason: "agent_presence" });
823
+ }
824
+ });
825
+ const row = (await pool2.query(
826
+ `SELECT id, status, expires_at, message, created_at, updated_at
827
+ FROM agent_login_requests
828
+ WHERE agent_id = $1
829
+ AND (status IN ('pending', 'starting', 'waiting_user') OR updated_at >= strftime('%Y-%m-%dT%H:%M:%f000Z', 'now', '-5 minutes'))
830
+ ORDER BY (status IN ('pending', 'starting', 'waiting_user')) DESC, updated_at DESC, id
831
+ LIMIT 1`,
832
+ [agent.id]
833
+ )).rows[0];
834
+ return {
835
+ ok: true,
836
+ pendingLoginRequest: row ? {
837
+ id: row.id,
838
+ status: row.status,
839
+ expiresAt: iso(row.expires_at),
840
+ ...row.message ? { message: row.message } : {},
841
+ createdAt: iso(row.created_at),
842
+ updatedAt: iso(row.updated_at)
843
+ } : null
844
+ };
845
+ }
846
+ async function requestAgentLogin(pool2, agentId, publish) {
847
+ return transaction(pool2, async (client) => {
848
+ const agent = (await client.query(
849
+ `SELECT id, auth_mode,
850
+ (last_heartbeat_at IS NOT NULL AND last_heartbeat_at >= strftime('%Y-%m-%dT%H:%M:%f000Z', 'now', '-30 seconds')) AS online
851
+ FROM agents WHERE id = $1`,
852
+ [agentId]
853
+ )).rows[0];
854
+ if (!agent) throw new HttpError(404, "Agent \u4E0D\u5B58\u5728");
855
+ if (agent.auth_mode !== "device_flow") throw new HttpError(409, "\u8BE5\u6267\u884C\u5668\u4F7F\u7528\u672C\u673A\u767B\u5F55\u6001\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u5B8C\u6210\u767B\u5F55");
856
+ if (!agent.online) throw new HttpError(409, "\u8BF7\u5148\u5728\u672C\u673A\u542F\u52A8\u8BE5 Agent \u63A5\u5165\u8FDB\u7A0B");
857
+ await expireLogins(client, agentId);
858
+ const existing = (await client.query(
859
+ `SELECT * FROM agent_login_requests WHERE agent_id = $1 AND status IN ('pending', 'starting', 'waiting_user')`,
860
+ [agentId]
861
+ )).rows[0];
862
+ if (existing) return { created: false, request: mapLogin(existing) };
863
+ const id = randomUUID();
864
+ const row = (await client.query(
865
+ `INSERT INTO agent_login_requests(id, agent_id, status, expires_at)
866
+ VALUES($1, $2, 'pending', strftime('%Y-%m-%dT%H:%M:%f000Z', 'now', '+16 minutes'))
867
+ RETURNING *`,
868
+ [id, agentId]
869
+ )).rows[0];
870
+ notifyAfterCommit(client, publish, { type: "command", command: "login-requested", agentId, requestId: id });
871
+ notifyAfterCommit(client, publish, { type: "board_updated", reason: "login_requested" });
872
+ return { created: true, request: mapLogin(row) };
873
+ });
874
+ }
875
+ async function cancelAgentLogin(pool2, agentId, requestId, publish) {
876
+ await expireLogins(pool2, agentId);
877
+ return transaction(pool2, async (client) => {
878
+ const row = (await client.query("SELECT * FROM agent_login_requests WHERE agent_id = $1 AND id = $2", [
879
+ agentId,
880
+ requestId
881
+ ])).rows[0];
882
+ if (!row) throw new HttpError(404, "\u767B\u5F55\u8BF7\u6C42\u4E0D\u5B58\u5728");
883
+ if (!ACTIVE_LOGIN_STATUSES.includes(row.status)) throw new HttpError(409, "\u767B\u5F55\u8BF7\u6C42\u5DF2\u7ED3\u675F");
884
+ const updated = (await client.query(
885
+ `UPDATE agent_login_requests
886
+ SET status = 'cancelled', message = '\u767B\u5F55\u8BF7\u6C42\u5DF2\u53D6\u6D88', updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
887
+ WHERE id = $1 RETURNING *`,
888
+ [requestId]
889
+ )).rows[0];
890
+ notifyAfterCommit(client, publish, { type: "board_updated", reason: "login_cancelled" });
891
+ return mapLogin(updated);
892
+ });
893
+ }
894
+ async function reportLoginProgress(pool2, agent, requestId, body, publish) {
895
+ await expireLogins(pool2, agent.id);
896
+ return transaction(pool2, async (client) => {
897
+ const row = (await client.query("SELECT * FROM agent_login_requests WHERE agent_id = $1 AND id = $2", [
898
+ agent.id,
899
+ requestId
900
+ ])).rows[0];
901
+ if (!row) throw new HttpError(404, "\u767B\u5F55\u8BF7\u6C42\u4E0D\u5B58\u5728");
902
+ const allowed = {
903
+ pending: ["starting", "cancelled", "expired"],
904
+ starting: ["starting", "waiting_user", "failed", "cancelled", "expired"],
905
+ waiting_user: ["waiting_user", "succeeded", "failed", "cancelled", "expired"]
906
+ };
907
+ if (!allowed[row.status]?.includes(body.status)) throw new HttpError(409, "\u4E0D\u5141\u8BB8\u7684\u767B\u5F55\u72B6\u6001\u8F6C\u6362");
908
+ const uri = body.status === "waiting_user" ? validateVerificationUri(agent.driver, body.verificationUri) : null;
909
+ const expires = body.expiresAt ? new Date(body.expiresAt) : null;
910
+ const updated = (await client.query(
911
+ `UPDATE agent_login_requests
912
+ SET status = $2,
913
+ verification_uri = COALESCE($3, verification_uri),
914
+ user_code = COALESCE($4, user_code),
915
+ expires_at = MIN(expires_at, COALESCE($5, expires_at)),
916
+ message = $6,
917
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
918
+ WHERE id = $1 RETURNING *`,
919
+ [
920
+ requestId,
921
+ body.status,
922
+ uri,
923
+ body.status === "waiting_user" ? body.userCode ?? null : null,
924
+ expires && Number.isFinite(expires.getTime()) ? expires : null,
925
+ body.message ?? null
926
+ ]
927
+ )).rows[0];
928
+ notifyAfterCommit(client, publish, { type: "board_updated", reason: "login_progress" });
929
+ const { userCode: _u, verificationUri: _v, ...safe } = mapLogin(updated);
930
+ return safe;
931
+ });
932
+ }
933
+
934
+ // src/domain/assistant.ts
935
+ import { randomUUID as randomUUID7 } from "crypto";
936
+
937
+ // src/domain/attachments.ts
938
+ import { execFile } from "child_process";
939
+ import { randomUUID as randomUUID3 } from "crypto";
940
+ import { createWriteStream } from "fs";
941
+ import { chmod, copyFile, mkdir, open, stat, unlink, writeFile } from "fs/promises";
942
+ import path from "path";
943
+ import { promisify } from "util";
944
+
945
+ // src/domain/cards/shared.ts
946
+ import { randomUUID as randomUUID2 } from "crypto";
947
+ var CARD_SELECT = `
948
+ SELECT c.*, p.name AS project_name
949
+ FROM cards c
950
+ JOIN projects p ON p.id = c.project_id
951
+ `;
952
+ var DECISION_SELECT = `
953
+ SELECT d.id, d.card_id, d.agent_id, a.name AS agent_name, a.driver,
954
+ d.question, d.context, d.options, d.status,
955
+ d.selected_option_id, d.selected_option_label, d.response_note,
956
+ d.created_at, d.resolved_at
957
+ FROM card_decisions d
958
+ JOIN agents a ON a.id = d.agent_id
959
+ `;
960
+ var iso2 = (value) => new Date(value).toISOString();
961
+ function bodyPreview(body) {
962
+ const clean = body.replace(/\s+/g, " ").trim();
963
+ return clean.length > 140 ? `${clean.slice(0, 140)}\u2026` : clean;
964
+ }
965
+ function assertAgentProjectAccess(actor, projectId) {
966
+ if (actor.kind === "agent" && actor.projectId && actor.projectId !== projectId) {
967
+ throw new HttpError(403, "\u8BE5 Agent \u65E0\u6743\u8BBF\u95EE\u6B64\u9879\u76EE");
968
+ }
969
+ }
970
+ async function resolveMentionAgents(client, projectId, mentions) {
971
+ const unique = [...new Set(mentions)];
972
+ if (!unique.length) return [];
973
+ const placeholders = unique.map((_, i) => `$${i + 1}`).join(", ");
974
+ const { rows } = await client.query(`SELECT id, name, driver, project_id, enabled FROM agents WHERE id IN (${placeholders})`, unique);
975
+ const byId = new Map(rows.map((row) => [row.id, row]));
976
+ const agents = [];
977
+ for (const agentId of unique) {
978
+ const row = byId.get(agentId);
979
+ if (!row) throw new HttpError(400, `\u6307\u5B9A\u7684 Agent \u4E0D\u5B58\u5728\uFF1A${agentId}`);
980
+ if (row.project_id && row.project_id !== projectId) throw new HttpError(403, `Agent\u300C${row.name}\u300D\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE`);
981
+ if (!row.enabled) throw new HttpError(400, `Agent\u300C${row.name}\u300D\u5DF2\u505C\u7528`);
982
+ agents.push({ id: row.id, name: row.name, driver: row.driver });
983
+ }
984
+ return agents;
985
+ }
986
+ async function validateCardDefaultAgent(client, projectId, agentId) {
987
+ const row = (await client.query(
988
+ "SELECT id, name, project_id FROM agents WHERE id = $1",
989
+ [agentId]
990
+ )).rows[0];
991
+ if (!row) throw new HttpError(400, "\u6307\u5B9A\u7684\u5361\u7247\u9ED8\u8BA4 Agent \u4E0D\u5B58\u5728");
992
+ if (row.project_id && row.project_id !== projectId) {
993
+ throw new HttpError(403, `Agent\u300C${row.name}\u300D\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE`);
994
+ }
995
+ return row;
996
+ }
997
+ async function getCardDefaultAgent(client, projectId, cardDefaultAgentId) {
998
+ if (!cardDefaultAgentId) return null;
999
+ const row = (await client.query(
1000
+ `SELECT id, name, driver
1001
+ FROM agents
1002
+ WHERE id = $1 AND enabled = 1 AND (project_id IS NULL OR project_id = $2)`,
1003
+ [cardDefaultAgentId, projectId]
1004
+ )).rows[0];
1005
+ return row ?? null;
1006
+ }
1007
+ async function getProjectDefaultAgent(client, projectId) {
1008
+ const row = (await client.query(
1009
+ `SELECT a.id, a.name, a.driver
1010
+ FROM projects p JOIN agents a ON a.id = p.default_agent_id
1011
+ WHERE p.id = $1 AND a.enabled = 1 AND (a.project_id IS NULL OR a.project_id = p.id)`,
1012
+ [projectId]
1013
+ )).rows[0];
1014
+ return row ?? null;
1015
+ }
1016
+ async function getEffectiveCardDefaultAgent(client, projectId, cardDefaultAgentId) {
1017
+ return await getCardDefaultAgent(client, projectId, cardDefaultAgentId) ?? getProjectDefaultAgent(client, projectId);
1018
+ }
1019
+ async function appendEvent(client, projectId, cardId, actor, type, data, publish) {
1020
+ const seqRow = (await client.query(
1021
+ `UPDATE event_counter SET value = value + 1 WHERE id = 1 RETURNING CAST(value AS TEXT) AS value`
1022
+ )).rows[0];
1023
+ const id = randomUUID2();
1024
+ await client.query(
1025
+ `INSERT INTO card_events(server_seq, id, project_id, card_id, type, actor_kind, actor_id, actor_name, data)
1026
+ VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
1027
+ [seqRow.value, id, projectId, cardId, type, actor.kind, actor.id, actor.name, JSON.stringify(data)]
1028
+ );
1029
+ const created = (await client.query(
1030
+ `SELECT id, CAST(server_seq AS TEXT) AS server_seq, project_id, card_id, type, actor_kind, actor_id, actor_name, data, created_at
1031
+ FROM card_events WHERE id = $1`,
1032
+ [id]
1033
+ )).rows[0];
1034
+ const targetActorIds = Array.isArray(data.targetActorIds) ? data.targetActorIds : [];
1035
+ notifyAfterCommit(client, publish, {
1036
+ type: "wake",
1037
+ projectId,
1038
+ cardId,
1039
+ eventId: id,
1040
+ serverSeq: seqRow.value,
1041
+ eventType: type,
1042
+ targetActorIds
1043
+ });
1044
+ notifyAfterCommit(client, publish, { type: "board_updated", projectId, cardId, reason: type });
1045
+ return decodeEvent(created);
1046
+ }
1047
+ function decodeEvent(row) {
1048
+ return {
1049
+ id: row.id,
1050
+ serverSeq: row.server_seq,
1051
+ projectId: row.project_id,
1052
+ cardId: row.card_id,
1053
+ type: row.type,
1054
+ actorKind: row.actor_kind,
1055
+ actorId: row.actor_id,
1056
+ actorName: row.actor_name,
1057
+ data: JSON.parse(row.data),
1058
+ createdAt: iso2(row.created_at)
1059
+ };
1060
+ }
1061
+ var SQL_IN_CHUNK_SIZE = 500;
1062
+ function chunkUniqueIds(ids, chunkSize = SQL_IN_CHUNK_SIZE) {
1063
+ const unique = [...new Set(ids)];
1064
+ const chunks = [];
1065
+ for (let i = 0; i < unique.length; i += chunkSize) {
1066
+ chunks.push(unique.slice(i, i + chunkSize));
1067
+ }
1068
+ return chunks;
1069
+ }
1070
+ async function fetchParticipantsByCards(db, cardIds) {
1071
+ const map = /* @__PURE__ */ new Map();
1072
+ for (const chunk of chunkUniqueIds(cardIds)) {
1073
+ const placeholders = chunk.map((_, i) => `$${i + 1}`).join(", ");
1074
+ const { rows } = await db.query(
1075
+ `SELECT cp.card_id, cp.agent_id, a.name AS agent_name, a.driver, cp.state, cp.activity_text,
1076
+ cp.work_dir, cp.branch, cp.processing_event_id,
1077
+ cp.last_outcome, cp.last_outcome_event_id, cp.last_outcome_summary, cp.updated_at,
1078
+ (cp.processing_until IS NOT NULL AND cp.processing_until > strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')) AS processing
1079
+ FROM card_participants cp
1080
+ JOIN agents a ON a.id = cp.agent_id
1081
+ WHERE cp.card_id IN (${placeholders})
1082
+ ORDER BY processing DESC, cp.updated_at DESC`,
1083
+ chunk
1084
+ );
1085
+ for (const r of rows) {
1086
+ const list = map.get(r.card_id) ?? [];
1087
+ list.push({
1088
+ agentId: r.agent_id,
1089
+ agentName: r.agent_name,
1090
+ driver: r.driver,
1091
+ state: r.state,
1092
+ processing: !!r.processing,
1093
+ activityText: r.activity_text,
1094
+ workDir: r.work_dir,
1095
+ branch: r.branch,
1096
+ lastOutcome: r.last_outcome ?? null,
1097
+ lastOutcomeEventId: r.last_outcome_event_id ?? null,
1098
+ lastOutcomeSummary: r.last_outcome_summary ?? null,
1099
+ updatedAt: iso2(r.updated_at)
1100
+ });
1101
+ map.set(r.card_id, list);
1102
+ }
1103
+ }
1104
+ return map;
1105
+ }
1106
+ async function fetchCardCountsByCards(db, cardIds) {
1107
+ const map = /* @__PURE__ */ new Map();
1108
+ for (const chunk of chunkUniqueIds(cardIds)) {
1109
+ const placeholders = chunk.map((_, i) => `$${i + 1}`).join(", ");
1110
+ const [attachmentRows, commentRows, decisionRows] = await Promise.all([
1111
+ db.query(
1112
+ `SELECT card_id, COUNT(*) AS count
1113
+ FROM card_attachments
1114
+ WHERE card_id IN (${placeholders}) AND output_id IS NULL
1115
+ GROUP BY card_id`,
1116
+ chunk
1117
+ ),
1118
+ db.query(
1119
+ `SELECT card_id, COUNT(*) AS count
1120
+ FROM card_events
1121
+ WHERE card_id IN (${placeholders}) AND type = 'comment'
1122
+ GROUP BY card_id`,
1123
+ chunk
1124
+ ),
1125
+ db.query(
1126
+ `SELECT card_id, COUNT(*) AS count
1127
+ FROM card_decisions
1128
+ WHERE card_id IN (${placeholders}) AND status = 'pending'
1129
+ GROUP BY card_id`,
1130
+ chunk
1131
+ )
1132
+ ]);
1133
+ for (const r of attachmentRows.rows) {
1134
+ const existing = map.get(r.card_id);
1135
+ const attachmentCount = Number(r.count ?? 0);
1136
+ if (existing) existing.attachmentCount = attachmentCount;
1137
+ else map.set(r.card_id, { attachmentCount, commentCount: 0, pendingDecisionCount: 0 });
1138
+ }
1139
+ for (const r of commentRows.rows) {
1140
+ const existing = map.get(r.card_id);
1141
+ const commentCount = Number(r.count ?? 0);
1142
+ if (existing) existing.commentCount = commentCount;
1143
+ else map.set(r.card_id, { attachmentCount: 0, commentCount, pendingDecisionCount: 0 });
1144
+ }
1145
+ for (const r of decisionRows.rows) {
1146
+ const existing = map.get(r.card_id);
1147
+ const pendingDecisionCount = Number(r.count ?? 0);
1148
+ if (existing) existing.pendingDecisionCount = pendingDecisionCount;
1149
+ else map.set(r.card_id, { attachmentCount: 0, commentCount: 0, pendingDecisionCount });
1150
+ }
1151
+ }
1152
+ return map;
1153
+ }
1154
+ function toSummary(row, participants, counts) {
1155
+ const checklist = JSON.parse(row.checklist);
1156
+ const outputs = JSON.parse(row.outputs);
1157
+ const tags = JSON.parse(row.tags);
1158
+ return {
1159
+ id: row.id,
1160
+ projectId: row.project_id,
1161
+ projectName: row.project_name,
1162
+ parentId: row.parent_id,
1163
+ defaultAgentId: row.default_agent_id ?? null,
1164
+ title: row.title,
1165
+ bodyPreview: bodyPreview(row.body),
1166
+ status: row.status,
1167
+ priority: row.priority,
1168
+ tags,
1169
+ checklistTotal: checklist.length,
1170
+ checklistDone: checklist.filter((i) => i.done).length,
1171
+ outputCount: outputs.length,
1172
+ attachmentCount: counts?.attachmentCount ?? 0,
1173
+ commentCount: counts?.commentCount ?? 0,
1174
+ pendingDecisionCount: counts?.pendingDecisionCount ?? 0,
1175
+ position: row.position,
1176
+ version: row.version,
1177
+ participants,
1178
+ archivedAt: row.archived_at ? iso2(row.archived_at) : null,
1179
+ completedAt: row.completed_at ? iso2(row.completed_at) : null,
1180
+ createdAt: iso2(row.created_at),
1181
+ updatedAt: iso2(row.updated_at)
1182
+ };
1183
+ }
1184
+ async function buildCardSummaries(db, rows) {
1185
+ if (!rows.length) return [];
1186
+ const cardIds = rows.map((row) => row.id);
1187
+ const [participants, counts] = await Promise.all([
1188
+ fetchParticipantsByCards(db, cardIds),
1189
+ fetchCardCountsByCards(db, cardIds)
1190
+ ]);
1191
+ return rows.map((row) => toSummary(row, participants.get(row.id) ?? [], counts.get(row.id)));
1192
+ }
1193
+ async function buildCardSummary(db, row) {
1194
+ const [summary] = await buildCardSummaries(db, [row]);
1195
+ return summary;
1196
+ }
1197
+ function mapDecision(row) {
1198
+ return {
1199
+ id: row.id,
1200
+ cardId: row.card_id,
1201
+ agentId: row.agent_id,
1202
+ agentName: row.agent_name,
1203
+ driver: row.driver,
1204
+ question: row.question,
1205
+ context: row.context,
1206
+ options: JSON.parse(row.options || "[]"),
1207
+ status: row.status,
1208
+ selectedOptionId: row.selected_option_id,
1209
+ selectedOptionLabel: row.selected_option_label,
1210
+ responseNote: row.response_note,
1211
+ createdAt: iso2(row.created_at),
1212
+ resolvedAt: row.resolved_at ? iso2(row.resolved_at) : null
1213
+ };
1214
+ }
1215
+ async function readCardRow(db, cardId) {
1216
+ const row = (await db.query(`${CARD_SELECT} WHERE c.id = $1`, [cardId])).rows[0];
1217
+ if (!row) throw new HttpError(404, "\u5361\u7247\u4E0D\u5B58\u5728");
1218
+ return row;
1219
+ }
1220
+ async function touchParticipant(client, cardId, agentId, state, activityText) {
1221
+ await client.query(
1222
+ `INSERT INTO card_participants(card_id, agent_id, state, activity_text, updated_at)
1223
+ VALUES($1, $2, $3, $4, strftime('%Y-%m-%dT%H:%M:%f000Z', 'now'))
1224
+ ON CONFLICT(card_id, agent_id) DO UPDATE SET
1225
+ state = COALESCE($5, card_participants.state),
1226
+ activity_text = CASE WHEN $6 <> '' THEN $6 ELSE card_participants.activity_text END,
1227
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')`,
1228
+ [cardId, agentId, state ?? "idle", activityText ?? "", state ?? null, activityText ?? ""]
1229
+ );
1230
+ }
1231
+
1232
+ // src/domain/attachments.ts
1233
+ var execFileAsync = promisify(execFile);
1234
+ var INLINE_IMAGE_MIMES = new Set(IMAGE_ATTACHMENT_MIME_TYPES);
1235
+ var MAX_TEXT_PREVIEW_BYTES = 256 * 1024;
1236
+ var IMAGE_ONLY_ERROR_MESSAGE = "\u4EC5\u652F\u6301 PNG / JPG / WebP / GIF \u683C\u5F0F\u56FE\u7247";
1237
+ var PREVIEWABLE_TEXT_EXTS = /* @__PURE__ */ new Set([
1238
+ ".md",
1239
+ ".markdown",
1240
+ ".txt",
1241
+ ".log",
1242
+ ".json",
1243
+ ".csv",
1244
+ ".yaml",
1245
+ ".yml",
1246
+ ".xml",
1247
+ ".html",
1248
+ ".htm",
1249
+ ".svg",
1250
+ ".ts",
1251
+ ".tsx",
1252
+ ".js",
1253
+ ".mjs",
1254
+ ".cjs",
1255
+ ".jsx",
1256
+ ".css",
1257
+ ".sql",
1258
+ ".sh",
1259
+ ".py",
1260
+ ".go",
1261
+ ".rs",
1262
+ ".toml"
1263
+ ]);
1264
+ function isTextPreviewable(mimeType, filename) {
1265
+ if (mimeType.startsWith("text/")) return true;
1266
+ if (mimeType === "application/json" || mimeType === "application/xml" || mimeType === "application/yaml" || mimeType === "image/svg+xml") {
1267
+ return true;
1268
+ }
1269
+ return PREVIEWABLE_TEXT_EXTS.has(path.extname(filename).toLowerCase());
1270
+ }
1271
+ async function readBoundedUtf8File(filePath, maxBytes) {
1272
+ const handle = await open(filePath, "r");
1273
+ try {
1274
+ const buf = Buffer.allocUnsafe(maxBytes + 1);
1275
+ let offset = 0;
1276
+ while (offset < buf.length) {
1277
+ const { bytesRead } = await handle.read(buf, offset, buf.length - offset, offset);
1278
+ if (bytesRead === 0) break;
1279
+ offset += bytesRead;
1280
+ }
1281
+ const truncated = offset > maxBytes;
1282
+ const slice = buf.subarray(0, truncated ? maxBytes : offset);
1283
+ const content = truncated ? new TextDecoder("utf-8", { ignoreBOM: true }).decode(slice, { stream: true }) : slice.toString("utf8");
1284
+ return { content, truncated };
1285
+ } finally {
1286
+ await handle.close();
1287
+ }
1288
+ }
1289
+ async function revealLocalFile(filePath) {
1290
+ try {
1291
+ if (process.platform === "darwin") {
1292
+ await execFileAsync("open", ["-R", filePath]);
1293
+ } else if (process.platform === "win32") {
1294
+ await execFileAsync("explorer.exe", [`/select,${filePath}`]);
1295
+ } else {
1296
+ await execFileAsync("xdg-open", [path.dirname(filePath)]);
1297
+ }
1298
+ } catch {
1299
+ throw new HttpError(500, "\u65E0\u6CD5\u5728\u672C\u5730\u6587\u4EF6\u7BA1\u7406\u5668\u4E2D\u663E\u793A\u8BE5\u6587\u4EF6");
1300
+ }
1301
+ }
1302
+ var EXT_TO_MIME = {
1303
+ ".png": "image/png",
1304
+ ".jpg": "image/jpeg",
1305
+ ".jpeg": "image/jpeg",
1306
+ ".webp": "image/webp",
1307
+ ".gif": "image/gif",
1308
+ ".svg": "image/svg+xml",
1309
+ ".pdf": "application/pdf",
1310
+ ".txt": "text/plain",
1311
+ ".log": "text/plain",
1312
+ ".md": "text/markdown",
1313
+ ".json": "application/json",
1314
+ ".csv": "text/csv",
1315
+ ".html": "text/html",
1316
+ ".htm": "text/html",
1317
+ ".xml": "application/xml",
1318
+ ".yaml": "application/yaml",
1319
+ ".yml": "application/yaml",
1320
+ ".zip": "application/zip",
1321
+ ".gz": "application/gzip",
1322
+ ".tar": "application/x-tar"
1323
+ };
1324
+ var MIME_TO_EXT = {
1325
+ "image/png": ".png",
1326
+ "image/jpeg": ".jpg",
1327
+ "image/webp": ".webp",
1328
+ "image/gif": ".gif",
1329
+ "application/pdf": ".pdf",
1330
+ "text/plain": ".txt",
1331
+ "text/markdown": ".md",
1332
+ "application/json": ".json",
1333
+ "text/csv": ".csv"
1334
+ };
1335
+ var ATTACHMENT_COLS = "id, project_id, card_id, event_id, output_id, filename, mime_type, kind, size_bytes, storage_path, uploaded_by_kind, uploaded_by_name, created_at";
1336
+ function sanitizeFilename(raw) {
1337
+ const cleaned2 = raw.replace(/[\x00-\x1f\x7f/\\]/g, "_").trim();
1338
+ if (!cleaned2 || cleaned2 === "." || cleaned2 === "..") return "attachment";
1339
+ return cleaned2.slice(0, 255);
1340
+ }
1341
+ function normalizeMimeType(rawMime, filename) {
1342
+ const base = rawMime?.split(";")[0]?.trim().toLowerCase() ?? "";
1343
+ const validMime = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(base) ? base.slice(0, 128) : "";
1344
+ if (validMime && validMime !== "application/octet-stream") {
1345
+ return validMime;
1346
+ }
1347
+ const ext = path.extname(filename).toLowerCase();
1348
+ return EXT_TO_MIME[ext] ?? "application/octet-stream";
1349
+ }
1350
+ function resolveSafeStoragePath(uploadsRoot, storagePath) {
1351
+ const root = path.resolve(uploadsRoot);
1352
+ const full = path.resolve(root, storagePath);
1353
+ if (full !== root && !full.startsWith(root + path.sep)) {
1354
+ throw new HttpError(400, "\u975E\u6CD5\u9644\u4EF6\u5B58\u50A8\u8DEF\u5F84");
1355
+ }
1356
+ return full;
1357
+ }
1358
+ function safeExtension(filename, mimeType) {
1359
+ const ext = path.extname(filename).toLowerCase();
1360
+ if (/^\.[a-z0-9]{1,10}$/.test(ext)) return ext;
1361
+ return MIME_TO_EXT[mimeType] ?? "";
1362
+ }
1363
+ function buildContentDisposition(filename, inline) {
1364
+ const type = inline ? "inline" : "attachment";
1365
+ const asciiFallback = filename.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_") || "attachment";
1366
+ const encoded = encodeURIComponent(filename).replace(
1367
+ /['()*]/g,
1368
+ (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`
1369
+ );
1370
+ return `${type}; filename="${asciiFallback}"; filename*=UTF-8''${encoded}`;
1371
+ }
1372
+ function mapAttachment(row, uploadsRoot) {
1373
+ return {
1374
+ id: row.id,
1375
+ projectId: row.project_id,
1376
+ cardId: row.card_id,
1377
+ eventId: row.event_id ?? null,
1378
+ filename: row.filename,
1379
+ mimeType: row.mime_type,
1380
+ kind: row.kind,
1381
+ sizeBytes: Number(row.size_bytes),
1382
+ url: `/v1/attachments/${row.id}/content`,
1383
+ localPath: resolveSafeStoragePath(uploadsRoot, row.storage_path),
1384
+ uploadedByKind: row.uploaded_by_kind,
1385
+ uploadedByName: row.uploaded_by_name,
1386
+ createdAt: iso2(row.created_at)
1387
+ };
1388
+ }
1389
+ async function writeBoundedStream(stream, filePath, maxBytes) {
1390
+ await mkdir(path.dirname(filePath), { recursive: true, mode: 448 });
1391
+ const ws = createWriteStream(filePath, { mode: 384 });
1392
+ let sizeBytes = 0;
1393
+ try {
1394
+ for await (const chunk of stream) {
1395
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1396
+ sizeBytes += buf.length;
1397
+ if (sizeBytes > maxBytes) {
1398
+ ws.destroy();
1399
+ stream.destroy();
1400
+ throw new HttpError(413, `\u5355\u4E2A\u9644\u4EF6\u4E0D\u80FD\u8D85\u8FC7 ${Math.round(maxBytes / (1024 * 1024))}MB`);
1401
+ }
1402
+ if (!ws.write(buf)) {
1403
+ await new Promise((resolve3, reject) => {
1404
+ ws.once("drain", resolve3);
1405
+ ws.once("error", reject);
1406
+ });
1407
+ }
1408
+ }
1409
+ await new Promise((resolve3, reject) => {
1410
+ ws.once("finish", resolve3);
1411
+ ws.once("error", reject);
1412
+ ws.end();
1413
+ });
1414
+ if (sizeBytes === 0) {
1415
+ throw new HttpError(400, "\u9644\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A");
1416
+ }
1417
+ return sizeBytes;
1418
+ } catch (err) {
1419
+ ws.destroy();
1420
+ await unlink(filePath).catch(() => {
1421
+ });
1422
+ throw err;
1423
+ }
1424
+ }
1425
+ async function uploadAttachment(pool2, actor, input, uploadsRoot, publish) {
1426
+ assertAgentProjectAccess(actor, input.projectId);
1427
+ if (input.contentLength !== void 0 && input.contentLength > ATTACHMENT_MAX_BYTES) {
1428
+ input.stream.resume();
1429
+ throw new HttpError(413, `\u5355\u4E2A\u9644\u4EF6\u4E0D\u80FD\u8D85\u8FC7 ${Math.round(ATTACHMENT_MAX_BYTES / (1024 * 1024))}MB`);
1430
+ }
1431
+ const filename = sanitizeFilename(input.filename);
1432
+ const mimeType = normalizeMimeType(input.mimeType, filename);
1433
+ const kind = INLINE_IMAGE_MIMES.has(mimeType) ? "image" : "file";
1434
+ if (input.imagesOnly && kind !== "image") {
1435
+ input.stream.resume();
1436
+ throw new HttpError(400, IMAGE_ONLY_ERROR_MESSAGE);
1437
+ }
1438
+ const project = (await pool2.query("SELECT id FROM projects WHERE id = $1", [input.projectId])).rows[0];
1439
+ if (!project) {
1440
+ input.stream.resume();
1441
+ throw new HttpError(404, "\u9879\u76EE\u4E0D\u5B58\u5728");
1442
+ }
1443
+ if (input.cardId) {
1444
+ const card = (await pool2.query("SELECT id, project_id FROM cards WHERE id = $1", [
1445
+ input.cardId
1446
+ ])).rows[0];
1447
+ if (!card) {
1448
+ input.stream.resume();
1449
+ throw new HttpError(404, "\u5361\u7247\u4E0D\u5B58\u5728");
1450
+ }
1451
+ if (card.project_id !== input.projectId) {
1452
+ input.stream.resume();
1453
+ throw new HttpError(400, "\u9644\u4EF6\u6240\u5C5E\u9879\u76EE\u4E0E\u5361\u7247\u4E0D\u4E00\u81F4");
1454
+ }
1455
+ const existingCount = (await pool2.query(
1456
+ "SELECT COUNT(*) AS count FROM card_attachments WHERE card_id = $1 AND event_id IS NULL AND output_id IS NULL",
1457
+ [input.cardId]
1458
+ )).rows[0].count;
1459
+ if (existingCount >= CARD_MAX_ATTACHMENTS) {
1460
+ input.stream.resume();
1461
+ throw new HttpError(400, `\u5355\u5F20\u5361\u7247\u6700\u591A\u652F\u6301 ${CARD_MAX_ATTACHMENTS} \u4E2A\u9644\u4EF6`);
1462
+ }
1463
+ }
1464
+ const id = randomUUID3();
1465
+ const ext = safeExtension(filename, mimeType);
1466
+ const now = /* @__PURE__ */ new Date();
1467
+ const ym = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}`;
1468
+ const storagePath = `${input.projectId}/${ym}/${id}${ext}`;
1469
+ const diskPath = resolveSafeStoragePath(uploadsRoot, storagePath);
1470
+ const sizeBytes = await writeBoundedStream(input.stream, diskPath, ATTACHMENT_MAX_BYTES);
1471
+ try {
1472
+ const row = await transaction(pool2, async (client) => {
1473
+ if (input.cardId) {
1474
+ const card = (await client.query("SELECT project_id FROM cards WHERE id = $1", [input.cardId])).rows[0];
1475
+ if (!card) throw new HttpError(404, "\u5361\u7247\u4E0D\u5B58\u5728");
1476
+ if (card.project_id !== input.projectId) throw new HttpError(400, "\u9644\u4EF6\u6240\u5C5E\u9879\u76EE\u4E0E\u5361\u7247\u4E0D\u4E00\u81F4");
1477
+ const count = (await client.query(
1478
+ "SELECT COUNT(*) AS count FROM card_attachments WHERE card_id = $1 AND event_id IS NULL AND output_id IS NULL",
1479
+ [input.cardId]
1480
+ )).rows[0].count;
1481
+ if (count >= CARD_MAX_ATTACHMENTS) {
1482
+ throw new HttpError(400, `\u5355\u5F20\u5361\u7247\u6700\u591A\u652F\u6301 ${CARD_MAX_ATTACHMENTS} \u4E2A\u9644\u4EF6`);
1483
+ }
1484
+ }
1485
+ const inserted = (await client.query(
1486
+ `INSERT INTO card_attachments(
1487
+ id, project_id, card_id, event_id, filename, mime_type, kind, size_bytes, storage_path, uploaded_by_kind, uploaded_by_name
1488
+ ) VALUES($1, $2, $3, NULL, $4, $5, $6, $7, $8, $9, $10)
1489
+ RETURNING ${ATTACHMENT_COLS}`,
1490
+ [
1491
+ id,
1492
+ input.projectId,
1493
+ input.cardId ?? null,
1494
+ filename,
1495
+ mimeType,
1496
+ kind,
1497
+ sizeBytes,
1498
+ storagePath,
1499
+ actor.kind,
1500
+ actor.name
1501
+ ]
1502
+ )).rows[0];
1503
+ if (input.cardId) {
1504
+ await client.query(`UPDATE cards SET updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now') WHERE id = $1`, [
1505
+ input.cardId
1506
+ ]);
1507
+ notifyAfterCommit(client, publish, {
1508
+ type: "board_updated",
1509
+ projectId: input.projectId,
1510
+ cardId: input.cardId,
1511
+ reason: "attachment_added"
1512
+ });
1513
+ }
1514
+ return inserted;
1515
+ });
1516
+ return mapAttachment(row, uploadsRoot);
1517
+ } catch (err) {
1518
+ await unlink(diskPath).catch(() => {
1519
+ });
1520
+ throw err;
1521
+ }
1522
+ }
1523
+ async function getAttachmentContent(pool2, actor, attachmentId, uploadsRoot, options) {
1524
+ const row = (await pool2.query(`SELECT ${ATTACHMENT_COLS} FROM card_attachments WHERE id = $1`, [attachmentId])).rows[0];
1525
+ if (!row) throw new HttpError(404, "\u9644\u4EF6\u4E0D\u5B58\u5728");
1526
+ assertAgentProjectAccess(actor, row.project_id);
1527
+ const filePath = resolveSafeStoragePath(uploadsRoot, row.storage_path);
1528
+ let info;
1529
+ try {
1530
+ info = await stat(filePath);
1531
+ } catch {
1532
+ throw new HttpError(404, "\u9644\u4EF6\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u79FB\u9664");
1533
+ }
1534
+ if (!info.isFile()) throw new HttpError(404, "\u9644\u4EF6\u6587\u4EF6\u4E0D\u53EF\u8BFB\u53D6");
1535
+ const inline = !options?.forceDownload && INLINE_IMAGE_MIMES.has(row.mime_type);
1536
+ const isActiveMarkup = row.mime_type === "image/svg+xml" || row.mime_type === "text/html" || row.mime_type === "application/xhtml+xml";
1537
+ const contentType = inline ? row.mime_type : isActiveMarkup ? "application/octet-stream" : row.mime_type;
1538
+ return {
1539
+ filePath,
1540
+ sizeBytes: info.size,
1541
+ contentType,
1542
+ contentDisposition: buildContentDisposition(row.filename, inline)
1543
+ };
1544
+ }
1545
+ async function getAttachmentLocalPath(pool2, actor, attachmentId, uploadsRoot) {
1546
+ const row = (await pool2.query(`SELECT ${ATTACHMENT_COLS} FROM card_attachments WHERE id = $1`, [attachmentId])).rows[0];
1547
+ if (!row) throw new HttpError(404, "\u9644\u4EF6\u4E0D\u5B58\u5728");
1548
+ assertAgentProjectAccess(actor, row.project_id);
1549
+ const filePath = resolveSafeStoragePath(uploadsRoot, row.storage_path);
1550
+ let info;
1551
+ try {
1552
+ info = await stat(filePath);
1553
+ } catch {
1554
+ throw new HttpError(404, "\u9644\u4EF6\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u79FB\u9664");
1555
+ }
1556
+ if (!info.isFile()) throw new HttpError(404, "\u9644\u4EF6\u6587\u4EF6\u4E0D\u53EF\u8BFB\u53D6");
1557
+ return filePath;
1558
+ }
1559
+ async function previewAttachmentText(pool2, actor, attachmentId, uploadsRoot) {
1560
+ const row = (await pool2.query(`SELECT ${ATTACHMENT_COLS} FROM card_attachments WHERE id = $1`, [attachmentId])).rows[0];
1561
+ if (!row) throw new HttpError(404, "\u9644\u4EF6\u4E0D\u5B58\u5728");
1562
+ assertAgentProjectAccess(actor, row.project_id);
1563
+ if (!isTextPreviewable(row.mime_type, row.filename)) {
1564
+ throw new HttpError(400, "\u8BE5\u9644\u4EF6\u4E0D\u652F\u6301\u6587\u672C\u9884\u89C8\uFF0C\u8BF7\u5728\u8BBF\u8FBE\u4E2D\u67E5\u770B\u6216\u67E5\u770B\u539F\u56FE");
1565
+ }
1566
+ const filePath = resolveSafeStoragePath(uploadsRoot, row.storage_path);
1567
+ let info;
1568
+ try {
1569
+ info = await stat(filePath);
1570
+ } catch {
1571
+ throw new HttpError(404, "\u9644\u4EF6\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u79FB\u9664");
1572
+ }
1573
+ if (!info.isFile()) throw new HttpError(404, "\u9644\u4EF6\u6587\u4EF6\u4E0D\u53EF\u8BFB\u53D6");
1574
+ const { content, truncated } = await readBoundedUtf8File(filePath, MAX_TEXT_PREVIEW_BYTES);
1575
+ return {
1576
+ attachmentId: row.id,
1577
+ filename: row.filename,
1578
+ mimeType: row.mime_type,
1579
+ localPath: filePath,
1580
+ content,
1581
+ truncated
1582
+ };
1583
+ }
1584
+ async function cloneAttachments(pool2, actor, input, uploadsRoot) {
1585
+ assertAgentProjectAccess(actor, input.projectId);
1586
+ const uniqueIds = [...new Set(input.attachmentIds)];
1587
+ if (uniqueIds.length === 0) return [];
1588
+ if (uniqueIds.length > CARD_MAX_ATTACHMENTS) {
1589
+ throw new HttpError(400, `\u5355\u6B21\u6700\u591A\u652F\u6301\u514B\u9686 ${CARD_MAX_ATTACHMENTS} \u4E2A\u9644\u4EF6`);
1590
+ }
1591
+ const placeholders = uniqueIds.map((_, i) => `$${i + 1}`).join(", ");
1592
+ const { rows } = await pool2.query(
1593
+ `SELECT ${ATTACHMENT_COLS} FROM card_attachments WHERE id IN (${placeholders})`,
1594
+ uniqueIds
1595
+ );
1596
+ const byId = new Map(rows.map((r) => [r.id, r]));
1597
+ const sources = [];
1598
+ for (const id of uniqueIds) {
1599
+ const row = byId.get(id);
1600
+ if (!row) throw new HttpError(404, `\u9644\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u8FC7\u671F\uFF1A${id}`);
1601
+ if (row.project_id !== input.projectId) throw new HttpError(400, "\u9644\u4EF6\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE");
1602
+ if (row.output_id !== null) throw new HttpError(400, "\u4E0D\u652F\u6301\u5C06\u4EA7\u51FA\u6587\u4EF6\u514B\u9686\u4E3A\u5361\u7247\u8F93\u5165\u9644\u4EF6");
1603
+ const srcPath = resolveSafeStoragePath(uploadsRoot, row.storage_path);
1604
+ let info;
1605
+ try {
1606
+ info = await stat(srcPath);
1607
+ } catch {
1608
+ throw new HttpError(404, `\u9644\u4EF6\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u79FB\u9664\uFF1A${row.filename}`);
1609
+ }
1610
+ if (!info.isFile()) throw new HttpError(404, `\u9644\u4EF6\u6587\u4EF6\u4E0D\u53EF\u8BFB\u53D6\uFF1A${row.filename}`);
1611
+ sources.push({ row, srcPath });
1612
+ }
1613
+ const now = /* @__PURE__ */ new Date();
1614
+ const ym = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}`;
1615
+ const staged = [];
1616
+ try {
1617
+ for (const { row, srcPath } of sources) {
1618
+ const id = randomUUID3();
1619
+ const ext = safeExtension(row.filename, row.mime_type);
1620
+ const storagePath = `${input.projectId}/${ym}/${id}${ext}`;
1621
+ const diskPath = resolveSafeStoragePath(uploadsRoot, storagePath);
1622
+ await mkdir(path.dirname(diskPath), { recursive: true, mode: 448 });
1623
+ await copyFile(srcPath, diskPath);
1624
+ await chmod(diskPath, 384);
1625
+ staged.push({ id, source: row, storagePath, diskPath });
1626
+ }
1627
+ const insertedRows = await transaction(pool2, async (client) => {
1628
+ const out = [];
1629
+ for (const item of staged) {
1630
+ const inserted = (await client.query(
1631
+ `INSERT INTO card_attachments(
1632
+ id, project_id, card_id, event_id, filename, mime_type, kind, size_bytes, storage_path, uploaded_by_kind, uploaded_by_name
1633
+ ) VALUES($1, $2, NULL, NULL, $3, $4, $5, $6, $7, $8, $9)
1634
+ RETURNING ${ATTACHMENT_COLS}`,
1635
+ [
1636
+ item.id,
1637
+ input.projectId,
1638
+ item.source.filename,
1639
+ item.source.mime_type,
1640
+ item.source.kind,
1641
+ item.source.size_bytes,
1642
+ item.storagePath,
1643
+ actor.kind,
1644
+ actor.name
1645
+ ]
1646
+ )).rows[0];
1647
+ out.push(inserted);
1648
+ }
1649
+ return out;
1650
+ });
1651
+ return insertedRows.map((row) => mapAttachment(row, uploadsRoot));
1652
+ } catch (err) {
1653
+ await Promise.all(staged.map((item) => unlink(item.diskPath).catch(() => {
1654
+ })));
1655
+ throw err;
1656
+ }
1657
+ }
1658
+ async function deleteAttachment(pool2, attachmentId, uploadsRoot, publish) {
1659
+ let storagePath = "";
1660
+ await transaction(pool2, async (client) => {
1661
+ const row = (await client.query(
1662
+ "SELECT id, project_id, card_id, storage_path FROM card_attachments WHERE id = $1",
1663
+ [attachmentId]
1664
+ )).rows[0];
1665
+ if (!row) throw new HttpError(404, "\u9644\u4EF6\u4E0D\u5B58\u5728");
1666
+ storagePath = row.storage_path;
1667
+ await client.query("DELETE FROM card_attachments WHERE id = $1", [attachmentId]);
1668
+ if (row.card_id) {
1669
+ await client.query(`UPDATE cards SET updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now') WHERE id = $1`, [
1670
+ row.card_id
1671
+ ]);
1672
+ notifyAfterCommit(client, publish, {
1673
+ type: "board_updated",
1674
+ projectId: row.project_id,
1675
+ cardId: row.card_id,
1676
+ reason: "attachment_deleted"
1677
+ });
1678
+ }
1679
+ });
1680
+ if (storagePath) {
1681
+ await unlink(resolveSafeStoragePath(uploadsRoot, storagePath)).catch(() => {
1682
+ });
1683
+ }
1684
+ return { ok: true };
1685
+ }
1686
+ async function bindAttachmentsToCard(client, projectId, cardId, attachmentIds) {
1687
+ const unique = [...new Set(attachmentIds)];
1688
+ if (unique.length === 0) return;
1689
+ if (unique.length > CARD_MAX_ATTACHMENTS) {
1690
+ throw new HttpError(400, `\u5355\u5F20\u5361\u7247\u6700\u591A\u652F\u6301 ${CARD_MAX_ATTACHMENTS} \u4E2A\u9644\u4EF6`);
1691
+ }
1692
+ const placeholders = unique.map((_, i) => `$${i + 1}`).join(", ");
1693
+ const { rows } = await client.query(
1694
+ `SELECT id, project_id, card_id, event_id, output_id, kind FROM card_attachments WHERE id IN (${placeholders})`,
1695
+ unique
1696
+ );
1697
+ const byId = new Map(rows.map((r) => [r.id, r]));
1698
+ for (const id of unique) {
1699
+ const row = byId.get(id);
1700
+ if (!row) throw new HttpError(400, `\u9644\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u8FC7\u671F\uFF1A${id}`);
1701
+ if (row.project_id !== projectId) throw new HttpError(400, "\u9644\u4EF6\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE");
1702
+ if (row.card_id !== null || row.event_id !== null || row.output_id !== null) {
1703
+ throw new HttpError(400, "\u9644\u4EF6\u5DF2\u7ED1\u5B9A\u5230\u5176\u4ED6\u5361\u7247");
1704
+ }
1705
+ }
1706
+ const updatePlaceholders = unique.map((_, i) => `$${i + 3}`).join(", ");
1707
+ await client.query(
1708
+ `UPDATE card_attachments
1709
+ SET card_id = $1
1710
+ WHERE project_id = $2 AND card_id IS NULL AND event_id IS NULL AND output_id IS NULL AND id IN (${updatePlaceholders})`,
1711
+ [cardId, projectId, ...unique]
1712
+ );
1713
+ }
1714
+ async function validateAssistantRunAttachments(client, projectId, attachmentIds) {
1715
+ const unique = [...new Set(attachmentIds)];
1716
+ if (unique.length === 0) return [];
1717
+ if (unique.length > CARD_MAX_ATTACHMENTS) {
1718
+ throw new HttpError(400, `\u5355\u6B21\u6700\u591A\u652F\u6301\u9644\u52A0 ${CARD_MAX_ATTACHMENTS} \u4E2A\u9644\u4EF6`);
1719
+ }
1720
+ const placeholders = unique.map((_, i) => `$${i + 1}`).join(", ");
1721
+ const { rows } = await client.query(
1722
+ `SELECT id, project_id, kind FROM card_attachments WHERE id IN (${placeholders})`,
1723
+ unique
1724
+ );
1725
+ const byId = new Map(rows.map((r) => [r.id, r]));
1726
+ for (const id of unique) {
1727
+ const row = byId.get(id);
1728
+ if (!row) throw new HttpError(400, `\u9644\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u8FC7\u671F\uFF1A${id}`);
1729
+ if (row.project_id !== projectId) throw new HttpError(400, "\u9644\u4EF6\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE");
1730
+ }
1731
+ return unique;
1732
+ }
1733
+ async function validateCommentAttachments(client, projectId, attachmentIds) {
1734
+ const unique = [...new Set(attachmentIds)];
1735
+ if (unique.length === 0) return [];
1736
+ if (unique.length > COMMENT_MAX_ATTACHMENTS) {
1737
+ throw new HttpError(400, `\u5355\u6761\u8BC4\u8BBA\u6700\u591A\u652F\u6301 ${COMMENT_MAX_ATTACHMENTS} \u4E2A\u9644\u4EF6`);
1738
+ }
1739
+ const placeholders = unique.map((_, i) => `$${i + 1}`).join(", ");
1740
+ const { rows } = await client.query(
1741
+ `SELECT id, project_id, card_id, event_id, output_id, kind FROM card_attachments WHERE id IN (${placeholders})`,
1742
+ unique
1743
+ );
1744
+ const byId = new Map(rows.map((r) => [r.id, r]));
1745
+ for (const id of unique) {
1746
+ const row = byId.get(id);
1747
+ if (!row) throw new HttpError(400, `\u9644\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u8FC7\u671F\uFF1A${id}`);
1748
+ if (row.project_id !== projectId) throw new HttpError(400, "\u9644\u4EF6\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE");
1749
+ if (row.card_id !== null || row.event_id !== null || row.output_id !== null) {
1750
+ throw new HttpError(400, "\u9644\u4EF6\u5DF2\u7ED1\u5B9A\u5230\u5176\u4ED6\u5361\u7247\u6216\u8BC4\u8BBA");
1751
+ }
1752
+ }
1753
+ return unique;
1754
+ }
1755
+ async function bindAttachmentsToComment(client, projectId, cardId, eventId, attachmentIds, uploadsRoot) {
1756
+ if (attachmentIds.length === 0) return [];
1757
+ const placeholders = attachmentIds.map((_, i) => `$${i + 4}`).join(", ");
1758
+ await client.query(
1759
+ `UPDATE card_attachments
1760
+ SET card_id = $1, event_id = $2
1761
+ WHERE project_id = $3 AND card_id IS NULL AND event_id IS NULL AND output_id IS NULL AND id IN (${placeholders})`,
1762
+ [cardId, eventId, projectId, ...attachmentIds]
1763
+ );
1764
+ return fetchAttachmentsByIds(client, projectId, attachmentIds, uploadsRoot);
1765
+ }
1766
+ async function fetchCardAttachments(db, cardId, uploadsRoot) {
1767
+ const { rows } = await db.query(
1768
+ `SELECT ${ATTACHMENT_COLS}
1769
+ FROM card_attachments
1770
+ WHERE card_id = $1 AND event_id IS NULL AND output_id IS NULL
1771
+ ORDER BY created_at ASC, id ASC`,
1772
+ [cardId]
1773
+ );
1774
+ return rows.map((row) => mapAttachment(row, uploadsRoot));
1775
+ }
1776
+ async function stageManagedOutputText(uploadsRoot, projectId, rawFilename, rawMimeType, content) {
1777
+ const id = randomUUID3();
1778
+ const filename = sanitizeFilename(rawFilename);
1779
+ const mimeType = normalizeMimeType(rawMimeType, filename);
1780
+ const kind = INLINE_IMAGE_MIMES.has(mimeType) ? "image" : "file";
1781
+ const ext = safeExtension(filename, mimeType);
1782
+ const now = /* @__PURE__ */ new Date();
1783
+ const ym = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}`;
1784
+ const storagePath = `${projectId}/${ym}/${id}${ext}`;
1785
+ const diskPath = resolveSafeStoragePath(uploadsRoot, storagePath);
1786
+ const buf = Buffer.from(content, "utf8");
1787
+ if (buf.byteLength === 0) throw new HttpError(400, "\u4EA7\u51FA\u6587\u6863\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A");
1788
+ if (buf.byteLength > ATTACHMENT_MAX_BYTES) {
1789
+ throw new HttpError(413, `\u5355\u4E2A\u4EA7\u51FA\u6587\u4EF6\u4E0D\u80FD\u8D85\u8FC7 ${Math.round(ATTACHMENT_MAX_BYTES / (1024 * 1024))}MB`);
1790
+ }
1791
+ await mkdir(path.dirname(diskPath), { recursive: true, mode: 448 });
1792
+ await writeFile(diskPath, buf, { mode: 384 });
1793
+ return { id, filename, mimeType, kind, sizeBytes: buf.byteLength, storagePath, diskPath };
1794
+ }
1795
+ async function insertManagedOutputAttachment(client, actor, staged, projectId, cardId, outputId, uploadsRoot) {
1796
+ const inserted = (await client.query(
1797
+ `INSERT INTO card_attachments(
1798
+ id, project_id, card_id, event_id, output_id, filename, mime_type, kind, size_bytes, storage_path, uploaded_by_kind, uploaded_by_name
1799
+ ) VALUES($1, $2, $3, NULL, $4, $5, $6, $7, $8, $9, $10, $11)
1800
+ RETURNING ${ATTACHMENT_COLS}`,
1801
+ [
1802
+ staged.id,
1803
+ projectId,
1804
+ cardId,
1805
+ outputId,
1806
+ staged.filename,
1807
+ staged.mimeType,
1808
+ staged.kind,
1809
+ staged.sizeBytes,
1810
+ staged.storagePath,
1811
+ actor.kind,
1812
+ actor.name
1813
+ ]
1814
+ )).rows[0];
1815
+ return mapAttachment(inserted, uploadsRoot);
1816
+ }
1817
+ async function bindAttachmentToOutput(client, projectId, cardId, outputId, attachmentId, uploadsRoot) {
1818
+ const row = (await client.query(`SELECT ${ATTACHMENT_COLS} FROM card_attachments WHERE id = $1`, [attachmentId])).rows[0];
1819
+ if (!row) throw new HttpError(400, `\u4EA7\u51FA\u9644\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u8FC7\u671F\uFF1A${attachmentId}`);
1820
+ if (row.project_id !== projectId) throw new HttpError(400, "\u4EA7\u51FA\u9644\u4EF6\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE");
1821
+ if (row.card_id !== null || row.event_id !== null || row.output_id !== null) {
1822
+ throw new HttpError(400, "\u4EA7\u51FA\u9644\u4EF6\u5DF2\u7ED1\u5B9A\u5230\u5176\u4ED6\u5361\u7247\u3001\u8BC4\u8BBA\u6216\u4EA7\u51FA");
1823
+ }
1824
+ const updated = (await client.query(
1825
+ `UPDATE card_attachments
1826
+ SET card_id = $1, output_id = $2
1827
+ WHERE id = $3 AND project_id = $4 AND card_id IS NULL AND event_id IS NULL AND output_id IS NULL
1828
+ RETURNING ${ATTACHMENT_COLS}`,
1829
+ [cardId, outputId, attachmentId, projectId]
1830
+ )).rows[0];
1831
+ if (!updated) throw new HttpError(409, "\u4EA7\u51FA\u9644\u4EF6\u7ED1\u5B9A\u51B2\u7A81\uFF0C\u8BF7\u91CD\u8BD5");
1832
+ return mapAttachment(updated, uploadsRoot);
1833
+ }
1834
+ async function fetchAttachmentsByOutputIds(db, cardId, outputIds, uploadsRoot) {
1835
+ const map = /* @__PURE__ */ new Map();
1836
+ const unique = [...new Set(outputIds)];
1837
+ if (unique.length === 0) return map;
1838
+ const placeholders = unique.map((_, i) => `$${i + 2}`).join(", ");
1839
+ const { rows } = await db.query(
1840
+ `SELECT ${ATTACHMENT_COLS}
1841
+ FROM card_attachments
1842
+ WHERE card_id = $1 AND output_id IN (${placeholders})`,
1843
+ [cardId, ...unique]
1844
+ );
1845
+ for (const row of rows) {
1846
+ if (row.output_id) map.set(row.output_id, mapAttachment(row, uploadsRoot));
1847
+ }
1848
+ return map;
1849
+ }
1850
+ async function getOutputAttachmentFile(db, cardId, outputId, attachmentId, uploadsRoot) {
1851
+ const row = (await db.query(
1852
+ `SELECT ${ATTACHMENT_COLS}
1853
+ FROM card_attachments
1854
+ WHERE id = $1 AND card_id = $2 AND output_id = $3`,
1855
+ [attachmentId, cardId, outputId]
1856
+ )).rows[0];
1857
+ if (!row) return null;
1858
+ return {
1859
+ filename: row.filename,
1860
+ mimeType: row.mime_type,
1861
+ kind: row.kind,
1862
+ filePath: resolveSafeStoragePath(uploadsRoot, row.storage_path)
1863
+ };
1864
+ }
1865
+ async function fetchAttachmentsByEventIds(db, eventIds, uploadsRoot) {
1866
+ const map = /* @__PURE__ */ new Map();
1867
+ const unique = [...new Set(eventIds)];
1868
+ if (unique.length === 0) return map;
1869
+ const chunkSize = 500;
1870
+ for (let i = 0; i < unique.length; i += chunkSize) {
1871
+ const chunk = unique.slice(i, i + chunkSize);
1872
+ const placeholders = chunk.map((_, idx) => `$${idx + 1}`).join(", ");
1873
+ const { rows } = await db.query(
1874
+ `SELECT ${ATTACHMENT_COLS}
1875
+ FROM card_attachments
1876
+ WHERE event_id IN (${placeholders})
1877
+ ORDER BY created_at ASC, id ASC`,
1878
+ chunk
1879
+ );
1880
+ for (const row of rows) {
1881
+ if (!row.event_id) continue;
1882
+ const list = map.get(row.event_id) ?? [];
1883
+ list.push(mapAttachment(row, uploadsRoot));
1884
+ map.set(row.event_id, list);
1885
+ }
1886
+ }
1887
+ return map;
1888
+ }
1889
+ async function fetchAttachmentsByIds(db, projectId, attachmentIds, uploadsRoot) {
1890
+ const unique = [...new Set(attachmentIds)];
1891
+ if (unique.length === 0) return [];
1892
+ const placeholders = unique.map((_, i) => `$${i + 2}`).join(", ");
1893
+ const { rows } = await db.query(
1894
+ `SELECT ${ATTACHMENT_COLS}
1895
+ FROM card_attachments
1896
+ WHERE project_id = $1 AND id IN (${placeholders})`,
1897
+ [projectId, ...unique]
1898
+ );
1899
+ const byId = new Map(rows.map((row) => [row.id, mapAttachment(row, uploadsRoot)]));
1900
+ const ordered = [];
1901
+ for (const id of unique) {
1902
+ const found = byId.get(id);
1903
+ if (found) ordered.push(found);
1904
+ }
1905
+ return ordered;
1906
+ }
1907
+ async function collectStoragePathsForCard(client, cardId) {
1908
+ const { rows } = await client.query(
1909
+ "SELECT storage_path FROM card_attachments WHERE card_id = $1",
1910
+ [cardId]
1911
+ );
1912
+ return rows.map((r) => r.storage_path);
1913
+ }
1914
+ async function collectStoragePathsForProject(client, projectId) {
1915
+ const { rows } = await client.query(
1916
+ "SELECT storage_path FROM card_attachments WHERE project_id = $1",
1917
+ [projectId]
1918
+ );
1919
+ return rows.map((r) => r.storage_path);
1920
+ }
1921
+ async function unlinkStoragePaths(uploadsRoot, storagePaths) {
1922
+ await Promise.all(
1923
+ storagePaths.map((sp) => {
1924
+ try {
1925
+ return unlink(resolveSafeStoragePath(uploadsRoot, sp)).catch(() => {
1926
+ });
1927
+ } catch {
1928
+ return Promise.resolve();
1929
+ }
1930
+ })
1931
+ );
1932
+ }
1933
+ async function cleanupOrphanAttachments(pool2, uploadsRoot, maxAgeMs = 24 * 60 * 60 * 1e3) {
1934
+ const cutoff = new Date(Date.now() - maxAgeMs).toISOString();
1935
+ const stale = await transaction(pool2, async (client) => {
1936
+ const { rows } = await client.query(
1937
+ `SELECT storage_path FROM card_attachments WHERE card_id IS NULL AND created_at < $1`,
1938
+ [cutoff]
1939
+ );
1940
+ if (rows.length === 0) return [];
1941
+ await client.query(`DELETE FROM card_attachments WHERE card_id IS NULL AND created_at < $1`, [cutoff]);
1942
+ return rows;
1943
+ });
1944
+ if (stale.length > 0) {
1945
+ await unlinkStoragePaths(
1946
+ uploadsRoot,
1947
+ stale.map((r) => r.storage_path)
1948
+ );
1949
+ }
1950
+ return { removedCount: stale.length };
1951
+ }
1952
+
1953
+ // src/domain/cards.ts
1954
+ import { randomUUID as randomUUID6 } from "crypto";
1955
+
1956
+ // src/domain/cards/queries.ts
1957
+ async function listCards(pool2, actor, filters = {}) {
1958
+ const projectId = filters.projectId ?? (actor.kind === "agent" ? actor.projectId ?? void 0 : void 0);
1959
+ if (projectId) assertAgentProjectAccess(actor, projectId);
1960
+ const conditions = [];
1961
+ const params = [];
1962
+ const push = (val) => {
1963
+ params.push(val);
1964
+ return `$${params.length}`;
1965
+ };
1966
+ if (projectId) conditions.push(`c.project_id = ${push(projectId)}`);
1967
+ if (filters.status) conditions.push(`c.status = ${push(filters.status)}`);
1968
+ if (filters.parentId) conditions.push(`c.parent_id = ${push(filters.parentId)}`);
1969
+ if (!filters.includeArchived) conditions.push("c.archived_at IS NULL");
1970
+ if (filters.search?.trim()) {
1971
+ const kw = `%${filters.search.trim().toLowerCase()}%`;
1972
+ const p = push(kw);
1973
+ conditions.push(`(LOWER(c.title) LIKE ${p} OR LOWER(c.body) LIKE ${p} OR LOWER(c.tags) LIKE ${p})`);
1974
+ }
1975
+ if (filters.tag?.trim()) {
1976
+ conditions.push(`EXISTS(SELECT 1 FROM json_each(c.tags) WHERE value = ${push(filters.tag.trim())})`);
1977
+ }
1978
+ if (filters.agentId) {
1979
+ const p = push(filters.agentId);
1980
+ conditions.push(
1981
+ `(c.default_agent_id = ${p} OR EXISTS(SELECT 1 FROM card_participants cp WHERE cp.card_id = c.id AND cp.agent_id = ${p}))`
1982
+ );
1983
+ }
1984
+ const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
1985
+ return transaction(
1986
+ pool2,
1987
+ async (client) => {
1988
+ const { rows } = await client.query(
1989
+ `${CARD_SELECT} ${where} ORDER BY c.position ASC, c.updated_at DESC LIMIT 300`,
1990
+ params
1991
+ );
1992
+ return buildCardSummaries(client, rows);
1993
+ },
1994
+ { readOnly: true }
1995
+ );
1996
+ }
1997
+ async function getCardDetail(pool2, actor, cardId, uploadsRoot = config.uploadsDir, options) {
1998
+ const includeRevisions = options?.includeRevisions ?? true;
1999
+ const eventLimit = options?.eventLimit;
2000
+ return transaction(
2001
+ pool2,
2002
+ async (client) => {
2003
+ const row = await readCardRow(client, cardId);
2004
+ assertAgentProjectAccess(actor, row.project_id);
2005
+ const childRows = (await client.query(
2006
+ `${CARD_SELECT} WHERE c.parent_id = $1 AND c.archived_at IS NULL ORDER BY c.position ASC, c.created_at ASC`,
2007
+ [cardId]
2008
+ )).rows;
2009
+ const [summary, ...children] = await buildCardSummaries(client, [row, ...childRows]);
2010
+ let totalEventCount;
2011
+ let rawEvents;
2012
+ if (eventLimit !== void 0) {
2013
+ const countRow = (await client.query("SELECT COUNT(*) AS count FROM card_events WHERE card_id = $1", [
2014
+ cardId
2015
+ ])).rows[0];
2016
+ totalEventCount = Number(countRow.count);
2017
+ rawEvents = (await client.query(
2018
+ `SELECT id, CAST(server_seq AS TEXT) AS server_seq, project_id, card_id, type, actor_kind, actor_id, actor_name, data, created_at
2019
+ FROM (
2020
+ SELECT id, server_seq, project_id, card_id, type, actor_kind, actor_id, actor_name, data, created_at
2021
+ FROM card_events
2022
+ WHERE card_id = $1
2023
+ ORDER BY server_seq DESC
2024
+ LIMIT $2
2025
+ ) AS recent
2026
+ ORDER BY server_seq ASC`,
2027
+ [cardId, eventLimit]
2028
+ )).rows;
2029
+ } else {
2030
+ rawEvents = (await client.query(
2031
+ `SELECT id, CAST(server_seq AS TEXT) AS server_seq, project_id, card_id, type, actor_kind, actor_id, actor_name, data, created_at
2032
+ FROM card_events WHERE card_id = $1 ORDER BY server_seq ASC`,
2033
+ [cardId]
2034
+ )).rows;
2035
+ }
2036
+ const decoded = rawEvents.map(decodeEvent);
2037
+ const lastAgentEventSeq = /* @__PURE__ */ new Map();
2038
+ const targetedEvents = [];
2039
+ const targetIds = /* @__PURE__ */ new Set();
2040
+ for (const ev of decoded) {
2041
+ const evSeq = BigInt(ev.serverSeq);
2042
+ if (ev.actorKind === "agent") {
2043
+ const prev = lastAgentEventSeq.get(ev.actorId);
2044
+ if (prev === void 0 || evSeq > prev) {
2045
+ lastAgentEventSeq.set(ev.actorId, evSeq);
2046
+ }
2047
+ continue;
2048
+ }
2049
+ const targets = Array.isArray(ev.data.targetActorIds) ? ev.data.targetActorIds : [];
2050
+ if (ev.actorKind === "human" && targets.length > 0 && ev.type !== "agent_stop_requested") {
2051
+ targetedEvents.push({ ev, seq: evSeq, targets });
2052
+ for (const id of targets) targetIds.add(id);
2053
+ }
2054
+ }
2055
+ if (targetIds.size > 0) {
2056
+ const targetIdList = [...targetIds];
2057
+ const placeholders = targetIdList.map((_, i) => `$${i + 1}`).join(", ");
2058
+ const agentRows = (await client.query(
2059
+ `SELECT id, name, driver FROM agents WHERE id IN (${placeholders})`,
2060
+ targetIdList
2061
+ )).rows;
2062
+ const agentById = new Map(agentRows.map((a) => [a.id, a]));
2063
+ const participantStates = (await client.query(
2064
+ `SELECT agent_id, processing_event_id, last_outcome, last_outcome_event_id, last_outcome_summary,
2065
+ (processing_until IS NOT NULL AND processing_until > strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')) AS processing
2066
+ FROM card_participants
2067
+ WHERE card_id = $1`,
2068
+ [cardId]
2069
+ )).rows;
2070
+ const stateByAgent = new Map(participantStates.map((p) => [p.agent_id, p]));
2071
+ for (const { ev, seq, targets } of targetedEvents) {
2072
+ const responses = targets.map((agentId) => {
2073
+ const info = agentById.get(agentId);
2074
+ const pState = stateByAgent.get(agentId);
2075
+ const isProcessing = Boolean(pState?.processing) && (!pState?.processing_event_id || pState.processing_event_id === ev.id);
2076
+ const lastSeq = lastAgentEventSeq.get(agentId);
2077
+ const hasResponded = lastSeq !== void 0 && lastSeq > seq;
2078
+ const matchedOutcome = pState?.last_outcome_event_id === ev.id ? pState.last_outcome : null;
2079
+ let status;
2080
+ let summary2;
2081
+ if (isProcessing) {
2082
+ status = "processing";
2083
+ } else if (matchedOutcome === "failed" || matchedOutcome === "stopped") {
2084
+ status = matchedOutcome;
2085
+ summary2 = pState?.last_outcome_summary ?? void 0;
2086
+ } else if (hasResponded) {
2087
+ status = "responded";
2088
+ } else if (matchedOutcome === "no_write") {
2089
+ status = "no_write";
2090
+ summary2 = pState?.last_outcome_summary ?? void 0;
2091
+ } else {
2092
+ status = "pending";
2093
+ }
2094
+ return {
2095
+ agentId,
2096
+ agentName: info?.name ?? agentId.slice(0, 8),
2097
+ driver: info?.driver,
2098
+ status,
2099
+ ...summary2 ? { summary: summary2 } : {}
2100
+ };
2101
+ });
2102
+ ev.responses = responses;
2103
+ }
2104
+ }
2105
+ const revisions = includeRevisions ? (await client.query(`SELECT * FROM card_revisions WHERE card_id = $1 ORDER BY version DESC LIMIT 50`, [cardId])).rows.map((r) => ({
2106
+ id: r.id,
2107
+ cardId: r.card_id,
2108
+ version: r.version,
2109
+ actorKind: r.actor_kind,
2110
+ actorId: r.actor_id,
2111
+ actorName: r.actor_name,
2112
+ summary: r.summary,
2113
+ beforeSnapshot: JSON.parse(r.before_snapshot),
2114
+ afterSnapshot: JSON.parse(r.after_snapshot),
2115
+ createdAt: iso2(r.created_at)
2116
+ })) : [];
2117
+ const decisionRows = (await client.query(
2118
+ `${DECISION_SELECT}
2119
+ WHERE d.card_id = $1
2120
+ ORDER BY CASE WHEN d.status = 'pending' THEN 0 ELSE 1 END ASC, d.created_at DESC
2121
+ LIMIT 30`,
2122
+ [cardId]
2123
+ )).rows;
2124
+ const decisions = decisionRows.map(mapDecision);
2125
+ const attachments = await fetchCardAttachments(client, cardId, uploadsRoot);
2126
+ const commentEventIds = decoded.filter((ev) => ev.type === "comment").map((ev) => ev.id);
2127
+ if (commentEventIds.length > 0) {
2128
+ const byEvent = await fetchAttachmentsByEventIds(client, commentEventIds, uploadsRoot);
2129
+ for (const ev of decoded) {
2130
+ const list = byEvent.get(ev.id);
2131
+ if (list && list.length > 0) ev.attachments = list;
2132
+ }
2133
+ }
2134
+ const rawOutputs = JSON.parse(row.outputs);
2135
+ const outputIdsWithAttachment = rawOutputs.filter((o) => Boolean(o.attachmentId)).map((o) => o.id);
2136
+ const outputAttachments = outputIdsWithAttachment.length > 0 ? await fetchAttachmentsByOutputIds(client, cardId, outputIdsWithAttachment, uploadsRoot) : /* @__PURE__ */ new Map();
2137
+ const outputs = rawOutputs.map((o) => {
2138
+ const att = outputAttachments.get(o.id);
2139
+ return att ? { ...o, attachment: att } : o;
2140
+ });
2141
+ return {
2142
+ ...summary,
2143
+ body: row.body,
2144
+ checklist: JSON.parse(row.checklist),
2145
+ outputs,
2146
+ attachments,
2147
+ decisions,
2148
+ children,
2149
+ events: decoded,
2150
+ revisions,
2151
+ ...totalEventCount !== void 0 ? { totalEventCount, eventsTruncated: totalEventCount > decoded.length } : {},
2152
+ ...!includeRevisions ? { revisionsOmitted: true } : {},
2153
+ createdByKind: row.created_by_kind,
2154
+ createdById: row.created_by_id,
2155
+ createdByName: row.created_by_name
2156
+ };
2157
+ },
2158
+ { readOnly: true }
2159
+ );
2160
+ }
2161
+
2162
+ // src/domain/cards/runs.ts
2163
+ function parseSteps(raw) {
2164
+ try {
2165
+ const parsed = JSON.parse(raw);
2166
+ return Array.isArray(parsed) ? parsed : [];
2167
+ } catch {
2168
+ return [];
2169
+ }
2170
+ }
2171
+ function mapRunRow(row) {
2172
+ const steps = parseSteps(row.steps);
2173
+ return {
2174
+ id: row.id,
2175
+ projectId: row.project_id,
2176
+ cardId: row.card_id,
2177
+ agentId: row.agent_id,
2178
+ agentName: row.agent_name,
2179
+ driver: row.driver,
2180
+ triggerEventId: row.trigger_event_id,
2181
+ status: row.status,
2182
+ workDir: row.work_dir,
2183
+ branch: row.branch,
2184
+ summary: row.summary,
2185
+ steps,
2186
+ stepCount: row.step_count,
2187
+ truncated: row.step_count > steps.length,
2188
+ startedAt: iso2(row.started_at),
2189
+ finishedAt: row.finished_at ? iso2(row.finished_at) : null,
2190
+ updatedAt: iso2(row.updated_at)
2191
+ };
2192
+ }
2193
+ async function upsertCardRunStart(client, options, publish) {
2194
+ const existing = (await client.query("SELECT * FROM card_agent_runs WHERE id = $1", [options.runId])).rows[0];
2195
+ if (existing) {
2196
+ if (existing.card_id !== options.cardId || existing.agent_id !== options.actor.id) {
2197
+ throw new HttpError(409, "\u6267\u884C\u8BB0\u5F55 ID \u5DF2\u88AB\u5176\u4ED6\u5361\u7247\u6216\u534F\u4F5C\u8005\u5360\u7528");
2198
+ }
2199
+ await client.query(
2200
+ `UPDATE card_agent_runs
2201
+ SET work_dir = COALESCE($2, work_dir),
2202
+ branch = COALESCE($3, branch),
2203
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
2204
+ WHERE id = $1`,
2205
+ [options.runId, options.workDir ?? null, options.branch ?? null]
2206
+ );
2207
+ return (await client.query("SELECT * FROM card_agent_runs WHERE id = $1", [options.runId])).rows[0];
2208
+ }
2209
+ await client.query(
2210
+ `UPDATE card_agent_runs
2211
+ SET status = 'stopped',
2212
+ summary = COALESCE(summary, '\u4E0A\u6B21\u6267\u884C\u672A\u6B63\u5E38\u4E0A\u62A5\u7ED3\u675F'),
2213
+ finished_at = COALESCE(finished_at, strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')),
2214
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
2215
+ WHERE card_id = $1 AND agent_id = $2 AND status = 'running'`,
2216
+ [options.cardId, options.actor.id]
2217
+ );
2218
+ await client.query(
2219
+ `INSERT INTO card_agent_runs(
2220
+ id, project_id, card_id, agent_id, agent_name, driver, trigger_event_id, status, work_dir, branch
2221
+ )
2222
+ VALUES($1, $2, $3, $4, $5, $6, $7, 'running', $8, $9)`,
2223
+ [
2224
+ options.runId,
2225
+ options.projectId,
2226
+ options.cardId,
2227
+ options.actor.id,
2228
+ options.actor.name,
2229
+ options.actor.driver,
2230
+ options.eventId ?? null,
2231
+ options.workDir ?? null,
2232
+ options.branch ?? null
2233
+ ]
2234
+ );
2235
+ const created = (await client.query("SELECT * FROM card_agent_runs WHERE id = $1", [options.runId])).rows[0];
2236
+ notifyAfterCommit(client, publish, {
2237
+ type: "card_run_step",
2238
+ projectId: created.project_id,
2239
+ cardId: created.card_id,
2240
+ runId: created.id,
2241
+ agentId: created.agent_id,
2242
+ agentName: created.agent_name,
2243
+ driver: created.driver,
2244
+ status: created.status,
2245
+ workDir: created.work_dir,
2246
+ branch: created.branch,
2247
+ summary: created.summary,
2248
+ stepCount: created.step_count,
2249
+ truncated: false,
2250
+ steps: [],
2251
+ startedAt: iso2(created.started_at),
2252
+ finishedAt: null
2253
+ });
2254
+ return created;
2255
+ }
2256
+ async function finalizeCardRun(client, options, publish) {
2257
+ const status = options.outcome ?? "completed";
2258
+ let row;
2259
+ if (options.runId) {
2260
+ row = (await client.query(
2261
+ "SELECT * FROM card_agent_runs WHERE id = $1 AND card_id = $2 AND agent_id = $3",
2262
+ [options.runId, options.cardId, options.actor.id]
2263
+ )).rows[0];
2264
+ } else {
2265
+ row = (await client.query(
2266
+ `SELECT * FROM card_agent_runs
2267
+ WHERE card_id = $1 AND agent_id = $2 AND status = 'running'
2268
+ AND ($3 IS NULL OR trigger_event_id = $3)
2269
+ ORDER BY started_at DESC LIMIT 1`,
2270
+ [options.cardId, options.actor.id, options.eventId ?? null]
2271
+ )).rows[0];
2272
+ }
2273
+ if (!row) return;
2274
+ await client.query(
2275
+ `UPDATE card_agent_runs
2276
+ SET status = $2,
2277
+ summary = $3,
2278
+ finished_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now'),
2279
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
2280
+ WHERE id = $1`,
2281
+ [row.id, status, options.summary]
2282
+ );
2283
+ const updated = (await client.query("SELECT * FROM card_agent_runs WHERE id = $1", [row.id])).rows[0];
2284
+ const storedSteps = parseSteps(updated.steps);
2285
+ notifyAfterCommit(client, publish, {
2286
+ type: "card_run_step",
2287
+ projectId: updated.project_id,
2288
+ cardId: updated.card_id,
2289
+ runId: updated.id,
2290
+ agentId: updated.agent_id,
2291
+ agentName: updated.agent_name,
2292
+ driver: updated.driver,
2293
+ status: updated.status,
2294
+ workDir: updated.work_dir,
2295
+ branch: updated.branch,
2296
+ summary: updated.summary,
2297
+ stepCount: updated.step_count,
2298
+ truncated: updated.step_count > storedSteps.length,
2299
+ steps: [],
2300
+ startedAt: iso2(updated.started_at),
2301
+ finishedAt: updated.finished_at ? iso2(updated.finished_at) : null
2302
+ });
2303
+ }
2304
+ async function appendCardRunSteps(pool2, actor, cardId, input, publish) {
2305
+ return transaction(pool2, async (client) => {
2306
+ const current = await readCardRow(client, cardId);
2307
+ assertAgentProjectAccess(actor, current.project_id);
2308
+ let row = (await client.query("SELECT * FROM card_agent_runs WHERE id = $1", [input.runId])).rows[0];
2309
+ if (row) {
2310
+ if (row.card_id !== cardId || row.agent_id !== actor.id) {
2311
+ throw new HttpError(403, "\u65E0\u6743\u5411\u8BE5\u6267\u884C\u8BB0\u5F55\u8FFD\u52A0\u6B65\u9AA4");
2312
+ }
2313
+ if (row.status !== "running") {
2314
+ const stored = parseSteps(row.steps);
2315
+ return {
2316
+ ok: true,
2317
+ runId: row.id,
2318
+ stepCount: row.step_count,
2319
+ truncated: row.step_count > stored.length
2320
+ };
2321
+ }
2322
+ } else {
2323
+ row = await upsertCardRunStart(client, {
2324
+ runId: input.runId,
2325
+ projectId: current.project_id,
2326
+ cardId,
2327
+ actor,
2328
+ eventId: input.eventId
2329
+ });
2330
+ }
2331
+ const existingSteps = parseSteps(row.steps);
2332
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
2333
+ const addedSteps = input.steps.map((step, idx) => ({
2334
+ seq: row.step_count + idx + 1,
2335
+ kind: step.kind,
2336
+ title: step.title,
2337
+ ...step.detail ? { detail: step.detail } : {},
2338
+ at: step.at ?? nowIso
2339
+ }));
2340
+ const nextCount = row.step_count + addedSteps.length;
2341
+ const merged = [...existingSteps, ...addedSteps];
2342
+ const bounded = merged.length > CARD_RUN_MAX_STEPS ? merged.slice(-CARD_RUN_MAX_STEPS) : merged;
2343
+ const truncated = nextCount > bounded.length;
2344
+ await client.query(
2345
+ `UPDATE card_agent_runs
2346
+ SET steps = $2,
2347
+ step_count = $3,
2348
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
2349
+ WHERE id = $1`,
2350
+ [row.id, JSON.stringify(bounded), nextCount]
2351
+ );
2352
+ notifyAfterCommit(client, publish, {
2353
+ type: "card_run_step",
2354
+ projectId: row.project_id,
2355
+ cardId: row.card_id,
2356
+ runId: row.id,
2357
+ agentId: row.agent_id,
2358
+ agentName: row.agent_name,
2359
+ driver: row.driver,
2360
+ status: row.status,
2361
+ workDir: row.work_dir,
2362
+ branch: row.branch,
2363
+ summary: row.summary,
2364
+ stepCount: nextCount,
2365
+ truncated,
2366
+ steps: addedSteps,
2367
+ startedAt: iso2(row.started_at),
2368
+ finishedAt: null
2369
+ });
2370
+ return { ok: true, runId: row.id, stepCount: nextCount, truncated };
2371
+ });
2372
+ }
2373
+ async function listCardRuns(pool2, actor, cardId, limit = 15) {
2374
+ const current = await readCardRow(pool2, cardId);
2375
+ assertAgentProjectAccess(actor, current.project_id);
2376
+ const boundedLimit = Math.min(50, Math.max(1, limit));
2377
+ const rows = (await pool2.query(
2378
+ `SELECT * FROM card_agent_runs
2379
+ WHERE card_id = $1
2380
+ ORDER BY started_at DESC
2381
+ LIMIT $2`,
2382
+ [cardId, boundedLimit]
2383
+ )).rows;
2384
+ return { runs: rows.map(mapRunRow) };
2385
+ }
2386
+
2387
+ // src/domain/cards/collaboration.ts
2388
+ async function addComment(pool2, actor, cardId, input, publish, uploadsRoot = config.uploadsDir) {
2389
+ return transaction(pool2, async (client) => {
2390
+ const current = await readCardRow(client, cardId);
2391
+ assertAgentProjectAccess(actor, current.project_id);
2392
+ const uniqueAttachmentIds = await validateCommentAttachments(client, current.project_id, input.attachmentIds ?? []);
2393
+ let replyEvent;
2394
+ if (input.replyTo) {
2395
+ replyEvent = (await client.query(
2396
+ "SELECT id, actor_kind, actor_id FROM card_events WHERE card_id = $1 AND id = $2",
2397
+ [cardId, input.replyTo]
2398
+ )).rows[0];
2399
+ if (!replyEvent) throw new HttpError(400, "\u56DE\u590D\u7684\u76EE\u6807\u4E8B\u4EF6\u4E0D\u5B58\u5728");
2400
+ }
2401
+ let mentionAgents = [];
2402
+ let targetActorIds = [];
2403
+ let routingReason = "none";
2404
+ if (actor.kind === "human") {
2405
+ mentionAgents = await resolveMentionAgents(client, current.project_id, input.mentions);
2406
+ let replyAgentId = null;
2407
+ if (replyEvent?.actor_kind === "agent") {
2408
+ const replyAgent = (await client.query(
2409
+ "SELECT id, project_id, enabled FROM agents WHERE id = $1",
2410
+ [replyEvent.actor_id]
2411
+ )).rows[0];
2412
+ if (replyAgent?.enabled && (!replyAgent.project_id || replyAgent.project_id === current.project_id)) {
2413
+ replyAgentId = replyAgent.id;
2414
+ }
2415
+ }
2416
+ if (mentionAgents.length > 0) {
2417
+ const ids = new Set(mentionAgents.map((a) => a.id));
2418
+ if (replyAgentId) ids.add(replyAgentId);
2419
+ targetActorIds = [...ids];
2420
+ routingReason = "mention";
2421
+ } else if (replyEvent?.actor_kind === "agent") {
2422
+ if (replyAgentId) {
2423
+ targetActorIds = [replyAgentId];
2424
+ routingReason = "reply";
2425
+ }
2426
+ } else {
2427
+ const cardDefaultAgent = await getCardDefaultAgent(
2428
+ client,
2429
+ current.project_id,
2430
+ current.default_agent_id ?? null
2431
+ );
2432
+ if (cardDefaultAgent) {
2433
+ targetActorIds = [cardDefaultAgent.id];
2434
+ routingReason = "default_agent";
2435
+ } else {
2436
+ const participants = (await client.query(
2437
+ `SELECT cp.agent_id FROM card_participants cp JOIN agents a ON a.id = cp.agent_id
2438
+ WHERE cp.card_id = $1 AND a.enabled = 1 AND (a.project_id IS NULL OR a.project_id = $2)`,
2439
+ [cardId, current.project_id]
2440
+ )).rows;
2441
+ if (participants.length === 1) {
2442
+ targetActorIds = [participants[0].agent_id];
2443
+ routingReason = "sole_participant";
2444
+ } else {
2445
+ const projectDefaultAgent = await getProjectDefaultAgent(client, current.project_id);
2446
+ if (projectDefaultAgent) {
2447
+ targetActorIds = [projectDefaultAgent.id];
2448
+ routingReason = "default_agent";
2449
+ }
2450
+ }
2451
+ }
2452
+ }
2453
+ } else {
2454
+ await touchParticipant(client, cardId, actor.id, void 0, bodyPreview(input.text || "\u6DFB\u52A0\u4E86\u9644\u4EF6\u8BC4\u8BBA"));
2455
+ }
2456
+ await client.query(`UPDATE cards SET updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now') WHERE id = $1`, [
2457
+ cardId
2458
+ ]);
2459
+ const event = await appendEvent(
2460
+ client,
2461
+ current.project_id,
2462
+ cardId,
2463
+ actor,
2464
+ "comment",
2465
+ {
2466
+ text: input.text,
2467
+ mentions: mentionAgents.map((a) => a.id),
2468
+ mentionNames: mentionAgents.map((a) => a.name),
2469
+ targetActorIds,
2470
+ routingReason,
2471
+ ...uniqueAttachmentIds.length > 0 ? { attachmentIds: uniqueAttachmentIds } : {},
2472
+ ...input.replyTo ? { replyTo: input.replyTo } : {},
2473
+ ...input.relatesTo ? { relatesTo: input.relatesTo } : {}
2474
+ },
2475
+ publish
2476
+ );
2477
+ if (uniqueAttachmentIds.length > 0) {
2478
+ event.attachments = await bindAttachmentsToComment(
2479
+ client,
2480
+ current.project_id,
2481
+ cardId,
2482
+ event.id,
2483
+ uniqueAttachmentIds,
2484
+ uploadsRoot
2485
+ );
2486
+ }
2487
+ return event;
2488
+ });
2489
+ }
2490
+ async function stopCardAgent(pool2, actor, cardId, agentId, publish) {
2491
+ return transaction(pool2, async (client) => {
2492
+ const current = await readCardRow(client, cardId);
2493
+ const agent = (await client.query(
2494
+ "SELECT id, name, project_id FROM agents WHERE id = $1",
2495
+ [agentId]
2496
+ )).rows[0];
2497
+ if (!agent) throw new HttpError(404, "Agent \u4E0D\u5B58\u5728");
2498
+ if (agent.project_id && agent.project_id !== current.project_id) {
2499
+ throw new HttpError(403, `Agent\u300C${agent.name}\u300D\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE`);
2500
+ }
2501
+ await client.query(
2502
+ `INSERT INTO card_participants(card_id, agent_id, state, activity_text, processing_event_id, processing_until, updated_at)
2503
+ VALUES($1, $2, 'paused', '\u5DF2\u8BF7\u6C42\u505C\u6B62', NULL, NULL, strftime('%Y-%m-%dT%H:%M:%f000Z', 'now'))
2504
+ ON CONFLICT(card_id, agent_id) DO UPDATE SET
2505
+ state = 'paused', activity_text = '\u5DF2\u8BF7\u6C42\u505C\u6B62', processing_event_id = NULL, processing_until = NULL,
2506
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')`,
2507
+ [cardId, agentId]
2508
+ );
2509
+ const event = await appendEvent(
2510
+ client,
2511
+ current.project_id,
2512
+ cardId,
2513
+ actor,
2514
+ "agent_stop_requested",
2515
+ { agentId, agentName: agent.name, targetActorIds: [agentId], routingReason: "stop" },
2516
+ publish
2517
+ );
2518
+ notifyAfterCommit(client, publish, { type: "command", command: "stop-agent", agentId, cardId });
2519
+ return event;
2520
+ });
2521
+ }
2522
+ async function reportProcessing(pool2, actor, cardId, input, publish) {
2523
+ await transaction(pool2, async (client) => {
2524
+ const current = await readCardRow(client, cardId);
2525
+ assertAgentProjectAccess(actor, current.project_id);
2526
+ await client.query(
2527
+ `INSERT INTO card_participants(card_id, agent_id, state, activity_text, work_dir, branch, processing_event_id, processing_until, updated_at)
2528
+ VALUES($1, $2, 'running', $3, $4, $5, $6, strftime('%Y-%m-%dT%H:%M:%f000Z', 'now', '+120 seconds'), strftime('%Y-%m-%dT%H:%M:%f000Z', 'now'))
2529
+ ON CONFLICT(card_id, agent_id) DO UPDATE SET
2530
+ state = 'running',
2531
+ activity_text = CASE WHEN $3 <> '' THEN $3 ELSE card_participants.activity_text END,
2532
+ work_dir = COALESCE($4, card_participants.work_dir),
2533
+ branch = COALESCE($5, card_participants.branch),
2534
+ processing_event_id = COALESCE($6, card_participants.processing_event_id),
2535
+ processing_until = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now', '+120 seconds'),
2536
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')`,
2537
+ [cardId, actor.id, input.activityText, input.workDir ?? null, input.branch ?? null, input.eventId ?? null]
2538
+ );
2539
+ if (input.runId) {
2540
+ await upsertCardRunStart(
2541
+ client,
2542
+ {
2543
+ runId: input.runId,
2544
+ projectId: current.project_id,
2545
+ cardId,
2546
+ actor,
2547
+ eventId: input.eventId,
2548
+ workDir: input.workDir,
2549
+ branch: input.branch
2550
+ },
2551
+ publish
2552
+ );
2553
+ }
2554
+ notifyAfterCommit(client, publish, {
2555
+ type: "board_updated",
2556
+ projectId: current.project_id,
2557
+ cardId,
2558
+ reason: "processing"
2559
+ });
2560
+ });
2561
+ return { ok: true };
2562
+ }
2563
+ async function clearProcessing(pool2, actor, cardId, input, publish) {
2564
+ await transaction(pool2, async (client) => {
2565
+ const current = await readCardRow(client, cardId);
2566
+ assertAgentProjectAccess(actor, current.project_id);
2567
+ const existing = (await client.query(`SELECT state, processing_event_id FROM card_participants WHERE card_id = $1 AND agent_id = $2`, [
2568
+ cardId,
2569
+ actor.id
2570
+ ])).rows[0];
2571
+ const resolvedEventId = input?.eventId ?? existing?.processing_event_id ?? null;
2572
+ let resolvedOutcome = input?.outcome ?? null;
2573
+ let resolvedSummary = input?.summary?.trim() || null;
2574
+ if (resolvedOutcome === "completed" && resolvedEventId) {
2575
+ const triggerRow = (await client.query(
2576
+ `SELECT server_seq FROM card_events WHERE id = $1 AND card_id = $2`,
2577
+ [resolvedEventId, cardId]
2578
+ )).rows[0];
2579
+ if (triggerRow) {
2580
+ const agentWrite = await client.query(
2581
+ `SELECT server_seq FROM card_events
2582
+ WHERE card_id = $1 AND actor_kind = 'agent' AND actor_id = $2 AND server_seq > $3
2583
+ LIMIT 1`,
2584
+ [cardId, actor.id, triggerRow.server_seq]
2585
+ );
2586
+ if (agentWrite.rowCount === 0) {
2587
+ resolvedOutcome = "no_write";
2588
+ resolvedSummary = resolvedSummary ?? "\u672C\u8F6E\u6267\u884C\u5DF2\u7ED3\u675F\uFF0C\u4F46\u672A\u5411\u5361\u7247\u5199\u5165\u4EFB\u4F55\u66F4\u65B0";
2589
+ }
2590
+ }
2591
+ }
2592
+ if (resolvedOutcome !== null) {
2593
+ await client.query(
2594
+ `UPDATE card_participants
2595
+ SET state = CASE WHEN state = 'paused' THEN 'paused' ELSE 'idle' END,
2596
+ activity_text = CASE WHEN state = 'paused' THEN activity_text ELSE '' END,
2597
+ processing_event_id = NULL,
2598
+ processing_until = NULL,
2599
+ last_outcome = $3,
2600
+ last_outcome_event_id = $4,
2601
+ last_outcome_summary = $5,
2602
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
2603
+ WHERE card_id = $1 AND agent_id = $2`,
2604
+ [cardId, actor.id, resolvedOutcome, resolvedEventId, resolvedSummary]
2605
+ );
2606
+ } else {
2607
+ await client.query(
2608
+ `UPDATE card_participants
2609
+ SET state = CASE WHEN state = 'paused' THEN 'paused' ELSE 'idle' END,
2610
+ activity_text = CASE WHEN state = 'paused' THEN activity_text ELSE '' END,
2611
+ processing_event_id = NULL,
2612
+ processing_until = NULL,
2613
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
2614
+ WHERE card_id = $1 AND agent_id = $2`,
2615
+ [cardId, actor.id]
2616
+ );
2617
+ }
2618
+ await finalizeCardRun(
2619
+ client,
2620
+ {
2621
+ cardId,
2622
+ actor,
2623
+ runId: input?.runId,
2624
+ eventId: resolvedEventId,
2625
+ outcome: resolvedOutcome,
2626
+ summary: resolvedSummary
2627
+ },
2628
+ publish
2629
+ );
2630
+ notifyAfterCommit(client, publish, {
2631
+ type: "board_updated",
2632
+ projectId: current.project_id,
2633
+ cardId,
2634
+ reason: "processing_clear"
2635
+ });
2636
+ });
2637
+ return { ok: true };
2638
+ }
2639
+ async function listEvents(pool2, actor, options, uploadsRoot = config.uploadsDir) {
2640
+ const projectId = options.projectId ?? (actor.kind === "agent" ? actor.projectId ?? void 0 : void 0);
2641
+ if (projectId) assertAgentProjectAccess(actor, projectId);
2642
+ const conditions = ["server_seq > $1"];
2643
+ const params = [BigInt(options.cursor)];
2644
+ const push = (val) => {
2645
+ params.push(val);
2646
+ return `$${params.length}`;
2647
+ };
2648
+ if (projectId) conditions.push(`project_id = ${push(projectId)}`);
2649
+ if (options.cardId) conditions.push(`card_id = ${push(options.cardId)}`);
2650
+ const limitParam = push(options.limit + 1);
2651
+ const rows = (await pool2.query(
2652
+ `SELECT id, CAST(server_seq AS TEXT) AS server_seq, project_id, card_id, type, actor_kind, actor_id, actor_name, data, created_at
2653
+ FROM card_events WHERE ${conditions.join(" AND ")} ORDER BY server_seq ASC LIMIT ${limitParam}`,
2654
+ params
2655
+ )).rows.map(decodeEvent);
2656
+ const page = rows.slice(0, options.limit);
2657
+ const commentEventIds = page.filter((ev) => ev.type === "comment").map((ev) => ev.id);
2658
+ if (commentEventIds.length > 0) {
2659
+ const byEvent = await fetchAttachmentsByEventIds(pool2, commentEventIds, uploadsRoot);
2660
+ for (const ev of page) {
2661
+ const list = byEvent.get(ev.id);
2662
+ if (list && list.length > 0) ev.attachments = list;
2663
+ }
2664
+ }
2665
+ return {
2666
+ events: page,
2667
+ nextCursor: page.at(-1)?.serverSeq ?? options.cursor,
2668
+ hasMore: rows.length > options.limit
2669
+ };
2670
+ }
2671
+
2672
+ // src/domain/cards/decisions.ts
2673
+ import { randomUUID as randomUUID4 } from "crypto";
2674
+ async function createCardDecision(pool2, actor, cardId, input, publish) {
2675
+ const decisionId = randomUUID4();
2676
+ const options = (input.options ?? []).map((o) => ({
2677
+ id: o.id,
2678
+ label: o.label,
2679
+ ...o.description ? { description: o.description } : {},
2680
+ recommended: Boolean(o.recommended)
2681
+ }));
2682
+ await transaction(pool2, async (client) => {
2683
+ const current = await readCardRow(client, cardId);
2684
+ assertAgentProjectAccess(actor, current.project_id);
2685
+ await client.query(
2686
+ `INSERT INTO card_decisions(id, project_id, card_id, agent_id, question, context, options, status)
2687
+ VALUES($1, $2, $3, $4, $5, $6, $7, 'pending')`,
2688
+ [
2689
+ decisionId,
2690
+ current.project_id,
2691
+ cardId,
2692
+ actor.id,
2693
+ input.question,
2694
+ input.context ?? null,
2695
+ JSON.stringify(options)
2696
+ ]
2697
+ );
2698
+ await touchParticipant(client, cardId, actor.id, "paused", "\u7B49\u5F85\u4F60\u786E\u8BA4\u51B3\u7B56");
2699
+ const lines = [`\u3010\u5F85\u4F60\u786E\u8BA4\u3011${input.question}`];
2700
+ if (input.context) lines.push(input.context);
2701
+ if (options.length > 0) {
2702
+ lines.push(
2703
+ options.map((o) => `- ${o.label}${o.recommended ? "\uFF08\u63A8\u8350\uFF09" : ""}${o.description ? `\uFF1A${o.description}` : ""}`).join("\n")
2704
+ );
2705
+ }
2706
+ await appendEvent(
2707
+ client,
2708
+ current.project_id,
2709
+ cardId,
2710
+ actor,
2711
+ "comment",
2712
+ { text: lines.join("\n"), decisionId, targetActorIds: [], routingReason: "none" },
2713
+ publish
2714
+ );
2715
+ });
2716
+ const row = (await pool2.query(`${DECISION_SELECT} WHERE d.id = $1`, [decisionId])).rows[0];
2717
+ return {
2718
+ ...mapDecision(row),
2719
+ hint: "\u5DF2\u521B\u5EFA\u5F85\u786E\u8BA4\u51B3\u7B56\u5E76\u81EA\u52A8\u5199\u5165\u5361\u7247\u8BC4\u8BBA\uFF0C\u4F60\u7684\u53C2\u4E0E\u6001\u5DF2\u7F6E\u4E3A\u6682\u505C\uFF1B\u65E0\u9700\u518D\u8C03\u7528 slate comment \u91CD\u590D\u63D0\u95EE\uFF0C\u8BF7\u7ED3\u675F\u672C\u8F6E\u7B49\u5F85\u4EBA\u786E\u8BA4\u3002"
2720
+ };
2721
+ }
2722
+ async function resolveCardDecision(pool2, actor, cardId, decisionId, input, publish) {
2723
+ return transaction(pool2, async (client) => {
2724
+ const current = await readCardRow(client, cardId);
2725
+ const row = (await client.query(`${DECISION_SELECT} WHERE d.id = $1 AND d.card_id = $2`, [decisionId, cardId])).rows[0];
2726
+ if (!row) throw new HttpError(404, "\u5F85\u786E\u8BA4\u51B3\u7B56\u4E0D\u5B58\u5728");
2727
+ if (row.status !== "pending") throw new HttpError(409, "\u8BE5\u51B3\u7B56\u5DF2\u5904\u7406");
2728
+ const options = JSON.parse(row.options || "[]");
2729
+ let selectedOptionLabel = null;
2730
+ if (input.optionId) {
2731
+ const matched = options.find((o) => o.id === input.optionId);
2732
+ if (!matched) throw new HttpError(400, "\u6240\u9009\u9009\u9879\u65E0\u6548");
2733
+ selectedOptionLabel = matched.label;
2734
+ }
2735
+ const note = input.note?.trim() || null;
2736
+ await client.query(
2737
+ `UPDATE card_decisions
2738
+ SET status = 'resolved',
2739
+ selected_option_id = $2,
2740
+ selected_option_label = $3,
2741
+ response_note = $4,
2742
+ resolved_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
2743
+ WHERE id = $1`,
2744
+ [decisionId, input.optionId ?? null, selectedOptionLabel, note]
2745
+ );
2746
+ const commentParts = [];
2747
+ if (selectedOptionLabel) commentParts.push(`\u3010\u5DF2\u62CD\u677F\uFF1A${selectedOptionLabel}\u3011`);
2748
+ else commentParts.push("\u3010\u5DF2\u56DE\u590D\u786E\u8BA4\u3011");
2749
+ if (note) commentParts.push(note);
2750
+ let canWakeAgent = false;
2751
+ if (input.wakeAgent) {
2752
+ const targetAgent = (await client.query(
2753
+ "SELECT project_id, enabled FROM agents WHERE id = $1",
2754
+ [row.agent_id]
2755
+ )).rows[0];
2756
+ canWakeAgent = Boolean(
2757
+ targetAgent?.enabled && (!targetAgent.project_id || targetAgent.project_id === current.project_id)
2758
+ );
2759
+ }
2760
+ const targetActorIds = canWakeAgent ? [row.agent_id] : [];
2761
+ const event = await appendEvent(
2762
+ client,
2763
+ current.project_id,
2764
+ cardId,
2765
+ actor,
2766
+ "comment",
2767
+ {
2768
+ text: commentParts.join(" "),
2769
+ decisionId,
2770
+ selectedOptionId: input.optionId ?? null,
2771
+ selectedOptionLabel,
2772
+ mentions: targetActorIds,
2773
+ mentionNames: targetActorIds.length ? [row.agent_name] : [],
2774
+ targetActorIds,
2775
+ routingReason: targetActorIds.length ? "reply" : "none"
2776
+ },
2777
+ publish
2778
+ );
2779
+ const updated = (await client.query(`${DECISION_SELECT} WHERE d.id = $1`, [decisionId])).rows[0];
2780
+ return { decision: mapDecision(updated), event };
2781
+ });
2782
+ }
2783
+ async function dismissCardDecision(pool2, cardId, decisionId, publish) {
2784
+ await transaction(pool2, async (client) => {
2785
+ const current = await readCardRow(client, cardId);
2786
+ const existing = (await client.query(
2787
+ "SELECT status FROM card_decisions WHERE id = $1 AND card_id = $2",
2788
+ [decisionId, cardId]
2789
+ )).rows[0];
2790
+ if (!existing) throw new HttpError(404, "\u5F85\u786E\u8BA4\u51B3\u7B56\u4E0D\u5B58\u5728");
2791
+ if (existing.status !== "pending") throw new HttpError(409, "\u8BE5\u51B3\u7B56\u5DF2\u5904\u7406");
2792
+ await client.query(
2793
+ `UPDATE card_decisions
2794
+ SET status = 'dismissed',
2795
+ resolved_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
2796
+ WHERE id = $1 AND card_id = $2 AND status = 'pending'`,
2797
+ [decisionId, cardId]
2798
+ );
2799
+ notifyAfterCommit(client, publish, {
2800
+ type: "board_updated",
2801
+ projectId: current.project_id,
2802
+ cardId,
2803
+ reason: "decision_dismissed"
2804
+ });
2805
+ });
2806
+ return { ok: true };
2807
+ }
2808
+
2809
+ // src/domain/cards/outputs.ts
2810
+ import { randomUUID as randomUUID5 } from "crypto";
2811
+ import { realpath, stat as stat2, unlink as unlink2 } from "fs/promises";
2812
+ import { homedir } from "os";
2813
+ import path2 from "path";
2814
+ var MAX_PREVIEW_BYTES = 64 * 1024;
2815
+ function defaultMarkdownFilename(label) {
2816
+ const clean = sanitizeFilename(label).replace(/[:*?"<>|]/g, "-").replace(/\s+/g, " ").trim();
2817
+ const base = (clean || "output").slice(0, 80);
2818
+ return /\.md$/i.test(base) ? base : `${base}.md`;
2819
+ }
2820
+ function expandTilde(rawPath) {
2821
+ const trimmed = rawPath.trim();
2822
+ if (trimmed === "~") return homedir();
2823
+ if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) {
2824
+ return path2.join(homedir(), trimmed.slice(2));
2825
+ }
2826
+ return trimmed;
2827
+ }
2828
+ function resolveUserPath(rawPath) {
2829
+ return path2.resolve(expandTilde(rawPath));
2830
+ }
2831
+ function isPathInsideRoot(root, target) {
2832
+ const prefix = root.endsWith(path2.sep) ? root : root + path2.sep;
2833
+ return target === root || target.startsWith(prefix);
2834
+ }
2835
+ async function addCardOutput(pool2, actor, cardId, input, publish, uploadsRoot = config.uploadsDir) {
2836
+ const outputId = randomUUID5();
2837
+ const precheck = await readCardRow(pool2, cardId);
2838
+ assertAgentProjectAccess(actor, precheck.project_id);
2839
+ let staged;
2840
+ if (input.content !== void 0) {
2841
+ const filename = input.filename?.trim() || defaultMarkdownFilename(input.label ?? "output");
2842
+ const mimeType = input.mimeType ?? (/\.md$/i.test(filename) ? "text/markdown" : void 0);
2843
+ staged = await stageManagedOutputText(uploadsRoot, precheck.project_id, filename, mimeType, input.content);
2844
+ }
2845
+ let storedOutput;
2846
+ let hydratedAttachment;
2847
+ try {
2848
+ await transaction(pool2, async (client) => {
2849
+ const current = await readCardRow(client, cardId);
2850
+ assertAgentProjectAccess(actor, current.project_id);
2851
+ if (staged) {
2852
+ hydratedAttachment = await insertManagedOutputAttachment(
2853
+ client,
2854
+ actor,
2855
+ staged,
2856
+ current.project_id,
2857
+ cardId,
2858
+ outputId,
2859
+ uploadsRoot
2860
+ );
2861
+ } else if (input.attachmentId) {
2862
+ hydratedAttachment = await bindAttachmentToOutput(
2863
+ client,
2864
+ current.project_id,
2865
+ cardId,
2866
+ outputId,
2867
+ input.attachmentId,
2868
+ uploadsRoot
2869
+ );
2870
+ }
2871
+ const resolvedLabel = input.label?.trim() || hydratedAttachment?.filename || staged?.filename || input.path?.trim() || input.branch?.trim() || input.url?.trim() || "\u4EA7\u51FA\u6587\u4EF6";
2872
+ storedOutput = {
2873
+ id: outputId,
2874
+ label: resolvedLabel,
2875
+ ...input.path !== void 0 ? { path: input.path } : {},
2876
+ ...input.branch !== void 0 ? { branch: input.branch } : {},
2877
+ ...input.summary !== void 0 ? { summary: input.summary } : {},
2878
+ ...input.url !== void 0 ? { url: input.url } : {},
2879
+ ...staged ? { attachmentId: staged.id } : input.attachmentId ? { attachmentId: input.attachmentId } : {},
2880
+ actorKind: actor.kind,
2881
+ actorId: actor.id,
2882
+ actorName: actor.name,
2883
+ ...actor.kind === "agent" ? { driver: actor.driver } : {},
2884
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2885
+ };
2886
+ const outputs = JSON.parse(current.outputs);
2887
+ outputs.push(storedOutput);
2888
+ await client.query(
2889
+ `UPDATE cards SET outputs = $2, version = version + 1, updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
2890
+ WHERE id = $1`,
2891
+ [cardId, JSON.stringify(outputs)]
2892
+ );
2893
+ if (actor.kind === "agent") {
2894
+ await touchParticipant(client, cardId, actor.id, void 0, `\u6DFB\u52A0\u4E86\u4EA7\u51FA\uFF1A${storedOutput.label}`);
2895
+ }
2896
+ await appendEvent(client, current.project_id, cardId, actor, "output_added", { output: storedOutput }, publish);
2897
+ });
2898
+ } catch (err) {
2899
+ if (staged) await unlink2(staged.diskPath).catch(() => {
2900
+ });
2901
+ throw err;
2902
+ }
2903
+ const hydratedOutput = hydratedAttachment ? { ...storedOutput, attachment: hydratedAttachment } : storedOutput;
2904
+ return { output: hydratedOutput, card: await getCardDetail(pool2, actor, cardId, uploadsRoot) };
2905
+ }
2906
+ async function resolveOutputTarget(pool2, actor, cardId, outputId, sandboxRoot, uploadsRoot) {
2907
+ const row = await readCardRow(pool2, cardId);
2908
+ assertAgentProjectAccess(actor, row.project_id);
2909
+ const outputs = JSON.parse(row.outputs);
2910
+ const output = outputs.find((o) => o.id === outputId);
2911
+ if (!output) throw new HttpError(404, "\u4EA7\u51FA\u8BB0\u5F55\u4E0D\u5B58\u5728");
2912
+ if (output.attachmentId) {
2913
+ const file = await getOutputAttachmentFile(pool2, cardId, outputId, output.attachmentId, uploadsRoot);
2914
+ if (!file) throw new HttpError(404, "\u6258\u7BA1\u4EA7\u51FA\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u79FB\u9664");
2915
+ let info2;
2916
+ try {
2917
+ info2 = await stat2(file.filePath);
2918
+ } catch {
2919
+ throw new HttpError(404, "\u6258\u7BA1\u4EA7\u51FA\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u79FB\u9664");
2920
+ }
2921
+ if (!info2.isFile()) throw new HttpError(400, "\u76EE\u6807\u8DEF\u5F84\u4E0D\u662F\u666E\u901A\u6587\u4EF6");
2922
+ return {
2923
+ output,
2924
+ managed: true,
2925
+ displayPath: file.filename,
2926
+ filename: file.filename,
2927
+ mimeType: file.mimeType,
2928
+ filePath: file.filePath
2929
+ };
2930
+ }
2931
+ if (!output.path?.trim()) throw new HttpError(400, "\u8BE5\u4EA7\u51FA\u6CA1\u6709\u5173\u8054\u672C\u5730\u6587\u4EF6\u8DEF\u5F84");
2932
+ const proj = (await pool2.query("SELECT root_path FROM projects WHERE id = $1", [row.project_id])).rows[0];
2933
+ const allowedRoots = [];
2934
+ for (const candidate of [proj?.root_path, sandboxRoot]) {
2935
+ if (!candidate?.trim()) continue;
2936
+ try {
2937
+ allowedRoots.push(await realpath(resolveUserPath(candidate)));
2938
+ } catch {
2939
+ }
2940
+ }
2941
+ const baseDir = proj?.root_path?.trim() ? resolveUserPath(proj.root_path) : resolveUserPath(sandboxRoot);
2942
+ const expandedOutputPath = expandTilde(output.path);
2943
+ const rawPath = path2.isAbsolute(expandedOutputPath) ? expandedOutputPath : path2.resolve(baseDir, expandedOutputPath);
2944
+ let actualPath;
2945
+ try {
2946
+ actualPath = await realpath(rawPath);
2947
+ } catch {
2948
+ throw new HttpError(404, `\u627E\u4E0D\u5230\u672C\u5730\u6587\u4EF6\uFF1A${output.path}`);
2949
+ }
2950
+ const inAllowed = allowedRoots.some((root) => isPathInsideRoot(root, actualPath));
2951
+ if (!inAllowed) throw new HttpError(403, "\u4EC5\u5141\u8BB8\u8BBF\u95EE\u9879\u76EE\u5DE5\u4F5C\u76EE\u5F55\u6216\u6C99\u7BB1\u76EE\u5F55\u5185\u7684\u4EA7\u51FA\u6587\u4EF6");
2952
+ const info = await stat2(actualPath);
2953
+ if (!info.isFile()) throw new HttpError(400, "\u76EE\u6807\u8DEF\u5F84\u4E0D\u662F\u666E\u901A\u6587\u4EF6");
2954
+ const filename = path2.basename(output.path);
2955
+ const mimeType = normalizeMimeType(void 0, filename);
2956
+ return {
2957
+ output,
2958
+ managed: false,
2959
+ displayPath: output.path,
2960
+ filename,
2961
+ mimeType,
2962
+ filePath: actualPath
2963
+ };
2964
+ }
2965
+ async function getOutputLocalPath(pool2, actor, cardId, outputId, sandboxRoot, uploadsRoot = config.uploadsDir) {
2966
+ const target = await resolveOutputTarget(pool2, actor, cardId, outputId, sandboxRoot, uploadsRoot);
2967
+ return target.filePath;
2968
+ }
2969
+ async function previewOutputFile(pool2, actor, cardId, outputId, sandboxRoot, uploadsRoot = config.uploadsDir) {
2970
+ const target = await resolveOutputTarget(pool2, actor, cardId, outputId, sandboxRoot, uploadsRoot);
2971
+ if (target.managed && !isTextPreviewable(target.mimeType, target.filename)) {
2972
+ throw new HttpError(400, "\u8BE5\u4EA7\u51FA\u4E3A\u4E8C\u8FDB\u5236\u6587\u4EF6\uFF0C\u8BF7\u5728\u8BBF\u8FBE\u4E2D\u67E5\u770B");
2973
+ }
2974
+ const maxBytes = target.managed ? MAX_TEXT_PREVIEW_BYTES : MAX_PREVIEW_BYTES;
2975
+ const { content, truncated } = await readBoundedUtf8File(target.filePath, maxBytes);
2976
+ return {
2977
+ outputId: target.output.id,
2978
+ label: target.output.label,
2979
+ path: target.displayPath,
2980
+ filename: target.filename,
2981
+ mimeType: target.mimeType,
2982
+ localPath: target.filePath,
2983
+ content,
2984
+ truncated
2985
+ };
2986
+ }
2987
+
2988
+ // src/domain/cards.ts
2989
+ async function createCard(pool2, actor, input, publish, uploadsRoot = config.uploadsDir) {
2990
+ assertAgentProjectAccess(actor, input.projectId);
2991
+ if (actor.kind === "agent" && input.status === "done") {
2992
+ throw new HttpError(403, "Agent \u4E0D\u80FD\u76F4\u63A5\u521B\u5EFA\u4E3A\u5DF2\u5B8C\u6210\u72B6\u6001\uFF0C\u8BF7\u521B\u5EFA\u4E3A todo / doing / review");
2993
+ }
2994
+ const cardId = randomUUID6();
2995
+ await transaction(pool2, async (client) => {
2996
+ const project = (await client.query("SELECT id FROM projects WHERE id = $1", [input.projectId])).rows[0];
2997
+ if (!project) throw new HttpError(404, "\u9879\u76EE\u4E0D\u5B58\u5728");
2998
+ if (input.parentId) {
2999
+ const parent = (await client.query("SELECT project_id FROM cards WHERE id = $1", [input.parentId])).rows[0];
3000
+ if (!parent) throw new HttpError(404, "\u7236\u5361\u7247\u4E0D\u5B58\u5728");
3001
+ if (parent.project_id !== input.projectId) throw new HttpError(400, "\u7236\u5361\u7247\u5FC5\u987B\u5C5E\u4E8E\u540C\u4E00\u9879\u76EE");
3002
+ }
3003
+ const cardDefaultAgentId = input.defaultAgentId ?? null;
3004
+ if (cardDefaultAgentId) {
3005
+ await validateCardDefaultAgent(client, input.projectId, cardDefaultAgentId);
3006
+ }
3007
+ const posRow = (await client.query(
3008
+ `SELECT COALESCE(MAX(position), -1) + 1 AS next_pos FROM cards WHERE project_id = $1 AND status = $2 AND archived_at IS NULL`,
3009
+ [input.projectId, input.status]
3010
+ )).rows[0];
3011
+ const completedAt = input.status === "done" ? /* @__PURE__ */ new Date() : null;
3012
+ await client.query(
3013
+ `INSERT INTO cards(id, project_id, parent_id, default_agent_id, title, body, status, priority, tags, checklist, outputs, position, created_by_kind, created_by_id, created_by_name, completed_at)
3014
+ VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, '[]', $11, $12, $13, $14, $15)`,
3015
+ [
3016
+ cardId,
3017
+ input.projectId,
3018
+ input.parentId ?? null,
3019
+ cardDefaultAgentId,
3020
+ input.title,
3021
+ input.body,
3022
+ input.status,
3023
+ input.priority,
3024
+ JSON.stringify([...new Set(input.tags)]),
3025
+ JSON.stringify(input.checklist),
3026
+ posRow.next_pos,
3027
+ actor.kind,
3028
+ actor.id,
3029
+ actor.name,
3030
+ completedAt
3031
+ ]
3032
+ );
3033
+ if (input.attachmentIds.length > 0) {
3034
+ await bindAttachmentsToCard(client, input.projectId, cardId, input.attachmentIds);
3035
+ }
3036
+ let mentionAgents = [];
3037
+ let targetActorIds = [];
3038
+ let routingReason = "none";
3039
+ if (actor.kind === "human") {
3040
+ mentionAgents = await resolveMentionAgents(client, input.projectId, input.mentions);
3041
+ if (mentionAgents.length > 0) {
3042
+ targetActorIds = mentionAgents.map((a) => a.id);
3043
+ routingReason = "mention";
3044
+ } else if (input.status === "doing" && !input.skipDefaultAgent) {
3045
+ const defaultAgent = await getEffectiveCardDefaultAgent(client, input.projectId, cardDefaultAgentId);
3046
+ if (defaultAgent) {
3047
+ targetActorIds = [defaultAgent.id];
3048
+ routingReason = "default_agent";
3049
+ }
3050
+ }
3051
+ } else {
3052
+ await touchParticipant(client, cardId, actor.id, "idle", `\u521B\u5EFA\u4E86\u4EFB\u52A1\u5361\u7247\u300C${input.title}\u300D`);
3053
+ }
3054
+ await appendEvent(
3055
+ client,
3056
+ input.projectId,
3057
+ cardId,
3058
+ actor,
3059
+ "card_created",
3060
+ {
3061
+ title: input.title,
3062
+ status: input.status,
3063
+ defaultAgentId: cardDefaultAgentId,
3064
+ mentions: mentionAgents.map((a) => a.id),
3065
+ mentionNames: mentionAgents.map((a) => a.name),
3066
+ targetActorIds,
3067
+ routingReason
3068
+ },
3069
+ publish
3070
+ );
3071
+ });
3072
+ return getCardDetail(pool2, actor, cardId, uploadsRoot);
3073
+ }
3074
+ function summarizeChanges(changedFields, before, after, customSummary, nextDefaultAgentName) {
3075
+ if (customSummary?.trim()) return customSummary.trim();
3076
+ const parts = [];
3077
+ if (changedFields.includes("title")) {
3078
+ parts.push(`\u4FEE\u6539\u6807\u9898\u4E3A\u300C${after.title}\u300D`);
3079
+ }
3080
+ if (changedFields.includes("priority")) {
3081
+ const pLabels = { high: "\u9AD8\u4F18\u5148", medium: "\u4E2D\u4F18\u5148", low: "\u4F4E\u4F18\u5148" };
3082
+ parts.push(`\u5C06\u4F18\u5148\u7EA7\u8C03\u6574\u4E3A\u300C${pLabels[after.priority]}\u300D`);
3083
+ }
3084
+ if (changedFields.includes("tags")) {
3085
+ const added = after.tags.filter((t) => !before.tags.includes(t));
3086
+ const removed = before.tags.filter((t) => !after.tags.includes(t));
3087
+ if (added.length) parts.push(`\u6DFB\u52A0\u6807\u7B7E ${added.map((t) => `#${t}`).join(" ")}`);
3088
+ if (removed.length) parts.push(`\u79FB\u9664\u6807\u7B7E ${removed.map((t) => `#${t}`).join(" ")}`);
3089
+ }
3090
+ if (changedFields.includes("checklist")) {
3091
+ const prevById = new Map(before.checklist.map((i) => [i.id, i]));
3092
+ const nextById = new Map(after.checklist.map((i) => [i.id, i]));
3093
+ const added = after.checklist.filter((i) => !prevById.has(i.id));
3094
+ const removed = before.checklist.filter((i) => !nextById.has(i.id));
3095
+ const checked = after.checklist.filter((i) => prevById.get(i.id)?.done === false && i.done);
3096
+ const unchecked = after.checklist.filter((i) => prevById.get(i.id)?.done === true && !i.done);
3097
+ if (checked.length === 1 && !added.length && !removed.length && !unchecked.length) {
3098
+ parts.push(`\u52FE\u9009\u5B8C\u6210\u300C${checked[0].text}\u300D`);
3099
+ } else if (unchecked.length === 1 && !added.length && !removed.length && !checked.length) {
3100
+ parts.push(`\u53D6\u6D88\u52FE\u9009\u300C${unchecked[0].text}\u300D`);
3101
+ } else if (added.length === 1 && !removed.length && !checked.length && !unchecked.length) {
3102
+ parts.push(`\u65B0\u589E\u6E05\u5355\u9879\u300C${added[0].text}\u300D`);
3103
+ } else if (removed.length === 1 && !added.length && !checked.length && !unchecked.length) {
3104
+ parts.push(`\u79FB\u9664\u6E05\u5355\u9879\u300C${removed[0].text}\u300D`);
3105
+ } else {
3106
+ const sub = [];
3107
+ if (checked.length) sub.push(`\u5B8C\u6210 ${checked.length} \u9879`);
3108
+ if (unchecked.length) sub.push(`\u53D6\u6D88\u5B8C\u6210 ${unchecked.length} \u9879`);
3109
+ if (added.length) sub.push(`\u65B0\u589E ${added.length} \u9879`);
3110
+ if (removed.length) sub.push(`\u79FB\u9664 ${removed.length} \u9879`);
3111
+ parts.push(sub.length ? `\u66F4\u65B0\u4EFB\u52A1\u6E05\u5355\uFF08${sub.join("\u3001")}\uFF09` : "\u66F4\u65B0\u4E86\u4EFB\u52A1\u6E05\u5355");
3112
+ }
3113
+ }
3114
+ if (changedFields.includes("body")) {
3115
+ parts.push(before.body.trim() ? "\u66F4\u65B0\u4E86\u4EFB\u52A1\u6B63\u6587" : "\u8865\u5145\u4E86\u4EFB\u52A1\u6B63\u6587");
3116
+ }
3117
+ if (changedFields.includes("parentId")) {
3118
+ parts.push(after.parentId ? "\u5173\u8054\u4E86\u7236\u5361\u7247" : "\u53D6\u6D88\u4E86\u7236\u5361\u7247\u5173\u8054");
3119
+ }
3120
+ if (changedFields.includes("defaultAgentId")) {
3121
+ parts.push(
3122
+ after.defaultAgentId ? `\u5C06\u5361\u7247\u9ED8\u8BA4 Agent \u8BBE\u4E3A\u300C${nextDefaultAgentName ?? after.defaultAgentId.slice(0, 8)}\u300D` : "\u5C06\u5361\u7247\u9ED8\u8BA4 Agent \u6539\u4E3A\u8DDF\u968F\u9879\u76EE\u9ED8\u8BA4"
3123
+ );
3124
+ }
3125
+ return parts.join("\uFF1B") || "\u66F4\u65B0\u4E86\u5361\u7247";
3126
+ }
3127
+ async function assertValidParentCard(client, cardId, projectId, nextParentId) {
3128
+ let cursorId = nextParentId;
3129
+ const visited = /* @__PURE__ */ new Set([cardId]);
3130
+ let isImmediateParent = true;
3131
+ while (cursorId) {
3132
+ if (visited.has(cursorId)) throw new HttpError(400, "\u4E0D\u80FD\u5F62\u6210\u5FAA\u73AF\u7236\u5B50\u5361\u7247\u5173\u7CFB");
3133
+ visited.add(cursorId);
3134
+ const ancestor = (await client.query(
3135
+ "SELECT project_id, parent_id FROM cards WHERE id = $1",
3136
+ [cursorId]
3137
+ )).rows[0];
3138
+ if (isImmediateParent) {
3139
+ if (!ancestor) throw new HttpError(404, "\u7236\u5361\u7247\u4E0D\u5B58\u5728");
3140
+ if (ancestor.project_id !== projectId) throw new HttpError(400, "\u7236\u5361\u7247\u5FC5\u987B\u5C5E\u4E8E\u540C\u4E00\u9879\u76EE");
3141
+ isImmediateParent = false;
3142
+ } else if (!ancestor) {
3143
+ break;
3144
+ }
3145
+ cursorId = ancestor.parent_id;
3146
+ }
3147
+ }
3148
+ function applyChecklistOps(current, ops, actorName) {
3149
+ const next = current.map((item) => ({ ...item }));
3150
+ for (const op of ops) {
3151
+ if (op.op === "add") {
3152
+ const id = op.id ?? `c-${randomUUID6().slice(0, 8)}`;
3153
+ if (next.some((item) => item.id === id)) {
3154
+ throw new HttpError(400, `\u6E05\u5355\u9879 ID \u5DF2\u5B58\u5728\uFF1A${id}`, {
3155
+ existingIds: next.map((item) => item.id),
3156
+ hint: "\u8BF7\u66F4\u6362\u4E0D\u91CD\u590D\u7684 id\uFF0C\u6216\u7701\u7565 id \u7531\u670D\u52A1\u7AEF\u81EA\u52A8\u751F\u6210"
3157
+ });
3158
+ }
3159
+ if (next.length >= 100) {
3160
+ throw new HttpError(400, "\u4EFB\u52A1\u6E05\u5355\u6700\u591A\u652F\u6301 100 \u9879");
3161
+ }
3162
+ next.push({ id, text: op.text, done: Boolean(op.done), updatedBy: actorName });
3163
+ } else if (op.op === "update") {
3164
+ const target = next.find((item) => item.id === op.id);
3165
+ if (!target) {
3166
+ throw new HttpError(400, `\u6E05\u5355\u9879\u4E0D\u5B58\u5728\uFF1A${op.id}`, {
3167
+ availableChecklistIds: next.map((item) => ({ id: item.id, text: item.text, done: item.done })),
3168
+ hint: "\u8BF7\u4ECE availableChecklistIds \u4E2D\u6838\u5BF9\u6E05\u5355\u9879 id \u540E\u91CD\u8BD5"
3169
+ });
3170
+ }
3171
+ const textChanged = op.text !== void 0 && op.text !== target.text;
3172
+ const doneChanged = op.done !== void 0 && op.done !== target.done;
3173
+ if (textChanged) target.text = op.text;
3174
+ if (doneChanged) target.done = op.done;
3175
+ if (textChanged || doneChanged) target.updatedBy = actorName;
3176
+ } else {
3177
+ const idx = next.findIndex((item) => item.id === op.id);
3178
+ if (idx === -1) {
3179
+ throw new HttpError(400, `\u6E05\u5355\u9879\u4E0D\u5B58\u5728\uFF1A${op.id}`, {
3180
+ availableChecklistIds: next.map((item) => ({ id: item.id, text: item.text, done: item.done })),
3181
+ hint: "\u8BF7\u4ECE availableChecklistIds \u4E2D\u6838\u5BF9\u6E05\u5355\u9879 id \u540E\u91CD\u8BD5"
3182
+ });
3183
+ }
3184
+ next.splice(idx, 1);
3185
+ }
3186
+ }
3187
+ return checklistSchema.parse(next);
3188
+ }
3189
+ async function updateCard(pool2, actor, cardId, input, publish, uploadsRoot = config.uploadsDir) {
3190
+ await transaction(pool2, async (client) => {
3191
+ const current = await readCardRow(client, cardId);
3192
+ assertAgentProjectAccess(actor, current.project_id);
3193
+ const beforeSnapshot = {
3194
+ title: current.title,
3195
+ body: current.body,
3196
+ priority: current.priority,
3197
+ tags: JSON.parse(current.tags),
3198
+ checklist: JSON.parse(current.checklist),
3199
+ parentId: current.parent_id,
3200
+ defaultAgentId: current.default_agent_id ?? null
3201
+ };
3202
+ if (input.expectedVersion !== void 0 && current.version !== input.expectedVersion) {
3203
+ throw new HttpError(
3204
+ 409,
3205
+ `\u5361\u7247\u7248\u672C\u51B2\u7A81\uFF1A\u671F\u671B\u7248\u672C v${input.expectedVersion}\uFF0C\u5F53\u524D\u6700\u65B0\u7248\u672C\u4E3A v${current.version}\u3002\u8BF7\u5148\u8FD0\u884C slate read \u83B7\u53D6\u6700\u65B0\u5185\u5BB9\u540E\u91CD\u8BD5`,
3206
+ {
3207
+ expectedVersion: input.expectedVersion,
3208
+ currentVersion: current.version,
3209
+ currentStatus: current.status,
3210
+ checklist: beforeSnapshot.checklist,
3211
+ hint: "\u68C0\u6D4B\u5230\u5E76\u53D1\u4FEE\u6539\uFF0C\u8BF7\u7528 slate read \u67E5\u770B\u6700\u65B0\u6B63\u6587\u4E0E\u6E05\u5355\uFF0C\u518D\u57FA\u4E8E\u6700\u65B0 version \u91CD\u8BD5 slate update\uFF08\u5E76\u53D1\u573A\u666F\u63A8\u8350\u4F7F\u7528 checklistOps \u5C40\u90E8\u66F4\u65B0\u6E05\u5355\uFF09"
3212
+ }
3213
+ );
3214
+ }
3215
+ const nextTitle = input.title ?? beforeSnapshot.title;
3216
+ const nextBody = input.body ?? beforeSnapshot.body;
3217
+ const nextPriority = input.priority ?? beforeSnapshot.priority;
3218
+ const nextTags = input.tags !== void 0 ? [...new Set(input.tags)] : beforeSnapshot.tags;
3219
+ const nextChecklist = input.checklistOps !== void 0 ? applyChecklistOps(beforeSnapshot.checklist, input.checklistOps, actor.name) : input.checklist !== void 0 ? input.checklist : beforeSnapshot.checklist;
3220
+ const nextParentId = input.parentId !== void 0 ? input.parentId : beforeSnapshot.parentId;
3221
+ const nextDefaultAgentId = input.defaultAgentId !== void 0 ? input.defaultAgentId : beforeSnapshot.defaultAgentId;
3222
+ const nextPosition = input.position ?? current.position;
3223
+ if (nextParentId === cardId) throw new HttpError(400, "\u4E0D\u80FD\u5C06\u5361\u7247\u8BBE\u4E3A\u81EA\u5DF1\u7684\u7236\u5361\u7247");
3224
+ if (nextParentId && nextParentId !== beforeSnapshot.parentId) {
3225
+ await assertValidParentCard(client, cardId, current.project_id, nextParentId);
3226
+ }
3227
+ let nextDefaultAgentName = null;
3228
+ if (nextDefaultAgentId && nextDefaultAgentId !== beforeSnapshot.defaultAgentId) {
3229
+ const validated = await validateCardDefaultAgent(client, current.project_id, nextDefaultAgentId);
3230
+ nextDefaultAgentName = validated.name;
3231
+ }
3232
+ const afterSnapshot = {
3233
+ title: nextTitle,
3234
+ body: nextBody,
3235
+ priority: nextPriority,
3236
+ tags: nextTags,
3237
+ checklist: nextChecklist,
3238
+ parentId: nextParentId,
3239
+ defaultAgentId: nextDefaultAgentId
3240
+ };
3241
+ const changedFields = [];
3242
+ if (afterSnapshot.title !== beforeSnapshot.title) changedFields.push("title");
3243
+ if (afterSnapshot.body !== beforeSnapshot.body) changedFields.push("body");
3244
+ if (afterSnapshot.priority !== beforeSnapshot.priority) changedFields.push("priority");
3245
+ if (JSON.stringify(afterSnapshot.tags) !== JSON.stringify(beforeSnapshot.tags)) changedFields.push("tags");
3246
+ if (JSON.stringify(afterSnapshot.checklist) !== JSON.stringify(beforeSnapshot.checklist))
3247
+ changedFields.push("checklist");
3248
+ if (afterSnapshot.parentId !== beforeSnapshot.parentId) changedFields.push("parentId");
3249
+ if (afterSnapshot.defaultAgentId !== beforeSnapshot.defaultAgentId) changedFields.push("defaultAgentId");
3250
+ const positionChanged = nextPosition !== current.position;
3251
+ if (changedFields.length === 0 && !positionChanged) {
3252
+ return;
3253
+ }
3254
+ const nextVersion = changedFields.length > 0 ? current.version + 1 : current.version;
3255
+ await client.query(
3256
+ `UPDATE cards SET
3257
+ title = $2, body = $3, priority = $4, tags = $5, checklist = $6, parent_id = $7, default_agent_id = $8, position = $9,
3258
+ version = $10, updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
3259
+ WHERE id = $1`,
3260
+ [
3261
+ cardId,
3262
+ nextTitle,
3263
+ nextBody,
3264
+ nextPriority,
3265
+ JSON.stringify(nextTags),
3266
+ JSON.stringify(nextChecklist),
3267
+ nextParentId,
3268
+ nextDefaultAgentId,
3269
+ nextPosition,
3270
+ nextVersion
3271
+ ]
3272
+ );
3273
+ if (changedFields.length > 0) {
3274
+ const revisionId = randomUUID6();
3275
+ const summary = summarizeChanges(
3276
+ changedFields,
3277
+ beforeSnapshot,
3278
+ afterSnapshot,
3279
+ input.summary,
3280
+ nextDefaultAgentName
3281
+ );
3282
+ await client.query(
3283
+ `INSERT INTO card_revisions(id, card_id, version, actor_kind, actor_id, actor_name, summary, before_snapshot, after_snapshot)
3284
+ VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
3285
+ [
3286
+ revisionId,
3287
+ cardId,
3288
+ nextVersion,
3289
+ actor.kind,
3290
+ actor.id,
3291
+ actor.name,
3292
+ summary,
3293
+ JSON.stringify(beforeSnapshot),
3294
+ JSON.stringify(afterSnapshot)
3295
+ ]
3296
+ );
3297
+ if (actor.kind === "agent") await touchParticipant(client, cardId, actor.id, void 0, summary);
3298
+ await appendEvent(
3299
+ client,
3300
+ current.project_id,
3301
+ cardId,
3302
+ actor,
3303
+ "card_updated",
3304
+ { summary, changedFields, revisionId, version: nextVersion },
3305
+ publish
3306
+ );
3307
+ } else {
3308
+ notifyAfterCommit(client, publish, {
3309
+ type: "board_updated",
3310
+ projectId: current.project_id,
3311
+ cardId,
3312
+ reason: "reordered"
3313
+ });
3314
+ }
3315
+ });
3316
+ return getCardDetail(pool2, actor, cardId, uploadsRoot);
3317
+ }
3318
+ async function changeCardStatus(pool2, actor, cardId, input, publish) {
3319
+ return transaction(pool2, async (client) => {
3320
+ const current = await readCardRow(client, cardId);
3321
+ assertAgentProjectAccess(actor, current.project_id);
3322
+ if (actor.kind === "agent" && input.status === "done") {
3323
+ throw new HttpError(403, "Agent \u4E0D\u80FD\u76F4\u63A5\u5C06\u5361\u7247\u6807\u8BB0\u4E3A\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u5148\u63A8\u8FDB\u81F3 review\uFF08\u5F85\u9A8C\u6536\uFF09\u7531\u4EBA\u786E\u8BA4");
3324
+ }
3325
+ if (actor.kind === "agent" && current.status === "done") {
3326
+ throw new HttpError(409, "\u5361\u7247\u5DF2\u5B8C\u6210\uFF1B\u5982\u9700\u8865\u5145\u4FE1\u606F\u8BF7\u4F7F\u7528 slate comment\uFF0C\u7531\u4EBA\u51B3\u5B9A\u662F\u5426\u91CD\u65B0\u6253\u5F00", {
3327
+ currentStatus: "done"
3328
+ });
3329
+ }
3330
+ const outputs = JSON.parse(current.outputs);
3331
+ if (current.status === input.status && input.position === void 0) {
3332
+ const lastStatusEv = (await client.query(
3333
+ `SELECT id, CAST(server_seq AS TEXT) AS server_seq, project_id, card_id, type, actor_kind, actor_id, actor_name, data, created_at
3334
+ FROM card_events WHERE card_id = $1 AND type = 'status_changed'
3335
+ ORDER BY server_seq DESC LIMIT 1`,
3336
+ [cardId]
3337
+ )).rows[0];
3338
+ const lastData = lastStatusEv ? JSON.parse(lastStatusEv.data) : null;
3339
+ const lastBy = lastStatusEv?.actor_name ?? current.created_by_name;
3340
+ return {
3341
+ changed: false,
3342
+ card: await buildCardSummary(client, current),
3343
+ currentStatus: current.status,
3344
+ ...lastStatusEv ? {
3345
+ lastStatusChange: {
3346
+ actorName: lastStatusEv.actor_name,
3347
+ at: iso2(lastStatusEv.created_at),
3348
+ ...typeof lastData?.note === "string" && lastData.note ? { note: lastData.note } : {}
3349
+ }
3350
+ } : {},
3351
+ recentOutputs: outputs.slice(-5),
3352
+ hint: `\u5361\u7247\u5F53\u524D\u5DF2\u5904\u4E8E ${current.status} \u72B6\u6001\uFF08\u6700\u8FD1\u7531\u300C${lastBy}\u300D\u53D8\u66F4\uFF09\u3002\u5982\u9700\u6DFB\u52A0\u989D\u5916\u8BF4\u660E\u6216\u4EA7\u7269\uFF0C\u8BF7\u4F7F\u7528 slate comment \u6216 slate output\u3002`
3353
+ };
3354
+ }
3355
+ const statusChanged = current.status !== input.status;
3356
+ let nextPos = input.position;
3357
+ if (nextPos === void 0) {
3358
+ nextPos = (await client.query(
3359
+ `SELECT COALESCE(MAX(position), -1) + 1 AS next_pos FROM cards WHERE project_id = $1 AND status = $2 AND archived_at IS NULL`,
3360
+ [current.project_id, input.status]
3361
+ )).rows[0].next_pos;
3362
+ }
3363
+ if (!statusChanged && nextPos === current.position) {
3364
+ return {
3365
+ changed: false,
3366
+ card: await buildCardSummary(client, current),
3367
+ currentStatus: current.status
3368
+ };
3369
+ }
3370
+ const completedAt = input.status === "done" ? statusChanged || !current.completed_at ? /* @__PURE__ */ new Date() : current.completed_at : null;
3371
+ const nextVersion = statusChanged ? current.version + 1 : current.version;
3372
+ await client.query(
3373
+ `UPDATE cards SET
3374
+ status = $2, position = $3, completed_at = $4, version = $5,
3375
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
3376
+ WHERE id = $1`,
3377
+ [cardId, input.status, nextPos, completedAt, nextVersion]
3378
+ );
3379
+ if (actor.kind === "agent" && statusChanged) {
3380
+ const state = input.status === "doing" ? "running" : "idle";
3381
+ await touchParticipant(client, cardId, actor.id, state, input.note?.trim() || `\u5C06\u72B6\u6001\u6539\u4E3A ${input.status}`);
3382
+ }
3383
+ if (statusChanged) {
3384
+ let targetActorIds = [];
3385
+ let routingReason = "none";
3386
+ if (actor.kind === "human" && current.status === "todo" && input.status === "doing") {
3387
+ const effectiveAgent = await getEffectiveCardDefaultAgent(
3388
+ client,
3389
+ current.project_id,
3390
+ current.default_agent_id ?? null
3391
+ );
3392
+ if (effectiveAgent) {
3393
+ targetActorIds = [effectiveAgent.id];
3394
+ routingReason = "default_agent";
3395
+ }
3396
+ }
3397
+ await appendEvent(
3398
+ client,
3399
+ current.project_id,
3400
+ cardId,
3401
+ actor,
3402
+ "status_changed",
3403
+ {
3404
+ fromStatus: current.status,
3405
+ toStatus: input.status,
3406
+ ...input.note?.trim() ? { note: input.note.trim() } : {},
3407
+ targetActorIds,
3408
+ routingReason
3409
+ },
3410
+ publish
3411
+ );
3412
+ if (actor.kind === "human" && input.status === "todo") {
3413
+ const runningAgents = (await client.query(
3414
+ `SELECT cp.agent_id, a.name AS agent_name
3415
+ FROM card_participants cp
3416
+ JOIN agents a ON a.id = cp.agent_id
3417
+ WHERE cp.card_id = $1
3418
+ AND (cp.state = 'running' OR (cp.processing_until IS NOT NULL AND cp.processing_until > strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')))`,
3419
+ [cardId]
3420
+ )).rows;
3421
+ for (const running of runningAgents) {
3422
+ await client.query(
3423
+ `UPDATE card_participants
3424
+ SET state = 'paused',
3425
+ activity_text = '\u5361\u7247\u5DF2\u79FB\u56DE\u5F85\u529E\uFF0C\u5DF2\u81EA\u52A8\u505C\u6B62',
3426
+ processing_event_id = NULL,
3427
+ processing_until = NULL,
3428
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
3429
+ WHERE card_id = $1 AND agent_id = $2`,
3430
+ [cardId, running.agent_id]
3431
+ );
3432
+ await appendEvent(
3433
+ client,
3434
+ current.project_id,
3435
+ cardId,
3436
+ actor,
3437
+ "agent_stop_requested",
3438
+ {
3439
+ agentId: running.agent_id,
3440
+ agentName: running.agent_name,
3441
+ targetActorIds: [running.agent_id],
3442
+ routingReason: "stop",
3443
+ reason: "moved_to_todo"
3444
+ },
3445
+ publish
3446
+ );
3447
+ notifyAfterCommit(client, publish, {
3448
+ type: "command",
3449
+ command: "stop-agent",
3450
+ agentId: running.agent_id,
3451
+ cardId
3452
+ });
3453
+ }
3454
+ }
3455
+ } else {
3456
+ notifyAfterCommit(client, publish, {
3457
+ type: "board_updated",
3458
+ projectId: current.project_id,
3459
+ cardId,
3460
+ reason: "reordered"
3461
+ });
3462
+ }
3463
+ const updatedRow = await readCardRow(client, cardId);
3464
+ return {
3465
+ changed: statusChanged,
3466
+ card: await buildCardSummary(client, updatedRow),
3467
+ currentStatus: updatedRow.status
3468
+ };
3469
+ });
3470
+ }
3471
+ async function archiveCard(pool2, cardId, archived, publish) {
3472
+ await transaction(pool2, async (client) => {
3473
+ const current = await readCardRow(client, cardId);
3474
+ if (Boolean(current.archived_at) === archived) return;
3475
+ await client.query(
3476
+ `UPDATE cards SET archived_at = $2, updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now') WHERE id = $1`,
3477
+ [cardId, archived ? /* @__PURE__ */ new Date() : null]
3478
+ );
3479
+ notifyAfterCommit(client, publish, {
3480
+ type: "board_updated",
3481
+ projectId: current.project_id,
3482
+ cardId,
3483
+ reason: archived ? "archived" : "unarchived"
3484
+ });
3485
+ });
3486
+ return { ok: true };
3487
+ }
3488
+ async function deleteCard(pool2, cardId, publish, uploadsRoot = config.uploadsDir) {
3489
+ let attachmentPaths = [];
3490
+ await transaction(pool2, async (client) => {
3491
+ const current = await readCardRow(client, cardId);
3492
+ attachmentPaths = await collectStoragePathsForCard(client, cardId);
3493
+ await client.query("DELETE FROM cards WHERE id = $1", [cardId]);
3494
+ notifyAfterCommit(client, publish, {
3495
+ type: "board_updated",
3496
+ projectId: current.project_id,
3497
+ cardId,
3498
+ reason: "deleted"
3499
+ });
3500
+ });
3501
+ if (attachmentPaths.length > 0) {
3502
+ await unlinkStoragePaths(uploadsRoot, attachmentPaths);
3503
+ }
3504
+ return { ok: true };
3505
+ }
3506
+
3507
+ // src/domain/assistant.ts
3508
+ var RUN_SELECT = `
3509
+ SELECT r.id, r.project_id, r.thread_id, r.agent_id, a.name AS agent_name, a.driver,
3510
+ r.kind, r.preset, r.prompt, r.options, r.attachment_ids, r.status, r.activity_text,
3511
+ r.session_id, r.result, r.applied_action_ids, r.error_message,
3512
+ r.created_at, r.updated_at
3513
+ FROM project_assistant_runs r
3514
+ JOIN agents a ON a.id = r.agent_id
3515
+ `;
3516
+ var iso3 = (v) => v instanceof Date ? v.toISOString() : v;
3517
+ function mapRun(row) {
3518
+ return {
3519
+ id: row.id,
3520
+ projectId: row.project_id,
3521
+ threadId: row.thread_id,
3522
+ agentId: row.agent_id,
3523
+ agentName: row.agent_name,
3524
+ driver: row.driver,
3525
+ kind: row.kind,
3526
+ preset: row.preset,
3527
+ prompt: row.prompt,
3528
+ options: assistantRunOptionsSchema.parse(JSON.parse(row.options || "{}")),
3529
+ attachmentIds: JSON.parse(row.attachment_ids || "[]"),
3530
+ status: row.status,
3531
+ activityText: row.activity_text,
3532
+ sessionId: row.session_id,
3533
+ result: row.result ? JSON.parse(row.result) : null,
3534
+ appliedActionIds: JSON.parse(row.applied_action_ids || "[]"),
3535
+ errorMessage: row.error_message,
3536
+ createdAt: iso3(row.created_at),
3537
+ updatedAt: iso3(row.updated_at)
3538
+ };
3539
+ }
3540
+ async function readRunRow(db, id) {
3541
+ const row = (await db.query(`${RUN_SELECT} WHERE r.id = $1`, [id])).rows[0];
3542
+ if (!row) throw new HttpError(404, "\u52A9\u624B\u4EFB\u52A1\u4E0D\u5B58\u5728");
3543
+ return row;
3544
+ }
3545
+ async function createAssistantRun(pool2, input, publish) {
3546
+ const id = randomUUID7();
3547
+ const threadId = input.threadId ?? randomUUID7();
3548
+ const options = assistantRunOptionsSchema.parse(input.options ?? {});
3549
+ await transaction(pool2, async (client) => {
3550
+ const project = (await client.query("SELECT id FROM projects WHERE id = $1", [input.projectId])).rows[0];
3551
+ if (!project) throw new HttpError(404, "\u9879\u76EE\u4E0D\u5B58\u5728");
3552
+ const agent = (await client.query(
3553
+ "SELECT id, project_id, enabled FROM agents WHERE id = $1",
3554
+ [input.agentId]
3555
+ )).rows[0];
3556
+ if (!agent) throw new HttpError(404, "\u6307\u5B9A\u7684 Agent \u4E0D\u5B58\u5728");
3557
+ if (!agent.enabled) throw new HttpError(400, "\u6307\u5B9A\u7684 Agent \u5DF2\u505C\u7528");
3558
+ if (agent.project_id && agent.project_id !== input.projectId) {
3559
+ throw new HttpError(403, "\u8BE5 Agent \u672A\u7ED1\u5B9A\u5230\u6B64\u9879\u76EE");
3560
+ }
3561
+ const attachmentIds = await validateAssistantRunAttachments(client, input.projectId, input.attachmentIds ?? []);
3562
+ let priorSessionId = null;
3563
+ if (input.kind === "assistant_chat" && input.threadId) {
3564
+ const prev = (await client.query(
3565
+ `SELECT session_id FROM project_assistant_runs
3566
+ WHERE project_id = $1 AND thread_id = $2 AND agent_id = $3 AND session_id IS NOT NULL
3567
+ ORDER BY created_at DESC, rowid DESC LIMIT 1`,
3568
+ [input.projectId, threadId, input.agentId]
3569
+ )).rows[0];
3570
+ priorSessionId = prev?.session_id ?? null;
3571
+ }
3572
+ await client.query(
3573
+ `INSERT INTO project_assistant_runs(
3574
+ id, project_id, thread_id, agent_id, kind, preset, prompt, options, attachment_ids, status, activity_text, session_id
3575
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'queued', $10, $11)`,
3576
+ [
3577
+ id,
3578
+ input.projectId,
3579
+ threadId,
3580
+ input.agentId,
3581
+ input.kind,
3582
+ input.preset ?? null,
3583
+ input.prompt,
3584
+ JSON.stringify(options),
3585
+ JSON.stringify(attachmentIds),
3586
+ input.kind === "card_draft" ? "\u6B63\u5728\u7B49\u5F85\u672C\u673A Agent \u6574\u7406\u8349\u7A3F\u2026" : "\u6B63\u5728\u7B49\u5F85\u672C\u673A Agent \u54CD\u5E94\u2026",
3587
+ priorSessionId
3588
+ ]
3589
+ );
3590
+ notifyAfterCommit(client, publish, {
3591
+ type: "command",
3592
+ command: "assistant-run",
3593
+ agentId: input.agentId,
3594
+ runId: id
3595
+ });
3596
+ notifyAfterCommit(client, publish, {
3597
+ type: "board_updated",
3598
+ projectId: input.projectId,
3599
+ reason: "assistant_run_created"
3600
+ });
3601
+ });
3602
+ return mapRun(await readRunRow(pool2, id));
3603
+ }
3604
+ async function listAssistantRuns(pool2, filters) {
3605
+ const conditions = ["r.project_id = $1"];
3606
+ const params = [filters.projectId];
3607
+ const push = (val) => {
3608
+ params.push(val);
3609
+ return `$${params.length}`;
3610
+ };
3611
+ if (filters.kind) conditions.push(`r.kind = ${push(filters.kind)}`);
3612
+ if (filters.threadId) conditions.push(`r.thread_id = ${push(filters.threadId)}`);
3613
+ const limitParam = push(Math.min(Math.max(filters.limit ?? 30, 1), 100));
3614
+ const order = filters.threadId ? "ASC" : "DESC";
3615
+ const rows = (await pool2.query(
3616
+ `${RUN_SELECT} WHERE ${conditions.join(" AND ")} ORDER BY r.created_at ${order}, r.rowid ${order} LIMIT ${limitParam}`,
3617
+ params
3618
+ )).rows;
3619
+ return rows.map(mapRun);
3620
+ }
3621
+ async function getAssistantRun(pool2, id) {
3622
+ return mapRun(await readRunRow(pool2, id));
3623
+ }
3624
+ async function claimNextAssistantRun(pool2, agent, publish, uploadsRoot = config.uploadsDir) {
3625
+ if (!agent.enabled) return null;
3626
+ const claimed = await transaction(pool2, async (client) => {
3627
+ const freshAgent = (await client.query("SELECT id, name, driver, project_id, enabled FROM agents WHERE id = $1", [agent.id])).rows[0];
3628
+ if (!freshAgent?.enabled) return null;
3629
+ const next = (await client.query(
3630
+ `SELECT id, project_id FROM project_assistant_runs
3631
+ WHERE agent_id = $1
3632
+ AND status = 'queued'
3633
+ AND ($2 IS NULL OR project_id = $2)
3634
+ ORDER BY created_at ASC, rowid ASC LIMIT 1`,
3635
+ [freshAgent.id, freshAgent.project_id]
3636
+ )).rows[0];
3637
+ if (!next) return null;
3638
+ const projRow = (await client.query(
3639
+ `SELECT id, name, description, root_path, default_agent_id, parallel_mode, created_at
3640
+ FROM projects WHERE id = $1`,
3641
+ [next.project_id]
3642
+ )).rows[0];
3643
+ if (!projRow) return null;
3644
+ const updated = await client.query(
3645
+ `UPDATE project_assistant_runs
3646
+ SET status = 'running',
3647
+ activity_text = '\u6B63\u5728\u8BFB\u53D6\u9879\u76EE\u770B\u677F\u4E0A\u4E0B\u6587\u2026',
3648
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
3649
+ WHERE id = $1 AND status = 'queued'`,
3650
+ [next.id]
3651
+ );
3652
+ if (!updated.rowCount) return null;
3653
+ const run = mapRun(await readRunRow(client, next.id));
3654
+ const project = {
3655
+ id: projRow.id,
3656
+ name: projRow.name,
3657
+ description: projRow.description,
3658
+ rootPath: projRow.root_path,
3659
+ defaultAgentId: projRow.default_agent_id,
3660
+ parallelMode: projRow.parallel_mode,
3661
+ createdAt: iso3(projRow.created_at)
3662
+ };
3663
+ const actor = {
3664
+ kind: "agent",
3665
+ id: freshAgent.id,
3666
+ name: freshAgent.name,
3667
+ driver: freshAgent.driver,
3668
+ projectId: freshAgent.project_id
3669
+ };
3670
+ notifyAfterCommit(client, publish, {
3671
+ type: "board_updated",
3672
+ projectId: next.project_id,
3673
+ reason: "assistant_run_running"
3674
+ });
3675
+ return { run, project, actor };
3676
+ });
3677
+ if (!claimed) return null;
3678
+ const cards = claimed.run.options.includeExistingCards ? await listCards(pool2, claimed.actor, { projectId: claimed.run.projectId, includeArchived: false }) : [];
3679
+ const allAgents = await listAgents(pool2, claimed.run.projectId);
3680
+ const agents = allAgents.map((a) => ({
3681
+ id: a.id,
3682
+ name: a.name,
3683
+ driver: a.driver,
3684
+ online: a.online,
3685
+ enabled: a.enabled
3686
+ }));
3687
+ const attachments = await fetchAttachmentsByIds(pool2, claimed.run.projectId, claimed.run.attachmentIds, uploadsRoot);
3688
+ return { run: claimed.run, project: claimed.project, cards, agents, attachments };
3689
+ }
3690
+ var activeRunMeta = /* @__PURE__ */ new Map();
3691
+ async function streamAssistantRunDelta(pool2, agent, runId, input, publish) {
3692
+ let meta = activeRunMeta.get(runId);
3693
+ if (!meta) {
3694
+ const row = (await pool2.query("SELECT project_id, thread_id, kind, agent_id, status FROM project_assistant_runs WHERE id = $1", [runId])).rows[0];
3695
+ if (!row) throw new HttpError(404, "\u52A9\u624B\u4EFB\u52A1\u4E0D\u5B58\u5728");
3696
+ if (row.agent_id !== agent.id) throw new HttpError(403, "\u65E0\u6743\u63A8\u9001\u5176\u4ED6 Agent \u7684\u6D41\u5F0F\u8F93\u51FA");
3697
+ if (row.status !== "running" && row.status !== "queued") return { ok: true };
3698
+ meta = { projectId: row.project_id, threadId: row.thread_id, kind: row.kind, agentId: row.agent_id };
3699
+ activeRunMeta.set(runId, meta);
3700
+ } else if (meta.agentId !== agent.id) {
3701
+ throw new HttpError(403, "\u65E0\u6743\u63A8\u9001\u5176\u4ED6 Agent \u7684\u6D41\u5F0F\u8F93\u51FA");
3702
+ }
3703
+ publish?.({
3704
+ type: "assistant_delta",
3705
+ projectId: meta.projectId,
3706
+ runId,
3707
+ threadId: meta.threadId,
3708
+ kind: meta.kind,
3709
+ text: input.text,
3710
+ stage: input.stage,
3711
+ ...input.activityText ? { activityText: input.activityText } : {}
3712
+ });
3713
+ return { ok: true };
3714
+ }
3715
+ async function reportAssistantRunProgress(pool2, agent, runId, input, publish) {
3716
+ await transaction(pool2, async (client) => {
3717
+ const current = await readRunRow(client, runId);
3718
+ if (current.agent_id !== agent.id) throw new HttpError(403, "\u65E0\u6743\u66F4\u65B0\u5176\u4ED6 Agent \u7684\u52A9\u624B\u4EFB\u52A1");
3719
+ if (["succeeded", "failed", "cancelled"].includes(current.status)) {
3720
+ activeRunMeta.delete(runId);
3721
+ return;
3722
+ }
3723
+ await client.query(
3724
+ `UPDATE project_assistant_runs
3725
+ SET status = $2,
3726
+ activity_text = COALESCE($3, activity_text),
3727
+ session_id = COALESCE($4, session_id),
3728
+ result = COALESCE($5, result),
3729
+ error_message = COALESCE($6, error_message),
3730
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
3731
+ WHERE id = $1`,
3732
+ [
3733
+ runId,
3734
+ input.status,
3735
+ input.activityText ?? null,
3736
+ input.sessionId ?? null,
3737
+ input.result ? JSON.stringify(input.result) : null,
3738
+ input.errorMessage ?? null
3739
+ ]
3740
+ );
3741
+ notifyAfterCommit(client, publish, {
3742
+ type: "board_updated",
3743
+ projectId: current.project_id,
3744
+ reason: `assistant_run_${input.status}`
3745
+ });
3746
+ if (input.status !== "running") {
3747
+ client.afterCommit(() => activeRunMeta.delete(runId));
3748
+ }
3749
+ });
3750
+ return mapRun(await readRunRow(pool2, runId));
3751
+ }
3752
+ async function cancelAssistantRun(pool2, runId, publish) {
3753
+ await transaction(pool2, async (client) => {
3754
+ const current = await readRunRow(client, runId);
3755
+ if (["succeeded", "failed", "cancelled"].includes(current.status)) {
3756
+ activeRunMeta.delete(runId);
3757
+ return;
3758
+ }
3759
+ await client.query(
3760
+ `UPDATE project_assistant_runs
3761
+ SET status = 'cancelled',
3762
+ activity_text = '\u5DF2\u53D6\u6D88',
3763
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
3764
+ WHERE id = $1`,
3765
+ [runId]
3766
+ );
3767
+ client.afterCommit(() => activeRunMeta.delete(runId));
3768
+ if (current.status === "running") {
3769
+ notifyAfterCommit(client, publish, {
3770
+ type: "command",
3771
+ command: "stop-assistant-run",
3772
+ agentId: current.agent_id,
3773
+ runId
3774
+ });
3775
+ }
3776
+ notifyAfterCommit(client, publish, {
3777
+ type: "board_updated",
3778
+ projectId: current.project_id,
3779
+ reason: "assistant_run_cancelled"
3780
+ });
3781
+ });
3782
+ return mapRun(await readRunRow(pool2, runId));
3783
+ }
3784
+ async function applyAssistantProposals(pool2, actor, runId, actions, publish) {
3785
+ const run = mapRun(await readRunRow(pool2, runId));
3786
+ const seenIds = new Set(run.appliedActionIds);
3787
+ const pendingActions = [];
3788
+ for (const action of actions) {
3789
+ if (seenIds.has(action.id)) continue;
3790
+ seenIds.add(action.id);
3791
+ pendingActions.push(action);
3792
+ }
3793
+ if (pendingActions.length === 0) {
3794
+ return { appliedIds: [], createdCardIds: [], updatedCardIds: [], archivedCardIds: [] };
3795
+ }
3796
+ const referencedCardIds = /* @__PURE__ */ new Set();
3797
+ for (const action of pendingActions) {
3798
+ if (action.type === "update_card" || action.type === "archive_card") {
3799
+ referencedCardIds.add(action.cardId);
3800
+ } else if (action.type === "create_card" && action.draft.parentId) {
3801
+ referencedCardIds.add(action.draft.parentId);
3802
+ }
3803
+ }
3804
+ if (referencedCardIds.size > 0) {
3805
+ const ids = Array.from(referencedCardIds);
3806
+ const placeholders = ids.map((_, idx) => `$${idx + 1}`).join(", ");
3807
+ const rows = (await pool2.query(
3808
+ `SELECT id, project_id FROM cards WHERE id IN (${placeholders})`,
3809
+ ids
3810
+ )).rows;
3811
+ const cardProjects = new Map(rows.map((r) => [r.id, r.project_id]));
3812
+ for (const action of pendingActions) {
3813
+ if (action.type === "update_card" || action.type === "archive_card") {
3814
+ const projectId = cardProjects.get(action.cardId);
3815
+ if (!projectId) throw new HttpError(404, "\u63D0\u6848\u76EE\u6807\u5361\u7247\u4E0D\u5B58\u5728");
3816
+ if (projectId !== run.projectId) throw new HttpError(400, "\u63D0\u6848\u76EE\u6807\u5361\u7247\u4E0D\u5C5E\u4E8E\u5F53\u524D\u9879\u76EE");
3817
+ } else if (action.type === "create_card" && action.draft.parentId) {
3818
+ const projectId = cardProjects.get(action.draft.parentId);
3819
+ if (!projectId) throw new HttpError(404, "\u7236\u5361\u7247\u4E0D\u5B58\u5728");
3820
+ if (projectId !== run.projectId) throw new HttpError(400, "\u7236\u5361\u7247\u5FC5\u987B\u5C5E\u4E8E\u540C\u4E00\u9879\u76EE");
3821
+ }
3822
+ }
3823
+ }
3824
+ const createdCardIds = [];
3825
+ const updatedCardIds = [];
3826
+ const archivedCardIds = [];
3827
+ const appliedIds = [];
3828
+ try {
3829
+ for (const action of pendingActions) {
3830
+ if (action.type === "create_card") {
3831
+ const created = await createCard(
3832
+ pool2,
3833
+ actor,
3834
+ {
3835
+ projectId: run.projectId,
3836
+ parentId: action.draft.parentId ?? null,
3837
+ title: action.draft.title,
3838
+ body: action.draft.body,
3839
+ status: action.draft.status,
3840
+ priority: action.draft.priority,
3841
+ tags: action.draft.tags,
3842
+ checklist: action.draft.checklist.map((text, idx) => ({
3843
+ id: `c-${idx + 1}-${randomUUID7().slice(0, 6)}`,
3844
+ text,
3845
+ done: false
3846
+ })),
3847
+ mentions: action.mentions,
3848
+ attachmentIds: [],
3849
+ skipDefaultAgent: action.skipDefaultAgent
3850
+ },
3851
+ publish
3852
+ );
3853
+ createdCardIds.push(created.id);
3854
+ appliedIds.push(action.id);
3855
+ } else if (action.type === "update_card") {
3856
+ const { status, ...rest } = action.patch;
3857
+ if (rest.title !== void 0 || rest.priority !== void 0 || rest.tags !== void 0) {
3858
+ await updateCard(
3859
+ pool2,
3860
+ actor,
3861
+ action.cardId,
3862
+ {
3863
+ ...rest,
3864
+ summary: action.summary
3865
+ },
3866
+ publish
3867
+ );
3868
+ }
3869
+ if (status !== void 0) {
3870
+ await changeCardStatus(pool2, actor, action.cardId, { status, note: action.summary }, publish);
3871
+ }
3872
+ updatedCardIds.push(action.cardId);
3873
+ appliedIds.push(action.id);
3874
+ } else if (action.type === "archive_card") {
3875
+ await archiveCard(pool2, action.cardId, true, publish);
3876
+ archivedCardIds.push(action.cardId);
3877
+ appliedIds.push(action.id);
3878
+ }
3879
+ }
3880
+ } finally {
3881
+ if (appliedIds.length > 0) {
3882
+ await transaction(pool2, async (client) => {
3883
+ const latest = await readRunRow(client, runId);
3884
+ const existingIds = JSON.parse(latest.applied_action_ids || "[]");
3885
+ const mergedApplied = Array.from(/* @__PURE__ */ new Set([...existingIds, ...appliedIds]));
3886
+ await client.query(
3887
+ `UPDATE project_assistant_runs
3888
+ SET applied_action_ids = $2,
3889
+ updated_at = strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')
3890
+ WHERE id = $1`,
3891
+ [runId, JSON.stringify(mergedApplied)]
3892
+ );
3893
+ notifyAfterCommit(client, publish, {
3894
+ type: "board_updated",
3895
+ projectId: run.projectId,
3896
+ reason: "assistant_proposals_applied"
3897
+ });
3898
+ });
3899
+ }
3900
+ }
3901
+ return { appliedIds, createdCardIds, updatedCardIds, archivedCardIds };
3902
+ }
3903
+
3904
+ // src/http/routes.ts
3905
+ var uuid = z2.string().uuid();
3906
+ var idParam = (req, key = "id") => uuid.parse(req.params[key]);
3907
+ var eventQuery = z2.object({
3908
+ cursor: z2.string().regex(/^(0|[1-9][0-9]{0,18})$/).default("0"),
3909
+ limit: z2.coerce.number().int().min(1).max(200).default(100),
3910
+ projectId: uuid.optional(),
3911
+ cardId: uuid.optional()
3912
+ }).strict();
3913
+ var optionalQueryBoolean = z2.preprocess((value) => {
3914
+ if (value === void 0 || typeof value === "boolean") return value;
3915
+ if (typeof value === "string") {
3916
+ const normalized = value.trim().toLowerCase();
3917
+ if (normalized === "true" || normalized === "1") return true;
3918
+ if (normalized === "false" || normalized === "0") return false;
3919
+ }
3920
+ return value;
3921
+ }, z2.boolean().optional());
3922
+ var cardListQuery = z2.object({
3923
+ projectId: uuid.optional(),
3924
+ status: cardStatusSchema.optional(),
3925
+ search: z2.string().max(200).optional(),
3926
+ tag: z2.string().max(40).optional(),
3927
+ agentId: uuid.optional(),
3928
+ parentId: uuid.optional(),
3929
+ includeArchived: optionalQueryBoolean
3930
+ }).strict();
3931
+ var cardDetailQuery = z2.object({
3932
+ includeRevisions: optionalQueryBoolean,
3933
+ eventLimit: z2.coerce.number().int().min(1).max(200).optional()
3934
+ }).strict();
3935
+ function requireHuman(req, action) {
3936
+ if (req.actor.kind !== "human") throw new HttpError(403, `\u4EC5\u672C\u673A\u64CD\u4F5C\u8005\u53EF\u4EE5${action}`);
3937
+ }
3938
+ function requireAgent(req) {
3939
+ if (!req.agent || req.actor.kind !== "agent") throw new HttpError(403, "\u9700\u8981\u6709\u6548\u7684 Agent \u51ED\u636E");
3940
+ return { agent: req.agent, actor: req.actor };
3941
+ }
3942
+ function mapProject(row) {
3943
+ return {
3944
+ id: row.id,
3945
+ name: row.name,
3946
+ description: row.description,
3947
+ rootPath: row.root_path,
3948
+ defaultAgentId: row.default_agent_id,
3949
+ parallelMode: row.parallel_mode,
3950
+ createdAt: new Date(row.created_at).toISOString()
3951
+ };
3952
+ }
3953
+ var attachmentUploadQuery = z2.object({
3954
+ projectId: uuid,
3955
+ cardId: uuid.optional(),
3956
+ imagesOnly: optionalQueryBoolean,
3957
+ filename: z2.string().trim().min(1).max(255),
3958
+ mimeType: z2.string().trim().max(128).optional()
3959
+ }).strict();
3960
+ var attachmentContentQuery = z2.object({
3961
+ download: optionalQueryBoolean
3962
+ }).strict();
3963
+ function registerRoutes(app2, pool2, streams, options) {
3964
+ const revealFile = options.revealFile ?? revealLocalFile;
3965
+ app2.get("/v1/projects", async (request) => {
3966
+ const projectId = request.agent?.projectId ?? null;
3967
+ const { rows } = await pool2.query(
3968
+ `SELECT id, name, description, root_path, default_agent_id, parallel_mode, created_at
3969
+ FROM projects WHERE ($1 IS NULL OR id = $1) ORDER BY created_at ASC, id ASC`,
3970
+ [projectId]
3971
+ );
3972
+ return rows.map(mapProject);
3973
+ });
3974
+ app2.post("/v1/projects", async (request, reply) => {
3975
+ requireHuman(request, "\u521B\u5EFA\u9879\u76EE");
3976
+ const data = projectCreateSchema.parse(request.body);
3977
+ const id = randomUUID8();
3978
+ const project = await transaction(pool2, async (client) => {
3979
+ if (data.defaultAgentId) {
3980
+ const ag = (await client.query("SELECT project_id FROM agents WHERE id = $1", [
3981
+ data.defaultAgentId
3982
+ ])).rows[0];
3983
+ if (!ag) throw new HttpError(400, "\u9ED8\u8BA4\u4E3B Agent \u4E0D\u5B58\u5728");
3984
+ if (ag.project_id) throw new HttpError(400, "\u8BE5 Agent \u5DF2\u7ED1\u5B9A\u5176\u4ED6\u9879\u76EE");
3985
+ }
3986
+ const row = (await client.query(
3987
+ `INSERT INTO projects(id, name, description, root_path, default_agent_id, parallel_mode)
3988
+ VALUES($1, $2, $3, $4, $5, $6)
3989
+ RETURNING id, name, description, root_path, default_agent_id, parallel_mode, created_at`,
3990
+ [id, data.name, data.description, data.rootPath, data.defaultAgentId ?? null, data.parallelMode]
3991
+ )).rows[0];
3992
+ notifyAfterCommit(client, streams.publish, { type: "board_updated", projectId: id, reason: "project_created" });
3993
+ return mapProject(row);
3994
+ });
3995
+ return reply.code(201).send(project);
3996
+ });
3997
+ app2.get("/v1/projects/:id", async (request) => {
3998
+ const id = idParam(request);
3999
+ if (request.agent?.projectId && request.agent.projectId !== id) throw new HttpError(403, "\u8BE5 Agent \u65E0\u6743\u8BBF\u95EE\u6B64\u9879\u76EE");
4000
+ const row = (await pool2.query(
4001
+ `SELECT id, name, description, root_path, default_agent_id, parallel_mode, created_at
4002
+ FROM projects WHERE id = $1`,
4003
+ [id]
4004
+ )).rows[0];
4005
+ if (!row) throw new HttpError(404, "\u9879\u76EE\u4E0D\u5B58\u5728");
4006
+ return mapProject(row);
4007
+ });
4008
+ app2.patch("/v1/projects/:id", async (request) => {
4009
+ requireHuman(request, "\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");
4010
+ const id = idParam(request);
4011
+ const data = projectUpdateSchema.parse(request.body);
4012
+ return transaction(pool2, async (client) => {
4013
+ const existing = await client.query("SELECT 1 FROM projects WHERE id = $1", [id]);
4014
+ if (!existing.rowCount) throw new HttpError(404, "\u9879\u76EE\u4E0D\u5B58\u5728");
4015
+ if (data.defaultAgentId) {
4016
+ const ag = (await client.query("SELECT project_id FROM agents WHERE id = $1", [
4017
+ data.defaultAgentId
4018
+ ])).rows[0];
4019
+ if (!ag) throw new HttpError(400, "\u9ED8\u8BA4\u4E3B Agent \u4E0D\u5B58\u5728");
4020
+ if (ag.project_id && ag.project_id !== id) throw new HttpError(400, "\u8BE5 Agent \u4E0D\u5C5E\u4E8E\u6B64\u9879\u76EE");
4021
+ }
4022
+ const row = (await client.query(
4023
+ `UPDATE projects SET
4024
+ name = COALESCE($2, name),
4025
+ description = COALESCE($3, description),
4026
+ root_path = COALESCE($4, root_path),
4027
+ default_agent_id = CASE WHEN $5 = 1 THEN $6 ELSE default_agent_id END,
4028
+ parallel_mode = COALESCE($7, parallel_mode)
4029
+ WHERE id = $1
4030
+ RETURNING id, name, description, root_path, default_agent_id, parallel_mode, created_at`,
4031
+ [
4032
+ id,
4033
+ data.name ?? null,
4034
+ data.description ?? null,
4035
+ data.rootPath ?? null,
4036
+ data.defaultAgentId !== void 0 ? 1 : 0,
4037
+ data.defaultAgentId ?? null,
4038
+ data.parallelMode ?? null
4039
+ ]
4040
+ )).rows[0];
4041
+ notifyAfterCommit(client, streams.publish, { type: "board_updated", projectId: id, reason: "project_updated" });
4042
+ return mapProject(row);
4043
+ });
4044
+ });
4045
+ app2.delete("/v1/projects/:id", async (request) => {
4046
+ requireHuman(request, "\u5220\u9664\u9879\u76EE");
4047
+ const id = idParam(request);
4048
+ let attachmentPaths = [];
4049
+ await transaction(pool2, async (client) => {
4050
+ const existing = await client.query("SELECT 1 FROM projects WHERE id = $1", [id]);
4051
+ if (!existing.rowCount) throw new HttpError(404, "\u9879\u76EE\u4E0D\u5B58\u5728");
4052
+ const count = (await client.query("SELECT COUNT(*) AS c FROM projects")).rows[0].c;
4053
+ if (count <= 1) throw new HttpError(422, "\u81F3\u5C11\u9700\u8981\u4FDD\u7559\u4E00\u4E2A\u9879\u76EE");
4054
+ attachmentPaths = await collectStoragePathsForProject(client, id);
4055
+ await client.query("DELETE FROM projects WHERE id = $1", [id]);
4056
+ notifyAfterCommit(client, streams.publish, { type: "board_updated", reason: "project_deleted" });
4057
+ });
4058
+ if (attachmentPaths.length > 0) {
4059
+ await unlinkStoragePaths(options.uploadsRoot, attachmentPaths);
4060
+ }
4061
+ return { ok: true };
4062
+ });
4063
+ app2.register(async (uploadScope) => {
4064
+ uploadScope.removeAllContentTypeParsers();
4065
+ uploadScope.addContentTypeParser("*", (_request, payload, done) => {
4066
+ done(null, payload);
4067
+ });
4068
+ uploadScope.post("/v1/attachments", async (request, reply) => {
4069
+ const query = attachmentUploadQuery.parse(request.query);
4070
+ const rawLength = request.headers["content-length"];
4071
+ const parsedLength = typeof rawLength === "string" && /^\d+$/.test(rawLength) ? Number(rawLength) : void 0;
4072
+ const mimeFromHeader = typeof request.headers["content-type"] === "string" ? request.headers["content-type"] : void 0;
4073
+ const attachment = await uploadAttachment(
4074
+ pool2,
4075
+ request.actor,
4076
+ {
4077
+ projectId: query.projectId,
4078
+ cardId: query.cardId,
4079
+ imagesOnly: query.imagesOnly === true,
4080
+ filename: query.filename,
4081
+ mimeType: query.mimeType ?? mimeFromHeader,
4082
+ contentLength: parsedLength,
4083
+ stream: request.body
4084
+ },
4085
+ options.uploadsRoot,
4086
+ streams.publish
4087
+ );
4088
+ return reply.code(201).send(attachment);
4089
+ });
4090
+ });
4091
+ app2.post("/v1/attachments/clone", async (request, reply) => {
4092
+ requireHuman(request, "\u590D\u5236\u9644\u4EF6");
4093
+ const data = attachmentCloneSchema.parse(request.body);
4094
+ const attachments = await cloneAttachments(pool2, request.actor, data, options.uploadsRoot);
4095
+ return reply.code(201).send({ attachments });
4096
+ });
4097
+ app2.get("/v1/attachments/:id/preview", async (request) => {
4098
+ return previewAttachmentText(pool2, request.actor, idParam(request), options.uploadsRoot);
4099
+ });
4100
+ app2.post("/v1/attachments/:id/reveal", async (request) => {
4101
+ requireHuman(request, "\u5728\u8BBF\u8FBE\u4E2D\u663E\u793A\u6587\u4EF6");
4102
+ const localPath = await getAttachmentLocalPath(pool2, request.actor, idParam(request), options.uploadsRoot);
4103
+ await revealFile(localPath);
4104
+ return { ok: true, localPath };
4105
+ });
4106
+ app2.get("/v1/attachments/:id/content", async (request, reply) => {
4107
+ const query = attachmentContentQuery.parse(request.query);
4108
+ const content = await getAttachmentContent(pool2, request.actor, idParam(request), options.uploadsRoot, {
4109
+ forceDownload: query.download === true
4110
+ });
4111
+ return reply.header("content-type", content.contentType).header("content-length", String(content.sizeBytes)).header("content-disposition", content.contentDisposition).header("x-content-type-options", "nosniff").header("content-security-policy", "default-src 'none'; sandbox").header("cache-control", "private, max-age=3600").send(createReadStream(content.filePath));
4112
+ });
4113
+ app2.delete("/v1/attachments/:id", async (request) => {
4114
+ requireHuman(request, "\u5220\u9664\u9644\u4EF6");
4115
+ return deleteAttachment(pool2, idParam(request), options.uploadsRoot, streams.publish);
4116
+ });
4117
+ app2.get("/v1/cards", async (request) => {
4118
+ const query = cardListQuery.parse(request.query);
4119
+ return listCards(pool2, request.actor, query);
4120
+ });
4121
+ app2.post("/v1/cards", async (request, reply) => {
4122
+ const data = cardCreateSchema.parse(request.body);
4123
+ return reply.code(201).send(await createCard(pool2, request.actor, data, streams.publish, options.uploadsRoot));
4124
+ });
4125
+ app2.get("/v1/cards/:id", async (request) => {
4126
+ const query = cardDetailQuery.parse(request.query);
4127
+ return getCardDetail(pool2, request.actor, idParam(request), options.uploadsRoot, query);
4128
+ });
4129
+ app2.patch("/v1/cards/:id", async (request) => {
4130
+ const data = cardUpdateSchema.parse(request.body);
4131
+ return updateCard(pool2, request.actor, idParam(request), data, streams.publish, options.uploadsRoot);
4132
+ });
4133
+ app2.post("/v1/cards/:id/status", async (request) => {
4134
+ const data = cardStatusChangeSchema.parse(request.body);
4135
+ return changeCardStatus(pool2, request.actor, idParam(request), data, streams.publish);
4136
+ });
4137
+ app2.post("/v1/cards/:id/comments", async (request, reply) => {
4138
+ const data = commentCreateSchema.parse(request.body);
4139
+ return reply.code(201).send(await addComment(pool2, request.actor, idParam(request), data, streams.publish, options.uploadsRoot));
4140
+ });
4141
+ app2.post("/v1/cards/:id/outputs", async (request, reply) => {
4142
+ const data = cardOutputInputSchema.parse(request.body);
4143
+ return reply.code(201).send(await addCardOutput(pool2, request.actor, idParam(request), data, streams.publish, options.uploadsRoot));
4144
+ });
4145
+ app2.post("/v1/cards/:id/decisions", async (request, reply) => {
4146
+ const { actor } = requireAgent(request);
4147
+ const data = cardDecisionCreateSchema.parse(request.body);
4148
+ return reply.code(201).send(await createCardDecision(pool2, actor, idParam(request), data, streams.publish));
4149
+ });
4150
+ app2.post("/v1/cards/:id/decisions/:decisionId/resolve", async (request) => {
4151
+ requireHuman(request, "\u786E\u8BA4\u51B3\u7B56");
4152
+ const data = cardDecisionResolveSchema.parse(request.body);
4153
+ return resolveCardDecision(
4154
+ pool2,
4155
+ request.actor,
4156
+ idParam(request),
4157
+ idParam(request, "decisionId"),
4158
+ data,
4159
+ streams.publish
4160
+ );
4161
+ });
4162
+ app2.post("/v1/cards/:id/decisions/:decisionId/dismiss", async (request) => {
4163
+ requireHuman(request, "\u5FFD\u7565\u5F85\u786E\u8BA4\u9879");
4164
+ return dismissCardDecision(pool2, idParam(request), idParam(request, "decisionId"), streams.publish);
4165
+ });
4166
+ app2.get("/v1/cards/:id/outputs/:outputId/preview", async (request) => {
4167
+ return previewOutputFile(
4168
+ pool2,
4169
+ request.actor,
4170
+ idParam(request),
4171
+ idParam(request, "outputId"),
4172
+ options.sandboxRoot,
4173
+ options.uploadsRoot
4174
+ );
4175
+ });
4176
+ app2.post("/v1/cards/:id/outputs/:outputId/reveal", async (request) => {
4177
+ requireHuman(request, "\u5728\u8BBF\u8FBE\u4E2D\u663E\u793A\u4EA7\u51FA\u6587\u4EF6");
4178
+ const localPath = await getOutputLocalPath(
4179
+ pool2,
4180
+ request.actor,
4181
+ idParam(request),
4182
+ idParam(request, "outputId"),
4183
+ options.sandboxRoot,
4184
+ options.uploadsRoot
4185
+ );
4186
+ await revealFile(localPath);
4187
+ return { ok: true, localPath };
4188
+ });
4189
+ app2.post("/v1/cards/:id/archive", async (request) => {
4190
+ requireHuman(request, "\u5F52\u6863\u5361\u7247");
4191
+ const body = z2.object({ archived: z2.boolean().default(true) }).strict().parse(request.body ?? {});
4192
+ return archiveCard(pool2, idParam(request), body.archived, streams.publish);
4193
+ });
4194
+ app2.delete("/v1/cards/:id", async (request) => {
4195
+ requireHuman(request, "\u5220\u9664\u5361\u7247");
4196
+ return deleteCard(pool2, idParam(request), streams.publish, options.uploadsRoot);
4197
+ });
4198
+ app2.post("/v1/cards/:id/agents/:agentId/stop", async (request, reply) => {
4199
+ requireHuman(request, "\u505C\u6B62 Agent");
4200
+ return reply.code(201).send(await stopCardAgent(pool2, request.actor, idParam(request), idParam(request, "agentId"), streams.publish));
4201
+ });
4202
+ app2.post("/v1/cards/:id/processing", async (request) => {
4203
+ const { actor } = requireAgent(request);
4204
+ const data = processingReportSchema.parse(request.body ?? {});
4205
+ return reportProcessing(pool2, actor, idParam(request), data, streams.publish);
4206
+ });
4207
+ app2.post("/v1/cards/:id/processing/clear", async (request) => {
4208
+ const { actor } = requireAgent(request);
4209
+ const data = processingClearSchema.parse(request.body ?? {});
4210
+ return clearProcessing(pool2, actor, idParam(request), data, streams.publish);
4211
+ });
4212
+ app2.get("/v1/cards/:id/runs", async (request) => {
4213
+ const query = z2.object({ limit: z2.coerce.number().int().min(1).max(50).default(15) }).strict().parse(request.query);
4214
+ return listCardRuns(pool2, request.actor, idParam(request), query.limit);
4215
+ });
4216
+ app2.post("/v1/cards/:id/runs/steps", async (request) => {
4217
+ const { actor } = requireAgent(request);
4218
+ const data = cardRunStepsAppendSchema.parse(request.body ?? {});
4219
+ return appendCardRunSteps(pool2, actor, idParam(request), data, streams.publish);
4220
+ });
4221
+ app2.get("/v1/events", async (request) => {
4222
+ const query = eventQuery.parse(request.query);
4223
+ return listEvents(pool2, request.actor, query, options.uploadsRoot);
4224
+ });
4225
+ app2.get("/v1/events/stream", async (request, reply) => {
4226
+ const { projectId } = z2.object({ projectId: uuid.optional() }).strict().parse(request.query);
4227
+ const effectiveProject = projectId ?? request.agent?.projectId ?? void 0;
4228
+ if (request.agent?.projectId && effectiveProject && request.agent.projectId !== effectiveProject) {
4229
+ throw new HttpError(403, "\u8BE5 Agent \u65E0\u6743\u8BA2\u9605\u6B64\u9879\u76EE\u4E8B\u4EF6\u6D41");
4230
+ }
4231
+ reply.hijack();
4232
+ reply.raw.writeHead(200, {
4233
+ "content-type": "text/event-stream; charset=utf-8",
4234
+ "cache-control": "no-store",
4235
+ "x-content-type-options": "nosniff",
4236
+ "x-accel-buffering": "no"
4237
+ });
4238
+ if (!streams.subscribe(reply.raw, { projectId: effectiveProject, agentId: request.agent?.id })) {
4239
+ reply.raw.end();
4240
+ }
4241
+ });
4242
+ app2.get("/v1/agents", async (request) => {
4243
+ const { projectId } = z2.object({ projectId: uuid.optional() }).strict().parse(request.query);
4244
+ const effectiveProjectId = projectId ?? request.agent?.projectId ?? void 0;
4245
+ if (request.agent?.projectId && effectiveProjectId !== request.agent.projectId) {
4246
+ throw new HttpError(403, "\u8BE5 Agent \u65E0\u6743\u8BBF\u95EE\u6B64\u9879\u76EE");
4247
+ }
4248
+ return { agents: await listAgents(pool2, effectiveProjectId) };
4249
+ });
4250
+ app2.get("/v1/agents/me", async (request) => {
4251
+ const { agent } = requireAgent(request);
4252
+ return agent;
4253
+ });
4254
+ app2.post("/v1/agents", async (request, reply) => {
4255
+ requireHuman(request, "\u6CE8\u518C Agent");
4256
+ const data = agentRegisterSchema.parse(request.body);
4257
+ return reply.code(201).send(await registerAgent(pool2, data, streams.publish));
4258
+ });
4259
+ app2.patch("/v1/agents/:id", async (request) => {
4260
+ requireHuman(request, "\u66F4\u65B0 Agent \u8BBE\u7F6E");
4261
+ const data = agentUpdateSchema.parse(request.body);
4262
+ return updateAgent(pool2, idParam(request), data, streams.publish);
4263
+ });
4264
+ app2.delete("/v1/agents/:id", async (request) => {
4265
+ requireHuman(request, "\u5220\u9664 Agent");
4266
+ return deleteAgent(pool2, idParam(request), streams.publish);
4267
+ });
4268
+ app2.post("/v1/agents/presence", async (request) => {
4269
+ const { agent } = requireAgent(request);
4270
+ const data = agentPresenceReportSchema.parse(request.body);
4271
+ return reportPresence(pool2, agent, data, streams.publish);
4272
+ });
4273
+ app2.post("/v1/agents/:id/login", async (request, reply) => {
4274
+ requireHuman(request, "\u53D1\u8D77\u8BBE\u5907\u767B\u5F55");
4275
+ const res = await requestAgentLogin(pool2, idParam(request), streams.publish);
4276
+ return reply.code(res.created ? 201 : 200).send(res.request);
4277
+ });
4278
+ app2.post("/v1/agents/:id/login/:requestId/cancel", async (request) => {
4279
+ requireHuman(request, "\u53D6\u6D88\u8BBE\u5907\u767B\u5F55");
4280
+ return cancelAgentLogin(pool2, idParam(request), idParam(request, "requestId"), streams.publish);
4281
+ });
4282
+ app2.post("/v1/agents/login/:requestId/progress", async (request) => {
4283
+ const { agent } = requireAgent(request);
4284
+ const data = agentLoginProgressSchema.parse(request.body);
4285
+ return reportLoginProgress(pool2, agent, idParam(request, "requestId"), data, streams.publish);
4286
+ });
4287
+ app2.get("/v1/assistant/runs", async (request) => {
4288
+ requireHuman(request, "\u67E5\u770B\u9879\u76EE\u52A9\u624B\u8BB0\u5F55");
4289
+ const query = z2.object({
4290
+ projectId: uuid,
4291
+ kind: assistantRunKindSchema.optional(),
4292
+ threadId: uuid.optional(),
4293
+ limit: z2.coerce.number().int().min(1).max(100).optional()
4294
+ }).strict().parse(request.query);
4295
+ return { runs: await listAssistantRuns(pool2, query) };
4296
+ });
4297
+ app2.post("/v1/assistant/runs", async (request, reply) => {
4298
+ requireHuman(request, "\u53D1\u8D77\u9879\u76EE\u52A9\u624B\u4EFB\u52A1");
4299
+ const data = assistantRunCreateSchema.parse(request.body);
4300
+ return reply.code(201).send(await createAssistantRun(pool2, data, streams.publish));
4301
+ });
4302
+ app2.get("/v1/assistant/runs/:id", async (request) => {
4303
+ requireHuman(request, "\u67E5\u770B\u52A9\u624B\u4EFB\u52A1\u8BE6\u60C5");
4304
+ return getAssistantRun(pool2, idParam(request));
4305
+ });
4306
+ app2.post("/v1/assistant/runs/:id/cancel", async (request) => {
4307
+ requireHuman(request, "\u53D6\u6D88\u52A9\u624B\u4EFB\u52A1");
4308
+ return cancelAssistantRun(pool2, idParam(request), streams.publish);
4309
+ });
4310
+ app2.post("/v1/assistant/runs/:id/apply", async (request) => {
4311
+ requireHuman(request, "\u6267\u884C\u52A9\u624B\u63D0\u6848");
4312
+ const data = assistantProposalApplySchema.parse(request.body);
4313
+ return applyAssistantProposals(pool2, request.actor, idParam(request), data.actions, streams.publish);
4314
+ });
4315
+ app2.post("/v1/agents/assistant-runs/claim", async (request) => {
4316
+ const { agent } = requireAgent(request);
4317
+ const claimed = await claimNextAssistantRun(pool2, agent, streams.publish, options.uploadsRoot);
4318
+ return { claimed };
4319
+ });
4320
+ app2.post("/v1/agents/assistant-runs/:id/progress", async (request) => {
4321
+ const { agent } = requireAgent(request);
4322
+ const data = assistantRunProgressSchema.parse(request.body);
4323
+ return reportAssistantRunProgress(pool2, agent, idParam(request), data, streams.publish);
4324
+ });
4325
+ app2.post("/v1/agents/assistant-runs/:id/stream", async (request) => {
4326
+ const { agent } = requireAgent(request);
4327
+ const data = assistantRunStreamSchema.parse(request.body);
4328
+ return streamAssistantRunDelta(pool2, agent, idParam(request), data, streams.publish);
4329
+ });
4330
+ }
4331
+
4332
+ // src/http/static-web.ts
4333
+ import { createReadStream as createReadStream2, existsSync, statSync as statSync2 } from "fs";
4334
+ import { extname, resolve as resolve2, sep } from "path";
4335
+ var MIME_TYPES = {
4336
+ ".html": "text/html; charset=utf-8",
4337
+ ".js": "text/javascript; charset=utf-8",
4338
+ ".mjs": "text/javascript; charset=utf-8",
4339
+ ".css": "text/css; charset=utf-8",
4340
+ ".json": "application/json; charset=utf-8",
4341
+ ".svg": "image/svg+xml",
4342
+ ".png": "image/png",
4343
+ ".jpg": "image/jpeg",
4344
+ ".jpeg": "image/jpeg",
4345
+ ".webp": "image/webp",
4346
+ ".gif": "image/gif",
4347
+ ".ico": "image/x-icon",
4348
+ ".woff2": "font/woff2",
4349
+ ".woff": "font/woff",
4350
+ ".ttf": "font/ttf",
4351
+ ".txt": "text/plain; charset=utf-8"
4352
+ };
4353
+ function resolveStaticFile(webRoot, rawPathname) {
4354
+ let pathname;
4355
+ try {
4356
+ pathname = decodeURIComponent(rawPathname);
4357
+ } catch {
4358
+ return null;
4359
+ }
4360
+ const rel = pathname.replace(/^\/+/, "");
4361
+ const candidate = resolve2(webRoot, rel || "index.html");
4362
+ const rootPrefix = webRoot.endsWith(sep) ? webRoot : `${webRoot}${sep}`;
4363
+ if (candidate !== webRoot && !candidate.startsWith(rootPrefix)) return null;
4364
+ if (existsSync(candidate) && statSync2(candidate).isFile()) return candidate;
4365
+ return null;
4366
+ }
4367
+ function registerStaticWeb(app2, webDistDir2) {
4368
+ const webRoot = resolve2(webDistDir2);
4369
+ const indexHtml = resolve2(webRoot, "index.html");
4370
+ if (!existsSync(indexHtml)) return;
4371
+ app2.setNotFoundHandler((request, reply) => {
4372
+ const pathname = request.url.split("?")[0] ?? "/";
4373
+ if (pathname === "/health" || pathname === "/v1" || pathname.startsWith("/v1/")) {
4374
+ return reply.code(404).send({ message: "\u672A\u627E\u5230\u63A5\u53E3" });
4375
+ }
4376
+ if (request.method !== "GET" && request.method !== "HEAD") {
4377
+ return reply.code(404).send({ message: "\u672A\u627E\u5230\u9875\u9762" });
4378
+ }
4379
+ const filePath = resolveStaticFile(webRoot, pathname);
4380
+ const target = filePath ?? (extname(pathname) ? null : indexHtml);
4381
+ if (!target) {
4382
+ return reply.code(404).send({ message: "\u672A\u627E\u5230\u9759\u6001\u8D44\u6E90" });
4383
+ }
4384
+ const ext = extname(target).toLowerCase();
4385
+ reply.header("content-type", MIME_TYPES[ext] ?? "application/octet-stream");
4386
+ if (pathname.startsWith("/assets/")) {
4387
+ reply.header("cache-control", "public, max-age=31536000, immutable");
4388
+ } else if (target === indexHtml) {
4389
+ reply.header("cache-control", "no-cache");
4390
+ }
4391
+ if (request.method === "HEAD") {
4392
+ return reply.code(200).send();
4393
+ }
4394
+ return reply.send(createReadStream2(target));
4395
+ });
4396
+ }
4397
+
4398
+ // src/app.ts
4399
+ async function createApp(options) {
4400
+ const app2 = Fastify({
4401
+ logger: options.logger ? { level: "warn", redact: ["req.headers.authorization"] } : false,
4402
+ bodyLimit: 256 * 1024
4403
+ });
4404
+ app2.setErrorHandler((error, request, reply) => {
4405
+ if (error instanceof ZodError) return reply.code(400).send({ message: "\u8BF7\u6C42\u53C2\u6570\u4E0D\u5408\u6CD5", issues: error.issues });
4406
+ if (error instanceof HttpError)
4407
+ return reply.code(error.statusCode).send({ message: error.message, ...error.details });
4408
+ if (error instanceof Error && "statusCode" in error && typeof error.statusCode === "number" && error.statusCode < 500) {
4409
+ return reply.code(error.statusCode).send({ message: error.message });
4410
+ }
4411
+ if (request.routeOptions.url?.includes("/login") || request.routeOptions.url?.includes("/presence")) {
4412
+ app2.log.error("Agent \u72B6\u6001\u6216\u767B\u5F55\u8BF7\u6C42\u5931\u8D25");
4413
+ } else {
4414
+ app2.log.error({ err: error }, "\u8BF7\u6C42\u5931\u8D25");
4415
+ }
4416
+ return reply.code(500).send({ message: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" });
4417
+ });
4418
+ await registerAuthContext(app2, options.pool, options.webOrigin ?? config.webOrigin);
4419
+ const streams = new BoardEventStreams();
4420
+ app2.addHook("preClose", async () => streams.close());
4421
+ registerRoutes(app2, options.pool, streams, {
4422
+ sandboxRoot: options.sandboxRoot ?? config.sandboxRoot,
4423
+ uploadsRoot: options.uploadsRoot ?? config.uploadsDir,
4424
+ ...options.revealFile ? { revealFile: options.revealFile } : {}
4425
+ });
4426
+ app2.get("/health", async () => {
4427
+ await options.pool.query("SELECT 1");
4428
+ return { ok: true, version: "v2" };
4429
+ });
4430
+ const webDistDir2 = options.webDistDir !== void 0 ? options.webDistDir : config.webDistDir;
4431
+ if (webDistDir2) {
4432
+ registerStaticWeb(app2, webDistDir2);
4433
+ }
4434
+ return app2;
4435
+ }
4436
+
4437
+ // src/db/seed.ts
4438
+ import { randomUUID as randomUUID9 } from "crypto";
4439
+ import { pathToFileURL as pathToFileURL2 } from "url";
4440
+
4441
+ // src/db/migrate.ts
4442
+ import { readFile } from "fs/promises";
4443
+ import { pathToFileURL } from "url";
4444
+ var migrationNames = [
4445
+ "001_initial",
4446
+ "002_project_assistant",
4447
+ "003_card_decisions",
4448
+ "004_card_default_agent",
4449
+ "005_card_attachments",
4450
+ "006_comment_attachments",
4451
+ "007_participant_last_outcome",
4452
+ "008_output_attachments",
4453
+ "009_card_agent_runs"
4454
+ ];
4455
+ async function migrate(pool2) {
4456
+ const migrations = await Promise.all(
4457
+ migrationNames.map(
4458
+ async (name) => [name, await readFile(new URL(`./${name}.sql`, import.meta.url), "utf8")]
4459
+ )
4460
+ );
4461
+ await transaction(pool2, async (client) => {
4462
+ client.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
4463
+ name TEXT PRIMARY KEY,
4464
+ applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%f000Z', 'now'))
4465
+ ) STRICT`);
4466
+ await client.query(
4467
+ `UPDATE schema_migrations SET name = '001_initial' WHERE name = '001_v2_initial' AND NOT EXISTS (SELECT 1 FROM schema_migrations WHERE name = '001_initial')`
4468
+ );
4469
+ for (const [name, sql] of migrations) {
4470
+ if ((await client.query("SELECT 1 FROM schema_migrations WHERE name=$1", [name])).rowCount) continue;
4471
+ client.exec(sql);
4472
+ await client.query("INSERT INTO schema_migrations(name) VALUES($1)", [name]);
4473
+ }
4474
+ });
4475
+ }
4476
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
4477
+ const pool2 = createPool(config.databasePath);
4478
+ try {
4479
+ await migrate(pool2);
4480
+ console.log("SQLite V2 \u6570\u636E\u5E93\u8FC1\u79FB\u5B8C\u6210");
4481
+ } finally {
4482
+ await pool2.end();
4483
+ }
4484
+ }
4485
+
4486
+ // src/db/seed.ts
4487
+ async function seed(pool2) {
4488
+ await migrate(pool2);
4489
+ await transaction(pool2, async (client) => {
4490
+ const existing = await client.query("SELECT id FROM projects LIMIT 1");
4491
+ if (existing.rowCount > 0) return;
4492
+ const projectId = randomUUID9();
4493
+ await client.query(
4494
+ `INSERT INTO projects(id, name, description, root_path, parallel_mode) VALUES($1, $2, $3, $4, 'auto')`,
4495
+ [projectId, "\u9ED8\u8BA4\u9879\u76EE", "\u672C\u673A\u4EBA\u673A\u534F\u540C\u770B\u677F\u9ED8\u8BA4\u9879\u76EE\uFF0C\u53EF\u5728\u9879\u76EE\u8BBE\u7F6E\u4E2D\u7ED1\u5B9A\u771F\u5B9E\u5DE5\u4F5C\u76EE\u5F55\u4E0E\u9ED8\u8BA4\u4E3B Agent\u3002", ""]
4496
+ );
4497
+ const cardId = randomUUID9();
4498
+ await client.query(
4499
+ `INSERT INTO cards(id, project_id, title, body, status, priority, tags, checklist, outputs, position, created_by_kind, created_by_id, created_by_name)
4500
+ VALUES($1, $2, $3, $4, 'todo', 'medium', $5, $6, '[]', 0, 'human', 'local-user', '\u6211')`,
4501
+ [
4502
+ cardId,
4503
+ projectId,
4504
+ "\u6B22\u8FCE\u4F7F\u7528 Slate\uFF1A\u5728\u5361\u7247\u91CC\u76F4\u63A5 @Agent \u534F\u540C\u5E72\u6D3B",
4505
+ "\u4F60\u53EF\u4EE5\uFF1A\n1. \u5728\u5DE6\u4FA7\u9879\u76EE\u8BBE\u7F6E\u4E2D\u7ED1\u5B9A\u771F\u5B9E\u4EE3\u7801\u76EE\u5F55\u4E0E\u9ED8\u8BA4\u4E3B Agent\uFF1B\n2. \u76F4\u63A5\u62D6\u62FD\u5361\u7247\u6539\u72B6\u6001\uFF0C\u6216\u5728\u8FD9\u91CC\u884C\u5185\u7F16\u8F91 Markdown \u6B63\u6587\u4E0E\u6E05\u5355\uFF1B\n3. \u5728\u4E0B\u65B9\u8BC4\u8BBA\u533A\u8F93\u5165 `@Codex`\u3001`@Claude Code`\u3001`@Antigravity` \u5B9E\u73B0\u5355\u5361\u591A Agent \u771F\u5E76\u884C\uFF01",
4506
+ JSON.stringify(["\u5F15\u5BFC"]),
4507
+ JSON.stringify([
4508
+ { id: "chk-1", text: "\u914D\u7F6E\u9879\u76EE\u5DE5\u4F5C\u76EE\u5F55\uFF08\u53EF\u9009\uFF09", done: false },
4509
+ { id: "chk-2", text: "\u542F\u52A8\u81F3\u5C11\u4E00\u4E2A\u672C\u673A CLI Agent", done: false },
4510
+ { id: "chk-3", text: "\u5C1D\u8BD5\u5EFA\u5361\u5E76 @Agent \u534F\u540C\u7F16\u8F91\u5361\u7247", done: false }
4511
+ ])
4512
+ ]
4513
+ );
4514
+ const seq = (await client.query("UPDATE event_counter SET value = value + 1 WHERE id = 1 RETURNING value")).rows[0].value;
4515
+ await client.query(
4516
+ `INSERT INTO card_events(server_seq, id, project_id, card_id, type, actor_kind, actor_id, actor_name, data)
4517
+ VALUES($1, $2, $3, $4, 'card_created', 'human', 'local-user', '\u6211', $5)`,
4518
+ [
4519
+ seq,
4520
+ randomUUID9(),
4521
+ projectId,
4522
+ cardId,
4523
+ JSON.stringify({
4524
+ title: "\u6B22\u8FCE\u4F7F\u7528 Slate\uFF1A\u5728\u5361\u7247\u91CC\u76F4\u63A5 @Agent \u534F\u540C\u5E72\u6D3B",
4525
+ mentions: [],
4526
+ targetActorIds: [],
4527
+ routingReason: "none"
4528
+ })
4529
+ ]
4530
+ );
4531
+ });
4532
+ }
4533
+ if (process.argv[1] && import.meta.url === pathToFileURL2(process.argv[1]).href) {
4534
+ const pool2 = createPool(config.databasePath);
4535
+ try {
4536
+ await seed(pool2);
4537
+ console.log("SQLite V2 \u9ED8\u8BA4\u521D\u59CB\u5316\u5B8C\u6210");
4538
+ } finally {
4539
+ await pool2.end();
4540
+ }
4541
+ }
4542
+
4543
+ // src/server.ts
4544
+ var pool = createPool(config.databasePath);
4545
+ await seed(pool);
4546
+ var cleaned = await cleanupOrphanAttachments(pool, config.uploadsDir);
4547
+ if (cleaned.removedCount > 0) {
4548
+ console.log(`\u5DF2\u6E05\u7406 ${cleaned.removedCount} \u4E2A\u8D85\u8FC7 24 \u5C0F\u65F6\u672A\u7ED1\u5B9A\u7684\u4E34\u65F6\u9644\u4EF6`);
4549
+ }
4550
+ var app = await createApp({
4551
+ pool,
4552
+ webOrigin: config.webOrigin,
4553
+ sandboxRoot: config.sandboxRoot,
4554
+ uploadsRoot: config.uploadsDir,
4555
+ webDistDir: config.webDistDir,
4556
+ logger: true
4557
+ });
4558
+ await app.listen({ host: "127.0.0.1", port: config.port });
4559
+ console.log(`\u770B\u677F API \u5DF2\u542F\u52A8\uFF1Ahttp://127.0.0.1:${config.port}`);
4560
+ for (const signal of ["SIGINT", "SIGTERM"]) {
4561
+ process.once(signal, async () => {
4562
+ await app.close();
4563
+ await pool.end();
4564
+ process.exit(0);
4565
+ });
4566
+ }
4567
+ //# sourceMappingURL=server.js.map