@goodfish/jarvy 0.12.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/THIRD_PARTY_NOTICE.md +2 -0
- package/dist/server/cli.js +187 -86
- package/dist/web/assets/data-uMIXh-O1.js +1 -0
- package/dist/web/assets/index-BcZqnyAQ.js +837 -0
- package/dist/web/assets/index-QCSgDIcx.css +1 -0
- package/dist/web/index.html +2 -2
- package/licenses/UNICODE-LICENSE-V3.txt +39 -0
- package/package.json +2 -1
- package/dist/web/assets/index-Bt8AJEH6.css +0 -1
- package/dist/web/assets/index-tNqSfXZo.js +0 -787
package/dist/server/cli.js
CHANGED
|
@@ -179,6 +179,7 @@ function installAuthentication(api, account) {
|
|
|
179
179
|
api.post("/logout", (c) => {
|
|
180
180
|
account.logout(c.get("sessionToken"));
|
|
181
181
|
sessionCookie(c, cookie2(c), "", 0);
|
|
182
|
+
c.header("Clear-Site-Data", '"cache"');
|
|
182
183
|
return c.json({ ok: true });
|
|
183
184
|
});
|
|
184
185
|
}
|
|
@@ -490,14 +491,73 @@ function byteRange(header, size) {
|
|
|
490
491
|
var ATTACHMENT_MAX_BYTES = 4 * 1024 ** 3;
|
|
491
492
|
|
|
492
493
|
// src/server/infra/files/attachments.ts
|
|
493
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
494
|
+
import { createHash, randomUUID as randomUUID2 } from "node:crypto";
|
|
494
495
|
import { createReadStream } from "node:fs";
|
|
495
|
-
import { mkdir, open, readdir, rename, rm, stat } from "node:fs/promises";
|
|
496
|
+
import { mkdir, open, readdir, rename as rename2, rm as rm2, stat as stat2 } from "node:fs/promises";
|
|
496
497
|
import { dirname, join } from "node:path";
|
|
498
|
+
|
|
499
|
+
// src/server/infra/files/thumbnails.ts
|
|
500
|
+
import { randomUUID } from "node:crypto";
|
|
501
|
+
import { rename, rm, stat } from "node:fs/promises";
|
|
502
|
+
import sharp from "sharp";
|
|
503
|
+
var WIDTH = 1600;
|
|
504
|
+
var HEIGHT = 640;
|
|
505
|
+
var SMALL = 300 * 1024;
|
|
506
|
+
var FORMATS = /* @__PURE__ */ new Set(["jpeg", "png", "webp", "avif"]);
|
|
507
|
+
var AT_ONCE = 4;
|
|
508
|
+
var Thumbnails = class {
|
|
509
|
+
making = /* @__PURE__ */ new Map();
|
|
510
|
+
running = 0;
|
|
511
|
+
waiting = [];
|
|
512
|
+
/** The thumbnail's path for the original at `source`, kept at `target`; null to show the original. */
|
|
513
|
+
async thumbnail(source2, target3) {
|
|
514
|
+
if (await stat(target3).then(() => true, () => false)) return target3;
|
|
515
|
+
let pending = this.making.get(target3);
|
|
516
|
+
if (!pending) {
|
|
517
|
+
pending = this.make(source2, target3).finally(() => this.making.delete(target3));
|
|
518
|
+
this.making.set(target3, pending);
|
|
519
|
+
}
|
|
520
|
+
return pending;
|
|
521
|
+
}
|
|
522
|
+
async make(source2, target3) {
|
|
523
|
+
const meta = await sharp(source2).metadata().catch(() => null);
|
|
524
|
+
if (!meta?.width || !meta.height || !FORMATS.has(meta.format ?? "") || (meta.pages ?? 1) > 1) return null;
|
|
525
|
+
const [width, height] = (meta.orientation ?? 1) >= 5 ? [meta.height, meta.width] : [meta.width, meta.height];
|
|
526
|
+
if (width <= WIDTH && height <= HEIGHT && (meta.size ?? (await stat(source2)).size) <= SMALL) return null;
|
|
527
|
+
await this.turn();
|
|
528
|
+
const part = `${target3}.${randomUUID()}.part`;
|
|
529
|
+
try {
|
|
530
|
+
await sharp(source2).rotate().resize(WIDTH, HEIGHT, { fit: "inside", withoutEnlargement: true }).webp({ quality: 80 }).toFile(part);
|
|
531
|
+
await rename(part, target3);
|
|
532
|
+
return target3;
|
|
533
|
+
} catch (error) {
|
|
534
|
+
console.warn("[files] could not make a thumbnail", { source: source2, error: error instanceof Error ? error.message : String(error) });
|
|
535
|
+
await rm(part, { force: true });
|
|
536
|
+
return null;
|
|
537
|
+
} finally {
|
|
538
|
+
this.done();
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
async turn() {
|
|
542
|
+
if (this.running < AT_ONCE) {
|
|
543
|
+
this.running++;
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
await new Promise((resolve5) => this.waiting.push(resolve5));
|
|
547
|
+
}
|
|
548
|
+
done() {
|
|
549
|
+
const next = this.waiting.shift();
|
|
550
|
+
if (next) next();
|
|
551
|
+
else this.running--;
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
// src/server/infra/files/attachments.ts
|
|
497
556
|
var attachmentPath = (root, id) => join(root, id.slice(0, 2), id);
|
|
498
557
|
var INCOMING = "incoming";
|
|
499
558
|
var SHARD = /^[a-f\d]{2}$/;
|
|
500
559
|
var ID = /^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/;
|
|
560
|
+
var THUMB = ".thumb";
|
|
501
561
|
var FileTooLarge = class extends Error {
|
|
502
562
|
constructor() {
|
|
503
563
|
super("File is too large");
|
|
@@ -505,13 +565,14 @@ var FileTooLarge = class extends Error {
|
|
|
505
565
|
};
|
|
506
566
|
var AttachmentFiles = class {
|
|
507
567
|
root;
|
|
568
|
+
thumbnails = new Thumbnails();
|
|
508
569
|
constructor(dataDir) {
|
|
509
570
|
this.root = join(dataDir, "attachments");
|
|
510
571
|
}
|
|
511
572
|
/** Writes `chunks` to a new file under a new id; past `limit` bytes it stops and throws FileTooLarge. Nothing is
|
|
512
573
|
* left behind when it throws. */
|
|
513
574
|
async stage(chunks, limit2, signal) {
|
|
514
|
-
const id =
|
|
575
|
+
const id = randomUUID2(), part = this.part(id), hash = createHash("sha256");
|
|
515
576
|
await mkdir(dirname(part), { recursive: true, mode: 448 });
|
|
516
577
|
const handle = await open(part, "wx", 384);
|
|
517
578
|
let size = 0;
|
|
@@ -527,7 +588,7 @@ var AttachmentFiles = class {
|
|
|
527
588
|
await handle.sync();
|
|
528
589
|
} catch (error) {
|
|
529
590
|
await handle.close().catch(() => void 0);
|
|
530
|
-
await
|
|
591
|
+
await rm2(part, { force: true });
|
|
531
592
|
throw error;
|
|
532
593
|
}
|
|
533
594
|
await handle.close();
|
|
@@ -537,11 +598,17 @@ var AttachmentFiles = class {
|
|
|
537
598
|
async commit(id) {
|
|
538
599
|
const target3 = this.path(id);
|
|
539
600
|
await mkdir(dirname(target3), { recursive: true, mode: 448 });
|
|
540
|
-
await
|
|
601
|
+
await rename2(this.part(id), target3);
|
|
541
602
|
}
|
|
542
|
-
/** Drops files, staged or in place; ids with no file are skipped. */
|
|
603
|
+
/** Drops files, staged or in place, with their thumbnails; ids with no file are skipped. */
|
|
543
604
|
async discard(ids) {
|
|
544
|
-
for (const id of ids) if (ID.test(id)) await Promise.all([
|
|
605
|
+
for (const id of ids) if (ID.test(id)) await Promise.all([rm2(this.part(id), { force: true }), rm2(this.path(id), { force: true }), rm2(this.path(id) + THUMB, { force: true })]);
|
|
606
|
+
}
|
|
607
|
+
/** A picture's thumbnail (A80), made the first time it is asked for; null when the original is to be shown. */
|
|
608
|
+
async thumbnail(id) {
|
|
609
|
+
const path = await this.thumbnails.thumbnail(this.path(id), this.path(id) + THUMB);
|
|
610
|
+
if (!path) return null;
|
|
611
|
+
return { size: (await stat2(path)).size, stream: createReadStream(path) };
|
|
545
612
|
}
|
|
546
613
|
/** The file's bytes from `start` to `end` (inclusive), as a stream. */
|
|
547
614
|
stream(id, range) {
|
|
@@ -571,31 +638,33 @@ var AttachmentFiles = class {
|
|
|
571
638
|
}
|
|
572
639
|
async size(id) {
|
|
573
640
|
try {
|
|
574
|
-
return (await
|
|
641
|
+
return (await stat2(this.path(id))).size;
|
|
575
642
|
} catch {
|
|
576
643
|
return null;
|
|
577
644
|
}
|
|
578
645
|
}
|
|
579
|
-
/** Removes what no attachment owns: files left in incoming/ by a stop mid-upload, files
|
|
580
|
-
* (`known` says which ids still have one), and anything else under the root, such as the readable
|
|
581
|
-
* versions kept in `<id>/<name>` folders. Folders left empty go too.
|
|
646
|
+
/** Removes what no attachment owns: files left in incoming/ by a stop mid-upload, files and thumbnails whose
|
|
647
|
+
* attachment is gone (`known` says which ids still have one), and anything else under the root, such as the readable
|
|
648
|
+
* copies older versions kept in `<id>/<name>` folders or a thumbnail cut off midway. Folders left empty go too.
|
|
649
|
+
* Returns how many files went. */
|
|
582
650
|
async sweep(known) {
|
|
583
651
|
let removed = 0;
|
|
584
652
|
for (const entry of await entries(this.root)) {
|
|
585
653
|
const path = join(this.root, entry.name);
|
|
586
654
|
if (!entry.isDirectory() || !(SHARD.test(entry.name) || entry.name === INCOMING)) {
|
|
587
655
|
removed += await count(path);
|
|
588
|
-
await
|
|
656
|
+
await rm2(path, { force: true, recursive: true });
|
|
589
657
|
continue;
|
|
590
658
|
}
|
|
591
659
|
const files = await entries(path);
|
|
592
660
|
for (const file of files) {
|
|
593
|
-
|
|
661
|
+
const id = file.name.endsWith(THUMB) ? file.name.slice(0, -THUMB.length) : file.name;
|
|
662
|
+
if (entry.name === INCOMING || !ID.test(id) || !id.startsWith(entry.name) || !known(id)) {
|
|
594
663
|
removed += await count(join(path, file.name));
|
|
595
|
-
await
|
|
664
|
+
await rm2(join(path, file.name), { force: true, recursive: true });
|
|
596
665
|
}
|
|
597
666
|
}
|
|
598
|
-
if (entry.name !== INCOMING && !(await entries(path)).length) await
|
|
667
|
+
if (entry.name !== INCOMING && !(await entries(path)).length) await rm2(path, { force: true, recursive: true });
|
|
599
668
|
}
|
|
600
669
|
return removed;
|
|
601
670
|
}
|
|
@@ -609,7 +678,7 @@ var AttachmentFiles = class {
|
|
|
609
678
|
};
|
|
610
679
|
async function count(path) {
|
|
611
680
|
const inside2 = await entries(path);
|
|
612
|
-
if (!inside2.length) return (await
|
|
681
|
+
if (!inside2.length) return (await stat2(path).catch(() => null))?.isFile() ? 1 : 0;
|
|
613
682
|
let total = 0;
|
|
614
683
|
for (const entry of inside2) total += entry.isDirectory() ? await count(join(path, entry.name)) : 1;
|
|
615
684
|
return total;
|
|
@@ -668,6 +737,10 @@ var ChatAttachments = class {
|
|
|
668
737
|
stream(file, range) {
|
|
669
738
|
return this.files.stream(file.id, range);
|
|
670
739
|
}
|
|
740
|
+
/** A picture's thumbnail (A80), made on first use; null when its original is to be shown. */
|
|
741
|
+
thumbnail(file) {
|
|
742
|
+
return this.files.thumbnail(file.id);
|
|
743
|
+
}
|
|
671
744
|
/** The first bytes of a file, to tell its kind. */
|
|
672
745
|
head(file, bytes) {
|
|
673
746
|
return this.files.head(file.id, bytes);
|
|
@@ -752,6 +825,8 @@ function chatRoutes({ chats, bots }) {
|
|
|
752
825
|
});
|
|
753
826
|
return routes;
|
|
754
827
|
}
|
|
828
|
+
var ATTACHMENT_CACHE = "private, max-age=31536000, immutable";
|
|
829
|
+
var disposition = (name3) => `attachment; filename*=UTF-8''${encodeURIComponent(name3)}`;
|
|
755
830
|
function attachmentRoutes(chats) {
|
|
756
831
|
const routes = new Hono5();
|
|
757
832
|
routes.get("/:id", (c) => {
|
|
@@ -761,7 +836,9 @@ function attachmentRoutes(chats) {
|
|
|
761
836
|
const headers2 = {
|
|
762
837
|
"Content-Type": downloadType(file.mimeType),
|
|
763
838
|
"Accept-Ranges": "bytes",
|
|
764
|
-
"
|
|
839
|
+
"Cache-Control": ATTACHMENT_CACHE,
|
|
840
|
+
"Vary": "Cookie",
|
|
841
|
+
"Content-Disposition": disposition(file.name)
|
|
765
842
|
};
|
|
766
843
|
if (range === "unsatisfiable") return c.body(null, 416, { ...headers2, "Content-Range": `bytes */${size}` });
|
|
767
844
|
if (!range) return c.body(web(chats.attachments.stream(file)), 200, { ...headers2, "Content-Length": String(size) });
|
|
@@ -771,6 +848,14 @@ function attachmentRoutes(chats) {
|
|
|
771
848
|
{ ...headers2, "Content-Length": String(range.end - range.start + 1), "Content-Range": `bytes ${range.start}-${range.end}/${size}` }
|
|
772
849
|
);
|
|
773
850
|
});
|
|
851
|
+
routes.get("/:id/thumb", async (c) => {
|
|
852
|
+
const file = chats.attachments.find(c.get("actorId"), c.req.param("id"));
|
|
853
|
+
if (!file) throw new HTTPException8(404, { message: "Attachment not found" });
|
|
854
|
+
const thumbnail = await chats.attachments.thumbnail(file);
|
|
855
|
+
const kept = { "Cache-Control": ATTACHMENT_CACHE, "Vary": "Cookie", "Content-Disposition": disposition(file.name) };
|
|
856
|
+
if (thumbnail) return c.body(web(thumbnail.stream), 200, { ...kept, "Content-Type": "image/webp", "Content-Length": String(thumbnail.size) });
|
|
857
|
+
return c.body(web(chats.attachments.stream(file)), 200, { ...kept, "Content-Type": downloadType(file.mimeType), "Content-Length": String(file.size) });
|
|
858
|
+
});
|
|
774
859
|
routes.get("/:id/run", (c) => {
|
|
775
860
|
const file = chats.attachments.find(c.get("actorId"), c.req.param("id"));
|
|
776
861
|
if (!file) throw new HTTPException8(404, { message: "Attachment not found" });
|
|
@@ -1649,13 +1734,13 @@ function migrateChannels(db) {
|
|
|
1649
1734
|
SELECT cm.chat_id, cm.member_id, COALESCE((SELECT MAX(sequence) FROM messages m WHERE m.chat_id=cm.chat_id), 0) FROM chat_members cm;
|
|
1650
1735
|
`);
|
|
1651
1736
|
const taken = new Set(db.prepare("SELECT username FROM account").all().map((row2) => row2.username.toLowerCase()));
|
|
1652
|
-
const
|
|
1737
|
+
const rename5 = db.prepare("UPDATE bots SET name=? WHERE id=?");
|
|
1653
1738
|
for (const bot of db.prepare("SELECT id,name FROM bots ORDER BY created_at,id").all()) {
|
|
1654
1739
|
const base = bot.name.replace(/@/g, "").trim() || "Bot";
|
|
1655
1740
|
let name3 = base;
|
|
1656
1741
|
for (let suffix = 2; taken.has(name3.toLowerCase()); suffix++) name3 = `${base} ${suffix}`;
|
|
1657
1742
|
taken.add(name3.toLowerCase());
|
|
1658
|
-
if (name3 !== bot.name)
|
|
1743
|
+
if (name3 !== bot.name) rename5.run(name3, bot.id);
|
|
1659
1744
|
}
|
|
1660
1745
|
db.exec("PRAGMA user_version=12; COMMIT;");
|
|
1661
1746
|
} catch (error) {
|
|
@@ -2150,7 +2235,7 @@ function sizeOf(path) {
|
|
|
2150
2235
|
}
|
|
2151
2236
|
|
|
2152
2237
|
// src/server/infra/storage/migrations/own-computer-schema.ts
|
|
2153
|
-
import { createHash as createHash2, randomUUID as
|
|
2238
|
+
import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
|
|
2154
2239
|
function migrateOwnComputers(db, dataDir) {
|
|
2155
2240
|
const tag = createHash2("sha256").update(dataDir).digest("hex").slice(0, 6);
|
|
2156
2241
|
migration(db, 29, () => {
|
|
@@ -2161,7 +2246,7 @@ function migrateOwnComputers(db, dataDir) {
|
|
|
2161
2246
|
for (const bot of bots) {
|
|
2162
2247
|
if (bot.homeKind === "computer") continue;
|
|
2163
2248
|
const existing = db.prepare("SELECT id FROM environments WHERE bot_id=? AND kind='computer' AND deleted_at IS NULL").get(bot.id);
|
|
2164
|
-
const id = existing?.id ??
|
|
2249
|
+
const id = existing?.id ?? randomUUID3();
|
|
2165
2250
|
if (!existing) db.prepare("INSERT INTO environments(id,owner_id,kind,connection,directory,bot_id,created_at) VALUES(?,?,'computer',?,'/workspace',?,?)").run(id, owner, JSON.stringify({ container: `jarvy-${tag}-${bot.id.slice(0, 8)}` }), bot.id, now);
|
|
2166
2251
|
db.prepare("UPDATE bots SET home_environment_id=?, current_environment_id=? WHERE id=?").run(id, id, bot.id);
|
|
2167
2252
|
}
|
|
@@ -2187,10 +2272,10 @@ function migratePublishedPorts(db) {
|
|
|
2187
2272
|
}
|
|
2188
2273
|
|
|
2189
2274
|
// src/server/infra/storage/migrations/schema.ts
|
|
2190
|
-
import { randomUUID as
|
|
2275
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
2191
2276
|
|
|
2192
2277
|
// src/server/infra/storage/migrations/prototype-schema.ts
|
|
2193
|
-
import { randomUUID as
|
|
2278
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
2194
2279
|
function migratePrototype(db) {
|
|
2195
2280
|
const version = db.prepare("PRAGMA user_version").get().user_version;
|
|
2196
2281
|
if (version >= 4) return;
|
|
@@ -2256,7 +2341,7 @@ function migratePrototype(db) {
|
|
|
2256
2341
|
const legacy = db.prepare("SELECT provider,base_url AS baseUrl,model,api_key AS apiKey FROM model_credentials WHERE id=1").get();
|
|
2257
2342
|
const botModels = db.prepare("SELECT DISTINCT model_id AS modelId FROM bots WHERE model_id<>''").all();
|
|
2258
2343
|
if (legacy && (legacy.baseUrl || legacy.model || legacy.apiKey || botModels.length)) {
|
|
2259
|
-
const id =
|
|
2344
|
+
const id = randomUUID4(), now = Date.now();
|
|
2260
2345
|
db.prepare("INSERT INTO provider_connections(id,provider_name,display_name,kind,auth_type,base_url,api,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)").run(id, legacy.provider || "openai-compatible", "\u65E7\u6A21\u578B\u914D\u7F6E", "custom", "api_key", legacy.baseUrl, "openai-completions", now, now);
|
|
2261
2346
|
if (legacy.apiKey) db.prepare("INSERT INTO provider_credentials(connection_id,type,credential_json,updated_at) VALUES(?,'api_key',?,?)").run(id, JSON.stringify({ type: "api_key", key: legacy.apiKey }), now);
|
|
2262
2347
|
const modelIds = new Set([legacy.model, ...botModels.map((row2) => row2.modelId)].filter(Boolean));
|
|
@@ -2340,7 +2425,7 @@ function migrateDatabase(db, cipher, dataDir) {
|
|
|
2340
2425
|
}
|
|
2341
2426
|
db.exec("PRAGMA foreign_keys=OFF; BEGIN IMMEDIATE");
|
|
2342
2427
|
try {
|
|
2343
|
-
const userId =
|
|
2428
|
+
const userId = randomUUID5();
|
|
2344
2429
|
db.exec(`
|
|
2345
2430
|
CREATE TABLE members(id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK(kind IN ('user','bot')));
|
|
2346
2431
|
ALTER TABLE account ADD COLUMN member_id TEXT REFERENCES members(id);
|
|
@@ -2424,7 +2509,7 @@ function migrateDatabase(db, cipher, dataDir) {
|
|
|
2424
2509
|
}
|
|
2425
2510
|
|
|
2426
2511
|
// src/server/infra/storage/account-repository.ts
|
|
2427
|
-
import { createHash as createHash3, randomBytes as randomBytes2, randomUUID as
|
|
2512
|
+
import { createHash as createHash3, randomBytes as randomBytes2, randomUUID as randomUUID6, scryptSync, timingSafeEqual } from "node:crypto";
|
|
2428
2513
|
|
|
2429
2514
|
// src/server/infra/storage/text.ts
|
|
2430
2515
|
function requireText(value2, label, max) {
|
|
@@ -2452,7 +2537,7 @@ var AccountRepository = class {
|
|
|
2452
2537
|
installationDeviceId() {
|
|
2453
2538
|
const row2 = this.db.prepare("SELECT device_id FROM installation WHERE id=1").get();
|
|
2454
2539
|
if (row2) return row2.device_id;
|
|
2455
|
-
const id =
|
|
2540
|
+
const id = randomUUID6();
|
|
2456
2541
|
this.db.prepare("INSERT INTO installation(id,device_id) VALUES(1,?)").run(id);
|
|
2457
2542
|
return id;
|
|
2458
2543
|
}
|
|
@@ -2499,13 +2584,13 @@ var AccountRepository = class {
|
|
|
2499
2584
|
// src/server/infra/storage/bot-repository.ts
|
|
2500
2585
|
import { mkdirSync as mkdirSync2 } from "node:fs";
|
|
2501
2586
|
import { join as join4 } from "node:path";
|
|
2502
|
-
import { randomInt as randomInt2, randomUUID as
|
|
2587
|
+
import { randomInt as randomInt2, randomUUID as randomUUID8 } from "node:crypto";
|
|
2503
2588
|
|
|
2504
2589
|
// src/server/infra/storage/model-connection-repository.ts
|
|
2505
|
-
import { randomUUID as
|
|
2590
|
+
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
2506
2591
|
|
|
2507
2592
|
// src/server/infra/pi/catalog.ts
|
|
2508
|
-
import { mkdir as mkdir2, readFile, rename as
|
|
2593
|
+
import { mkdir as mkdir2, readFile, rename as rename3, writeFile } from "node:fs/promises";
|
|
2509
2594
|
import { dirname as dirname3, join as join3 } from "node:path";
|
|
2510
2595
|
import { builtinProviders, getBuiltinModelDataGeneratedAt } from "@earendil-works/pi-ai/providers/all";
|
|
2511
2596
|
var CATALOG_URL = "https://pi.dev/api/models";
|
|
@@ -2634,7 +2719,7 @@ var ModelCatalog = class {
|
|
|
2634
2719
|
await mkdir2(dirname3(this.path), { recursive: true, mode: 448 });
|
|
2635
2720
|
const next = `${this.path}.tmp`;
|
|
2636
2721
|
await writeFile(next, JSON.stringify(this.kept), { mode: 384 });
|
|
2637
|
-
await
|
|
2722
|
+
await rename3(next, this.path);
|
|
2638
2723
|
}
|
|
2639
2724
|
};
|
|
2640
2725
|
function merge(models, newer) {
|
|
@@ -2755,7 +2840,7 @@ var ModelConnectionRepository = class {
|
|
|
2755
2840
|
const baseUrl = input.baseUrl === void 0 ? "" : modelUrl(optionalText(input.baseUrl, "Base URL", 2048));
|
|
2756
2841
|
const key = input.apiKey === void 0 ? null : requireText(input.apiKey, "API Key", 8192);
|
|
2757
2842
|
if (key && authType !== "api_key") throw new ValidationError("Invalid credential type");
|
|
2758
|
-
const id =
|
|
2843
|
+
const id = randomUUID7(), now = Date.now();
|
|
2759
2844
|
transaction(this.db, () => {
|
|
2760
2845
|
this.db.prepare("INSERT INTO provider_connections(id,provider_name,display_name,kind,auth_type,base_url,api,created_at,updated_at,owner_id) VALUES(?,?,?,?,?,?,?,?,?,?)").run(id, providerName, displayName, kind, authType, baseUrl, api, now, now, this.ownerId());
|
|
2761
2846
|
if (key) this.db.prepare("INSERT INTO provider_credentials(connection_id,type,credential_json,updated_at) VALUES(?,'api_key',?,?)").run(id, this.credentials.stored(id, { type: "api_key", key }), now);
|
|
@@ -2918,7 +3003,7 @@ var BotRepository = class {
|
|
|
2918
3003
|
/** The caller names the Bot (A45: the interface picks a free default in its own language). */
|
|
2919
3004
|
create(name3) {
|
|
2920
3005
|
const clean = this.botName(name3);
|
|
2921
|
-
const id =
|
|
3006
|
+
const id = randomUUID8(), createdAt = Date.now();
|
|
2922
3007
|
transaction(this.db, () => {
|
|
2923
3008
|
this.db.prepare("INSERT INTO members VALUES(?,'bot')").run(id);
|
|
2924
3009
|
this.db.prepare("INSERT INTO bots(id,name,description,system_prompt,model_id,created_at,owner_id,thinking_level,color) VALUES(?,?,?,?,?,?,?,'auto',?)").run(id, clean, "", "", "", createdAt, this.ownerId(), BOT_COLORS[randomInt2(BOT_COLORS.length)]);
|
|
@@ -2953,10 +3038,10 @@ var BotRepository = class {
|
|
|
2953
3038
|
};
|
|
2954
3039
|
|
|
2955
3040
|
// src/server/infra/storage/chat-repository.ts
|
|
2956
|
-
import { randomUUID as
|
|
3041
|
+
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
2957
3042
|
|
|
2958
3043
|
// src/server/infra/storage/channel-repository.ts
|
|
2959
|
-
import { randomUUID as
|
|
3044
|
+
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
2960
3045
|
|
|
2961
3046
|
// src/server/shared/delivery.ts
|
|
2962
3047
|
var CATEGORY = {
|
|
@@ -3068,13 +3153,14 @@ var InboxRepository = class {
|
|
|
3068
3153
|
for (const id of ids) this.db.prepare("UPDATE inbox SET state='told',told_at=? WHERE id=? AND member_id=? AND state='pending'").run(now, id, botId);
|
|
3069
3154
|
}
|
|
3070
3155
|
// A person's rows: what their chat list shows.
|
|
3071
|
-
/** What a person's chat row shows (A41): unread interrupt messages, and the newest
|
|
3156
|
+
/** What a person's chat row shows (A41): unread interrupt messages, and the newest activity not read yet (queued,
|
|
3157
|
+
* or a notice version, which is a digest, A77). */
|
|
3072
3158
|
rowState(memberId, chatId) {
|
|
3073
3159
|
const counts = this.db.prepare(`SELECT count(*) AS n,COALESCE(SUM(reason IN ('mention','reply')),0) AS at FROM inbox
|
|
3074
3160
|
WHERE member_id=? AND chat_id=? AND category='message' AND urgency='interrupt' AND state='pending'`).get(memberId, chatId);
|
|
3075
3161
|
const row2 = this.db.prepare(`SELECT i.kind,i.chat_id AS chatId,c.type AS chatType,c.title,i.actor_id AS actorId,i.payload,i.created_at AS createdAt
|
|
3076
3162
|
FROM inbox i JOIN chats c ON c.id=i.chat_id
|
|
3077
|
-
WHERE i.member_id=? AND i.category='activity' AND i.urgency
|
|
3163
|
+
WHERE i.member_id=? AND i.category='activity' AND i.urgency IN ('queue','digest') AND i.state='pending' AND (i.chat_id=? OR c.parent_id=?) ORDER BY i.id DESC LIMIT 1`).get(memberId, chatId, chatId);
|
|
3078
3164
|
if (!row2) return { alerts: counts.n, atMe: counts.at > 0, hint: null };
|
|
3079
3165
|
const payload = row2.payload ? JSON.parse(row2.payload) : {};
|
|
3080
3166
|
const detail = row2.kind === "reaction" ? payload.emoji ?? "" : String(payload.version ?? "");
|
|
@@ -3142,7 +3228,7 @@ var ChannelRepository = class {
|
|
|
3142
3228
|
return this.db.prepare(`SELECT ${SECTION_COLUMNS} FROM sections WHERE id=? AND owner_id=?`).get(id, ownerId) ?? null;
|
|
3143
3229
|
}
|
|
3144
3230
|
createSection(ownerId, name3) {
|
|
3145
|
-
const id =
|
|
3231
|
+
const id = randomUUID9(), now = Date.now();
|
|
3146
3232
|
const position = this.db.prepare("SELECT COALESCE(MAX(position),0)+1 AS next FROM sections WHERE owner_id=?").get(ownerId).next;
|
|
3147
3233
|
this.db.prepare("INSERT INTO sections(id,owner_id,name,position,created_at,updated_at) VALUES(?,?,?,?,?,?)").run(id, ownerId, name3, position, now, now);
|
|
3148
3234
|
return this.section(ownerId, id);
|
|
@@ -3162,7 +3248,7 @@ var ChannelRepository = class {
|
|
|
3162
3248
|
const allowed = new Set(this.directory(ownerId).map((member) => member.id));
|
|
3163
3249
|
const members = [.../* @__PURE__ */ new Set([ownerId, ...input.memberIds])];
|
|
3164
3250
|
if (members.some((id2) => !allowed.has(id2))) throw new ChatError(400, "Invalid channel members");
|
|
3165
|
-
const id =
|
|
3251
|
+
const id = randomUUID9(), now = Date.now();
|
|
3166
3252
|
return transaction(this.db, () => {
|
|
3167
3253
|
this.db.prepare("INSERT INTO chats(id,type,title,owner_id,created_at,updated_at,section_id,topic) VALUES(?,'channel',?,?,?,?,?,?)").run(id, input.name, ownerId, now, now, input.sectionId, input.topic);
|
|
3168
3254
|
for (const memberId of members) {
|
|
@@ -3291,7 +3377,7 @@ var ChannelRepository = class {
|
|
|
3291
3377
|
};
|
|
3292
3378
|
|
|
3293
3379
|
// src/server/infra/storage/thread-repository.ts
|
|
3294
|
-
import { randomUUID as
|
|
3380
|
+
import { randomUUID as randomUUID10 } from "node:crypto";
|
|
3295
3381
|
function threadTitle(content2, names, file = "") {
|
|
3296
3382
|
const line = (content2.split("\n").map((item) => item.trim()).find(Boolean) ?? "").replace(/[*`~]/g, "").replace(/^[#>\s-]+/, "");
|
|
3297
3383
|
const sorted = [...names].sort((a, b) => b.length - a.length);
|
|
@@ -3321,7 +3407,7 @@ var ThreadRepository = class {
|
|
|
3321
3407
|
if (root.type !== "channel") throw new ChatError(400, "Threads start from channel messages");
|
|
3322
3408
|
let id = this.db.prepare("SELECT id FROM chats WHERE root_message_id=?").get(rootMessageId)?.id;
|
|
3323
3409
|
if (!id) {
|
|
3324
|
-
id =
|
|
3410
|
+
id = randomUUID10();
|
|
3325
3411
|
const now = Date.now();
|
|
3326
3412
|
const firstFile = this.db.prepare("SELECT name FROM attachments WHERE message_id=? ORDER BY created_at,rowid LIMIT 1").get(rootMessageId)?.name;
|
|
3327
3413
|
this.db.prepare(`INSERT INTO chats(id,type,title,owner_id,created_at,updated_at,parent_id,root_message_id,status)
|
|
@@ -3547,7 +3633,7 @@ var ChatRepository = class {
|
|
|
3547
3633
|
const id = transaction(this.db, () => {
|
|
3548
3634
|
const existing = this.db.prepare(`SELECT c.id FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.member_id=?
|
|
3549
3635
|
JOIN chat_members b ON b.chat_id=c.id AND b.member_id=? WHERE c.type='dm' ORDER BY c.updated_at DESC,c.id DESC LIMIT 1`).get(actorId, targetId);
|
|
3550
|
-
const id2 = existing?.id ??
|
|
3636
|
+
const id2 = existing?.id ?? randomUUID11();
|
|
3551
3637
|
if (!existing) {
|
|
3552
3638
|
this.db.prepare("INSERT INTO chats(id,type,title,owner_id,created_at,updated_at) VALUES(?,'dm',?,?,?,?)").run(id2, title, ownerId, now, now);
|
|
3553
3639
|
this.db.prepare("INSERT INTO chat_members(chat_id,member_id) VALUES(?,?),(?,?)").run(id2, actorId, id2, targetId);
|
|
@@ -3779,7 +3865,7 @@ var ChatRepository = class {
|
|
|
3779
3865
|
};
|
|
3780
3866
|
|
|
3781
3867
|
// src/server/infra/storage/runtime-repository.ts
|
|
3782
|
-
import { randomUUID as
|
|
3868
|
+
import { randomUUID as randomUUID12 } from "node:crypto";
|
|
3783
3869
|
var RUN_COLUMNS = "id,bot_id AS botId,state,selection_json AS selectionJson,created_at AS createdAt,ended_at AS endedAt,error_code AS errorCode";
|
|
3784
3870
|
var RuntimeRepository = class {
|
|
3785
3871
|
/** `inbox`: a run claims and settles the Bot's message deliveries there (A41). */
|
|
@@ -3811,7 +3897,7 @@ var RuntimeRepository = class {
|
|
|
3811
3897
|
return transaction(this.db, () => {
|
|
3812
3898
|
const inputs = this.inbox.pendingMessages(botId);
|
|
3813
3899
|
if (!inputs.length && !allowEmpty) return null;
|
|
3814
|
-
const id =
|
|
3900
|
+
const id = randomUUID12();
|
|
3815
3901
|
this.db.prepare("INSERT INTO bot_runs(id,bot_id,state,selection_json,created_at) VALUES(?,?,'claimed',?,?)").run(id, botId, JSON.stringify(selection), Date.now());
|
|
3816
3902
|
inputs.forEach((input, position) => this.db.prepare("INSERT INTO bot_run_inputs VALUES(?,?,?,?)").run(id, position + 1, input.chatId, input.messageId));
|
|
3817
3903
|
this.inbox.claimMessages(botId, id);
|
|
@@ -3866,7 +3952,7 @@ var RuntimeRepository = class {
|
|
|
3866
3952
|
return !!this.db.prepare("SELECT 1 FROM bot_model_changes WHERE bot_id=? AND state IN ('applying','unknown') LIMIT 1").get(botId);
|
|
3867
3953
|
}
|
|
3868
3954
|
beginModelChange(botId, selection) {
|
|
3869
|
-
const id =
|
|
3955
|
+
const id = randomUUID12();
|
|
3870
3956
|
this.db.prepare("INSERT INTO bot_model_changes(id,bot_id,selection_json,state,created_at) VALUES(?,?,?,'applying',?)").run(id, botId, JSON.stringify(selection), Date.now());
|
|
3871
3957
|
return id;
|
|
3872
3958
|
}
|
|
@@ -3965,7 +4051,7 @@ var AgentRepository = class {
|
|
|
3965
4051
|
};
|
|
3966
4052
|
|
|
3967
4053
|
// src/server/infra/storage/environment-repository.ts
|
|
3968
|
-
import { randomUUID as
|
|
4054
|
+
import { randomUUID as randomUUID13 } from "node:crypto";
|
|
3969
4055
|
var FIELDS = (table) => ["id", "owner_id AS ownerId", "kind", "bot_id AS botId", "name", "directory", "description", "connection"].map((column) => `${table}${column}`).join(", ");
|
|
3970
4056
|
var COLUMNS = FIELDS("");
|
|
3971
4057
|
var record = (row2) => ({
|
|
@@ -4001,7 +4087,7 @@ var EnvironmentRepository = class {
|
|
|
4001
4087
|
addComputer(botId, container) {
|
|
4002
4088
|
const existing = this.computerOf(botId);
|
|
4003
4089
|
if (existing) return existing;
|
|
4004
|
-
const id =
|
|
4090
|
+
const id = randomUUID13();
|
|
4005
4091
|
this.db.prepare("INSERT INTO environments(id,owner_id,kind,connection,directory,bot_id,created_at) VALUES(?,?,'computer',?,'/workspace',?,?)").run(id, this.ownerId(), JSON.stringify({ container }), botId, Date.now());
|
|
4006
4092
|
return this.get(id);
|
|
4007
4093
|
}
|
|
@@ -4061,7 +4147,7 @@ var EnvironmentRepository = class {
|
|
|
4061
4147
|
sshMachines() {
|
|
4062
4148
|
return this.db.prepare(`SELECT ${COLUMNS} FROM environments WHERE kind='ssh' AND deleted_at IS NULL ORDER BY created_at, id`).all().map(record);
|
|
4063
4149
|
}
|
|
4064
|
-
addSsh(input, id =
|
|
4150
|
+
addSsh(input, id = randomUUID13()) {
|
|
4065
4151
|
const { host, port, user, home, platform } = input;
|
|
4066
4152
|
this.db.prepare("INSERT INTO environments(id,owner_id,kind,name,connection,directory,description,key,host_keys,password,created_at) VALUES(?,?,'ssh',?,?,?,?,?,?,?,?)").run(
|
|
4067
4153
|
id,
|
|
@@ -4134,7 +4220,7 @@ var SettingsRepository = class {
|
|
|
4134
4220
|
};
|
|
4135
4221
|
|
|
4136
4222
|
// src/server/infra/storage/secret-repository.ts
|
|
4137
|
-
import { randomUUID as
|
|
4223
|
+
import { randomUUID as randomUUID14 } from "node:crypto";
|
|
4138
4224
|
|
|
4139
4225
|
// src/server/shared/secret.ts
|
|
4140
4226
|
var SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
@@ -4177,7 +4263,7 @@ var SecretRepository = class {
|
|
|
4177
4263
|
if (typeof input.name !== "string" || !SECRET_NAME.test(input.name)) throw new ValidationError("Names use capital letters, digits and underscores, and start with a letter", "secret_name_invalid");
|
|
4178
4264
|
const description = this.checkDescription(input.description), value2 = this.checkValue(input.value);
|
|
4179
4265
|
if (this.db.prepare("SELECT 1 FROM secrets WHERE owner_id=? AND kind='value' AND name=?").get(this.ownerId(), input.name)) throw new ConflictError("Another secret has this name", "secret_name_taken");
|
|
4180
|
-
const id =
|
|
4266
|
+
const id = randomUUID14(), now = Date.now();
|
|
4181
4267
|
this.db.prepare("INSERT INTO secrets(id,owner_id,name,kind,bot_id,description,value,fingerprint,created_at,updated_at) VALUES(?,?,?,'value',NULL,?,?,?,?,?)").run(id, this.ownerId(), input.name, description, this.cipher.seal(value2, `secret:${id}`), this.cipher.fingerprint(value2), now, now);
|
|
4182
4268
|
return this.get(id);
|
|
4183
4269
|
}
|
|
@@ -4238,7 +4324,7 @@ var SecretRepository = class {
|
|
|
4238
4324
|
};
|
|
4239
4325
|
|
|
4240
4326
|
// src/server/infra/storage/task-repository.ts
|
|
4241
|
-
import { randomUUID as
|
|
4327
|
+
import { randomUUID as randomUUID15 } from "node:crypto";
|
|
4242
4328
|
|
|
4243
4329
|
// src/server/shared/task.ts
|
|
4244
4330
|
var TASK_MINUTES_MIN = 5;
|
|
@@ -4333,7 +4419,7 @@ var TaskRepository = class {
|
|
|
4333
4419
|
create(input) {
|
|
4334
4420
|
const now = Date.now(), at2 = nextAfter(input.schedule, now);
|
|
4335
4421
|
if (at2 === null) throw new ValidationError("A one-off task has to be in the future", "task_time_past");
|
|
4336
|
-
const id =
|
|
4422
|
+
const id = randomUUID15(), columns = scheduleColumns(input.schedule);
|
|
4337
4423
|
this.db.prepare(`INSERT INTO tasks(id,bot_id,name,instruction,schedule_kind,schedule_at,schedule_minutes,schedule_hour,schedule_minute,schedule_weekday,
|
|
4338
4424
|
state,next_run_at,last_run_at,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,'active',?,NULL,?,?)`).run(id, input.botId, input.name, input.instruction, columns.kind, columns.at, columns.minutes, columns.hour, columns.minute, columns.weekday, at2, now, now);
|
|
4339
4425
|
return this.get(input.botId, id);
|
|
@@ -4785,7 +4871,7 @@ var AccountService = class {
|
|
|
4785
4871
|
|
|
4786
4872
|
// src/server/infra/pi/model.ts
|
|
4787
4873
|
import { ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
4788
|
-
var
|
|
4874
|
+
var FORMATS2 = /* @__PURE__ */ new Set(["openai", "openrouter", "deepseek", "together", "baseten", "zai", "qwen", "chat-template", "qwen-chat-template", "string-thinking", "ant-ling"]);
|
|
4789
4875
|
function installModel(runtime, connection, configured2, headers2 = {}, catalog) {
|
|
4790
4876
|
const api = configured2.api || connection.api;
|
|
4791
4877
|
const bundled = runtime.getModel(connection.providerName, configured2.id);
|
|
@@ -4795,7 +4881,7 @@ function installModel(runtime, connection, configured2, headers2 = {}, catalog)
|
|
|
4795
4881
|
const maxTokens = configured2.maxTokens ?? builtin?.maxTokens;
|
|
4796
4882
|
const baseUrl = connection.baseUrl || configured2.baseUrl || builtin?.baseUrl || runtime.getModels(connection.providerName)[0]?.baseUrl;
|
|
4797
4883
|
if (!contextWindow || !maxTokens) throw new RuntimeFault("model_incomplete", "Fill in the model's context window and max output.", 422);
|
|
4798
|
-
if (configured2.thinkingFormat && !
|
|
4884
|
+
if (configured2.thinkingFormat && !FORMATS2.has(configured2.thinkingFormat)) throw new RuntimeFault("thinking_format", "This thinking format isn't supported.", 422);
|
|
4799
4885
|
const compat = { ...builtin?.compat, ...configured2.compat, ...configured2.thinkingFormat ? { thinkingFormat: configured2.thinkingFormat } : {} };
|
|
4800
4886
|
runtime.registerProvider(connection.providerName, {
|
|
4801
4887
|
baseUrl,
|
|
@@ -5251,7 +5337,7 @@ var ModelService = class {
|
|
|
5251
5337
|
};
|
|
5252
5338
|
|
|
5253
5339
|
// src/server/infra/pi/auth.ts
|
|
5254
|
-
import { randomUUID as
|
|
5340
|
+
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
5255
5341
|
import { ModelRuntime as ModelRuntime2 } from "@earendil-works/pi-coding-agent";
|
|
5256
5342
|
var CredentialLogins = class {
|
|
5257
5343
|
constructor(store, credentials, changed) {
|
|
@@ -5299,7 +5385,7 @@ var CredentialLogins = class {
|
|
|
5299
5385
|
prompt(flow, prompt) {
|
|
5300
5386
|
const signal = prompt.signal ? AbortSignal.any([flow.controller.signal, prompt.signal]) : flow.controller.signal;
|
|
5301
5387
|
signal.throwIfAborted();
|
|
5302
|
-
const id =
|
|
5388
|
+
const id = randomUUID16();
|
|
5303
5389
|
flow.state.prompt = {
|
|
5304
5390
|
id,
|
|
5305
5391
|
type: prompt.type,
|
|
@@ -5432,8 +5518,9 @@ var POLICY = {
|
|
|
5432
5518
|
message: { dm: "interrupt", mention: "interrupt", reply: "interrupt", subscription: "interrupt" },
|
|
5433
5519
|
// Marks on your messages are queued: they wake you but never interrupt (A39).
|
|
5434
5520
|
reaction: { author: "queue" },
|
|
5435
|
-
// A new version of a notice or summary
|
|
5436
|
-
|
|
5521
|
+
// A new version of a notice or summary rides along with the Bot's next batch: a Bot that is working hears it at
|
|
5522
|
+
// once, and one that is idle is not woken for it (A77). A person's sidebar still shows the hint line.
|
|
5523
|
+
note: { member: "digest", follower: "digest" },
|
|
5437
5524
|
// The owner just gave the agent Bot its first model: it should welcome them now (A48).
|
|
5438
5525
|
onboard: { setup: "interrupt" },
|
|
5439
5526
|
// What the agent Bot changed about a Bot, or the owner about where it works, rides along with that Bot's next batch,
|
|
@@ -6362,12 +6449,12 @@ function byteSize(bytes) {
|
|
|
6362
6449
|
}
|
|
6363
6450
|
|
|
6364
6451
|
// src/server/service/events.ts
|
|
6365
|
-
import { randomUUID as
|
|
6452
|
+
import { randomUUID as randomUUID17 } from "node:crypto";
|
|
6366
6453
|
var KEEP_MS = 10 * 6e4;
|
|
6367
6454
|
var KEEP_MAX = 5e3;
|
|
6368
6455
|
var Changes = class {
|
|
6369
6456
|
/** This run's changes: a number from before a restart says nothing. */
|
|
6370
|
-
run =
|
|
6457
|
+
run = randomUUID17().slice(0, 8);
|
|
6371
6458
|
last = 0;
|
|
6372
6459
|
kept = [];
|
|
6373
6460
|
listeners = /* @__PURE__ */ new Set();
|
|
@@ -6420,7 +6507,7 @@ function activityPage(messages, history, limit2) {
|
|
|
6420
6507
|
|
|
6421
6508
|
// src/server/service/bot/service.ts
|
|
6422
6509
|
import { dirname as dirname10, join as join16 } from "node:path";
|
|
6423
|
-
import { rm as
|
|
6510
|
+
import { rm as rm6 } from "node:fs/promises";
|
|
6424
6511
|
|
|
6425
6512
|
// src/server/infra/pi/history.ts
|
|
6426
6513
|
var value = (input) => JSON.parse(JSON.stringify(input));
|
|
@@ -6742,7 +6829,7 @@ function resultText(result) {
|
|
|
6742
6829
|
|
|
6743
6830
|
// src/server/infra/pi/environment-tools.ts
|
|
6744
6831
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6745
|
-
import { readFile as readLocal, rm as
|
|
6832
|
+
import { readFile as readLocal, rm as rm3 } from "node:fs/promises";
|
|
6746
6833
|
import { basename } from "node:path";
|
|
6747
6834
|
import { createBashToolDefinition, createEditToolDefinition, createReadToolDefinition, createWriteToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
6748
6835
|
|
|
@@ -7057,7 +7144,7 @@ function relocated(definition, current) {
|
|
|
7057
7144
|
async function moveOut(path, env) {
|
|
7058
7145
|
const target3 = `${env.temp ?? `${env.cwd}/temp`}/${basename(path)}`;
|
|
7059
7146
|
await env.writeFile(target3, await readLocal(path));
|
|
7060
|
-
await
|
|
7147
|
+
await rm3(path, { force: true });
|
|
7061
7148
|
return target3;
|
|
7062
7149
|
}
|
|
7063
7150
|
function defined(vars) {
|
|
@@ -7375,7 +7462,7 @@ var PiSession = class _PiSession {
|
|
|
7375
7462
|
import { execFile, spawn } from "node:child_process";
|
|
7376
7463
|
import { createHash as createHash6 } from "node:crypto";
|
|
7377
7464
|
import { createWriteStream } from "node:fs";
|
|
7378
|
-
import { mkdir as mkdir4, mkdtemp, readFile as readFile2, rename as
|
|
7465
|
+
import { mkdir as mkdir4, mkdtemp, readFile as readFile2, rename as rename4, rm as rm4, writeFile as writeFile2 } from "node:fs/promises";
|
|
7379
7466
|
import { tmpdir } from "node:os";
|
|
7380
7467
|
import { join as join9 } from "node:path";
|
|
7381
7468
|
import { Connection, RemoteExecutionEnv, packagedDaemon } from "@earendil-works/pi-env";
|
|
@@ -7531,7 +7618,7 @@ async function buildImage(tag, uid, gid, logFile) {
|
|
|
7531
7618
|
}).finally(() => log.end());
|
|
7532
7619
|
if (code !== 0) throw Object.assign(new Error(`docker build exited with ${code}`), { code: "docker_failed" });
|
|
7533
7620
|
} finally {
|
|
7534
|
-
await
|
|
7621
|
+
await rm4(dir, { recursive: true, force: true });
|
|
7535
7622
|
}
|
|
7536
7623
|
}
|
|
7537
7624
|
async function containerStates(label) {
|
|
@@ -7626,7 +7713,7 @@ async function syncDaemon(dir) {
|
|
|
7626
7713
|
await mkdir4(dir, { recursive: true, mode: 448 });
|
|
7627
7714
|
const temp = `${target3}.${process.pid}.tmp`;
|
|
7628
7715
|
await writeFile2(temp, wanted, { mode: 493 });
|
|
7629
|
-
await
|
|
7716
|
+
await rename4(temp, target3);
|
|
7630
7717
|
}
|
|
7631
7718
|
function containerEnvironment(id, container, log) {
|
|
7632
7719
|
const connection = new Connection({ command: ["docker", "exec", "-i", container, `${DAEMON_DIR}/pi-env`], onLog: (text5) => log(text5.trim()) });
|
|
@@ -8263,13 +8350,13 @@ var BotEnvironments = class {
|
|
|
8263
8350
|
};
|
|
8264
8351
|
|
|
8265
8352
|
// src/server/service/bot/machines.ts
|
|
8266
|
-
import { randomUUID as
|
|
8353
|
+
import { randomUUID as randomUUID18 } from "node:crypto";
|
|
8267
8354
|
import { dirname as dirname6, join as join12, posix } from "node:path";
|
|
8268
8355
|
|
|
8269
8356
|
// src/server/infra/env/ssh.ts
|
|
8270
8357
|
import { spawn as spawn2 } from "node:child_process";
|
|
8271
8358
|
import { mkdirSync as mkdirSync6, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
|
|
8272
|
-
import { mkdir as mkdir5, mkdtemp as mkdtemp2, readFile as readFile3, rm as
|
|
8359
|
+
import { mkdir as mkdir5, mkdtemp as mkdtemp2, readFile as readFile3, rm as rm5 } from "node:fs/promises";
|
|
8273
8360
|
import { join as join11 } from "node:path";
|
|
8274
8361
|
import { HostKeyChangedError, HostKeyUnknownError, RemoteExecutionEnv as RemoteExecutionEnv2, detectPlatform, scanHostKey, sshArguments, sshConnection } from "@earendil-works/pi-env";
|
|
8275
8362
|
var SshFault = class extends Error {
|
|
@@ -8299,7 +8386,7 @@ async function generateKey(runtime, comment) {
|
|
|
8299
8386
|
await run("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", join11(directory, "key")]);
|
|
8300
8387
|
return { privateKey: await readFile3(join11(directory, "key"), "utf8"), publicKey: (await readFile3(join11(directory, "key.pub"), "utf8")).trim() };
|
|
8301
8388
|
} finally {
|
|
8302
|
-
await
|
|
8389
|
+
await rm5(directory, { recursive: true, force: true });
|
|
8303
8390
|
}
|
|
8304
8391
|
}
|
|
8305
8392
|
function publicKeyOf(privateKey, comment) {
|
|
@@ -8390,7 +8477,7 @@ async function withFiles(access, work) {
|
|
|
8390
8477
|
try {
|
|
8391
8478
|
return await work(writeFilesSync(directory, access));
|
|
8392
8479
|
} finally {
|
|
8393
|
-
await
|
|
8480
|
+
await rm5(directory, { recursive: true, force: true });
|
|
8394
8481
|
}
|
|
8395
8482
|
}
|
|
8396
8483
|
function writeFilesSync(directory, access) {
|
|
@@ -8490,7 +8577,7 @@ var SshMachines = class {
|
|
|
8490
8577
|
async prepareKey() {
|
|
8491
8578
|
const now = Date.now();
|
|
8492
8579
|
for (const [keyId2, key2] of this.prepared) if (key2.until < now) this.prepared.delete(keyId2);
|
|
8493
|
-
const id =
|
|
8580
|
+
const id = randomUUID18(), key = await this.wrap(() => generateKey(this.runtime, keyComment(id)));
|
|
8494
8581
|
this.prepared.set(id, { id, ...key, until: now + PREPARED_MS });
|
|
8495
8582
|
return { keyId: id, publicKey: key.publicKey };
|
|
8496
8583
|
}
|
|
@@ -8506,7 +8593,7 @@ var SshMachines = class {
|
|
|
8506
8593
|
if (!password && (!prepared || prepared.until < Date.now())) throw new ChatError(409, "That key is no longer kept; show a new one and add it to the machine", "ssh_key_expired");
|
|
8507
8594
|
if (!input.hostKeys.keys.length) throw new ChatError(400, "The host keys are missing; scan the machine first");
|
|
8508
8595
|
directoryIn("/", input.directory);
|
|
8509
|
-
const id = prepared && !password ? prepared.id :
|
|
8596
|
+
const id = prepared && !password ? prepared.id : randomUUID18(), comment = keyComment(id);
|
|
8510
8597
|
const record3 = await this.wrap(async () => {
|
|
8511
8598
|
const key = prepared && !password ? prepared : await generateKey(this.runtime, comment);
|
|
8512
8599
|
const access = { ...where2, runtime: this.runtime, alias: alias(id), hostKeys: input.hostKeys.keys, privateKey: key.privateKey };
|
|
@@ -8967,9 +9054,12 @@ var Bot = class extends Member {
|
|
|
8967
9054
|
status() {
|
|
8968
9055
|
return this.state.snapshot();
|
|
8969
9056
|
}
|
|
8970
|
-
/** 投递已保存(A41);Bot
|
|
9057
|
+
/** 投递已保存(A41);Bot 按需激活,交给运行层按急迫程度处理。附带的不必为它启动:只在它正跑着一轮时插进去(A77)。 */
|
|
8971
9058
|
async deliver(urgency) {
|
|
8972
|
-
if (urgency === "digest")
|
|
9059
|
+
if (urgency === "digest") {
|
|
9060
|
+
if (!this.stopping && this.status().status !== "stop") this.agentRuntime.deliver(urgency);
|
|
9061
|
+
return;
|
|
9062
|
+
}
|
|
8973
9063
|
if (this.stopping) await this.stopping;
|
|
8974
9064
|
if (this.status().status === "stop") await this.start();
|
|
8975
9065
|
this.agentRuntime.deliver(urgency);
|
|
@@ -9355,7 +9445,7 @@ var ToolContext = class {
|
|
|
9355
9445
|
};
|
|
9356
9446
|
|
|
9357
9447
|
// src/server/service/bot/history-read.ts
|
|
9358
|
-
import { randomUUID as
|
|
9448
|
+
import { randomUUID as randomUUID19 } from "node:crypto";
|
|
9359
9449
|
import { Type as Type2 } from "typebox";
|
|
9360
9450
|
|
|
9361
9451
|
// src/server/service/bot/history-format.ts
|
|
@@ -9435,7 +9525,7 @@ async function readHistory(memory, workspace, input, signal) {
|
|
|
9435
9525
|
const rendered = formatHistory(result, format);
|
|
9436
9526
|
signal?.throwIfAborted();
|
|
9437
9527
|
if (!input.to_file) return rendered;
|
|
9438
|
-
const name3 = `history-${
|
|
9528
|
+
const name3 = `history-${randomUUID19()}.${format === "json" ? "json" : "md"}`;
|
|
9439
9529
|
return workspace.writeTempFile(name3, rendered, signal);
|
|
9440
9530
|
}
|
|
9441
9531
|
|
|
@@ -10573,9 +10663,11 @@ var BotInbox = class {
|
|
|
10573
10663
|
if (notices.length) this.tell(notices);
|
|
10574
10664
|
}
|
|
10575
10665
|
/** Notices the Bot has not been told (A39), as the XML that goes into a steered message or a run of notices alone.
|
|
10576
|
-
* `steer`: what may go into a running turn
|
|
10577
|
-
|
|
10578
|
-
|
|
10666
|
+
* `steer`: what may go into a running turn. A queued delivery takes everything but a task, which waits for the turn
|
|
10667
|
+
* to end and opens one of its own (A58); a digest (a new notice version) takes only chat activity, so the system
|
|
10668
|
+
* notices keep riding with the next batch (A48, A73, A77). */
|
|
10669
|
+
notices(prompt, steer) {
|
|
10670
|
+
const pending = this.chats.notices(this.botId).filter((notice) => !steer || (steer === "queue" ? notice.kind !== "task" : notice.chat !== null));
|
|
10579
10671
|
if (!pending.length) return null;
|
|
10580
10672
|
const { kept, stale } = this.convert(pending);
|
|
10581
10673
|
if (!kept.length && !prompt) {
|
|
@@ -10664,9 +10756,14 @@ var AgentRuntime = class {
|
|
|
10664
10756
|
}
|
|
10665
10757
|
/** Something was delivered (A41); the runtime only looks at how urgent it is. Interrupt: abort the running
|
|
10666
10758
|
* turn and start over with everything pending (A05). Queue: steer it into the running turn, or wake an idle
|
|
10667
|
-
* Bot (A39). Digest:
|
|
10759
|
+
* Bot (A39). Digest: chat activity into a running turn, never a wake; otherwise it rides along with the next run (A77).
|
|
10760
|
+
* The delivery itself is durable. */
|
|
10668
10761
|
deliver(urgency) {
|
|
10669
|
-
if (this.stopping
|
|
10762
|
+
if (this.stopping) return;
|
|
10763
|
+
if (urgency === "digest") {
|
|
10764
|
+
if (this.prompting) this.steer("digest");
|
|
10765
|
+
return;
|
|
10766
|
+
}
|
|
10670
10767
|
if (urgency === "interrupt") {
|
|
10671
10768
|
this.inputVersion++;
|
|
10672
10769
|
if (this.prompting) this.session?.requestAbort();
|
|
@@ -10677,12 +10774,16 @@ var AgentRuntime = class {
|
|
|
10677
10774
|
this.wake();
|
|
10678
10775
|
return;
|
|
10679
10776
|
}
|
|
10777
|
+
this.steer("queue");
|
|
10778
|
+
}
|
|
10779
|
+
/** Puts the notices a running turn has not been told into it (A39, A77); nothing is woken. A steer that does not
|
|
10780
|
+
* go through leaves them for the next batch. Serialised, so two quick deliveries cannot both read the same rows. */
|
|
10781
|
+
steer(urgency) {
|
|
10680
10782
|
this.notices = this.notices.catch(() => {
|
|
10681
10783
|
}).then(async () => {
|
|
10682
|
-
const pending = this.inbox.notices(null,
|
|
10683
|
-
if (!pending || this.stopping) return;
|
|
10684
|
-
if (this.
|
|
10685
|
-
else this.wake();
|
|
10784
|
+
const pending = this.inbox.notices(null, urgency);
|
|
10785
|
+
if (!pending || this.stopping || !this.prompting) return;
|
|
10786
|
+
if (this.session?.steer(pending.xml)) this.inbox.tell(pending.ids);
|
|
10686
10787
|
}).catch((error) => {
|
|
10687
10788
|
console.error("[bot] steer failed", { botId: this.inbox.botId, error });
|
|
10688
10789
|
});
|
|
@@ -11803,7 +11904,7 @@ var BotService = class {
|
|
|
11803
11904
|
if (!this.deps.store.bots.delete(id)) throw new RuntimeFault("bot_missing", "Bot not found", 404);
|
|
11804
11905
|
this.ports.changed();
|
|
11805
11906
|
await this.deps.chats.attachments.clean();
|
|
11806
|
-
if (!keepFiles) await
|
|
11907
|
+
if (!keepFiles) await rm6(dirname10(workspacePath), { recursive: true, force: true });
|
|
11807
11908
|
}
|
|
11808
11909
|
async close() {
|
|
11809
11910
|
if (this.closed) return;
|