@goodfish/jarvy 0.12.1 → 0.13.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.
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/server/cli.ts
4
- import { existsSync as existsSync5 } from "node:fs";
4
+ import { existsSync as existsSync6 } from "node:fs";
5
5
  import { createInterface } from "node:readline/promises";
6
- import { dirname as dirname11, join as join19 } from "node:path";
6
+ import { dirname as dirname12, join as join20 } from "node:path";
7
7
  import { fileURLToPath as fileURLToPath2 } from "node:url";
8
8
 
9
9
  // src/server/api/server.ts
@@ -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) => {
@@ -411,9 +426,13 @@ function botRoutes(bots) {
411
426
  return c.json(await bots.setComputerLimits(c.req.param("id"), { memory: input.memory, cpus: input.cpus }));
412
427
  });
413
428
  routes.get("/:id/computer/resources", async (c) => c.json(await bots.computerResources(c.req.param("id"))));
429
+ routes.put("/:id/computer/type", jsonBody, async (c) => {
430
+ const input = await readJson(c);
431
+ return c.json(await bots.setComputerType(c.req.param("id"), input.type));
432
+ });
414
433
  routes.post("/:id/computer/:action", async (c) => {
415
434
  const action = c.req.param("action");
416
- if (action !== "start" && action !== "stop" && action !== "reset") throw new HTTPException7(404, { message: "Not found" });
435
+ if (action !== "start" && action !== "stop" && action !== "reset" && action !== "restart") throw new HTTPException8(404, { message: "Not found" });
417
436
  return c.json(await bots.computer(c.req.param("id"), action));
418
437
  });
419
438
  routes.get("/:id", (c) => c.json(bots.describe(c.req.param("id"))));
@@ -466,8 +485,8 @@ function botRoutes(bots) {
466
485
 
467
486
  // src/server/api/routes/chats.ts
468
487
  import { Readable } from "node:stream";
469
- import { Hono as Hono5 } from "hono";
470
- import { HTTPException as HTTPException8 } from "hono/http-exception";
488
+ import { Hono as Hono6 } from "hono";
489
+ import { HTTPException as HTTPException9 } from "hono/http-exception";
471
490
 
472
491
  // src/server/api/views/download.ts
473
492
  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 +796,7 @@ var tooLarge = () => new ChatError(413, "File is too large", "file_too_large", {
777
796
 
778
797
  // src/server/api/routes/chats.ts
779
798
  function chatRoutes({ chats, bots }) {
780
- const routes = new Hono5();
799
+ const routes = new Hono6();
781
800
  const view = (chat) => chatView(chat, (id) => chats.member(id));
782
801
  routes.get("/", (c) => c.json({ chats: chats.list(c.get("actorId")).map(view), followed: chats.threads.followedSummary(c.get("actorId")) }));
783
802
  routes.post("/", jsonBody, async (c) => {
@@ -808,18 +827,18 @@ function chatRoutes({ chats, bots }) {
808
827
  try {
809
828
  name3 = decodeURIComponent(c.req.header("x-file-name") ?? "");
810
829
  } catch {
811
- throw new HTTPException8(400, { message: "Invalid filename" });
830
+ throw new HTTPException9(400, { message: "Invalid filename" });
812
831
  }
813
832
  const declared = Number(c.req.header("content-length") ?? NaN);
814
833
  if (declared > ATTACHMENT_MAX_BYTES) throw tooLarge();
815
834
  const body = c.req.raw.body;
816
- if (!body) throw new HTTPException8(400, { message: "Empty attachment" });
835
+ if (!body) throw new HTTPException9(400, { message: "Empty attachment" });
817
836
  const mime = (c.req.header("content-type") ?? "application/octet-stream").slice(0, 100);
818
837
  return c.json(await chats.attachments.upload(c.get("actorId"), c.req.param("id"), name3, mime, idle(body, c.req.raw.signal)), 201);
819
838
  });
820
839
  routes.delete("/:id", async (c) => {
821
840
  const id = c.req.param("id");
822
- if (!await chats.delete(c.get("actorId"), id)) throw new HTTPException8(404, { message: "Chat not found" });
841
+ if (!await chats.delete(c.get("actorId"), id)) throw new HTTPException9(404, { message: "Chat not found" });
823
842
  await bots.chatDeleted(id);
824
843
  return c.json({ ok: true });
825
844
  });
@@ -828,10 +847,10 @@ function chatRoutes({ chats, bots }) {
828
847
  var ATTACHMENT_CACHE = "private, max-age=31536000, immutable";
829
848
  var disposition = (name3) => `attachment; filename*=UTF-8''${encodeURIComponent(name3)}`;
830
849
  function attachmentRoutes(chats) {
831
- const routes = new Hono5();
850
+ const routes = new Hono6();
832
851
  routes.get("/:id", (c) => {
833
852
  const file = chats.attachments.find(c.get("actorId"), c.req.param("id"));
834
- if (!file) throw new HTTPException8(404, { message: "Attachment not found" });
853
+ if (!file) throw new HTTPException9(404, { message: "Attachment not found" });
835
854
  const size = file.size, range = byteRange(c.req.header("Range"), size);
836
855
  const headers2 = {
837
856
  "Content-Type": downloadType(file.mimeType),
@@ -850,7 +869,7 @@ function attachmentRoutes(chats) {
850
869
  });
851
870
  routes.get("/:id/thumb", async (c) => {
852
871
  const file = chats.attachments.find(c.get("actorId"), c.req.param("id"));
853
- if (!file) throw new HTTPException8(404, { message: "Attachment not found" });
872
+ if (!file) throw new HTTPException9(404, { message: "Attachment not found" });
854
873
  const thumbnail = await chats.attachments.thumbnail(file);
855
874
  const kept = { "Cache-Control": ATTACHMENT_CACHE, "Vary": "Cookie", "Content-Disposition": disposition(file.name) };
856
875
  if (thumbnail) return c.body(web(thumbnail.stream), 200, { ...kept, "Content-Type": "image/webp", "Content-Length": String(thumbnail.size) });
@@ -858,13 +877,13 @@ function attachmentRoutes(chats) {
858
877
  });
859
878
  routes.get("/:id/run", (c) => {
860
879
  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" });
880
+ if (!file) throw new HTTPException9(404, { message: "Attachment not found" });
881
+ if (!/\.html?$/i.test(file.name) && file.mimeType !== "text/html") throw new HTTPException9(415, { message: "Only HTML attachments can run" });
863
882
  c.set("sandboxedDocument", true);
864
883
  return c.body(web(chats.attachments.stream(file)), 200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": String(file.size) });
865
884
  });
866
885
  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" });
886
+ if (!await chats.attachments.removePending(c.get("actorId"), c.req.param("id"))) throw new HTTPException9(404, { message: "Pending attachment not found" });
868
887
  return c.json({ ok: true });
869
888
  });
870
889
  return routes;
@@ -873,10 +892,10 @@ async function* idle(body, signal) {
873
892
  const reader = body.getReader();
874
893
  try {
875
894
  for (; ; ) {
876
- if (signal.aborted) throw new HTTPException8(400, { message: "Upload cancelled" });
895
+ if (signal.aborted) throw new HTTPException9(400, { message: "Upload cancelled" });
877
896
  let timer;
878
897
  const stalled = new Promise((_, reject) => {
879
- timer = setTimeout(() => reject(new HTTPException8(408, { message: "Upload stalled" })), UPLOAD_IDLE_MS);
898
+ timer = setTimeout(() => reject(new HTTPException9(408, { message: "Upload stalled" })), UPLOAD_IDLE_MS);
880
899
  });
881
900
  try {
882
901
  const { done: done2, value: value2 } = await Promise.race([reader.read(), stalled]);
@@ -894,15 +913,15 @@ var UPLOAD_IDLE_MS = 6e4;
894
913
  var web = (stream) => Readable.toWeb(stream);
895
914
 
896
915
  // src/server/api/routes/models.ts
897
- import { Hono as Hono6 } from "hono";
916
+ import { Hono as Hono7 } from "hono";
898
917
  function modelRoutes(models) {
899
- const routes = new Hono6();
918
+ const routes = new Hono7();
900
919
  routes.get("/model-providers", (c) => c.json({ providers: models.providers() }));
901
920
  routes.get("/model-providers/:provider/models", (c) => c.json({ models: models.builtinModels(c.req.param("provider")) }));
902
921
  routes.get("/model-options", (c) => c.json({ connections: models.options() }));
903
922
  routes.post("/model-autoconfig", jsonBody, async (c) => c.json(models.autoconfigure(await readJson(c))));
904
923
  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();
924
+ const connections = new Hono7();
906
925
  connections.get("/", (c) => c.json({ connections: models.list() }));
907
926
  connections.post("/", jsonBody, async (c) => c.json(models.create(await readJson(c)), 201));
908
927
  connections.put("/:id", jsonBody, async (c) => c.json(models.update(c.req.param("id"), await readJson(c))));
@@ -939,10 +958,10 @@ function modelRoutes(models) {
939
958
  }
940
959
 
941
960
  // src/server/api/routes/events.ts
942
- import { Hono as Hono7 } from "hono";
961
+ import { Hono as Hono8 } from "hono";
943
962
 
944
963
  // src/server/api/event-stream.ts
945
- function eventStream(c, authenticated, open2) {
964
+ function eventStream(c, authenticated, open3) {
946
965
  const signal = c.req.raw.signal;
947
966
  let disconnect;
948
967
  const body = new ReadableStream({
@@ -961,7 +980,7 @@ data: ${JSON.stringify(data)}
961
980
 
962
981
  `));
963
982
  };
964
- const { unsubscribe, ready } = open2({
983
+ const { unsubscribe, ready } = open3({
965
984
  send,
966
985
  close: () => disconnect(),
967
986
  signedIn: (listener) => (...args) => {
@@ -999,7 +1018,7 @@ data: ${JSON.stringify(data)}
999
1018
 
1000
1019
  // src/server/api/routes/events.ts
1001
1020
  function eventRoutes({ events, account, chats, bots }) {
1002
- const routes = new Hono7();
1021
+ const routes = new Hono8();
1003
1022
  routes.get("/events", (c) => {
1004
1023
  const actorId = c.get("actorId"), token = c.get("sessionToken");
1005
1024
  const after2 = c.req.header("Last-Event-ID") ?? c.req.query("after");
@@ -1064,14 +1083,14 @@ function once(entries2) {
1064
1083
  }
1065
1084
 
1066
1085
  // src/server/api/routes/channels.ts
1067
- import { Hono as Hono8 } from "hono";
1068
- import { HTTPException as HTTPException9 } from "hono/http-exception";
1086
+ import { Hono as Hono9 } from "hono";
1087
+ import { HTTPException as HTTPException10 } from "hono/http-exception";
1069
1088
  function channelRoutes({ chats }) {
1070
- const routes = new Hono8();
1089
+ const routes = new Hono9();
1071
1090
  const channels = chats.channels;
1072
1091
  const chat = (actorId, id) => {
1073
1092
  const found = chats.get(actorId, id);
1074
- if (!found) throw new HTTPException9(404, { message: "Chat not found" });
1093
+ if (!found) throw new HTTPException10(404, { message: "Chat not found" });
1075
1094
  return chatView(found, (member) => chats.member(member));
1076
1095
  };
1077
1096
  routes.get("/members", (c) => c.json({ members: channels.everyone(c.get("actorId")) }));
@@ -1094,7 +1113,7 @@ function channelRoutes({ chats }) {
1094
1113
  routes.post("/sections", jsonBody, async (c) => c.json(channels.createSection(c.get("actorId"), await readJson(c)), 201));
1095
1114
  routes.patch("/sections/:id", jsonBody, async (c) => c.json(channels.updateSection(c.get("actorId"), c.req.param("id"), await readJson(c))));
1096
1115
  routes.delete("/sections/:id", (c) => {
1097
- if (!channels.deleteSection(c.get("actorId"), c.req.param("id"))) throw new HTTPException9(404, { message: "Section not found" });
1116
+ if (!channels.deleteSection(c.get("actorId"), c.req.param("id"))) throw new HTTPException10(404, { message: "Section not found" });
1098
1117
  return c.json({ ok: true });
1099
1118
  });
1100
1119
  routes.post("/channels", jsonBody, async (c) => {
@@ -1110,7 +1129,7 @@ function channelRoutes({ chats }) {
1110
1129
  routes.get("/chats/:id", (c) => c.json(chat(c.get("actorId"), c.req.param("id"))));
1111
1130
  routes.get("/messages/:id", (c) => {
1112
1131
  const found = chats.message(c.get("actorId"), c.req.param("id"));
1113
- if (!found) throw new HTTPException9(404, { message: "Message not found" });
1132
+ if (!found) throw new HTTPException10(404, { message: "Message not found" });
1114
1133
  return c.json(messageView(found));
1115
1134
  });
1116
1135
  routes.post("/messages/:id/thread", (c) => {
@@ -1149,9 +1168,9 @@ function channelRoutes({ chats }) {
1149
1168
  }
1150
1169
 
1151
1170
  // src/server/api/routes/live.ts
1152
- import { Hono as Hono9 } from "hono";
1171
+ import { Hono as Hono10 } from "hono";
1153
1172
  function liveRoutes({ account, bots }) {
1154
- const routes = new Hono9();
1173
+ const routes = new Hono10();
1155
1174
  routes.get("/bots/:id/live", (c) => {
1156
1175
  const token = c.get("sessionToken"), live = bots.live(c.req.param("id"));
1157
1176
  return eventStream(c, () => account.authenticated(token), ({ send, close, signedIn }) => {
@@ -1163,34 +1182,34 @@ function liveRoutes({ account, bots }) {
1163
1182
  }
1164
1183
 
1165
1184
  // src/server/api/routes/connection.ts
1166
- import { Hono as Hono10 } from "hono";
1167
- import { HTTPException as HTTPException10 } from "hono/http-exception";
1185
+ import { Hono as Hono11 } from "hono";
1186
+ import { HTTPException as HTTPException11 } from "hono/http-exception";
1168
1187
  function rootCertificateRoute(connection) {
1169
- const routes = new Hono10();
1188
+ const routes = new Hono11();
1170
1189
  routes.get("/connection/root.crt", (c) => {
1171
1190
  const der = connection.rootCertificate();
1172
- if (!der) throw new HTTPException10(404, { message: "Jarvy serves HTTPS only when it listens beyond this machine" });
1191
+ if (!der) throw new HTTPException11(404, { message: "Jarvy serves HTTPS only when it listens beyond this machine" });
1173
1192
  return c.body(new Uint8Array(der), 200, { "Content-Type": "application/x-x509-ca-cert", "Content-Disposition": 'attachment; filename="jarvy-root.crt"' });
1174
1193
  });
1175
1194
  return routes;
1176
1195
  }
1177
1196
  function connectionRoutes(connection) {
1178
- const routes = new Hono10();
1197
+ const routes = new Hono11();
1179
1198
  routes.get("/connection", (c) => c.json(connection.info()));
1180
1199
  routes.put("/connection", jsonBody, async (c) => {
1181
1200
  const input = await readJson(c);
1182
1201
  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" });
1202
+ if (typeof input.allowHttp !== "boolean") throw new HTTPException11(400, { message: "allowHttp must be true or false" });
1184
1203
  return c.json(connection.setAllowHttp(input.allowHttp));
1185
1204
  });
1186
1205
  return routes;
1187
1206
  }
1188
1207
 
1189
1208
  // src/server/api/routes/secrets.ts
1190
- import { Hono as Hono11 } from "hono";
1191
- import { HTTPException as HTTPException11 } from "hono/http-exception";
1209
+ import { Hono as Hono12 } from "hono";
1210
+ import { HTTPException as HTTPException12 } from "hono/http-exception";
1192
1211
  function secretRoutes(secrets) {
1193
- const routes = new Hono11();
1212
+ const routes = new Hono12();
1194
1213
  routes.get("/", (c) => c.json(secrets.list()));
1195
1214
  routes.post("/", jsonBody, async (c) => {
1196
1215
  const input = await readJson(c);
@@ -1206,7 +1225,7 @@ function secretRoutes(secrets) {
1206
1225
  });
1207
1226
  routes.put("/:id/grants/:botId", jsonBody, async (c) => {
1208
1227
  const input = await readJson(c);
1209
- if (typeof input.granted !== "boolean") throw new HTTPException11(400, { message: "granted must be true or false" });
1228
+ if (typeof input.granted !== "boolean") throw new HTTPException12(400, { message: "granted must be true or false" });
1210
1229
  return c.json(secrets.grant(c.req.param("id"), c.req.param("botId"), input.granted));
1211
1230
  });
1212
1231
  routes.get("/:id/uses", (c) => c.json({ uses: secrets.uses(c.req.param("id")) }));
@@ -1218,11 +1237,13 @@ function secretRoutes(secrets) {
1218
1237
  }
1219
1238
 
1220
1239
  // src/server/api/routes/environments.ts
1221
- import { Hono as Hono12 } from "hono";
1222
- import { HTTPException as HTTPException12 } from "hono/http-exception";
1240
+ import { Hono as Hono13 } from "hono";
1241
+ import { HTTPException as HTTPException13 } from "hono/http-exception";
1223
1242
  function environmentRoutes(bots) {
1224
- const routes = new Hono12(), machines = bots.machines;
1243
+ const routes = new Hono13(), machines = bots.machines;
1225
1244
  routes.get("/", (c) => c.json({ machines: machines.list() }));
1245
+ routes.get("/vm", (c) => c.json(bots.vmSupport()));
1246
+ routes.post("/vm/check", (c) => c.json(bots.vmSupport(true)));
1226
1247
  routes.post("/scan", jsonBody, async (c) => {
1227
1248
  const input = await readJson(c);
1228
1249
  return c.json(await machines.scan({ host: input.host, port: input.port, user: input.user }));
@@ -1261,7 +1282,7 @@ function environmentRoutes(bots) {
1261
1282
  });
1262
1283
  routes.put("/:id/grants/:botId", jsonBody, async (c) => {
1263
1284
  const input = await readJson(c);
1264
- if (typeof input.granted !== "boolean") throw new HTTPException12(400, { message: "granted must be true or false" });
1285
+ if (typeof input.granted !== "boolean") throw new HTTPException13(400, { message: "granted must be true or false" });
1265
1286
  bots.grantMachine(c.req.param("botId"), c.req.param("id"), input.granted);
1266
1287
  return c.json(machines.get(c.req.param("id")));
1267
1288
  });
@@ -1279,14 +1300,14 @@ function environmentRoutes(bots) {
1279
1300
  function hostKeys(value2) {
1280
1301
  const keys = value2;
1281
1302
  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" });
1303
+ if (!keys || !strings(keys.keys) || !strings(keys.fingerprints)) throw new HTTPException13(400, { message: "hostKeys must be what the scan returned" });
1283
1304
  return { keys: keys.keys, fingerprints: keys.fingerprints };
1284
1305
  }
1285
1306
 
1286
1307
  // src/server/api/routes/tasks.ts
1287
- import { Hono as Hono13 } from "hono";
1308
+ import { Hono as Hono14 } from "hono";
1288
1309
  function taskRoutes(services) {
1289
- const routes = new Hono13();
1310
+ const routes = new Hono14();
1290
1311
  const bot = (id) => {
1291
1312
  services.bots.describe(id);
1292
1313
  return id;
@@ -1303,10 +1324,10 @@ function taskRoutes(services) {
1303
1324
  }
1304
1325
 
1305
1326
  // src/server/api/routes/ports.ts
1306
- import { Hono as Hono14 } from "hono";
1307
- import { HTTPException as HTTPException13 } from "hono/http-exception";
1327
+ import { Hono as Hono15 } from "hono";
1328
+ import { HTTPException as HTTPException14 } from "hono/http-exception";
1308
1329
  function portRoutes(services) {
1309
- const routes = new Hono14();
1330
+ const routes = new Hono15();
1310
1331
  const bot = (id) => {
1311
1332
  services.bots.describe(id);
1312
1333
  return id;
@@ -1314,7 +1335,7 @@ function portRoutes(services) {
1314
1335
  routes.get("/bots/:id/ports", async (c) => c.json({ ports: await services.bots.ports.list(bot(c.req.param("id"))) }));
1315
1336
  routes.delete("/bots/:id/ports/:port", (c) => {
1316
1337
  const port = Number(c.req.param("port"));
1317
- if (!Number.isInteger(port)) throw new HTTPException13(400, { message: "port must be a number" });
1338
+ if (!Number.isInteger(port)) throw new HTTPException14(400, { message: "port must be a number" });
1318
1339
  services.bots.ports.unpublish(bot(c.req.param("id")), port);
1319
1340
  return c.json({ ok: true });
1320
1341
  });
@@ -1323,15 +1344,16 @@ function portRoutes(services) {
1323
1344
 
1324
1345
  // src/server/api/app.ts
1325
1346
  function createHttpApp(services, webRoot) {
1326
- const app = new Hono15();
1347
+ const app = new Hono16();
1327
1348
  app.use("*", headers);
1328
1349
  app.onError(handleError);
1329
- const api = new Hono15();
1350
+ const api = new Hono16();
1330
1351
  api.use("*", apiSecurity);
1331
1352
  api.route("/", rootCertificateRoute(services.connection));
1332
1353
  installAuthentication(api, services.account);
1333
1354
  api.route("/", taskRoutes(services));
1334
1355
  api.route("/", portRoutes(services));
1356
+ api.route("/", usageRoutes(services.bots));
1335
1357
  api.route("/bots", botRoutes(services.bots));
1336
1358
  api.route("/", channelRoutes(services));
1337
1359
  api.route("/chats", chatRoutes(services));
@@ -1343,7 +1365,7 @@ function createHttpApp(services, webRoot) {
1343
1365
  api.route("/secrets", secretRoutes(services.secrets));
1344
1366
  api.route("/environments", environmentRoutes(services.bots));
1345
1367
  api.all("*", () => {
1346
- throw new HTTPException14(404, { message: "API route not found" });
1368
+ throw new HTTPException15(404, { message: "API route not found" });
1347
1369
  });
1348
1370
  app.route("/api", api);
1349
1371
  app.get("*", serveStatic({ root: webRoot, onFound: (path, c) => {
@@ -1353,8 +1375,8 @@ function createHttpApp(services, webRoot) {
1353
1375
  c.header("Cache-Control", "no-store");
1354
1376
  } }));
1355
1377
  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" });
1378
+ if (c.req.method !== "GET" && c.req.method !== "HEAD") throw new HTTPException15(405, { message: "Method not allowed" });
1379
+ throw new HTTPException15(404, { message: "Web assets missing; run npm run build" });
1358
1380
  });
1359
1381
  return app;
1360
1382
  }
@@ -3537,6 +3559,44 @@ var QuoteRepository = class {
3537
3559
  }
3538
3560
  };
3539
3561
 
3562
+ // src/contract/message-refs.ts
3563
+ var MESSAGE_ID = /(?<![A-Za-z0-9_/#.@-])m\d{1,9}(?![A-Za-z0-9_-]|\.[A-Za-z0-9])/g;
3564
+ var MESSAGE_REFS_MAX = 20;
3565
+ function messageIds(text5) {
3566
+ const ids = [];
3567
+ for (const [id] of text5.matchAll(MESSAGE_ID)) if (!ids.includes(id) && ids.push(id) >= MESSAGE_REFS_MAX) break;
3568
+ return ids;
3569
+ }
3570
+
3571
+ // src/server/infra/storage/message-ref-repository.ts
3572
+ var MessageRefRepository = class {
3573
+ constructor(db, quotes) {
3574
+ this.db = db;
3575
+ this.quotes = quotes;
3576
+ }
3577
+ of(readerId, messageId, content2) {
3578
+ const ids = messageIds(content2).filter((id) => id !== messageId);
3579
+ if (!ids.length) return [];
3580
+ 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,
3581
+ 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
3582
+ FROM messages m JOIN chats c ON c.id=m.chat_id LEFT JOIN chats p ON p.id=c.parent_id
3583
+ 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)
3584
+ AND cm.member_id=? AND cm.can_read=1) OR (c.type='dm' AND c.owner_id=?))`).all(...ids, readerId, readerId);
3585
+ const found = new Map(rows3.map((row2) => [row2.id, row2]));
3586
+ return ids.flatMap((id) => {
3587
+ const row2 = found.get(id);
3588
+ return row2 ? [{
3589
+ id,
3590
+ senderId: row2.senderId,
3591
+ content: clipMarked(row2.content, 200),
3592
+ quotes: this.quotes.of(id),
3593
+ createdAt: row2.createdAt,
3594
+ chat: { id: row2.chatId, type: row2.type, title: row2.title, parentTitle: row2.parentTitle }
3595
+ }] : [];
3596
+ });
3597
+ }
3598
+ };
3599
+
3540
3600
  // src/server/infra/storage/chat-repository.ts
3541
3601
  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
3602
  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 +3612,7 @@ var ChatRepository = class {
3552
3612
  this.threads = new ThreadRepository(db, this);
3553
3613
  this.interactions = new InteractionRepository(db, this);
3554
3614
  this.quotes = new QuoteRepository(db);
3615
+ this.refs = new MessageRefRepository(db, this.quotes);
3555
3616
  this.inbox = new InboxRepository(db, this);
3556
3617
  }
3557
3618
  /** Sections, channels, notes, read positions and threads share this connection. */
@@ -3559,6 +3620,7 @@ var ChatRepository = class {
3559
3620
  threads;
3560
3621
  interactions;
3561
3622
  quotes;
3623
+ refs;
3562
3624
  /** Every delivery (A41, A61): the one place inbox SQL lives. */
3563
3625
  inbox;
3564
3626
  member(id) {
@@ -3676,14 +3738,16 @@ var ChatRepository = class {
3676
3738
  messagesBefore(actorId, chatId, before, limit2) {
3677
3739
  this.assertAccess(actorId, chatId);
3678
3740
  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));
3741
+ const reader = this.reader(actorId);
3742
+ return rows3.reverse().map((row2) => this.messageFromRow(row2, reader));
3680
3743
  }
3681
3744
  /** Exactly the messages counted as unread for this member (same rule as `unread`), oldest first. */
3682
3745
  unreadMessages(memberId, chatId, limit2) {
3683
3746
  this.assertAccess(memberId, chatId);
3684
3747
  if (this.db.prepare("SELECT type FROM chats WHERE id=?").get(chatId).type === "thread" && !this.threads.isFollowing(memberId, chatId)) return [];
3685
3748
  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));
3749
+ const reader = this.reader(memberId);
3750
+ return rows3.map((row2) => this.messageFromRow(row2, reader));
3687
3751
  }
3688
3752
  /** Search every chat the member can read: its DMs and channels and their threads (newest first). `within` keeps
3689
3753
  * one chat, a channel with its threads; `sender` keeps one member's messages. */
@@ -3692,7 +3756,8 @@ var ChatRepository = class {
3692
3756
  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
3757
  JOIN chat_members cm ON cm.chat_id=COALESCE(c.parent_id,c.id) AND cm.member_id=? AND cm.can_read=1
3694
3758
  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));
3759
+ const reader = this.reader(actorId);
3760
+ return rows3.map((row2) => this.messageFromRow(row2, reader));
3696
3761
  }
3697
3762
  /** Channels and threads the member can read whose title, topic or notice / summary contains the query (newest first). */
3698
3763
  searchChatIds(actorId, query, limit2) {
@@ -3704,17 +3769,19 @@ var ChatRepository = class {
3704
3769
  messages(actorId, chatId, after2 = 0, limit2 = 1e3) {
3705
3770
  this.assertAccess(actorId, chatId);
3706
3771
  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));
3772
+ const reader = this.reader(actorId);
3773
+ return rows3.map((row2) => this.messageFromRow(row2, reader));
3708
3774
  }
3709
3775
  message(actorId, id) {
3710
3776
  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;
3777
+ return row2 && this.canAccess(actorId, row2.chatId) ? this.messageFromRow(row2, this.reader(actorId)) : null;
3712
3778
  }
3713
3779
  search(actorId, chatId, query, limit2, sender) {
3714
3780
  this.assertAccess(actorId, chatId);
3715
3781
  const rows3 = this.db.prepare(`SELECT ${MESSAGE_COLUMNS} FROM messages WHERE chat_id=? AND instr(lower(content),lower(?))>0 ${sender ? "AND sender_id=?" : ""}
3716
3782
  ORDER BY sequence DESC LIMIT ?`).all(chatId, query, ...sender ? [sender] : [], limit2);
3717
- return rows3.map((row2) => this.messageFromRow(row2));
3783
+ const reader = this.reader(actorId);
3784
+ return rows3.map((row2) => this.messageFromRow(row2, reader));
3718
3785
  }
3719
3786
  sentActivity(actorId, senderId, before, limit2) {
3720
3787
  const condition = !before ? "" : before.kind === "chat" ? "AND (m.created_at<? OR (m.created_at=? AND m.id<?))" : "AND m.created_at<=?";
@@ -3727,7 +3794,11 @@ var ChatRepository = class {
3727
3794
  WHERE m.sender_id=? ${condition} ORDER BY m.created_at DESC,m.id DESC LIMIT ?`).all(actorId, senderId, ...cursor2, limit2);
3728
3795
  return rows3.map(({ historyId, toolCallId, ...row2 }) => ({ ...row2, source: historyId === null ? null : { historyId, toolCallId } }));
3729
3796
  }
3730
- messageFromRow(row2) {
3797
+ /** Who reads the snapshots: a person gets the messages a text names by ID (A82); a Bot reads IDs itself. */
3798
+ reader(actorId) {
3799
+ return this.member(actorId)?.kind === "bot" ? null : actorId;
3800
+ }
3801
+ messageFromRow(row2, reader) {
3731
3802
  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
3803
  return {
3733
3804
  id: row2.id,
@@ -3745,7 +3816,8 @@ var ChatRepository = class {
3745
3816
  replyTo: row2.replyTo === null ? null : this.quote(row2.replyTo),
3746
3817
  reactions: this.interactions.reactions(row2.id),
3747
3818
  quotes: this.quotes.of(row2.id),
3748
- folded: row2.foldedAt !== null
3819
+ folded: row2.foldedAt !== null,
3820
+ refs: reader ? this.refs.of(reader, row2.id, row2.content) : []
3749
3821
  };
3750
3822
  }
3751
3823
  /** 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 +3833,7 @@ var ChatRepository = class {
3761
3833
  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
3834
  if (prior) {
3763
3835
  if (prior.requestHash !== requestHash) throw new ChatError(409, "Message key already used with different content");
3764
- const message2 = this.messageFromRow(prior);
3836
+ const message2 = this.messageFromRow(prior, this.reader(actorId));
3765
3837
  return { message: message2, duplicate: true };
3766
3838
  }
3767
3839
  }
@@ -3807,13 +3879,13 @@ var ChatRepository = class {
3807
3879
  echoOf: chatId,
3808
3880
  replyTo: null,
3809
3881
  foldedAt: null
3810
- });
3882
+ }, this.reader(actorId));
3811
3883
  }
3812
3884
  }
3813
3885
  const file = this.db.prepare("SELECT name FROM attachments WHERE message_id=? ORDER BY created_at,rowid LIMIT 1").get(id);
3814
3886
  const title = draft.content ? previewQuotes(draft.content, draft.quotes ?? []).slice(0, 46).replace(/\s+/g, " ") : file?.name.slice(0, 46) ?? "";
3815
3887
  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 });
3888
+ 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
3889
  return { message, duplicate: false, ...echo ? { echo } : {} };
3818
3890
  });
3819
3891
  }
@@ -4103,6 +4175,13 @@ var EnvironmentRepository = class {
4103
4175
  ...limits2.cpus !== null ? { cpus: String(limits2.cpus) } : {}
4104
4176
  }), id);
4105
4177
  }
4178
+ /** Keeps what a computer is (A85): a VM, or left out for a container. */
4179
+ setType(id, type) {
4180
+ const computer = this.get(id);
4181
+ if (computer?.kind !== "computer") return;
4182
+ const { type: _type, ...spec } = computer.spec;
4183
+ this.db.prepare("UPDATE environments SET connection=? WHERE id=?").run(JSON.stringify({ ...spec, ...type === "vm" ? { type } : {} }), id);
4184
+ }
4106
4185
  /** The Bot is deleted, and its computer with it. Its row stays its home, deleted, so what reads a deleted Bot's
4107
4186
  * placement still finds one. */
4108
4187
  dropComputer(botId) {
@@ -5464,7 +5543,7 @@ var User = class extends Member {
5464
5543
  // src/server/application.ts
5465
5544
  import { createHash as createHash9 } from "node:crypto";
5466
5545
  import { mkdir as mkdir8, realpath } from "node:fs/promises";
5467
- import { join as join17, resolve as resolve3 } from "node:path";
5546
+ import { join as join18, resolve as resolve3 } from "node:path";
5468
5547
  import lockfile from "proper-lockfile";
5469
5548
 
5470
5549
  // src/contract/mentions.ts
@@ -5495,11 +5574,11 @@ function mentionedMembers(source2, candidates2) {
5495
5574
  function messageTargets({ dm, sender, members, mentioned, replied, subscribers }) {
5496
5575
  if (dm) return members.filter((member) => member.id !== sender.id).map((member) => ({ member, reason: "dm" }));
5497
5576
  const targets = mentioned.filter((member) => member.id !== sender.id).map((member) => ({ member, reason: "mention" }));
5498
- const add = (member, reason) => {
5577
+ const add2 = (member, reason) => {
5499
5578
  if (member.id !== sender.id && !targets.some((target3) => target3.member.id === member.id)) targets.push({ member, reason });
5500
5579
  };
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");
5580
+ if (replied && members.some((member) => member.id === replied.id)) add2(replied, "reply");
5581
+ for (const member of members) if (subscribers.includes(member.id)) add2(member, "subscription");
5503
5582
  return targets;
5504
5583
  }
5505
5584
  function echoTargets({ sender, members, subscribers, reached }) {
@@ -6075,12 +6154,12 @@ var ChatThreads = class {
6075
6154
  /** The open threads a member follows, most recently active first, up to `limit`, and how many there are (A73): what a
6076
6155
  * Bot is reminded of after a compaction. Finished threads are left out, as from a Bot's unread (A70). */
6077
6156
  openFollowed(actorId, limit2) {
6078
- const open2 = this.store.followedKeys(actorId).filter((row2) => row2.status === "open").sort((a, b) => b.lastReplyAt - a.lastReplyAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
6079
- const threads = open2.slice(0, limit2).flatMap((row2) => {
6157
+ const open3 = this.store.followedKeys(actorId).filter((row2) => row2.status === "open").sort((a, b) => b.lastReplyAt - a.lastReplyAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
6158
+ const threads = open3.slice(0, limit2).flatMap((row2) => {
6080
6159
  const chat = this.repository.getChat(actorId, row2.id), channel2 = chat?.parentId ? this.repository.getChat(actorId, chat.parentId) : null;
6081
6160
  return chat && channel2 ? [{ id: chat.id, title: chat.title, channel: { id: channel2.id, title: channel2.title }, lastReplyAt: row2.lastReplyAt, unread: row2.unread }] : [];
6082
6161
  });
6083
- return { total: open2.length, threads };
6162
+ return { total: open3.length, threads };
6084
6163
  }
6085
6164
  update(actorId, threadId, input) {
6086
6165
  const title = input.title;
@@ -6387,9 +6466,9 @@ var ChatFiles = class {
6387
6466
  constructor(chats) {
6388
6467
  this.chats = chats;
6389
6468
  }
6390
- async envelope(botId, messageIds, signal) {
6469
+ async envelope(botId, messageIds2, signal) {
6391
6470
  const output = [];
6392
- for (const id of messageIds) {
6471
+ for (const id of messageIds2) {
6393
6472
  signal?.throwIfAborted();
6394
6473
  const message = this.chats.message(botId, id);
6395
6474
  if (!message) throw new ChatError(404, "Message not found");
@@ -6505,9 +6584,35 @@ function activityPage(messages, history, limit2) {
6505
6584
  return { items, nextBefore: candidates2.length > limit2 ? position : null };
6506
6585
  }
6507
6586
 
6587
+ // src/server/service/bot/usage.ts
6588
+ var empty = () => ({ calls: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: null });
6589
+ function add(into, row2) {
6590
+ into.calls += row2.calls;
6591
+ into.input += row2.input;
6592
+ into.output += row2.output;
6593
+ into.cacheRead += row2.cacheRead;
6594
+ into.cacheWrite += row2.cacheWrite;
6595
+ if (row2.cost !== null) into.cost = (into.cost ?? 0) + row2.cost;
6596
+ }
6597
+ var costly = (a, b) => (b.cost ?? 0) - (a.cost ?? 0) || b.calls - a.calls;
6598
+ function usageOverview(since2, perBot) {
6599
+ const models = /* @__PURE__ */ new Map(), bots = [];
6600
+ for (const [botId, rows3] of perBot) {
6601
+ if (!rows3.length) continue;
6602
+ const bot = { botId, ...empty() };
6603
+ for (const { provider, model, ...row2 } of rows3) {
6604
+ const key = `${provider}\0${model}`;
6605
+ add(models.get(key) ?? models.set(key, { provider, model, ...empty() }).get(key), row2);
6606
+ add(bot, row2);
6607
+ }
6608
+ bots.push(bot);
6609
+ }
6610
+ return { since: since2, models: [...models.values()].sort(costly), bots: bots.sort(costly) };
6611
+ }
6612
+
6508
6613
  // src/server/service/bot/service.ts
6509
- import { dirname as dirname10, join as join16 } from "node:path";
6510
- import { rm as rm6 } from "node:fs/promises";
6614
+ import { dirname as dirname11, join as join17 } from "node:path";
6615
+ import { rm as rm8 } from "node:fs/promises";
6511
6616
 
6512
6617
  // src/server/infra/pi/history.ts
6513
6618
  var value = (input) => JSON.parse(JSON.stringify(input));
@@ -7074,7 +7179,7 @@ function environmentTools(lookup, secrets) {
7074
7179
  const access = async (path) => {
7075
7180
  if (!await current().exists(path)) throw Object.assign(new Error(`ENOENT: no such file or directory, access '${path}'`), { code: "ENOENT" });
7076
7181
  };
7077
- const readFile4 = (path) => current().readFile(path), writeFile5 = (path, content2) => current().writeFile(path, content2);
7182
+ const readFile4 = (path) => current().readFile(path), writeFile4 = (path, content2) => current().writeFile(path, content2);
7078
7183
  const cwd = current().cwd;
7079
7184
  const definitions = [
7080
7185
  relocated(createBashToolDefinition(cwd, { operations: {
@@ -7098,8 +7203,8 @@ function environmentTools(lookup, secrets) {
7098
7203
  } }), current),
7099
7204
  // Pictures go to the model as pictures; the kind comes from a file's first bytes, as Pi's local read does.
7100
7205
  createReadToolDefinition(cwd, { operations: { readFile: readFile4, access, detectImageMimeType: async (path) => imageKind(await current().head(path, IMAGE_SNIFF_BYTES)) } }),
7101
- createWriteToolDefinition(cwd, { operations: { writeFile: writeFile5, mkdir: (path) => current().mkdir(path) } }),
7102
- createEditToolDefinition(cwd, { operations: { readFile: readFile4, writeFile: writeFile5, access } })
7206
+ createWriteToolDefinition(cwd, { operations: { writeFile: writeFile4, mkdir: (path) => current().mkdir(path) } }),
7207
+ createEditToolDefinition(cwd, { operations: { readFile: readFile4, writeFile: writeFile4, access } })
7103
7208
  ];
7104
7209
  return definitions.map((definition) => inside(definition, lookup, pinned));
7105
7210
  }
@@ -7486,6 +7591,35 @@ ENV NPM_CONFIG_PREFIX=/home/bot/.npm-global PATH=/home/bot/.npm-global/bin:$PATH
7486
7591
  USER bot
7487
7592
  WORKDIR /workspace
7488
7593
  `;
7594
+ var VM_DISK = "/opt/jarvy-disk/docker.img";
7595
+ var DOCKER_UP = `#!/bin/sh
7596
+ set -eu
7597
+ DISK=${VM_DISK}
7598
+ if ! mountpoint -q /var/lib/docker; then
7599
+ [ -e /dev/loop-control ] || mknod -m 660 /dev/loop-control c 10 237
7600
+ i=0; while [ $i -lt 8 ]; do [ -e /dev/loop$i ] || mknod -m 660 /dev/loop$i b 7 $i; i=$((i+1)); done
7601
+ dev=$(losetup -j "$DISK" | cut -d: -f1 | head -n1)
7602
+ [ -n "$dev" ] || dev=$(losetup --direct-io=on -f --show "$DISK")
7603
+ blkid "$dev" > /dev/null 2>&1 || mkfs.ext4 -q -F -E lazy_itable_init=1,lazy_journal_init=1 "$dev"
7604
+ mkdir -p /var/lib/docker && mount "$dev" /var/lib/docker
7605
+ fi
7606
+ grep -q ' /sys/fs/cgroup cgroup2 rw' /proc/mounts || mount -o remount,rw /sys/fs/cgroup 2>/dev/null || true
7607
+ if ! docker version > /dev/null 2>&1; then
7608
+ pkill -x dockerd 2>/dev/null || true; pkill -x containerd 2>/dev/null || true
7609
+ rm -rf /var/run/docker /var/run/docker.pid /var/run/docker.sock /run/containerd
7610
+ setsid nohup dockerd > /var/log/dockerd.log 2>&1 < /dev/null &
7611
+ i=0; until docker version > /dev/null 2>&1; do i=$((i+1)); [ $i -lt 120 ] || { tail -n 5 /var/log/dockerd.log >&2; exit 1; }; sleep 0.5; done
7612
+ fi
7613
+ `;
7614
+ var vmDockerfile = (base) => `FROM ${base}
7615
+ USER root
7616
+ RUN apt-get update \\
7617
+ && apt-get install -y --no-install-recommends docker.io docker-compose-v2 e2fsprogs iptables \\
7618
+ && rm -rf /var/lib/apt/lists/* \\
7619
+ && usermod -aG docker bot && mkdir -p /var/lib/docker /opt/jarvy-disk
7620
+ COPY jarvy-docker-up /usr/local/bin/jarvy-docker-up
7621
+ USER bot
7622
+ `;
7489
7623
 
7490
7624
  // src/server/infra/env/durable.ts
7491
7625
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
@@ -7564,26 +7698,36 @@ var COMPUTER_CWD = "/workspace";
7564
7698
  var DAEMON_DIR = "/opt/jarvy";
7565
7699
  function docker(args, timeoutMs = 6e4) {
7566
7700
  return new Promise((resolve5, reject) => execFile("docker", args, { timeout: timeoutMs, maxBuffer: 8 << 20 }, (error, stdout, stderr) => {
7567
- if (error) reject(Object.assign(new Error((stderr || error.message).trim().split("\n").at(-1) ?? "docker failed"), { code: "docker_failed" }));
7568
- else resolve5(stdout.trim());
7701
+ if (!error) return resolve5(stdout.trim());
7702
+ const said = stderr.trim().split("\n").filter((line) => line.trim() && !/^Run 'docker .*--help'/.test(line)).at(-1);
7703
+ const ended = error.killed ? `docker ${args[0]} was stopped after ${timeoutMs / 1e3} seconds` : `docker ${args[0]} exited with ${error.code ?? error.signal}`;
7704
+ reject(Object.assign(new Error(said ?? (stdout.trim().split("\n").at(-1) || ended)), { code: "docker_failed" }));
7569
7705
  }));
7570
7706
  }
7571
- async function dockerAvailable() {
7572
- try {
7573
- await docker(["version", "--format", "{{.Server.Version}}"], 1e4);
7574
- return true;
7575
- } catch {
7576
- return false;
7577
- }
7707
+ function dockerProblem() {
7708
+ return new Promise((resolve5) => execFile("docker", ["version", "--format", "{{.Server.Version}}"], { timeout: 1e4 }, (error, _stdout, stderr) => {
7709
+ if (!error) return resolve5(null);
7710
+ const said = (stderr || error.message).trim(), detail = said.split("\n").filter(Boolean).at(-1) ?? said;
7711
+ if (error.code === "ENOENT") resolve5({ reason: "missing", detail: "no docker command" });
7712
+ else if (/permission denied/i.test(said)) resolve5({ reason: "denied", detail });
7713
+ else if (/cannot connect|failed to connect|daemon (is )?running|no such file|connection refused|error during connect/i.test(said)) resolve5({ reason: "stopped", detail });
7714
+ else resolve5({ reason: "failed", detail: error.killed ? "docker didn't answer within 10 seconds" : detail });
7715
+ }));
7578
7716
  }
7579
7717
  function computerImage(uid, gid) {
7580
7718
  return `jarvy-computer:${createHash6("sha256").update(`${COMPUTER_DOCKERFILE}
7581
7719
  ${uid}:${gid}`).digest("hex").slice(0, 12)}`;
7582
7720
  }
7721
+ function vmImage(base) {
7722
+ return `jarvy-computer:vm-${createHash6("sha256").update(`${vmDockerfile(base)}
7723
+ ${DOCKER_UP}`).digest("hex").slice(0, 12)}`;
7724
+ }
7725
+ var computerRecipe = (uid, gid) => ({ dockerfile: COMPUTER_DOCKERFILE, args: { UID: String(uid), GID: String(gid) } });
7726
+ var vmRecipe = (base) => ({ dockerfile: vmDockerfile(base), files: { "jarvy-docker-up": DOCKER_UP } });
7583
7727
  async function pruneImages(keep) {
7584
7728
  const tags = (await docker(["images", "--filter", "label=jarvy.computer=1", "--format", "{{.Repository}}:{{.Tag}}"])).split("\n").filter(Boolean);
7585
7729
  const removed = [];
7586
- for (const tag of tags) if (tag !== keep) {
7730
+ for (const tag of tags) if (!keep.includes(tag)) {
7587
7731
  try {
7588
7732
  await docker(["image", "rm", tag], 12e4);
7589
7733
  removed.push(tag);
@@ -7600,17 +7744,22 @@ async function imageExists(tag) {
7600
7744
  return false;
7601
7745
  }
7602
7746
  }
7603
- async function buildImage(tag, uid, gid, logFile) {
7747
+ async function buildImage(tag, recipe, logFile) {
7604
7748
  const dir = await mkdtemp(join9(tmpdir(), "jarvy-computer-"));
7605
7749
  try {
7606
- await writeFile2(join9(dir, "Dockerfile"), COMPUTER_DOCKERFILE);
7750
+ await writeFile2(join9(dir, "Dockerfile"), recipe.dockerfile);
7751
+ for (const [name3, content2] of Object.entries(recipe.files ?? {})) await writeFile2(join9(dir, name3), content2, { mode: 493 });
7607
7752
  const log = createWriteStream(logFile, { flags: "w", mode: 384 });
7608
7753
  const code = await new Promise((resolve5, reject) => {
7609
- const child = spawn(
7610
- "docker",
7611
- ["build", "-t", tag, "--label", "jarvy.computer=1", "--build-arg", `UID=${uid}`, "--build-arg", `GID=${gid}`, dir],
7612
- { stdio: ["ignore", "pipe", "pipe"] }
7613
- );
7754
+ const child = spawn("docker", [
7755
+ "build",
7756
+ "-t",
7757
+ tag,
7758
+ "--label",
7759
+ "jarvy.computer=1",
7760
+ ...Object.entries(recipe.args ?? {}).flatMap(([key, value2]) => ["--build-arg", `${key}=${value2}`]),
7761
+ dir
7762
+ ], { stdio: ["ignore", "pipe", "pipe"] });
7614
7763
  child.stdout.pipe(log, { end: false });
7615
7764
  child.stderr.pipe(log, { end: false });
7616
7765
  child.on("error", reject);
@@ -7654,6 +7803,7 @@ async function runContainer(spec) {
7654
7803
  ...Object.entries(spec.hosts ?? {}).flatMap(([name3, address2]) => ["--add-host", `${name3}:${address2}`]),
7655
7804
  ...spec.limits?.memory ? memoryFlags(spec.limits.memory, spec.limits.memory) : [],
7656
7805
  ...spec.limits?.cpus ? ["--cpus", String(spec.limits.cpus)] : [],
7806
+ ...spec.vm ? vmFlags(spec.vm.disk) : [],
7657
7807
  "-v",
7658
7808
  `${spec.workspace}:${COMPUTER_CWD}`,
7659
7809
  "-v",
@@ -7665,6 +7815,27 @@ async function runContainer(spec) {
7665
7815
  "infinity"
7666
7816
  ], 12e4);
7667
7817
  }
7818
+ var KATA_RUNTIME = "io.containerd.kata.v2";
7819
+ var vmFlags = (disk) => [
7820
+ "--runtime",
7821
+ KATA_RUNTIME,
7822
+ "--group-add",
7823
+ "docker",
7824
+ "--cap-add",
7825
+ "ALL",
7826
+ "--security-opt",
7827
+ "seccomp=unconfined",
7828
+ "--security-opt",
7829
+ "apparmor=unconfined",
7830
+ "--security-opt",
7831
+ "systempaths=unconfined",
7832
+ "--device-cgroup-rule",
7833
+ "b 7:* rmw",
7834
+ "--device-cgroup-rule",
7835
+ "c 10:237 rmw",
7836
+ "-v",
7837
+ `${disk}:${VM_DISK}`
7838
+ ];
7668
7839
  var memoryFlags = (memory, withSwap) => ["--memory", String(memory), "--memory-swap", String(withSwap)];
7669
7840
  async function updateLimits(name3, change, machine) {
7670
7841
  const args = [
@@ -7789,24 +7960,177 @@ function loopbackAddress(hex) {
7789
7960
 
7790
7961
  // src/server/service/bot/computers.ts
7791
7962
  import { createHash as createHash7 } from "node:crypto";
7792
- import { dirname as dirname5, join as join10 } from "node:path";
7963
+ import { dirname as dirname6, join as join11 } from "node:path";
7964
+
7965
+ // src/server/infra/env/kata.ts
7966
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
7967
+ import { isIP } from "node:net";
7968
+ import { mkdir as mkdir5, open as open2, rm as rm5 } from "node:fs/promises";
7969
+ import { dirname as dirname5 } from "node:path";
7970
+ var VM_DISK_SIZE = 64 * 2 ** 30;
7971
+ async function vmProblem(image) {
7972
+ if (!existsSync4("/dev/kvm")) return { reason: "no_kvm", detail: "this machine has no /dev/kvm" };
7973
+ try {
7974
+ await docker(["run", "--rm", "--runtime", KATA_RUNTIME, "--memory", "512m", "--entrypoint", "true", image], 12e4);
7975
+ return null;
7976
+ } catch (error) {
7977
+ const said = error.message;
7978
+ if (/binary not installed|containerd-shim-kata|unknown runtime|executable file not found/i.test(said)) return { reason: "no_kata", detail: said };
7979
+ if (/resource busy|KVM_CREATE_VM/i.test(said) || /QMP ready/i.test(said) && otherHypervisor()) return { reason: "busy", detail: said };
7980
+ if (/\/dev\/kvm|kvm/i.test(said)) return { reason: "no_kvm", detail: said };
7981
+ return { reason: "failed", detail: said };
7982
+ }
7983
+ }
7984
+ function otherHypervisor() {
7985
+ try {
7986
+ return /^vboxdrv /m.test(readFileSync4("/proc/modules", "utf8"));
7987
+ } catch {
7988
+ return false;
7989
+ }
7990
+ }
7991
+ async function createDisk(path) {
7992
+ await mkdir5(dirname5(path), { recursive: true, mode: 448 });
7993
+ const file = await open2(path, "wx", 384).catch((error) => {
7994
+ if (error.code === "EEXIST") return null;
7995
+ throw error;
7996
+ });
7997
+ if (!file) return;
7998
+ try {
7999
+ await file.truncate(VM_DISK_SIZE);
8000
+ } finally {
8001
+ await file.close();
8002
+ }
8003
+ }
8004
+ async function removeDisk(path) {
8005
+ await rm5(path, { force: true });
8006
+ }
8007
+ async function dockerUp(container) {
8008
+ await docker(["exec", "-u", "root", container, "/usr/local/bin/jarvy-docker-up"], 9e4);
8009
+ }
8010
+ function hostResolvers() {
8011
+ for (const file of ["/run/systemd/resolve/resolv.conf", "/etc/resolv.conf"]) {
8012
+ let text5;
8013
+ try {
8014
+ text5 = readFileSync4(file, "utf8");
8015
+ } catch {
8016
+ continue;
8017
+ }
8018
+ const servers = [...text5.matchAll(/^\s*nameserver\s+(\S+)/gm)].map((match) => match[1]).filter((address2) => isIP(address2) && !address2.startsWith("127.") && address2 !== "::1" && !address2.toLowerCase().startsWith("fe80:"));
8019
+ if (servers.length) return servers.slice(0, 3);
8020
+ }
8021
+ return ["8.8.8.8", "8.8.4.4"];
8022
+ }
8023
+ async function useResolvers(container, servers) {
8024
+ await docker(["exec", "-u", "root", container, "sh", "-c", `printf 'nameserver %s\\n' ${servers.join(" ")} > /etc/resolv.conf`], 3e4);
8025
+ }
8026
+
8027
+ // src/server/service/bot/computer-vm.ts
8028
+ import { join as join10 } from "node:path";
8029
+ var VM_SIZE = { memory: 4 * 2 ** 30, cpus: 2 };
8030
+ var computerType = (record3) => record3.spec.type === "vm" ? "vm" : "container";
8031
+ var vmDisk = (dataDir, container) => join10(dataDir, "computers", "disks", `${container}.img`);
8032
+ var ComputerImages = class {
8033
+ constructor(dataDir, uid, gid, log) {
8034
+ this.dataDir = dataDir;
8035
+ this.uid = uid;
8036
+ this.gid = gid;
8037
+ this.log = log;
8038
+ }
8039
+ base = null;
8040
+ vm = null;
8041
+ /** The tag a sandbox of this type starts from, built or not. */
8042
+ tag(type) {
8043
+ const base = computerImage(this.uid, this.gid);
8044
+ return type === "vm" ? vmImage(base) : base;
8045
+ }
8046
+ /** The image for this type, built first when missing. */
8047
+ ready(type) {
8048
+ this.base ??= this.build(computerImage(this.uid, this.gid), computerRecipe(this.uid, this.gid)).catch((error) => {
8049
+ this.base = null;
8050
+ throw error;
8051
+ });
8052
+ if (type === "container") return this.base;
8053
+ this.vm ??= this.base.then((base) => this.build(vmImage(base), vmRecipe(base))).catch((error) => {
8054
+ this.vm = null;
8055
+ throw error;
8056
+ });
8057
+ return this.vm;
8058
+ }
8059
+ async build(tag, recipe) {
8060
+ if (await imageExists(tag)) return tag;
8061
+ this.log(`building ${tag}`);
8062
+ await buildImage(tag, recipe, join10(this.dataDir, "computers", "build.log"));
8063
+ const keep = [this.tag("container"), this.tag("vm")];
8064
+ void pruneImages(keep).then((removed) => {
8065
+ if (removed.length) this.log(`removed ${removed.join(", ")}`);
8066
+ }).catch(() => {
8067
+ });
8068
+ return tag;
8069
+ }
8070
+ };
8071
+ var VmSupportCheck = class {
8072
+ constructor(images, log) {
8073
+ this.images = images;
8074
+ this.log = log;
8075
+ }
8076
+ known = { state: "unknown" };
8077
+ running = null;
8078
+ get current() {
8079
+ return this.known;
8080
+ }
8081
+ /** The last answer, checking first when there is none yet or `again`. */
8082
+ check(again = false) {
8083
+ if (this.running) return this.running;
8084
+ if (!again && this.known.state !== "unknown") return Promise.resolve(this.known);
8085
+ this.known = { state: "checking" };
8086
+ this.running = (async () => {
8087
+ try {
8088
+ const problem = await vmProblem(await this.images.ready("container"));
8089
+ if (problem) this.log(`VM sandboxes can't be used (${problem.reason}): ${problem.detail}`);
8090
+ return problem ? { state: "unavailable", ...problem } : { state: "available" };
8091
+ } catch (error) {
8092
+ return { state: "unavailable", reason: "failed", detail: error.message };
8093
+ }
8094
+ })().then((answer) => {
8095
+ this.known = answer;
8096
+ return answer;
8097
+ }).finally(() => {
8098
+ this.running = null;
8099
+ });
8100
+ return this.running;
8101
+ }
8102
+ };
8103
+
8104
+ // src/server/service/bot/computers.ts
8105
+ import { userInfo } from "node:os";
7793
8106
  var SWEEP_MS = 6e4;
8107
+ var RECHECK_MS = 3e4;
7794
8108
  var HOST_NAME = "host.docker.internal";
7795
- var MIN_MEMORY = 256 * 2 ** 20;
7796
- var MIN_CPUS = 0.1;
8109
+ var MIN = { container: { memory: 256 * 2 ** 20, cpus: 0.1 }, vm: { memory: 2 ** 30, cpus: 1 } };
7797
8110
  function computerLimits(record3) {
7798
8111
  const read3 = (value2) => value2 && Number(value2) > 0 ? Number(value2) : null;
7799
- return { memory: read3(record3.spec.memory), cpus: read3(record3.spec.cpus) };
8112
+ const memory = read3(record3.spec.memory), cpus = read3(record3.spec.cpus);
8113
+ return computerType(record3) === "vm" ? { memory: memory ?? VM_SIZE.memory, cpus: cpus ?? VM_SIZE.cpus } : { memory, cpus };
7800
8114
  }
7801
8115
  var Computers = class {
7802
8116
  constructor(deps) {
7803
8117
  this.deps = deps;
7804
- this.dataDir = dirname5(deps.store.path);
8118
+ this.dataDir = dirname6(deps.store.path);
7805
8119
  this.tag = createHash7("sha256").update(this.dataDir).digest("hex").slice(0, 12);
8120
+ this.images = new ComputerImages(this.dataDir, this.uid, this.gid, (text5) => this.log(text5));
8121
+ this.vms = new VmSupportCheck(this.images, (text5) => this.log(text5));
7806
8122
  }
7807
8123
  docker = null;
8124
+ /** Why Docker can't be used, while it can't. */
8125
+ problem = null;
8126
+ recheck = null;
8127
+ closed = false;
7808
8128
  probing = null;
7809
- image = null;
8129
+ images;
8130
+ /** Whether VM sandboxes can be used here (A85). */
8131
+ vms;
8132
+ /** VM sandboxes resized while they ran: the new size comes with their next start. */
8133
+ resized = /* @__PURE__ */ new Set();
7810
8134
  timer = null;
7811
8135
  states = /* @__PURE__ */ new Map();
7812
8136
  preparing = /* @__PURE__ */ new Map();
@@ -7824,25 +8148,52 @@ var Computers = class {
7824
8148
  tag;
7825
8149
  uid = process.getuid?.() ?? 1e3;
7826
8150
  gid = process.getgid?.() ?? 1e3;
7827
- /** Looks for Docker and learns the state of every computer, once; every computer waits for it. */
8151
+ /** Looks for Docker and learns the state of every computer; every computer waits for the first look. While Docker
8152
+ * can't be used, it looks again every 30 seconds and takes it up once it can. */
7828
8153
  start() {
7829
8154
  this.probing ??= this.probe();
7830
8155
  return this.probing;
7831
8156
  }
7832
8157
  async probe() {
7833
- this.docker = await dockerAvailable();
7834
- if (!this.docker) return;
8158
+ const problem = await dockerProblem();
8159
+ if (problem) return this.unusable(problem);
7835
8160
  try {
7836
- await syncDaemon(join10(this.dataDir, "computers", "bin"));
8161
+ await syncDaemon(join11(this.dataDir, "computers", "bin"));
7837
8162
  } catch (error) {
7838
- this.docker = false;
7839
- this.log(`computers disabled: ${error.message}`);
7840
- return;
8163
+ return this.unusable({ reason: "failed", detail: `the tools' daemon could not be put in place: ${error.message}` });
7841
8164
  }
8165
+ const found = this.docker === false;
8166
+ this.docker = true;
8167
+ this.problem = null;
8168
+ if (found) this.log("Docker can be used now");
7842
8169
  await this.joinNetwork().catch((error) => this.log(`sandbox network unavailable, staying on the default bridge: ${error.message}`));
7843
8170
  await this.sweep().catch((error) => this.log(`computer sweep failed: ${error.message}`));
7844
8171
  this.timer = setInterval(() => void this.sweep().catch((error) => this.log(`computer sweep failed: ${error.message}`)), SWEEP_MS);
7845
8172
  this.timer.unref();
8173
+ if (found) this.deps.changed();
8174
+ }
8175
+ /** Docker can't be used: said once in the log per reason, and looked for again later. */
8176
+ unusable(problem) {
8177
+ const before = this.docker === null ? null : this.problem?.reason;
8178
+ if (before !== problem.reason) this.log(`Docker can't be used (${problem.reason}): ${problem.detail}`);
8179
+ this.docker = false;
8180
+ this.problem = problem;
8181
+ if (before && before !== problem.reason) this.deps.changed();
8182
+ if (this.closed) return;
8183
+ this.recheck = setTimeout(() => {
8184
+ this.recheck = null;
8185
+ void this.probe();
8186
+ }, RECHECK_MS);
8187
+ this.recheck.unref();
8188
+ }
8189
+ /** Why Docker can't be used, in a Bot's words; null when it can, or before Jarvy has looked. */
8190
+ get dockerProblem() {
8191
+ const problem = this.docker === false ? this.problem : null;
8192
+ if (!problem) return null;
8193
+ if (problem.reason === "missing") return "Docker isn't installed on the computer running Jarvy";
8194
+ if (problem.reason === "stopped") return "Docker is installed on the computer running Jarvy but isn't running";
8195
+ if (problem.reason === "denied") return `Docker on the computer running Jarvy refuses the user Jarvy runs as (${userInfo().username})`;
8196
+ return `Docker on the computer running Jarvy can't be used (${problem.detail})`;
7846
8197
  }
7847
8198
  /** Whether new computers can be made here; false until `start` found Docker. */
7848
8199
  get available() {
@@ -7850,40 +8201,74 @@ var Computers = class {
7850
8201
  }
7851
8202
  status(botId) {
7852
8203
  if (!this.deps.store.environments.computerOf(botId)) return null;
7853
- if (!this.available) return { state: "unavailable" };
8204
+ if (!this.available) return { state: "unavailable", ...this.problem ? { error: this.problem.reason } : {} };
7854
8205
  return this.states.get(botId) ?? { state: "stopped" };
7855
8206
  }
7856
8207
  /** The sandbox as Bot info shows it: its state, and the container, image and workspace folder it is made of. */
7857
8208
  info(botId) {
7858
8209
  const computer = this.deps.store.environments.computerOf(botId), status = this.status(botId);
7859
8210
  if (!computer || !status) return null;
8211
+ const type = computerType(computer);
7860
8212
  return {
7861
8213
  ...status,
8214
+ type,
7862
8215
  container: computer.spec.container,
7863
- image: computerImage(this.uid, this.gid),
8216
+ image: this.images.tag(type),
7864
8217
  workspace: this.workspace(botId),
7865
8218
  mount: COMPUTER_CWD,
7866
- limits: computerLimits(computer)
8219
+ limits: computerLimits(computer),
8220
+ ...this.resized.has(botId) ? { restartNeeded: true } : {}
7867
8221
  };
7868
8222
  }
7869
- /** What the sandbox uses now, when it runs, and what this machine has; null for what Docker doesn't answer. */
8223
+ /** Whether VM sandboxes can be used here, as last checked (A85). */
8224
+ get vmSupport() {
8225
+ return this.available ? this.vms.current : { state: "unavailable", reason: "failed", detail: this.dockerProblem ?? "Docker can't be used" };
8226
+ }
8227
+ /** Checks whether VM sandboxes can be used here: the first time when asked, or `again`. */
8228
+ checkVms(again = false) {
8229
+ return this.available ? this.vms.check(again) : Promise.resolve(this.vmSupport);
8230
+ }
8231
+ /** Makes the Bot's sandbox a container or a VM (A85). Like a reset, what was installed goes and the workspace stays;
8232
+ * a VM's Docker disk goes too. The next start makes the new one. */
8233
+ async setType(botId, type) {
8234
+ const computer = this.need(botId);
8235
+ if (computerType(computer) === type) return;
8236
+ if (type === "vm") {
8237
+ const support = await this.vms.check();
8238
+ if (support.state !== "available") throw new ValidationError("This machine can't run VM sandboxes", "vm_unavailable", { reason: support.reason ?? "failed" });
8239
+ }
8240
+ await this.settled(botId);
8241
+ await this.disconnect(botId);
8242
+ await removeContainer(computer.spec.container);
8243
+ await removeDisk(vmDisk(this.dataDir, computer.spec.container));
8244
+ this.homes.delete(computer.spec.container);
8245
+ this.resized.delete(botId);
8246
+ this.deps.store.environments.setType(computer.id, type);
8247
+ this.set(botId, { state: "stopped" });
8248
+ this.deps.changed();
8249
+ }
8250
+ /** What the sandbox uses now, when it runs, and what this machine has; null for what Docker doesn't answer. A VM's
8251
+ * use isn't known (A85): Docker counts only its container's own processes, not what runs in the VM besides. */
7870
8252
  async resources(botId) {
7871
8253
  const computer = this.need(botId);
7872
- const usage = this.status(botId)?.state === "running" ? await containerUsage(computer.spec.container).catch(() => null) : null;
8254
+ const usage = this.status(botId)?.state === "running" && computerType(computer) === "container" ? await containerUsage(computer.spec.container).catch(() => null) : null;
7873
8255
  return { usage, capacity: await this.capacity().catch(() => null) };
7874
8256
  }
7875
8257
  /** Sets what the sandbox may use at most (A75): a container that exists changes at once, running or not, and one made
7876
8258
  * later, after a reset too, starts with them. Each is null for no limit, or from a floor up to this machine's size. */
7877
8259
  async setLimits(botId, input) {
7878
- const computer = this.need(botId), machine = await this.capacity();
7879
- const memory = limit(input.memory, MIN_MEMORY, machine.memory, 2 ** 20), cpus = limit(input.cpus, MIN_CPUS, machine.cpus, 0.01);
8260
+ const computer = this.need(botId), machine = await this.capacity(), type = computerType(computer), least = MIN[type];
8261
+ const memory = limit(input.memory, least.memory, machine.memory, 2 ** 20), cpus = limit(input.cpus, least.cpus, machine.cpus, 0.01);
7880
8262
  if (memory === void 0 || cpus === void 0) throw new ValidationError(
7881
8263
  "Limits are null or a number within this machine's size",
7882
- "limits_invalid",
8264
+ type === "vm" ? "vm_size_invalid" : "limits_invalid",
7883
8265
  { memory: Math.floor(machine.memory / 2 ** 30 * 10) / 10, cpus: machine.cpus }
7884
8266
  );
7885
- const before = computerLimits(computer), change = { ...memory !== before.memory ? { memory } : {}, ...cpus !== before.cpus ? { cpus } : {} };
7886
- if (Object.keys(change).length && await containerState(computer.spec.container) !== "missing") await updateLimits(computer.spec.container, change, machine);
8267
+ const next = computerLimits({ ...computer, spec: { ...computer.spec, memory: memory === null ? "" : String(memory), cpus: cpus === null ? "" : String(cpus) } });
8268
+ const before = computerLimits(computer), change = { ...next.memory !== before.memory ? { memory: next.memory } : {}, ...next.cpus !== before.cpus ? { cpus: next.cpus } : {} };
8269
+ const state = Object.keys(change).length ? await containerState(computer.spec.container) : "missing";
8270
+ if (state !== "missing") await updateLimits(computer.spec.container, change, machine);
8271
+ if (type === "vm" && state === "running") this.resized.add(botId);
7887
8272
  this.deps.store.environments.setLimits(computer.id, { memory, cpus });
7888
8273
  this.deps.changed();
7889
8274
  }
@@ -7941,7 +8326,10 @@ var Computers = class {
7941
8326
  const container = await this.ensure(botId);
7942
8327
  let home = this.homes.get(container);
7943
8328
  if (!home) {
7944
- home = this.prepare(container).catch((error) => this.log(`sandbox of ${botId} not set up: ${error.message}`));
8329
+ home = this.prepare(container, computerType(record3) === "vm").catch((error) => {
8330
+ this.homes.delete(container);
8331
+ this.log(`sandbox of ${botId} not set up: ${error.message}`);
8332
+ });
7945
8333
  this.homes.set(container, home);
7946
8334
  }
7947
8335
  await home;
@@ -7952,11 +8340,15 @@ var Computers = class {
7952
8340
  }
7953
8341
  return env;
7954
8342
  }
7955
- /** Sets up a container after it starts: the workspace as its home, and this machine's name for one made before
7956
- * containers got it at creation. */
7957
- async prepare(container) {
8343
+ /** Sets up a container after it starts: the workspace as its home, this machine's name for one made before
8344
+ * containers got it at creation, and in a VM (A85) Docker on its disk. */
8345
+ async prepare(container, vm) {
7958
8346
  await homeAtWorkspace(container);
7959
8347
  if (this.network) await addHost(container, HOST_NAME, this.network.gateway);
8348
+ if (vm) {
8349
+ await useResolvers(container, hostResolvers());
8350
+ await dockerUp(container);
8351
+ }
7960
8352
  }
7961
8353
  /** Makes this Jarvy's network and moves the containers still on Docker's default bridge there, running or not. */
7962
8354
  async joinNetwork() {
@@ -8014,29 +8406,35 @@ var Computers = class {
8014
8406
  const task = (async () => {
8015
8407
  try {
8016
8408
  await this.start();
8017
- if (!this.available) throw new RuntimeFault("docker_unavailable", "Docker is not available on this machine.", 503);
8018
- const image = await this.imageReady();
8409
+ if (!this.available) throw this.unavailable(503);
8410
+ const type = computerType(computer), image = await this.images.ready(type), disk = vmDisk(this.dataDir, container);
8411
+ if (type === "vm") await createDisk(disk);
8019
8412
  const state = await containerState(container);
8020
8413
  if (state === "missing") await runContainer({
8021
8414
  name: container,
8022
8415
  image,
8023
8416
  workspace: this.workspace(botId),
8024
- daemonDir: join10(this.dataDir, "computers", "bin"),
8417
+ daemonDir: join11(this.dataDir, "computers", "bin"),
8025
8418
  uid: this.uid,
8026
8419
  gid: this.gid,
8027
8420
  labels: { "jarvy.data": this.tag, "jarvy.bot": botId },
8028
8421
  limits: computerLimits(computer),
8029
- ...this.network ? { network: this.network.name, hosts: { [HOST_NAME]: this.network.gateway } } : {}
8422
+ ...this.network ? { network: this.network.name, hosts: { [HOST_NAME]: this.network.gateway } } : {},
8423
+ ...type === "vm" ? { vm: { disk } } : {}
8030
8424
  });
8031
8425
  else if (state === "stopped") await startContainer(container);
8032
8426
  if (state !== "running") {
8033
8427
  this.homes.delete(container);
8034
8428
  this.book = null;
8429
+ this.resized.delete(botId);
8035
8430
  }
8036
8431
  this.set(botId, { state: "running" });
8037
8432
  return container;
8038
8433
  } catch (error) {
8039
- this.set(botId, { state: "failed", error: error instanceof RuntimeFault ? error.code : "computer_failed" });
8434
+ if (error instanceof RuntimeFault && error.code === "docker_unavailable") {
8435
+ this.states.delete(botId);
8436
+ this.deps.changed();
8437
+ } else this.set(botId, { state: "failed", error: error instanceof RuntimeFault ? error.code : "computer_failed" });
8040
8438
  this.log(`computer of ${botId} failed: ${error.message}`);
8041
8439
  if (error instanceof RuntimeFault) throw error;
8042
8440
  throw new RuntimeFault("computer_failed", `Your sandbox could not start: ${error.message}`, 503);
@@ -8049,15 +8447,19 @@ var Computers = class {
8049
8447
  const computer = this.need(botId);
8050
8448
  await this.disconnect(botId);
8051
8449
  await stopContainer(computer.spec.container);
8450
+ this.resized.delete(botId);
8052
8451
  this.set(botId, { state: "stopped" });
8053
8452
  }
8054
8453
  /** Removes the container, so the next start makes a fresh one from the image: what was installed goes, the
8055
8454
  * workspace stays. */
8056
8455
  async reset(botId) {
8057
8456
  const computer = this.need(botId);
8457
+ await this.settled(botId);
8058
8458
  await this.disconnect(botId);
8059
8459
  await removeContainer(computer.spec.container);
8460
+ await removeDisk(vmDisk(this.dataDir, computer.spec.container));
8060
8461
  this.homes.delete(computer.spec.container);
8462
+ this.resized.delete(botId);
8061
8463
  this.set(botId, { state: "stopped" });
8062
8464
  }
8063
8465
  /** The Bot is being deleted: its container goes with it. */
@@ -8066,41 +8468,36 @@ var Computers = class {
8066
8468
  if (!computer) return;
8067
8469
  await this.disconnect(botId);
8068
8470
  if (this.available) await removeContainer(computer.spec.container);
8471
+ await removeDisk(vmDisk(this.dataDir, computer.spec.container));
8069
8472
  this.deps.store.environments.dropComputer(botId);
8070
8473
  this.states.delete(botId);
8071
8474
  }
8072
8475
  /** Closes the connections; containers keep running. */
8073
8476
  async close() {
8477
+ this.closed = true;
8074
8478
  if (this.timer) clearInterval(this.timer);
8479
+ if (this.recheck) clearTimeout(this.recheck);
8075
8480
  this.timer = null;
8481
+ this.recheck = null;
8076
8482
  await Promise.all([...this.connections.keys()].map((botId) => this.disconnect(botId)));
8077
8483
  }
8484
+ unavailable(status) {
8485
+ const problem = this.dockerProblem;
8486
+ return new RuntimeFault("docker_unavailable", problem ? `${problem[0].toUpperCase()}${problem.slice(1)}.` : "Docker is not available on this machine.", status);
8487
+ }
8078
8488
  workspace(botId) {
8079
- return join10(this.dataDir, "bots", botId, "workspace");
8489
+ return join11(this.dataDir, "bots", botId, "workspace");
8080
8490
  }
8081
8491
  need(botId) {
8082
8492
  const computer = this.deps.store.environments.computerOf(botId);
8083
8493
  if (!computer) throw new RuntimeFault("computer_missing", "This Bot has no sandbox.", 404);
8084
- if (!this.available) throw new RuntimeFault("docker_unavailable", "Docker is not available on this machine.", 409);
8494
+ if (!this.available) throw this.unavailable(409);
8085
8495
  return computer;
8086
8496
  }
8087
- imageReady() {
8088
- this.image ??= (async () => {
8089
- const tag = computerImage(this.uid, this.gid);
8090
- if (!await imageExists(tag)) {
8091
- this.log(`building ${tag}`);
8092
- await buildImage(tag, this.uid, this.gid, join10(this.dataDir, "computers", "build.log"));
8093
- void pruneImages(tag).then((removed) => {
8094
- if (removed.length) this.log(`removed ${removed.join(", ")}`);
8095
- }).catch(() => {
8096
- });
8097
- }
8098
- return tag;
8099
- })().catch((error) => {
8100
- this.image = null;
8101
- throw error;
8497
+ /** Waits for a start under way, so a container it is making isn't made after the one replacing it is asked for. */
8498
+ async settled(botId) {
8499
+ await this.preparing.get(botId)?.catch(() => {
8102
8500
  });
8103
- return this.image;
8104
8501
  }
8105
8502
  async disconnect(botId) {
8106
8503
  const env = this.connections.get(botId);
@@ -8128,6 +8525,7 @@ var Computers = class {
8128
8525
  const running = states.get(computer.spec.container) === "running";
8129
8526
  if (!running) {
8130
8527
  if (this.states.get(botId)?.state !== "failed") this.set(botId, { state: "stopped" });
8528
+ this.resized.delete(botId);
8131
8529
  await this.disconnect(botId);
8132
8530
  continue;
8133
8531
  }
@@ -8152,6 +8550,9 @@ function limits(record3) {
8152
8550
  const parts = [memory ? `${Number((memory / 2 ** 30).toFixed(2))} GB of memory` : "", cpus ? `${cpus} ${cpus === 1 ? "CPU" : "CPUs"}` : ""].filter(Boolean);
8153
8551
  return parts.length ? parts.join(" and ") : null;
8154
8552
  }
8553
+ var sentence = (text5) => `${text5[0].toUpperCase()}${text5.slice(1)}`;
8554
+ var VM = "A Linux virtual machine only you use, with Node, Python, git, build tools, Playwright with its browsers, and Docker with Docker Compose: docker works there without sudo, and a port a container of yours publishes is a port of your sandbox. Your images, containers and volumes stay until the owner resets your sandbox.";
8555
+ var CONTAINER = "A Linux container only you use, with Node, Python, git, build tools, and Playwright with its browsers.";
8155
8556
  var sandbox = {
8156
8557
  kind: "computer",
8157
8558
  home: true,
@@ -8169,12 +8570,17 @@ var sandbox = {
8169
8570
  connects: false,
8170
8571
  summary: (record3, botId) => record3.botId === botId ? "own sandbox" : "another Bot's sandbox",
8171
8572
  describe: (record3, botId, deps) => {
8172
- const most = limits(record3);
8173
- return { state: deps.computers.status(record3.botId ?? botId)?.state ?? "stopped", ...most ? { limits: `at most ${most}` } : {} };
8573
+ const most = limits(record3), problem = deps.computers.dockerProblem;
8574
+ return {
8575
+ state: deps.computers.status(record3.botId ?? botId)?.state ?? "stopped",
8576
+ ...computerType(record3) === "vm" ? { type: "virtual machine with Docker" } : {},
8577
+ ...most ? { limits: `at most ${most}` } : {},
8578
+ ...problem ? { problem } : {}
8579
+ };
8174
8580
  },
8175
8581
  about: (record3, _botId, deps) => {
8176
8582
  const most = limits(record3);
8177
- return "A Linux container only you use, with Node, Python, git, build tools, and Playwright with its browsers. You can install software there with sudo; it stays until the owner resets your sandbox, and /workspace, your home there, is kept when it is reset. Other Bots' sandboxes can't be reached from it; services of this machine that listen on all its addresses are at host.docker.internal. To show a web service of yours to people or other Bots, publish its port with ports.publish." + (most ? ` It may use at most ${most}; a process that takes more memory than that is ended.` : "") + (deps.computers.available ? "" : " This machine has no Docker yet, so your file and command tools are unavailable here; your chat tools work as usual.");
8583
+ return (computerType(record3) === "vm" ? VM : CONTAINER) + " You can install software there with sudo; it stays until the owner resets your sandbox, and /workspace, your home there, is kept when it is reset. Other Bots' sandboxes can't be reached from it; services of this machine that listen on all its addresses are at host.docker.internal. To show a web service of yours to people or other Bots, publish its port with ports.publish." + (most ? ` It may use at most ${most}; a process that takes more memory than that is ended.` : "") + (deps.computers.dockerProblem ? ` ${sentence(deps.computers.dockerProblem)}, so your file and command tools don't work here; your chat tools work as usual. Jarvy looks for Docker again every 30 seconds.` : "");
8178
8584
  },
8179
8585
  signature: (record3) => record3.id
8180
8586
  };
@@ -8207,9 +8613,9 @@ var BotEnvironments = class {
8207
8613
  kinds;
8208
8614
  current(botId, workspacePath) {
8209
8615
  const target3 = this.store.environments.placement(botId).current, signature = this.signature(target3);
8210
- const open2 = this.open.get(botId);
8211
- if (open2?.id === signature) return open2.view;
8212
- if (open2) this.retire(open2);
8616
+ const open3 = this.open.get(botId);
8617
+ if (open3?.id === signature) return open3.view;
8618
+ if (open3) this.retire(open3);
8213
8619
  const opened = this.track(signature, KINDS[target3.kind].open(target3, botId, workspacePath, this.kinds));
8214
8620
  this.open.set(botId, opened);
8215
8621
  return opened.view;
@@ -8298,24 +8704,24 @@ var BotEnvironments = class {
8298
8704
  return { changed, moved: { from, to: this.here(botId, workspacePath) }, name: name3 };
8299
8705
  }
8300
8706
  async release(botId) {
8301
- const open2 = this.open.get(botId);
8707
+ const open3 = this.open.get(botId);
8302
8708
  this.open.delete(botId);
8303
- await open2?.env.close();
8709
+ await open3?.env.close();
8304
8710
  await this.computers.remove(botId);
8305
8711
  }
8306
8712
  async close() {
8307
8713
  const all = [...this.open.values()];
8308
8714
  this.open.clear();
8309
- await Promise.all(all.map((open2) => open2.env.close()));
8715
+ await Promise.all(all.map((open3) => open3.env.close()));
8310
8716
  await this.computers.close();
8311
8717
  }
8312
8718
  /** What an open environment is for: changing a machine's directory reopens it where the owner put it. */
8313
8719
  signature(record3) {
8314
8720
  return KINDS[record3.kind].signature(record3);
8315
8721
  }
8316
- retire(open2) {
8317
- open2.retired = true;
8318
- if (!open2.busy) void open2.env.close();
8722
+ retire(open3) {
8723
+ open3.retired = true;
8724
+ if (!open3.busy) void open3.env.close();
8319
8725
  }
8320
8726
  /** Counts the operations running on an environment, so one the Bot has left closes only when they are done. */
8321
8727
  track(id, env) {
@@ -8351,13 +8757,13 @@ var BotEnvironments = class {
8351
8757
 
8352
8758
  // src/server/service/bot/machines.ts
8353
8759
  import { randomUUID as randomUUID18 } from "node:crypto";
8354
- import { dirname as dirname6, join as join12, posix } from "node:path";
8760
+ import { dirname as dirname7, join as join13, posix } from "node:path";
8355
8761
 
8356
8762
  // src/server/infra/env/ssh.ts
8357
8763
  import { spawn as spawn2 } from "node:child_process";
8358
8764
  import { mkdirSync as mkdirSync6, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
8359
- import { mkdir as mkdir5, mkdtemp as mkdtemp2, readFile as readFile3, rm as rm5 } from "node:fs/promises";
8360
- import { join as join11 } from "node:path";
8765
+ import { mkdir as mkdir6, mkdtemp as mkdtemp2, readFile as readFile3, rm as rm6 } from "node:fs/promises";
8766
+ import { join as join12 } from "node:path";
8361
8767
  import { HostKeyChangedError, HostKeyUnknownError, RemoteExecutionEnv as RemoteExecutionEnv2, detectPlatform, scanHostKey, sshArguments, sshConnection } from "@earendil-works/pi-env";
8362
8768
  var SshFault = class extends Error {
8363
8769
  constructor(code, message) {
@@ -8368,9 +8774,9 @@ var SshFault = class extends Error {
8368
8774
  var SCAN_ALIAS = "jarvy-scan";
8369
8775
  var TIMEOUT_MS2 = 3e4;
8370
8776
  async function scanHost(address2, runtime) {
8371
- await mkdir5(runtime, { recursive: true, mode: 448 });
8777
+ await mkdir6(runtime, { recursive: true, mode: 448 });
8372
8778
  try {
8373
- const scanned = await scanHostKey({ ...target(address2, SCAN_ALIAS), knownHostsFile: join11(runtime, "none") });
8779
+ const scanned = await scanHostKey({ ...target(address2, SCAN_ALIAS), knownHostsFile: join12(runtime, "none") });
8374
8780
  return {
8375
8781
  keys: scanned.lines.map((line) => line.trim().split(/\s+/).slice(1, 3).join(" ")),
8376
8782
  fingerprints: scanned.fingerprints.map((line) => line.replace(` ${SCAN_ALIAS} `, " ").replace(/^\d+\s+/, ""))
@@ -8380,13 +8786,13 @@ async function scanHost(address2, runtime) {
8380
8786
  }
8381
8787
  }
8382
8788
  async function generateKey(runtime, comment) {
8383
- await mkdir5(runtime, { recursive: true, mode: 448 });
8384
- const directory = await mkdtemp2(join11(runtime, "keygen-"));
8789
+ await mkdir6(runtime, { recursive: true, mode: 448 });
8790
+ const directory = await mkdtemp2(join12(runtime, "keygen-"));
8385
8791
  try {
8386
- await run("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", join11(directory, "key")]);
8387
- return { privateKey: await readFile3(join11(directory, "key"), "utf8"), publicKey: (await readFile3(join11(directory, "key.pub"), "utf8")).trim() };
8792
+ await run("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", join12(directory, "key")]);
8793
+ return { privateKey: await readFile3(join12(directory, "key"), "utf8"), publicKey: (await readFile3(join12(directory, "key.pub"), "utf8")).trim() };
8388
8794
  } finally {
8389
- await rm5(directory, { recursive: true, force: true });
8795
+ await rm6(directory, { recursive: true, force: true });
8390
8796
  }
8391
8797
  }
8392
8798
  function publicKeyOf(privateKey, comment) {
@@ -8453,7 +8859,7 @@ async function removeKey(access, comment) {
8453
8859
  }
8454
8860
  function sshEnvironment(id, access, directory, temp, onLog) {
8455
8861
  mkdirSync6(access.runtime, { recursive: true, mode: 448 });
8456
- const folder = join11(access.runtime, `open-${id}-${process.pid}-${Date.now().toString(36)}`);
8862
+ const folder = join12(access.runtime, `open-${id}-${process.pid}-${Date.now().toString(36)}`);
8457
8863
  const files = writeFilesSync(folder, access);
8458
8864
  const { connection } = sshConnection({ ...target(access, access.alias), ...files, ...onLog ? { onLog } : {} });
8459
8865
  return overDurable(id, "ssh", new RemoteExecutionEnv2({ connection, id: `ssh:${id}`, cwd: directory }), {
@@ -8472,21 +8878,21 @@ function target(address2, alias2) {
8472
8878
  return { host: address2.host, port: address2.port, user: address2.user, hostKeyAlias: alias2, configFile: "/dev/null" };
8473
8879
  }
8474
8880
  async function withFiles(access, work) {
8475
- await mkdir5(access.runtime, { recursive: true, mode: 448 });
8476
- const directory = await mkdtemp2(join11(access.runtime, "use-"));
8881
+ await mkdir6(access.runtime, { recursive: true, mode: 448 });
8882
+ const directory = await mkdtemp2(join12(access.runtime, "use-"));
8477
8883
  try {
8478
8884
  return await work(writeFilesSync(directory, access));
8479
8885
  } finally {
8480
- await rm5(directory, { recursive: true, force: true });
8886
+ await rm6(directory, { recursive: true, force: true });
8481
8887
  }
8482
8888
  }
8483
8889
  function writeFilesSync(directory, access) {
8484
8890
  mkdirSync6(directory, { recursive: true, mode: 448 });
8485
- const knownHostsFile = join11(directory, "known_hosts");
8891
+ const knownHostsFile = join12(directory, "known_hosts");
8486
8892
  writeFileSync3(knownHostsFile, access.hostKeys.map((key) => `${access.alias} ${key}
8487
8893
  `).join(""), { mode: 384 });
8488
8894
  if (access.password) {
8489
- const secret = join11(directory, "password"), askpass = join11(directory, "askpass"), ssh2 = join11(directory, "ssh");
8895
+ const secret = join12(directory, "password"), askpass = join12(directory, "askpass"), ssh2 = join12(directory, "ssh");
8490
8896
  writeFileSync3(secret, `${access.password}
8491
8897
  `, { mode: 384 });
8492
8898
  writeFileSync3(askpass, `#!/bin/sh
@@ -8495,7 +8901,7 @@ exec cat ${quote(secret)}
8495
8901
  writeFileSync3(ssh2, ["#!/bin/sh", `exec env -u SSH_AUTH_SOCK SSH_ASKPASS=${quote(askpass)} SSH_ASKPASS_REQUIRE=force DISPLAY=none ssh -o BatchMode=no -o PreferredAuthentications=keyboard-interactive,password -o PubkeyAuthentication=no -o NumberOfPasswordPrompts=1 -o ConnectTimeout=15 "$@"`, ""].join("\n"), { mode: 448 });
8496
8902
  return { knownHostsFile, ssh: ssh2 };
8497
8903
  }
8498
- const identityFile = join11(directory, "key");
8904
+ const identityFile = join12(directory, "key");
8499
8905
  writeFileSync3(identityFile, access.privateKey.endsWith("\n") ? access.privateKey : `${access.privateKey}
8500
8906
  `, { mode: 384 });
8501
8907
  return { knownHostsFile, identityFile };
@@ -8558,7 +8964,7 @@ var SshMachines = class {
8558
8964
  this.store = store;
8559
8965
  this.chats = chats;
8560
8966
  this.changed = changed;
8561
- this.runtime = join12(dirname6(store.path), "ssh");
8967
+ this.runtime = join13(dirname7(store.path), "ssh");
8562
8968
  clearRuntime(this.runtime);
8563
8969
  }
8564
8970
  runtime;
@@ -8842,7 +9248,7 @@ function directoryIn(home, value2) {
8842
9248
  // src/server/infra/storage/history-repository.ts
8843
9249
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
8844
9250
  import { chmodSync as chmodSync3, mkdirSync as mkdirSync7 } from "node:fs";
8845
- import { dirname as dirname7 } from "node:path";
9251
+ import { dirname as dirname8 } from "node:path";
8846
9252
  var json = (value2) => value2 == null ? null : JSON.stringify(value2);
8847
9253
  var CALL = "EXISTS (SELECT 1 FROM json_each(history.message, '$.content') b WHERE json_extract(b.value, '$.type')=? AND json_extract(b.value, '$.tool_call_id')=?)";
8848
9254
  var BLOCKS = "FROM json_each(history.message,'$.content') b WHERE json_extract(b.value,'$.type')";
@@ -8854,7 +9260,7 @@ var SUMMARY = `SELECT id,timestamp,role,model,
8854
9260
  var HistoryRepository = class {
8855
9261
  db;
8856
9262
  constructor(path) {
8857
- mkdirSync7(dirname7(path), { recursive: true, mode: 448 });
9263
+ mkdirSync7(dirname8(path), { recursive: true, mode: 448 });
8858
9264
  this.db = new DatabaseSync2(path);
8859
9265
  chmodSync3(path, 384);
8860
9266
  const version = this.db.prepare("PRAGMA user_version").get().user_version;
@@ -8893,13 +9299,13 @@ var HistoryRepository = class {
8893
9299
  });
8894
9300
  }
8895
9301
  /** Model calls since a time, per provider and model: every assistant record with usage is one call. */
8896
- usage(since) {
9302
+ usage(since2) {
8897
9303
  const rows3 = this.db.prepare(`SELECT json_extract(model,'$.provider') AS provider,json_extract(model,'$.id') AS model,count(*) AS calls,
8898
9304
  COALESCE(SUM(json_extract(usage,'$.input_tokens')),0) AS input,COALESCE(SUM(json_extract(usage,'$.output_tokens')),0) AS output,
8899
9305
  COALESCE(SUM(json_extract(usage,'$.cache_read_tokens')),0) AS cacheRead,COALESCE(SUM(json_extract(usage,'$.cache_write_tokens')),0) AS cacheWrite,
8900
9306
  COALESCE(SUM(json_extract(usage,'$.cost.total')),0) AS cost,COALESCE(MAX(json_extract(usage,'$.cost.total')),0)>0 AS priced
8901
9307
  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);
9308
+ GROUP BY 1,2 ORDER BY cost DESC,calls DESC`).all(since2);
8903
9309
  return rows3.map(({ priced, cost, ...row2 }) => ({ ...row2, cost: priced ? cost : null }));
8904
9310
  }
8905
9311
  decodeSummary(row2) {
@@ -8960,8 +9366,8 @@ var Memory = class {
8960
9366
  timeline(before, limit2) {
8961
9367
  return this.history().timeline(before, limit2);
8962
9368
  }
8963
- usage(since) {
8964
- return this.history().usage(since);
9369
+ usage(since2) {
9370
+ return this.history().usage(since2);
8965
9371
  }
8966
9372
  read(id) {
8967
9373
  const record3 = this.history().read(id);
@@ -9172,89 +9578,37 @@ var Model = class {
9172
9578
  import { posix as posix2 } from "node:path";
9173
9579
 
9174
9580
  // src/server/infra/files/workspace.ts
9175
- import { mkdir as mkdir6, writeFile as writeFile3 } from "node:fs/promises";
9176
- import { join as join13 } from "node:path";
9581
+ import { mkdir as mkdir7, writeFile as writeFile3 } from "node:fs/promises";
9582
+ import { join as join14 } from "node:path";
9177
9583
  var LocalWorkspace = class {
9178
9584
  constructor(cwd) {
9179
9585
  this.cwd = cwd;
9180
9586
  }
9181
9587
  get tempDir() {
9182
- return join13(this.cwd, "temp");
9588
+ return join14(this.cwd, "temp");
9183
9589
  }
9184
9590
  async prepare() {
9185
- await mkdir6(this.tempDir, { recursive: true, mode: 448 });
9591
+ await mkdir7(this.tempDir, { recursive: true, mode: 448 });
9186
9592
  }
9187
9593
  async writeTempFile(name3, content2, signal) {
9188
9594
  await this.prepare();
9189
- const path = join13(this.tempDir, name3);
9595
+ const path = join14(this.tempDir, name3);
9190
9596
  await writeFile3(path, content2, { encoding: "utf8", flag: "wx", mode: 384, signal });
9191
9597
  return path;
9192
9598
  }
9193
9599
  };
9194
9600
 
9195
- // src/server/infra/files/skills.ts
9196
- import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync4 } from "node:fs";
9197
- import { mkdir as mkdir7, writeFile as writeFile4 } from "node:fs/promises";
9198
- import { dirname as dirname8, join as join14 } from "node:path";
9199
- import { fileURLToPath } from "node:url";
9200
-
9201
- // src/server/shared/skill.ts
9202
- var skillPath = (name3) => `skills/${name3}/SKILL.md`;
9203
-
9204
- // src/server/infra/files/skills.ts
9205
- function builtinSkills() {
9206
- const dir = skillsDir();
9207
- if (!dir) return [];
9208
- const skills = [];
9209
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
9210
- if (!entry.isDirectory()) continue;
9211
- const file = join14(dir, entry.name, "SKILL.md");
9212
- if (!existsSync4(file)) continue;
9213
- const skill = parseSkill(entry.name, readFileSync4(file, "utf8"));
9214
- if (skill) skills.push(skill);
9215
- else console.warn(`Jarvy: skipped the skill in ${entry.name}: SKILL.md needs a name matching its folder and a description`);
9216
- }
9217
- return skills.sort((a, b) => a.name.localeCompare(b.name));
9218
- }
9219
- async function installSkills(workspace, skills) {
9220
- for (const skill of skills) {
9221
- const file = join14(workspace, skillPath(skill.name));
9222
- await mkdir7(dirname8(file), { recursive: true });
9223
- await writeFile4(file, skill.content, "utf8");
9224
- }
9225
- }
9226
- function skillsDir() {
9227
- let dir = dirname8(fileURLToPath(import.meta.url));
9228
- for (let depth = 0; depth < 6; depth++) {
9229
- if (existsSync4(join14(dir, "package.json"))) return existsSync4(join14(dir, "skills")) ? join14(dir, "skills") : null;
9230
- const parent = dirname8(dir);
9231
- if (parent === dir) break;
9232
- dir = parent;
9233
- }
9234
- return null;
9235
- }
9236
- function parseSkill(folder, content2) {
9237
- const head = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(content2);
9238
- if (!head) return null;
9239
- const field2 = (key) => new RegExp(`^${key}:\\s*(.+)$`, "m").exec(head[1])?.[1]?.trim() ?? "";
9240
- const name3 = field2("name"), description = field2("description");
9241
- if (name3 !== folder || !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name3) || !description) return null;
9242
- return { name: name3, description, content: content2 };
9243
- }
9244
-
9245
9601
  // src/server/service/bot/workspace.ts
9246
9602
  var CHUNK = 4 * 1024 * 1024;
9247
9603
  var Workspace = class {
9248
- constructor(cwd, current, home, skills = []) {
9604
+ constructor(cwd, current, home) {
9249
9605
  this.current = current;
9250
9606
  this.home = home;
9251
- this.skills = skills;
9252
9607
  this.local = new LocalWorkspace(cwd);
9253
9608
  }
9254
9609
  local;
9255
9610
  async prepare() {
9256
9611
  await this.local.prepare();
9257
- await installSkills(this.local.cwd, this.skills);
9258
9612
  }
9259
9613
  /** A file in the temporary directory of the environment the Bot works in, by the path it sees there. */
9260
9614
  async writeTempFile(name3, content2, signal) {
@@ -10326,6 +10680,12 @@ function channel(context2, chatId) {
10326
10680
  return chat;
10327
10681
  }
10328
10682
  var agentTools = [
10683
+ tool(
10684
+ "skills.read",
10685
+ "Read one of the skills your prompt lists: its whole guide. Works wherever you work, also when your file tools can't.",
10686
+ Type11.Object({ name: Type11.String({ minLength: 1, maxLength: 80, description: "The skill's name, as your prompt lists it" }) }, { additionalProperties: false }),
10687
+ (input, context2) => ops(context2).skill(input.name)
10688
+ ),
10329
10689
  tool(
10330
10690
  "models.list",
10331
10691
  "List the models you can give a Bot: each connection with its models and their thinking levels. Only the owner adds connections, keys and logins, in Settings.",
@@ -10503,9 +10863,9 @@ function remember(map, id, definition) {
10503
10863
  var noticeName = (note) => note.type === "thread" ? `this thread's summary (version ${note.version})` : `the notice of \u300C${note.title}\u300D (${note.type}, version ${note.version})`;
10504
10864
  var unreadNoteLine = (notes) => notes.length ? `<notice_unread>${notes.map((note) => `<chat${attribute("id", note.chatId)}${attribute("title", note.title)}${attribute("type", note.type)}${attribute("version", String(note.version))}/>`).join("")}
10505
10865
  <note>You haven't read ${notes.map(noticeName).join(" or ")} yet. Read ${notes.length === 1 ? "it" : "them"} with chats.info (${notes.map((note) => `chatId: "${note.chatId}"`).join(", ")}), make sure your message follows ${notes.length === 1 ? "it" : "them"} before you send here.</note></notice_unread>` : "";
10506
- var environmentLine = (place) => place ? `<environment${attribute("name", place.name)}${attribute("directory", place.directory)}/>` : "";
10866
+ var environmentLine = (place) => place ? `<environment${attribute("name", place.name)}${attribute("directory", place.directory)}${place.problem ? attribute("problem", place.problem) : ""}/>` : "";
10507
10867
  var iso2 = (time2) => new Date(time2).toISOString().replace(".000Z", "Z");
10508
- var welcome = (owner, language) => `${owner} has just set up this chat platform and picked your model. You are their agent Bot. Write to them in a DM (messages.send with to: "${owner}") and welcome them in ${WELCOME_LANGUAGES[language]}, the language of their interface: say in a few sentences what it is and how you can help, such as building a team of Bots for their work and running the platform for them. Then ask what they want to get done: a software project, writing, research or something else.`;
10868
+ var welcome = (owner, language) => `${owner} has just set up this chat platform and picked your model. You are their agent Bot. Write to them in a DM (messages.send with to: "${owner}") and welcome them in ${WELCOME_LANGUAGES[language]}, the language of their interface: say in a few sentences what it is and how you can help, such as building a team of Bots for their work and running the platform for them. Then ask what they want to get done: a software project, writing, research or something else. If the environment at the end of this batch names a problem, also tell them in a sentence what it means for the Bots and offer to help set it up, as your setup skill describes.`;
10509
10869
  function encodeNoticeBatch(botId, notices, environment, prompt, unreadNotes) {
10510
10870
  if (!notices.length && !prompt) throw new Error("Empty notice batch");
10511
10871
  const chats = /* @__PURE__ */ new Map(), members = /* @__PURE__ */ new Map();
@@ -10653,8 +11013,8 @@ var BotInbox = class {
10653
11013
  }
10654
11014
  // Its conversation was compacted (A73): the open threads it follows, as they are now.
10655
11015
  case "followed": {
10656
- const open2 = this.chats.threads.openFollowed(this.botId, FOLLOWED_SHOWN);
10657
- return open2.total ? { kind: "followed", id, total: open2.total, threads: open2.threads, createdAt } : null;
11016
+ const open3 = this.chats.threads.openFollowed(this.botId, FOLLOWED_SHOWN);
11017
+ return open3.total ? { kind: "followed", id, total: open3.total, threads: open3.threads, createdAt } : null;
10658
11018
  }
10659
11019
  }
10660
11020
  }
@@ -10925,7 +11285,7 @@ var AGENT_ROLE = `
10925
11285
  ## Your role
10926
11286
  You are the owner's agent Bot. Besides working like any Bot, you help them set up and run Jarvy itself.
10927
11287
  Help a new owner get started: find out what they want to get done, suggest a team of Bots for it, then create and set up those Bots.
10928
- The chat gateway lists tools only you have: models.list, bots.create, bots.update, bots.start, bots.stop and bots.usage. bots.delete, chats.delete, chats.removeMembers and sections.delete first ask the owner on a card, and delete nothing unless they confirm.
11288
+ The chat gateway lists tools only you have: skills.read, models.list, bots.create, bots.update, bots.start, bots.stop and bots.usage. bots.delete, chats.delete, chats.removeMembers and sections.delete first ask the owner on a card, and delete nothing unless they confirm.
10929
11289
  Other Bots may ask you to do these things for them. Do the ordinary ones; deleting always waits for the owner's confirmation.
10930
11290
  You can't add model connections, keys or logins. The owner does that in Settings, so point them there when a model is missing.
10931
11291
  `;
@@ -10943,7 +11303,7 @@ You are in a group chat with people and other Bots. You take part in direct mess
10943
11303
  Here your name is ${bot.name}, and your description is: ${bot.description}
10944
11304
  ` },
10945
11305
  { name: "Your role", text: bot.agent ? AGENT_ROLE : "" },
10946
- { name: "Skills", text: skillsSection(setup, skills) },
11306
+ { name: "Skills", text: skillsSection(skills) },
10947
11307
  { name: "Rules", text: `
10948
11308
  ## Language
10949
11309
  Write to people in the language they write to you in. In a channel or thread, use the language its conversation is held in.
@@ -10987,16 +11347,63 @@ Your file and command tools run on your own computer: a Linux container only you
10987
11347
  You can also work in other, external workspaces. environments.list shows the ones your owner has given you; environments.switch moves you to one, and from then on your file and command tools run there until you switch back. Your chat tools are the same either way. To work on another machine over SSH, ask your owner to add it with environments.request; they type its password on that card, not in the chat. Each batch of messages ends with the environment you are in now.
10988
11348
  `;
10989
11349
  }
10990
- function skillsSection(setup, skills) {
11350
+ function skillsSection(skills) {
10991
11351
  if (!skills.length) return "";
10992
- const base = setup.home().cwd;
10993
11352
  return `
10994
11353
  ## Skills
10995
- Skills are guides that come with this chat platform for kinds of work you help with. When a task matches one, read its file before you start, and follow it. They are suggestions for the owner: propose a plan from them and act once the owner agrees. They are kept in your workspace and written again each time you start, so changes to them don't last.
10996
- ${skills.map((skill) => `- ${skill.name}: ${skill.description} File: ${base}/${skillPath(skill.name)}`).join("\n")}
11354
+ Skills are guides that come with this chat platform for kinds of work you help with. When a task matches one, read it with skills.read before you start, and follow it. They are suggestions for the owner: propose a plan from them and act once the owner agrees.
11355
+ ${skills.map((skill) => `- ${skill.name}: ${skill.description}`).join("\n")}
10997
11356
  `;
10998
11357
  }
10999
11358
 
11359
+ // src/server/infra/files/skills.ts
11360
+ import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync5 } from "node:fs";
11361
+ import { rm as rm7, rmdir } from "node:fs/promises";
11362
+ import { dirname as dirname10, join as join16 } from "node:path";
11363
+ import { fileURLToPath } from "node:url";
11364
+ function builtinSkills() {
11365
+ const dir = skillsDir();
11366
+ if (!dir) return [];
11367
+ const skills = [];
11368
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
11369
+ if (!entry.isDirectory()) continue;
11370
+ const file = join16(dir, entry.name, "SKILL.md");
11371
+ if (!existsSync5(file)) continue;
11372
+ const skill = parseSkill(entry.name, readFileSync5(file, "utf8"));
11373
+ if (skill) skills.push(skill);
11374
+ else console.warn(`Jarvy: skipped the skill in ${entry.name}: SKILL.md needs a name matching its folder and a description`);
11375
+ }
11376
+ return skills.sort((a, b) => a.name.localeCompare(b.name));
11377
+ }
11378
+ async function removeSkillCopies(workspace, skills) {
11379
+ const root = join16(workspace, "skills");
11380
+ for (const skill of skills) {
11381
+ await rm7(join16(root, skill.name, "SKILL.md"), { force: true });
11382
+ await rmdir(join16(root, skill.name)).catch(() => {
11383
+ });
11384
+ }
11385
+ await rmdir(root).catch(() => {
11386
+ });
11387
+ }
11388
+ function skillsDir() {
11389
+ let dir = dirname10(fileURLToPath(import.meta.url));
11390
+ for (let depth = 0; depth < 6; depth++) {
11391
+ if (existsSync5(join16(dir, "package.json"))) return existsSync5(join16(dir, "skills")) ? join16(dir, "skills") : null;
11392
+ const parent = dirname10(dir);
11393
+ if (parent === dir) break;
11394
+ dir = parent;
11395
+ }
11396
+ return null;
11397
+ }
11398
+ function parseSkill(folder, content2) {
11399
+ const head = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(content2);
11400
+ if (!head) return null;
11401
+ const field2 = (key) => new RegExp(`^${key}:\\s*(.+)$`, "m").exec(head[1])?.[1]?.trim() ?? "";
11402
+ const name3 = field2("name"), description = field2("description");
11403
+ if (name3 !== folder || !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name3) || !description) return null;
11404
+ return { name: name3, description, content: content2 };
11405
+ }
11406
+
11000
11407
  // src/server/shared/live.ts
11001
11408
  var LIVE_STEPS = 300;
11002
11409
  var LIVE_TEXT = 4e3;
@@ -11252,11 +11659,12 @@ var LiveTurns = class {
11252
11659
  // src/server/service/bot/agent.ts
11253
11660
  var same2 = (a, b) => a.trim().replace(/^@/, "").toLocaleLowerCase() === b.trim().toLocaleLowerCase();
11254
11661
  var AgentOps = class {
11255
- constructor(bots, store, chats, deliveries) {
11662
+ constructor(bots, store, chats, deliveries, skills = []) {
11256
11663
  this.bots = bots;
11257
11664
  this.store = store;
11258
11665
  this.chats = chats;
11259
11666
  this.deliveries = deliveries;
11667
+ this.skills = skills;
11260
11668
  }
11261
11669
  get owner() {
11262
11670
  return this.store.account.userMemberId();
@@ -11268,6 +11676,12 @@ var AgentOps = class {
11268
11676
  if (!bot) throw new ChatError(404, `No Bot named ${name3} (see bots.list)`);
11269
11677
  return bot;
11270
11678
  }
11679
+ /** A skill's guide (A55), read from Jarvy itself so it can be read wherever the agent works and when its tools can't. */
11680
+ skill(name3) {
11681
+ const skill = this.skills.find((item) => item.name === name3.trim().toLowerCase());
11682
+ if (!skill) throw new ChatError(404, `No skill named ${name3}; there are ${this.skills.map((item) => item.name).join(", ") || "none"}`);
11683
+ return { name: skill.name, description: skill.description, content: skill.content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "").trim() };
11684
+ }
11271
11685
  /** Connected models and their thinking levels; never credentials. */
11272
11686
  models() {
11273
11687
  return this.store.connections.list().filter((connection) => connection.models.length).map((connection) => ({
@@ -11333,8 +11747,8 @@ var AgentOps = class {
11333
11747
  return this.bots.status(bot.id).status;
11334
11748
  }
11335
11749
  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) };
11750
+ const since2 = Date.now() - days * 24 * 60 * 60 * 1e3;
11751
+ return { since: new Date(since2).toISOString(), models: this.bots.memory(bot.id).usage(since2) };
11338
11752
  }
11339
11753
  /** Deletions run as the owner, who has just confirmed them on a card. */
11340
11754
  async deleteBot(bot) {
@@ -11587,7 +12001,7 @@ function text4(value2, label, max) {
11587
12001
  var BotService = class {
11588
12002
  constructor(deps) {
11589
12003
  this.deps = deps;
11590
- this.agent = new AgentOps(this, deps.store, deps.chats, deps.deliveries);
12004
+ this.agent = new AgentOps(this, deps.store, deps.chats, deps.deliveries, this.skills);
11591
12005
  this.computers = new Computers({ store: deps.store, changed: () => this.listChanged() });
11592
12006
  this.computers.adopt(deps.store.bots.list().map((record3) => record3.id));
11593
12007
  this.ports = new PublishedPorts(deps.store, this.computers, () => deps.listening?.() ?? null);
@@ -11618,9 +12032,11 @@ var BotService = class {
11618
12032
  let bot = this.bots.get(id);
11619
12033
  if (bot) return bot;
11620
12034
  const { store, chats, files, credentials } = this.deps, live = this.live(id), skills = id === AGENT_BOT_ID ? this.skills : [];
12035
+ if (skills.length) void removeSkillCopies(record3.workspacePath, skills).catch(() => {
12036
+ });
11621
12037
  const here = () => {
11622
- const place = this.environments.here(id, record3.workspacePath);
11623
- return { name: place.name, directory: place.directory };
12038
+ const place = this.environments.here(id, record3.workspacePath), problem = place.kind === "sandbox" ? this.computers.dockerProblem : null;
12039
+ return { name: place.name, directory: place.directory, ...problem ? { problem: `${problem}, so your file and command tools don't work here` } : {} };
11624
12040
  };
11625
12041
  const runtime = new AgentRuntime(new BotInbox(id, store.runtime, chats, files, store.tasks, here), (setup, model, reference, activity) => (this.deps.factory ?? PiSession.create)({
11626
12042
  store,
@@ -11645,8 +12061,8 @@ var BotService = class {
11645
12061
  const workspace = new Workspace(record3.workspacePath, () => this.environments.current(id, record3.workspacePath), () => {
11646
12062
  const place = this.environments.default(id, record3.workspacePath);
11647
12063
  return { kind: "computer", cwd: place.directory };
11648
- }, skills);
11649
- const memory = new Memory(join16(dirname10(record3.workspacePath), "history.db"));
12064
+ });
12065
+ const memory = new Memory(join17(dirname11(record3.workspacePath), "history.db"));
11650
12066
  bot = new Bot(id, {
11651
12067
  identity: new Identity(id, store),
11652
12068
  model: new Model(id, store, resolveThinking),
@@ -11778,11 +12194,12 @@ var BotService = class {
11778
12194
  if (!record3) throw new RuntimeFault("bot_missing", "Bot not found", 404);
11779
12195
  return record3;
11780
12196
  }
11781
- /** Starting (or resetting, which starts afresh) returns at once: the Bot's state follows as it changes. */
12197
+ /** Starting (or resetting, which starts afresh, or restarting, which a VM's new size needs) returns at once: the
12198
+ * Bot's state follows as it changes. */
11782
12199
  async computer(id, action) {
11783
12200
  this.describe(id);
11784
- if (action === "stop") await this.computers.stop(id);
11785
- else {
12201
+ if (action === "stop" || action === "restart") await this.computers.stop(id);
12202
+ if (action !== "stop") {
11786
12203
  if (action === "reset") {
11787
12204
  await this.computers.reset(id);
11788
12205
  this.ports.unpublishAll(id);
@@ -11792,6 +12209,24 @@ var BotService = class {
11792
12209
  }
11793
12210
  return this.describe(id);
11794
12211
  }
12212
+ /** Makes the sandbox a container or a VM (A85) and starts the new one; what ran there is gone, and so are the links
12213
+ * to it. */
12214
+ async setComputerType(id, type) {
12215
+ this.describe(id);
12216
+ if (type !== "container" && type !== "vm") throw new ValidationError("type is container or vm", "type_invalid");
12217
+ await this.computers.setType(id, type);
12218
+ this.ports.unpublishAll(id);
12219
+ void this.computers.ensure(id).catch(() => {
12220
+ });
12221
+ return this.describe(id);
12222
+ }
12223
+ /** Whether VM sandboxes can be used here (A85), as last checked; asking the first time, or `again`, starts a check,
12224
+ * `checking` until it is done. */
12225
+ vmSupport(again = false) {
12226
+ void this.computers.checkVms(again).catch(() => {
12227
+ });
12228
+ return this.computers.vmSupport;
12229
+ }
11795
12230
  /** What the sandbox may use at most (A75); returns the Bot with them. */
11796
12231
  async setComputerLimits(id, limits2) {
11797
12232
  this.describe(id);
@@ -11826,6 +12261,10 @@ var BotService = class {
11826
12261
  memory(id) {
11827
12262
  return this.get(id).memory;
11828
12263
  }
12264
+ /** Usage across every Bot since a time (A81), from each one's History. */
12265
+ usage(since2) {
12266
+ return usageOverview(since2, this.deps.store.bots.list().map((record3) => [record3.id, this.memory(record3.id).usage(since2)]));
12267
+ }
11829
12268
  /** A delivery reached a Bot (A41); the Bot responds to its urgency. */
11830
12269
  deliver(id, urgency) {
11831
12270
  if (this.closed || !this.deps.store.bots.get(id)) return;
@@ -11904,7 +12343,7 @@ var BotService = class {
11904
12343
  if (!this.deps.store.bots.delete(id)) throw new RuntimeFault("bot_missing", "Bot not found", 404);
11905
12344
  this.ports.changed();
11906
12345
  await this.deps.chats.attachments.clean();
11907
- if (!keepFiles) await rm6(dirname10(workspacePath), { recursive: true, force: true });
12346
+ if (!keepFiles) await rm8(dirname11(workspacePath), { recursive: true, force: true });
11908
12347
  }
11909
12348
  async close() {
11910
12349
  if (this.closed) return;
@@ -12272,7 +12711,7 @@ var Application = class _Application {
12272
12711
  retries: 0,
12273
12712
  stale: 3e4,
12274
12713
  update: 1e4,
12275
- lockfilePath: join17(root, ".runtime.lock"),
12714
+ lockfilePath: join18(root, ".runtime.lock"),
12276
12715
  onCompromised: () => {
12277
12716
  console.error("[runtime] data lock compromised");
12278
12717
  options.onCompromised?.();
@@ -12316,10 +12755,10 @@ var Application = class _Application {
12316
12755
 
12317
12756
  // src/server/daemon.ts
12318
12757
  import { spawn as spawn3 } from "node:child_process";
12319
- import { closeSync as closeSync2, mkdirSync as mkdirSync8, openSync as openSync2, readFileSync as readFileSync5, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
12320
- import { join as join18, resolve as resolve4 } from "node:path";
12321
- var pidPath = (dir) => join18(resolve4(dir), "jarvy.pid");
12322
- var logPath = (dir) => join18(resolve4(dir), "jarvy.log");
12758
+ import { closeSync as closeSync2, mkdirSync as mkdirSync8, openSync as openSync2, readFileSync as readFileSync6, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
12759
+ import { join as join19, resolve as resolve4 } from "node:path";
12760
+ var pidPath = (dir) => join19(resolve4(dir), "jarvy.pid");
12761
+ var logPath = (dir) => join19(resolve4(dir), "jarvy.log");
12323
12762
  function writePidFile(dir, url) {
12324
12763
  const record3 = { pid: process.pid, startToken: startToken(process.pid), url, startedAt: Date.now() };
12325
12764
  writeFileSync4(pidPath(dir), JSON.stringify(record3), { mode: 384 });
@@ -12329,14 +12768,14 @@ function removePidFile(dir) {
12329
12768
  }
12330
12769
  function readRecord(dir) {
12331
12770
  try {
12332
- return JSON.parse(readFileSync5(pidPath(dir), "utf8"));
12771
+ return JSON.parse(readFileSync6(pidPath(dir), "utf8"));
12333
12772
  } catch {
12334
12773
  return null;
12335
12774
  }
12336
12775
  }
12337
12776
  function startToken(pid) {
12338
12777
  try {
12339
- return readFileSync5(`/proc/${pid}/stat`, "utf8").split(") ").pop().split(" ")[19] ?? "";
12778
+ return readFileSync6(`/proc/${pid}/stat`, "utf8").split(") ").pop().split(" ")[19] ?? "";
12340
12779
  } catch {
12341
12780
  return "";
12342
12781
  }
@@ -12379,7 +12818,7 @@ function startBackground(script, runArgs, dir) {
12379
12818
  }
12380
12819
  function lastLogLine(dir) {
12381
12820
  try {
12382
- return readFileSync5(logPath(dir), "utf8").slice(-4e3).trim().split("\n").reverse().find((line) => line.startsWith("Jarvy: "))?.slice(7) ?? null;
12821
+ return readFileSync6(logPath(dir), "utf8").slice(-4e3).trim().split("\n").reverse().find((line) => line.startsWith("Jarvy: "))?.slice(7) ?? null;
12383
12822
  } catch {
12384
12823
  return null;
12385
12824
  }
@@ -12543,8 +12982,8 @@ async function main() {
12543
12982
  try {
12544
12983
  if (!store.account.isInitialized()) await initialize(store);
12545
12984
  const { host, port, url } = listenOptions(args);
12546
- const webRoot = join19(dirname11(fileURLToPath2(import.meta.url)), "../web");
12547
- if (!existsSync5(join19(webRoot, "index.html"))) throw new Error("Web build missing. Run npm run build first");
12985
+ const webRoot = join20(dirname12(fileURLToPath2(import.meta.url)), "../web");
12986
+ if (!existsSync6(join20(webRoot, "index.html"))) throw new Error("Web build missing. Run npm run build first");
12548
12987
  const tls = app.connection.prepare(host, port);
12549
12988
  const server = createJarvyServer(app, webRoot, tls);
12550
12989
  const published = new PublishedListeners(app, tls, host, port);