Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f03120526 | ||
|
|
247ddd614d | ||
|
|
16362595f9 | ||
|
|
3b5391f320 | ||
|
|
cd981228d5 |
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.24.0",
|
||||
"version": "0.24.2",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
+12
-1
@@ -3,6 +3,7 @@ import { AppData } from "@/src/data/app-data";
|
||||
import type { BotJobKind } from "@/src/dict/bot-queue-dict";
|
||||
import claimBotJobs from "@/src/functions/backend/db/bots-queue/claim-bot-jobs";
|
||||
import releaseWorkerBotJobs from "@/src/functions/backend/db/bots-queue/release-worker-bot-jobs";
|
||||
import releaseRestingBotJobs from "@/src/functions/backend/db/bots-queue/release-resting-bot-jobs";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import processBotJob from "./process-bot-job";
|
||||
import reportLostBotJobs from "./report-lost-bot-jobs";
|
||||
@@ -45,9 +46,19 @@ export default async function botsQueue() {
|
||||
if (released) {
|
||||
bunext.bunextLog.info(`Bots queue: released ${released} cut-off job(s)`);
|
||||
}
|
||||
|
||||
/**
|
||||
* A restart forgets every model rest (the cooldowns are in memory),
|
||||
* so the jobs one parked would wait for benches that no longer exist.
|
||||
*/
|
||||
const woken = await releaseRestingBotJobs();
|
||||
|
||||
if (woken) {
|
||||
bunext.bunextLog.info(`Bots queue: woke ${woken} job(s) parked on a model rest`);
|
||||
}
|
||||
} catch (error) {
|
||||
await logError({
|
||||
title: "Bots queue couldn't release cut-off jobs",
|
||||
title: "Bots queue couldn't release held jobs",
|
||||
error,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
|
||||
import type { ComputerFileStat } from "@/src/functions/backend/computers/stat-computer-file";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
|
||||
/**
|
||||
* The reconciliation a task run opens with: a source a rebuild took off the
|
||||
* computer is named back to the run with the file that still has it, so it
|
||||
* never searches the machine (or the user's accounts) for it.
|
||||
*/
|
||||
let stat: ComputerFileStat | Error = { exists: false };
|
||||
let saved: Array<{ id: number; name: string; path: string }> = [];
|
||||
|
||||
mock.module("@/src/functions/backend/computers/stat-computer-file", () => ({
|
||||
default: async () => {
|
||||
if (stat instanceof Error) throw stat;
|
||||
|
||||
return stat;
|
||||
},
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bot-files/list-bot-files", () => ({
|
||||
default: async () => saved,
|
||||
}));
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
const computer = {} as ComputerApi;
|
||||
const dirs = computerRunDirs({ bot_id: 8, bot_kind: "worker", user_id: 1, workspace_id: null });
|
||||
const brief = "Build a layered PSD from uploads/2026-11/summit-canva-v1.png, keeping the layers.";
|
||||
|
||||
async function note(text = brief) {
|
||||
const { default: namedFilesNote } = await import("./named-files-note");
|
||||
|
||||
return namedFilesNote({ computer, dirs, scopes: [], text });
|
||||
}
|
||||
|
||||
describe("namedFilesNote", () => {
|
||||
test("names the saved file a rebuild took off the computer", async () => {
|
||||
stat = { exists: false };
|
||||
saved = [{ id: 313, name: "summit-canva-v1.png", path: "uploads/2026-11/summit-canva-v1.png" }];
|
||||
|
||||
const result = await note();
|
||||
|
||||
expect(result).toContain("uploads/2026-11/summit-canva-v1.png");
|
||||
expect(result).toContain("[file:313]");
|
||||
expect(result).toContain("export_file");
|
||||
});
|
||||
|
||||
test("says plainly not to look for one there is no copy of", async () => {
|
||||
stat = { exists: false };
|
||||
saved = [];
|
||||
|
||||
const result = await note();
|
||||
|
||||
expect(result).toContain("not on this computer");
|
||||
expect(result).toContain("don't go looking");
|
||||
expect(result).not.toContain("[file:");
|
||||
});
|
||||
|
||||
test("says a file is there, without pointing anywhere", async () => {
|
||||
stat = { exists: true, type: "file", size: 1000, mtime_ms: 0 };
|
||||
saved = [{ id: 313, name: "summit-canva-v1.png", path: "uploads/2026-11/summit-canva-v1.png" }];
|
||||
|
||||
const result = await note();
|
||||
|
||||
expect(result).toContain("there now");
|
||||
expect(result).not.toContain("[file:313]");
|
||||
});
|
||||
|
||||
test("says nothing when the computer won't answer", async () => {
|
||||
stat = new Error("down");
|
||||
|
||||
expect(await note()).toBe("");
|
||||
});
|
||||
|
||||
test("says nothing when the brief names no files", async () => {
|
||||
stat = { exists: false };
|
||||
|
||||
expect(await note("Write up the audit.")).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
|
||||
import statComputerFile from "@/src/functions/backend/computers/stat-computer-file";
|
||||
import listBotFiles from "@/src/functions/backend/db/bot-files/list-bot-files";
|
||||
import { resolveComputerPath, type ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import fileRef from "@/src/utils/file-ref";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
import namedFiles from "@/src/utils/named-files";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
|
||||
type Params = {
|
||||
computer: ComputerApi;
|
||||
dirs: ComputerRunDirs;
|
||||
scopes: StorageScope[];
|
||||
/**
|
||||
* The user's own request and the brief the bot wrote: both name the
|
||||
* files the run is about.
|
||||
*/
|
||||
text: string;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
/**
|
||||
* Where the files a task brief names actually stand, checked before the run
|
||||
* starts: on the computer, or gone but still in the bot's files.
|
||||
*
|
||||
* App storage is the copy that survives a rebuild, and the computer's
|
||||
* workspace is the copy that doesn't, so a source the user gave the bot in
|
||||
* chat is on the computer only until the next rebuild. Without this check
|
||||
* nothing tells the run that: one looked at its empty folder, concluded the
|
||||
* file had to be somewhere, and spent thirty turns probing the container and
|
||||
* then the user's own accounts for a copy the app was holding as [file:313]
|
||||
* the whole time.
|
||||
*
|
||||
* Best effort by design: a stat that fails, or a path the run may not touch,
|
||||
* says nothing rather than blocking the run. Empty when the brief names no
|
||||
* files.
|
||||
*/
|
||||
export default async function namedFilesNote({ computer, dirs, scopes, text, signal }: Params): Promise<string> {
|
||||
const files = namedFiles({ text });
|
||||
|
||||
if (!files.length) return "";
|
||||
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
let path: string;
|
||||
|
||||
try {
|
||||
path = resolveComputerPath({ path: file.path, dirs });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
const stat = await statComputerFile({ computer, path, run_as: dirs.run_as, signal }).catch(() => null);
|
||||
|
||||
/**
|
||||
* A computer that stopped answering is not asked again: the rest of
|
||||
* the note would be guesses, and the run is better off starting.
|
||||
*/
|
||||
if (!stat) break;
|
||||
|
||||
if (stat.exists) {
|
||||
lines.push(`- ${file.path}: there now${stat.type == "directory" ? "" : ` (${formatBytes({ bytes: stat.size })})`}.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const saved = await listBotFiles({ scopes, search: file.name, limit: 3 }).catch(() => []);
|
||||
const hit = saved.find((row) => (row.name || "").toLowerCase() == file.name.toLowerCase());
|
||||
|
||||
lines.push(
|
||||
hit?.id
|
||||
? `- ${file.path}: not on this computer, but you have it in your files as ${fileRef({ id: hit.id })} (${hit.path}): copy it there with export_file and work from that.`
|
||||
: `- ${file.path}: not on this computer. It isn't elsewhere on the machine either: don't go looking through the rest of it or through the user's own accounts for it. Ask the user for it, or use the way they named.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!lines.length) return "";
|
||||
|
||||
return [
|
||||
`# Where the files this brief names stand`,
|
||||
`Checked on this computer just now, before you started. A file that isn't there was lost when the computer was rebuilt (only your folders and the browser's logins survive that) or it never arrived, so where it is isn't a question for you to go looking into.`,
|
||||
...lines,
|
||||
].join("\n\n");
|
||||
}
|
||||
@@ -80,6 +80,9 @@ import BotJobFatalError from "./bot-job-fatal-error";
|
||||
import type { BotJobContext, BotJobOutcome } from "./types";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
import taskIncoming from "./task-incoming";
|
||||
import taskRequestNote from "./task-request-note";
|
||||
import namedFilesNote from "./named-files-note";
|
||||
import grabUserBotMessage from "@/src/functions/backend/db/bots/grab-user-bot-message";
|
||||
import planBotTask from "./plan-bot-task";
|
||||
import shouldPlanBotTask from "./should-plan-bot-task";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
@@ -105,6 +108,9 @@ type Params = BotJobContext & {
|
||||
* A scheduled run acts on its own (`ScheduledRunNote`), as does a hook
|
||||
* call (`HookRunNote`, its payload only data); one that reports it failed
|
||||
* (`report_run_failed`) throws, so the queue retries it.
|
||||
* One the user asked for in their chat opens with their own words, in
|
||||
* front of the brief the bot wrote (`taskRequestNote`), so the way they
|
||||
* named survives the summary.
|
||||
* A task the user follows takes in what they write in its conversation
|
||||
* from when it was queued (`taskIncoming`): already there at the start,
|
||||
* between steps, past a report not yet out, and by the wrap up. A
|
||||
@@ -135,6 +141,12 @@ export default async function runBotTask({
|
||||
* The tracker tasks the run worked on, linked under its report.
|
||||
*/
|
||||
const task_ids: number[] = [];
|
||||
/**
|
||||
* The files the run may read, and what its computer tools export from
|
||||
* them (`export_file`): read before the computer is opened, since its
|
||||
* tool list needs them.
|
||||
*/
|
||||
const scopes = await grabRunScopes({ bot, user_id, workspace_id });
|
||||
|
||||
const computer = job.computer_id
|
||||
? await openComputerTools({
|
||||
@@ -143,6 +155,7 @@ export default async function runBotTask({
|
||||
user_id,
|
||||
workspace_id,
|
||||
dirs,
|
||||
scopes,
|
||||
onSecretRef: ({ ref }) => shown.push(ref),
|
||||
signal,
|
||||
})
|
||||
@@ -214,12 +227,6 @@ export default async function runBotTask({
|
||||
...computers.filter((c) => c.id == job.computer_id),
|
||||
...computers.filter((c) => c.id != job.computer_id),
|
||||
];
|
||||
/**
|
||||
* The files this run reaches, for its file tools, an import and the
|
||||
* pictures it may set: one answer, where `grabRunScopes` decides.
|
||||
*/
|
||||
const scopes = await grabRunScopes({ bot, user_id, workspace_id });
|
||||
|
||||
/**
|
||||
* A workspace admin's task keeps the workspace's context and its
|
||||
* members' instructions; it hands nothing over (no session to report
|
||||
@@ -473,6 +480,19 @@ export default async function runBotTask({
|
||||
? await taskIncoming({ session_id, queued_at: Number(job.created_at) || Date.now(), user_id })
|
||||
: null;
|
||||
const arrived = (await incoming?.take()) || [];
|
||||
/**
|
||||
* What the user asked for, in their own words. The brief is the
|
||||
* bot's summary of it, and a summary can lose the way they named
|
||||
* ("using the ArtCraft MCP"), which leaves the run free to reach the
|
||||
* same result another way (`taskRequestNote`). Routines, hook calls
|
||||
* and crew requests weren't asked for in a chat, so there is no
|
||||
* request to put in front of the brief.
|
||||
*/
|
||||
const request_message =
|
||||
job.message_id && !scheduled && !hooked && !Number(params.ask_id)
|
||||
? await grabUserBotMessage({ user_id, message_id: job.message_id }).catch(() => null)
|
||||
: null;
|
||||
const request_note = taskRequestNote({ message: request_message });
|
||||
const brief: HarnessMessage = {
|
||||
role: "user",
|
||||
content: composeJobBrief({
|
||||
@@ -481,7 +501,24 @@ export default async function runBotTask({
|
||||
params,
|
||||
}),
|
||||
};
|
||||
const opening: HarnessMessage[] = [brief];
|
||||
/**
|
||||
* The brief names the files the work is about. Where they actually
|
||||
* stand is the app's to check, once, rather than the run's to find
|
||||
* out: a source a rebuild took off the computer is still in the
|
||||
* bot's files, and this is what says so (`namedFilesNote`).
|
||||
*/
|
||||
const named_files_note = computer
|
||||
? await namedFilesNote({
|
||||
computer: computer.computer,
|
||||
dirs,
|
||||
scopes,
|
||||
text: [request_note, String(brief.content)].filter(Boolean).join("\n\n"),
|
||||
signal,
|
||||
})
|
||||
: "";
|
||||
const opening: HarnessMessage[] = request_note
|
||||
? [{ role: "user", content: request_note }, brief]
|
||||
: [brief];
|
||||
|
||||
if (arrived.length) {
|
||||
pushUserTurn({ transcript: opening, content: TaskIncomingNote });
|
||||
@@ -503,6 +540,7 @@ export default async function runBotTask({
|
||||
Number(params.ask_id) ? AskTaskRunNote : "",
|
||||
botFilesNote({ bot_id: bot.id }),
|
||||
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
|
||||
named_files_note,
|
||||
TasksNote,
|
||||
ActionCheckNote,
|
||||
RequestScopeNote({ can_ask }),
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import taskRequestNote from "./task-request-note";
|
||||
|
||||
describe("taskRequestNote", () => {
|
||||
test("puts the user's own words in front of the brief", () => {
|
||||
const note = taskRequestNote({
|
||||
message: { author: "user", text: "Convert this to PSD using the Artcraft MCP PhotoCraft" },
|
||||
});
|
||||
|
||||
expect(note).toContain("# What the user asked for");
|
||||
expect(note).toContain("Convert this to PSD using the Artcraft MCP PhotoCraft");
|
||||
expect(note).toContain("The brief below it is your own summary");
|
||||
expect(note).toContain("these words win");
|
||||
});
|
||||
|
||||
test("is empty for what the user didn't write", () => {
|
||||
expect(taskRequestNote({ message: { author: "bot", text: "Please make a PSD" } })).toBe("");
|
||||
expect(taskRequestNote({ message: { author: "", text: "Please make a PSD" } })).toBe("");
|
||||
expect(taskRequestNote({ message: null })).toBe("");
|
||||
expect(taskRequestNote({})).toBe("");
|
||||
});
|
||||
|
||||
test("is empty without text", () => {
|
||||
expect(taskRequestNote({ message: { author: "user", text: "" } })).toBe("");
|
||||
expect(taskRequestNote({ message: { author: "user", text: " \n " } })).toBe("");
|
||||
expect(taskRequestNote({ message: { author: "user" } })).toBe("");
|
||||
});
|
||||
|
||||
test("trims the request and writes no em dash", () => {
|
||||
const note = taskRequestNote({ message: { author: "user", text: "\n\n Make it A5 \n\n" } });
|
||||
|
||||
expect(note.endsWith("Make it A5")).toBe(true);
|
||||
expect(note).not.toContain("\u2014");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
|
||||
|
||||
/**
|
||||
* The user's own words that asked for a task run, put in front of the
|
||||
* bot's brief (`runBotTask`).
|
||||
*
|
||||
* A task run opens with the brief its bot wrote for itself
|
||||
* (`composeJobBrief`), so the request was only in the run if the bot
|
||||
* repeated it there: one that shortened it away left its run with the
|
||||
* goal and no route, and the run reached the same result by a way the
|
||||
* user didn't ask for (a PNG to "layered PSD", locally, when they said to
|
||||
* use their ArtCraft MCP). The message that asked for the work is on the
|
||||
* job (`bots_queue.message_id`, from `start_task`), so the run reads the
|
||||
* request itself, and `TaskRunNote` says the words win over the brief.
|
||||
*
|
||||
* Empty for a message the user didn't write (a crew message that asked
|
||||
* for the work, an app notice) and for one with no text.
|
||||
*/
|
||||
export default function taskRequestNote({
|
||||
message,
|
||||
}: {
|
||||
message?: Pick<BUN_SQLITE_COBBLE_BOT_MESSAGES, "author" | "text"> | null;
|
||||
}) {
|
||||
if (message?.author !== "user") return "";
|
||||
|
||||
const text = (message.text || "").trim();
|
||||
|
||||
if (!text) return "";
|
||||
|
||||
return `# What the user asked for
|
||||
|
||||
This is the request itself, as they wrote it. The brief below it is your own summary: where they disagree these words win, and the way they named is the way it is done.
|
||||
|
||||
${text}`;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import type {
|
||||
TWUIButtonColorType,
|
||||
@@ -7,7 +7,11 @@ import type {
|
||||
} from "@moduletrace/twui/layout/Button";
|
||||
import { AppWindow } from "lucide-react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import ComputerViewerModal from "./computer-viewer-modal";
|
||||
/**
|
||||
* The screen itself (noVNC, its websocket and transport) loads with the
|
||||
* click, not with the button that opens it.
|
||||
*/
|
||||
const ComputerViewerModal = lazy(() => import("./computer-viewer-modal"));
|
||||
|
||||
type Props = {
|
||||
computer_id: number;
|
||||
@@ -65,12 +69,14 @@ export default function ComputerOpenButton({
|
||||
<AppWindow size={16} aria-hidden />
|
||||
{label}
|
||||
</Button>
|
||||
<ComputerViewerModal
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
computer_id={computer_id}
|
||||
name={name}
|
||||
/>
|
||||
<Suspense fallback={null}>
|
||||
<ComputerViewerModal
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
computer_id={computer_id}
|
||||
name={name}
|
||||
/>
|
||||
</Suspense>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { lazy, Suspense, useState, type ReactNode } from "react";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import type { FilePreviewItem } from "@/src/types";
|
||||
import isPlainClick from "@/src/utils/is-plain-click";
|
||||
import FilePreviewModal from "./file-preview-modal";
|
||||
|
||||
/**
|
||||
* The preview is markdown rendering, CSV tables, the image viewer and PDF,
|
||||
* audio and video playback: none of it is needed until a file is clicked,
|
||||
* so it loads as its own chunk rather than with the conversation.
|
||||
*/
|
||||
const FilePreviewModal = lazy(() => import("./file-preview-modal"));
|
||||
|
||||
type Props = {
|
||||
name: string;
|
||||
@@ -59,15 +65,17 @@ export default function FilePreviewLink({
|
||||
{children}
|
||||
</Link>
|
||||
{open ? (
|
||||
<FilePreviewModal
|
||||
name={name}
|
||||
url={url}
|
||||
media_type={media_type}
|
||||
size={size}
|
||||
full_path={full_path}
|
||||
gallery={gallery}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
<Suspense fallback={null}>
|
||||
<FilePreviewModal
|
||||
name={name}
|
||||
url={url}
|
||||
media_type={media_type}
|
||||
size={size}
|
||||
full_path={full_path}
|
||||
gallery={gallery}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1262,6 +1262,20 @@ export const AppData = {
|
||||
* call, so a folder of raw evidence can't fill the data volume.
|
||||
*/
|
||||
BotFileImportMaxBytes: 20 * 1024 * 1024,
|
||||
/**
|
||||
* The most a bot copies from its own files onto a computer in one call
|
||||
* (`export_file`), the other direction of `BotFileImportMaxBytes`. The
|
||||
* bytes go base64 encoded in one request, so this stays well under the
|
||||
* agent's own body limit.
|
||||
*/
|
||||
BotFileExportMaxBytes: 20 * 1024 * 1024,
|
||||
/**
|
||||
* The most file paths one brief is checked for at the start of a task
|
||||
* run (`namedFiles`), the reconciliation that says where a source the
|
||||
* brief names actually is. A brief naming more than this is not about
|
||||
* its files.
|
||||
*/
|
||||
NamedFilesMax: 5,
|
||||
/**
|
||||
* Ingesting a knowledgebase document: how much text one chunk holds,
|
||||
* how much of the previous chunk it repeats, and the largest file it
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
AskGateRequest,
|
||||
crewRequestsNote,
|
||||
openRunsNote,
|
||||
QuestionsNote,
|
||||
RequestScopeNote,
|
||||
TaskIncomingNote,
|
||||
TaskPlanPrompt,
|
||||
@@ -127,6 +128,11 @@ describe("RequestScopeNote", () => {
|
||||
expect(note).toContain("delegating a task");
|
||||
expect(note).toContain("ask before it leaves: one ask_user card with every task they named");
|
||||
expect(note).toContain("don't offer it again in this conversation");
|
||||
expect(note).toContain("The way they named is part of the request");
|
||||
expect(note).toContain("ask before you start a different way");
|
||||
expect(note).toContain("Never deliver the same result by a way they didn't ask for");
|
||||
expect(note).toContain("A probe is work too");
|
||||
expect(note).toContain("a test of what the tools can reach is not the deliverable");
|
||||
expect(note).not.toContain("the brief is what you may do");
|
||||
expect(note).not.toContain("\u2014");
|
||||
});
|
||||
@@ -137,11 +143,21 @@ describe("RequestScopeNote", () => {
|
||||
expect(note).toContain("the brief is what you may do");
|
||||
expect(note).toContain("Say in your report what you would propose");
|
||||
expect(note).toContain("move it as to do and say in your report that it waits for the user to start it");
|
||||
expect(note).toContain("say in your report what was blocked and what you would propose");
|
||||
expect(note).not.toContain("ask before you start a different way");
|
||||
expect(note).not.toContain("ask_user");
|
||||
expect(note).not.toContain("\u2014");
|
||||
});
|
||||
});
|
||||
|
||||
describe("QuestionsNote", () => {
|
||||
test("asks before working around the way the user named", () => {
|
||||
expect(QuestionsNote).toContain("before changing the approach the user named");
|
||||
expect(QuestionsNote).toContain("Ask before the substitute starts, never after");
|
||||
expect(QuestionsNote).not.toContain("\u2014");
|
||||
});
|
||||
});
|
||||
|
||||
describe("task incoming notes", () => {
|
||||
test("leave separate requests to the chat and never offer send_message", () => {
|
||||
for (const note of [TaskIncomingNote, TaskRedraftNote, TaskWrapUpIncomingNote]) {
|
||||
@@ -204,6 +220,14 @@ describe("TaskRunNote", () => {
|
||||
test("gives the plan permission to hand work on", () => {
|
||||
expect(TaskPlanPrompt).toContain("hands the rest on with start_task is following the plan");
|
||||
});
|
||||
|
||||
test("says the user's own words win over the brief, and the way they named is the way it is done", () => {
|
||||
expect(TaskRunNote).toContain("the run opens with their own words");
|
||||
expect(TaskRunNote).toContain("the brief after it is your summary of it");
|
||||
expect(TaskRunNote).toContain("the way they named (a tool, app, service or path) is the way it is done");
|
||||
expect(TaskRunNote).toContain("never reach the same result some other way without asking first");
|
||||
expect(TaskRunNote).not.toContain("\u2014");
|
||||
});
|
||||
});
|
||||
|
||||
describe("AskGateNote", () => {
|
||||
|
||||
@@ -166,7 +166,7 @@ What you make there (downloads, screenshots, a crawl, raw evidence, logs) is kep
|
||||
- The user can open any of it: name a folder on the computer as a folder ref with its full path as you see it, e.g. ${folderRef({ volume: "computer", owner_id: computer_id, path: `${dirs.cwd}/seo/coderank/raw` })}. It opens that folder in Files, so it downloads nothing. Point at the folder holding the evidence they may want to see.
|
||||
${
|
||||
can_import
|
||||
? `- import_file copies a file or a folder off the computer into your own files, in one go, and the copy is searchable straight away. Import the finished work (the report, the spreadsheet, the final document), attach it when it is what they asked for, and name it with its [file:ID] ref.\n- The raw evidence can stay on the computer: import it only when the user needs it kept, or when the computer may be rebuilt.\n`
|
||||
? `- import_file copies a file or a folder off the computer into your own files, in one go, and the copy is searchable straight away. Import the finished work (the report, the spreadsheet, the final document), attach it when it is what they asked for, and name it with its [file:ID] ref.\n- The raw evidence can stay on the computer: import it only when the user needs it kept, or when the computer may be rebuilt.\n- export_file goes the other way: it copies one of your own files onto the computer, for a source the user gave you or a file to fill in. When something you need isn't there any more (a rebuild takes everything outside your folders), export it, or ask the user for it: don't search the rest of the machine for it and don't fetch it again through the browser.\n`
|
||||
: `- Work that ends in a file on the computer is a task: start one, and it saves what it made into your files with import_file, so it is kept and searchable.\n`
|
||||
}- Never say a file is saved if it only exists on the computer. Say where it is, and that it can be imported.`;
|
||||
|
||||
@@ -249,6 +249,12 @@ export const RequestScopeNote = ({ can_ask }: { can_ask: boolean }) => `# Only w
|
||||
The user's request sets the scope. Do what they asked, in the scope they gave, and nothing more.
|
||||
|
||||
- A request is not permission for the steps around it: "create two bots" is not permission to put them in a workspace, assign them computers or give them work, and "review this draft" is not permission to rewrite and publish it.
|
||||
- The way they named is part of the request. A tool, app, service, provider or path they said to use is the one to use: if it can't work, say what blocked it and what the alternatives are, and ${
|
||||
can_ask
|
||||
? `ask before you start a different way.`
|
||||
: `say in your report what was blocked and what you would propose.`
|
||||
} Never deliver the same result by a way they didn't ask for, and never let a result of your own stand in for the one they named.
|
||||
- A probe is work too. Run a check only to answer a question the request needs answered, and stop at the first answer: a test of what the tools can reach is not the deliverable, so never report one in place of what was asked.
|
||||
- Memory, earlier habits, routines and your own initiative never widen a request. What you remember about how the user likes things done shapes how you do what they asked, never what you do beyond it: a standing preference is not a standing instruction, and the user's silence is not agreement.
|
||||
- Crew changes (creating a bot or a workspace, placing one in a workspace, removing one, assigning a computer, changing a role) and handing work out (delegating a task, handing over a task or a routine to another bot) happen only when the user asked for that: ${
|
||||
can_ask
|
||||
@@ -272,6 +278,7 @@ export const QuestionsNote = `# Asking before acting
|
||||
Be proactive about moving the work forward, but let the user steer it: whenever what happens next is theirs to decide, check with ask_user instead of deciding for them or asking in your text. ask_user puts a card of multiple-choice questions in the chat (one pick or several, with "Other" for their own words) that they answer in a click, so asking costs them little. Use it:
|
||||
|
||||
- when a request could mean more than one thing, or leaves out something that changes the result (which target, which items, how far to go, what form it takes);
|
||||
- before changing the approach the user named: working around a tool they asked for, another provider, another file type, or doing it by hand instead. Ask before the substitute starts, never after: a card under work already done is not the ask;
|
||||
- before work that is hard to undo, costly or seen by others;
|
||||
- to offer the next step once you've answered or reported: the concrete next steps as options, only when a real decision or new direction remains for the user. Never interrupt an approved workflow with next-step questions when the user already gave their instruction.
|
||||
|
||||
@@ -327,6 +334,8 @@ export const TaskRunNote = `# Working on a task
|
||||
|
||||
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user. Keep the report short and in markdown.
|
||||
|
||||
When they asked for this work in their chat, the run opens with their own words: that message is the request itself, and the brief after it is your summary of it. Where the two disagree the words win, and the way they named (a tool, app, service or path) is the way it is done. If that way can't work, the report says what blocked it and what the alternatives are; never reach the same result some other way without asking first.
|
||||
|
||||
Pace your work: don't spend more than about a third of the run on pre-flight checks and backups. When the task calls for an action (a write, update, code edit, database change or file creation), execute the change early enough to verify it and report. If pre-checks pass, proceed immediately to the action. Never spend your entire run repeating read-only checks without making the change.
|
||||
|
||||
A brief can be wrong about the repository: it is written from a report or an earlier conversation, and it does not override the tree. When it says work is committed, deployed or live, check that yourself (git log, git status, the branch a file is on) before building on it. When the two disagree, the tree wins, and the report says what you found and what that means for the task.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Wakes the pending jobs a model rest parked ahead of time.
|
||||
*
|
||||
* `deferBotJob` pushes `available_at` up to a day out when every model is
|
||||
* resting with no end, and `claimBotJobs` only claims what is already
|
||||
* available. Nothing else would ever move it: the benches live in memory, so
|
||||
* a restart forgets them, and a run-limits save clears them, while the job
|
||||
* they parked kept sleeping. `last_error IS NULL` keeps a real failure
|
||||
* backoff out of it: a job deferred for a rest has never failed a turn.
|
||||
*/
|
||||
export const ReleaseRestingBotJobsSql = `UPDATE bots_queue SET available_at = ?, updated_at = ?
|
||||
WHERE status = 'pending' AND last_error IS NULL AND available_at > ?
|
||||
RETURNING id`;
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { beforeEach, describe, expect, test } from "bun:test";
|
||||
import { ReleaseRestingBotJobsSql } from "./release-resting-bot-jobs-sql";
|
||||
|
||||
const db = new Database(":memory:");
|
||||
const now = 1_800_000_000_000;
|
||||
|
||||
beforeEach(() => {
|
||||
db.run(`DROP TABLE IF EXISTS bots_queue`);
|
||||
db.run(`CREATE TABLE bots_queue (
|
||||
id INTEGER PRIMARY KEY,
|
||||
status TEXT NOT NULL,
|
||||
available_at INTEGER NOT NULL,
|
||||
last_error TEXT,
|
||||
updated_at INTEGER
|
||||
)`);
|
||||
});
|
||||
|
||||
function insert(row: {
|
||||
id: number;
|
||||
status: string;
|
||||
available_at: number;
|
||||
last_error?: string | null;
|
||||
updated_at?: number;
|
||||
}) {
|
||||
db.run(
|
||||
`INSERT INTO bots_queue (id, status, available_at, last_error, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
[row.id, row.status, row.available_at, row.last_error ?? null, row.updated_at ?? 0],
|
||||
);
|
||||
}
|
||||
|
||||
function available(id: number) {
|
||||
return db.query(`SELECT available_at FROM bots_queue WHERE id = ?`).get(id) as {
|
||||
available_at: number;
|
||||
};
|
||||
}
|
||||
|
||||
function release() {
|
||||
return db.query(ReleaseRestingBotJobsSql).all(now, now, now) as { id: number }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A job parked on a model rest must wake when the benches it waited on are
|
||||
* gone (a run-limits save, a restart), while a job backing off a real failure
|
||||
* keeps its delay and work in flight is left alone.
|
||||
*/
|
||||
describe("ReleaseRestingBotJobsSql", () => {
|
||||
test("wakes a pending job parked by a rest", () => {
|
||||
insert({ id: 1, status: "pending", available_at: now + 86_400_000 });
|
||||
|
||||
const woken = release();
|
||||
|
||||
expect(woken.map((row) => row.id)).toEqual([1]);
|
||||
expect(available(1).available_at).toBe(now);
|
||||
});
|
||||
|
||||
test("leaves a job backing off a real failure", () => {
|
||||
insert({ id: 2, status: "pending", available_at: now + 60_000, last_error: "Provider is down" });
|
||||
|
||||
expect(release()).toEqual([]);
|
||||
expect(available(2).available_at).toBe(now + 60_000);
|
||||
});
|
||||
|
||||
test("leaves work in flight, and a job already available", () => {
|
||||
insert({ id: 3, status: "processing", available_at: now + 86_400_000 });
|
||||
insert({ id: 4, status: "pending", available_at: now - 1_000 });
|
||||
|
||||
expect(release()).toEqual([]);
|
||||
expect(available(3).available_at).toBe(now + 86_400_000);
|
||||
expect(available(4).available_at).toBe(now - 1_000);
|
||||
});
|
||||
|
||||
test("wakes every parked job at once", () => {
|
||||
insert({ id: 5, status: "pending", available_at: now + 86_400_000 });
|
||||
insert({ id: 6, status: "pending", available_at: now + 3_600_000 });
|
||||
insert({ id: 7, status: "failed", available_at: now + 86_400_000 });
|
||||
|
||||
expect(release().map((row) => row.id).sort()).toEqual([5, 6]);
|
||||
expect(available(5).available_at).toBe(now);
|
||||
expect(available(6).available_at).toBe(now);
|
||||
expect(available(7).available_at).toBe(now + 86_400_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { ReleaseRestingBotJobsSql } from "./release-resting-bot-jobs-sql";
|
||||
|
||||
/**
|
||||
* Puts every pending job a model rest parked ahead of time back in the queue
|
||||
* now, and returns how many woke.
|
||||
*
|
||||
* Called where the benches they waited on stop existing: when the run limits
|
||||
* (and with them the model rest) are saved, and when the queue starts, since
|
||||
* the cooldowns are in memory and a restart forgets them. Without this the
|
||||
* job sleeps until its day-long `available_at` cap with nothing left to wait
|
||||
* for, and the bot shows "Waiting for a free model" over a stopped queue.
|
||||
*/
|
||||
export default async function releaseRestingBotJobs() {
|
||||
const now = Date.now();
|
||||
|
||||
const res = await BunSQLite.sql({
|
||||
sql: ReleaseRestingBotJobsSql,
|
||||
values: [now, now, now],
|
||||
});
|
||||
|
||||
return res.payload?.length || 0;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import HarnessCooldowns from "./harness-cooldowns";
|
||||
|
||||
/**
|
||||
* The benches must be one store for the whole process. bunext bundles API
|
||||
* routes and the server entry separately, so a module-scoped map let a
|
||||
* run-limits save clear the API bundle's copy while the queue kept its own:
|
||||
* a rest with no end survived the save that was supposed to end it.
|
||||
*/
|
||||
describe("HarnessCooldowns", () => {
|
||||
test("lives on the shared global slot", () => {
|
||||
const holder = globalThis as Record<symbol, unknown>;
|
||||
|
||||
expect(holder[Symbol.for("cobble.harnessCooldowns")]).toBe(HarnessCooldowns);
|
||||
});
|
||||
|
||||
test("a second copy of the module is the same store", async () => {
|
||||
const specifier = "./harness-cooldowns.ts?bundle=2";
|
||||
const other = (await import(specifier)).default;
|
||||
|
||||
expect(other).toBe(HarnessCooldowns);
|
||||
|
||||
HarnessCooldowns.set({ key: "9:test-model", at: Date.now() + 60_000 });
|
||||
|
||||
expect(other.get({ key: "9:test-model" })).toBeGreaterThan(Date.now());
|
||||
|
||||
other.clear();
|
||||
|
||||
expect(HarnessCooldowns.get({ key: "9:test-model" })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,21 @@
|
||||
import globalCache from "@/src/utils/global-cache";
|
||||
import createCooldowns from "./create-cooldowns";
|
||||
import type { HarnessCooldowns } from "./create-cooldowns";
|
||||
|
||||
/**
|
||||
* The process-wide cooldowns every harness call shares, so one job's rate
|
||||
* limit spares the next job the same failed call.
|
||||
*
|
||||
* Held on `globalThis`, not in a module variable: bunext bundles API routes
|
||||
* and the server entry separately, so a module-scoped map let a run-limits
|
||||
* save (`HarnessCooldowns.clear()`) empty the API bundle's copy while the
|
||||
* queue kept its own benches, and a rest with no end survived the save that
|
||||
* was supposed to end it.
|
||||
*/
|
||||
const HarnessCooldowns = createCooldowns();
|
||||
const slot = globalCache<HarnessCooldowns>({ name: "cobble.harnessCooldowns" });
|
||||
|
||||
export default HarnessCooldowns;
|
||||
const HarnessCooldowns = slot.get() || createCooldowns();
|
||||
|
||||
slot.set(HarnessCooldowns);
|
||||
|
||||
export default HarnessCooldowns;
|
||||
@@ -0,0 +1,175 @@
|
||||
import { afterAll, beforeAll, describe, expect, mock, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { ComputerWorkspaceQuotaSettingKey } from "@/src/dict/computer-dict";
|
||||
import type { ComputerFileStat } from "@/src/functions/backend/computers/stat-computer-file";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
|
||||
/**
|
||||
* `export_file` is the way back for a source a rebuild took off the
|
||||
* computer: it copies one of the bot's own files there, base64 and whole,
|
||||
* charged against the workspace only for what it adds.
|
||||
*/
|
||||
let file: { id: number; name: string; path: string; media: { media_write_path: string } | null } | null = null;
|
||||
let stat: ComputerFileStat = { exists: false };
|
||||
let saved_mb: string | undefined;
|
||||
let usage: { used_bytes: number } | null = null;
|
||||
const writes: Array<{ path: string; content: Buffer }> = [];
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "export-file-"));
|
||||
/**
|
||||
* The rows point at `media/stored.png` inside a data directory of the
|
||||
* test's own: the real `mediaFilePath` resolves it, so the reach rule and
|
||||
* the byte read are the ones a run gets.
|
||||
*/
|
||||
const stored = path.join(dir, "media", "stored.png");
|
||||
const previous_data_dir = process.env.DATA_DIR;
|
||||
|
||||
beforeAll(() => {
|
||||
mkdirSync(path.dirname(stored), { recursive: true });
|
||||
process.env.DATA_DIR = dir;
|
||||
});
|
||||
|
||||
mock.module("@/src/functions/backend/db/bot-files/grab-bot-file", () => ({
|
||||
default: async () => file,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/app-settings/grab-app-setting", () => ({
|
||||
default: async ({ key }: { key: string }) => (key == ComputerWorkspaceQuotaSettingKey ? saved_mb : undefined),
|
||||
}));
|
||||
mock.module("@/src/functions/backend/computers/grab-computer-usage", () => ({
|
||||
default: async () => usage,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/computers/stat-computer-file", () => ({
|
||||
default: async () => stat,
|
||||
}));
|
||||
mock.module("@/src/functions/backend/computers/write-computer-file", () => ({
|
||||
default: async ({ path, content }: { path: string; content: Buffer }) => {
|
||||
writes.push({ path, content });
|
||||
|
||||
return { ok: true, size: content.length };
|
||||
},
|
||||
}));
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
|
||||
if (previous_data_dir == undefined) delete process.env.DATA_DIR;
|
||||
else process.env.DATA_DIR = previous_data_dir;
|
||||
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const computer = {} as ComputerApi;
|
||||
const dirs = computerRunDirs({ bot_id: 8, bot_kind: "worker", user_id: 1, workspace_id: null });
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
async function exportTo(computer_path = "sources/summit.png") {
|
||||
const { default: make } = await import("./export-file-tool");
|
||||
const tool = make({ computer, dirs, scopes: [] });
|
||||
|
||||
return tool.run({ args: { file_id: 313, path: computer_path }, signal: new AbortController().signal });
|
||||
}
|
||||
|
||||
describe("exportFileTool", () => {
|
||||
test("copies the bytes onto the computer, whole", async () => {
|
||||
writeFileSync(stored, Buffer.from([0x89, 0x50, 0x4e, 0x47]));
|
||||
file = { id: 313, name: "summit.png", path: "uploads/summit.png", media: { media_write_path: "media/stored.png" } };
|
||||
stat = { exists: false };
|
||||
saved_mb = "0";
|
||||
usage = null;
|
||||
writes.length = 0;
|
||||
|
||||
const result = await exportTo();
|
||||
|
||||
expect(result).toContain("Copied summit.png");
|
||||
expect(result).toContain(`${dirs.cwd}/sources/summit.png`);
|
||||
expect(result).toContain("new file");
|
||||
expect(writes.length).toBe(1);
|
||||
expect(Array.from(writes[0]!.content)).toEqual([0x89, 0x50, 0x4e, 0x47]);
|
||||
});
|
||||
|
||||
test("says what it replaced", async () => {
|
||||
writeFileSync(stored, Buffer.from("hello"));
|
||||
file = { id: 313, name: "summit.png", path: "uploads/summit.png", media: { media_write_path: "media/stored.png" } };
|
||||
stat = { exists: true, type: "file", size: 9000, mtime_ms: 0 };
|
||||
saved_mb = "0";
|
||||
writes.length = 0;
|
||||
|
||||
const result = await exportTo();
|
||||
|
||||
expect(result).toContain("replaced");
|
||||
expect(result).toContain("8.8 KB");
|
||||
});
|
||||
|
||||
test("a file the run can't reach is named as unknown", async () => {
|
||||
file = null;
|
||||
writes.length = 0;
|
||||
|
||||
const result = await exportTo();
|
||||
|
||||
expect(result).toContain("No file matches that");
|
||||
expect(writes.length).toBe(0);
|
||||
});
|
||||
|
||||
test("a row with no stored bytes says so", async () => {
|
||||
file = { id: 313, name: "summit.png", path: "uploads/summit.png", media: null };
|
||||
writes.length = 0;
|
||||
|
||||
const result = await exportTo();
|
||||
|
||||
expect(result).toContain("No file matches that");
|
||||
expect(writes.length).toBe(0);
|
||||
});
|
||||
|
||||
test("a row whose bytes were cleaned up says so", async () => {
|
||||
rmSync(stored, { force: true });
|
||||
file = { id: 313, name: "summit.png", path: "uploads/summit.png", media: { media_write_path: "media/stored.png" } };
|
||||
writes.length = 0;
|
||||
|
||||
const result = await exportTo();
|
||||
|
||||
expect(result).toContain("missing on the server");
|
||||
expect(writes.length).toBe(0);
|
||||
});
|
||||
|
||||
test("a file over the cap is refused, naming a way through", async () => {
|
||||
writeFileSync(stored, Buffer.alloc(AppData.BotFileExportMaxBytes + 1));
|
||||
file = { id: 313, name: "summit.png", path: "uploads/summit.png", media: { media_write_path: "media/stored.png" } };
|
||||
writes.length = 0;
|
||||
|
||||
const result = await exportTo();
|
||||
|
||||
expect(result).toContain("transform_image");
|
||||
expect(writes.length).toBe(0);
|
||||
});
|
||||
|
||||
test("a copy that would fill the workspace is refused", async () => {
|
||||
writeFileSync(stored, Buffer.alloc(2000));
|
||||
file = { id: 313, name: "summit.png", path: "uploads/summit.png", media: { media_write_path: "media/stored.png" } };
|
||||
stat = { exists: false };
|
||||
saved_mb = "10";
|
||||
usage = { used_bytes: 10 * MB };
|
||||
writes.length = 0;
|
||||
|
||||
const result = await exportTo();
|
||||
|
||||
expect(result).toContain("No room left");
|
||||
expect(writes.length).toBe(0);
|
||||
});
|
||||
|
||||
test("a copy over a file the same size adds nothing to the workspace", async () => {
|
||||
writeFileSync(stored, Buffer.alloc(2000));
|
||||
file = { id: 313, name: "summit.png", path: "uploads/summit.png", media: { media_write_path: "media/stored.png" } };
|
||||
stat = { exists: true, type: "file", size: 2000, mtime_ms: 0 };
|
||||
saved_mb = "10";
|
||||
usage = { used_bytes: 10 * MB };
|
||||
writes.length = 0;
|
||||
|
||||
const result = await exportTo();
|
||||
|
||||
expect(result).toContain("Copied");
|
||||
expect(writes.length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
|
||||
import statComputerFile from "@/src/functions/backend/computers/stat-computer-file";
|
||||
import writeComputerFile from "@/src/functions/backend/computers/write-computer-file";
|
||||
import grabBotFile from "@/src/functions/backend/db/bot-files/grab-bot-file";
|
||||
import { resolveComputerPath, type ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
import mediaFilePath from "@/src/utils/media-file-path";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import computerWorkspaceRoomError from "./computer-workspace-room";
|
||||
|
||||
type Params = {
|
||||
computer: ComputerApi;
|
||||
dirs: ComputerRunDirs;
|
||||
/**
|
||||
* The files this run may read (`grabRunScopes`): a file outside them is
|
||||
* not its to export.
|
||||
*/
|
||||
scopes: StorageScope[];
|
||||
};
|
||||
|
||||
type Args = {
|
||||
file_id: number;
|
||||
path: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Copies one of the bot's own files onto its computer: the inverse of
|
||||
* `import_file`, and the way back for a source a rebuild took with it.
|
||||
*
|
||||
* A bot given a file in the chat had it in its files only: app storage is
|
||||
* the copy that survives a rebuild, while the computer's workspace is a
|
||||
* mount a rebuild recreates empty. Without this, a run whose source was no
|
||||
* longer on the computer had no legal way to get it back, and one spent
|
||||
* thirty turns probing the container, then the user's own accounts, for a
|
||||
* copy of a file the app was holding all along.
|
||||
*
|
||||
* The bytes go over the agent's write endpoint, which takes them base64
|
||||
* encoded (`writeComputerFile`), so a binary source arrives whole.
|
||||
*/
|
||||
export default function exportFileTool({ computer, dirs, scopes }: Params): HarnessTool<Args> {
|
||||
const max = formatBytes({ bytes: AppData.BotFileExportMaxBytes });
|
||||
|
||||
return {
|
||||
name: "export_file",
|
||||
description: `Copy one of your own files onto this computer, so you can work on it here. Give the file's ref id and where it goes in your folder (${dirs.cwd}); missing folders are created. Use it for a source the user gave you when it isn't on the computer any more (a rebuild takes everything outside your folders), instead of looking for it elsewhere or fetching it again through the browser. Up to ${max}.`,
|
||||
schema: z.object({
|
||||
file_id: z.number().int().positive().describe(`The file's id from its [file:ID] ref, or from list_files`),
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(AppData.BotFilePathMaxChars)
|
||||
.describe(`Where to put it on the computer, relative to your folder, e.g. "sources/summit-canva-v1.png"`),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
const file = await grabBotFile({ scopes, file_id: args.file_id });
|
||||
const absolute = mediaFilePath({ write_path: file?.media?.media_write_path });
|
||||
|
||||
if (!file?.id || !absolute) {
|
||||
return `No file matches that, or it has no bytes stored. Use list_files to see what you have.`;
|
||||
}
|
||||
|
||||
const stored = Bun.file(absolute);
|
||||
|
||||
if (!(await stored.exists())) {
|
||||
return `That file's copy is missing on the server (it may have been cleaned up since). Use list_files to see what you have.`;
|
||||
}
|
||||
|
||||
const name = file.name || file.path || "file";
|
||||
|
||||
/**
|
||||
* The size is checked before the read, so a file over the cap is
|
||||
* refused without loading it into memory.
|
||||
*/
|
||||
if (stored.size > AppData.BotFileExportMaxBytes) {
|
||||
return `That file is ${formatBytes({ bytes: stored.size })}: export_file takes up to ${max}. For an image, transform_image can make a smaller copy to export instead.`;
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(await stored.arrayBuffer());
|
||||
|
||||
const path = resolveComputerPath({ path: args.path, dirs });
|
||||
const existing = await statComputerFile({ computer, path, run_as: dirs.run_as, signal }).catch(() => null);
|
||||
const existing_bytes = existing?.exists && existing.type == "file" ? existing.size : 0;
|
||||
/**
|
||||
* Only what the copy adds counts against the workspace's limit,
|
||||
* as a rewrite does (`computer_write_file`): exporting over a
|
||||
* file the same size adds nothing.
|
||||
*/
|
||||
const too_big = await computerWorkspaceRoomError({
|
||||
computer,
|
||||
dirs,
|
||||
incoming_bytes: Math.max(0, bytes.length - existing_bytes),
|
||||
signal,
|
||||
});
|
||||
|
||||
if (too_big) return too_big;
|
||||
|
||||
const written = await writeComputerFile({ computer, path, content: bytes, run_as: dirs.run_as, signal });
|
||||
|
||||
return [
|
||||
`Copied ${name} (${formatBytes({ bytes: written.size })}) from your files to ${path}.`,
|
||||
existing_bytes
|
||||
? `It replaced the ${formatBytes({ bytes: existing_bytes })} file that was there.`
|
||||
: `It is a new file there.`,
|
||||
].join(" ");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -74,7 +74,7 @@ export default function importFileTool({
|
||||
name: "import_file",
|
||||
description: `Copy a file or folder from this computer into your own files, so it is kept with the app and stays after the computer is rebuilt. Give its path on the computer, relative to your folder there (${dirs.cwd}), e.g. "seo/coderank/raw/crawl.json" or "seo/coderank/raw"; a folder comes in as it is, in one go. Up to ${max_mb} MB. Check with list_files and the computer's own tools what you already imported: importing the same thing twice just writes over the copy, so do it once.${
|
||||
own?.scope == "workspace" ? " The copies land in the workspace's shared files." : ""
|
||||
} Imports are readable at once. Name a copy with its [file:ID] ref. Import the report you wrote before the last long steps of a run, so it is never lost to the step limit.`,
|
||||
} Imports are readable at once. Name a copy with its [file:ID] ref. Import the report you wrote before the last long steps of a run, so it is never lost to the step limit. The other direction is export_file, which puts one of your own files back on the computer.`,
|
||||
schema: z.object({
|
||||
path: z
|
||||
.string()
|
||||
|
||||
@@ -9,6 +9,7 @@ import computerNotReadyMessage from "@/src/utils/computer-not-ready-message";
|
||||
import isComputerDown from "@/src/utils/computer-down";
|
||||
import BotJobFatalError from "@/src/bots-queue/bot-job-fatal-error";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import redactSecrets from "@/src/utils/redact-secrets";
|
||||
import connectMcpServer from "../../mcp/connect-mcp-server";
|
||||
import grabMcpTools from "../../mcp/grab-mcp-tools";
|
||||
@@ -20,6 +21,7 @@ import computerEditFileTool from "./computer-edit-file-tool";
|
||||
import computerReadFileTool from "./computer-read-file-tool";
|
||||
import type { ComputerToolContext } from "./computer-tool-context";
|
||||
import computerWriteFileTool from "./computer-write-file-tool";
|
||||
import exportFileTool from "./export-file-tool";
|
||||
import withBrowserOutputs from "./with-browser-outputs";
|
||||
import withComputerDirs from "./with-computer-dirs";
|
||||
import withWorkerBrowserFiles from "./with-worker-browser-files";
|
||||
@@ -44,6 +46,11 @@ type Params = {
|
||||
* kept inside them.
|
||||
*/
|
||||
dirs: ComputerRunDirs;
|
||||
/**
|
||||
* The bot files this run may read (`grabRunScopes`): what `export_file`
|
||||
* can copy onto the computer.
|
||||
*/
|
||||
scopes: StorageScope[];
|
||||
/**
|
||||
* Called with the ref of each secret the bot captures on the computer
|
||||
* (`capture_secret`), so the run's message always carries its chip.
|
||||
@@ -99,6 +106,7 @@ export default async function openComputerTools({
|
||||
user_id,
|
||||
workspace_id,
|
||||
dirs,
|
||||
scopes,
|
||||
onSecretRef,
|
||||
browser = true,
|
||||
signal,
|
||||
@@ -160,6 +168,7 @@ export default async function openComputerTools({
|
||||
computerReadFileTool(context),
|
||||
computerWriteFileTool(context),
|
||||
computerEditFileTool(context),
|
||||
exportFileTool({ computer: target, dirs, scopes }),
|
||||
...browser_tools.map((tool) =>
|
||||
withBrowserOutputs({
|
||||
tool: withComputerDirs({ tool: withWorkerBrowserFiles({ tool, computer: target, dirs }), dirs }),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import isCrewMessage from "@/src/utils/is-crew-message";
|
||||
import { useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { lazy, Suspense, useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import awaitsReply from "../(utils)/awaits-reply";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { BotMessageReactionEmoji } from "@/src/dict/bot-dict";
|
||||
@@ -36,7 +36,13 @@ import ConversationHeader from "../(partials)/conversation-header";
|
||||
import useDebugOpen from "../(hooks)/use-debug-open";
|
||||
import MessageThread from "../(partials)/message-thread";
|
||||
import Composer, { type ComposerHandle } from "../(partials)/composer";
|
||||
import ComputerViewerModal from "../(partials)/computer-viewer-modal";
|
||||
/**
|
||||
* A computer's live screen (noVNC, its websocket and transport) is only
|
||||
* needed once the user opens one, so it loads as its own chunk.
|
||||
*/
|
||||
const ComputerViewerModal = lazy(
|
||||
() => import("../(partials)/computer-viewer-modal"),
|
||||
);
|
||||
import HistoryErrorRow from "../(partials)/history-error-row";
|
||||
import useConversationHistory from "../(hooks)/use-conversation-history";
|
||||
import mergeLoadedHistory from "../(utils)/merge-loaded-history";
|
||||
@@ -607,7 +613,9 @@ export default function Conversation() {
|
||||
)}
|
||||
</Stack>
|
||||
</BotMessageActionsContext.Provider>
|
||||
<ComputerViewerModal bot={live_bot} />
|
||||
<Suspense fallback={null}>
|
||||
<ComputerViewerModal bot={live_bot} />
|
||||
</Suspense>
|
||||
</SpeakMessageContext.Provider>
|
||||
</BotComputersContext.Provider>
|
||||
</CrewWorkspacesContext.Provider>
|
||||
|
||||
@@ -17,6 +17,7 @@ import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import HarnessCooldowns from "@/src/harness/resolve/harness-cooldowns";
|
||||
import releaseRestingBotJobs from "@/src/functions/backend/db/bots-queue/release-resting-bot-jobs";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
@@ -68,6 +69,12 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<RunLimitsOverview>
|
||||
*/
|
||||
HarnessCooldowns.clear();
|
||||
|
||||
/**
|
||||
* The jobs a rest parked ahead of time were waiting on those same
|
||||
* benches, which just went away: nothing else would wake them.
|
||||
*/
|
||||
const released = await releaseRestingBotJobs();
|
||||
|
||||
await logEvent({
|
||||
title: "Bot run limits changed",
|
||||
category: "system",
|
||||
@@ -75,7 +82,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<RunLimitsOverview>
|
||||
plain_text: `User #${user.id} set the tool step limits to ${loggedValue(task_steps)} per task, ${loggedValue(reply_steps)} per chat reply and ${loggedValue(unattended_steps)} per routine or hook call, the tokens per run to ${loggedValue(run_tokens)}, the working context to ${loggedValue(context_tokens)} and the model rest to ${
|
||||
model_rest_seconds == -1 ? "unlimited" : model_rest_seconds > 0 ? `${model_rest_seconds} seconds` : "default"
|
||||
}.`,
|
||||
metadata: { task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds },
|
||||
metadata: { task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds, jobs_released: released },
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
|
||||
@@ -19,7 +19,8 @@ type Slot<Value> = {
|
||||
*/
|
||||
export type GlobalCacheName =
|
||||
| "cobble.grabAllEnvs.cache"
|
||||
| "cobble.grabAppSettings.cache";
|
||||
| "cobble.grabAppSettings.cache"
|
||||
| "cobble.harnessCooldowns";
|
||||
|
||||
export default function globalCache<Value>({
|
||||
name,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import namedFiles from "./named-files";
|
||||
|
||||
describe("namedFiles", () => {
|
||||
test("finds a path the brief names", () => {
|
||||
const files = namedFiles({
|
||||
text: "Build a layered PSD from uploads/2026-11/summit-canva-v1.png, keeping the layers.",
|
||||
});
|
||||
|
||||
expect(files).toEqual([{ path: "uploads/2026-11/summit-canva-v1.png", name: "summit-canva-v1.png" }]);
|
||||
});
|
||||
|
||||
test("finds a bare name with a known extension", () => {
|
||||
expect(namedFiles({ text: "use summit-canva-v1.png as the source" })).toEqual([
|
||||
{ path: "summit-canva-v1.png", name: "summit-canva-v1.png" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("leaves prose alone", () => {
|
||||
expect(namedFiles({ text: "run it with node.js, then bump to v1.2, e.g. the Build step" })).toEqual([]);
|
||||
});
|
||||
|
||||
test("keeps the order the brief names them in, and dedupes", () => {
|
||||
const files = namedFiles({
|
||||
text: "Compare report.pdf with notes.md, then with report.pdf again.",
|
||||
});
|
||||
|
||||
expect(files.map((file) => file.name)).toEqual(["report.pdf", "notes.md"]);
|
||||
});
|
||||
|
||||
test("stops at the limit", () => {
|
||||
const files = namedFiles({ text: "a.png b.png c.png d.png e.png f.png g.png", limit: 3 });
|
||||
|
||||
expect(files.map((file) => file.name)).toEqual(["a.png", "b.png", "c.png"]);
|
||||
});
|
||||
|
||||
test("drops a URL's path", () => {
|
||||
expect(namedFiles({ text: "download it from https://example.com/media/source.png first" })).toEqual([]);
|
||||
});
|
||||
|
||||
test("finds nothing in an empty brief", () => {
|
||||
expect(namedFiles({ text: " \n " })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
/**
|
||||
* Extensions a brief names a file by. A token without a `/` only counts as
|
||||
* a file when it ends in one of these, so "node.js" or "v1.2" in a brief
|
||||
* don't send a run looking for a file that was never meant.
|
||||
*/
|
||||
const NamedFileExtensions = new Set([
|
||||
"png",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"gif",
|
||||
"webp",
|
||||
"svg",
|
||||
"heic",
|
||||
"tif",
|
||||
"tiff",
|
||||
"avif",
|
||||
"psd",
|
||||
"ai",
|
||||
"eps",
|
||||
"indd",
|
||||
"sketch",
|
||||
"fig",
|
||||
"pdf",
|
||||
"csv",
|
||||
"tsv",
|
||||
"xlsx",
|
||||
"xls",
|
||||
"ods",
|
||||
"docx",
|
||||
"doc",
|
||||
"odt",
|
||||
"pptx",
|
||||
"ppt",
|
||||
"key",
|
||||
"md",
|
||||
"txt",
|
||||
"rtf",
|
||||
"json",
|
||||
"xml",
|
||||
"yaml",
|
||||
"yml",
|
||||
"zip",
|
||||
"tar",
|
||||
"gz",
|
||||
"7z",
|
||||
"mp3",
|
||||
"wav",
|
||||
"m4a",
|
||||
"mp4",
|
||||
"mov",
|
||||
"webm",
|
||||
"avi",
|
||||
"mkv",
|
||||
"epub",
|
||||
"sql",
|
||||
"db",
|
||||
"ipynb",
|
||||
]);
|
||||
|
||||
/**
|
||||
* A path-ish token with an extension, e.g. `uploads/2026-11/summit.png`.
|
||||
* Punctuation is not part of it, so a match never keeps the comma or the
|
||||
* bracket around it.
|
||||
*/
|
||||
const NamedFileToken = /[A-Za-z0-9_][A-Za-z0-9_.\-/]*\.[A-Za-z0-9]{2,5}/g;
|
||||
|
||||
export type NamedFile = {
|
||||
/**
|
||||
* As the brief wrote it: `uploads/2026-11/summit-canva-v1.png`.
|
||||
*/
|
||||
path: string;
|
||||
/**
|
||||
* Its last segment: `summit-canva-v1.png`.
|
||||
*/
|
||||
name: string;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* What the user asked for and the brief the bot wrote: both name the
|
||||
* files the run is about.
|
||||
*/
|
||||
text: string;
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The files a brief names, in the order it names them, deduped.
|
||||
*
|
||||
* A run that needs a source which a rebuild took off its computer otherwise
|
||||
* has nothing to go on but the name in its brief, and one went looking for
|
||||
* it across the container and then the user's own accounts. Checking those
|
||||
* names against the computer, and against the bot's files, starts the run
|
||||
* with the answer (`namedFilesNote`).
|
||||
*
|
||||
* Deliberately conservative: a token counts as a file when it has a folder
|
||||
* in it or a known file extension, so prose ("node.js", "v1.2", "e.g")
|
||||
* stays out of it. A URL is not a file on the computer either, so its path
|
||||
* (the part after the host) is dropped.
|
||||
*/
|
||||
export default function namedFiles({ text, limit = AppData.NamedFilesMax }: Params): NamedFile[] {
|
||||
if (!text.trim()) return [];
|
||||
|
||||
const found: NamedFile[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const match of text.matchAll(NamedFileToken)) {
|
||||
const token = match[0];
|
||||
|
||||
if (found.length >= limit) break;
|
||||
/**
|
||||
* `https://host/a.png` leaves `host/a.png`, since the regex has no
|
||||
* `:`: a URL is not a file on this computer.
|
||||
*/
|
||||
if (text[match.index - 1] == "/" || /^[a-z0-9-]+\.[a-z]{2,4}\//i.test(token)) continue;
|
||||
/**
|
||||
* A path ending in a folder is not a file; only the last segment's
|
||||
* extension counts.
|
||||
*/
|
||||
const name = token.split("/").pop() || "";
|
||||
const ext = name.split(".").pop()?.toLowerCase() || "";
|
||||
|
||||
if (!name.includes(".") || !ext) continue;
|
||||
if (!token.includes("/") && !NamedFileExtensions.has(ext)) continue;
|
||||
|
||||
const key = token.toLowerCase();
|
||||
|
||||
if (seen.has(key)) continue;
|
||||
|
||||
seen.add(key);
|
||||
found.push({ path: token, name });
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
Reference in New Issue
Block a user