@goodfish/jarvy 0.12.1 → 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,8 +14,8 @@ import { networkInterfaces } from "node:os";
14
14
  import { getRequestListener } from "@hono/node-server";
15
15
 
16
16
  // src/server/api/app.ts
17
- import { Hono as Hono15 } from "hono";
18
- import { HTTPException as HTTPException14 } from "hono/http-exception";
17
+ import { Hono as Hono16 } from "hono";
18
+ import { HTTPException as HTTPException15 } from "hono/http-exception";
19
19
  import { serveStatic } from "@hono/node-server/serve-static";
20
20
 
21
21
  // src/server/api/middleware/security.ts
@@ -185,8 +185,8 @@ function installAuthentication(api, account) {
185
185
  }
186
186
 
187
187
  // src/server/api/routes/bots.ts
188
- import { Hono as Hono4 } from "hono";
189
- import { HTTPException as HTTPException7 } from "hono/http-exception";
188
+ import { Hono as Hono5 } from "hono";
189
+ import { HTTPException as HTTPException8 } from "hono/http-exception";
190
190
 
191
191
  // src/server/api/views/bot-status.ts
192
192
  function botStatusView(status) {
@@ -317,7 +317,8 @@ function messageView(message) {
317
317
  replyTo: message.replyTo,
318
318
  reactions: message.reactions,
319
319
  quotes: message.quotes,
320
- folded: message.folded
320
+ folded: message.folded,
321
+ refs: message.refs
321
322
  };
322
323
  }
323
324
 
@@ -358,19 +359,35 @@ function activityRoutes(bots) {
358
359
  }
359
360
 
360
361
  // src/server/api/routes/history.ts
362
+ import { Hono as Hono4 } from "hono";
363
+ import { HTTPException as HTTPException7 } from "hono/http-exception";
364
+
365
+ // src/server/api/routes/usage.ts
361
366
  import { Hono as Hono3 } from "hono";
362
367
  import { HTTPException as HTTPException6 } from "hono/http-exception";
368
+ function since(raw) {
369
+ const value2 = Number(raw ?? "");
370
+ if (!/^\d+$/.test(raw ?? "") || !Number.isSafeInteger(value2)) throw new HTTPException6(400, { message: "Invalid start time" });
371
+ return value2;
372
+ }
373
+ function usageRoutes(bots) {
374
+ const routes = new Hono3();
375
+ routes.get("/usage", (c) => c.json(bots.usage(since(c.req.query("since")))));
376
+ return routes;
377
+ }
378
+
379
+ // src/server/api/routes/history.ts
363
380
  function integer(raw, label) {
364
381
  const n = Number(raw);
365
- if (!/^\d+$/.test(raw) || !Number.isSafeInteger(n) || n < 1) throw new HTTPException6(400, { message: `Invalid ${label}` });
382
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(n) || n < 1) throw new HTTPException7(400, { message: `Invalid ${label}` });
366
383
  return n;
367
384
  }
368
385
  function historyRoutes(bots) {
369
- const routes = new Hono3();
386
+ const routes = new Hono4();
370
387
  routes.get("/:id/history", (c) => {
371
388
  const memory = bots.memory(c.req.param("id"));
372
389
  const before = c.req.query("before"), limit2 = integer(c.req.query("limit") ?? "50", "page size");
373
- if (limit2 > 100) throw new HTTPException6(400, { message: "The page size can't be over 100" });
390
+ if (limit2 > 100) throw new HTTPException7(400, { message: "The page size can't be over 100" });
374
391
  return c.json(memory.list(before === void 0 ? void 0 : integer(before, "page position"), limit2));
375
392
  });
376
393
  routes.get("/:id/history/:recordId{[0-9]+}", (c) => {
@@ -379,23 +396,21 @@ function historyRoutes(bots) {
379
396
  return c.json(detail);
380
397
  });
381
398
  routes.get("/:id/usage", (c) => {
382
- const raw = c.req.query("since") ?? "";
383
- const since = Number(raw);
384
- if (!/^\d+$/.test(raw) || !Number.isSafeInteger(since)) throw new HTTPException6(400, { message: "Invalid start time" });
385
- return c.json({ since, models: bots.memory(c.req.param("id")).usage(since) });
399
+ const from = since(c.req.query("since"));
400
+ return c.json({ since: from, models: bots.memory(c.req.param("id")).usage(from) });
386
401
  });
387
402
  routes.all("/:id/history", () => {
388
- throw new HTTPException6(405, { message: "History is read-only" });
403
+ throw new HTTPException7(405, { message: "History is read-only" });
389
404
  });
390
405
  routes.all("/:id/history/:recordId{[0-9]+}", () => {
391
- throw new HTTPException6(405, { message: "History is read-only" });
406
+ throw new HTTPException7(405, { message: "History is read-only" });
392
407
  });
393
408
  return routes;
394
409
  }
395
410
 
396
411
  // src/server/api/routes/bots.ts
397
412
  function botRoutes(bots) {
398
- const routes = new Hono4();
413
+ const routes = new Hono5();
399
414
  routes.get("/", (c) => c.json({ bots: bots.list() }));
400
415
  routes.post("/", jsonBody, async (c) => {
401
416
  const input = await readJson(c);
@@ -403,7 +418,7 @@ function botRoutes(bots) {
403
418
  });
404
419
  routes.put("/:id/environment", jsonBody, async (c) => {
405
420
  const input = await readJson(c), id = c.req.param("id");
406
- if (typeof input.machineId !== "string" || typeof input.granted !== "boolean") throw new HTTPException7(400, { message: "machineId and granted (true or false) are needed" });
421
+ if (typeof input.machineId !== "string" || typeof input.granted !== "boolean") throw new HTTPException8(400, { message: "machineId and granted (true or false) are needed" });
407
422
  return c.json(bots.grantMachine(id, input.machineId, input.granted));
408
423
  });
409
424
  routes.put("/:id/computer/limits", jsonBody, async (c) => {
@@ -413,7 +428,7 @@ function botRoutes(bots) {
413
428
  routes.get("/:id/computer/resources", async (c) => c.json(await bots.computerResources(c.req.param("id"))));
414
429
  routes.post("/:id/computer/:action", async (c) => {
415
430
  const action = c.req.param("action");
416
- if (action !== "start" && action !== "stop" && action !== "reset") throw new HTTPException7(404, { message: "Not found" });
431
+ if (action !== "start" && action !== "stop" && action !== "reset") throw new HTTPException8(404, { message: "Not found" });
417
432
  return c.json(await bots.computer(c.req.param("id"), action));
418
433
  });
419
434
  routes.get("/:id", (c) => c.json(bots.describe(c.req.param("id"))));
@@ -466,8 +481,8 @@ function botRoutes(bots) {
466
481
 
467
482
  // src/server/api/routes/chats.ts
468
483
  import { Readable } from "node:stream";
469
- import { Hono as Hono5 } from "hono";
470
- import { HTTPException as HTTPException8 } from "hono/http-exception";
484
+ import { Hono as Hono6 } from "hono";
485
+ import { HTTPException as HTTPException9 } from "hono/http-exception";
471
486
 
472
487
  // src/server/api/views/download.ts
473
488
  var MEDIA_TYPES = /* @__PURE__ */ new Set(["video/webm", "video/mp4", "video/quicktime", "audio/mpeg", "audio/wav", "audio/x-wav", "audio/ogg", "audio/webm", "audio/mp4"]);
@@ -777,7 +792,7 @@ var tooLarge = () => new ChatError(413, "File is too large", "file_too_large", {
777
792
 
778
793
  // src/server/api/routes/chats.ts
779
794
  function chatRoutes({ chats, bots }) {
780
- const routes = new Hono5();
795
+ const routes = new Hono6();
781
796
  const view = (chat) => chatView(chat, (id) => chats.member(id));
782
797
  routes.get("/", (c) => c.json({ chats: chats.list(c.get("actorId")).map(view), followed: chats.threads.followedSummary(c.get("actorId")) }));
783
798
  routes.post("/", jsonBody, async (c) => {
@@ -808,18 +823,18 @@ function chatRoutes({ chats, bots }) {
808
823
  try {
809
824
  name3 = decodeURIComponent(c.req.header("x-file-name") ?? "");
810
825
  } catch {
811
- throw new HTTPException8(400, { message: "Invalid filename" });
826
+ throw new HTTPException9(400, { message: "Invalid filename" });
812
827
  }
813
828
  const declared = Number(c.req.header("content-length") ?? NaN);
814
829
  if (declared > ATTACHMENT_MAX_BYTES) throw tooLarge();
815
830
  const body = c.req.raw.body;
816
- if (!body) throw new HTTPException8(400, { message: "Empty attachment" });
831
+ if (!body) throw new HTTPException9(400, { message: "Empty attachment" });
817
832
  const mime = (c.req.header("content-type") ?? "application/octet-stream").slice(0, 100);
818
833
  return c.json(await chats.attachments.upload(c.get("actorId"), c.req.param("id"), name3, mime, idle(body, c.req.raw.signal)), 201);
819
834
  });
820
835
  routes.delete("/:id", async (c) => {
821
836
  const id = c.req.param("id");
822
- if (!await chats.delete(c.get("actorId"), id)) throw new HTTPException8(404, { message: "Chat not found" });
837
+ if (!await chats.delete(c.get("actorId"), id)) throw new HTTPException9(404, { message: "Chat not found" });
823
838
  await bots.chatDeleted(id);
824
839
  return c.json({ ok: true });
825
840
  });
@@ -828,10 +843,10 @@ function chatRoutes({ chats, bots }) {
828
843
  var ATTACHMENT_CACHE = "private, max-age=31536000, immutable";
829
844
  var disposition = (name3) => `attachment; filename*=UTF-8''${encodeURIComponent(name3)}`;
830
845
  function attachmentRoutes(chats) {
831
- const routes = new Hono5();
846
+ const routes = new Hono6();
832
847
  routes.get("/:id", (c) => {
833
848
  const file = chats.attachments.find(c.get("actorId"), c.req.param("id"));
834
- if (!file) throw new HTTPException8(404, { message: "Attachment not found" });
849
+ if (!file) throw new HTTPException9(404, { message: "Attachment not found" });
835
850
  const size = file.size, range = byteRange(c.req.header("Range"), size);
836
851
  const headers2 = {
837
852
  "Content-Type": downloadType(file.mimeType),
@@ -850,7 +865,7 @@ function attachmentRoutes(chats) {
850
865
  });
851
866
  routes.get("/:id/thumb", async (c) => {
852
867
  const file = chats.attachments.find(c.get("actorId"), c.req.param("id"));
853
- if (!file) throw new HTTPException8(404, { message: "Attachment not found" });
868
+ if (!file) throw new HTTPException9(404, { message: "Attachment not found" });
854
869
  const thumbnail = await chats.attachments.thumbnail(file);
855
870
  const kept = { "Cache-Control": ATTACHMENT_CACHE, "Vary": "Cookie", "Content-Disposition": disposition(file.name) };
856
871
  if (thumbnail) return c.body(web(thumbnail.stream), 200, { ...kept, "Content-Type": "image/webp", "Content-Length": String(thumbnail.size) });
@@ -858,13 +873,13 @@ function attachmentRoutes(chats) {
858
873
  });
859
874
  routes.get("/:id/run", (c) => {
860
875
  const file = chats.attachments.find(c.get("actorId"), c.req.param("id"));
861
- if (!file) throw new HTTPException8(404, { message: "Attachment not found" });
862
- if (!/\.html?$/i.test(file.name) && file.mimeType !== "text/html") throw new HTTPException8(415, { message: "Only HTML attachments can run" });
876
+ if (!file) throw new HTTPException9(404, { message: "Attachment not found" });
877
+ if (!/\.html?$/i.test(file.name) && file.mimeType !== "text/html") throw new HTTPException9(415, { message: "Only HTML attachments can run" });
863
878
  c.set("sandboxedDocument", true);
864
879
  return c.body(web(chats.attachments.stream(file)), 200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": String(file.size) });
865
880
  });
866
881
  routes.delete("/:id", async (c) => {
867
- if (!await chats.attachments.removePending(c.get("actorId"), c.req.param("id"))) throw new HTTPException8(404, { message: "Pending attachment not found" });
882
+ if (!await chats.attachments.removePending(c.get("actorId"), c.req.param("id"))) throw new HTTPException9(404, { message: "Pending attachment not found" });
868
883
  return c.json({ ok: true });
869
884
  });
870
885
  return routes;
@@ -873,10 +888,10 @@ async function* idle(body, signal) {
873
888
  const reader = body.getReader();
874
889
  try {
875
890
  for (; ; ) {
876
- if (signal.aborted) throw new HTTPException8(400, { message: "Upload cancelled" });
891
+ if (signal.aborted) throw new HTTPException9(400, { message: "Upload cancelled" });
877
892
  let timer;
878
893
  const stalled = new Promise((_, reject) => {
879
- timer = setTimeout(() => reject(new HTTPException8(408, { message: "Upload stalled" })), UPLOAD_IDLE_MS);
894
+ timer = setTimeout(() => reject(new HTTPException9(408, { message: "Upload stalled" })), UPLOAD_IDLE_MS);
880
895
  });
881
896
  try {
882
897
  const { done: done2, value: value2 } = await Promise.race([reader.read(), stalled]);
@@ -894,15 +909,15 @@ var UPLOAD_IDLE_MS = 6e4;
894
909
  var web = (stream) => Readable.toWeb(stream);
895
910
 
896
911
  // src/server/api/routes/models.ts
897
- import { Hono as Hono6 } from "hono";
912
+ import { Hono as Hono7 } from "hono";
898
913
  function modelRoutes(models) {
899
- const routes = new Hono6();
914
+ const routes = new Hono7();
900
915
  routes.get("/model-providers", (c) => c.json({ providers: models.providers() }));
901
916
  routes.get("/model-providers/:provider/models", (c) => c.json({ models: models.builtinModels(c.req.param("provider")) }));
902
917
  routes.get("/model-options", (c) => c.json({ connections: models.options() }));
903
918
  routes.post("/model-autoconfig", jsonBody, async (c) => c.json(models.autoconfigure(await readJson(c))));
904
919
  routes.post("/model-discovery", jsonBody, async (c) => c.json({ models: await models.discover(await readJson(c), c.req.raw.signal) }));
905
- const connections = new Hono6();
920
+ const connections = new Hono7();
906
921
  connections.get("/", (c) => c.json({ connections: models.list() }));
907
922
  connections.post("/", jsonBody, async (c) => c.json(models.create(await readJson(c)), 201));
908
923
  connections.put("/:id", jsonBody, async (c) => c.json(models.update(c.req.param("id"), await readJson(c))));
@@ -939,7 +954,7 @@ function modelRoutes(models) {
939
954
  }
940
955
 
941
956
  // src/server/api/routes/events.ts
942
- import { Hono as Hono7 } from "hono";
957
+ import { Hono as Hono8 } from "hono";
943
958
 
944
959
  // src/server/api/event-stream.ts
945
960
  function eventStream(c, authenticated, open2) {
@@ -999,7 +1014,7 @@ data: ${JSON.stringify(data)}
999
1014
 
1000
1015
  // src/server/api/routes/events.ts
1001
1016
  function eventRoutes({ events, account, chats, bots }) {
1002
- const routes = new Hono7();
1017
+ const routes = new Hono8();
1003
1018
  routes.get("/events", (c) => {
1004
1019
  const actorId = c.get("actorId"), token = c.get("sessionToken");
1005
1020
  const after2 = c.req.header("Last-Event-ID") ?? c.req.query("after");
@@ -1064,14 +1079,14 @@ function once(entries2) {
1064
1079
  }
1065
1080
 
1066
1081
  // src/server/api/routes/channels.ts
1067
- import { Hono as Hono8 } from "hono";
1068
- import { HTTPException as HTTPException9 } from "hono/http-exception";
1082
+ import { Hono as Hono9 } from "hono";
1083
+ import { HTTPException as HTTPException10 } from "hono/http-exception";
1069
1084
  function channelRoutes({ chats }) {
1070
- const routes = new Hono8();
1085
+ const routes = new Hono9();
1071
1086
  const channels = chats.channels;
1072
1087
  const chat = (actorId, id) => {
1073
1088
  const found = chats.get(actorId, id);
1074
- if (!found) throw new HTTPException9(404, { message: "Chat not found" });
1089
+ if (!found) throw new HTTPException10(404, { message: "Chat not found" });
1075
1090
  return chatView(found, (member) => chats.member(member));
1076
1091
  };
1077
1092
  routes.get("/members", (c) => c.json({ members: channels.everyone(c.get("actorId")) }));
@@ -1094,7 +1109,7 @@ function channelRoutes({ chats }) {
1094
1109
  routes.post("/sections", jsonBody, async (c) => c.json(channels.createSection(c.get("actorId"), await readJson(c)), 201));
1095
1110
  routes.patch("/sections/:id", jsonBody, async (c) => c.json(channels.updateSection(c.get("actorId"), c.req.param("id"), await readJson(c))));
1096
1111
  routes.delete("/sections/:id", (c) => {
1097
- if (!channels.deleteSection(c.get("actorId"), c.req.param("id"))) throw new HTTPException9(404, { message: "Section not found" });
1112
+ if (!channels.deleteSection(c.get("actorId"), c.req.param("id"))) throw new HTTPException10(404, { message: "Section not found" });
1098
1113
  return c.json({ ok: true });
1099
1114
  });
1100
1115
  routes.post("/channels", jsonBody, async (c) => {
@@ -1110,7 +1125,7 @@ function channelRoutes({ chats }) {
1110
1125
  routes.get("/chats/:id", (c) => c.json(chat(c.get("actorId"), c.req.param("id"))));
1111
1126
  routes.get("/messages/:id", (c) => {
1112
1127
  const found = chats.message(c.get("actorId"), c.req.param("id"));
1113
- if (!found) throw new HTTPException9(404, { message: "Message not found" });
1128
+ if (!found) throw new HTTPException10(404, { message: "Message not found" });
1114
1129
  return c.json(messageView(found));
1115
1130
  });
1116
1131
  routes.post("/messages/:id/thread", (c) => {
@@ -1149,9 +1164,9 @@ function channelRoutes({ chats }) {
1149
1164
  }
1150
1165
 
1151
1166
  // src/server/api/routes/live.ts
1152
- import { Hono as Hono9 } from "hono";
1167
+ import { Hono as Hono10 } from "hono";
1153
1168
  function liveRoutes({ account, bots }) {
1154
- const routes = new Hono9();
1169
+ const routes = new Hono10();
1155
1170
  routes.get("/bots/:id/live", (c) => {
1156
1171
  const token = c.get("sessionToken"), live = bots.live(c.req.param("id"));
1157
1172
  return eventStream(c, () => account.authenticated(token), ({ send, close, signedIn }) => {
@@ -1163,34 +1178,34 @@ function liveRoutes({ account, bots }) {
1163
1178
  }
1164
1179
 
1165
1180
  // src/server/api/routes/connection.ts
1166
- import { Hono as Hono10 } from "hono";
1167
- import { HTTPException as HTTPException10 } from "hono/http-exception";
1181
+ import { Hono as Hono11 } from "hono";
1182
+ import { HTTPException as HTTPException11 } from "hono/http-exception";
1168
1183
  function rootCertificateRoute(connection) {
1169
- const routes = new Hono10();
1184
+ const routes = new Hono11();
1170
1185
  routes.get("/connection/root.crt", (c) => {
1171
1186
  const der = connection.rootCertificate();
1172
- if (!der) throw new HTTPException10(404, { message: "Jarvy serves HTTPS only when it listens beyond this machine" });
1187
+ if (!der) throw new HTTPException11(404, { message: "Jarvy serves HTTPS only when it listens beyond this machine" });
1173
1188
  return c.body(new Uint8Array(der), 200, { "Content-Type": "application/x-x509-ca-cert", "Content-Disposition": 'attachment; filename="jarvy-root.crt"' });
1174
1189
  });
1175
1190
  return routes;
1176
1191
  }
1177
1192
  function connectionRoutes(connection) {
1178
- const routes = new Hono10();
1193
+ const routes = new Hono11();
1179
1194
  routes.get("/connection", (c) => c.json(connection.info()));
1180
1195
  routes.put("/connection", jsonBody, async (c) => {
1181
1196
  const input = await readJson(c);
1182
1197
  if (input.ports !== void 0) return c.json(connection.setPortRange(input.ports));
1183
- if (typeof input.allowHttp !== "boolean") throw new HTTPException10(400, { message: "allowHttp must be true or false" });
1198
+ if (typeof input.allowHttp !== "boolean") throw new HTTPException11(400, { message: "allowHttp must be true or false" });
1184
1199
  return c.json(connection.setAllowHttp(input.allowHttp));
1185
1200
  });
1186
1201
  return routes;
1187
1202
  }
1188
1203
 
1189
1204
  // src/server/api/routes/secrets.ts
1190
- import { Hono as Hono11 } from "hono";
1191
- import { HTTPException as HTTPException11 } from "hono/http-exception";
1205
+ import { Hono as Hono12 } from "hono";
1206
+ import { HTTPException as HTTPException12 } from "hono/http-exception";
1192
1207
  function secretRoutes(secrets) {
1193
- const routes = new Hono11();
1208
+ const routes = new Hono12();
1194
1209
  routes.get("/", (c) => c.json(secrets.list()));
1195
1210
  routes.post("/", jsonBody, async (c) => {
1196
1211
  const input = await readJson(c);
@@ -1206,7 +1221,7 @@ function secretRoutes(secrets) {
1206
1221
  });
1207
1222
  routes.put("/:id/grants/:botId", jsonBody, async (c) => {
1208
1223
  const input = await readJson(c);
1209
- if (typeof input.granted !== "boolean") throw new HTTPException11(400, { message: "granted must be true or false" });
1224
+ if (typeof input.granted !== "boolean") throw new HTTPException12(400, { message: "granted must be true or false" });
1210
1225
  return c.json(secrets.grant(c.req.param("id"), c.req.param("botId"), input.granted));
1211
1226
  });
1212
1227
  routes.get("/:id/uses", (c) => c.json({ uses: secrets.uses(c.req.param("id")) }));
@@ -1218,10 +1233,10 @@ function secretRoutes(secrets) {
1218
1233
  }
1219
1234
 
1220
1235
  // src/server/api/routes/environments.ts
1221
- import { Hono as Hono12 } from "hono";
1222
- import { HTTPException as HTTPException12 } from "hono/http-exception";
1236
+ import { Hono as Hono13 } from "hono";
1237
+ import { HTTPException as HTTPException13 } from "hono/http-exception";
1223
1238
  function environmentRoutes(bots) {
1224
- const routes = new Hono12(), machines = bots.machines;
1239
+ const routes = new Hono13(), machines = bots.machines;
1225
1240
  routes.get("/", (c) => c.json({ machines: machines.list() }));
1226
1241
  routes.post("/scan", jsonBody, async (c) => {
1227
1242
  const input = await readJson(c);
@@ -1261,7 +1276,7 @@ function environmentRoutes(bots) {
1261
1276
  });
1262
1277
  routes.put("/:id/grants/:botId", jsonBody, async (c) => {
1263
1278
  const input = await readJson(c);
1264
- if (typeof input.granted !== "boolean") throw new HTTPException12(400, { message: "granted must be true or false" });
1279
+ if (typeof input.granted !== "boolean") throw new HTTPException13(400, { message: "granted must be true or false" });
1265
1280
  bots.grantMachine(c.req.param("botId"), c.req.param("id"), input.granted);
1266
1281
  return c.json(machines.get(c.req.param("id")));
1267
1282
  });
@@ -1279,14 +1294,14 @@ function environmentRoutes(bots) {
1279
1294
  function hostKeys(value2) {
1280
1295
  const keys = value2;
1281
1296
  const strings = (list) => Array.isArray(list) && list.length > 0 && list.length <= 20 && list.every((item) => typeof item === "string" && item.length <= 2e3);
1282
- if (!keys || !strings(keys.keys) || !strings(keys.fingerprints)) throw new HTTPException12(400, { message: "hostKeys must be what the scan returned" });
1297
+ if (!keys || !strings(keys.keys) || !strings(keys.fingerprints)) throw new HTTPException13(400, { message: "hostKeys must be what the scan returned" });
1283
1298
  return { keys: keys.keys, fingerprints: keys.fingerprints };
1284
1299
  }
1285
1300
 
1286
1301
  // src/server/api/routes/tasks.ts
1287
- import { Hono as Hono13 } from "hono";
1302
+ import { Hono as Hono14 } from "hono";
1288
1303
  function taskRoutes(services) {
1289
- const routes = new Hono13();
1304
+ const routes = new Hono14();
1290
1305
  const bot = (id) => {
1291
1306
  services.bots.describe(id);
1292
1307
  return id;
@@ -1303,10 +1318,10 @@ function taskRoutes(services) {
1303
1318
  }
1304
1319
 
1305
1320
  // src/server/api/routes/ports.ts
1306
- import { Hono as Hono14 } from "hono";
1307
- import { HTTPException as HTTPException13 } from "hono/http-exception";
1321
+ import { Hono as Hono15 } from "hono";
1322
+ import { HTTPException as HTTPException14 } from "hono/http-exception";
1308
1323
  function portRoutes(services) {
1309
- const routes = new Hono14();
1324
+ const routes = new Hono15();
1310
1325
  const bot = (id) => {
1311
1326
  services.bots.describe(id);
1312
1327
  return id;
@@ -1314,7 +1329,7 @@ function portRoutes(services) {
1314
1329
  routes.get("/bots/:id/ports", async (c) => c.json({ ports: await services.bots.ports.list(bot(c.req.param("id"))) }));
1315
1330
  routes.delete("/bots/:id/ports/:port", (c) => {
1316
1331
  const port = Number(c.req.param("port"));
1317
- if (!Number.isInteger(port)) throw new HTTPException13(400, { message: "port must be a number" });
1332
+ if (!Number.isInteger(port)) throw new HTTPException14(400, { message: "port must be a number" });
1318
1333
  services.bots.ports.unpublish(bot(c.req.param("id")), port);
1319
1334
  return c.json({ ok: true });
1320
1335
  });
@@ -1323,15 +1338,16 @@ function portRoutes(services) {
1323
1338
 
1324
1339
  // src/server/api/app.ts
1325
1340
  function createHttpApp(services, webRoot) {
1326
- const app = new Hono15();
1341
+ const app = new Hono16();
1327
1342
  app.use("*", headers);
1328
1343
  app.onError(handleError);
1329
- const api = new Hono15();
1344
+ const api = new Hono16();
1330
1345
  api.use("*", apiSecurity);
1331
1346
  api.route("/", rootCertificateRoute(services.connection));
1332
1347
  installAuthentication(api, services.account);
1333
1348
  api.route("/", taskRoutes(services));
1334
1349
  api.route("/", portRoutes(services));
1350
+ api.route("/", usageRoutes(services.bots));
1335
1351
  api.route("/bots", botRoutes(services.bots));
1336
1352
  api.route("/", channelRoutes(services));
1337
1353
  api.route("/chats", chatRoutes(services));
@@ -1343,7 +1359,7 @@ function createHttpApp(services, webRoot) {
1343
1359
  api.route("/secrets", secretRoutes(services.secrets));
1344
1360
  api.route("/environments", environmentRoutes(services.bots));
1345
1361
  api.all("*", () => {
1346
- throw new HTTPException14(404, { message: "API route not found" });
1362
+ throw new HTTPException15(404, { message: "API route not found" });
1347
1363
  });
1348
1364
  app.route("/api", api);
1349
1365
  app.get("*", serveStatic({ root: webRoot, onFound: (path, c) => {
@@ -1353,8 +1369,8 @@ function createHttpApp(services, webRoot) {
1353
1369
  c.header("Cache-Control", "no-store");
1354
1370
  } }));
1355
1371
  app.all("*", (c) => {
1356
- if (c.req.method !== "GET" && c.req.method !== "HEAD") throw new HTTPException14(405, { message: "Method not allowed" });
1357
- throw new HTTPException14(404, { message: "Web assets missing; run npm run build" });
1372
+ if (c.req.method !== "GET" && c.req.method !== "HEAD") throw new HTTPException15(405, { message: "Method not allowed" });
1373
+ throw new HTTPException15(404, { message: "Web assets missing; run npm run build" });
1358
1374
  });
1359
1375
  return app;
1360
1376
  }
@@ -3537,6 +3553,44 @@ var QuoteRepository = class {
3537
3553
  }
3538
3554
  };
3539
3555
 
3556
+ // src/contract/message-refs.ts
3557
+ var MESSAGE_ID = /(?<![A-Za-z0-9_/#.@-])m\d{1,9}(?![A-Za-z0-9_-]|\.[A-Za-z0-9])/g;
3558
+ var MESSAGE_REFS_MAX = 20;
3559
+ function messageIds(text5) {
3560
+ const ids = [];
3561
+ for (const [id] of text5.matchAll(MESSAGE_ID)) if (!ids.includes(id) && ids.push(id) >= MESSAGE_REFS_MAX) break;
3562
+ return ids;
3563
+ }
3564
+
3565
+ // src/server/infra/storage/message-ref-repository.ts
3566
+ var MessageRefRepository = class {
3567
+ constructor(db, quotes) {
3568
+ this.db = db;
3569
+ this.quotes = quotes;
3570
+ }
3571
+ of(readerId, messageId, content2) {
3572
+ const ids = messageIds(content2).filter((id) => id !== messageId);
3573
+ if (!ids.length) return [];
3574
+ const rows3 = this.db.prepare(`SELECT m.id,m.sender_id AS senderId,m.content,m.created_at AS createdAt,c.id AS chatId,c.type,p.title AS parentTitle,
3575
+ CASE WHEN c.type='dm' THEN COALESCE((SELECT group_concat(b.name,' \xB7 ') FROM chat_members d JOIN bots b ON b.id=d.member_id WHERE d.chat_id=c.id),c.title) ELSE c.title END AS title
3576
+ FROM messages m JOIN chats c ON c.id=m.chat_id LEFT JOIN chats p ON p.id=c.parent_id
3577
+ WHERE m.id IN (${ids.map(() => "?").join(",")}) AND (EXISTS (SELECT 1 FROM chat_members cm WHERE cm.chat_id=COALESCE(c.parent_id,c.id)
3578
+ AND cm.member_id=? AND cm.can_read=1) OR (c.type='dm' AND c.owner_id=?))`).all(...ids, readerId, readerId);
3579
+ const found = new Map(rows3.map((row2) => [row2.id, row2]));
3580
+ return ids.flatMap((id) => {
3581
+ const row2 = found.get(id);
3582
+ return row2 ? [{
3583
+ id,
3584
+ senderId: row2.senderId,
3585
+ content: clipMarked(row2.content, 200),
3586
+ quotes: this.quotes.of(id),
3587
+ createdAt: row2.createdAt,
3588
+ chat: { id: row2.chatId, type: row2.type, title: row2.title, parentTitle: row2.parentTitle }
3589
+ }] : [];
3590
+ });
3591
+ }
3592
+ };
3593
+
3540
3594
  // src/server/infra/storage/chat-repository.ts
3541
3595
  var MESSAGE_COLUMNS = "id,chat_id AS chatId,sequence,sender_id AS senderId,content,created_at AS createdAt,history_id AS historyId,tool_call_id AS toolCallId,question,echo_of AS echoOf,reply_to AS replyTo,folded_at AS foldedAt";
3542
3596
  var CHAT_COLUMNS = `c.id,c.type,c.title,c.owner_id AS ownerId,c.created_at AS createdAt,c.updated_at AS updatedAt,
@@ -3552,6 +3606,7 @@ var ChatRepository = class {
3552
3606
  this.threads = new ThreadRepository(db, this);
3553
3607
  this.interactions = new InteractionRepository(db, this);
3554
3608
  this.quotes = new QuoteRepository(db);
3609
+ this.refs = new MessageRefRepository(db, this.quotes);
3555
3610
  this.inbox = new InboxRepository(db, this);
3556
3611
  }
3557
3612
  /** Sections, channels, notes, read positions and threads share this connection. */
@@ -3559,6 +3614,7 @@ var ChatRepository = class {
3559
3614
  threads;
3560
3615
  interactions;
3561
3616
  quotes;
3617
+ refs;
3562
3618
  /** Every delivery (A41, A61): the one place inbox SQL lives. */
3563
3619
  inbox;
3564
3620
  member(id) {
@@ -3676,14 +3732,16 @@ var ChatRepository = class {
3676
3732
  messagesBefore(actorId, chatId, before, limit2) {
3677
3733
  this.assertAccess(actorId, chatId);
3678
3734
  const rows3 = this.db.prepare(`SELECT ${MESSAGE_COLUMNS} FROM messages WHERE chat_id=? AND sequence<? ORDER BY sequence DESC LIMIT ?`).all(chatId, before, limit2);
3679
- return rows3.reverse().map((row2) => this.messageFromRow(row2));
3735
+ const reader = this.reader(actorId);
3736
+ return rows3.reverse().map((row2) => this.messageFromRow(row2, reader));
3680
3737
  }
3681
3738
  /** Exactly the messages counted as unread for this member (same rule as `unread`), oldest first. */
3682
3739
  unreadMessages(memberId, chatId, limit2) {
3683
3740
  this.assertAccess(memberId, chatId);
3684
3741
  if (this.db.prepare("SELECT type FROM chats WHERE id=?").get(chatId).type === "thread" && !this.threads.isFollowing(memberId, chatId)) return [];
3685
3742
  const rows3 = this.db.prepare(`SELECT ${MESSAGE_COLUMNS.split(",").map((column) => `m.${column}`).join(",")} ${unreadIn(":chat")} ORDER BY m.sequence LIMIT :limit`).all({ chat: chatId, member: memberId, limit: limit2 });
3686
- return rows3.map((row2) => this.messageFromRow(row2));
3743
+ const reader = this.reader(memberId);
3744
+ return rows3.map((row2) => this.messageFromRow(row2, reader));
3687
3745
  }
3688
3746
  /** Search every chat the member can read: its DMs and channels and their threads (newest first). `within` keeps
3689
3747
  * one chat, a channel with its threads; `sender` keeps one member's messages. */
@@ -3692,7 +3750,8 @@ var ChatRepository = class {
3692
3750
  const rows3 = this.db.prepare(`SELECT ${MESSAGE_COLUMNS.split(",").map((column) => `m.${column}`).join(",")} FROM messages m JOIN chats c ON c.id=m.chat_id
3693
3751
  JOIN chat_members cm ON cm.chat_id=COALESCE(c.parent_id,c.id) AND cm.member_id=? AND cm.can_read=1
3694
3752
  WHERE instr(lower(m.content),lower(?))>0 ${scope} ORDER BY m.position DESC LIMIT ?`).all(actorId, query, ...within ? [within, within] : [], ...sender ? [sender] : [], limit2);
3695
- return rows3.map((row2) => this.messageFromRow(row2));
3753
+ const reader = this.reader(actorId);
3754
+ return rows3.map((row2) => this.messageFromRow(row2, reader));
3696
3755
  }
3697
3756
  /** Channels and threads the member can read whose title, topic or notice / summary contains the query (newest first). */
3698
3757
  searchChatIds(actorId, query, limit2) {
@@ -3704,17 +3763,19 @@ var ChatRepository = class {
3704
3763
  messages(actorId, chatId, after2 = 0, limit2 = 1e3) {
3705
3764
  this.assertAccess(actorId, chatId);
3706
3765
  const rows3 = this.db.prepare(`SELECT ${MESSAGE_COLUMNS} FROM messages WHERE chat_id=? AND sequence>? ORDER BY sequence LIMIT ?`).all(chatId, after2, limit2);
3707
- return rows3.map((row2) => this.messageFromRow(row2));
3766
+ const reader = this.reader(actorId);
3767
+ return rows3.map((row2) => this.messageFromRow(row2, reader));
3708
3768
  }
3709
3769
  message(actorId, id) {
3710
3770
  const row2 = this.db.prepare(`SELECT ${MESSAGE_COLUMNS} FROM messages WHERE id=?`).get(id);
3711
- return row2 && this.canAccess(actorId, row2.chatId) ? this.messageFromRow(row2) : null;
3771
+ return row2 && this.canAccess(actorId, row2.chatId) ? this.messageFromRow(row2, this.reader(actorId)) : null;
3712
3772
  }
3713
3773
  search(actorId, chatId, query, limit2, sender) {
3714
3774
  this.assertAccess(actorId, chatId);
3715
3775
  const rows3 = this.db.prepare(`SELECT ${MESSAGE_COLUMNS} FROM messages WHERE chat_id=? AND instr(lower(content),lower(?))>0 ${sender ? "AND sender_id=?" : ""}
3716
3776
  ORDER BY sequence DESC LIMIT ?`).all(chatId, query, ...sender ? [sender] : [], limit2);
3717
- return rows3.map((row2) => this.messageFromRow(row2));
3777
+ const reader = this.reader(actorId);
3778
+ return rows3.map((row2) => this.messageFromRow(row2, reader));
3718
3779
  }
3719
3780
  sentActivity(actorId, senderId, before, limit2) {
3720
3781
  const condition = !before ? "" : before.kind === "chat" ? "AND (m.created_at<? OR (m.created_at=? AND m.id<?))" : "AND m.created_at<=?";
@@ -3727,7 +3788,11 @@ var ChatRepository = class {
3727
3788
  WHERE m.sender_id=? ${condition} ORDER BY m.created_at DESC,m.id DESC LIMIT ?`).all(actorId, senderId, ...cursor2, limit2);
3728
3789
  return rows3.map(({ historyId, toolCallId, ...row2 }) => ({ ...row2, source: historyId === null ? null : { historyId, toolCallId } }));
3729
3790
  }
3730
- messageFromRow(row2) {
3791
+ /** Who reads the snapshots: a person gets the messages a text names by ID (A82); a Bot reads IDs itself. */
3792
+ reader(actorId) {
3793
+ return this.member(actorId)?.kind === "bot" ? null : actorId;
3794
+ }
3795
+ messageFromRow(row2, reader) {
3731
3796
  const attachments = this.db.prepare("SELECT id,name,mime_type AS mimeType,size FROM attachments WHERE message_id=? ORDER BY created_at,rowid").all(row2.id);
3732
3797
  return {
3733
3798
  id: row2.id,
@@ -3745,7 +3810,8 @@ var ChatRepository = class {
3745
3810
  replyTo: row2.replyTo === null ? null : this.quote(row2.replyTo),
3746
3811
  reactions: this.interactions.reactions(row2.id),
3747
3812
  quotes: this.quotes.of(row2.id),
3748
- folded: row2.foldedAt !== null
3813
+ folded: row2.foldedAt !== null,
3814
+ refs: reader ? this.refs.of(reader, row2.id, row2.content) : []
3749
3815
  };
3750
3816
  }
3751
3817
  /** What a reply shows of the message it answers: who wrote it and the start of its content, with its quotes ("" is attachments only). */
@@ -3761,7 +3827,7 @@ var ChatRepository = class {
3761
3827
  const prior = this.db.prepare(`SELECT ${MESSAGE_COLUMNS},request_hash AS requestHash FROM messages WHERE sender_id=? AND client_key=?`).get(actorId, draft.clientMessageId);
3762
3828
  if (prior) {
3763
3829
  if (prior.requestHash !== requestHash) throw new ChatError(409, "Message key already used with different content");
3764
- const message2 = this.messageFromRow(prior);
3830
+ const message2 = this.messageFromRow(prior, this.reader(actorId));
3765
3831
  return { message: message2, duplicate: true };
3766
3832
  }
3767
3833
  }
@@ -3807,13 +3873,13 @@ var ChatRepository = class {
3807
3873
  echoOf: chatId,
3808
3874
  replyTo: null,
3809
3875
  foldedAt: null
3810
- });
3876
+ }, this.reader(actorId));
3811
3877
  }
3812
3878
  }
3813
3879
  const file = this.db.prepare("SELECT name FROM attachments WHERE message_id=? ORDER BY created_at,rowid LIMIT 1").get(id);
3814
3880
  const title = draft.content ? previewQuotes(draft.content, draft.quotes ?? []).slice(0, 46).replace(/\s+/g, " ") : file?.name.slice(0, 46) ?? "";
3815
3881
  this.db.prepare("UPDATE chats SET title=CASE WHEN title='' AND ?=1 THEN ? ELSE title END,updated_at=? WHERE id=?").run(sequence, title, createdAt, chatId);
3816
- const message = this.messageFromRow({ id, chatId, sequence, senderId: actorId, content: draft.content, createdAt, historyId: draft.source?.historyId ?? null, toolCallId: draft.source?.toolCallId ?? null, question, echoOf: null, replyTo: draft.replyTo ?? null, foldedAt: null });
3882
+ const message = this.messageFromRow({ id, chatId, sequence, senderId: actorId, content: draft.content, createdAt, historyId: draft.source?.historyId ?? null, toolCallId: draft.source?.toolCallId ?? null, question, echoOf: null, replyTo: draft.replyTo ?? null, foldedAt: null }, this.reader(actorId));
3817
3883
  return { message, duplicate: false, ...echo ? { echo } : {} };
3818
3884
  });
3819
3885
  }
@@ -5495,11 +5561,11 @@ function mentionedMembers(source2, candidates2) {
5495
5561
  function messageTargets({ dm, sender, members, mentioned, replied, subscribers }) {
5496
5562
  if (dm) return members.filter((member) => member.id !== sender.id).map((member) => ({ member, reason: "dm" }));
5497
5563
  const targets = mentioned.filter((member) => member.id !== sender.id).map((member) => ({ member, reason: "mention" }));
5498
- const add = (member, reason) => {
5564
+ const add2 = (member, reason) => {
5499
5565
  if (member.id !== sender.id && !targets.some((target3) => target3.member.id === member.id)) targets.push({ member, reason });
5500
5566
  };
5501
- if (replied && members.some((member) => member.id === replied.id)) add(replied, "reply");
5502
- for (const member of members) if (subscribers.includes(member.id)) add(member, "subscription");
5567
+ if (replied && members.some((member) => member.id === replied.id)) add2(replied, "reply");
5568
+ for (const member of members) if (subscribers.includes(member.id)) add2(member, "subscription");
5503
5569
  return targets;
5504
5570
  }
5505
5571
  function echoTargets({ sender, members, subscribers, reached }) {
@@ -6387,9 +6453,9 @@ var ChatFiles = class {
6387
6453
  constructor(chats) {
6388
6454
  this.chats = chats;
6389
6455
  }
6390
- async envelope(botId, messageIds, signal) {
6456
+ async envelope(botId, messageIds2, signal) {
6391
6457
  const output = [];
6392
- for (const id of messageIds) {
6458
+ for (const id of messageIds2) {
6393
6459
  signal?.throwIfAborted();
6394
6460
  const message = this.chats.message(botId, id);
6395
6461
  if (!message) throw new ChatError(404, "Message not found");
@@ -6505,6 +6571,32 @@ function activityPage(messages, history, limit2) {
6505
6571
  return { items, nextBefore: candidates2.length > limit2 ? position : null };
6506
6572
  }
6507
6573
 
6574
+ // src/server/service/bot/usage.ts
6575
+ var empty = () => ({ calls: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: null });
6576
+ function add(into, row2) {
6577
+ into.calls += row2.calls;
6578
+ into.input += row2.input;
6579
+ into.output += row2.output;
6580
+ into.cacheRead += row2.cacheRead;
6581
+ into.cacheWrite += row2.cacheWrite;
6582
+ if (row2.cost !== null) into.cost = (into.cost ?? 0) + row2.cost;
6583
+ }
6584
+ var costly = (a, b) => (b.cost ?? 0) - (a.cost ?? 0) || b.calls - a.calls;
6585
+ function usageOverview(since2, perBot) {
6586
+ const models = /* @__PURE__ */ new Map(), bots = [];
6587
+ for (const [botId, rows3] of perBot) {
6588
+ if (!rows3.length) continue;
6589
+ const bot = { botId, ...empty() };
6590
+ for (const { provider, model, ...row2 } of rows3) {
6591
+ const key = `${provider}\0${model}`;
6592
+ add(models.get(key) ?? models.set(key, { provider, model, ...empty() }).get(key), row2);
6593
+ add(bot, row2);
6594
+ }
6595
+ bots.push(bot);
6596
+ }
6597
+ return { since: since2, models: [...models.values()].sort(costly), bots: bots.sort(costly) };
6598
+ }
6599
+
6508
6600
  // src/server/service/bot/service.ts
6509
6601
  import { dirname as dirname10, join as join16 } from "node:path";
6510
6602
  import { rm as rm6 } from "node:fs/promises";
@@ -8893,13 +8985,13 @@ var HistoryRepository = class {
8893
8985
  });
8894
8986
  }
8895
8987
  /** Model calls since a time, per provider and model: every assistant record with usage is one call. */
8896
- usage(since) {
8988
+ usage(since2) {
8897
8989
  const rows3 = this.db.prepare(`SELECT json_extract(model,'$.provider') AS provider,json_extract(model,'$.id') AS model,count(*) AS calls,
8898
8990
  COALESCE(SUM(json_extract(usage,'$.input_tokens')),0) AS input,COALESCE(SUM(json_extract(usage,'$.output_tokens')),0) AS output,
8899
8991
  COALESCE(SUM(json_extract(usage,'$.cache_read_tokens')),0) AS cacheRead,COALESCE(SUM(json_extract(usage,'$.cache_write_tokens')),0) AS cacheWrite,
8900
8992
  COALESCE(SUM(json_extract(usage,'$.cost.total')),0) AS cost,COALESCE(MAX(json_extract(usage,'$.cost.total')),0)>0 AS priced
8901
8993
  FROM history WHERE role='assistant' AND usage IS NOT NULL AND model IS NOT NULL AND timestamp>=?
8902
- GROUP BY 1,2 ORDER BY cost DESC,calls DESC`).all(since);
8994
+ GROUP BY 1,2 ORDER BY cost DESC,calls DESC`).all(since2);
8903
8995
  return rows3.map(({ priced, cost, ...row2 }) => ({ ...row2, cost: priced ? cost : null }));
8904
8996
  }
8905
8997
  decodeSummary(row2) {
@@ -8960,8 +9052,8 @@ var Memory = class {
8960
9052
  timeline(before, limit2) {
8961
9053
  return this.history().timeline(before, limit2);
8962
9054
  }
8963
- usage(since) {
8964
- return this.history().usage(since);
9055
+ usage(since2) {
9056
+ return this.history().usage(since2);
8965
9057
  }
8966
9058
  read(id) {
8967
9059
  const record3 = this.history().read(id);
@@ -11333,8 +11425,8 @@ var AgentOps = class {
11333
11425
  return this.bots.status(bot.id).status;
11334
11426
  }
11335
11427
  usage(bot, days) {
11336
- const since = Date.now() - days * 24 * 60 * 60 * 1e3;
11337
- return { since: new Date(since).toISOString(), models: this.bots.memory(bot.id).usage(since) };
11428
+ const since2 = Date.now() - days * 24 * 60 * 60 * 1e3;
11429
+ return { since: new Date(since2).toISOString(), models: this.bots.memory(bot.id).usage(since2) };
11338
11430
  }
11339
11431
  /** Deletions run as the owner, who has just confirmed them on a card. */
11340
11432
  async deleteBot(bot) {
@@ -11826,6 +11918,10 @@ var BotService = class {
11826
11918
  memory(id) {
11827
11919
  return this.get(id).memory;
11828
11920
  }
11921
+ /** Usage across every Bot since a time (A81), from each one's History. */
11922
+ usage(since2) {
11923
+ return usageOverview(since2, this.deps.store.bots.list().map((record3) => [record3.id, this.memory(record3.id).usage(since2)]));
11924
+ }
11829
11925
  /** A delivery reached a Bot (A41); the Bot responds to its urgency. */
11830
11926
  deliver(id, urgency) {
11831
11927
  if (this.closed || !this.deps.store.bots.get(id)) return;