@miles-huang/cove 0.1.3 → 0.1.5

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 (85) hide show
  1. package/.env.example +7 -3
  2. package/README.md +17 -9
  3. package/bin/cove.js +220 -9
  4. package/package.json +1 -1
  5. package/server/agent/messages.js +213 -4
  6. package/server/agent/runtime.js +1 -1
  7. package/server/agent/session-hub.js +305 -22
  8. package/server/app.js +21 -4
  9. package/server/auth.js +40 -29
  10. package/server/cli.js +207 -28
  11. package/server/config.js +6 -5
  12. package/server/credentials.js +174 -0
  13. package/server/index.js +3 -0
  14. package/server/routes/meta.js +4 -2
  15. package/server/routes/sessions.js +30 -0
  16. package/server/routes/update.js +36 -0
  17. package/server/routes/uploads.js +100 -0
  18. package/server/routes/voice.js +95 -0
  19. package/server/server.js +114 -14
  20. package/server/updater.js +484 -0
  21. package/server/voice.js +618 -0
  22. package/shared/protocol.js +8 -0
  23. package/web/assets/{abnfDiagram-VCTEODGH-BvfDeUDt.js → abnfDiagram-VCTEODGH-CzbWgcsF.js} +1 -1
  24. package/web/assets/{architectureDiagram-5GKGNRK7-B6x-Vdta.js → architectureDiagram-5GKGNRK7-jpqUHglp.js} +1 -1
  25. package/web/assets/{blockDiagram-I7D4REHJ-DSdow19J.js → blockDiagram-I7D4REHJ-CaDKtZbM.js} +1 -1
  26. package/web/assets/{c4Diagram-7LVT6UL2-DNANA_BY.js → c4Diagram-7LVT6UL2-DSzOjXhU.js} +1 -1
  27. package/web/assets/channel-CyiORw9T.js +1 -0
  28. package/web/assets/{chunk-2Q5K7J3B-DQhKxJim.js → chunk-2Q5K7J3B-jC1KoHVE.js} +1 -1
  29. package/web/assets/{chunk-5VM5RSS4-CxYuf8nJ.js → chunk-5VM5RSS4-D6X5RslJ.js} +1 -1
  30. package/web/assets/{chunk-F27PBJKO-pm7TdZp3.js → chunk-F27PBJKO-BbRLxBSh.js} +1 -1
  31. package/web/assets/{chunk-IMKFNOWR-BOUFtEzN.js → chunk-IMKFNOWR-y223YRpm.js} +1 -1
  32. package/web/assets/{chunk-JWPE2WC7-AmPhkmIF.js → chunk-JWPE2WC7-s-_Lm4OD.js} +1 -1
  33. package/web/assets/{chunk-POPQ4Y6H-DAjm7eYi.js → chunk-POPQ4Y6H-FAjR47qb.js} +1 -1
  34. package/web/assets/{chunk-SVP7TREG-CPIhAIng.js → chunk-SVP7TREG-V3BsTVSS.js} +1 -1
  35. package/web/assets/{chunk-TICWLB2K-zdUNYXIa.js → chunk-TICWLB2K-BHXaSfO0.js} +1 -1
  36. package/web/assets/{chunk-XXDRQBXY-HxMWsKyb.js → chunk-XXDRQBXY-uzA700bf.js} +1 -1
  37. package/web/assets/classDiagram-ZZMXUADV-gyexRBgY.js +1 -0
  38. package/web/assets/classDiagram-v2-VYDZK3BY-Bc9eynfM.js +1 -0
  39. package/web/assets/{cose-bilkent-JH36ORCC-lYmJLW2h.js → cose-bilkent-JH36ORCC-B6XhcmxK.js} +1 -1
  40. package/web/assets/{cynefin-OW5HDTMX-C8UcJePz.js → cynefin-OW5HDTMX-CCabvWFn.js} +1 -1
  41. package/web/assets/{cynefinDiagram-5FMLGOSQ-Dt1tZqyf.js → cynefinDiagram-5FMLGOSQ-D3FXPxq1.js} +1 -1
  42. package/web/assets/{dagre-GXQ25YYZ-Y0qiXkMO.js → dagre-GXQ25YYZ-eitZh1b1.js} +1 -1
  43. package/web/assets/{diagram-S7CK7UJ4-BtcdW_SA.js → diagram-S7CK7UJ4-B_523Ard.js} +1 -1
  44. package/web/assets/{diagram-UQ7AKVKN-DMwC8JNI.js → diagram-UQ7AKVKN-DLK2D1Lf.js} +1 -1
  45. package/web/assets/{diagram-VSXAHHWV-BVU0Bm6u.js → diagram-VSXAHHWV-IqWaTga0.js} +1 -1
  46. package/web/assets/{diagram-VX7I27RA-BYlx-nH2.js → diagram-VX7I27RA-D42Xhhqj.js} +1 -1
  47. package/web/assets/{diagram-Z3DM3KII-C_oAUIPq.js → diagram-Z3DM3KII-B38ZR6s3.js} +1 -1
  48. package/web/assets/{ebnfDiagram-PWID7BFC-D9eTa0_d.js → ebnfDiagram-PWID7BFC-Bto2hjgy.js} +1 -1
  49. package/web/assets/{erDiagram-RLTQ6QDP-Cn00lD_I.js → erDiagram-RLTQ6QDP-BbrcgCtr.js} +1 -1
  50. package/web/assets/{flowDiagram-HODETNUW-CBjFObVm.js → flowDiagram-HODETNUW-BccX2IC1.js} +1 -1
  51. package/web/assets/{ganttDiagram-EL5Y4UJY-BrJFpYUI.js → ganttDiagram-EL5Y4UJY-CIVhLWAs.js} +1 -1
  52. package/web/assets/{gitGraphDiagram-WWUBYQGX-CgDCGY4x.js → gitGraphDiagram-WWUBYQGX-CiQgydKF.js} +1 -1
  53. package/web/assets/{highlighted-body-6RAV4W6J-BaouqEZW.js → highlighted-body-6RAV4W6J-eKTYB7cG.js} +1 -1
  54. package/web/assets/index-8rrMUwb2.css +1 -0
  55. package/web/assets/index-DFKPpT1o.js +1289 -0
  56. package/web/assets/{infoDiagram-27XIBGKW-4GAuy2r7.js → infoDiagram-27XIBGKW-C3mfF7LW.js} +1 -1
  57. package/web/assets/{ishikawaDiagram-5VMMS53U-CDZ9dPA6.js → ishikawaDiagram-5VMMS53U-XWdz8N0o.js} +1 -1
  58. package/web/assets/{journeyDiagram-3NMN7TZE-D0uXeMh-.js → journeyDiagram-3NMN7TZE-CtvvC10N.js} +1 -1
  59. package/web/assets/{kanban-definition-UXKFOSKX-C4H7MD6w.js → kanban-definition-UXKFOSKX-uhxTqXnW.js} +1 -1
  60. package/web/assets/{layout-BFfV8fTs.js → layout-BQ419s8Q.js} +1 -1
  61. package/web/assets/{mindmap-definition-YA3MSWOX-Dd7Obl6F.js → mindmap-definition-YA3MSWOX-Cg7HolUO.js} +1 -1
  62. package/web/assets/{pegDiagram-XKGWAZYB-nDep-Xjv.js → pegDiagram-XKGWAZYB-Ca_T_k1c.js} +1 -1
  63. package/web/assets/{pieDiagram-E7YTZNPT-C8783QQe.js → pieDiagram-E7YTZNPT-Cqu0K07s.js} +1 -1
  64. package/web/assets/{quadrantDiagram-AXDQQJYC-CH5o8mIt.js → quadrantDiagram-AXDQQJYC-wK7kSaZg.js} +1 -1
  65. package/web/assets/{railroadDiagram-O6MQD6OU-QPxQi08o.js → railroadDiagram-O6MQD6OU-Yt2QDvBQ.js} +1 -1
  66. package/web/assets/{requirementDiagram-BXWQKSXE-DVr0s9y9.js → requirementDiagram-BXWQKSXE-BnUkaWq7.js} +1 -1
  67. package/web/assets/{sankeyDiagram-P5KCCOFB-Bq3TJeq8.js → sankeyDiagram-P5KCCOFB-M_ig6yCr.js} +1 -1
  68. package/web/assets/{sequenceDiagram-WJ2MYXX4-VWpvqhZf.js → sequenceDiagram-WJ2MYXX4-BZsd1fkB.js} +1 -1
  69. package/web/assets/{sizeCapture-INFHLROL-1n-6h_CN.js → sizeCapture-INFHLROL-QGHTzTuy.js} +1 -1
  70. package/web/assets/{stateDiagram-D77RDMKH-cmZfkPUb.js → stateDiagram-D77RDMKH-B-fkTedS.js} +1 -1
  71. package/web/assets/stateDiagram-v2-MP3YSRHH-BUXoRLIu.js +1 -0
  72. package/web/assets/{swimlanes-42K2YHIH-BqTB27WF.js → swimlanes-42K2YHIH-BP-raAm4.js} +1 -1
  73. package/web/assets/swimlanesDiagram-VR7AAH4N-ClyXkjH5.js +8 -0
  74. package/web/assets/{timeline-definition-24CTP7MA--BCgTKxF.js → timeline-definition-24CTP7MA-CDTB4Ri6.js} +1 -1
  75. package/web/assets/{vennDiagram-4TSXK5OY-BJaPku01.js → vennDiagram-4TSXK5OY-DFmr7Hbu.js} +1 -1
  76. package/web/assets/{wardleyDiagram-VM6X3IG4-n2YbPRWQ.js → wardleyDiagram-VM6X3IG4-DrhRjyVy.js} +1 -1
  77. package/web/assets/{xychartDiagram-S5SC5T6Z-CQpktgwa.js → xychartDiagram-S5SC5T6Z-CvH_0Dcr.js} +1 -1
  78. package/web/index.html +2 -2
  79. package/web/assets/channel-CyEPAFBz.js +0 -1
  80. package/web/assets/classDiagram-ZZMXUADV-DqTY3X0j.js +0 -1
  81. package/web/assets/classDiagram-v2-VYDZK3BY-BSxiMdF_.js +0 -1
  82. package/web/assets/index-4qPcqjHt.js +0 -1259
  83. package/web/assets/index-5AGKaJhL.css +0 -1
  84. package/web/assets/stateDiagram-v2-MP3YSRHH-wEaM0KsS.js +0 -1
  85. package/web/assets/swimlanesDiagram-VR7AAH4N-CjIKX5n2.js +0 -8
@@ -1,10 +1,14 @@
1
- import { lstatSync, readdirSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { existsSync, lstatSync, readdirSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { isAbsolute, join, relative, sep } from "node:path";
3
3
  import { SessionManager } from "@earendil-works/pi-coding-agent";
4
4
  import { clampThinkingLevelForDescriptor, isThinkingLevel, } from "../../shared/protocol.js";
5
- import { contentText, projectSessionMessages, summarizeTool, TURN_TIMING_CUSTOM_TYPE, } from "./messages.js";
5
+ import { computeSessionStats, contentText, projectSessionMessages, summarizeTool, TURN_TIMING_CUSTOM_TYPE, USER_ATTACHMENTS_CUSTOM_TYPE, } from "./messages.js";
6
6
  export { projectSessionMessages } from "./messages.js";
7
7
  const SESSION_ID = /^[a-zA-Z0-9_-]{1,128}$/;
8
+ const MAX_IMAGES_PER_MESSAGE = 8;
9
+ const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
10
+ const MAX_ATTACHMENTS_PER_MESSAGE = 10;
11
+ const ALLOWED_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
8
12
  export class SessionHubError extends Error {
9
13
  status;
10
14
  code;
@@ -23,6 +27,17 @@ function validateSessionId(id) {
23
27
  function notFound() {
24
28
  return new SessionHubError(404, "SESSION_NOT_FOUND", "Session not found.");
25
29
  }
30
+ function isContainedIn(root, target) {
31
+ const rel = relative(root, target);
32
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
33
+ }
34
+ function formatAttachmentBytes(bytes) {
35
+ if (bytes < 1024)
36
+ return `${bytes} B`;
37
+ if (bytes < 1024 * 1024)
38
+ return `${(bytes / 1024).toFixed(1)} KB`;
39
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
40
+ }
26
41
  function resolveModelDescriptor(runtime, providerInput, modelInput, fallback) {
27
42
  if (providerInput !== undefined) {
28
43
  return providerInput && modelInput ? runtime.getModelDescriptor(providerInput, modelInput) : undefined;
@@ -105,16 +120,22 @@ export class SessionHub {
105
120
  config;
106
121
  runtime;
107
122
  sessionsDir;
123
+ realWorkspaceDir;
108
124
  active = new Map();
125
+ compacting = new Set();
109
126
  deleting = new Set();
110
127
  constructor(config, runtime) {
111
128
  this.config = config;
112
129
  this.runtime = runtime;
113
130
  this.sessionsDir = realpathSync(config.sessionsDir);
131
+ this.realWorkspaceDir = realpathSync(config.workspaceDir);
114
132
  }
115
133
  defaults() {
116
134
  return this.runtime.getDefaults();
117
135
  }
136
+ hasBusySessions() {
137
+ return this.active.size > 0 || this.compacting.size > 0;
138
+ }
118
139
  listSessions() {
119
140
  const sessions = [];
120
141
  for (const entry of readdirSync(this.sessionsDir, { withFileTypes: true })) {
@@ -164,7 +185,125 @@ export class SessionHub {
164
185
  return this.describe(activeRun.manager, true);
165
186
  return this.describe(this.openSession(sessionId), false);
166
187
  }
188
+ renameSession(sessionId, title) {
189
+ validateSessionId(sessionId);
190
+ if (this.deleting.has(sessionId))
191
+ throw notFound();
192
+ if (typeof title !== "string") {
193
+ throw new SessionHubError(400, "INVALID_SESSION_TITLE", "会话标题必须是字符串。");
194
+ }
195
+ const trimmed = title.replace(/[\r\n]+/g, " ").trim();
196
+ if (!trimmed || trimmed.length > 120) {
197
+ throw new SessionHubError(400, "INVALID_SESSION_TITLE", "会话标题不能为空且长度不能超过 120 个字符。");
198
+ }
199
+ const activeRun = this.active.get(sessionId);
200
+ const manager = activeRun ? activeRun.manager : this.openSession(sessionId);
201
+ manager.appendSessionInfo(trimmed);
202
+ return this.describe(manager, Boolean(activeRun)).session;
203
+ }
204
+ branchSession(sessionId, messageId) {
205
+ validateSessionId(sessionId);
206
+ if (this.deleting.has(sessionId))
207
+ throw notFound();
208
+ if (typeof messageId !== "string" || !messageId.trim()) {
209
+ throw new SessionHubError(400, "INVALID_MESSAGE_ID", "消息 ID 无效。");
210
+ }
211
+ // Open a dedicated SessionManager so branching never mutates an active run's in-memory manager.
212
+ const manager = this.openSession(sessionId);
213
+ const sourceTitle = this.describe(manager, false).session.title;
214
+ const branch = manager.getBranch();
215
+ const targetIndex = branch.findIndex((entry) => entry.id === messageId &&
216
+ entry.type === "message" &&
217
+ (entry.message.role === "user" || entry.message.role === "assistant"));
218
+ if (targetIndex < 0) {
219
+ throw new SessionHubError(404, "MESSAGE_NOT_FOUND", "未找到用于分支的目标消息。");
220
+ }
221
+ const includedIds = new Set(branch.slice(0, targetIndex + 1).map((entry) => entry.id));
222
+ let leafIndex = targetIndex;
223
+ for (let i = targetIndex + 1; i < branch.length; i += 1) {
224
+ const entry = branch[i];
225
+ if (entry.type === "message") {
226
+ if (entry.message.role === "toolResult") {
227
+ leafIndex = i;
228
+ includedIds.add(entry.id);
229
+ continue;
230
+ }
231
+ break;
232
+ }
233
+ if (entry.type === "compaction")
234
+ break;
235
+ if (entry.type === "custom" &&
236
+ (entry.customType === TURN_TIMING_CUSTOM_TYPE || entry.customType === USER_ATTACHMENTS_CUSTOM_TYPE)) {
237
+ const refId = entry.data?.entryId;
238
+ if (typeof refId === "string" && includedIds.has(refId)) {
239
+ leafIndex = i;
240
+ includedIds.add(entry.id);
241
+ continue;
242
+ }
243
+ }
244
+ break;
245
+ }
246
+ manager.createBranchedSession(branch[leafIndex].id);
247
+ if (!manager.isPersisted()) {
248
+ const file = this.containedPath(manager.getSessionFile());
249
+ const entries = [manager.getHeader(), ...manager.getEntries()];
250
+ writeFileSync(file, entries.map((entry) => `${JSON.stringify(entry)}\n`).join(""), { flag: "wx", mode: 0o600 });
251
+ }
252
+ const suffix = " (分支)";
253
+ const branchTitle = sourceTitle.endsWith("(分支)")
254
+ ? sourceTitle.slice(0, 120)
255
+ : `${sourceTitle.slice(0, 120 - suffix.length)}${suffix}`;
256
+ manager.appendSessionInfo(branchTitle);
257
+ return this.describe(manager, false).session;
258
+ }
259
+ async compactSession(sessionId, instructions) {
260
+ validateSessionId(sessionId);
261
+ if (this.active.has(sessionId) || this.compacting.has(sessionId) || this.deleting.has(sessionId)) {
262
+ throw new SessionHubError(409, "SESSION_BUSY", "会话正在运行或压缩中,请稍后再试。");
263
+ }
264
+ if (instructions !== undefined && typeof instructions !== "string") {
265
+ throw new SessionHubError(400, "INVALID_COMPACT_INSTRUCTIONS", "压缩指令必须是字符串。");
266
+ }
267
+ const trimmedInstructions = instructions?.trim();
268
+ if (trimmedInstructions && trimmedInstructions.length > 1000) {
269
+ throw new SessionHubError(400, "INVALID_COMPACT_INSTRUCTIONS", "压缩指令长度不能超过 1000 个字符。");
270
+ }
271
+ const manager = this.openSession(sessionId);
272
+ const stored = storedPreferences(manager.getBranch(), this.defaults(), this.runtime);
273
+ const preferences = selectPreferences({}, stored, this.runtime);
274
+ this.compacting.add(sessionId);
275
+ try {
276
+ const session = await this.runtime.createSession(manager, preferences.provider, preferences.model, preferences.thinkingLevel);
277
+ let result;
278
+ try {
279
+ result = await session.compact(trimmedInstructions || undefined);
280
+ }
281
+ catch (error) {
282
+ const msg = error instanceof Error ? error.message : String(error);
283
+ if (/nothing to compact|already compacted/i.test(msg)) {
284
+ throw new SessionHubError(400, "COMPACT_UNAVAILABLE", "当前对话上下文较短或已压缩,无需再次压缩。");
285
+ }
286
+ throw new SessionHubError(502, "COMPACT_FAILED", `压缩上下文失败:${msg}`);
287
+ }
288
+ finally {
289
+ session.dispose();
290
+ }
291
+ const detail = this.describe(manager, false);
292
+ return {
293
+ ...detail,
294
+ summary: result.summary,
295
+ tokensBefore: result.tokensBefore,
296
+ };
297
+ }
298
+ finally {
299
+ this.compacting.delete(sessionId);
300
+ }
301
+ }
167
302
  async deleteSession(sessionId) {
303
+ validateSessionId(sessionId);
304
+ if (this.compacting.has(sessionId)) {
305
+ throw new SessionHubError(409, "SESSION_BUSY", "The session is busy.");
306
+ }
168
307
  const manager = this.openSession(sessionId);
169
308
  this.deleting.add(sessionId);
170
309
  try {
@@ -201,16 +340,18 @@ export class SessionHub {
201
340
  }
202
341
  sendMessage(sessionId, req, emit, detachSignal) {
203
342
  validateSessionId(sessionId);
204
- if (this.active.has(sessionId) || this.deleting.has(sessionId)) {
343
+ if (this.active.has(sessionId) || this.compacting.has(sessionId) || this.deleting.has(sessionId)) {
205
344
  throw new SessionHubError(409, "SESSION_BUSY", "The session is busy.");
206
345
  }
207
- if (typeof req?.content !== "string" || !req.content.trim()) {
208
- throw new SessionHubError(400, "INVALID_MESSAGE", "A non-empty message is required.");
346
+ if (req?.content !== undefined && typeof req.content !== "string") {
347
+ throw new SessionHubError(400, "INVALID_MESSAGE", "Message content must be a string.");
209
348
  }
210
349
  const manager = this.openSession(sessionId);
211
350
  const defaults = this.defaults();
212
351
  const stored = storedPreferences(manager.getBranch(), defaults, this.runtime);
213
352
  const preferences = selectPreferences(req, stored, this.runtime);
353
+ const descriptor = this.runtime.getModelDescriptor(preferences.provider, preferences.model);
354
+ const prepared = this.prepareSendInput(req, descriptor);
214
355
  const controller = new AbortController();
215
356
  const run = {
216
357
  sessionId,
@@ -223,14 +364,16 @@ export class SessionHub {
223
364
  id: `pending-user-${Date.now()}`,
224
365
  role: "user",
225
366
  createdAt: new Date().toISOString(),
226
- content: req.content,
367
+ content: prepared.displayContent,
368
+ ...(prepared.images.length > 0 ? { images: prepared.images } : {}),
369
+ ...(prepared.attachments.length > 0 ? { attachments: prepared.attachments } : {}),
227
370
  },
228
371
  completedTurns: [],
229
372
  currentTurnParts: [],
230
373
  };
231
374
  this.active.set(sessionId, run);
232
375
  run.finished = Promise.resolve()
233
- .then(() => this.generate(run, req.content, preferences))
376
+ .then(() => this.generate(run, prepared, preferences, descriptor?.contextWindow ?? 128_000))
234
377
  .finally(() => {
235
378
  if (this.active.get(sessionId) === run) {
236
379
  this.active.delete(sessionId);
@@ -247,9 +390,109 @@ export class SessionHub {
247
390
  return this.attachSubscriber(activeRun, emit, detachSignal, buildReplayEvents(activeRun));
248
391
  }
249
392
  const manager = this.openSession(sessionId);
250
- emit({ type: "done", session: this.describe(manager, false).session });
393
+ const detail = this.describe(manager, false);
394
+ emit({ type: "done", session: detail.session, stats: detail.stats });
251
395
  return Promise.resolve();
252
396
  }
397
+ prepareSendInput(req, descriptor) {
398
+ const displayContent = typeof req.content === "string" ? req.content : "";
399
+ const images = [];
400
+ const piImages = [];
401
+ if (req.images !== undefined) {
402
+ if (!Array.isArray(req.images)) {
403
+ throw new SessionHubError(400, "INVALID_IMAGE", "图片列表格式无效。");
404
+ }
405
+ if (req.images.length > MAX_IMAGES_PER_MESSAGE) {
406
+ throw new SessionHubError(400, "INVALID_IMAGE", `单次最多附加 ${MAX_IMAGES_PER_MESSAGE} 张图片。`);
407
+ }
408
+ for (const raw of req.images) {
409
+ if (!raw || typeof raw !== "object") {
410
+ throw new SessionHubError(400, "INVALID_IMAGE", "图片格式无效。");
411
+ }
412
+ const mimeType = typeof raw.mimeType === "string" ? raw.mimeType.trim().toLowerCase() : "";
413
+ if (!ALLOWED_IMAGE_MIME_TYPES.has(mimeType)) {
414
+ throw new SessionHubError(400, "INVALID_IMAGE", "仅支持 PNG、JPEG、WebP 或 GIF 图片。");
415
+ }
416
+ if (typeof raw.data !== "string" || !raw.data.trim()) {
417
+ throw new SessionHubError(400, "INVALID_IMAGE", "图片数据为空。");
418
+ }
419
+ const cleanBase64 = raw.data.replace(/^data:[^;]+;base64,/, "").replace(/\s+/g, "");
420
+ if (!cleanBase64 || !/^[A-Za-z0-9+/=]+$/.test(cleanBase64)) {
421
+ throw new SessionHubError(400, "INVALID_IMAGE", "图片 Base64 编码无效。");
422
+ }
423
+ const decoded = Buffer.from(cleanBase64, "base64");
424
+ if (decoded.byteLength === 0 || decoded.byteLength > MAX_IMAGE_BYTES) {
425
+ throw new SessionHubError(400, "INVALID_IMAGE", "单张图片大小须大于 0 且不超过 10 MB。");
426
+ }
427
+ const name = typeof raw.name === "string" && raw.name.trim() ? raw.name.trim().slice(0, 120) : undefined;
428
+ images.push({ data: cleanBase64, mimeType, ...(name ? { name } : {}) });
429
+ piImages.push({ type: "image", data: cleanBase64, mimeType });
430
+ }
431
+ }
432
+ if (images.length > 0 && !descriptor?.supportsImages) {
433
+ throw new SessionHubError(400, "MODEL_NO_IMAGE_SUPPORT", "当前模型未开启图片输入,请切换视觉模型或在「设置 → 模型」中开启「支持图片输入」。");
434
+ }
435
+ const attachments = [];
436
+ if (req.attachments !== undefined) {
437
+ if (!Array.isArray(req.attachments)) {
438
+ throw new SessionHubError(400, "INVALID_ATTACHMENT", "附件列表格式无效。");
439
+ }
440
+ if (req.attachments.length > MAX_ATTACHMENTS_PER_MESSAGE) {
441
+ throw new SessionHubError(400, "INVALID_ATTACHMENT", `单次最多附加 ${MAX_ATTACHMENTS_PER_MESSAGE} 个文件。`);
442
+ }
443
+ const uploadsDir = join(this.realWorkspaceDir, "uploads");
444
+ const realUploadsDir = existsSync(uploadsDir) ? realpathSync(uploadsDir) : undefined;
445
+ for (const raw of req.attachments) {
446
+ if (!raw || typeof raw !== "object") {
447
+ throw new SessionHubError(400, "INVALID_ATTACHMENT", "附件信息无效。");
448
+ }
449
+ const wp = typeof raw.workspacePath === "string" ? raw.workspacePath : "";
450
+ if (!wp.startsWith("uploads/") ||
451
+ wp.includes("\0") ||
452
+ wp.includes("\\") ||
453
+ wp.split("/").some((seg) => !seg || seg === "." || seg === "..")) {
454
+ throw new SessionHubError(400, "INVALID_ATTACHMENT", "附件路径无效。");
455
+ }
456
+ if (!realUploadsDir || !isContainedIn(this.realWorkspaceDir, realUploadsDir)) {
457
+ throw new SessionHubError(400, "INVALID_ATTACHMENT", "附件文件不存在,请重新上传。");
458
+ }
459
+ const absPath = join(this.realWorkspaceDir, wp);
460
+ const stat = lstatSync(absPath, { throwIfNoEntry: false });
461
+ if (!stat?.isFile()) {
462
+ throw new SessionHubError(400, "INVALID_ATTACHMENT", "附件文件不存在,请重新上传。");
463
+ }
464
+ const realTarget = realpathSync(absPath);
465
+ if (!isContainedIn(realUploadsDir, realTarget)) {
466
+ throw new SessionHubError(400, "INVALID_ATTACHMENT", "附件路径越界。");
467
+ }
468
+ const id = typeof raw.id === "string" && raw.id.trim() ? raw.id.trim().slice(0, 64) : wp;
469
+ const name = typeof raw.name === "string" && raw.name.trim() ? raw.name.trim().slice(0, 120) : wp.slice(8);
470
+ const mimeType = typeof raw.mimeType === "string" && raw.mimeType.trim() ? raw.mimeType.trim().slice(0, 120) : "application/octet-stream";
471
+ const size = typeof raw.size === "number" && Number.isFinite(raw.size) && raw.size >= 0 ? Math.round(raw.size) : stat.size;
472
+ attachments.push({ id, name, mimeType, size, workspacePath: wp });
473
+ }
474
+ }
475
+ if (!displayContent.trim() && images.length === 0 && attachments.length === 0) {
476
+ throw new SessionHubError(400, "INVALID_MESSAGE", "A non-empty message is required.");
477
+ }
478
+ let promptText = displayContent;
479
+ if (attachments.length > 0) {
480
+ const lines = attachments.map((att) => `- ${att.name} (${att.mimeType}, ${formatAttachmentBytes(att.size)}) -> 工作区路径: ${att.workspacePath}`);
481
+ const block = `[用户上传了以下工作区文件,可使用 read 或 bash 工具查看和处理]\n${lines.join("\n")}`;
482
+ promptText = displayContent.trim() ? `${displayContent}\n\n${block}` : block;
483
+ }
484
+ else if (!displayContent.trim() && images.length > 0) {
485
+ promptText = "请查看附带的图片。";
486
+ }
487
+ return {
488
+ displayContent,
489
+ promptText,
490
+ images,
491
+ piImages,
492
+ attachments,
493
+ needsAttachmentEntry: attachments.length > 0 || promptText !== displayContent,
494
+ };
495
+ }
253
496
  attachSubscriber(run, emit, detachSignal, replayEvents = []) {
254
497
  return new Promise((resolve) => {
255
498
  let settled = false;
@@ -322,6 +565,7 @@ export class SessionHub {
322
565
  const sessionId = manager.getSessionId();
323
566
  const entries = manager.getBranch();
324
567
  const defaults = this.defaults();
568
+ const preferences = storedPreferences(entries, defaults, this.runtime);
325
569
  const resolveDescriptor = (provider, modelId) => this.runtime.getModelDescriptor(provider, modelId);
326
570
  const messages = projectSessionMessages(entries, defaults, resolveDescriptor);
327
571
  const activeRun = isStreaming ? this.active.get(sessionId) : undefined;
@@ -334,21 +578,26 @@ export class SessionHub {
334
578
  }
335
579
  }
336
580
  const { timestamp } = manager.getHeader();
337
- const firstMessage = messages.find((message) => message.role === "user")?.content?.trim().replace(/\s+/g, " ");
581
+ const firstUser = messages.find((message) => message.role === "user");
582
+ const firstMessage = firstUser?.content?.trim().replace(/\s+/g, " ");
583
+ const firstAttachmentTitle = firstUser?.attachments?.[0]?.name || (firstUser?.images?.length ? "图片对话" : "");
584
+ const descriptor = this.runtime.getModelDescriptor(preferences.provider, preferences.model);
585
+ const contextWindow = descriptor?.contextWindow ?? 128_000;
338
586
  return {
339
587
  session: {
340
588
  id: sessionId,
341
- title: manager.getSessionName() || firstMessage?.slice(0, 48) || "新对话",
589
+ title: manager.getSessionName() || firstMessage?.slice(0, 48) || firstAttachmentTitle.slice(0, 48) || "新对话",
342
590
  createdAt: timestamp,
343
591
  updatedAt: entries.at(-1)?.timestamp ?? timestamp,
344
592
  messageCount: messages.length,
345
- ...storedPreferences(entries, defaults, this.runtime),
593
+ ...preferences,
346
594
  isStreaming,
347
595
  },
348
596
  messages,
597
+ stats: computeSessionStats(manager, contextWindow),
349
598
  };
350
599
  }
351
- async generate(run, content, preferences) {
600
+ async generate(run, prepared, preferences, contextWindow) {
352
601
  const { manager, controller, sessionId } = run;
353
602
  const signal = controller.signal;
354
603
  // Pi's listeners are synchronous. Record live snapshots for stream reattach and fan out to attached writers.
@@ -358,6 +607,21 @@ export class SessionHub {
358
607
  subscriber.enqueue(event);
359
608
  }
360
609
  }
610
+ let userAttachmentsRecorded = false;
611
+ const persistUserAttachments = () => {
612
+ if (!prepared.needsAttachmentEntry || userAttachmentsRecorded)
613
+ return;
614
+ const added = manager.getBranch().slice(run.baseEntryCount);
615
+ const userEntry = added.find((entry) => entry.type === "message" && entry.message.role === "user");
616
+ if (userEntry) {
617
+ userAttachmentsRecorded = true;
618
+ manager.appendCustomEntry(USER_ATTACHMENTS_CUSTOM_TYPE, {
619
+ entryId: userEntry.id,
620
+ displayContent: prepared.displayContent,
621
+ attachments: prepared.attachments,
622
+ });
623
+ }
624
+ };
361
625
  let failure;
362
626
  try {
363
627
  if (!signal.aborted) {
@@ -369,7 +633,13 @@ export class SessionHub {
369
633
  // An abort triggered during Pi's prompt preflight may precede the SDK's active run.
370
634
  if (event.type === "agent_start" && signal.aborted)
371
635
  abort();
372
- bridgeEvent(event, manager, preferences, toolSummaries, timingTracker, this.runtime, publish);
636
+ if (event.type === "message_start" ||
637
+ event.type === "message_update" ||
638
+ event.type === "tool_execution_start" ||
639
+ event.type === "turn_end") {
640
+ persistUserAttachments();
641
+ }
642
+ bridgeEvent(event, manager, preferences, toolSummaries, timingTracker, this.runtime, contextWindow, publish);
373
643
  if (event.type === "agent_end" && !event.willRetry) {
374
644
  const last = event.messages.findLast((message) => message.role === "assistant");
375
645
  if (last?.role === "assistant" && last.stopReason === "error") {
@@ -389,10 +659,14 @@ export class SessionHub {
389
659
  stored.thinkingLevel !== preferences.thinkingLevel) {
390
660
  manager.appendThinkingLevelChange(preferences.thinkingLevel);
391
661
  }
392
- await session.prompt(content, { source: "rpc" });
662
+ await session.prompt(prepared.promptText, {
663
+ source: "rpc",
664
+ ...(prepared.piImages.length > 0 ? { images: prepared.piImages } : {}),
665
+ });
393
666
  }
394
667
  }
395
668
  finally {
669
+ persistUserAttachments();
396
670
  signal.removeEventListener("abort", abort);
397
671
  unsubscribe();
398
672
  session.dispose();
@@ -409,7 +683,8 @@ export class SessionHub {
409
683
  const attached = [...run.subscribers];
410
684
  if (failure && !signal.aborted)
411
685
  publish({ type: "error", code: "GENERATION_FAILED", message: failure });
412
- publish({ type: "done", session: this.describe(manager, false).session });
686
+ const detail = this.describe(manager, false);
687
+ publish({ type: "done", session: detail.session, stats: detail.stats });
413
688
  await Promise.allSettled(attached.map((subscriber) => subscriber.writes));
414
689
  for (const subscriber of attached)
415
690
  subscriber.settle();
@@ -564,12 +839,15 @@ class TurnTimingTracker {
564
839
  finishTurn(entryId, now = Date.now()) {
565
840
  this.closeThinking(now);
566
841
  let result = null;
567
- if (this.hasProcessActivity && this.turnStartedAt !== null) {
568
- const end = this.processEndedAt ?? now;
569
- const durationMs = Math.max(1, end - this.turnStartedAt);
842
+ if (this.turnStartedAt !== null) {
843
+ const generationDurationMs = Math.max(1, now - this.turnStartedAt);
844
+ const processDurationMs = this.hasProcessActivity
845
+ ? Math.max(1, (this.processEndedAt ?? now) - this.turnStartedAt)
846
+ : undefined;
570
847
  result = {
571
848
  entryId,
572
- durationMs,
849
+ ...(processDurationMs !== undefined ? { durationMs: processDurationMs } : {}),
850
+ generationDurationMs,
573
851
  ...(this.thinkingDurations.length > 0 ? { thinkingDurations: [...this.thinkingDurations] } : {}),
574
852
  };
575
853
  }
@@ -581,7 +859,7 @@ class TurnTimingTracker {
581
859
  return result;
582
860
  }
583
861
  }
584
- function bridgeEvent(event, manager, preferences, toolSummaries, timingTracker, runtime, emit) {
862
+ function bridgeEvent(event, manager, preferences, toolSummaries, timingTracker, runtime, contextWindow, emit) {
585
863
  switch (event.type) {
586
864
  case "turn_start": {
587
865
  timingTracker.onTurnStart();
@@ -638,8 +916,13 @@ function bridgeEvent(event, manager, preferences, toolSummaries, timingTracker,
638
916
  }
639
917
  const updatedBranch = timing ? manager.getBranch() : branch;
640
918
  const [message] = projectSessionMessages(updatedBranch.slice(index), preferences, (provider, modelId) => runtime.getModelDescriptor(provider, modelId));
641
- if (message)
642
- emit({ type: "turn_end", message });
919
+ if (message) {
920
+ emit({
921
+ type: "turn_end",
922
+ message,
923
+ stats: computeSessionStats(manager, contextWindow),
924
+ });
925
+ }
643
926
  }
644
927
  break;
645
928
  }
package/server/app.js CHANGED
@@ -7,6 +7,11 @@ import { createAuthRoutes } from "./routes/auth.js";
7
7
  import { createMetaRoutes } from "./routes/meta.js";
8
8
  import { createProviderRoutes } from "./routes/providers.js";
9
9
  import { createSessionRoutes } from "./routes/sessions.js";
10
+ import { createUpdateRoutes } from "./routes/update.js";
11
+ import { createUploadRoutes } from "./routes/uploads.js";
12
+ import { createVoiceRoutes } from "./routes/voice.js";
13
+ import { UpdateManager } from "./updater.js";
14
+ import { VoiceStore } from "./voice.js";
10
15
  const MIME_TYPES = {
11
16
  ".html": "text/html; charset=utf-8",
12
17
  ".js": "text/javascript; charset=utf-8",
@@ -88,7 +93,14 @@ async function serveStatic(c, root) {
88
93
  return c.body(await readFile(file), 200, headers);
89
94
  }
90
95
  export function createApp(options) {
91
- const { config, registry, runtime, sessionHub, hostCtx, webDistDir, sseHeartbeatIntervalMs } = options;
96
+ const { config, registry, runtime, sessionHub, hostCtx, webDistDir, sseHeartbeatIntervalMs, disableAuth } = options;
97
+ const voiceStore = options.voiceStore ?? new VoiceStore(config);
98
+ const updateManager = options.updateManager ??
99
+ new UpdateManager({
100
+ dataDir: config.dataDir,
101
+ runtimeMode: "source",
102
+ hasBusySessions: () => sessionHub.hasBusySessions(),
103
+ });
92
104
  const app = new Hono();
93
105
  app.onError((error, c) => {
94
106
  console.error("Unhandled request error:", error);
@@ -97,11 +109,16 @@ export function createApp(options) {
97
109
  }
98
110
  return c.text("Internal Server Error", 500);
99
111
  });
100
- app.use("*", createAuthMiddleware(config));
101
- app.route("/api/auth", createAuthRoutes(config));
102
- app.route("/api/meta", createMetaRoutes(config, registry, runtime));
112
+ if (!disableAuth) {
113
+ app.use("*", createAuthMiddleware(config));
114
+ app.route("/api/auth", createAuthRoutes(config));
115
+ }
116
+ app.route("/api/meta", createMetaRoutes(config, registry, runtime, voiceStore, updateManager.getCurrentVersion()));
103
117
  app.route("/api/providers", createProviderRoutes(runtime));
104
118
  app.route("/api/sessions", createSessionRoutes(sessionHub, { sseHeartbeatIntervalMs }));
119
+ app.route("/api/uploads", createUploadRoutes(config));
120
+ app.route("/api/voice", createVoiceRoutes(voiceStore));
121
+ app.route("/api/update", createUpdateRoutes(updateManager));
105
122
  registry.mountRoutes(app, hostCtx);
106
123
  // Unknown API routes must stay JSON errors; never fall through to index.html.
107
124
  app.all("/api", apiNotFound);
package/server/auth.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
2
  import { deleteCookie, getCookie, setCookie } from "hono/cookie";
3
+ import { loadStoredCredentials, verifyPasswordHash } from "./credentials.js";
3
4
  const COOKIE_NAME = "cloud_personal_agent_session";
4
5
  const SESSION_TTL_SECONDS = 60 * 60 * 24 * 7;
5
6
  const authByConfig = new WeakMap();
@@ -7,36 +8,50 @@ export function createAuth(config) {
7
8
  const cached = authByConfig.get(config);
8
9
  if (cached)
9
10
  return cached;
10
- const username = config.appUsername?.trim() ? config.appUsername.trim() : undefined;
11
- const password = config.appPassword?.trim() ? config.appPassword : undefined;
12
- const production = config.nodeEnv === "production";
13
- if (production && (!username || !password)) {
14
- throw new Error("APP_USERNAME and APP_PASSWORD are required in production.");
15
- }
16
- if (Boolean(username) !== Boolean(password)) {
11
+ const envUsername = config.appUsername?.trim() ? config.appUsername.trim() : undefined;
12
+ const envPassword = config.appPassword?.trim() ? config.appPassword : undefined;
13
+ if (Boolean(envUsername) !== Boolean(envPassword)) {
17
14
  throw new Error("Both APP_USERNAME and APP_PASSWORD must be set together.");
18
15
  }
19
- const authEnabled = username !== undefined && password !== undefined;
20
- if (!authEnabled) {
21
- console.warn("APP_USERNAME / APP_PASSWORD is unset. API authentication is disabled.");
22
- }
23
- const key = config.authSecret || (username && password
24
- ? createHash("sha256")
25
- .update("cloud-personal-agent/auth/v2\0")
26
- .update(username)
27
- .update("\0")
28
- .update(password)
29
- .digest()
30
- : randomBytes(32));
31
16
  const digest = (value) => createHash("sha256").update(value).digest();
32
- const usernameDigest = username && digest(username);
33
- const passwordDigest = password && digest(password);
17
+ let key;
18
+ let usernameDigest;
19
+ let verifyPasswordFn;
20
+ if (envUsername && envPassword) {
21
+ usernameDigest = digest(envUsername);
22
+ const passwordDigest = digest(envPassword);
23
+ verifyPasswordFn = (candidatePassword) => timingSafeEqual(digest(candidatePassword), passwordDigest);
24
+ key = config.authSecret
25
+ ? Buffer.from(config.authSecret)
26
+ : createHash("sha256")
27
+ .update("cloud-personal-agent/auth/v2\0")
28
+ .update(envUsername)
29
+ .update("\0")
30
+ .update(envPassword)
31
+ .digest();
32
+ }
33
+ else {
34
+ const stored = loadStoredCredentials(config.agentDir);
35
+ if (!stored) {
36
+ throw new Error('尚未配置管理员账号密码。请先在终端运行 "cove init" 完成初始化,或同时设置 APP_USERNAME 与 APP_PASSWORD。');
37
+ }
38
+ usernameDigest = digest(stored.username);
39
+ verifyPasswordFn = (candidatePassword) => verifyPasswordHash(candidatePassword, stored.passwordHash);
40
+ key = config.authSecret
41
+ ? Buffer.from(config.authSecret)
42
+ : createHash("sha256")
43
+ .update("cloud-personal-agent/auth/v2\0")
44
+ .update(stored.sessionSecret)
45
+ .update("\0")
46
+ .update(stored.passwordHash)
47
+ .digest();
48
+ }
34
49
  const sign = (payload) => createHmac("sha256", key).update(payload).digest();
35
50
  const cookieOptions = (context) => ({
36
51
  httpOnly: true,
37
52
  sameSite: "Lax",
38
53
  path: "/",
39
- secure: production || context.req.header("x-forwarded-proto") === "https",
54
+ secure: Boolean(config.tls) || context.req.header("x-forwarded-proto") === "https",
40
55
  });
41
56
  function validToken(token) {
42
57
  if (!token)
@@ -50,20 +65,16 @@ export function createAuth(config) {
50
65
  && expiresAt > Math.floor(Date.now() / 1000);
51
66
  }
52
67
  const auth = {
53
- authEnabled,
68
+ authEnabled: true,
54
69
  verifyCredentials(candidateUsername, candidatePassword) {
55
- if (!usernameDigest || !passwordDigest)
56
- return false;
57
70
  if (typeof candidateUsername !== "string" || typeof candidatePassword !== "string") {
58
71
  return false;
59
72
  }
60
73
  const usernameOk = timingSafeEqual(digest(candidateUsername.trim()), usernameDigest);
61
- const passwordOk = timingSafeEqual(digest(candidatePassword), passwordDigest);
74
+ const passwordOk = verifyPasswordFn(candidatePassword);
62
75
  return usernameOk && passwordOk;
63
76
  },
64
77
  setSessionCookie(context) {
65
- if (!authEnabled)
66
- return;
67
78
  const expiresAt = Math.floor(Date.now() / 1000) + SESSION_TTL_SECONDS;
68
79
  const payload = `${expiresAt}.${randomBytes(16).toString("hex")}`;
69
80
  setCookie(context, COOKIE_NAME, `${payload}.${sign(payload).toString("hex")}`, {
@@ -75,7 +86,7 @@ export function createAuth(config) {
75
86
  deleteCookie(context, COOKIE_NAME, cookieOptions(context));
76
87
  },
77
88
  getStatus(context) {
78
- return { authenticated: !authEnabled || validToken(getCookie(context, COOKIE_NAME)), authEnabled };
89
+ return { authenticated: validToken(getCookie(context, COOKIE_NAME)), authEnabled: true };
79
90
  },
80
91
  };
81
92
  authByConfig.set(config, auth);