Find files in every folder, and let a reply import what it built
`list_files` with only a search never looked past the root folder, so a picture saved in `images/` was reported as missing and two tasks went hunting a computer for a script that sat in `scripts/`. `write_file` accepted base64 text under `.png` and attached a 2.6 KB file that would not open while the reply said a 1376x768 PNG was there. Replies had no `import_file`, so a real render made on a computer could only come back through a shell cut at 4,000 characters. - Search lists matches from every folder unless one is named, and an empty search no longer says the bot has no files. - `write_file` refuses binary extensions, and an image typed as a bot write must carry a real image signature. - A chat reply gets `import_file` from any of its computers, and the task run still imports from its own. - A rerun reads the failed attempt's reason instead of repeating the premise that failed.
This commit is contained in:
@@ -108,7 +108,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
|
||||
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages that have any, and only while they're within `BotReplyAttachmentMaxAgeMessages` of the latest (`liveAttachmentMessages`: one old screenshot, being the last message with files, was re-attached and re-read on every reply for the rest of a long session); older files are only named. An upload's bytes go with its message: whatever deletes messages that carry them (`deleteAskRows`) unlinks them and deletes a media row nothing else points at (`deleteUnlinkedAttachmentMedia`), and `prune-orphan-media` takes what is left after `AppData.MediaOrphanKeepDays` (both share `UnreferencedMediaSql`). Tasks don't get files yet.
|
||||
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
|
||||
- **Running a reply again:** the bot's last word in a conversation (`MessageThread` reads its own last bot message, crew messages aside) offers Run again (`retry-reply-button.tsx` -> `api/admin/bots/retry-reply`, eligibility in `rerunReplyProblem`), whatever it was: an answer that went out, a stopped run's notice, a task run's failure. A failed reply's notice carries `bot_messages.failed_job_id` (set by `notifyBotJobFailed`, not an FK); while it still `needs_you`, its actions show Retry instead (the same action, worded for a failure, eligibility in `retryReplyProblem`), which clears the notice's `needs_you`. Either way the route queues a reply to the newest user message with `params.retry_of`, so `run-bot-reply` bypasses the silent finish gate (a reply run again doesn't look unanswered) and gets `RerunReplyNote`; the thread leaves that message out (only a bot message is hidden, `threadMessages`) and shows its thinking row until a newer bot message lands (`rerun_after_id` in `conversation.tsx`: the message it runs again is the last one and looks answered, and a stopped run's notice would say it stopped right above the row). A run that was stopped, or ended without a word, leaves the user's own message last with nothing on its way: the thread says so there and offers the same Run again on it (`unanswered-reply-row.tsx`; the route answers it when `rerunReplyProblem` sees it is the session's last message), instead of a thinking row that would never move (`awaits-reply.ts`, which holds the row back once the open replies are read as none). Failure notices are the app's record, never the bot's words, so `botMessagesToHarness` skips them.
|
||||
- **Running a reply again:** the bot's last word in a conversation (`MessageThread` reads its own last bot message, crew messages aside) offers Run again (`retry-reply-button.tsx` -> `api/admin/bots/retry-reply`, eligibility in `rerunReplyProblem`), whatever it was: an answer that went out, a stopped run's notice, a task run's failure. A failed reply's notice carries `bot_messages.failed_job_id` (set by `notifyBotJobFailed`, not an FK); while it still `needs_you`, its actions show Retry instead (the same action, worded for a failure, eligibility in `retryReplyProblem`), which clears the notice's `needs_you`. Either way the route queues a reply to the newest user message with `params.retry_of`, so `run-bot-reply` bypasses the silent finish gate (a reply run again doesn't look unanswered) and gets `RerunReplyNote`; a retry whose message carries `failed_job_id` also reads that job's `last_error` (`grabRetryFailure` -> `RetryFailureNote`), so it knows what the failed attempt claimed and never did instead of setting off on the same premise; the thread leaves that message out (only a bot message is hidden, `threadMessages`) and shows its thinking row until a newer bot message lands (`rerun_after_id` in `conversation.tsx`: the message it runs again is the last one and looks answered, and a stopped run's notice would say it stopped right above the row). A run that was stopped, or ended without a word, leaves the user's own message last with nothing on its way: the thread says so there and offers the same Run again on it (`unanswered-reply-row.tsx`; the route answers it when `rerunReplyProblem` sees it is the session's last message), instead of a thinking row that would never move (`awaits-reply.ts`, which holds the row back once the open replies are read as none). Failure notices are the app's record, never the bot's words, so `botMessagesToHarness` skips them.
|
||||
- **Debug view:** what a run did in order: each turn with what the model reasoned (`stripThinkTags`'s `reasoning`, or the provider's `reasoning`/`reasoning_content`) and answered, each tool call with the arguments it was sent and the answer it got (and its duration), and the loop's own events (`wrap_up`, `redraft`, `review`, `incoming`, `steps_low`). `runTextLoop` emits them through `Params.trace` into `bot_job_traces` (never `bots_queue_updates`, which the `clear-job-steps` cron deletes a minute after a job ends). While a run works, the thinking row's bug button, beside Stop (`BotThinkingRow`), toggles a 250px strip under it (`(partials)/trace-panel.tsx`, `(partials)/trace-log-line.tsx`: one line per step, following its newest line while scrolled to the bottom), read live through `(hooks)/use-bot-trace.ts` and `api/admin/bots/trace`; that toggle stays as the user left it in every conversation (on this device, per user: `useDebugOpen` over `readDebugOpen`/`rememberDebugOpen`, `AppData.DebugViewStorageKey`). When the run ends its logs are tied to the message it answered (`attachJobTracesToMessage`, from the job helpers) and read in that message's Details modal, under a **Debug logs** tab beside Details (`(partials)/message-debug-logs.tsx`, `(hooks)/use-message-trace.ts`, `api/admin/bots/message-trace`), which copies itself as one markdown document (`CopyDebugLogsButton` over `messageDebugLogsMarkdown`), which checks the message's session for the user or a super admin). Every entry is redacted before storage (`insertBotJobTrace` with the run's reachable envs, plus the task run's computer redaction for what the bot captured), cut to `AppData.BotTraceTextMaxChars`/`BotTraceArgumentsMaxChars`/`BotTraceResultMaxChars` (an argument's `path` survives whole, `toolArgumentPath`: a write's path is what a reader needs), at most `BotTraceRowsPerJob` entries per run and `BotTraceJobsPerSession` runs shown, kept for the app setting `bot_trace_keep_days` (default `AppData.BotTraceKeepDays`, daily `prune-bot-traces`). Pushes carry only `BotTraceData` (`job_id`, `session_id`): an open view reads the entries it doesn't have.
|
||||
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
|
||||
- **Pictures:** `image_media_id` (private media, `bot-image`/`workspace-image`), via `set-profile-image.ts`, the `set_picture` tool or `update_workspace`. Bytes are **copied**, never moved; only picture-paradigm rows are deleted on replace. Format kept by `imageOutputFormat`.
|
||||
@@ -198,7 +198,8 @@ Set in Settings > Environment (super admin), not `.env`. `envs` (private; encryp
|
||||
|
||||
- Files live on the data volume, not on computers: `DATA_DIR/bots/<id>` and `DATA_DIR/workspaces/<id>`. Catalog `bot_files`, bytes in private `media` (`bot-file`) written by `recordBotFile`. Reach via `grabStorageScopes`; paths via `resolveBotPath` (no absolute, `..`, NUL, symlink escape); quota checked by `assertStorageRoom`.
|
||||
- Tools in `src/harness/tools/storage/` (every run). `attach` puts a file on the reply. `grabConversationFiles` must list the **whole** folder tree, or nested `[file:ID]` refs render dead. A workspace run saves to the bot's own folder unless it picks the workspace's, so a chip in a workspace conversation looks up both (`api/admin/bots/files?file_id=` with `bot_id` and `workspace_id`).
|
||||
- `import_file` copies from a computer through the agent's streaming `GET /api/files/download`, **never through its shell** (a shell's output is capped and once silently truncated imports). Size read first, the agent cuts a file that changes mid-send, length checked.
|
||||
- `import_file` copies from a computer through the agent's streaming `GET /api/files/download`, **never through its shell** (a shell's output is capped and once silently truncated imports). Size read first, the agent cuts a file that changes mid-send, length checked. A chat reply has it too (`grab-bot-chat-tools`, its computers to choose from), so what a reply made on a computer comes into its files the same way a task's does.
|
||||
- `list_files` with `search` matches names and paths in **every** folder (leaving `folder` out lists every folder too): scoping a search to the root hid `images/summit-hero-pil.png` and made a bot believe its file was never saved. `write_file` refuses a binary extension, since text saved under `.png` reached the user as a file that would not open.
|
||||
- **Only knowledgebases store text.** Bot files and uploads are never indexed and keep no extracted text (`media.text_content` only for knowledgebase documents); bots find files by name or path (`list_files` `search`) and read them with `read_file`, and the Files searches match names only. Text that should be searchable goes in a knowledgebase. `dropStoredFileText` clears what older versions stored, at boot, and vacuums when much of the file is free.
|
||||
- **Foreign keys are off per connection** unless `enableForeignKeys` ran (only `src/server.ts` does). Scripts never fire `ON DELETE CASCADE`, so **any helper that deletes a parent row must delete its children explicitly** (as `deleteBotFile`, `purgeStorage`, `deleteSkill` do). A leftover child fails the next `bun run db:schema` with a foreign key violation.
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.25.1",
|
||||
"version": "0.25.2",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
botFilesNote,
|
||||
chatReplyNote,
|
||||
RerunReplyNote,
|
||||
RetryFailureNote,
|
||||
ComputerFilesNote,
|
||||
coordinatorReplyNote,
|
||||
longSessionNote,
|
||||
@@ -73,6 +74,7 @@ import hasUnansweredMessage from "./has-unanswered-message";
|
||||
import reviewRunAnswer from "./review-run-answer";
|
||||
import cancelBotJob from "@/src/functions/backend/db/bots-queue/cancel-bot-job";
|
||||
import grabAnsweredMessageId from "@/src/functions/backend/db/bots-queue/grab-answered-message-id";
|
||||
import grabRetryFailure from "@/src/functions/backend/db/bots-queue/grab-retry-failure";
|
||||
import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-answered";
|
||||
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
|
||||
import updateRequesterTool from "@/src/harness/tools/bot/update-requester-tool";
|
||||
@@ -151,6 +153,14 @@ export default async function runBotReply({
|
||||
* session's last message and nothing looks unanswered.
|
||||
*/
|
||||
const is_retry = Number(job_params.retry_of) > 0;
|
||||
/**
|
||||
* Why the attempt before this one ended without an answer
|
||||
* (`grabRetryFailure`): what it claimed to have done may be exactly
|
||||
* what it never did, so the retry is told rather than repeating it.
|
||||
*/
|
||||
const retry_failure = is_retry
|
||||
? await grabRetryFailure({ message_id: Number(job_params.retry_of) }).catch(() => null)
|
||||
: null;
|
||||
|
||||
if (!on_plan_step && !is_retry && !hasUnansweredMessage({ history, answered_id })) {
|
||||
return { result: "", silent: true };
|
||||
@@ -369,6 +379,7 @@ export default async function runBotReply({
|
||||
led = admin;
|
||||
},
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
onAttach: ({ media_id }) => attachments.push(media_id),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -465,8 +476,9 @@ export default async function runBotReply({
|
||||
long_session_note,
|
||||
chatReplyNote({ bot_id: bot.id }),
|
||||
is_retry ? RerunReplyNote : "",
|
||||
retry_failure ? RetryFailureNote({ reason: retry_failure.reason }) : "",
|
||||
botFilesNote({ bot_id: bot.id }),
|
||||
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: false }),
|
||||
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: computers.length > 0 }),
|
||||
TasksNote,
|
||||
TaskReminderNote,
|
||||
can_hand_over ? HandOverTaskNote : "",
|
||||
|
||||
@@ -182,6 +182,19 @@ export default async function runBotTask({
|
||||
try {
|
||||
const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id });
|
||||
const computers = await grabBotComputers({ bot_id: bot.id, workspace_id });
|
||||
/**
|
||||
* `import_file` reads only the computer this run works on: what it
|
||||
* made is there. The row is read again when the list no longer has
|
||||
* it, so the tool still names the job's computer.
|
||||
*/
|
||||
const job_computers = job.computer_id
|
||||
? computers.filter((row) => Number(row.id) == Number(job.computer_id))
|
||||
: [];
|
||||
const import_computers = job_computers.length
|
||||
? job_computers
|
||||
: job.computer_id
|
||||
? [{ id: job.computer_id }]
|
||||
: [];
|
||||
|
||||
/**
|
||||
* What the bot's types let it do here. A coordinator's task can
|
||||
@@ -395,7 +408,7 @@ export default async function runBotTask({
|
||||
...(job.computer_id
|
||||
? [
|
||||
importFileTool({
|
||||
computer_id: job.computer_id,
|
||||
computers: import_computers,
|
||||
scopes,
|
||||
bot_id: bot.id,
|
||||
user_id,
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
PlanActiveNote,
|
||||
PlanPausedNote,
|
||||
ScheduledPlanNote,
|
||||
RetryFailureNote,
|
||||
} from "./harness-prompts";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
|
||||
@@ -96,6 +97,26 @@ describe("harness prompts", () => {
|
||||
expect(TasksNote).not.toContain("[folder:bot:");
|
||||
expect(TasksNote).not.toContain("[bot:");
|
||||
});
|
||||
|
||||
test("a retry is told why the attempt before it failed", () => {
|
||||
const note = RetryFailureNote({ reason: "The answer didn't hold up against the app's record." });
|
||||
|
||||
expect(note).toContain("The answer didn't hold up against the app's record.");
|
||||
expect(note).toContain("list_files");
|
||||
expect(note).toContain("correct the premise first");
|
||||
});
|
||||
|
||||
test("a retry outside the few hundred characters that matter keeps the start of the failure", () => {
|
||||
const reason = `${"first".repeat(80)}${"last".repeat(10)}`;
|
||||
const note = RetryFailureNote({ reason });
|
||||
|
||||
expect(note).toContain(`first${"first".repeat(78)}`);
|
||||
expect(note).not.toContain("lastlastlastlast");
|
||||
});
|
||||
|
||||
test("a retry with no reason recorded still reads as a failure", () => {
|
||||
expect(RetryFailureNote({ reason: "" })).toContain("It ended without sending an answer.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("openRunsNote", () => {
|
||||
|
||||
@@ -116,6 +116,19 @@ The user asked for this reply again. Work from their latest messages and write i
|
||||
- If the answer did go out, write it again for what they asked, as if it were the first time. The earlier one stays in the thread, so don't repeat it word for word if you have something better to say, and don't assume they missed it.
|
||||
- Start the work now, in this reply or with send_reply status "working" and work: never answer that you'll look into it.`;
|
||||
|
||||
/**
|
||||
* Added beside `RerunReplyNote` when the attempt before this one failed:
|
||||
* `reason` is the job's `last_error` (`grabRetryFailure`), so the run knows
|
||||
* what went wrong instead of starting from the same wrong premise. Cut
|
||||
* short: the note is guidance, not the failure log.
|
||||
*/
|
||||
export const RetryFailureNote = ({ reason }: { reason: string }) => `# The attempt before this one
|
||||
|
||||
It ended without sending an answer${reason ? `: ${reason.slice(0, 400)}` : "."}
|
||||
|
||||
- Check what that attempt actually left on record before you repeat it: list_files for what it says it saved, and the computer's own folders for what it says it made there. Take its word for nothing.
|
||||
- If it set off on a premise that wasn't true (a file that wasn't saved, a script that never existed), correct the premise first: that is the reason this attempt exists.`;
|
||||
|
||||
export const botFilesNote = ({ bot_id }: { bot_id: number | string }) => `# Your files
|
||||
|
||||
You have a folder of your own, kept with the app (not on a computer), and it stays between runs and conversations.
|
||||
@@ -137,8 +150,9 @@ You have a folder of your own, kept with the app (not on a computer), and it sta
|
||||
|
||||
/**
|
||||
* Added to a run that has a computer: what it leaves there is not in its
|
||||
* files, but the user can still open it. `can_import` is false in a chat
|
||||
* reply, where the import only happens inside a task.
|
||||
* files, but the user can still open it. `can_import` is false when the run
|
||||
* has no computer to read from (a reply whose bot has none): then file work
|
||||
* on one is a task.
|
||||
*
|
||||
* A folder ref is always a folder, so a file left on the computer is named
|
||||
* by the folder that holds it, never by the file's own path.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { Database } from "bun:sqlite";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import botFilesFilter from "./bot-files-filter";
|
||||
|
||||
/**
|
||||
* `list_files` with a search looked only at the root, so a bot that had
|
||||
* just saved `images/summit-hero-pil.png` was told it had no matching file,
|
||||
* believed its own save had never happened, and sent a task hunting the
|
||||
* filesystem for it. A search now looks through every folder.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE bot_files (id INTEGER PRIMARY KEY, scope TEXT, owner_id INTEGER, folder TEXT, name TEXT, path TEXT)`);
|
||||
db.run(
|
||||
`INSERT INTO bot_files VALUES
|
||||
(1, 'bot', 20, '', 'root.md', 'root.md'),
|
||||
(2, 'bot', 20, 'images', 'summit-hero-pil.png', 'images/summit-hero-pil.png'),
|
||||
(3, 'bot', 20, 'scripts', 'render-hero.py', 'scripts/render-hero.py'),
|
||||
(4, 'bot', 20, 'reports', 'render.md', 'reports/render.md'),
|
||||
(5, 'bot', 21, 'images', 'summit-hero-pil.png', 'images/summit-hero-pil.png'),
|
||||
(6, 'workspace', 2, 'shared', 'summit-hero-pil.png', 'shared/summit-hero-pil.png')`,
|
||||
);
|
||||
|
||||
const scopes: StorageScope[] = [{ scope: "bot", owner_id: 20 }];
|
||||
|
||||
function ids({ folder, recursive, search }: { folder?: string | null; recursive?: boolean; search?: string | null }) {
|
||||
const { where, values } = botFilesFilter({ scopes, folder, recursive, search });
|
||||
|
||||
return db
|
||||
.query(`SELECT id FROM bot_files WHERE ${where.join(" AND ")} ORDER BY id`)
|
||||
.all(...values)
|
||||
.map((row) => (row as { id: number }).id);
|
||||
}
|
||||
|
||||
describe("the file listing filter", () => {
|
||||
test("a search with no folder finds a file saved in a subfolder", () => {
|
||||
expect(ids({ search: "summit-hero" })).toEqual([2]);
|
||||
});
|
||||
|
||||
test("a search across folders finds every match, wherever it is saved", () => {
|
||||
expect(ids({ search: "render" })).toEqual([3, 4]);
|
||||
});
|
||||
|
||||
test("a named empty folder is still only that folder's own files", () => {
|
||||
expect(ids({ folder: "" })).toEqual([1]);
|
||||
});
|
||||
|
||||
test("a named folder lists what it holds", () => {
|
||||
expect(ids({ folder: "images" })).toEqual([2]);
|
||||
});
|
||||
|
||||
test("a named folder searched looks through it, not the rest of the tree", () => {
|
||||
expect(ids({ folder: "images", search: "render" })).toEqual([]);
|
||||
});
|
||||
|
||||
test("a recursive folder takes everything under it", () => {
|
||||
expect(ids({ folder: "reports", recursive: true })).toEqual([4]);
|
||||
expect(ids({ folder: "bot", recursive: true })).toEqual([]);
|
||||
});
|
||||
|
||||
test("another bot's file with the same name is never in it", () => {
|
||||
expect(ids({ search: "summit-hero" })).not.toContain(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
|
||||
type Params = {
|
||||
scopes: StorageScope[];
|
||||
folder?: string | null;
|
||||
recursive?: boolean;
|
||||
search?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The WHERE clause listing a run's files: its directories, one folder (or
|
||||
* its whole tree), and a name or path match. A search with no folder looks
|
||||
* through every folder, which is what a bot means by "list_files search":
|
||||
* scoping it to the root hid `images/summit-hero-pil.png` from the bot that
|
||||
* had just written it, and the bot went on to say the file was never saved.
|
||||
*/
|
||||
export default function botFilesFilter({ scopes, folder, recursive, search }: Params) {
|
||||
const owner_sql = scopes.map(() => `(scope = ? AND owner_id = ?)`).join(" OR ");
|
||||
const where = [owner_sql];
|
||||
const values: (string | number)[] = scopes.flatMap((s) => [s.scope, s.owner_id]);
|
||||
|
||||
const target = (folder || "").trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
|
||||
|
||||
if (target) {
|
||||
where.push(recursive ? `(folder = ? OR folder LIKE ?)` : `folder = ?`);
|
||||
values.push(target);
|
||||
|
||||
if (recursive) values.push(`${target}/%`);
|
||||
} else if (typeof folder == "string" && !recursive) {
|
||||
/**
|
||||
* A folder was named (even as ""), so this is that folder's own
|
||||
* listing. No folder at all means every folder, not just the root.
|
||||
*/
|
||||
where.push(`(folder = '' OR folder IS NULL)`);
|
||||
}
|
||||
|
||||
if (search?.trim()) {
|
||||
where.push(`(name LIKE ? OR path LIKE ?)`);
|
||||
values.push(`%${search.trim()}%`, `%${search.trim()}%`);
|
||||
}
|
||||
|
||||
return { where, values };
|
||||
}
|
||||
@@ -2,17 +2,18 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_FILES } from "@/db/types/db";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import botFilesFilter from "./bot-files-filter";
|
||||
|
||||
type Params = {
|
||||
scopes: StorageScope[];
|
||||
/**
|
||||
* Only this directory's files (a folder path), or, with `recursive`,
|
||||
* everything under it.
|
||||
* Only this folder's files (a folder path), or, with `recursive`,
|
||||
* everything under it. Left out, every folder is listed.
|
||||
*/
|
||||
folder?: string | null;
|
||||
recursive?: boolean;
|
||||
/**
|
||||
* Match the name or the path, case-insensitive.
|
||||
* Match the name or the path, case-insensitive, in every folder.
|
||||
*/
|
||||
search?: string | null;
|
||||
limit?: number;
|
||||
@@ -31,32 +32,7 @@ export default async function listBotFiles({
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_FILES[]> {
|
||||
if (!scopes.length) return [];
|
||||
|
||||
const target = (folder || "").trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
|
||||
|
||||
const owner_sql = scopes.map(() => `(scope = ? AND owner_id = ?)`).join(" OR ");
|
||||
const owner_values = scopes.flatMap((s) => [s.scope, s.owner_id]);
|
||||
|
||||
const where = [owner_sql];
|
||||
const values: (string | number)[] = [...owner_values];
|
||||
|
||||
if (target) {
|
||||
where.push(
|
||||
recursive
|
||||
? `(folder = ? OR folder LIKE ?)`
|
||||
: `folder = ?`,
|
||||
);
|
||||
|
||||
values.push(target);
|
||||
|
||||
if (recursive) values.push(`${target}/%`);
|
||||
} else if (!recursive) {
|
||||
where.push(`(folder = '' OR folder IS NULL)`);
|
||||
}
|
||||
|
||||
if (search?.trim()) {
|
||||
where.push(`(name LIKE ? OR path LIKE ?)`);
|
||||
values.push(`%${search.trim()}%`, `%${search.trim()}%`);
|
||||
}
|
||||
const { where, values } = botFilesFilter({ scopes, folder, recursive, search });
|
||||
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_FILES>({
|
||||
sql: `SELECT * FROM bot_files WHERE ${where.join(" AND ")} ORDER BY updated_at DESC, id DESC LIMIT ?`,
|
||||
|
||||
@@ -6,7 +6,10 @@ import type {
|
||||
} from "@/db/types/db";
|
||||
import type { BotFilePurpose, BotFileScope, BotFileSource } from "@/src/dict/bot-file-dict";
|
||||
import type { MediaType } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import extensionOf from "@/src/utils/extension-of";
|
||||
import grabDirNames from "@/src/utils/grab-dir-names";
|
||||
import looksLikeImage from "@/src/utils/looks-like-image";
|
||||
import resolveBotPath from "@/src/utils/resolve-bot-path";
|
||||
import assertStorageRoom from "./assert-storage-room";
|
||||
import grabStorageDir from "./grab-storage-dir";
|
||||
@@ -71,6 +74,24 @@ export default async function recordBotFile({
|
||||
const existing = await grabBotFileRow({ scope, owner_id, path: resolved.relative });
|
||||
const previous_size = Number(existing?.size) || 0;
|
||||
|
||||
/**
|
||||
* What `write_file` saved as an image has to look like one: text under
|
||||
* `.png` became a 2.6 KB "image" the user could not open, while the
|
||||
* reply said a 1376x768 PNG was attached. Other writers make real bytes
|
||||
* (`generate_image`, an import, an upload), so only a bot's own write is
|
||||
* checked here.
|
||||
*/
|
||||
if (
|
||||
media_type_resolved == "image" &&
|
||||
source == "bot-write" &&
|
||||
extensionOf({ name: resolved.name }) != "svg" &&
|
||||
!looksLikeImage({ bytes })
|
||||
) {
|
||||
throw new AppError(
|
||||
`${resolved.relative} isn't an image: it was saved as text, so the user would get a file that does not open. Make it with generate_image (or transform_image), or bring it in with import_file.`,
|
||||
);
|
||||
}
|
||||
|
||||
await assertStorageRoom({
|
||||
scope,
|
||||
owner_id,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The bot message the retry runs again: a failure notice carries the
|
||||
* job that ended without an answer (`failed_job_id`).
|
||||
*/
|
||||
message_id: number | string;
|
||||
};
|
||||
|
||||
type Row = {
|
||||
failed_job_id: number | null;
|
||||
last_error: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why the run behind a message ended without sending its answer: its
|
||||
* `failed_job_id` and that job's `last_error`. A retry reads it so it
|
||||
* doesn't set off on the same wrong premise a second time (the failure
|
||||
* notices themselves are app records, left out of the history the run
|
||||
* reads).
|
||||
*/
|
||||
export default async function grabRetryFailure({ message_id }: Params): Promise<{ job_id: number; reason: string } | null> {
|
||||
const res = await BunSQLite.sql<Row>({
|
||||
sql: `SELECT m.failed_job_id, q.last_error
|
||||
FROM bot_messages m
|
||||
LEFT JOIN bots_queue q ON q.id = m.failed_job_id
|
||||
WHERE m.id = ?
|
||||
LIMIT 1`,
|
||||
values: [Number(message_id) || 0],
|
||||
});
|
||||
|
||||
const row = res.payload?.[0];
|
||||
if (!row?.failed_job_id) return null;
|
||||
|
||||
return {
|
||||
job_id: Number(row.failed_job_id),
|
||||
reason: String(row.last_error || "").trim(),
|
||||
};
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import grabCrewWorkers from "@/src/functions/backend/db/bots/grab-crew-workers";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import askToTakeOverTool from "../computer/ask-to-take-over-tool";
|
||||
import importFileTool from "../computer/import-file-tool";
|
||||
import searchComputersTool from "../computer/search-computers-tool";
|
||||
import addBotToWorkspaceTool from "./add-bot-to-workspace-tool";
|
||||
import assignComputerTool from "./assign-computer-tool";
|
||||
@@ -103,13 +104,19 @@ type Params = {
|
||||
* posts links to it (`bot_messages.task_ids`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
/**
|
||||
* Called with a file the reply sent, so the message carries it.
|
||||
*/
|
||||
onAttach?: (params: { media_id: number; name: string }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The tools a bot replies in chat with: its own (memory, instructions, and
|
||||
* in a workspace switching its default computer), send_reply for the message
|
||||
* and the longer work it queues, search_computers to find what's on its computers,
|
||||
* ask_user_to_take_over when only the user can do something on one, and
|
||||
* and the longer work it queues, search_computers to find what's on its
|
||||
* computers, import_file to keep a file one of them made (an image, a PDF,
|
||||
* an export) in its own files, ask_user_to_take_over when only the user can
|
||||
* do something on one, and
|
||||
* for the coordinator (the super admin's alone) create_workspace and
|
||||
* update_workspace (a workspace and its shared context, which
|
||||
* find_workspace reads back wherever the coordinator works), create_bot to
|
||||
@@ -129,8 +136,9 @@ type Params = {
|
||||
* workspace admin, in the workspace it leads, gets
|
||||
* `grabWorkspaceAdminTools`. A worker gets no work to hand out, but it may
|
||||
* pass on a task of its own to a bot it could ask (`hand_over_task`). Every
|
||||
* gate reads the bot's types (`powers`), never `bots.kind`. Anything else on
|
||||
* a computer goes through a task, never mid-reply.
|
||||
* gate reads the bot's types (`powers`), never `bots.kind`. Longer work on
|
||||
* a computer, and anything that changes it, still goes through a task,
|
||||
* never mid-reply.
|
||||
*/
|
||||
export default async function grabBotChatTools({
|
||||
bot,
|
||||
@@ -149,8 +157,10 @@ export default async function grabBotChatTools({
|
||||
onPropose,
|
||||
onWorkspaceAdmin,
|
||||
onTask,
|
||||
onAttach,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
const bot_id = bot.id || 0;
|
||||
const dirs = computerRunDirs({ bot_id, bot_kind: bot.kind, user_id, workspace_id });
|
||||
const tools = [
|
||||
...(await grabBotTools({
|
||||
user_id,
|
||||
@@ -182,7 +192,15 @@ export default async function grabBotChatTools({
|
||||
user_id,
|
||||
computers,
|
||||
workspace_id,
|
||||
dirs: computerRunDirs({ bot_id, bot_kind: bot.kind, user_id, workspace_id }),
|
||||
dirs,
|
||||
}),
|
||||
importFileTool({
|
||||
computers,
|
||||
scopes,
|
||||
bot_id,
|
||||
user_id,
|
||||
dirs,
|
||||
onAttach,
|
||||
}),
|
||||
askToTakeOverTool({ computers, onAsk: (params) => onTakeOver?.(params) }),
|
||||
]
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import pickImportComputer from "./import-computer";
|
||||
|
||||
/**
|
||||
* A reply now imports from a computer, and a bot may reach several: the one
|
||||
* it names wins, and one it does not have is refused rather than quietly
|
||||
* reading the first machine's folder.
|
||||
*/
|
||||
const computers = [
|
||||
{ id: 4, name: "Main" },
|
||||
{ id: 9, name: "Build" },
|
||||
];
|
||||
|
||||
describe("picking the computer to import from", () => {
|
||||
test("no computer is null", () => {
|
||||
expect(pickImportComputer({ computers: [] })).toBeNull();
|
||||
});
|
||||
|
||||
test("nothing named means the first one", () => {
|
||||
expect(pickImportComputer({ computers })?.id).toEqual(4);
|
||||
expect(pickImportComputer({ computers, wanted: " " })?.id).toEqual(4);
|
||||
});
|
||||
|
||||
test("an id picks that computer", () => {
|
||||
expect(pickImportComputer({ computers, wanted: 9 })?.id).toEqual(9);
|
||||
expect(pickImportComputer({ computers, wanted: "9" })?.id).toEqual(9);
|
||||
});
|
||||
|
||||
test("a computer ref picks it too", () => {
|
||||
expect(pickImportComputer({ computers, wanted: "computer:9" })?.id).toEqual(9);
|
||||
});
|
||||
|
||||
test("one it does not have is null, not the first one", () => {
|
||||
expect(pickImportComputer({ computers, wanted: 2 })).toBeNull();
|
||||
expect(pickImportComputer({ computers, wanted: "elsewhere" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
type ComputerLike = {
|
||||
id?: number | string | null;
|
||||
name?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Which computer an import reads from: the one the bot named (an id, or a
|
||||
* `computer:<id>` ref), else the first it has. Null when it named one it
|
||||
* does not have, so the tool says so instead of reading the wrong machine.
|
||||
*/
|
||||
export default function pickImportComputer<T extends ComputerLike>({
|
||||
computers,
|
||||
wanted,
|
||||
}: {
|
||||
computers: T[];
|
||||
wanted?: number | string | null;
|
||||
}): T | null {
|
||||
if (!computers.length) return null;
|
||||
|
||||
if (wanted === undefined || wanted === null || String(wanted).trim() == "") return computers[0] ?? null;
|
||||
|
||||
const id = Number(String(wanted).trim().replace(/^computer:/, ""));
|
||||
if (!Number.isFinite(id)) return null;
|
||||
|
||||
return computers.find((computer) => Number(computer.id) == id) ?? null;
|
||||
}
|
||||
@@ -20,12 +20,14 @@ import downloadComputerFile, { type ComputerDownload } from "@/src/functions/bac
|
||||
import runComputerCommand from "@/src/functions/backend/computers/run-computer-command";
|
||||
import shellQuote from "@/src/utils/shell-quote";
|
||||
import walkRegularFiles from "@/src/utils/walk-regular-files";
|
||||
import pickImportComputer from "./import-computer";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The computer the run is on: what it made is in its workspace.
|
||||
* The computers the run reaches (`grabBotComputers`), the current one
|
||||
* first: the import reads from the one the bot names, else this one.
|
||||
*/
|
||||
computer_id: number | string;
|
||||
computers: { id?: number | string | null; name?: string | null }[];
|
||||
/**
|
||||
* The directories the run may write to (`grabStorageScopes`): the first
|
||||
* is where an import lands.
|
||||
@@ -44,13 +46,18 @@ type Params = {
|
||||
type Args = {
|
||||
path: string;
|
||||
name?: string;
|
||||
/**
|
||||
* Which of the run's computers to read from (its id); the first one
|
||||
* when left out.
|
||||
*/
|
||||
computer?: number | string;
|
||||
attach?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Copies what a bot made on its computer into its own files: one file, or
|
||||
* a whole folder (taken as a gzipped tar and unpacked into one row per
|
||||
* file). The copies are kept with the app, stay after the computer is
|
||||
* Copies what a bot made on one of its computers into its own files: one
|
||||
* file, or a whole folder (taken as a gzipped tar and unpacked into one row
|
||||
* per file). The copies are kept with the app, stay after the computer is
|
||||
* rebuilt, and are readable at once; the originals stay on the computer,
|
||||
* where the message's folder ref points at the folder holding them.
|
||||
*
|
||||
@@ -60,7 +67,7 @@ type Args = {
|
||||
* import at 30,047 characters.
|
||||
*/
|
||||
export default function importFileTool({
|
||||
computer_id,
|
||||
computers,
|
||||
scopes,
|
||||
bot_id,
|
||||
user_id,
|
||||
@@ -69,10 +76,20 @@ export default function importFileTool({
|
||||
}: Params): HarnessTool<Args> {
|
||||
const own = scopes[0];
|
||||
const max_mb = Math.round(AppData.BotFileImportMaxBytes / (1024 * 1024));
|
||||
const first = computers[0];
|
||||
const choices = computers
|
||||
.map((computer) => `${computer.id}${computer.name ? ` (${computer.name})` : ""}`)
|
||||
.join(", ");
|
||||
|
||||
return {
|
||||
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.${
|
||||
description: `Copy a file or folder from one of your computers into your own files, so it is kept with the app and stays after the computer is rebuilt.${
|
||||
computers.length > 1
|
||||
? ` Your computers: ${choices}; "computer" picks one, the first by default.`
|
||||
: first
|
||||
? ` It reads computer ${first.id}${first.name ? ` (${first.name})` : ""}.`
|
||||
: ""
|
||||
} 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. The other direction is export_file, which puts one of your own files back on the computer.`,
|
||||
schema: z.object({
|
||||
@@ -86,11 +103,23 @@ export default function importFileTool({
|
||||
.max(AppData.BotFilePathMaxChars)
|
||||
.optional()
|
||||
.describe(`Where to save it in your files, e.g. "reports/coderank-audit.md"`),
|
||||
computer: z
|
||||
.union([z.string(), z.number()])
|
||||
.optional()
|
||||
.describe(`Which of your computers (its id); the first one when left out`),
|
||||
attach: z.boolean().optional().describe(`Also send it to the user with this reply`),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
if (!own) return `You have no files folder to import into.`;
|
||||
|
||||
const chosen = pickImportComputer({ computers, wanted: args.computer });
|
||||
|
||||
if (!chosen) {
|
||||
return computers.length
|
||||
? `That isn't one of your computers. Yours: ${choices}.`
|
||||
: `You have no computer to import from.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Workspace-relative from here on, which is what a folder ref
|
||||
* names.
|
||||
@@ -100,6 +129,7 @@ export default function importFileTool({
|
||||
|
||||
if (!source) return `Give a file or folder inside your folder, e.g. "seo/coderank/raw".`;
|
||||
|
||||
const computer_id = chosen.id || 0;
|
||||
const target = await grabComputerMcpUrl({ computer_id });
|
||||
|
||||
if (!target) return `Computer #${computer_id} has no container to copy from.`;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import binaryWriteProblem from "./binary-write-problem";
|
||||
|
||||
/**
|
||||
* A `.png` path and a truncated base64 string became a 2.6 KB "image" the
|
||||
* user could not open, while the reply said a 1376x768 PNG was attached.
|
||||
* `write_file` saves text: a binary extension is refused, with the tool that
|
||||
* makes the real file named.
|
||||
*/
|
||||
describe("writing a binary file as text", () => {
|
||||
test("an image is refused", () => {
|
||||
expect(binaryWriteProblem({ path: "images/summit-hero.png" })).toContain("binary file (.png)");
|
||||
});
|
||||
|
||||
test("the refusal names a way to make it", () => {
|
||||
const problem = binaryWriteProblem({ path: "report.pdf" }) || "";
|
||||
|
||||
expect(problem).toContain("generate_image");
|
||||
expect(problem).toContain("make_pdf");
|
||||
expect(problem).toContain("import_file");
|
||||
});
|
||||
|
||||
test("an uppercase extension is refused too", () => {
|
||||
expect(binaryWriteProblem({ path: "SCREENSHOT.PNG" })).toContain(".png");
|
||||
});
|
||||
|
||||
test("a zip, an office document and a font are refused", () => {
|
||||
for (const path of ["bundle.zip", "notes.docx", "font.woff2"]) {
|
||||
expect(binaryWriteProblem({ path })).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
test("text files pass", () => {
|
||||
for (const path of ["notes.md", "data.csv", "run.py", "page.svg", "README"]) {
|
||||
expect(binaryWriteProblem({ path })).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { BotImageFileExtensions } from "@/src/dict/bot-file-dict";
|
||||
import { extensionOf } from "@/src/functions/backend/db/bot-files/media-type-for-file";
|
||||
|
||||
/**
|
||||
* Extensions that hold bytes rather than text. `write_file` stores what the
|
||||
* model passes as it is, so a `.png` path and a truncated `base64` string
|
||||
* became a 2.6 KB "image" the user could not open, while the reply said a
|
||||
* 1376x768 PNG was attached. SVG stays out: it is text, and a bot can write
|
||||
* one by hand.
|
||||
*/
|
||||
export const BinaryWriteExtensions = [
|
||||
...BotImageFileExtensions.filter((extension) => extension != "svg"),
|
||||
"pdf",
|
||||
"doc",
|
||||
"docx",
|
||||
"xls",
|
||||
"xlsx",
|
||||
"ppt",
|
||||
"pptx",
|
||||
"zip",
|
||||
"gz",
|
||||
"tgz",
|
||||
"tar",
|
||||
"7z",
|
||||
"rar",
|
||||
"mp3",
|
||||
"wav",
|
||||
"m4a",
|
||||
"ogg",
|
||||
"flac",
|
||||
"mp4",
|
||||
"mov",
|
||||
"mkv",
|
||||
"avi",
|
||||
"webm",
|
||||
"sqlite",
|
||||
"db",
|
||||
"exe",
|
||||
"bin",
|
||||
"woff",
|
||||
"woff2",
|
||||
"ttf",
|
||||
"otf",
|
||||
];
|
||||
|
||||
/**
|
||||
* Why `write_file` refuses a path, or null when it can save it: a binary
|
||||
* extension would turn text into a file that does not open, and the tool
|
||||
* that makes the real one is one of the named ones.
|
||||
*/
|
||||
export default function binaryWriteProblem({ path }: { path: string }) {
|
||||
const extension = extensionOf({ name: path });
|
||||
|
||||
if (!extension || !BinaryWriteExtensions.includes(extension)) return null;
|
||||
|
||||
return `write_file saves text, and ${path} is a binary file (.${extension}): the text would be stored as it is, so the user would get a file that does not open. Make an image with generate_image (or transform_image), a PDF with make_pdf, a video with generate_video, or build the file on a computer and bring it in with import_file.`;
|
||||
}
|
||||
@@ -22,7 +22,7 @@ type Args = {
|
||||
export default function listFilesTool(context: StorageToolContext): HarnessTool<Args> {
|
||||
return {
|
||||
name: "list_files",
|
||||
description: `List the files you have saved, newest first: one folder's with "folder", everything with "recursive", or the ones whose name or path has "search". Each line has its path, size and [file:ID] ref (e.g. [file:12]) to read it. The answer also names the folder as a folder ref, which opens it in Files without downloading anything: a file is a [file:ID] ref, a folder is a [folder:...] ref.`,
|
||||
description: `List the files you have saved, newest first: one folder's with "folder", everything with "recursive", or the ones whose name or path has "search" (in every folder, so a file saved deep in a tree is found). Each line has its path, size and [file:ID] ref (e.g. [file:12]) to read it. The answer also names the folder as a folder ref, which opens it in Files without downloading anything: a file is a [file:ID] ref, a folder is a [folder:...] ref.`,
|
||||
schema: z.object({
|
||||
folder: z.string().max(AppData.BotFilePathMaxChars).optional(),
|
||||
search: z.string().max(120).optional(),
|
||||
@@ -34,18 +34,23 @@ export default function listFilesTool(context: StorageToolContext): HarnessTool<
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const folder = args.folder?.trim() || "";
|
||||
const search = args.search?.trim() || "";
|
||||
|
||||
const files = await listBotFiles({
|
||||
scopes: context.scopes,
|
||||
folder,
|
||||
folder: folder || undefined,
|
||||
recursive: args.recursive,
|
||||
search: args.search,
|
||||
search: search || undefined,
|
||||
});
|
||||
|
||||
if (!files.length) {
|
||||
return folder
|
||||
? `Nothing in ${folder}.`
|
||||
: `You have no files yet. Write one with write_file.`;
|
||||
if (folder) return `Nothing in ${folder}.`;
|
||||
|
||||
if (search) {
|
||||
return `Nothing matches "${search}" in your files. Try a shorter name, or list_files with no arguments to see everything.`;
|
||||
}
|
||||
|
||||
return `You have no files yet. Write one with write_file.`;
|
||||
}
|
||||
|
||||
const lines = files.map((file) => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AppData } from "@/src/data/app-data";
|
||||
import type { BotFilePurpose } from "@/src/dict/bot-file-dict";
|
||||
import recordBotFile from "@/src/functions/backend/db/bot-files/record-bot-file";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import binaryWriteProblem from "./binary-write-problem";
|
||||
import {
|
||||
describeScope,
|
||||
fileRef,
|
||||
@@ -22,7 +23,8 @@ type Args = {
|
||||
/**
|
||||
* Writes a text file (markdown, CSV, JSON, code, plain text) into one of
|
||||
* the bot's directories, making folders as needed. The file stays for
|
||||
* later runs.
|
||||
* later runs. A binary extension is refused: text saved under `.png`
|
||||
* reached the user as a file that would not open.
|
||||
*/
|
||||
export default function writeFileTool(context: StorageToolContext): HarnessTool<Args> {
|
||||
const own = context.scopes[0];
|
||||
@@ -31,7 +33,7 @@ export default function writeFileTool(context: StorageToolContext): HarnessTool<
|
||||
name: "write_file",
|
||||
description: `Save a text file for later: markdown, CSV, JSON, code or plain text. Give it a path like "reports/q3.md"; folders are made as needed. Files belong to ${
|
||||
own?.scope == "workspace" ? "the workspace you're working in" : "you"
|
||||
} and stay between runs: write a file before telling the user something is saved, and list_files (by name or path) to find one you wrote before. It is readable at once.${
|
||||
} and stay between runs: write a file before telling the user something is saved, and list_files (by name or path) to find one you wrote before. It is readable at once. It saves text only: an image comes from generate_image, a PDF from make_pdf, and a file a computer made from import_file, never from writing base64 here.${
|
||||
context.scopes.length > 1
|
||||
? ` "scope" picks a directory: ${context.scopes.map((s) => `${s.scope}:${s.owner_id}`).join(", ")}.`
|
||||
: ""
|
||||
@@ -62,6 +64,9 @@ export default function writeFileTool(context: StorageToolContext): HarnessTool<
|
||||
.join(", ")}.`;
|
||||
}
|
||||
|
||||
const binary = binaryWriteProblem({ path: args.path });
|
||||
if (binary) return binary;
|
||||
|
||||
const file = await recordBotFile({
|
||||
bot_id: context.bot_id,
|
||||
scope: named.scope,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import looksLikeImage from "./looks-like-image";
|
||||
|
||||
const bytes = (...values: number[]) => new Uint8Array(values);
|
||||
|
||||
/**
|
||||
* A real PNG, JPEG, GIF, WEBP and BMP pass; text does not. The check exists
|
||||
* because a truncated base64 string saved under `.png` was attached as a
|
||||
* 1376x768 image and the user got a file that would not open.
|
||||
*/
|
||||
describe("reading image bytes", () => {
|
||||
test("a PNG", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a JPEG", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0xff, 0xd8, 0xff, 0xe0) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a GIF", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0x47, 0x49, 0x46, 0x38, 0x39, 0x61) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a WEBP", () => {
|
||||
expect(
|
||||
looksLikeImage({
|
||||
bytes: bytes(0x52, 0x49, 0x46, 0x46, 1, 2, 3, 4, 0x57, 0x45, 0x42, 0x50),
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("a BMP", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0x42, 0x4d, 0, 0) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a RIFF that isn't WEBP is not an image", () => {
|
||||
expect(
|
||||
looksLikeImage({
|
||||
bytes: bytes(0x52, 0x49, 0x46, 0x46, 1, 2, 3, 4, 0x57, 0x41, 0x56, 0x45),
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("base64 text is not an image", () => {
|
||||
expect(looksLikeImage({ bytes: new TextEncoder().encode("iVBORw0KGgo=") })).toBe(false);
|
||||
});
|
||||
|
||||
test("nothing at all is not an image", () => {
|
||||
expect(looksLikeImage({ bytes: new Uint8Array() })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Whether bytes start like a real image, by its signature. Enough to catch
|
||||
* text saved under an image's name (a truncated base64 string once reached
|
||||
* the user as a 2.6 KB "PNG" that would not open): a real PNG, JPEG, GIF,
|
||||
* WEBP or BMP always starts with its own magic. SVG is text and is checked
|
||||
* by the caller's extension, not here.
|
||||
*/
|
||||
export default function looksLikeImage({ bytes }: { bytes: Uint8Array }) {
|
||||
const head = bytes.subarray(0, 12);
|
||||
const starts = (...expected: number[]) => expected.every((byte, index) => head[index] == byte);
|
||||
|
||||
if (starts(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return true;
|
||||
if (starts(0xff, 0xd8, 0xff)) return true;
|
||||
if (starts(0x47, 0x49, 0x46, 0x38)) return true;
|
||||
if (starts(0x42, 0x4d)) return true;
|
||||
|
||||
return starts(0x52, 0x49, 0x46, 0x46) && head[8] == 0x57 && head[9] == 0x45 && head[10] == 0x42 && head[11] == 0x50;
|
||||
}
|
||||
Reference in New Issue
Block a user