Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2df1cccc5d | ||
|
|
85c4a5cd80 | ||
|
|
44f2abf9de | ||
|
|
fb944b5185 | ||
|
|
5b268828e2 | ||
|
|
9d2dcc73d0 | ||
|
|
28f19cbbfd | ||
|
|
9f03120526 | ||
|
|
247ddd614d | ||
|
|
16362595f9 | ||
|
|
3b5391f320 | ||
|
|
cd981228d5 |
@@ -5,6 +5,7 @@ import { promisify } from "node:util";
|
||||
import { AgentConfig } from "./config";
|
||||
import commandArgv from "./command-argv";
|
||||
import log from "./log";
|
||||
import mountPointsUnder from "./mount-points";
|
||||
import type { RunUser } from "./run-user-for";
|
||||
|
||||
const run = promisify(execFile);
|
||||
@@ -149,7 +150,8 @@ function quoted({ text }: { text: string }) {
|
||||
* Chrome runs as gem, and a page a worker opened could otherwise show
|
||||
* another bot's files. Walked whole only while the folder isn't its
|
||||
* owner's yet (files from before accounts were gem's). Links inside are
|
||||
* never followed.
|
||||
* never followed, and a folder from the host machine mounted inside is
|
||||
* left exactly as it is on the host: the walk prunes every mount point.
|
||||
*/
|
||||
async function shareFolder({ dir, uid, gid }: { dir: string; uid: number; gid: number }) {
|
||||
await makeParents({ dir });
|
||||
@@ -167,10 +169,20 @@ async function shareFolder({ dir, uid, gid }: { dir: string; uid: number; gid: n
|
||||
return;
|
||||
}
|
||||
|
||||
await run("chown", ["-R", "-P", `${uid}:${gid}`, dir]);
|
||||
await run("chmod", ["-R", "u+rwX,g+rwX,o-rwx", dir]);
|
||||
await run("find", [dir, "-type", "d", "-exec", "chmod", "g+s", "{}", "+"]);
|
||||
await run("find", [dir, "-type", "d", "-exec", "setfacl", "-m", "d:u::rwX,d:g::rwX,d:o::---", "{}", "+"]).catch((error) => {
|
||||
/**
|
||||
* `-xdev` keeps to this filesystem and each mount point is pruned
|
||||
* before any action runs on it, so a host folder mounted inside is
|
||||
* never chowned or chmoded here. Its own permissions are the user's,
|
||||
* set on the host machine (Settings > Host directories checks them).
|
||||
*/
|
||||
const mounts = await mountPointsUnder({ dir });
|
||||
const skip = mounts.flatMap((mount_point) => ["-path", mount_point, "-prune", "-o"]);
|
||||
const walk = [dir, "-xdev", ...skip];
|
||||
|
||||
await run("find", [...walk, "-exec", "chown", `${uid}:${gid}`, "{}", "+"]);
|
||||
await run("find", [...walk, "-exec", "chmod", "u+rwX,g+rwX,o-rwx", "{}", "+"]);
|
||||
await run("find", [...walk, "-type", "d", "-exec", "chmod", "g+s", "{}", "+"]);
|
||||
await run("find", [...walk, "-type", "d", "-exec", "setfacl", "-m", "d:u::rwX,d:g::rwX,d:o::---", "{}", "+"]).catch((error) => {
|
||||
log({ name: "agent", message: `couldn't set default ACLs on ${dir}: ${error?.stderr || error?.message || error}` });
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
/**
|
||||
* Mount point paths inside a folder, deepest irrelevant: a host folder is
|
||||
* bind-mounted in a bot's folder (or a workspace's), and walking that
|
||||
* folder must stop at it. `find -xdev` alone isn't enough, since the mount
|
||||
* point directory itself still counts as visited and would be chowned or
|
||||
* chmoded through the bind, changing the folder on the host machine.
|
||||
*/
|
||||
export default async function mountPointsUnder({ dir }: { dir: string }) {
|
||||
const text = await readFile("/proc/self/mountinfo", "utf8").catch(() => "");
|
||||
const prefix = dir.endsWith("/") ? dir : `${dir}/`;
|
||||
|
||||
return text.split("\n").flatMap((line) => {
|
||||
const field = line.split(" ")[4];
|
||||
const mount_point = unescape({ text: field || "" });
|
||||
|
||||
if (!mount_point.startsWith(prefix)) return [];
|
||||
|
||||
return [mount_point];
|
||||
});
|
||||
}
|
||||
|
||||
const Escapes: Record<string, string> = {
|
||||
"040": " ",
|
||||
"011": "\t",
|
||||
"012": "\n",
|
||||
"134": "\\",
|
||||
};
|
||||
|
||||
/** mountinfo writes a path's spaces and friends octal-escaped. */
|
||||
function unescape({ text }: { text: string }) {
|
||||
return text.replace(/\\([0-7]{3})/g, (match, code: string) => Escapes[code] ?? match);
|
||||
}
|
||||
@@ -68,13 +68,16 @@ export async function workspaceUsage(): Promise<WorkspaceUsage> {
|
||||
|
||||
/**
|
||||
* The workspace's size and its biggest folders through `du`, or null when
|
||||
* it can't be read.
|
||||
* it can't be read. `-x` keeps to the workspace's own filesystem: a folder
|
||||
* from the host machine mounted inside is the host's data, not the
|
||||
* computer's, so it neither counts against the workspace's quota nor makes
|
||||
* `du` walk a whole disk.
|
||||
*/
|
||||
function measureWorkspace() {
|
||||
return new Promise<WorkspaceUsage | null>((resolve) => {
|
||||
execFile(
|
||||
"du",
|
||||
["-B1", "--max-depth=2", "--", AgentConfig.WorkspaceDir],
|
||||
["-B1", "-x", "--max-depth=2", "--", AgentConfig.WorkspaceDir],
|
||||
{ timeout: 30_000, maxBuffer: 16 * 1024 * 1024 },
|
||||
(error, stdout) => {
|
||||
if (error) return resolve(null);
|
||||
|
||||
+250
-2
@@ -30,6 +30,7 @@ import {
|
||||
} from "@/src/dict/bot-hook-dict";
|
||||
import { ExtensionProposalStatuses } from "@/src/dict/extension-proposal-dict";
|
||||
import { InstallRequestStatuses } from "@/src/dict/install-request-dict";
|
||||
import { HostDirectoryAccesses } from "@/src/dict/host-directory-dict";
|
||||
import {
|
||||
BotFilePurposes,
|
||||
BotFileScopes,
|
||||
@@ -479,7 +480,12 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
{
|
||||
fieldName: "hook_id",
|
||||
fieldDescription: `The hook whose runs this session holds. Such sessions (status \`hook\`) never show in the bot's conversation, rails or session lists: their results are read in the hook's thread. Not a foreign key: a run can outlast its hook. Null: an ordinary session`,
|
||||
fieldDescription: `The hook whose runs this session holds. Not a foreign key: a run can outlast its hook. Null: a session no hook owns`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "routine_id",
|
||||
fieldDescription: `The routine (\`cron_jobs\`) whose runs this session holds. Not a foreign key: its runs outlast the routine. Null: a session no routine owns`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
@@ -506,6 +512,14 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
indexName: "idx_bot_sessions_ask_id",
|
||||
indexTableFields: ["ask_id"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_sessions_hook_id",
|
||||
indexTableFields: ["hook_id"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_sessions_routine_id",
|
||||
indexTableFields: ["routine_id"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_sessions_bot_id_workspace_id",
|
||||
indexTableFields: ["bot_id", "workspace_id", "status"],
|
||||
@@ -1476,9 +1490,15 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
{
|
||||
fieldName: "session_id",
|
||||
fieldDescription: `No longer used: runs land in the hook's own hidden session (\`bot_sessions.hook_id\`)`,
|
||||
fieldDescription: `No longer used: runs land in the hook's own session (\`bot_sessions.hook_id\`)`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "silent",
|
||||
fieldDescription: `0: its runs take over the conversation, landing in a session the user sees and can chat in. 1: they stay in the hook's own thread, pushed nowhere. Null only until the first start after this setting existed, which makes every existing hook silent`,
|
||||
dataType: "INTEGER",
|
||||
options: [0, 1],
|
||||
},
|
||||
{
|
||||
fieldName: "title",
|
||||
dataType: "TEXT",
|
||||
@@ -2852,6 +2872,234 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "host_directories",
|
||||
tableDescription: `A folder on the host machine (Settings > Host directories) that computers' bots work in, mounted into each computer it is linked to`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "name",
|
||||
fieldDescription: `What the user calls it; the folder's name in a computer is made from it`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "source",
|
||||
fieldDescription: `Its absolute path on the host machine, as the docker daemon sees it`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "slug",
|
||||
fieldDescription: `The name it is mounted under in a computer: hosts/<slug> in a bot's folder, <slug> in a workspace's folder`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "created_by",
|
||||
fieldDescription: `The super admin who added it (not a foreign key: users are kept)`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
],
|
||||
uniqueConstraints: [
|
||||
{
|
||||
alias: "one_host_directory_per_slug",
|
||||
constraintName: "A host directory's folder name is used once",
|
||||
constraintTableFields: [{ value: "slug" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "host_directory_computers",
|
||||
tableDescription: `A host directory mounted into a computer for every bot that reaches it, at hosts/<slug> in the bot's own folder`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "host_directory_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "host_directories",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "host_directory_computer_host_directory_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "computer_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "computers",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "host_directory_computer_computer_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "access",
|
||||
fieldDescription: `Read and write, or read only: the same folder is mounted the same way for every bot`,
|
||||
dataType: "TEXT",
|
||||
options: HostDirectoryAccesses.map((hda) => hda.value),
|
||||
defaultValue: "read-write",
|
||||
},
|
||||
{
|
||||
fieldName: "gate_deletes",
|
||||
fieldDescription: `Ask the user before a command deletes or moves out anything in the folder: deleting on a host machine can't be undone`,
|
||||
dataType: "INTEGER",
|
||||
options: [0, 1],
|
||||
defaultValue: 1,
|
||||
},
|
||||
],
|
||||
uniqueConstraints: [
|
||||
{
|
||||
alias: "one_computer_link_per_host_directory",
|
||||
constraintName: "A host directory is linked to a computer once",
|
||||
constraintTableFields: [{ value: "host_directory_id" }, { value: "computer_id" }],
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_host_directory_computers_computer_id",
|
||||
indexTableFields: ["computer_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "host_directory_workspaces",
|
||||
tableDescription: `A host directory mounted into every computer a workspace is on, at <slug> in the workspace's shared folder, for every bot working there`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "host_directory_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "host_directories",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "host_directory_workspace_host_directory_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "workspace_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "workspaces",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "host_directory_workspace_workspace_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "access",
|
||||
dataType: "TEXT",
|
||||
options: HostDirectoryAccesses.map((hda) => hda.value),
|
||||
defaultValue: "read-write",
|
||||
},
|
||||
{
|
||||
fieldName: "gate_deletes",
|
||||
fieldDescription: `Ask the user before a command deletes or moves out anything in the folder: deleting on a host machine can't be undone`,
|
||||
dataType: "INTEGER",
|
||||
options: [0, 1],
|
||||
defaultValue: 1,
|
||||
},
|
||||
],
|
||||
uniqueConstraints: [
|
||||
{
|
||||
alias: "one_workspace_link_per_host_directory",
|
||||
constraintName: "A host directory is linked to a workspace once",
|
||||
constraintTableFields: [{ value: "host_directory_id" }, { value: "workspace_id" }],
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_host_directory_workspaces_workspace_id",
|
||||
indexTableFields: ["workspace_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "host_directory_checks",
|
||||
tableDescription: `What a host directory's last check found on one computer: whether the folder is there, and whether each of that computer's bot accounts can read and write in it`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "host_directory_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "host_directories",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "host_directory_check_host_directory_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "computer_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "computers",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "host_directory_check_computer_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "last_check",
|
||||
fieldDescription: `What the check found, per account (JSON: src/types HostDirectoryCheck)`,
|
||||
dataType: "TEXT",
|
||||
json: true,
|
||||
},
|
||||
{
|
||||
fieldName: "checked_at",
|
||||
fieldDescription: `When the check ran, in milliseconds`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
],
|
||||
uniqueConstraints: [
|
||||
{
|
||||
alias: "one_check_per_host_directory_computer",
|
||||
constraintName: "A host directory is checked once per computer",
|
||||
constraintTableFields: [{ value: "host_directory_id" }, { value: "computer_id" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "host_directory_grants",
|
||||
tableDescription: `The bot accounts a host directory's folder was given access for (ACL entries, applied by Cobble when it is mounted, so every bot that sees it can read and write)`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "host_directory_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "host_directories",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "host_directory_grant_host_directory_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "uids",
|
||||
fieldDescription: `The accounts it was granted to, by uid (JSON array)`,
|
||||
dataType: "TEXT",
|
||||
json: true,
|
||||
},
|
||||
{
|
||||
fieldName: "granted_at",
|
||||
fieldDescription: `When access was last given, in milliseconds`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "error",
|
||||
fieldDescription: `Why giving access failed, when it did (the folder's own permissions are then the user's to set)`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
],
|
||||
uniqueConstraints: [
|
||||
{
|
||||
alias: "one_grant_per_host_directory",
|
||||
constraintName: "A host directory's access is granted once",
|
||||
constraintTableFields: [{ value: "host_directory_id" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "harness_providers",
|
||||
fields: [
|
||||
|
||||
+147
-3
@@ -43,6 +43,11 @@ export const BunSQLiteTables = [
|
||||
"computers",
|
||||
"bot_computers",
|
||||
"workspace_computers",
|
||||
"host_directories",
|
||||
"host_directory_computers",
|
||||
"host_directory_workspaces",
|
||||
"host_directory_checks",
|
||||
"host_directory_grants",
|
||||
"harness_providers",
|
||||
"harness_models",
|
||||
"harness_settings",
|
||||
@@ -366,9 +371,13 @@ export type BUN_SQLITE_COBBLE_BOT_SESSIONS = {
|
||||
*/
|
||||
ask_id?: number | "";
|
||||
/**
|
||||
* The hook whose runs this session holds. Such sessions (status `hook`) never show in the bot's conversation, rails or session lists: their results are read in the hook's thread. Not a foreign key: a run can outlast its hook. Null: an ordinary session
|
||||
* The hook whose runs this session holds. Not a foreign key: a run can outlast its hook. Null: a session no hook owns
|
||||
*/
|
||||
hook_id?: number | "";
|
||||
/**
|
||||
* The routine (`cron_jobs`) whose runs this session holds. Not a foreign key: its runs outlast the routine. Null: a session no routine owns
|
||||
*/
|
||||
routine_id?: number | "";
|
||||
/**
|
||||
* One active session per conversation; `ask` for a bot's part of a crew request, `hook` for a hook's runs
|
||||
*/
|
||||
@@ -927,9 +936,13 @@ export type BUN_SQLITE_COBBLE_BOT_HOOKS = {
|
||||
*/
|
||||
workspace_id?: number | "";
|
||||
/**
|
||||
* No longer used: runs land in the hook's own hidden session (`bot_sessions.hook_id`)
|
||||
* No longer used: runs land in the hook's own session (`bot_sessions.hook_id`)
|
||||
*/
|
||||
session_id?: number | "";
|
||||
/**
|
||||
* 0: its runs take over the conversation, landing in a session the user sees and can chat in. 1: they stay in the hook's own thread, pushed nowhere. Null only until the first start after this setting existed, which makes every existing hook silent
|
||||
*/
|
||||
silent?: 0 | 1 | "";
|
||||
title?: string;
|
||||
/**
|
||||
* The brief each run gets (markdown); the call's payload is added below it as data
|
||||
@@ -1762,6 +1775,137 @@ export type BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS = {
|
||||
computer_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_HOST_DIRECTORIES = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
/**
|
||||
* What the user calls it; the folder's name in a computer is made from it
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
* Its absolute path on the host machine, as the docker daemon sees it
|
||||
*/
|
||||
source?: string;
|
||||
/**
|
||||
* The name it is mounted under in a computer: hosts/<slug> in a bot's folder, <slug> in a workspace's folder
|
||||
*/
|
||||
slug?: string;
|
||||
/**
|
||||
* The super admin who added it (not a foreign key: users are kept)
|
||||
*/
|
||||
created_by?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
host_directory_id?: number | "";
|
||||
computer_id?: number | "";
|
||||
/**
|
||||
* Read and write, or read only: the same folder is mounted the same way for every bot
|
||||
*/
|
||||
access?: "read-write" | "read-only" | "";
|
||||
/**
|
||||
* Ask the user before a command deletes or moves out anything in the folder: deleting on a host machine can't be undone
|
||||
*/
|
||||
gate_deletes?: 0 | 1 | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
host_directory_id?: number | "";
|
||||
workspace_id?: number | "";
|
||||
access?: "read-write" | "read-only" | "";
|
||||
/**
|
||||
* Ask the user before a command deletes or moves out anything in the folder: deleting on a host machine can't be undone
|
||||
*/
|
||||
gate_deletes?: 0 | 1 | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
host_directory_id?: number | "";
|
||||
computer_id?: number | "";
|
||||
/**
|
||||
* What the check found, per account (JSON: src/types HostDirectoryCheck)
|
||||
*/
|
||||
last_check?: string;
|
||||
/**
|
||||
* When the check ran, in milliseconds
|
||||
*/
|
||||
checked_at?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_HOST_DIRECTORY_GRANTS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
host_directory_id?: number | "";
|
||||
/**
|
||||
* The accounts it was granted to, by uid (JSON array)
|
||||
*/
|
||||
uids?: string;
|
||||
/**
|
||||
* When access was last given, in milliseconds
|
||||
*/
|
||||
granted_at?: number | "";
|
||||
/**
|
||||
* Why giving access failed, when it did (the folder's own permissions are then the user's to set)
|
||||
*/
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_HARNESS_PROVIDERS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
@@ -2998,4 +3142,4 @@ export type BUN_SQLITE_COBBLE_APP_SETTINGS = {
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_BOT_ASKS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_BOT_JOB_TRACES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_PLANS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
|
||||
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_BOT_ASKS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_BOT_JOB_TRACES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_PLANS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HOST_DIRECTORIES & BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS & BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS & BUN_SQLITE_COBBLE_HOST_DIRECTORY_GRANTS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.24.0",
|
||||
"version": "0.24.3",
|
||||
"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");
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import withTimeout from "@/src/utils/with-timeout";
|
||||
import HarnessError from "@/src/harness/harness-error";
|
||||
import deferBotJob from "@/src/functions/backend/db/bots-queue/defer-bot-job";
|
||||
import recordBotHookFailure from "@/src/functions/backend/db/bot-hooks/record-bot-hook-failure";
|
||||
import grabSessionHookId from "@/src/functions/backend/db/bot-hooks/grab-session-hook-id";
|
||||
import isUnattendedHookSession from "@/src/functions/backend/db/bot-hooks/is-unattended-hook-session";
|
||||
import recordCronJobFailure from "@/src/functions/backend/db/cron-jobs/record-cron-job-failure";
|
||||
import scheduledRunRetryAt from "@/src/utils/scheduled-run-retry-at";
|
||||
import {
|
||||
@@ -101,14 +101,16 @@ export default async function processBotJob({
|
||||
const user_id = await grabJobUserId({ job }).catch(() => null);
|
||||
|
||||
/**
|
||||
* A crew request's session and a hook's run are hidden: neither is
|
||||
* ever named. A hook's run changes no face (nobody follows it); a
|
||||
* request's does, so the bot it was passed to shows its work.
|
||||
* A crew request's session is hidden and is never named. A silent
|
||||
* hook's thread is followed by nobody either: its runs change no face
|
||||
* (a hook that isn't silent takes the conversation over, so its runs
|
||||
* show like any other); a request's does, so the bot it was passed to
|
||||
* shows its work.
|
||||
*/
|
||||
const in_ask = Boolean(
|
||||
await grabSessionAskId({ session_id: Number(job.session_id) }).catch(() => null),
|
||||
);
|
||||
const in_hook = Boolean(await grabSessionHookId({ session_id: job.session_id }).catch(() => null));
|
||||
const unattended = await isUnattendedHookSession({ session_id: job.session_id }).catch(() => false);
|
||||
|
||||
if (controller.signal.aborted) {
|
||||
unregisterJobAbort({ job_id });
|
||||
@@ -132,7 +134,7 @@ export default async function processBotJob({
|
||||
* leave a bot that shows work with nothing behind it.
|
||||
*/
|
||||
const setFace = async (face: Omit<Parameters<typeof setBotFace>[0], "bot_id" | "user_id">) => {
|
||||
if (!user_id || in_hook || controller.signal.aborted) return;
|
||||
if (!user_id || unattended || controller.signal.aborted) return;
|
||||
|
||||
await pushBotNotice({ bot_id, bot: await setBotFace({ bot_id, user_id, ...face }) });
|
||||
};
|
||||
@@ -346,7 +348,7 @@ export default async function processBotJob({
|
||||
* job to name. Tasks name too: a session the coordinator's
|
||||
* delegation or a routine opened has no reply to name it.
|
||||
*/
|
||||
if (!in_ask && !in_hook && completion.message?.session_id) {
|
||||
if (!in_ask && completion.message?.session_id) {
|
||||
/**
|
||||
* The message's session, not the job's as it was claimed: a
|
||||
* reply that moved the conversation on answered in the new one.
|
||||
|
||||
@@ -7,7 +7,7 @@ import pushBotUpdated from "./push-bot-updated";
|
||||
import pushToSessionUser from "./push-to-session-user";
|
||||
import withSessionMessageTasks from "./with-session-message-tasks";
|
||||
import grabSessionAskId from "@/src/functions/backend/db/bot-sessions/grab-session-ask-id";
|
||||
import grabSessionHookId from "@/src/functions/backend/db/bot-hooks/grab-session-hook-id";
|
||||
import isUnattendedHookSession from "@/src/functions/backend/db/bot-hooks/is-unattended-hook-session";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
@@ -33,9 +33,10 @@ type Params = {
|
||||
* Pushes a new bot message to the open tabs of the user whose
|
||||
* conversation it's in, and a face change to the user it's for
|
||||
* (`pushBotUpdated`). A relayed report goes to the conversation it was
|
||||
* posted in. A message in a hidden session (a crew request's, a hook's) is
|
||||
* pushed nowhere: those are read in their own place. Best effort: a push
|
||||
* that fails is logged and never fails the job that made the change.
|
||||
* posted in. A message in a hidden session (a crew request's, or a silent
|
||||
* hook's thread) is pushed nowhere: those are read in their own place.
|
||||
* Best effort: a push that fails is logged and never fails the job that
|
||||
* made the change.
|
||||
*/
|
||||
export default async function pushBotNotice({ bot_id, message, bot, relay, quiet_push }: Params) {
|
||||
try {
|
||||
@@ -52,14 +53,14 @@ export default async function pushBotNotice({ bot_id, message, bot, relay, quiet
|
||||
async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
|
||||
/**
|
||||
* A message in a hidden session goes to no conversation and no
|
||||
* notification: a hook run's result is read in the hook's thread
|
||||
* (which reloads from `server:hook-call-updated`), and a crew request's
|
||||
* is read by the bots working it.
|
||||
* notification: a silent hook's result is read in its thread (which
|
||||
* reloads from `server:hook-call-updated`), and a crew request's is
|
||||
* read by the bots working it.
|
||||
*/
|
||||
const hidden =
|
||||
message &&
|
||||
(Boolean(await grabSessionAskId({ session_id: Number(message.session_id) })) ||
|
||||
Boolean(await grabSessionHookId({ session_id: message.session_id })));
|
||||
(await isUnattendedHookSession({ session_id: message.session_id })));
|
||||
|
||||
if (message && !hidden) {
|
||||
await pushToSessionUser({
|
||||
|
||||
@@ -256,7 +256,7 @@ export default async function runBotReply({
|
||||
const has_past_sessions = Boolean(
|
||||
(
|
||||
await BunSQLite.sql({
|
||||
sql: `SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND id != ? AND ask_id IS NULL AND hook_id IS NULL LIMIT 1`,
|
||||
sql: `SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND id != ? AND ask_id IS NULL LIMIT 1`,
|
||||
values: [user_id, bot.id!, workspace_id ? Number(workspace_id) : null, session_id],
|
||||
})
|
||||
).payload?.[0],
|
||||
|
||||
@@ -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,18 @@ 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 });
|
||||
|
||||
/**
|
||||
* The conversation the run answers in: read before its tools open, so a
|
||||
* delete inside a host folder can ask its user there.
|
||||
*/
|
||||
const session_id = await jobSessionId({ job });
|
||||
|
||||
const computer = job.computer_id
|
||||
? await openComputerTools({
|
||||
@@ -142,7 +160,9 @@ export default async function runBotTask({
|
||||
bot_id: bot.id,
|
||||
user_id,
|
||||
workspace_id,
|
||||
session_id,
|
||||
dirs,
|
||||
scopes,
|
||||
onSecretRef: ({ ref }) => shown.push(ref),
|
||||
signal,
|
||||
})
|
||||
@@ -153,7 +173,6 @@ export default async function runBotTask({
|
||||
let skills: OpenBotSkills | undefined;
|
||||
|
||||
try {
|
||||
const session_id = await jobSessionId({ job });
|
||||
const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id });
|
||||
const computers = await grabBotComputers({ bot_id: bot.id, workspace_id });
|
||||
|
||||
@@ -214,12 +233,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 +486,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 +507,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 +546,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}`;
|
||||
}
|
||||
@@ -20,14 +20,19 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* One session in the sessions modal: its title, the summary or last
|
||||
* message, how long and how recent. The one on screen is
|
||||
* Current (greyed out); any other opens on click (reopening a closed one,
|
||||
* going back to the active one).
|
||||
* One session in the sessions modal: its title (tagged Routine or Hook
|
||||
* when one owns it), the summary or last message, how long and how
|
||||
* recent. The one on screen is Current (greyed out); any other opens on
|
||||
* click (reopening a closed one, going back to the active one).
|
||||
*/
|
||||
export default function BotSessionRow({ session, loading, disabled, onOpen, current }: Props) {
|
||||
const preview = session.summary || session.last_message_text || "";
|
||||
const at = session.last_activity_at || session.created_at;
|
||||
const tag = session.routine_title
|
||||
? { title: `A routine's thread: ${session.routine_title}`, label: "Routine" }
|
||||
: session.hook_title
|
||||
? { title: `A hook's thread: ${session.hook_title}`, label: "Hook" }
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Button
|
||||
@@ -60,6 +65,14 @@ export default function BotSessionRow({ session, loading, disabled, onOpen, curr
|
||||
>
|
||||
{session.title || "Untitled session"}
|
||||
</Span>
|
||||
{tag ? (
|
||||
<Span
|
||||
title={tag.title}
|
||||
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
|
||||
>
|
||||
{tag.label}
|
||||
</Span>
|
||||
) : null}
|
||||
{session.unread && !current ? (
|
||||
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
|
||||
) : null}
|
||||
|
||||
@@ -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}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import type { BotHookWithNames } from "@/src/types";
|
||||
import conversationHref from "@/src/utils/conversation-href";
|
||||
import relativeTime from "@/src/utils/relative-time";
|
||||
import HookCallText from "./hook-call-text";
|
||||
import HookCalls from "./hook-calls";
|
||||
@@ -19,13 +21,20 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* A hook opened from a list in a modal of its own: what it is, and its
|
||||
* thread, every call with what its run answered. Results only ever show
|
||||
* here, never in a chat.
|
||||
* A hook opened from a list in a modal of its own: what it is, then its
|
||||
* every call with what its run answered, and the way to its thread (the
|
||||
* session its runs leave their messages in, chatted in like any other).
|
||||
*/
|
||||
export default function HookDetailModal({ hook, onClose, onEdit }: Props) {
|
||||
const runs = Number(hook?.run_count || 0);
|
||||
const watching = hook?.source == "browser_notifications";
|
||||
const thread_url = hook?.latest_session_id
|
||||
? conversationHref({
|
||||
bot_id: hook.bot_id!,
|
||||
workspace_id: hook.workspace_id,
|
||||
session_id: hook.latest_session_id,
|
||||
})
|
||||
: null;
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
@@ -46,7 +55,22 @@ export default function HookDetailModal({ hook, onClose, onEdit }: Props) {
|
||||
? "Its URL, signed calls only"
|
||||
: "Its URL"}
|
||||
</TaskFactRow>
|
||||
<TaskFactRow label="State">{hook.enabled ? "On" : "Paused"}</TaskFactRow>
|
||||
<TaskFactRow label="State">
|
||||
{hook.enabled ? (hook.silent ? "On, silent" : "On") : "Paused"}
|
||||
</TaskFactRow>
|
||||
<TaskFactRow label="Thread">
|
||||
{thread_url ? (
|
||||
<Link
|
||||
href={thread_url}
|
||||
title="Open the session its latest call left its messages in"
|
||||
className="text-ink underline underline-offset-2"
|
||||
>
|
||||
Its latest session
|
||||
</Link>
|
||||
) : (
|
||||
"No run yet"
|
||||
)}
|
||||
</TaskFactRow>
|
||||
<TaskFactRow label="Runs">{runs}</TaskFactRow>
|
||||
<TaskFactRow label="Last called">
|
||||
{hook.last_called_at ? relativeTime({ at: Number(hook.last_called_at) }) : "Never"}
|
||||
|
||||
@@ -54,7 +54,8 @@ type Props = {
|
||||
* its workspaces), what calls it (its URL, or a computer's browser
|
||||
* notifications, chosen once when it's made), and then either whether its
|
||||
* calls must be signed (the secret, the header it comes in and how it's
|
||||
* written) or which notifications it takes. Makes a hook or edits one; a
|
||||
* written) or which notifications it takes, and whether its runs take
|
||||
* over the conversation or stay in the hook's own thread. Makes a hook or edits one; a
|
||||
* saved secret is never shown again, so leaving it blank keeps it.
|
||||
*/
|
||||
export default function HookForm({
|
||||
@@ -77,6 +78,7 @@ export default function HookForm({
|
||||
const [title, setTitle] = useState(hook?.title || "");
|
||||
const [instructions, setInstructions] = useState(hook?.instructions || "");
|
||||
const [signed, setSigned] = useState(Boolean(hook?.has_signing_secret));
|
||||
const [silent, setSilent] = useState(Boolean(hook?.silent));
|
||||
const [secret, setSecret] = useState("");
|
||||
const [header, setHeader] = useState(
|
||||
hook?.signature_header || "X-Hub-Signature-256",
|
||||
@@ -121,6 +123,7 @@ export default function HookForm({
|
||||
title,
|
||||
instructions,
|
||||
workspace_id: place.workspace_id,
|
||||
silent,
|
||||
...signing,
|
||||
...(watching ? { watch_filter } : {}),
|
||||
},
|
||||
@@ -132,6 +135,7 @@ export default function HookForm({
|
||||
workspace_id: place.workspace_id,
|
||||
title,
|
||||
instructions,
|
||||
silent,
|
||||
source,
|
||||
...signing,
|
||||
...(watching ? { watch_computer_id, watch_filter } : {}),
|
||||
@@ -231,6 +235,13 @@ export default function HookForm({
|
||||
onChange={(e) => setWatchFilter(e.target.value)}
|
||||
/>
|
||||
) : null}
|
||||
<Checkbox
|
||||
title="Run silently"
|
||||
label="Keep its runs in the hook's own thread: they never take over the conversation or notify me. Read them from the hook, or in the bot's sessions."
|
||||
checked={silent}
|
||||
changeHandler={setSilent}
|
||||
labelProps={{ className: "w-full" }}
|
||||
/>
|
||||
{watching ? null : (
|
||||
<>
|
||||
<Checkbox
|
||||
|
||||
@@ -26,8 +26,9 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* One hook: its bot's avatar, its name (Paused when it is), which opens
|
||||
* it, what calls it, how often it ran and when it was last called, then Pause or Resume,
|
||||
* One hook: its bot's avatar, its name (Paused, Silent when it is silent
|
||||
* about its runs), which opens it, what calls it, how often it ran and
|
||||
* when it was last called, then Pause or Resume,
|
||||
* Edit, Calls, New URL (not for notification hooks: their URL is never
|
||||
* shown) and Delete.
|
||||
*/
|
||||
@@ -45,7 +46,7 @@ export default function HookRow({ hook, busy, onOpen, onToggle, onEdit, onCalls,
|
||||
}
|
||||
title={title}
|
||||
onOpen={onOpen}
|
||||
badge={hook.enabled ? undefined : "Paused"}
|
||||
badge={hook.enabled ? (hook.silent ? "Silent" : undefined) : "Paused"}
|
||||
subtitle={hookSubtitle({ hook, show_bot: !compact, show_workspace: !compact })}
|
||||
>
|
||||
<SettingsRowAction
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { CronJobWithNames } from "@/src/types";
|
||||
import SettingsListRow from "@/src/pages/admin/settings/(partials)/settings-list-row";
|
||||
import SettingsRowAction from "@/src/pages/admin/settings/(partials)/settings-row-action";
|
||||
import routineSubtitle from "@/src/utils/routine-subtitle";
|
||||
import conversationHref from "@/src/utils/conversation-href";
|
||||
import BotAvatar from "./bot-avatar";
|
||||
|
||||
type Props = {
|
||||
@@ -25,15 +26,23 @@ type Props = {
|
||||
|
||||
/**
|
||||
* One routine: its bot's avatar, its name (Paused or Done when it is),
|
||||
* whose it is and when it runs, then Chat, Pause or Resume, Edit, Hand
|
||||
* over, Delete.
|
||||
* whose it is and when it runs, then Thread (the session its latest run
|
||||
* left its messages in), Chat, Pause or Resume, Edit, Hand over, Delete.
|
||||
*/
|
||||
export default function RoutineRow({ cron_job, busy, onToggle, onEdit, onDelete, onHandOver, compact }: Props) {
|
||||
const title = cron_job.title || `Routine ${cron_job.id}`;
|
||||
const done = Boolean(cron_job.max_runs && Number(cron_job.run_count || 0) >= cron_job.max_runs);
|
||||
const chat_url = cron_job.workspace_id
|
||||
? `/admin/workspaces/${cron_job.workspace_id}/bots/${cron_job.bot_id}`
|
||||
: `/admin/bots/${cron_job.bot_id}`;
|
||||
const chat_url = conversationHref({
|
||||
bot_id: cron_job.bot_id!,
|
||||
workspace_id: cron_job.workspace_id,
|
||||
});
|
||||
const thread_url = cron_job.latest_session_id
|
||||
? conversationHref({
|
||||
bot_id: cron_job.bot_id!,
|
||||
workspace_id: cron_job.workspace_id,
|
||||
session_id: cron_job.latest_session_id,
|
||||
})
|
||||
: null;
|
||||
|
||||
return (
|
||||
<SettingsListRow
|
||||
@@ -52,6 +61,13 @@ export default function RoutineRow({ cron_job, busy, onToggle, onEdit, onDelete,
|
||||
show_workspace: !compact,
|
||||
})}
|
||||
>
|
||||
{thread_url ? (
|
||||
<SettingsRowAction
|
||||
title={`Open ${title}'s latest thread: what its runs left there, where you can chat with ${cron_job.bot_name || "the bot"}`}
|
||||
label="Thread"
|
||||
href={thread_url}
|
||||
/>
|
||||
) : null}
|
||||
{compact ? null : (
|
||||
<SettingsRowAction title={`Chat with ${cron_job.bot_name || "the bot"}`} label="Chat" href={chat_url} />
|
||||
)}
|
||||
|
||||
@@ -1,36 +1,17 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import deleteHookSessionRows from "@/src/functions/backend/db/bot-hooks/delete-hook-session-rows";
|
||||
import detachHookSessions from "@/src/functions/backend/db/bot-hooks/detach-hook-sessions";
|
||||
import { grabHookEventsKeepDays } from "@/src/functions/backend/db/app-settings/grab-hook-events-keep-days";
|
||||
import deleteUnlinkedAttachmentMedia from "@/src/functions/backend/db/media/delete-unlinked-attachment-media";
|
||||
|
||||
/**
|
||||
* Deletes hook calls (with their responses) older than the install's
|
||||
* retention (`grabHookEventsKeepDays`), the messages their runs left in
|
||||
* hooks' hidden sessions, and the sessions of hooks that are gone. Messages
|
||||
* a call posted into a chat before hooks had their own thread stay.
|
||||
* Deletes hook calls older than the install's retention
|
||||
* (`grabHookEventsKeepDays`) and lets go of the sessions of hooks that are
|
||||
* gone. The messages those calls left in a hook's thread stay: it's the
|
||||
* user's own session now, read and chatted in like any other.
|
||||
*/
|
||||
export default async function pruneBotHookEvents() {
|
||||
const cutoff = Date.now() - (await grabHookEventsKeepDays()) * 24 * 60 * 60 * 1000;
|
||||
const messages = `SELECT m.id FROM bot_messages m JOIN bot_sessions s ON s.id = m.session_id
|
||||
WHERE s.hook_id IS NOT NULL AND m.id IN (SELECT response_message_id FROM bot_hook_events WHERE created_at < ?)`;
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_message_reactions WHERE message_id IN (${messages})`, values: [cutoff] });
|
||||
|
||||
/**
|
||||
* The call's uploads go with its messages: their `media` row is what
|
||||
* the deleted link was the only way to reach.
|
||||
*/
|
||||
const uploads = await BunSQLite.sql<{ media_id: number }>({
|
||||
sql: `SELECT media_id FROM bot_message_media WHERE message_id IN (${messages})`,
|
||||
values: [cutoff],
|
||||
});
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_message_media WHERE message_id IN (${messages})`, values: [cutoff] });
|
||||
|
||||
await deleteUnlinkedAttachmentMedia({ media_ids: (uploads.payload || []).map((row) => Number(row.media_id)) }).catch(() => []);
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_messages WHERE id IN (${messages})`, values: [cutoff] });
|
||||
|
||||
await deleteHookSessionRows({});
|
||||
await detachHookSessions({});
|
||||
|
||||
return await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_hook_events WHERE created_at < ? RETURNING id`,
|
||||
|
||||
@@ -8,6 +8,9 @@ import provisionComputer from "@/src/functions/backend/db/computers/provision-co
|
||||
import refreshComputerContainer from "@/src/functions/backend/db/computers/refresh-computer-container";
|
||||
import reviveFailedComputer from "@/src/functions/backend/db/computers/revive-failed-computer";
|
||||
import syncComputerBrowserPolicy from "@/src/functions/backend/db/computers/sync-computer-browser-policy";
|
||||
import applyHostDirectoryGrant from "@/src/functions/backend/db/host-directories/apply-host-directory-grant";
|
||||
import grabComputerHostDirectoryIds from "@/src/functions/backend/db/host-directories/grab-computer-host-directory-ids";
|
||||
import reconcileComputerHostDirectories from "@/src/functions/backend/db/host-directories/reconcile-computer-host-directories";
|
||||
|
||||
type Row = Pick<
|
||||
BUN_SQLITE_COBBLE_CONTAINERS,
|
||||
@@ -20,7 +23,9 @@ type Row = Pick<
|
||||
* still being set up are left alone, and failed ones unless docker runs
|
||||
* them anyway (`reviveFailedComputer`). A container that
|
||||
* still mounts its computer's whole home is recreated with only the
|
||||
* workspace (`migrateComputerLayout`, once per computer). A running one
|
||||
* workspace (`migrateComputerLayout`, once per computer). A computer whose host
|
||||
* directories changed since it was set up is set up again
|
||||
* (`reconcileComputerHostDirectories`). A running one
|
||||
* gets the browser policy it lacks (`syncComputerBrowserPolicy`), so
|
||||
* computers made before an extension was added get it too. A setup the app
|
||||
* lost mid-way (still `creating`, untouched for
|
||||
@@ -49,6 +54,29 @@ export default async function syncComputers() {
|
||||
|
||||
if (await migrateComputerLayout({ computer_id, metadata })) continue;
|
||||
|
||||
/**
|
||||
* A mount only exists from a container's creation, so a computer
|
||||
* whose host directories were linked, unlinked or read only since
|
||||
* is set up again (unless a job works on it right now).
|
||||
*/
|
||||
if (await reconcileComputerHostDirectories({ computer_id, wait: true })) continue;
|
||||
|
||||
/**
|
||||
* A bot that joined since the last run means an account the mounted
|
||||
* folders don't know yet, so each gives access to everyone who sees
|
||||
* it now. A grant that already failed is not retried here: the
|
||||
* folder's permissions are the user's to fix, and they grant again
|
||||
* from the page.
|
||||
*/
|
||||
for (const host_directory_id of await grabComputerHostDirectoryIds({
|
||||
computer_id,
|
||||
})) {
|
||||
await applyHostDirectoryGrant({
|
||||
host_directory_id,
|
||||
retry: false,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
const refreshed = await refreshComputerContainer({
|
||||
computer_id,
|
||||
container,
|
||||
|
||||
+60
-5
@@ -117,7 +117,7 @@ export const AppData = {
|
||||
* `computer/` (the release workflow builds that tag), and bump
|
||||
* `ComputerWorkspaceLayout` too when existing computers must move to it.
|
||||
*/
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.3",
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.4",
|
||||
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
|
||||
/**
|
||||
* Only a computer's workspace (`ComputerWorkspaceDir` in its
|
||||
@@ -217,13 +217,54 @@ export const AppData = {
|
||||
* (`/home/cb-<bot>/workspace`, a link the agent keeps to their folder),
|
||||
* which an older agent would make a folder that isn't kept;
|
||||
* `cobble-computer-caches` is the image whose agent reports its
|
||||
* workspace (`/api/usage`), keeps run caches out of it and clears its
|
||||
* browser profile's caches at each start, so a computer still running
|
||||
* an older one is recreated onto it once.
|
||||
* workspace (`/api/usage`), keeps run caches out of it, clears its
|
||||
* browser profile's caches at each start, and leaves a host directory
|
||||
* mounted inside a bot's folder alone (its size and its permissions
|
||||
* are the host's), so a computer still running an older one is
|
||||
* recreated onto it once.
|
||||
*/
|
||||
ComputerWorkspaceLayout: "cobble-computer-caches",
|
||||
ComputerWorkspaceLayout: "cobble-computer-host-mounts",
|
||||
ComputerUserUid: 1000,
|
||||
ComputerUserGid: 1000,
|
||||
/**
|
||||
* A worker bot's own account on a computer is uid and gid
|
||||
* `ComputerWorkerIdBase + bot id` (`cb-<bot id>`, no sudo), and a
|
||||
* workspace's group is gid `ComputerWorkspaceGroupIdBase + workspace
|
||||
* id` (`cw-<workspace id>`); keep both alike with
|
||||
* `computer/agent/config.ts`. A host directory mounted into a
|
||||
* computer is owned by its users, so this app tells the user which
|
||||
* ids to give the folder (`hostDirectoryPermissionCommand`).
|
||||
*/
|
||||
ComputerWorkerIdBase: 100_000,
|
||||
ComputerWorkspaceGroupIdBase: 10_000_000,
|
||||
/**
|
||||
* A host directory is checked by running `test -d` and `test -w` as
|
||||
* each account that reaches it, in a throwaway container of the
|
||||
* computer's image, for at most this long (a cold image pull is not
|
||||
* part of it: the image is already there).
|
||||
*/
|
||||
HostDirectoryProbeTimeoutMs: 60 * 1000,
|
||||
/**
|
||||
* How long giving the bots access to a host folder may take: an ACL
|
||||
* entry on everything already there, which is a walk of the whole
|
||||
* folder, so a big one is allowed several minutes.
|
||||
*/
|
||||
HostDirectoryGrantTimeoutMs: 10 * 60 * 1000,
|
||||
/**
|
||||
* How much of a host folder is copied into the bot's own folder before
|
||||
* an approved delete: past this, the delete goes ahead without a copy
|
||||
* and the result says so, since the folder is the user's own data and
|
||||
* copying a whole disk into the workspace is what the quota guards.
|
||||
*/
|
||||
HostDirectoryRecoverMaxBytes: 512 * 1024 * 1024,
|
||||
/**
|
||||
* Where the copy of a deleted path is kept, in the run's own folder.
|
||||
*/
|
||||
HostDirectoryRecoverFolder: "recovered",
|
||||
/**
|
||||
* How long copying the paths an approved delete names may take.
|
||||
*/
|
||||
HostDirectoryRecoverTimeoutMs: 5 * 60 * 1000,
|
||||
/**
|
||||
* A worker's install request (`request_install`): at most this many
|
||||
* packages, a reason and notes this long, its answer this long.
|
||||
@@ -1262,6 +1303,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", () => {
|
||||
|
||||
@@ -86,7 +86,14 @@ You are chatting with the user. Answer their latest messages directly and briefl
|
||||
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just started a task (its result will offer what's next), or when the user is clearly wrapping up.
|
||||
|
||||
Your answer and that card go out together: ask_user and suggest_next_steps end the reply. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.`;
|
||||
Your answer and that card go out together: ask_user and suggest_next_steps end the reply. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.
|
||||
|
||||
## Nothing happens after you send
|
||||
|
||||
This message is the last thing the reply does: there is no next turn, and nothing runs once it goes out. So "I'll check", "let me check", "I'll connect and inspect", "next I'll" and "I'm going to" are promises the user waits on forever, and a promise with no run behind it is refused before it reaches them.
|
||||
|
||||
- If their latest message asks for work that needs no computer and takes a moment, do it in this reply and report what came back.
|
||||
- Otherwise call start_task now, then say in one sentence that it is running.`;
|
||||
|
||||
/**
|
||||
* Added to every run, chat replies and tasks alike: where its files live,
|
||||
@@ -166,7 +173,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 +256,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 +285,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 +341,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,74 @@
|
||||
/**
|
||||
* A folder on the host machine (Settings, under Host directories), mounted
|
||||
* into the computers linked to it, so bots reach the user's own files:
|
||||
* at `hosts/<slug>` in a bot's folder for a computer link, and at
|
||||
* `workspaces/<id>/<slug>` in the shared folder for a workspace link
|
||||
* (`hostDirectoryMountPlan`). A link is read and write unless it says read
|
||||
* only; a bot that must not change the user's files in place can clone
|
||||
* them into its own folder instead.
|
||||
*
|
||||
* The user sets the folder's permissions. The app only checks whether a
|
||||
* bot can write there (`probeHostDirectory`) and says what to run
|
||||
* (`hostDirectoryPermissionCommand`).
|
||||
*/
|
||||
export const HostDirectoryAccesses = [
|
||||
{
|
||||
title: "Read and write",
|
||||
value: "read-write",
|
||||
},
|
||||
{
|
||||
title: "Read only",
|
||||
value: "read-only",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type HostDirectoryAccess = (typeof HostDirectoryAccesses)[number]["value"];
|
||||
|
||||
/**
|
||||
* What a check found for one computer: the folder is there and every bot
|
||||
* can write (`writable`), only some can (`partial`), it exists but no bot
|
||||
* can (`read-only`), it isn't there (`missing`), or nothing was checked
|
||||
* yet (`unknown`).
|
||||
*/
|
||||
export const HostDirectoryCheckStates = [
|
||||
{
|
||||
title: "Read and write",
|
||||
value: "writable",
|
||||
},
|
||||
{
|
||||
title: "Some bots can't write",
|
||||
value: "partial",
|
||||
},
|
||||
{
|
||||
title: "Read only",
|
||||
value: "read-only",
|
||||
},
|
||||
{
|
||||
title: "Missing",
|
||||
value: "missing",
|
||||
},
|
||||
{
|
||||
title: "Not checked",
|
||||
value: "unknown",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type HostDirectoryCheckState = (typeof HostDirectoryCheckStates)[number]["value"];
|
||||
|
||||
/**
|
||||
* The folder a computer link is mounted at inside a bot's own folder
|
||||
* (`bots/<bot id>/hosts/<slug>`), so it works in every run of that bot
|
||||
* without the agent learning a new root.
|
||||
*/
|
||||
export const HostDirectoryMountFolder = "hosts";
|
||||
|
||||
export const HostDirectorySlugMaxChars = 32;
|
||||
export const HostDirectorySourceMaxChars = 4096;
|
||||
export const HostDirectoryNameMaxChars = 60;
|
||||
|
||||
/**
|
||||
* Where a mount's destination is prepared, as this app sees it, for a
|
||||
* computer: `DATA_DIR/computers/<id>/bots/<bot>/hosts/<slug>` and
|
||||
* `DATA_DIR/computers/<id>/workspaces/<id>/<slug>`.
|
||||
*/
|
||||
export const HostDirectoryCheckCacheMs = 30 * 1000;
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
KeyRound,
|
||||
Layers,
|
||||
Library,
|
||||
FolderTree,
|
||||
LockKeyhole,
|
||||
Monitor,
|
||||
Plug,
|
||||
@@ -42,6 +43,7 @@ export const SettingsBackupsPath = "/admin/settings/backups";
|
||||
export const SettingsDatabasePath = "/admin/settings/database";
|
||||
export const SettingsSetupPath = "/admin/settings/setup";
|
||||
export const SettingsModelsPath = "/admin/settings/models";
|
||||
export const SettingsHostDirectoriesPath = "/admin/settings/host-directories";
|
||||
|
||||
/**
|
||||
* The `/admin/settings/*` sub pages, listed in the rail on every settings
|
||||
@@ -69,6 +71,12 @@ export const SettingsPages: SettingsPage[] = [
|
||||
{ title: "Browsers", url: "/admin/settings/browsers", Icon: Compass },
|
||||
{ title: "Bots", url: "/admin/settings/bots", Icon: Bot, can_view: canManageCrew },
|
||||
{ title: "Workspaces", url: "/admin/settings/workspaces", Icon: Layers, can_view: canManageCrew },
|
||||
{
|
||||
title: "Host directories",
|
||||
url: SettingsHostDirectoriesPath,
|
||||
Icon: FolderTree,
|
||||
super_admin_only: true,
|
||||
},
|
||||
{ title: "Computers", url: SettingsComputersPath, Icon: Monitor, can_view: canManageCrew },
|
||||
{ title: "MCPs", url: "/admin/settings/mcps", Icon: Plug, can_view: canManageCrew },
|
||||
{ title: "Tools", url: "/admin/settings/tools", Icon: Wrench, can_view: canManageCrew },
|
||||
|
||||
@@ -45,10 +45,6 @@ export default async function createAsk({
|
||||
throw new AppError(`That request doesn't come from this bot's conversation.`);
|
||||
}
|
||||
|
||||
if (origin.hook_id) {
|
||||
throw new AppError(`A hook call can't ask the crew.`);
|
||||
}
|
||||
|
||||
const workspace_id = origin.workspace_id || null;
|
||||
const askable = await askableBots({
|
||||
user_id,
|
||||
|
||||
@@ -9,8 +9,8 @@ type Params = {
|
||||
/**
|
||||
* The session one bot keeps its part of an ask in: the coordinator's review,
|
||||
* then the asked bot's incoming brief and answer. Hidden from every
|
||||
* conversation and session list (`visibleSessionSql`), and never opened by a
|
||||
* user.
|
||||
* conversation and session list (`isHiddenSession`, and the `ask_id IS NULL`
|
||||
* in `followedSessionSql`), and never opened by a user.
|
||||
*/
|
||||
export default async function ensureAskSession({ ask, bot_id }: Params): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS> {
|
||||
const existing = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
|
||||
|
||||
@@ -40,12 +40,18 @@ type Params = {
|
||||
source?: BotHookSource;
|
||||
watch_computer_id?: number | string | null;
|
||||
watch_filter?: string | null;
|
||||
/**
|
||||
* Its runs stay in its own thread, pushed nowhere, instead of taking
|
||||
* over the conversation (see `updateBotHook`).
|
||||
*/
|
||||
silent?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gives one of the user's bots a hook: a secret URL whose calls each queue
|
||||
* the brief, with the call's payload, as a task there (`fireBotHook`), in
|
||||
* the hook's own thread, never in a chat. Returns the hook and its token, which is shown
|
||||
* the hook's own thread: the conversation's active one unless it's silent,
|
||||
* where the thread stays its own. Returns the hook and its token, which is shown
|
||||
* this once: only its hash is kept. A browser-notification hook needs a
|
||||
* computer both the user and the bot reach; its token is kept encrypted
|
||||
* for that computer's watcher, set up before this returns
|
||||
@@ -64,6 +70,7 @@ export default async function createBotHook({
|
||||
source = "url",
|
||||
watch_computer_id,
|
||||
watch_filter,
|
||||
silent,
|
||||
}: Params): Promise<BotHookWithToken> {
|
||||
const conversation = await grabUserConversation({ user_id, bot_id, workspace_id });
|
||||
const bot_id_num = conversation.bot.id;
|
||||
@@ -109,6 +116,7 @@ export default async function createBotHook({
|
||||
signature_format: secret ? signature_format || "sha256=hex" : undefined,
|
||||
enabled: 1,
|
||||
run_count: 0,
|
||||
silent: silent ? 1 : 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import deleteHookSessionRows from "./delete-hook-session-rows";
|
||||
import detachHookSessions from "./detach-hook-sessions";
|
||||
import grabUserBotHook from "./grab-user-bot-hook";
|
||||
import syncComputerNotifyWatch from "./sync-computer-notify-watch";
|
||||
|
||||
@@ -9,9 +9,10 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes one of the user's hooks, its recorded calls and its hidden
|
||||
* sessions (foreign keys are off outside the server, so they go first,
|
||||
* explicitly). A run already queued carries on. A notification hook's URL is taken off its
|
||||
* Deletes one of the user's hooks and its recorded calls. Its sessions
|
||||
* stay: they're ordinary threads once no hook owns them
|
||||
* (`detachHookSessions`), so the user keeps their history. A run already
|
||||
* queued carries on. A notification hook's URL is taken off its
|
||||
* computer's watcher.
|
||||
*/
|
||||
export default async function deleteBotHook({ user_id, hook_id }: Params) {
|
||||
@@ -22,7 +23,7 @@ export default async function deleteBotHook({ user_id, hook_id }: Params) {
|
||||
values: [hook.id!],
|
||||
});
|
||||
|
||||
await deleteHookSessionRows({ hook_id: hook.id! });
|
||||
await detachHookSessions({ hook_id: hook.id! });
|
||||
|
||||
const res = await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_hooks WHERE id = ?`,
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import deleteUnlinkedAttachmentMedia from "../media/delete-unlinked-attachment-media";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Only this hook's. Left out: every hidden session whose hook is gone.
|
||||
*/
|
||||
hook_id?: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes hooks' hidden sessions with what's in them. Explicitly, child
|
||||
* rows first, since foreign keys are off outside the server process. A
|
||||
* session with a run still open stays until that run ends (a deleted
|
||||
* hook's run carries on), and the daily prune takes it then.
|
||||
*/
|
||||
export default async function deleteHookSessionRows({ hook_id }: Params) {
|
||||
const res = await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT s.id FROM bot_sessions s WHERE s.hook_id IS NOT NULL
|
||||
AND ${hook_id ? `s.hook_id = ?` : `s.hook_id NOT IN (SELECT id FROM bot_hooks)`}
|
||||
AND NOT EXISTS (SELECT 1 FROM bots_queue q WHERE q.session_id = s.id AND q.status IN ('pending', 'processing'))`,
|
||||
values: hook_id ? [Number(hook_id)] : [],
|
||||
});
|
||||
|
||||
const list = (res.payload || []).map((row) => Number(row.id)).join(", ");
|
||||
|
||||
if (!list) return;
|
||||
|
||||
const messages = `SELECT id FROM bot_messages WHERE session_id IN (${list})`;
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `DELETE FROM bots_queue_updates WHERE bots_queue_id IN (SELECT id FROM bots_queue WHERE session_id IN (${list}))`,
|
||||
});
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bots_queue WHERE session_id IN (${list})` });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_tasks WHERE session_id IN (${list})` });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_message_reactions WHERE message_id IN (${messages})` });
|
||||
|
||||
/**
|
||||
* An upload's bytes are its `media` row, which the message's link was
|
||||
* the only way to reach.
|
||||
*/
|
||||
const uploads = await BunSQLite.sql<{ media_id: number }>({
|
||||
sql: `SELECT media_id FROM bot_message_media WHERE message_id IN (${messages})`,
|
||||
});
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_message_media WHERE message_id IN (${messages})` });
|
||||
|
||||
await deleteUnlinkedAttachmentMedia({ media_ids: (uploads.payload || []).map((row) => Number(row.media_id)) }).catch(() => []);
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_messages WHERE session_id IN (${list})` });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_sessions WHERE id IN (${list})` });
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The hook being deleted. Left out: every session whose hook is
|
||||
* already gone.
|
||||
*/
|
||||
hook_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Lets a hook's sessions go without deleting them: they're the user's own
|
||||
* threads now (`hook_id` null, a `hook` status row closed like any other),
|
||||
* so they stay in the session list and can be reopened. A run already
|
||||
* queued carries on there.
|
||||
*/
|
||||
export default async function detachHookSessions({ hook_id }: Params = {}) {
|
||||
const res = await BunSQLite.sql({
|
||||
sql: `UPDATE bot_sessions SET
|
||||
hook_id = NULL,
|
||||
status = CASE WHEN status = 'hook' THEN 'closed' ELSE status END,
|
||||
updated_at = ?
|
||||
WHERE hook_id IS NOT NULL
|
||||
${hook_id ? "AND hook_id = ?" : "AND NOT EXISTS (SELECT 1 FROM bot_hooks h WHERE h.id = bot_sessions.hook_id)"}`,
|
||||
values: hook_id ? [Date.now(), Number(hook_id)] : [Date.now()],
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
throw new Error(`Couldn't detach the hook's sessions: ${res.error}`);
|
||||
}
|
||||
}
|
||||
@@ -1,37 +1,84 @@
|
||||
import type {
|
||||
BUN_SQLITE_COBBLE_BOT_HOOKS,
|
||||
BUN_SQLITE_COBBLE_BOT_SESSIONS,
|
||||
} from "@/db/types/db";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_HOOKS } from "@/db/types/db";
|
||||
import { grabBotSessionMaxMessages } from "../app-settings/grab-bot-session-max-messages";
|
||||
import activateBotSession from "../bot-sessions/activate-bot-session";
|
||||
import createBotSession from "../bot-sessions/create-bot-session";
|
||||
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
|
||||
import rollOverLinkedSession from "../bot-sessions/roll-over-linked-session";
|
||||
|
||||
type Params = {
|
||||
hook: BUN_SQLITE_COBBLE_BOT_HOOKS;
|
||||
bot_id: number;
|
||||
workspace_id: number | null;
|
||||
bot_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The hidden session a hook's runs work in where it runs now (status
|
||||
* `hook`, in no conversation or list), started on its first call there.
|
||||
* Every session query that lists or picks a conversation leaves these out
|
||||
* (`hook_id IS NULL`); their results are read in the hook's thread.
|
||||
* The session a hook's call works in: the hook's own thread, never the
|
||||
* conversation's active session by itself. Started closed when the hook has
|
||||
* none, so a run never lands in a chat the user was having; once it's full
|
||||
* (`grabBotSessionMaxMessages`) it carries on in a new linked session
|
||||
* (`rollOverLinkedSession`). A hook that isn't silent takes the
|
||||
* conversation over: its thread becomes the active session first, so the
|
||||
* user sees the run and can chat there (`activateBotSession`). Returns the
|
||||
* session's id.
|
||||
*/
|
||||
export default async function ensureHookSession({ hook, bot_id, workspace_id }: Params): Promise<number> {
|
||||
const existing = (
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM bot_sessions WHERE hook_id = ? AND bot_id = ? AND workspace_id IS ? ORDER BY id DESC LIMIT 1`,
|
||||
values: [hook.id!, bot_id, workspace_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
const user_id = hook.user_id!;
|
||||
const workspace = workspace_id ? Number(workspace_id) : null;
|
||||
|
||||
if (existing?.id) return Number(existing.id);
|
||||
|
||||
const session = await createBotSession({
|
||||
user_id: hook.user_id!,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
status: "hook",
|
||||
hook_id: Number(hook.id),
|
||||
title: `Hook: ${hook.title || hook.id}`,
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
|
||||
sql: `SELECT s.* FROM bot_sessions s
|
||||
WHERE s.hook_id = ? AND s.user_id = ? AND s.bot_id = ? AND s.workspace_id IS ?
|
||||
ORDER BY s.id DESC LIMIT 1`,
|
||||
values: [hook.id!, user_id, bot_id, workspace],
|
||||
});
|
||||
|
||||
let session = res.payload?.[0];
|
||||
|
||||
if (!session?.id) {
|
||||
session = await createBotSession({
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id: workspace,
|
||||
status: "closed",
|
||||
hook_id: Number(hook.id!),
|
||||
title: `Hook: ${hook.title || hook.id}`,
|
||||
});
|
||||
} else {
|
||||
const count =
|
||||
Number(
|
||||
(
|
||||
await BunSQLite.sql<{ n: number }>({
|
||||
sql: `SELECT COUNT(*) AS n FROM bot_messages WHERE session_id = ?`,
|
||||
values: [session.id!],
|
||||
})
|
||||
).payload?.[0]?.n,
|
||||
) || 0;
|
||||
|
||||
if (count >= (await grabBotSessionMaxMessages())) {
|
||||
const next = await rollOverLinkedSession({
|
||||
session,
|
||||
user_id,
|
||||
bot_id: Number(bot_id),
|
||||
workspace_id: workspace,
|
||||
});
|
||||
|
||||
const carried = next ? await grabUserBotSession({ session_id: next, user_id }) : null;
|
||||
|
||||
if (carried?.id) session = carried;
|
||||
}
|
||||
}
|
||||
|
||||
if (!session?.id) {
|
||||
throw new Error(`Couldn't open a session for the hook ${hook.id}.`);
|
||||
}
|
||||
|
||||
if (!hook.silent && session.status != "active") {
|
||||
session = await activateBotSession({ session });
|
||||
}
|
||||
|
||||
return Number(session.id);
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,8 @@ export type FireBotHookResult = {
|
||||
|
||||
/**
|
||||
* Takes one call to a hook: records it, then gives it to its bot as a task
|
||||
* in the hook's own hidden session (`ensureHookSession`). A call while the hook's last run is
|
||||
* in the hook's own thread (`ensureHookSession`: silent hooks keep it out of
|
||||
* sight, the others take the conversation over for the run). A call while the hook's last run is
|
||||
* still waiting (queued, never tried) joins that run's brief instead, up
|
||||
* to `AppData.BotHookMaxEventsPerRun` calls, so a burst makes one run and
|
||||
* none is lost; once a run has started, the next call queues a new one.
|
||||
|
||||
@@ -22,7 +22,8 @@ type Params = {
|
||||
|
||||
/**
|
||||
* The user's hooks with their bot (its face as the user sees it) and
|
||||
* workspace names, the most recently called first. Never their token hash
|
||||
* workspace names, the most recently called first, each with the id of the
|
||||
* session its latest call left its messages in. Never their token hash
|
||||
* or signing secret, nor a notification hook's stored token.
|
||||
*/
|
||||
export default async function grabBotHooks({
|
||||
@@ -55,7 +56,8 @@ export default async function grabBotHooks({
|
||||
const res = await BunSQLite.sql<BotHookWithNames>({
|
||||
sql: `SELECT h.id, h.created_at, h.updated_at, h.user_id, h.bot_id, h.workspace_id, h.title,
|
||||
h.instructions, h.computer_id, h.token_prefix, h.signature_header, h.signature_format,
|
||||
h.enabled, h.run_count, h.last_called_at, h.last_job_id, h.last_error,
|
||||
h.enabled, h.run_count, h.last_called_at, h.last_job_id, h.last_error, h.silent,
|
||||
(SELECT r.id FROM bot_sessions r WHERE r.hook_id = h.id ORDER BY r.id DESC LIMIT 1) AS latest_session_id,
|
||||
h.source, h.watch_computer_id, h.watch_filter, wc.name AS watch_computer_name,
|
||||
(COALESCE(h.signing_secret, '') != '') AS has_signing_secret,
|
||||
b.name AS bot_name, b.kind AS bot_kind, b.hue AS bot_hue, b.color AS bot_color, b.stone AS bot_stone, ${face.sql},
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
session_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The hook whose runs a session holds, or null for any other session.
|
||||
*/
|
||||
export default async function grabSessionHookId({ session_id }: Params) {
|
||||
if (!session_id) return null;
|
||||
|
||||
const hook_id = (
|
||||
await BunSQLite.sql<{ hook_id: number | null }>({
|
||||
sql: `SELECT hook_id FROM bot_sessions WHERE id = ? LIMIT 1`,
|
||||
values: [session_id],
|
||||
})
|
||||
).payload?.[0]?.hook_id;
|
||||
|
||||
return hook_id ? Number(hook_id) : null;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
session_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a session is a silent hook's thread. Its runs are followed by
|
||||
* nobody: they change no face and are pushed nowhere. A hook that isn't
|
||||
* silent takes the conversation over instead, so its runs show like any
|
||||
* other and this is false for them.
|
||||
*/
|
||||
export default async function isUnattendedHookSession({ session_id }: Params) {
|
||||
if (!session_id) return false;
|
||||
|
||||
const res = await BunSQLite.sql<{ unattended: number }>({
|
||||
sql: `SELECT (h.id IS NOT NULL AND h.silent = 1) AS unattended
|
||||
FROM bot_sessions s LEFT JOIN bot_hooks h ON h.id = s.hook_id
|
||||
WHERE s.id = ? LIMIT 1`,
|
||||
values: [Number(session_id)],
|
||||
});
|
||||
|
||||
return res.payload?.[0]?.unattended == 1;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
/**
|
||||
* Hooks from before `silent` existed run silently from now on: an install
|
||||
* that updates shouldn't have its hooks start taking over conversations
|
||||
* unasked. New hooks are asked about it when they're made, and the flag is
|
||||
* only null until this runs once.
|
||||
*/
|
||||
export default async function migrateHookSilence() {
|
||||
const res = await BunSQLite.sql({
|
||||
sql: `UPDATE bot_hooks SET silent = 1 WHERE silent IS NULL`,
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
throw new Error(`Couldn't set the existing hooks silent: ${res.error}`);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,12 @@ type Params = {
|
||||
* A browser-notification hook's filter; empty takes them all.
|
||||
*/
|
||||
watch_filter?: string;
|
||||
/**
|
||||
* True: its runs stay in its own thread, pushed nowhere and off the
|
||||
* bot's face. False: each run takes over the conversation, in a
|
||||
* session the user sees and can chat in.
|
||||
*/
|
||||
silent?: boolean;
|
||||
/**
|
||||
* Where it runs from now, with the same bot: one of its
|
||||
* workspaces, or null for its own chat.
|
||||
@@ -38,7 +44,8 @@ type Params = {
|
||||
/**
|
||||
* Changes one of the user's hooks: its name and brief, pauses or resumes
|
||||
* it, sets how its calls are signed or, for browser notifications, which
|
||||
* ones it takes, or moves it to another of its bot's places. Its token stays (rotate it with `rotateBotHookToken`). A move
|
||||
* ones it takes, whether its runs take over the conversation or stay in
|
||||
* their own thread, or moves it to another of its bot's places. Its token stays (rotate it with `rotateBotHookToken`). A move
|
||||
* is refused while its last run is open (a call could still join it
|
||||
* there); its computer stays only if the bot reaches it in the new place,
|
||||
* and a notification hook can't go where its watched computer isn't.
|
||||
@@ -64,6 +71,8 @@ export default async function updateBotHook({ user_id, hook_id, data }: Params)
|
||||
if (data.enabled) set("last_error", null);
|
||||
}
|
||||
|
||||
if (data.silent !== undefined) set("silent", data.silent ? 1 : 0);
|
||||
|
||||
const watching = hook.source == "browser_notifications";
|
||||
|
||||
if (data.watch_filter !== undefined) {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import deleteSessionRows from "./delete-session-rows";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The user's session to make the conversation's active one.
|
||||
*/
|
||||
session: BUN_SQLITE_COBBLE_BOT_SESSIONS;
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes a session the active one of its conversation: the session that was
|
||||
* active is closed, and one of its own that is still empty is deleted
|
||||
* instead, together with its rows (`deleteSessionRows`), since a job it
|
||||
* holds would otherwise point at a session that is gone. The caller checks
|
||||
* whatever must be refused first. Returns the session, active.
|
||||
*/
|
||||
export default async function activateBotSession({
|
||||
session,
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS> {
|
||||
const now = Date.now();
|
||||
const workspace_id = session.workspace_id || null;
|
||||
|
||||
const emptied = (
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND status = 'active'
|
||||
AND NOT EXISTS (SELECT 1 FROM bot_messages m WHERE m.session_id = bot_sessions.id)`,
|
||||
values: [session.user_id!, session.bot_id!, workspace_id],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
await deleteSessionRows({ session_ids: emptied.map((row) => Number(row.id)) });
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_sessions SET status = 'closed', unread = 0, updated_at = ?
|
||||
WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND status = 'active'`,
|
||||
values: [now, session.user_id!, session.bot_id!, workspace_id],
|
||||
});
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_sessions SET status = 'active', updated_at = ? WHERE id = ?`,
|
||||
values: [now, session.id!],
|
||||
});
|
||||
|
||||
return { ...session, status: "active", updated_at: now };
|
||||
}
|
||||
@@ -5,11 +5,13 @@ import AppError from "@/src/utils/app-error";
|
||||
import insertBotMessage from "../bots/insert-bot-message";
|
||||
import createBotSession from "./create-bot-session";
|
||||
import grabActiveBotSession from "./grab-active-bot-session";
|
||||
import grabUserBotSession from "./grab-user-bot-session";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The session the bot is answering in: it must be the conversation's
|
||||
* active one.
|
||||
* active one, unless `allow_inactive` moves a routine's or a silent
|
||||
* hook's own thread, which never is.
|
||||
*/
|
||||
session_id: number | string;
|
||||
user_id: number | string;
|
||||
@@ -30,6 +32,18 @@ type Params = {
|
||||
* summary.
|
||||
*/
|
||||
job_id?: number | null;
|
||||
/**
|
||||
* Move the given session even when it isn't the conversation's active
|
||||
* one: a routine's or a silent hook's own thread.
|
||||
*/
|
||||
allow_inactive?: boolean;
|
||||
/**
|
||||
* The new session's status. `active` (default) moves the conversation
|
||||
* on; `closed` keeps a routine's or a silent hook's thread beside the
|
||||
* conversation, so its next run continues there without taking the
|
||||
* chat over.
|
||||
*/
|
||||
next_status?: "active" | "closed";
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -39,6 +53,9 @@ type Params = {
|
||||
* the next prompt as written) and opens the new one as a bot message
|
||||
* (`carried_from_session_id`), and the reply's own answer follows it
|
||||
* there. The new session is titled by the bot (else after the old one).
|
||||
* The same carries a routine's or a hook's own thread into its next
|
||||
* session (`allow_inactive`, `next_status` closed), keeping the link to
|
||||
* the routine or hook and the conversation's active session untouched.
|
||||
* Returns that first message, for the caller to push.
|
||||
*/
|
||||
export default async function carryOverBotSession({
|
||||
@@ -49,15 +66,28 @@ export default async function carryOverBotSession({
|
||||
summary,
|
||||
title,
|
||||
job_id,
|
||||
allow_inactive,
|
||||
next_status = "active",
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES> {
|
||||
const text = summary.trim().slice(0, AppData.BotSessionSummaryMaxChars);
|
||||
|
||||
if (!text) throw new AppError(`The summary is empty.`);
|
||||
|
||||
const active = await grabActiveBotSession({ user_id, bot_id, workspace_id });
|
||||
const active = allow_inactive
|
||||
? await grabUserBotSession({ session_id, user_id })
|
||||
: await grabActiveBotSession({ user_id, bot_id, workspace_id });
|
||||
|
||||
if (!active?.id || active.id != Number(session_id)) {
|
||||
throw new AppError(`This session isn't the conversation's current one, so it can't be moved on from.`);
|
||||
if (
|
||||
!active?.id ||
|
||||
active.id != Number(session_id) ||
|
||||
Number(active.bot_id) != Number(bot_id) ||
|
||||
(Number(active.workspace_id) || null) != (Number(workspace_id) || null)
|
||||
) {
|
||||
throw new AppError(
|
||||
allow_inactive
|
||||
? `That session isn't part of this conversation, so it can't be moved on from.`
|
||||
: `This session isn't the conversation's current one, so it can't be moved on from.`,
|
||||
);
|
||||
}
|
||||
|
||||
const message_count =
|
||||
@@ -93,6 +123,9 @@ export default async function carryOverBotSession({
|
||||
bot_id,
|
||||
workspace_id,
|
||||
previous_session_id: active.id,
|
||||
status: next_status,
|
||||
hook_id: Number(active.hook_id) || null,
|
||||
routine_id: Number(active.routine_id) || null,
|
||||
title:
|
||||
title?.replace(/\s+/g, " ").trim().slice(0, AppData.BotSessionTitleMaxChars) ||
|
||||
active.title ||
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { SessionContinuePrompt } from "@/src/data/harness-prompts";
|
||||
import parseSessionName from "@/src/bots-queue/parse-session-name";
|
||||
import sessionNameTranscript from "@/src/bots-queue/session-name-transcript";
|
||||
import generateText from "@/src/harness/text/generate-text";
|
||||
import { runWithHarnessUsageScope } from "@/src/harness/usage/harness-usage-scope";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import grabBotMessages from "../bots/grab-bot-messages";
|
||||
import carryOverBotSession from "./carry-over-bot-session";
|
||||
import grabActiveBotSession from "./grab-active-bot-session";
|
||||
import hasOpenSessionJob from "./has-open-session-job";
|
||||
import writeSessionContinuation from "./write-session-continuation";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -22,10 +16,11 @@ type Params = {
|
||||
* menu (and the automatic rollover, `rollOverBotSession`): does what the
|
||||
* bot does with `continue_in_new_session`. The bot's
|
||||
* text model writes the new session's title and the summary from the
|
||||
* session's latest messages, then `carryOverBotSession` closes this
|
||||
* session for good and opens the new one with the summary. Refused while
|
||||
* the bot is still working in the session, since its answer would land in
|
||||
* the closed one. Returns the summary's message, for the caller to push.
|
||||
* session's latest messages (`writeSessionContinuation`), then
|
||||
* `carryOverBotSession` closes this session for good and opens the new one
|
||||
* with the summary. Refused while the bot is still working in the session,
|
||||
* since its answer would land in the closed one. Returns the summary's
|
||||
* message, for the caller to push.
|
||||
*/
|
||||
export default async function continueBotSession({
|
||||
user_id,
|
||||
@@ -40,35 +35,13 @@ export default async function continueBotSession({
|
||||
throw new AppError(`The bot is still working in this session. Wait for it to finish, or stop it, then continue.`);
|
||||
}
|
||||
|
||||
const messages = await grabBotMessages({
|
||||
const written = await writeSessionContinuation({
|
||||
session_id: active.id,
|
||||
limit: AppData.BotSessionSummaryMessages,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
});
|
||||
|
||||
if (!messages.length) throw new AppError(`This session has no messages yet: it's already fresh.`);
|
||||
|
||||
const result = await runWithHarnessUsageScope({
|
||||
scope: {
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id: workspace_id || null,
|
||||
session_id: active.id,
|
||||
job_id: null,
|
||||
message_id: null,
|
||||
},
|
||||
task: () =>
|
||||
generateText({
|
||||
messages: [
|
||||
{ role: "system", content: SessionContinuePrompt },
|
||||
{ role: "user", content: sessionNameTranscript({ messages }) },
|
||||
],
|
||||
bot_id,
|
||||
workspace_id,
|
||||
}),
|
||||
});
|
||||
|
||||
const written = parseSessionName({ text: result.text });
|
||||
|
||||
if (!written?.summary) {
|
||||
throw new AppError(`Couldn't write the summary to carry over. Try again.`);
|
||||
}
|
||||
@@ -81,4 +54,4 @@ export default async function continueBotSession({
|
||||
summary: written.summary,
|
||||
title: written.title,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,10 @@ type Params = {
|
||||
* The hook whose runs it holds (status `hook`).
|
||||
*/
|
||||
hook_id?: number | null;
|
||||
/**
|
||||
* The routine (`cron_jobs`) whose runs it holds.
|
||||
*/
|
||||
routine_id?: number | null;
|
||||
title?: string | null;
|
||||
};
|
||||
|
||||
@@ -39,6 +43,7 @@ export default async function createBotSession({
|
||||
previous_session_id,
|
||||
status = "active",
|
||||
hook_id,
|
||||
routine_id,
|
||||
title,
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS> {
|
||||
const now = Date.now();
|
||||
@@ -50,6 +55,7 @@ export default async function createBotSession({
|
||||
previous_session_id: previous_session_id || undefined,
|
||||
status,
|
||||
hook_id: hook_id || undefined,
|
||||
routine_id: routine_id || undefined,
|
||||
title: title || undefined,
|
||||
unread: 0,
|
||||
last_activity_at: now,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import type {
|
||||
BUN_SQLITE_COBBLE_BOT_SESSIONS,
|
||||
BUN_SQLITE_COBBLE_CRON_JOBS,
|
||||
} from "@/db/types/db";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { grabBotSessionMaxMessages } from "../app-settings/grab-bot-session-max-messages";
|
||||
import createBotSession from "./create-bot-session";
|
||||
import rollOverLinkedSession from "./roll-over-linked-session";
|
||||
|
||||
type Params = {
|
||||
cron_job: BUN_SQLITE_COBBLE_CRON_JOBS;
|
||||
};
|
||||
|
||||
/**
|
||||
* The session a routine's run works in: the routine's own thread, not the
|
||||
* conversation's active session, so a run's messages never land in a chat
|
||||
* the user was having. Started closed when the routine has none, so it
|
||||
* doesn't take the conversation over; the user opens it from the routine
|
||||
* or the sessions list and can chat there. Once it's full
|
||||
* (`grabBotSessionMaxMessages`) it carries on in a new linked session
|
||||
* (`rollOverLinkedSession`). Returns the session's id.
|
||||
*/
|
||||
export default async function ensureRoutineSession({ cron_job }: Params): Promise<number> {
|
||||
const user_id = cron_job.user_id!;
|
||||
const bot_id = Number(cron_job.bot_id);
|
||||
const workspace_id = Number(cron_job.workspace_id) || null;
|
||||
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
|
||||
sql: `SELECT s.* FROM bot_sessions s
|
||||
WHERE s.routine_id = ? AND s.user_id = ? AND s.bot_id = ? AND s.workspace_id IS ?
|
||||
ORDER BY s.id DESC LIMIT 1`,
|
||||
values: [cron_job.id!, user_id, bot_id, workspace_id],
|
||||
});
|
||||
|
||||
const latest = res.payload?.[0];
|
||||
|
||||
if (!latest?.id) {
|
||||
const created = await createBotSession({
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
status: "closed",
|
||||
routine_id: Number(cron_job.id!),
|
||||
title: cron_job.title || "Scheduled task",
|
||||
});
|
||||
|
||||
return Number(created.id);
|
||||
}
|
||||
|
||||
const count =
|
||||
Number(
|
||||
(
|
||||
await BunSQLite.sql<{ n: number }>({
|
||||
sql: `SELECT COUNT(*) AS n FROM bot_messages WHERE session_id = ?`,
|
||||
values: [latest.id!],
|
||||
})
|
||||
).payload?.[0]?.n,
|
||||
) || 0;
|
||||
|
||||
if (count < (await grabBotSessionMaxMessages())) return Number(latest.id);
|
||||
|
||||
const next = await rollOverLinkedSession({
|
||||
session: latest,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
});
|
||||
|
||||
return next || Number(latest.id);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import followedSessionSql from "./followed-session-sql";
|
||||
|
||||
/**
|
||||
* What counts as the user's own activity: every session but a crew
|
||||
* request's and a silent hook's thread. Run against real SQLite, since the
|
||||
* rule is the SQL itself.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(
|
||||
`CREATE TABLE bot_hooks (id INTEGER PRIMARY KEY, silent INTEGER)`,
|
||||
);
|
||||
db.run(`INSERT INTO bot_hooks VALUES (4, 1), (5, 0)`);
|
||||
db.run(
|
||||
`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, title TEXT, ask_id INTEGER, hook_id INTEGER, routine_id INTEGER)`,
|
||||
);
|
||||
db.run(`INSERT INTO bot_sessions VALUES
|
||||
(1, 'The chat', NULL, NULL, NULL),
|
||||
(2, 'A crew request', 3, NULL, NULL),
|
||||
(3, 'A silent hook', NULL, 4, NULL),
|
||||
(4, 'A hook that talks', NULL, 5, NULL),
|
||||
(5, 'A routine', NULL, NULL, 9)`);
|
||||
|
||||
function ids(alias?: string) {
|
||||
const sql = `SELECT id FROM bot_sessions${alias ? ` ${alias}` : ""} WHERE ${followedSessionSql(alias ? { alias } : {})} ORDER BY id`;
|
||||
|
||||
return (db.query(sql).all() as { id: number }[]).map((row) => row.id);
|
||||
}
|
||||
|
||||
describe("followedSessionSql", () => {
|
||||
test("keeps the chat, a routine's thread and a hook that isn't silent", () => {
|
||||
expect(ids()).toEqual([1, 4, 5]);
|
||||
});
|
||||
|
||||
test("leaves out a crew request and a silent hook's thread", () => {
|
||||
expect(ids()).not.toContain(2);
|
||||
expect(ids()).not.toContain(3);
|
||||
});
|
||||
|
||||
test("reads the alias it's given, for queries that join sessions", () => {
|
||||
expect(ids("s")).toEqual([1, 4, 5]);
|
||||
});
|
||||
|
||||
test("a session whose hook is gone is the user's again", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (6, 'A detached hook thread', NULL, 99, NULL)`);
|
||||
|
||||
expect(ids()).toEqual([1, 4, 5, 6]);
|
||||
|
||||
db.run(`DELETE FROM bot_sessions WHERE id = 6`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The table alias to test, for queries that join sessions.
|
||||
*/
|
||||
alias?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The sessions a user follows: every one but a crew request's (status
|
||||
* `ask`, read by the bots working it) and a silent hook's thread (its runs
|
||||
* are pushed nowhere and read where the hook is). Used where a session
|
||||
* should count as the user's activity: unread marks, the rail, the
|
||||
* dashboard and the bot's face. Routine threads and a hook that isn't
|
||||
* silent always count.
|
||||
*/
|
||||
export default function followedSessionSql({ alias = "bot_sessions" }: Params = {}) {
|
||||
return `(${alias}.ask_id IS NULL AND NOT EXISTS (SELECT 1 FROM bot_hooks h WHERE h.id = ${alias}.hook_id AND h.silent = 1))`;
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BotSessionListItem } from "@/src/types";
|
||||
import followedSessionSql from "./followed-session-sql";
|
||||
import visibleSessionSql from "./visible-session-sql";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -18,12 +20,19 @@ type Params = {
|
||||
* How many to return; a page by default.
|
||||
*/
|
||||
limit?: number;
|
||||
/**
|
||||
* Leave out a silent hook's thread, which the rail doesn't list (it's
|
||||
* read in the sessions modal and on the hook itself).
|
||||
*/
|
||||
attended_only?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* A user's conversation's sessions for the sessions modal, latest activity first,
|
||||
* each with its message count and latest message. Empty sessions are left
|
||||
* out unless active.
|
||||
* A user's conversation's sessions for the sessions modal, latest activity
|
||||
* first, each with its message count, latest message and the routine or
|
||||
* hook that runs in it. Empty sessions are left out unless active. A
|
||||
* routine's and a hook's threads are ordinary sessions, so the user can
|
||||
* open and chat in them; only a crew request's is hidden.
|
||||
*/
|
||||
export default async function grabBotSessions({
|
||||
user_id,
|
||||
@@ -32,6 +41,7 @@ export default async function grabBotSessions({
|
||||
query,
|
||||
page = 1,
|
||||
limit,
|
||||
attended_only,
|
||||
}: Params): Promise<BotSessionListItem[]> {
|
||||
const search = query?.trim();
|
||||
const like = search ? `%${search.replace(/[\\%_]/g, (c) => `\\${c}`)}%` : null;
|
||||
@@ -41,9 +51,14 @@ export default async function grabBotSessions({
|
||||
|
||||
sql += `SELECT s.*,\n`;
|
||||
sql += ` (SELECT COUNT(*) FROM bot_messages m WHERE m.session_id = s.id) AS message_count,\n`;
|
||||
sql += ` (SELECT m.text FROM bot_messages m WHERE m.session_id = s.id ORDER BY m.created_at DESC, m.id DESC LIMIT 1) AS last_message_text\n`;
|
||||
sql += ` (SELECT m.text FROM bot_messages m WHERE m.session_id = s.id ORDER BY m.created_at DESC, m.id DESC LIMIT 1) AS last_message_text,\n`;
|
||||
sql += ` (SELECT c.title FROM cron_jobs c WHERE c.id = s.routine_id) AS routine_title,\n`;
|
||||
sql += ` (SELECT h.title FROM bot_hooks h WHERE h.id = s.hook_id) AS hook_title\n`;
|
||||
sql += `FROM bot_sessions s\n`;
|
||||
sql += `WHERE s.user_id = ? AND s.bot_id = ? AND s.workspace_id IS ? AND s.ask_id IS NULL AND s.hook_id IS NULL\n`;
|
||||
sql += `WHERE s.user_id = ? AND s.bot_id = ? AND s.workspace_id IS ?\n`;
|
||||
|
||||
sql += `AND ${attended_only ? followedSessionSql({ alias: "s" }) : visibleSessionSql({ alias: "s" })}\n`;
|
||||
|
||||
sql += `AND (s.status = 'active' OR EXISTS (SELECT 1 FROM bot_messages m WHERE m.session_id = s.id))\n`;
|
||||
|
||||
if (like) {
|
||||
|
||||
@@ -59,7 +59,6 @@ export default async function grabConversationHistory({
|
||||
const in_conversation =
|
||||
asked?.id &&
|
||||
!asked.ask_id &&
|
||||
!asked.hook_id &&
|
||||
Number(asked.bot_id) == Number(open_bot_id) &&
|
||||
(asked.workspace_id ? Number(asked.workspace_id) : null) ==
|
||||
(conversation_workspace_id ? Number(conversation_workspace_id) : null);
|
||||
|
||||
@@ -3,6 +3,8 @@ import type { BotTextModel, PagePropsType } from "@/src/types";
|
||||
import railBots from "@/src/utils/rail-bots";
|
||||
import railWorkspaces from "@/src/utils/rail-workspaces";
|
||||
import grabBots from "../bots/grab-bots";
|
||||
import recordBotVisit from "../bots/record-bot-visit";
|
||||
import recordWorkspaceVisit from "../workspaces/record-workspace-visit";
|
||||
import grabBotExtensionsOverview from "../extensions/grab-bot-extensions-overview";
|
||||
import grabConversationFiles from "../bot-files/grab-conversation-files";
|
||||
import grabBotComputers from "../computers/grab-bot-computers";
|
||||
@@ -36,7 +38,8 @@ type Params = {
|
||||
* the models modal: the install-wide catalog (`api/admin/harness/catalog`)
|
||||
* and the conversation's small setting
|
||||
* (`api/admin/bots/harness-overview`). They are most of a page's weight
|
||||
* and only that modal uses them.
|
||||
* and only that modal uses them. Opening a conversation records the visit
|
||||
* (`recordBotVisit`, and the workspace's), before the rail is read.
|
||||
* Null when the user can't chat with the bot there.
|
||||
*/
|
||||
export default async function grabConversationProps({
|
||||
@@ -52,6 +55,17 @@ export default async function grabConversationProps({
|
||||
|
||||
const scope = conversation.workspace_id;
|
||||
|
||||
/**
|
||||
* Noted before the rail is read, so the conversation just opened is
|
||||
* already the latest in it: the lists order by each user's last visit,
|
||||
* and reading them first left the open bot where it was until the
|
||||
* next page load.
|
||||
*/
|
||||
await Promise.all([
|
||||
recordBotVisit({ user_id, bot_id: conversation.bot.id }),
|
||||
scope ? recordWorkspaceVisit({ user_id, workspace_id: scope }) : null,
|
||||
]);
|
||||
|
||||
const [bots, workspaces, answer_ask] = await Promise.all([
|
||||
grabBots({ user_id, workspace_id: scope }),
|
||||
grabUserWorkspaces({ user_id }),
|
||||
|
||||
@@ -72,7 +72,7 @@ export default async function grabPastSessionMessages({
|
||||
const session = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
|
||||
sql: `SELECT id, title, previous_session_id FROM bot_sessions
|
||||
WHERE id = ? AND user_id = ? AND bot_id = ? AND workspace_id IS ? AND id != ? AND ask_id IS NULL AND hook_id IS NULL LIMIT 1`,
|
||||
WHERE id = ? AND user_id = ? AND bot_id = ? AND workspace_id IS ? AND id != ? AND ask_id IS NULL LIMIT 1`,
|
||||
values: [
|
||||
target_session_id,
|
||||
user_id,
|
||||
|
||||
@@ -5,11 +5,13 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a session is a crew request's or a hook's, which nobody follows.
|
||||
* Whether a session is a crew request's (status `ask`), which nobody
|
||||
* follows. A routine's or a hook's thread isn't hidden: the user can open
|
||||
* it and chat there.
|
||||
*/
|
||||
export default async function isHiddenSession({ session_id }: Params) {
|
||||
const res = await BunSQLite.sql<{ hidden: number }>({
|
||||
sql: `SELECT (ask_id IS NOT NULL OR hook_id IS NOT NULL) AS hidden FROM bot_sessions WHERE id = ?`,
|
||||
sql: `SELECT (ask_id IS NOT NULL) AS hidden FROM bot_sessions WHERE id = ?`,
|
||||
values: [Number(session_id)],
|
||||
});
|
||||
|
||||
|
||||
@@ -33,7 +33,8 @@ db.run(`ALTER TABLE bot_sessions ADD COLUMN ask_id INTEGER`);
|
||||
db.run(`INSERT INTO bot_sessions (id, user_id, bot_id, workspace_id, title, ask_id) VALUES (6, 1, 10, NULL, 'A crew request', 3)`);
|
||||
db.run(`INSERT INTO bot_messages (id, session_id, author, text) VALUES (9, 6, 'bot', 'Acme invoice asked in a crew request')`);
|
||||
/**
|
||||
* A hook's hidden session: read in its thread, never a past session.
|
||||
* A hook's thread: an ordinary session of the conversation now, so a
|
||||
* search can read it too.
|
||||
*/
|
||||
db.run(`ALTER TABLE bot_sessions ADD COLUMN hook_id INTEGER`);
|
||||
db.run(`INSERT INTO bot_sessions (id, user_id, bot_id, workspace_id, title, hook_id) VALUES (7, 1, 10, NULL, 'A hook', 4)`);
|
||||
@@ -53,7 +54,7 @@ function ids(params: Partial<SearchPastSessionsParams>) {
|
||||
|
||||
describe("searchPastSessionsSql", () => {
|
||||
test("finds only this conversation's earlier sessions, newest first", () => {
|
||||
expect(ids({ query: "acme invoice" })).toEqual([2, 1]);
|
||||
expect(ids({ query: "acme invoice" })).toEqual([10, 2, 1]);
|
||||
});
|
||||
|
||||
test("keeps the workspace's conversation apart from the bot's own chat", () => {
|
||||
|
||||
@@ -63,7 +63,6 @@ export default function searchPastSessionsSql({
|
||||
`s.workspace_id IS ?`,
|
||||
`s.id != ?`,
|
||||
`s.ask_id IS NULL`,
|
||||
`s.hook_id IS NULL`,
|
||||
];
|
||||
|
||||
for (const word of words) {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import activateBotSession from "./activate-bot-session";
|
||||
import grabUserBotSession from "./grab-user-bot-session";
|
||||
import deleteSessionRows from "./delete-session-rows";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
@@ -12,8 +12,8 @@ type Params = {
|
||||
/**
|
||||
* Makes a closed session of one of the user's conversations the active
|
||||
* one again, so the bot carries on from where it left off. The session
|
||||
* that was active is closed (an empty one is deleted). A session the bot
|
||||
* moved the conversation on from is never reopened.
|
||||
* that was active is closed (an empty one is deleted, `activateBotSession`).
|
||||
* A session the bot moved the conversation on from is never reopened.
|
||||
*/
|
||||
export default async function reopenBotSession({
|
||||
session_id,
|
||||
@@ -30,7 +30,7 @@ export default async function reopenBotSession({
|
||||
/**
|
||||
* A bot's part of a crew request is only ever read there.
|
||||
*/
|
||||
if (session.ask_id || session.hook_id) {
|
||||
if (session.ask_id) {
|
||||
throw new AppError(`Session not found.`);
|
||||
}
|
||||
|
||||
@@ -50,33 +50,5 @@ export default async function reopenBotSession({
|
||||
throw new AppError(`This conversation moved on to a newer session, so this one stays closed. You can still read it.`);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const workspace_id = session.workspace_id || null;
|
||||
|
||||
/**
|
||||
* The empty one goes with its own rows (`deleteSessionRows`): a job it
|
||||
* still held would otherwise point at a session that is gone.
|
||||
*/
|
||||
const emptied = (
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND status = 'active'
|
||||
AND NOT EXISTS (SELECT 1 FROM bot_messages m WHERE m.session_id = bot_sessions.id)`,
|
||||
values: [session.user_id!, session.bot_id!, workspace_id],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
await deleteSessionRows({ session_ids: emptied.map((row) => Number(row.id)) });
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_sessions SET status = 'closed', unread = 0, updated_at = ?
|
||||
WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND status = 'active'`,
|
||||
values: [now, session.user_id!, session.bot_id!, workspace_id],
|
||||
});
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_sessions SET status = 'active', updated_at = ? WHERE id = ?`,
|
||||
values: [now, session.id],
|
||||
});
|
||||
|
||||
return { ...session, status: "active", updated_at: now };
|
||||
}
|
||||
return await activateBotSession({ session });
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import carryOverBotSession from "./carry-over-bot-session";
|
||||
import hasOpenSessionJob from "./has-open-session-job";
|
||||
import writeSessionContinuation from "./write-session-continuation";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The routine's or hook's latest session, full to the app setting.
|
||||
*/
|
||||
session: BUN_SQLITE_COBBLE_BOT_SESSIONS;
|
||||
user_id: number | string;
|
||||
bot_id: number;
|
||||
workspace_id?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Carries a routine's or a silent hook's own thread into its next session
|
||||
* once it's full (`writeSessionContinuation`), like Continue in a new
|
||||
* session does for the conversation: the summary opens the new session as
|
||||
* its first message and `previous_session_id` links it, with the same
|
||||
* routine or hook attached, still closed so no run takes the chat over.
|
||||
* Null when it can't move (the bot still has work in it) or there is
|
||||
* nothing to carry (the model wrote no summary and none was stored): the
|
||||
* run then lands in the full session, which never blocks it.
|
||||
*/
|
||||
export default async function rollOverLinkedSession({
|
||||
session,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
}: Params): Promise<number | null> {
|
||||
if (!session.id || (await hasOpenSessionJob({ session_id: session.id }))) return null;
|
||||
|
||||
const written = await writeSessionContinuation({
|
||||
session_id: session.id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
}).catch((error: unknown) => {
|
||||
logError({ title: "Couldn't write the summary to carry a session over", error }).catch(() => {});
|
||||
return null;
|
||||
});
|
||||
|
||||
const summary = written?.summary || session.summary?.trim();
|
||||
|
||||
if (!summary) return null;
|
||||
|
||||
const message = await carryOverBotSession({
|
||||
session_id: session.id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
summary,
|
||||
title: written?.title,
|
||||
allow_inactive: true,
|
||||
next_status: "closed",
|
||||
}).catch((error: unknown) => {
|
||||
logError({ title: "Couldn't carry a session over", error }).catch(() => {});
|
||||
return null;
|
||||
});
|
||||
|
||||
return message ? Number(message.session_id) : null;
|
||||
}
|
||||
@@ -9,10 +9,11 @@ type Params = {
|
||||
|
||||
/**
|
||||
* The one test for "a session a user can open": not one bot's part of a
|
||||
* crew request (`ask_id`, status `ask`) and not a hook's runs (`hook_id`,
|
||||
* status `hook`). Every query that lists or picks a conversation adds it,
|
||||
* or a hidden session leaks into the rail, a session list or the prompt.
|
||||
* crew request (`ask_id`, status `ask`). Every query that lists or picks a
|
||||
* conversation adds it, or a hidden session leaks into the rail, a session
|
||||
* list or the prompt. A routine's and a hook's threads are ordinary
|
||||
* sessions: they show and can be chatted in.
|
||||
*/
|
||||
export default function visibleSessionSql({ alias = "bot_sessions" }: Params = {}) {
|
||||
return `(${alias}.ask_id IS NULL AND ${alias}.hook_id IS NULL)`;
|
||||
}
|
||||
return `(${alias}.ask_id IS NULL)`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { SessionContinuePrompt } from "@/src/data/harness-prompts";
|
||||
import parseSessionName from "@/src/bots-queue/parse-session-name";
|
||||
import sessionNameTranscript from "@/src/bots-queue/session-name-transcript";
|
||||
import generateText from "@/src/harness/text/generate-text";
|
||||
import { runWithHarnessUsageScope } from "@/src/harness/usage/harness-usage-scope";
|
||||
import grabBotMessages from "../bots/grab-bot-messages";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
user_id: number | string;
|
||||
bot_id: number;
|
||||
workspace_id?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Has the bot's text model write what a session's next one needs to carry
|
||||
* on: its title and a summary of its latest messages (`SessionContinuePrompt`).
|
||||
* Null when the session has no messages or the model wrote no summary.
|
||||
* `continueBotSession` and the rollover of a routine's or hook's own
|
||||
* thread both carry this into a new session.
|
||||
*/
|
||||
export default async function writeSessionContinuation({
|
||||
session_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
}: Params): Promise<{ summary: string; title: string } | null> {
|
||||
const messages = await grabBotMessages({
|
||||
session_id,
|
||||
limit: AppData.BotSessionSummaryMessages,
|
||||
});
|
||||
|
||||
if (!messages.length) return null;
|
||||
|
||||
const result = await runWithHarnessUsageScope({
|
||||
scope: {
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id: workspace_id || null,
|
||||
session_id: Number(session_id),
|
||||
job_id: null,
|
||||
message_id: null,
|
||||
},
|
||||
task: () =>
|
||||
generateText({
|
||||
messages: [
|
||||
{ role: "system", content: SessionContinuePrompt },
|
||||
{ role: "user", content: sessionNameTranscript({ messages }) },
|
||||
],
|
||||
bot_id,
|
||||
workspace_id,
|
||||
}),
|
||||
});
|
||||
|
||||
const written = parseSessionName({ text: result.text });
|
||||
|
||||
return written?.summary ? written : null;
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import { logError } from "@/src/functions/backend/logger";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import grabSessionAskId from "../bot-sessions/grab-session-ask-id";
|
||||
import onAskJobEnded from "../asks/on-ask-job-ended";
|
||||
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
|
||||
import isUnattendedHookSession from "../bot-hooks/is-unattended-hook-session";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import jobTrackerTaskId from "./job-tracker-task-id";
|
||||
|
||||
@@ -170,10 +170,11 @@ export default async function completeBotJob({
|
||||
const user_id = await grabJobUserId({ job });
|
||||
|
||||
/**
|
||||
* A hook's run is followed by nobody, so it never shows on the bot's
|
||||
* face. A crew request's does: the bot answering it is working.
|
||||
* A silent hook's run is followed by nobody, so it never shows on the
|
||||
* bot's face. A crew request's does, and so does a hook that isn't
|
||||
* silent: the bot answering it is working.
|
||||
*/
|
||||
const in_hook = Boolean(await grabSessionHookId({ session_id: job.session_id }));
|
||||
const unattended = await isUnattendedHookSession({ session_id: job.session_id });
|
||||
|
||||
/**
|
||||
* The job is done and its answer saved, so what is left is clearing up:
|
||||
@@ -185,7 +186,7 @@ export default async function completeBotJob({
|
||||
|
||||
try {
|
||||
bot =
|
||||
!user_id || in_hook
|
||||
!user_id || unattended
|
||||
? null
|
||||
: needs_you
|
||||
? await setBotFace({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import followedSessionSql from "../bot-sessions/followed-session-sql";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
@@ -7,8 +8,8 @@ type Params = {
|
||||
*/
|
||||
user_id: number | string;
|
||||
/**
|
||||
* Leave out jobs in hidden sessions (a crew request's, a hook's),
|
||||
* which never show on the bot's face.
|
||||
* Leave out jobs the user doesn't follow (a crew request's, a silent
|
||||
* hook's), which never show on the bot's face.
|
||||
*/
|
||||
conversations_only?: boolean;
|
||||
};
|
||||
@@ -19,8 +20,8 @@ type Params = {
|
||||
export default async function countOpenBotJobs({ bot_id, user_id, conversations_only }: Params) {
|
||||
const res = await BunSQLite.sql<{ open: number }>({
|
||||
sql: `SELECT COUNT(*) AS open FROM bots_queue WHERE bot_id = ? AND status IN ('pending', 'processing')
|
||||
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL${
|
||||
conversations_only ? " AND ask_id IS NULL" : ""
|
||||
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ?${
|
||||
conversations_only ? ` AND ${followedSessionSql()}` : " AND ask_id IS NULL AND hook_id IS NULL"
|
||||
})`,
|
||||
values: [bot_id, user_id],
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotFace } from "@/src/dict/bot-dict";
|
||||
import { BotReplyJobTitle } from "@/src/dict/bot-queue-dict";
|
||||
import taskStatusLine from "@/src/utils/task-status-line";
|
||||
import followedSessionSql from "../bot-sessions/followed-session-sql";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
@@ -16,7 +17,7 @@ type Params = {
|
||||
* still running: thinking while a reply runs (it's short, and its chat
|
||||
* needs the row), else working on a task (in its workspace, if it runs in
|
||||
* one). Null when none is running. Work in a crew request's hidden session
|
||||
* or a hook's thread never counts: it shows there, never on the face.
|
||||
* or a silent hook's thread never counts: it shows there, never on the face.
|
||||
*/
|
||||
export default async function grabRunningBotJobFace({
|
||||
bot_id,
|
||||
@@ -27,7 +28,7 @@ export default async function grabRunningBotJobFace({
|
||||
sql: `SELECT q.kind, w.name AS workspace_name FROM bots_queue q
|
||||
LEFT JOIN workspaces w ON w.id = q.workspace_id
|
||||
WHERE q.bot_id = ? AND q.status = 'processing'
|
||||
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL AND ask_id IS NULL)
|
||||
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ${followedSessionSql()})
|
||||
ORDER BY q.id`,
|
||||
values: [bot_id, user_id],
|
||||
})
|
||||
|
||||
@@ -10,7 +10,7 @@ import grabJobUserId from "./grab-job-user-id";
|
||||
import { BotNeedsYouStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import grabSessionAskId from "../bot-sessions/grab-session-ask-id";
|
||||
import onAskJobEnded from "../asks/on-ask-job-ended";
|
||||
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
|
||||
import isUnattendedHookSession from "../bot-hooks/is-unattended-hook-session";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import jobTrackerTaskId from "./job-tracker-task-id";
|
||||
import pauseFailedPlanStep from "../bot-plans/pause-failed-plan-step";
|
||||
@@ -91,12 +91,13 @@ export default async function notifyBotJobFailed({
|
||||
if (paused_plan) await pushBotPlan(paused_plan);
|
||||
|
||||
/**
|
||||
* A hook's run is followed by nobody, so it never shows on the bot's
|
||||
* face. A crew request's does: the bot answering it is working.
|
||||
* A silent hook's run is followed by nobody, so it never shows on the
|
||||
* bot's face. A crew request's does, and so does a hook that isn't
|
||||
* silent: the bot answering it is working.
|
||||
*/
|
||||
const in_hook = Boolean(await grabSessionHookId({ session_id: job.session_id }));
|
||||
const unattended = await isUnattendedHookSession({ session_id: job.session_id });
|
||||
|
||||
const bot = user_id && !in_hook
|
||||
const bot = user_id && !unattended
|
||||
? await setBotFace({
|
||||
bot_id: job.bot_id,
|
||||
user_id,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import parseJobJson from "@/src/bots-queue/parse-job-json";
|
||||
import stopAsk from "../asks/stop-ask";
|
||||
import stopAsks from "../asks/stop-asks";
|
||||
import grabOpenAskBySession from "../asks/grab-open-ask-by-session";
|
||||
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
|
||||
import isUnattendedHookSession from "../bot-hooks/is-unattended-hook-session";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import attachJobTracesToMessage from "./attach-job-traces-to-message";
|
||||
|
||||
@@ -181,10 +181,10 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
|
||||
|
||||
for (const [session_id, job] of pickReportedJobs({ jobs })) {
|
||||
/**
|
||||
* A hook's call says it was stopped in its thread
|
||||
* (`recordHookCallResponse`).
|
||||
* A silent hook's call says it was stopped in its thread
|
||||
* (`recordHookCallResponse`), nowhere the user reads.
|
||||
*/
|
||||
if (await grabSessionHookId({ session_id })) continue;
|
||||
if (await isUnattendedHookSession({ session_id })) continue;
|
||||
|
||||
const message = await insertBotMessage({
|
||||
bot_id: Number(bot_id),
|
||||
|
||||
@@ -4,6 +4,7 @@ import chatBotsSql from "@/src/utils/crew-access/chat-bots-sql";
|
||||
import workspaceBotsSql from "@/src/utils/crew-access/workspace-bots-sql";
|
||||
import botFaceSql from "@/src/utils/bot-face-sql";
|
||||
import grabCrewRole from "../access/grab-crew-role";
|
||||
import followedSessionSql from "../bot-sessions/followed-session-sql";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -47,11 +48,11 @@ export default async function grabBots({
|
||||
sql += `FROM bots b\n`;
|
||||
sql += `LEFT JOIN (\n`;
|
||||
sql += ` SELECT bot_id, MAX(unread) AS unread, MAX(last_activity_at) AS last_activity_at\n`;
|
||||
sql += ` FROM bot_sessions WHERE workspace_id IS ? AND user_id = ? AND ask_id IS NULL AND hook_id IS NULL GROUP BY bot_id\n`;
|
||||
sql += ` FROM bot_sessions WHERE workspace_id IS ? AND user_id = ? AND ${followedSessionSql()} GROUP BY bot_id\n`;
|
||||
sql += `) t ON t.bot_id = b.id\n`;
|
||||
sql += `LEFT JOIN bot_messages lm ON lm.id = (\n`;
|
||||
sql += ` SELECT m.id FROM bot_messages m JOIN bot_sessions s ON s.id = m.session_id\n`;
|
||||
sql += ` WHERE m.bot_id = b.id AND m.workspace_id IS ? AND s.user_id = ? AND s.ask_id IS NULL AND s.hook_id IS NULL\n`;
|
||||
sql += ` WHERE m.bot_id = b.id AND m.workspace_id IS ? AND s.user_id = ? AND ${followedSessionSql({ alias: "s" })}\n`;
|
||||
sql += ` ORDER BY m.created_at DESC, m.id DESC\n`;
|
||||
sql += ` LIMIT 1\n`;
|
||||
sql += `)\n`;
|
||||
|
||||
@@ -3,6 +3,9 @@ import AppError from "@/src/utils/app-error";
|
||||
import grabUserBot from "../bots/grab-user-bot";
|
||||
import grabUserComputer from "./grab-user-computer";
|
||||
import assertCrewManager from "@/src/functions/backend/db/access/assert-crew-manager";
|
||||
import applyHostDirectoryGrant from "../host-directories/apply-host-directory-grant";
|
||||
import grabComputerHostDirectoryIds from "../host-directories/grab-computer-host-directory-ids";
|
||||
import reconcileComputerHostDirectories from "../host-directories/reconcile-computer-host-directories";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -12,7 +15,9 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Gives one of the user's bots access to one of their computers. Adding a
|
||||
* bot that already has access is a no-op.
|
||||
* bot that already has access is a no-op. A host directory linked to the
|
||||
* computer is mounted in the bot's own folder, so the computer is set up
|
||||
* again to give it one (`reconcileComputerHostDirectories`).
|
||||
*/
|
||||
export default async function addBotToComputer({
|
||||
user_id,
|
||||
@@ -32,4 +37,19 @@ export default async function addBotToComputer({
|
||||
sql: `INSERT OR IGNORE INTO bot_computers (bot_id, computer_id, created_at, updated_at) VALUES (?, ?, ?, ?)`,
|
||||
values: [bot.id, computer.id, Date.now(), Date.now()],
|
||||
});
|
||||
|
||||
await reconcileComputerHostDirectories({ computer_id: Number(computer.id) });
|
||||
|
||||
/**
|
||||
* It reaches the folders mounted on that computer now, so each gives it
|
||||
* access, as every bot there has it.
|
||||
*/
|
||||
for (const host_directory_id of await grabComputerHostDirectoryIds({
|
||||
computer_id: Number(computer.id),
|
||||
})) {
|
||||
await applyHostDirectoryGrant({
|
||||
host_directory_id,
|
||||
retry: false,
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
computer_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A computer's container `metadata` as it was last written (a JSON text),
|
||||
* or null when it has no container. Read to compare what a container was
|
||||
* made with (its host directories) to what it should have now.
|
||||
*/
|
||||
export default async function grabComputerMetadata({ computer_id }: Params) {
|
||||
const row = (
|
||||
await BunSQLite.sql<{ metadata?: string | null }>({
|
||||
sql: `SELECT co.metadata AS metadata FROM computers c
|
||||
JOIN containers co ON co.id = c.container_id
|
||||
WHERE c.id = ?`,
|
||||
values: [Number(computer_id)],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
return row?.metadata || null;
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import parseJobJson from "@/src/bots-queue/parse-job-json";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import createComputerContainer from "@/src/functions/backend/docker/create-computer-container";
|
||||
import inspectDockerContainer from "@/src/functions/backend/docker/inspect-docker-container";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import logEvent, { logError } from "@/src/functions/backend/logger";
|
||||
import prepareComputerBrowserDir from "./prepare-computer-browser-dir";
|
||||
import prepareComputerDataDir from "./prepare-computer-data-dir";
|
||||
import computerBrowserEnv from "@/src/utils/computer-browser-env";
|
||||
@@ -12,6 +12,9 @@ import parseComputerBrowserSettings from "@/src/utils/parse-computer-browser-set
|
||||
import keepComputerSetupAlive from "./keep-computer-setup-alive";
|
||||
import pushComputerUpdate from "./push-computer-update";
|
||||
import syncComputerBrowserPolicy from "./sync-computer-browser-policy";
|
||||
import grabComputerHostDirectories from "../host-directories/grab-computer-host-directories";
|
||||
import prepareHostDirectoryMounts from "../host-directories/prepare-host-directory-mounts";
|
||||
import { hostDirectoryMountEntry } from "@/src/utils/host-directory-mounts-changed";
|
||||
|
||||
type Params = {
|
||||
computer_id: number;
|
||||
@@ -68,6 +71,28 @@ export default async function provisionComputer({ computer_id, fresh, pull }: Pa
|
||||
|
||||
const data_dir = await prepareComputerDataDir({ computer_id, fresh });
|
||||
const browser_dir = await prepareComputerBrowserDir({ computer_id, fresh });
|
||||
|
||||
/**
|
||||
* The host directories this computer should mount now. A mount only
|
||||
* exists from the container's creation, so what it was made with is
|
||||
* kept (`metadata.host_mounts`) for `syncComputers` to compare.
|
||||
*/
|
||||
const { mounts: host_mounts, skipped } =
|
||||
await grabComputerHostDirectories({ computer_id });
|
||||
await prepareHostDirectoryMounts({
|
||||
computer_dir: data_dir,
|
||||
mounts: host_mounts,
|
||||
});
|
||||
|
||||
if (skipped.length) {
|
||||
await logEvent({
|
||||
title: "a host directory isn't mounted",
|
||||
category: "system",
|
||||
plain_text: `${skipped.length} host ${skipped.length == 1 ? "directory" : "directories"} ${skipped.length == 1 ? "isn't" : "aren't"} on the host machine any more, so ${skipped.length == 1 ? "it isn't" : "they aren't"} mounted: ${skipped.map((item) => item.source).join(", ")}.`,
|
||||
metadata: { computer_id, sources: skipped.map((item) => item.source) },
|
||||
});
|
||||
}
|
||||
|
||||
const created = await createComputerContainer({
|
||||
computer_id,
|
||||
name: row.name,
|
||||
@@ -79,6 +104,11 @@ export default async function provisionComputer({ computer_id, fresh, pull }: Pa
|
||||
settings: parseComputerBrowserSettings({ text: row.browser_settings }),
|
||||
fallback_timezone: process.env.TZ,
|
||||
}),
|
||||
host_mounts: host_mounts.map((mount) => ({
|
||||
source: mount.source,
|
||||
target: mount.target,
|
||||
read_only: mount.access == "read-only",
|
||||
})),
|
||||
pull,
|
||||
});
|
||||
|
||||
@@ -102,6 +132,7 @@ export default async function provisionComputer({ computer_id, fresh, pull }: Pa
|
||||
browser_dir,
|
||||
browser_host_dir: created.browser_host_dir,
|
||||
layout: AppData.ComputerWorkspaceLayout,
|
||||
host_mounts: host_mounts.map((mount) => hostDirectoryMountEntry({ mount })),
|
||||
}),
|
||||
Date.now(),
|
||||
Date.now(),
|
||||
|
||||
@@ -12,10 +12,21 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Deletes one of the user's schedules. A run already queued carries on.
|
||||
* The sessions its runs held stay, as the user's own threads (they're
|
||||
* ordinary sessions once no routine owns them).
|
||||
*/
|
||||
export default async function deleteCronJob({ user_id, cron_job_id, bot_id }: Params) {
|
||||
const cron_job = await grabUserCronJob({ user_id, cron_job_id, bot_id });
|
||||
|
||||
const detached = await BunSQLite.sql({
|
||||
sql: `UPDATE bot_sessions SET routine_id = NULL, updated_at = ? WHERE routine_id = ?`,
|
||||
values: [Date.now(), cron_job.id!],
|
||||
});
|
||||
|
||||
if (!detached.success) {
|
||||
throw new Error(`Couldn't detach the routine's sessions: ${detached.error}`);
|
||||
}
|
||||
|
||||
const res = await BunSQLite.sql({
|
||||
sql: `DELETE FROM cron_jobs WHERE id = ?`,
|
||||
values: [cron_job.id!],
|
||||
@@ -26,4 +37,4 @@ export default async function deleteCronJob({ user_id, cron_job_id, bot_id }: Pa
|
||||
}
|
||||
|
||||
return cron_job;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
|
||||
import logEvent, { logError } from "@/src/functions/backend/logger";
|
||||
import nextCronRun from "@/src/utils/next-cron-run";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import ensureBotSession from "../bot-sessions/ensure-bot-session";
|
||||
import ensureRoutineSession from "../bot-sessions/ensure-routine-session";
|
||||
import enqueueBotJob from "../bots-queue/enqueue-bot-job";
|
||||
import isBotJobOpen from "../bots-queue/is-bot-job-open";
|
||||
import grabBotComputers from "../computers/grab-bot-computers";
|
||||
@@ -17,7 +17,8 @@ type Params = {
|
||||
/**
|
||||
* Runs one due schedule: moves it to its next run (claimed atomically, so
|
||||
* a run is never queued twice), then queues its brief as a task in the
|
||||
* bot's active session there, on its computer or the bot's current one.
|
||||
* routine's own session there (`ensureRoutineSession`, never the active
|
||||
* chat), on its computer or the bot's current one.
|
||||
* A run is skipped while the last one is still queued or working. It
|
||||
* turns itself off once it has no next run or has done its `max_runs`.
|
||||
* Why a run couldn't be queued is kept in `last_error`.
|
||||
@@ -48,11 +49,7 @@ export default async function fireCronJob({ cron_job, now = Date.now() }: Params
|
||||
return;
|
||||
}
|
||||
|
||||
const session = await ensureBotSession({
|
||||
user_id: cron_job.user_id!,
|
||||
bot_id: cron_job.bot_id!,
|
||||
workspace_id: cron_job.workspace_id || null,
|
||||
});
|
||||
const session_id = await ensureRoutineSession({ cron_job });
|
||||
|
||||
const computer_id =
|
||||
cron_job.computer_id ||
|
||||
@@ -66,7 +63,7 @@ export default async function fireCronJob({ cron_job, now = Date.now() }: Params
|
||||
const job_id = await enqueueBotJob({
|
||||
user_id: cron_job.user_id!,
|
||||
bot_id: cron_job.bot_id!,
|
||||
session_id: session.id!,
|
||||
session_id,
|
||||
title: cron_job.title || "Scheduled task",
|
||||
instructions: `${cron_job.instructions || ""}\n\nThis is a scheduled run of your schedule #${id} (\`${schedule}\`, UTC). Do the work; don't create another schedule for it.`,
|
||||
params: { schedule_id: id, schedule, run: Number(cron_job.run_count || 0) + 1 },
|
||||
|
||||
@@ -23,7 +23,8 @@ type Params = {
|
||||
|
||||
/**
|
||||
* The user's schedules with their bot (its face as the user sees it) and
|
||||
* workspace names, the next to run first and paused ones last. Given a
|
||||
* workspace names, the next to run first and paused ones last, each with
|
||||
* the id of the session its latest run left its messages in. Given a
|
||||
* `bot_id` and a `workspace_id` (null for its own chat) it is one
|
||||
* conversation's: the routines that run right there.
|
||||
*/
|
||||
@@ -56,7 +57,8 @@ export default async function grabCronJobs({
|
||||
|
||||
const res = await BunSQLite.sql<CronJobWithNames>({
|
||||
sql: `SELECT c.*, b.name AS bot_name, b.kind AS bot_kind, b.hue AS bot_hue, b.color AS bot_color, b.stone AS bot_stone, ${face.sql},
|
||||
b.image_media_id AS bot_image_media_id, w.name AS workspace_name
|
||||
b.image_media_id AS bot_image_media_id, w.name AS workspace_name,
|
||||
(SELECT r.id FROM bot_sessions r WHERE r.routine_id = c.id ORDER BY r.id DESC LIMIT 1) AS latest_session_id
|
||||
FROM cron_jobs c
|
||||
JOIN bots b ON b.id = c.bot_id
|
||||
LEFT JOIN workspaces w ON w.id = c.workspace_id
|
||||
|
||||
@@ -108,6 +108,11 @@ export default async function handOverCronJob({
|
||||
throw new AppError(`Couldn't hand the routine over: ${res.msg || res.error}`);
|
||||
}
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_sessions SET routine_id = NULL, updated_at = ? WHERE routine_id = ?`,
|
||||
values: [Date.now(), cron_job.id!],
|
||||
});
|
||||
|
||||
const session = await ensureBotSession({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
|
||||
|
||||
await pushBotNotice({
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_HOST_DIRECTORIES } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import grabComputerImage from "@/src/functions/backend/docker/grab-computer-image";
|
||||
import grantHostDirectory from "@/src/functions/backend/docker/grant-host-directory";
|
||||
import logEvent from "@/src/functions/backend/logger";
|
||||
import checkHostDirectory from "./check-host-directory";
|
||||
import grabHostDirectories from "./grab-host-directories";
|
||||
import grabHostDirectoryComputers from "./grab-host-directory-computers";
|
||||
|
||||
type Params = {
|
||||
host_directory_id: number | string;
|
||||
/**
|
||||
* Who is asking, when a person is: the computers are checked again
|
||||
* afterwards, so the page shows what the grant did. Left out by the
|
||||
* sync, which only keeps the folder in step with the crew.
|
||||
*/
|
||||
user_id?: number | string;
|
||||
/**
|
||||
* Whether a grant that failed last time is tried again (default). The
|
||||
* sync leaves it off, so a folder whose permissions the user hasn't
|
||||
* fixed yet doesn't start a container every five minutes.
|
||||
*/
|
||||
retry?: boolean;
|
||||
};
|
||||
|
||||
export type HostDirectoryGrantResult = {
|
||||
/**
|
||||
* The accounts that see the folder now.
|
||||
*/
|
||||
uids: number[];
|
||||
/**
|
||||
* The accounts the folder was granted to, as last recorded.
|
||||
*/
|
||||
granted: number[];
|
||||
added: number[];
|
||||
removed: number[];
|
||||
error: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gives the folder to every bot that sees it, and takes it from the ones
|
||||
* that no longer do: the difference between the accounts the crew has now
|
||||
* (`hostDirectoryLinkUids`, over the directory's links) and the ones it was
|
||||
* granted to last time, applied by a throwaway container as root
|
||||
* (`grantHostDirectory`, ACL entries only). A link or a new bot in a
|
||||
* workspace is all it takes for the bots to be able to work there; the
|
||||
* folder's owner, group and mode are never touched.
|
||||
*
|
||||
* Nothing runs when the accounts are the same as last time, unless the last
|
||||
* try failed, which is tried again.
|
||||
*/
|
||||
export default async function applyHostDirectoryGrant({
|
||||
host_directory_id,
|
||||
user_id,
|
||||
retry = true,
|
||||
}: Params): Promise<HostDirectoryGrantResult> {
|
||||
const directory = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_HOST_DIRECTORIES>({
|
||||
sql: `SELECT * FROM host_directories WHERE id = ?`,
|
||||
values: [host_directory_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!directory?.id) {
|
||||
throw new AppError("Host directory not found.");
|
||||
}
|
||||
|
||||
const source = String(directory.source || "");
|
||||
const links = (await grabHostDirectories({ host_directory_id }))[0];
|
||||
|
||||
const uids = [
|
||||
...new Set(
|
||||
[...(links?.computers || []), ...(links?.workspaces || [])].flatMap(
|
||||
(link) => link.uids || [],
|
||||
),
|
||||
),
|
||||
].sort((a, b) => a - b);
|
||||
|
||||
const previous = (
|
||||
await BunSQLite.sql<{
|
||||
uids: string | null;
|
||||
error: string | null;
|
||||
granted_at: number | null;
|
||||
}>({
|
||||
sql: `SELECT uids, error, granted_at FROM host_directory_grants WHERE host_directory_id = ?`,
|
||||
values: [directory.id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
const granted = parseUids({ text: previous?.uids });
|
||||
|
||||
/**
|
||||
* A failure is tried again whole: the entries that did get applied are
|
||||
* set again, which is the same as leaving them.
|
||||
*/
|
||||
const added =
|
||||
retry && previous?.error
|
||||
? uids
|
||||
: uids.filter((uid) => !granted.includes(uid));
|
||||
const removed = granted.filter((uid) => !uids.includes(uid));
|
||||
|
||||
if (!added.length && !removed.length && !(retry && previous?.error)) {
|
||||
return { uids, granted, added, removed, error: null };
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const run = await grantHostDirectory({
|
||||
image: await grabComputerImage(),
|
||||
source,
|
||||
added,
|
||||
removed,
|
||||
});
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `INSERT INTO host_directory_grants (host_directory_id, uids, granted_at, error, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(host_directory_id) DO UPDATE SET
|
||||
uids = excluded.uids,
|
||||
granted_at = excluded.granted_at,
|
||||
error = excluded.error,
|
||||
updated_at = excluded.updated_at`,
|
||||
values: [
|
||||
directory.id,
|
||||
JSON.stringify(run.error ? granted : uids),
|
||||
run.error ? previous?.granted_at || null : now,
|
||||
run.error,
|
||||
now,
|
||||
now,
|
||||
],
|
||||
});
|
||||
|
||||
if (run.error) {
|
||||
await logEvent({
|
||||
title: "giving bots access to a host directory failed",
|
||||
category: "system",
|
||||
plain_text: `Host directory #${directory.id} (${source}) couldn't be given to the bots: ${run.error}`,
|
||||
details: [
|
||||
{ label: "Folder", value: source },
|
||||
{ label: "Reason", value: run.error },
|
||||
],
|
||||
metadata: { host_directory_id: Number(directory.id) },
|
||||
});
|
||||
|
||||
return { uids, granted, added, removed, error: run.error };
|
||||
}
|
||||
|
||||
if (added.length || removed.length) {
|
||||
await logEvent({
|
||||
title: "bots were given access to a host directory",
|
||||
category: "system",
|
||||
plain_text: `Host directory #${directory.id} (${source}): ${added.length} account(s) given access, ${removed.length} taken away.`,
|
||||
details: [
|
||||
{ label: "Folder", value: source },
|
||||
{ label: "Given access", value: added },
|
||||
{ label: "Access taken away", value: removed },
|
||||
],
|
||||
metadata: {
|
||||
host_directory_id: Number(directory.id),
|
||||
added,
|
||||
removed,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (user_id) {
|
||||
for (const computer_id of await grabHostDirectoryComputers({
|
||||
host_directory_id: directory.id,
|
||||
})) {
|
||||
await checkHostDirectory({
|
||||
user_id,
|
||||
host_directory_id: directory.id,
|
||||
computer_id,
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
return { uids, granted: uids, added, removed, error: null };
|
||||
}
|
||||
|
||||
function parseUids({ text }: { text?: string | null }): number[] {
|
||||
if (!text) return [];
|
||||
|
||||
try {
|
||||
const value = JSON.parse(text);
|
||||
|
||||
if (!Array.isArray(value)) return [];
|
||||
|
||||
return value
|
||||
.map((uid) => Number(uid))
|
||||
.filter((uid) => Number.isInteger(uid) && uid > 0);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import grabCrewRole from "../access/grab-crew-role";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Throws unless the user is a super admin. A host directory is a folder on
|
||||
* the machine running Cobble, outside anything the app keeps, so only the
|
||||
* install's owner decides what a computer may mount and write in.
|
||||
*/
|
||||
export default async function assertHostDirectoryManager({ user_id }: Params) {
|
||||
if ((await grabCrewRole({ user_id })) != "super_admin") {
|
||||
throw new AppError(
|
||||
`Only a super admin can add or change host directories, since a mounted folder is on the host machine itself.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_HOST_DIRECTORIES } from "@/db/types/db";
|
||||
import type { HostDirectoryCheck } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import hostDirectoryAccount from "@/src/utils/host-directory-account";
|
||||
import grabComputerImage from "@/src/functions/backend/docker/grab-computer-image";
|
||||
import probeHostDirectory from "@/src/functions/backend/docker/probe-host-directory";
|
||||
import assertHostDirectoryManager from "./assert-host-directory-manager";
|
||||
import grabComputerHostDirectories from "./grab-computer-host-directories";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
host_directory_id: number | string;
|
||||
computer_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks a host directory on one computer: whether its folder is still
|
||||
* there, and whether every bot that sees it can read and write in it as its
|
||||
* own account (`probeHostDirectory`, one throwaway container, which only
|
||||
* tests). Mounted in the computer, that is every bot reaching the computer;
|
||||
* mounted in a workspace, only the bots working there and the coordinator.
|
||||
* The answer is stored (`host_directory_checks`) and returned; Cobble never
|
||||
* changes the host folder's permissions itself.
|
||||
*/
|
||||
export default async function checkHostDirectory({
|
||||
user_id,
|
||||
host_directory_id,
|
||||
computer_id,
|
||||
}: Params): Promise<HostDirectoryCheck> {
|
||||
await assertHostDirectoryManager({ user_id });
|
||||
|
||||
const directory = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_HOST_DIRECTORIES>({
|
||||
sql: `SELECT * FROM host_directories WHERE id = ?`,
|
||||
values: [host_directory_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!directory?.id) {
|
||||
throw new AppError("Host directory not found.");
|
||||
}
|
||||
|
||||
const access = await grabComputerHostDirectories({ computer_id });
|
||||
|
||||
const { bots, links } = access;
|
||||
|
||||
const link = links.find((row) => row.host_directory_id == directory.id);
|
||||
|
||||
if (!link) {
|
||||
throw new AppError("That host directory isn't mounted on this computer.");
|
||||
}
|
||||
|
||||
const members =
|
||||
link.scope == "workspace"
|
||||
? new Set(
|
||||
(
|
||||
(
|
||||
await BunSQLite.sql<{ bot_id: number }>({
|
||||
sql: `SELECT bot_id FROM workspace_bots WHERE workspace_id = ?`,
|
||||
values: [Number(link.workspace_id)],
|
||||
})
|
||||
).payload || []
|
||||
).map((row) => Number(row.bot_id)),
|
||||
)
|
||||
: null;
|
||||
|
||||
/** A workspace's mount is in its shared folder, so only its bots see it. */
|
||||
const seen = members
|
||||
? bots.filter((bot) => bot.kind == "coordinator" || members.has(bot.id))
|
||||
: bots;
|
||||
|
||||
const check = await probeHostDirectory({
|
||||
image: await grabComputerImage(),
|
||||
source: String(directory.source || ""),
|
||||
accounts: seen.map((bot) => {
|
||||
const workspace_ids = members ? [Number(link.workspace_id)] : [];
|
||||
|
||||
return {
|
||||
bot_id: bot.id,
|
||||
name: bot.kind == "coordinator" ? "coordinator" : `bot #${bot.id}`,
|
||||
...hostDirectoryAccount({
|
||||
bot_id: bot.id,
|
||||
bot_kind: bot.kind,
|
||||
workspace_ids,
|
||||
}),
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
const stored: HostDirectoryCheck = {
|
||||
...check,
|
||||
computer_id: Number(computer_id),
|
||||
checked_at: Date.now(),
|
||||
};
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
const saved = await BunSQLite.sql({
|
||||
sql: `INSERT INTO host_directory_checks (host_directory_id, computer_id, last_check, checked_at, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(host_directory_id, computer_id) DO UPDATE SET
|
||||
last_check = excluded.last_check,
|
||||
checked_at = excluded.checked_at,
|
||||
updated_at = excluded.updated_at`,
|
||||
values: [directory.id, computer_id, JSON.stringify(stored), now, now, now],
|
||||
});
|
||||
|
||||
/**
|
||||
* A write that fails is said so: the answer is what the page shows, and
|
||||
* losing it silently left a folder looking unchecked after a check.
|
||||
*/
|
||||
if (!saved.success) {
|
||||
throw new AppError(`The check couldn't be saved: ${saved.error || "the database refused it"}.`);
|
||||
}
|
||||
|
||||
return stored;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_HOST_DIRECTORIES, BunSQLiteTables } from "@/db/types/db";
|
||||
import {
|
||||
HostDirectoryNameMaxChars,
|
||||
HostDirectorySourceMaxChars,
|
||||
} from "@/src/dict/host-directory-dict";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import hostDirectoryPath from "@/src/utils/host-directory-path";
|
||||
import makeHostDirectorySlug from "@/src/utils/make-host-directory-slug";
|
||||
import assertHostDirectoryManager from "./assert-host-directory-manager";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
name: string;
|
||||
/**
|
||||
* Its absolute path on the host machine.
|
||||
*/
|
||||
source: string;
|
||||
/**
|
||||
* Paths that can't be mounted (the app's own data, besides the host's
|
||||
* system folders `hostDirectoryPath` always refuses).
|
||||
*/
|
||||
reserved?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a folder on the host machine (Settings > Host directories). Nothing
|
||||
* is mounted until it is linked to a computer or a workspace. Its `slug`
|
||||
* (the name it is mounted under) is made from its name once and kept, so
|
||||
* moving it around in a computer's folder never follows a rename.
|
||||
*/
|
||||
export default async function createHostDirectory({
|
||||
user_id,
|
||||
name,
|
||||
source,
|
||||
reserved = [],
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_HOST_DIRECTORIES> {
|
||||
await assertHostDirectoryManager({ user_id });
|
||||
|
||||
const clean_name = String(name || "").trim();
|
||||
|
||||
if (!clean_name) {
|
||||
throw new AppError("A host directory needs a name.");
|
||||
}
|
||||
|
||||
if (clean_name.length > HostDirectoryNameMaxChars) {
|
||||
throw new AppError(`A host directory's name can't be longer than ${HostDirectoryNameMaxChars} characters.`);
|
||||
}
|
||||
|
||||
if (/[\0\n\r]/.test(clean_name)) {
|
||||
throw new AppError("A host directory's name can't have line breaks.");
|
||||
}
|
||||
|
||||
const clean_source = hostDirectoryPath({ source, reserved });
|
||||
|
||||
if (clean_source.length > HostDirectorySourceMaxChars) {
|
||||
throw new AppError(`A host directory's path can't be longer than ${HostDirectorySourceMaxChars} characters.`);
|
||||
}
|
||||
|
||||
const taken = await BunSQLite.sql<{ slug: string }>({
|
||||
sql: `SELECT slug FROM host_directories`,
|
||||
values: [],
|
||||
});
|
||||
|
||||
const slug = makeHostDirectorySlug({
|
||||
name: clean_name,
|
||||
taken: (taken.payload || []).map((row) => row.slug),
|
||||
});
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
const result = await BunSQLite.insert<
|
||||
BUN_SQLITE_COBBLE_HOST_DIRECTORIES,
|
||||
(typeof BunSQLiteTables)[number]
|
||||
>({
|
||||
table: "host_directories",
|
||||
data: [
|
||||
{
|
||||
name: clean_name,
|
||||
source: clean_source,
|
||||
slug,
|
||||
created_by: Number(user_id),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return {
|
||||
id: Number(result.singleRes?.id || result.postInsertReturn?.insertId),
|
||||
name: clean_name,
|
||||
source: clean_source,
|
||||
slug,
|
||||
created_by: Number(user_id),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
} as BUN_SQLITE_COBBLE_HOST_DIRECTORIES;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import fs from "fs/promises";
|
||||
import type { BUN_SQLITE_COBBLE_HOST_DIRECTORIES } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import applyHostDirectoryGrant from "./apply-host-directory-grant";
|
||||
import assertHostDirectoryManager from "./assert-host-directory-manager";
|
||||
import grabComputerHostDirectories from "./grab-computer-host-directories";
|
||||
import grabHostDirectoryComputers from "./grab-host-directory-computers";
|
||||
import reconcileComputerHostDirectories from "./reconcile-computer-host-directories";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
host_directory_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a host directory with its links and checks. The folder on the
|
||||
* host machine is untouched, and so is what a bot already put in it: only
|
||||
* the mounts go, the next time each computer is set up again. The empty
|
||||
* folders left where they were mounted are removed.
|
||||
*/
|
||||
export default async function deleteHostDirectory({
|
||||
user_id,
|
||||
host_directory_id,
|
||||
}: Params) {
|
||||
await assertHostDirectoryManager({ user_id });
|
||||
|
||||
const directory = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_HOST_DIRECTORIES>({
|
||||
sql: `SELECT * FROM host_directories WHERE id = ?`,
|
||||
values: [host_directory_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!directory?.id) {
|
||||
throw new AppError("Host directory not found.");
|
||||
}
|
||||
|
||||
const computer_ids = await grabHostDirectoryComputers({
|
||||
host_directory_id: directory.id,
|
||||
});
|
||||
|
||||
const destinations: string[] = [];
|
||||
|
||||
for (const computer_id of computer_ids) {
|
||||
const { mounts } = await grabComputerHostDirectories({ computer_id });
|
||||
|
||||
destinations.push(
|
||||
...mounts
|
||||
.filter((mount) => mount.host_directory_id == directory.id)
|
||||
.map((mount) => mount.destination),
|
||||
);
|
||||
}
|
||||
|
||||
/** Foreign keys are off outside the server, so every child row goes by hand. */
|
||||
for (const sql of [
|
||||
`DELETE FROM host_directory_checks WHERE host_directory_id = ?`,
|
||||
`DELETE FROM host_directory_computers WHERE host_directory_id = ?`,
|
||||
`DELETE FROM host_directory_workspaces WHERE host_directory_id = ?`,
|
||||
]) {
|
||||
const res = await BunSQLite.sql({ sql, values: [directory.id] });
|
||||
|
||||
if (!res.success) {
|
||||
throw new AppError("Couldn't delete the host directory.");
|
||||
}
|
||||
}
|
||||
|
||||
for (const computer_id of computer_ids) {
|
||||
await reconcileComputerHostDirectories({ computer_id });
|
||||
}
|
||||
|
||||
/**
|
||||
* With no links left the accounts it was granted to lose it, so a folder
|
||||
* the user shares again later starts from where they left it. Its row
|
||||
* has to be there for the grant to read, so it goes last.
|
||||
*/
|
||||
await applyHostDirectoryGrant({ host_directory_id: directory.id }).catch(
|
||||
() => {},
|
||||
);
|
||||
|
||||
for (const sql of [
|
||||
`DELETE FROM host_directory_grants WHERE host_directory_id = ?`,
|
||||
`DELETE FROM host_directories WHERE id = ?`,
|
||||
]) {
|
||||
const res = await BunSQLite.sql({ sql, values: [directory.id] });
|
||||
|
||||
if (!res.success) {
|
||||
throw new AppError("Couldn't delete the host directory.");
|
||||
}
|
||||
}
|
||||
|
||||
for (const destination of destinations) {
|
||||
await fs.rmdir(destination).catch(() => {
|
||||
/**
|
||||
* Still mounted (the computer is busy and will be set up again
|
||||
* later), or holding something. Neither is an error here.
|
||||
*/
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type {
|
||||
BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS,
|
||||
BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS,
|
||||
BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES,
|
||||
} from "@/db/types/db";
|
||||
import type { HostDirectoryAccess } from "@/src/dict/host-directory-dict";
|
||||
import type { HostDirectoryCheck } from "@/src/types";
|
||||
import parseHostDirectoryCheck from "@/src/utils/parse-host-directory-check";
|
||||
import hostDirectoryMountPlan, {
|
||||
type HostDirectoryMount,
|
||||
type HostDirectoryMountSkip,
|
||||
} from "@/src/utils/host-directory-mount-plan";
|
||||
import grabComputerDataDir from "../computers/grab-computer-data-dir";
|
||||
|
||||
type Params = {
|
||||
computer_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A host directory as one computer sees it: linked to the computer itself,
|
||||
* or to one of its workspaces.
|
||||
*/
|
||||
export type ComputerHostDirectoryLink = {
|
||||
host_directory_id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
source: string;
|
||||
access: HostDirectoryAccess;
|
||||
scope: "computer" | "workspace";
|
||||
workspace_id?: number | null;
|
||||
/** Whether a delete inside the folder waits for the user's approval. */
|
||||
gate_deletes: boolean;
|
||||
check: HostDirectoryCheck | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The host directories mounted into a computer (`hostDirectoryMountPlan`):
|
||||
* its own links, and those of the workspaces joined to it, with the bots
|
||||
* that reach it deciding where a computer link goes. A link whose last
|
||||
* check found the folder missing is skipped, so docker never makes it as
|
||||
* root. Read by `provisionComputer` (what to mount) and by the settings
|
||||
* pages (what is mounted, and what its last check found).
|
||||
*/
|
||||
export default async function grabComputerHostDirectories({
|
||||
computer_id,
|
||||
}: Params): Promise<{
|
||||
computer_dir: string;
|
||||
bots: { id: number; kind: string }[];
|
||||
links: ComputerHostDirectoryLink[];
|
||||
mounts: HostDirectoryMount[];
|
||||
skipped: HostDirectoryMountSkip[];
|
||||
}> {
|
||||
const computer_dir = await grabComputerDataDir({ computer_id });
|
||||
|
||||
const [computer_rows, workspace_rows, bots, checks] = await Promise.all([
|
||||
BunSQLite.sql<
|
||||
BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS & {
|
||||
name: string;
|
||||
slug: string;
|
||||
source: string;
|
||||
}
|
||||
>({
|
||||
sql: `SELECT hdc.*, hd.name AS name, hd.slug AS slug, hd.source AS source
|
||||
FROM host_directory_computers hdc
|
||||
JOIN host_directories hd ON hd.id = hdc.host_directory_id
|
||||
WHERE hdc.computer_id = ?
|
||||
ORDER BY hd.name COLLATE NOCASE ASC, hd.id ASC`,
|
||||
values: [computer_id],
|
||||
}),
|
||||
BunSQLite.sql<
|
||||
BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & {
|
||||
name: string;
|
||||
slug: string;
|
||||
source: string;
|
||||
}
|
||||
>({
|
||||
sql: `SELECT hdw.*, hd.name AS name, hd.slug AS slug, hd.source AS source
|
||||
FROM host_directory_workspaces hdw
|
||||
JOIN host_directories hd ON hd.id = hdw.host_directory_id
|
||||
JOIN workspace_computers wc ON wc.workspace_id = hdw.workspace_id
|
||||
WHERE wc.computer_id = ?
|
||||
ORDER BY hd.name COLLATE NOCASE ASC, hd.id ASC`,
|
||||
values: [computer_id],
|
||||
}),
|
||||
BunSQLite.sql<{ id: number; kind: string }>({
|
||||
sql: `SELECT DISTINCT b.id, b.kind FROM bots b
|
||||
WHERE b.kind = 'coordinator'
|
||||
OR b.id IN (SELECT bot_id FROM bot_computers WHERE computer_id = ?)
|
||||
OR b.id IN (
|
||||
SELECT wb.bot_id FROM workspace_bots wb
|
||||
JOIN workspace_computers wc ON wc.workspace_id = wb.workspace_id
|
||||
WHERE wc.computer_id = ?
|
||||
)
|
||||
ORDER BY b.id ASC`,
|
||||
values: [computer_id, computer_id],
|
||||
}),
|
||||
BunSQLite.sql<BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS>({
|
||||
sql: `SELECT * FROM host_directory_checks WHERE computer_id = ?`,
|
||||
values: [computer_id],
|
||||
}),
|
||||
]);
|
||||
|
||||
const checked_on = (host_directory_id: number | string) => {
|
||||
const row = (checks.payload || []).find(
|
||||
(check) => check.host_directory_id == Number(host_directory_id),
|
||||
);
|
||||
|
||||
return parseHostDirectoryCheck({ text: row?.last_check });
|
||||
};
|
||||
|
||||
const links: ComputerHostDirectoryLink[] = [
|
||||
...(computer_rows.payload || []).map(({ name, slug, source, ...row }) => ({
|
||||
host_directory_id: Number(row.host_directory_id),
|
||||
name,
|
||||
slug,
|
||||
source,
|
||||
access: (row.access || "read-write") as HostDirectoryAccess,
|
||||
scope: "computer" as const,
|
||||
gate_deletes: Number(row.gate_deletes) != 0,
|
||||
check: checked_on(Number(row.host_directory_id)),
|
||||
})),
|
||||
...(workspace_rows.payload || []).map(({ name, slug, source, ...row }) => ({
|
||||
host_directory_id: Number(row.host_directory_id),
|
||||
name,
|
||||
slug,
|
||||
source,
|
||||
access: (row.access || "read-write") as HostDirectoryAccess,
|
||||
scope: "workspace" as const,
|
||||
workspace_id: Number(row.workspace_id),
|
||||
gate_deletes: Number(row.gate_deletes) != 0,
|
||||
check: checked_on(Number(row.host_directory_id)),
|
||||
})),
|
||||
];
|
||||
|
||||
const missing = links
|
||||
.filter((link) => {
|
||||
const accounts = link.check?.accounts || [];
|
||||
|
||||
return accounts.length > 0 && !accounts.some((account) => account.readable);
|
||||
})
|
||||
.map((link) => link.host_directory_id);
|
||||
|
||||
const plan = hostDirectoryMountPlan({
|
||||
computer_dir,
|
||||
computer_links: links
|
||||
.filter((link) => link.scope == "computer")
|
||||
.map((link) => ({
|
||||
host_directory_id: link.host_directory_id,
|
||||
slug: link.slug,
|
||||
source: link.source,
|
||||
access: link.access,
|
||||
})),
|
||||
workspace_links: links
|
||||
.filter((link) => link.scope == "workspace")
|
||||
.map((link) => ({
|
||||
host_directory_id: link.host_directory_id,
|
||||
slug: link.slug,
|
||||
source: link.source,
|
||||
access: link.access,
|
||||
workspace_id: Number(link.workspace_id),
|
||||
})),
|
||||
bots: bots.payload || [],
|
||||
missing,
|
||||
});
|
||||
|
||||
return {
|
||||
computer_dir,
|
||||
bots: (bots.payload || []).map((bot) => ({ id: Number(bot.id), kind: bot.kind })),
|
||||
links,
|
||||
...plan,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
computer_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Every host directory mounted on one computer: those it is linked to
|
||||
* itself, and those of the workspaces it is on.
|
||||
*/
|
||||
export default async function grabComputerHostDirectoryIds({
|
||||
computer_id,
|
||||
}: Params): Promise<number[]> {
|
||||
const rows = await BunSQLite.sql<{ host_directory_id: number }>({
|
||||
sql: `SELECT host_directory_id FROM host_directory_computers WHERE computer_id = ?
|
||||
UNION
|
||||
SELECT hdw.host_directory_id FROM host_directory_workspaces hdw
|
||||
JOIN workspace_computers wc ON wc.workspace_id = hdw.workspace_id
|
||||
WHERE wc.computer_id = ?
|
||||
ORDER BY host_directory_id ASC`,
|
||||
values: [computer_id, computer_id],
|
||||
});
|
||||
|
||||
return (rows.payload || []).map((row) => Number(row.host_directory_id));
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
/**
|
||||
* Whether the user's latest word in a conversation approves deleting the
|
||||
* paths a command named.
|
||||
*
|
||||
* A delete inside a folder mounted from the host machine waits for the
|
||||
* user (`host-directory-delete-guard`), and the approval is the user's own
|
||||
* message: the one an `ask_user` answer sends back (it carries the question
|
||||
* the bot asked, so the path is in it), or anything they typed that names
|
||||
* the path and says to go ahead. Only the newest user message counts, so an
|
||||
* approval from an earlier turn never carries to a later delete.
|
||||
*/
|
||||
|
||||
/** Words that read as the user saying yes. */
|
||||
const Affirmative = /\b(delete|remove|yes|approve[sd]?|confirm(ed)?|go ahead|do it|ok(ay)?|agreed?)\b/i;
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The spellings of the path the user's message may name: the run's
|
||||
* own (`/home/cb-4/workspace/...`) and the real one on the computer.
|
||||
*/
|
||||
needles: string[];
|
||||
};
|
||||
|
||||
export default async function grabDeleteApproval({ session_id, needles }: Params): Promise<boolean> {
|
||||
const paths = needles.map((needle) => needle.trim()).filter(Boolean);
|
||||
|
||||
if (!paths.length) return false;
|
||||
|
||||
const read = await BunSQLite.sql<{ text: string }>({
|
||||
sql: `SELECT text FROM bot_messages
|
||||
WHERE session_id = ? AND author = 'user'
|
||||
ORDER BY id DESC
|
||||
LIMIT 1`,
|
||||
values: [Number(session_id)],
|
||||
});
|
||||
|
||||
const text = String(read.payload?.[0]?.text || "");
|
||||
|
||||
if (!text) return false;
|
||||
|
||||
return Affirmative.test(text) && paths.some((needle) => text.includes(needle));
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type {
|
||||
BUN_SQLITE_COBBLE_HOST_DIRECTORIES,
|
||||
BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS,
|
||||
BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS,
|
||||
BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES,
|
||||
} from "@/db/types/db";
|
||||
import type { HostDirectoryCheck, HostDirectoryWithLinks } from "@/src/types";
|
||||
import hostDirectoryLinkUids from "@/src/utils/host-directory-link-uids";
|
||||
import parseHostDirectoryCheck from "@/src/utils/parse-host-directory-check";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* One directory instead of all of them.
|
||||
*/
|
||||
host_directory_id?: number | string;
|
||||
};
|
||||
|
||||
type ComputerLinkRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS & {
|
||||
computer_name?: string | null;
|
||||
};
|
||||
|
||||
type WorkspaceLinkRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & {
|
||||
workspace_name?: string | null;
|
||||
};
|
||||
|
||||
type CheckRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS;
|
||||
|
||||
/**
|
||||
* The host directories (Settings > Host directories), each with the
|
||||
* computers and workspaces it is linked to, what its last check on each
|
||||
* computer found, and the accounts that see it there (`uids`), by name.
|
||||
* Read-only: a check is parsed, never raw, and a workspace link carries the
|
||||
* checks of every computer the workspace is on.
|
||||
*/
|
||||
export default async function grabHostDirectories({
|
||||
host_directory_id,
|
||||
}: Params = {}): Promise<HostDirectoryWithLinks[]> {
|
||||
const filtered = host_directory_id !== undefined;
|
||||
|
||||
const [
|
||||
directories,
|
||||
computers,
|
||||
workspaces,
|
||||
checks,
|
||||
workspace_computers,
|
||||
bots,
|
||||
bot_computers,
|
||||
workspace_bots,
|
||||
] = await Promise.all([
|
||||
BunSQLite.sql<BUN_SQLITE_COBBLE_HOST_DIRECTORIES>({
|
||||
sql: `SELECT * FROM host_directories ${filtered ? "WHERE id = ?" : ""}
|
||||
ORDER BY name COLLATE NOCASE ASC, id ASC`,
|
||||
values: filtered ? [host_directory_id] : [],
|
||||
}),
|
||||
BunSQLite.sql<ComputerLinkRow>({
|
||||
sql: `SELECT hdc.*, c.name AS computer_name FROM host_directory_computers hdc
|
||||
LEFT JOIN computers c ON c.id = hdc.computer_id
|
||||
${filtered ? "WHERE hdc.host_directory_id = ?" : ""}
|
||||
ORDER BY hdc.id ASC`,
|
||||
values: filtered ? [host_directory_id] : [],
|
||||
}),
|
||||
BunSQLite.sql<WorkspaceLinkRow>({
|
||||
sql: `SELECT hdw.*, w.name AS workspace_name FROM host_directory_workspaces hdw
|
||||
LEFT JOIN workspaces w ON w.id = hdw.workspace_id
|
||||
${filtered ? "WHERE hdw.host_directory_id = ?" : ""}
|
||||
ORDER BY hdw.id ASC`,
|
||||
values: filtered ? [host_directory_id] : [],
|
||||
}),
|
||||
BunSQLite.sql<CheckRow>({
|
||||
sql: `SELECT * FROM host_directory_checks
|
||||
${filtered ? "WHERE host_directory_id = ?" : ""}
|
||||
ORDER BY checked_at DESC`,
|
||||
values: filtered ? [host_directory_id] : [],
|
||||
}),
|
||||
BunSQLite.sql<{ workspace_id: number; computer_id: number }>({
|
||||
sql: `SELECT workspace_id, computer_id FROM workspace_computers`,
|
||||
values: [],
|
||||
}),
|
||||
BunSQLite.sql<{ id: number; kind: string }>({
|
||||
sql: `SELECT id, kind FROM bots`,
|
||||
values: [],
|
||||
}),
|
||||
BunSQLite.sql<{ bot_id: number; computer_id: number }>({
|
||||
sql: `SELECT bot_id, computer_id FROM bot_computers`,
|
||||
values: [],
|
||||
}),
|
||||
BunSQLite.sql<{ bot_id: number; workspace_id: number }>({
|
||||
sql: `SELECT bot_id, workspace_id FROM workspace_bots`,
|
||||
values: [],
|
||||
}),
|
||||
]);
|
||||
|
||||
const reach = {
|
||||
bots: bots.payload || [],
|
||||
bot_computers: bot_computers.payload || [],
|
||||
workspace_bots: workspace_bots.payload || [],
|
||||
workspace_computers: workspace_computers.payload || [],
|
||||
};
|
||||
|
||||
const check_rows = (checks.payload || []).flatMap((row) => {
|
||||
const check = parseHostDirectoryCheck({ text: row.last_check });
|
||||
|
||||
return check ? [{ host_directory_id: Number(row.host_directory_id), check }] : [];
|
||||
});
|
||||
const workspace_computer_rows = workspace_computers.payload || [];
|
||||
|
||||
return (directories.payload || []).map((directory) => {
|
||||
const checked_on = (computer_id: number | string) =>
|
||||
check_rows.find(
|
||||
(row) => row.check.computer_id == Number(computer_id) && row.host_directory_id == directory.id,
|
||||
)?.check || null;
|
||||
|
||||
return {
|
||||
...directory,
|
||||
computers: (computers.payload || [])
|
||||
.filter((row) => row.host_directory_id == directory.id)
|
||||
.map((row) => ({
|
||||
...row,
|
||||
uids: hostDirectoryLinkUids({
|
||||
...reach,
|
||||
scope: "computer",
|
||||
computer_id: Number(row.computer_id),
|
||||
}),
|
||||
check: checked_on(Number(row.computer_id)),
|
||||
})),
|
||||
workspaces: (workspaces.payload || [])
|
||||
.filter((row) => row.host_directory_id == directory.id)
|
||||
.map((row) => {
|
||||
const computer_ids = workspace_computer_rows
|
||||
.filter((link) => link.workspace_id == row.workspace_id)
|
||||
.map((link) => Number(link.computer_id));
|
||||
|
||||
return {
|
||||
...row,
|
||||
computer_ids,
|
||||
uids: hostDirectoryLinkUids({
|
||||
...reach,
|
||||
scope: "workspace",
|
||||
workspace_id: Number(row.workspace_id),
|
||||
}),
|
||||
checks: computer_ids
|
||||
.map((computer_id) => checked_on(computer_id))
|
||||
.filter((check): check is HostDirectoryCheck => Boolean(check)),
|
||||
};
|
||||
}),
|
||||
checks: check_rows
|
||||
.filter((row) => row.host_directory_id == directory.id)
|
||||
.map((row) => row.check),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
host_directory_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Every computer a host directory is mounted on: those it is linked to
|
||||
* itself, and those of the workspaces it is linked to.
|
||||
*/
|
||||
export default async function grabHostDirectoryComputers({
|
||||
host_directory_id,
|
||||
}: Params): Promise<number[]> {
|
||||
const rows = await BunSQLite.sql<{ computer_id: number }>({
|
||||
sql: `SELECT computer_id FROM host_directory_computers WHERE host_directory_id = ?
|
||||
UNION
|
||||
SELECT wc.computer_id FROM host_directory_workspaces hdw
|
||||
JOIN workspace_computers wc ON wc.workspace_id = hdw.workspace_id
|
||||
WHERE hdw.host_directory_id = ?
|
||||
ORDER BY computer_id ASC`,
|
||||
values: [host_directory_id, host_directory_id],
|
||||
});
|
||||
|
||||
return (rows.payload || []).map((row) => Number(row.computer_id));
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
workspace_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Every host directory mounted in one workspace.
|
||||
*/
|
||||
export default async function grabWorkspaceHostDirectoryIds({
|
||||
workspace_id,
|
||||
}: Params): Promise<number[]> {
|
||||
const rows = await BunSQLite.sql<{ host_directory_id: number }>({
|
||||
sql: `SELECT host_directory_id FROM host_directory_workspaces WHERE workspace_id = ? ORDER BY host_directory_id ASC`,
|
||||
values: [workspace_id],
|
||||
});
|
||||
|
||||
return (rows.payload || []).map((row) => Number(row.host_directory_id));
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_HOST_DIRECTORIES } from "@/db/types/db";
|
||||
import type { HostDirectoryAccess } from "@/src/dict/host-directory-dict";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import applyHostDirectoryGrant from "./apply-host-directory-grant";
|
||||
import assertHostDirectoryManager from "./assert-host-directory-manager";
|
||||
import reconcileComputerHostDirectories from "./reconcile-computer-host-directories";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
host_directory_id: number | string;
|
||||
/**
|
||||
* The computer it is mounted into, for every bot that reaches it.
|
||||
*/
|
||||
computer_id?: number | string;
|
||||
/**
|
||||
* The workspace it is mounted into, on every computer the workspace is
|
||||
* on, for every bot working there.
|
||||
*/
|
||||
workspace_id?: number | string;
|
||||
access?: HostDirectoryAccess;
|
||||
};
|
||||
|
||||
/**
|
||||
* Links a host directory to a computer or a workspace, read and write
|
||||
* unless told otherwise. The computers it lands on are given it at once
|
||||
* (`reconcileComputerHostDirectories` recreates an idle one: a mount only
|
||||
* exists from a container's creation).
|
||||
*/
|
||||
export default async function linkHostDirectory({
|
||||
user_id,
|
||||
host_directory_id,
|
||||
computer_id,
|
||||
workspace_id,
|
||||
access = "read-write",
|
||||
}: Params) {
|
||||
await assertHostDirectoryManager({ user_id });
|
||||
|
||||
const directory = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_HOST_DIRECTORIES>({
|
||||
sql: `SELECT * FROM host_directories WHERE id = ?`,
|
||||
values: [host_directory_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!directory?.id) {
|
||||
throw new AppError("Host directory not found.");
|
||||
}
|
||||
|
||||
if (Boolean(computer_id) == Boolean(workspace_id)) {
|
||||
throw new AppError("Pick the computer or the workspace to mount it in.");
|
||||
}
|
||||
|
||||
if (access != "read-write" && access != "read-only") {
|
||||
throw new AppError("Pick read and write, or read only.");
|
||||
}
|
||||
|
||||
const table = computer_id ? "host_directory_computers" : "host_directory_workspaces";
|
||||
const column = computer_id ? "computer_id" : "workspace_id";
|
||||
const value = Number(computer_id || workspace_id);
|
||||
|
||||
const existing = await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM ${table} WHERE host_directory_id = ? AND ${column} = ?`,
|
||||
values: [directory.id, value],
|
||||
});
|
||||
|
||||
if (existing.payload?.[0]?.id) {
|
||||
throw new AppError("That host directory is already linked there.");
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `INSERT INTO ${table} (host_directory_id, ${column}, access, created_at, updated_at) VALUES (?, ?, ?, ?, ?)`,
|
||||
values: [directory.id, value, access, now, now],
|
||||
});
|
||||
|
||||
await applyHostDirectoryGrant({
|
||||
host_directory_id: directory.id,
|
||||
user_id,
|
||||
}).catch(() => {});
|
||||
|
||||
await reconcileComputerHostDirectories(
|
||||
computer_id ? { computer_id: value } : { workspace_id: value },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
import runDockerContainer from "@/src/functions/backend/docker/run-docker-container";
|
||||
import grabComputerImage from "@/src/functions/backend/docker/grab-computer-image";
|
||||
import resolveHostPath from "@/src/functions/backend/docker/resolve-host-path";
|
||||
import type { HostDirectoryMount } from "@/src/utils/host-directory-mount-plan";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
|
||||
type Params = {
|
||||
computer_dir: string;
|
||||
mounts: HostDirectoryMount[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes the folder each host directory is mounted at, before its container
|
||||
* is created: docker is told never to create a missing mount point itself,
|
||||
* since it would make it owned by root instead of failing.
|
||||
*
|
||||
* The folders under a bot's own folder and a workspace's belong to the
|
||||
* accounts on the computer, so an app running on the host as a plain user
|
||||
* can't make them (`EACCES`); those are made by a throwaway container as
|
||||
* root, over the computer's own folder. The container's root does the same
|
||||
* job the app does when it runs in docker, where it is root too.
|
||||
*/
|
||||
export default async function prepareHostDirectoryMounts({
|
||||
computer_dir,
|
||||
mounts,
|
||||
}: Params) {
|
||||
const blocked: string[] = [];
|
||||
|
||||
for (const mount of mounts) {
|
||||
try {
|
||||
await fs.mkdir(mount.destination, { recursive: true });
|
||||
} catch (error: unknown) {
|
||||
const code = (error as NodeJS.ErrnoException)?.code;
|
||||
|
||||
if (code != "EACCES" && code != "EPERM") {
|
||||
throw error;
|
||||
}
|
||||
|
||||
blocked.push(mount.destination);
|
||||
}
|
||||
}
|
||||
|
||||
if (!blocked.length) return;
|
||||
|
||||
const host_dir = await resolveHostPath({ local_path: computer_dir });
|
||||
const run = await runDockerContainer({
|
||||
image: await grabComputerImage(),
|
||||
entrypoint: ["/bin/sh", "-c"],
|
||||
cmd: [
|
||||
`mkdir -p "$@"`,
|
||||
"sh",
|
||||
...blocked.map((destination) => `/computer/${path.relative(computer_dir, destination)}`),
|
||||
],
|
||||
mounts: [{ source: host_dir, target: "/computer" }],
|
||||
});
|
||||
|
||||
if (run.error || run.exit_code != 0) {
|
||||
throw new AppError(
|
||||
`Couldn't make the folder to mount a host directory at: ${run.error || run.logs || "the container failed."}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import hostDirectoryMountsChanged from "@/src/utils/host-directory-mounts-changed";
|
||||
import logEvent, { logError } from "@/src/functions/backend/logger";
|
||||
import grabEnv from "../envs/grab-env";
|
||||
import grabComputerMetadata from "../computers/grab-computer-metadata";
|
||||
import grabComputerHostDirectories from "./grab-computer-host-directories";
|
||||
import grabUserComputers from "../computers/grab-user-computers";
|
||||
import isComputerBusy from "../computers/is-computer-busy";
|
||||
import provisionComputer from "../computers/provision-computer";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* One computer.
|
||||
*/
|
||||
computer_id?: number | string;
|
||||
/**
|
||||
* Every computer a workspace is on.
|
||||
*/
|
||||
workspace_id?: number | string;
|
||||
/**
|
||||
* Wait for the computers to be set up again before returning (a cron
|
||||
* run). A page's own save doesn't: it returns while they set up.
|
||||
*/
|
||||
wait?: boolean;
|
||||
};
|
||||
|
||||
type ReconcileOneParams = {
|
||||
computer_id: number;
|
||||
wait: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gives one computer the host directories it should have now, by setting it
|
||||
* up again when they differ from what its container was made with. Refused
|
||||
* while the computer is still being set up or a job works on it (that job
|
||||
* would lose its run), and for a computer reached at `MAIN_COMPUTER_URL`,
|
||||
* which this install doesn't make. Returns whether it will be recreated.
|
||||
*/
|
||||
async function reconcileOne({ computer_id, wait }: ReconcileOneParams) {
|
||||
const computer = (await grabUserComputers({ computer_id }))[0];
|
||||
|
||||
if (!computer?.id) return false;
|
||||
|
||||
/**
|
||||
* Only a container that is up is set up again: one that is stopped
|
||||
* keeps the mounts it had until it runs, and one still being set up is
|
||||
* already taking them.
|
||||
*/
|
||||
if (computer.status != "running" && computer.status != "unhealthy") return false;
|
||||
if (await isComputerBusy({ computer_id })) return false;
|
||||
|
||||
const external =
|
||||
computer.kind == "main" && Boolean((await grabEnv({ key: "MAIN_COMPUTER_URL" }))?.trim());
|
||||
|
||||
if (external) return false;
|
||||
|
||||
const container_metadata = await grabComputerMetadata({ computer_id });
|
||||
|
||||
const stored = (() => {
|
||||
try {
|
||||
const metadata = JSON.parse(container_metadata || "{}");
|
||||
|
||||
return Array.isArray(metadata?.host_mounts) ? (metadata.host_mounts as string[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
})();
|
||||
|
||||
const { mounts } = await grabComputerHostDirectories({ computer_id });
|
||||
|
||||
if (!hostDirectoryMountsChanged({ stored, mounts })) return false;
|
||||
|
||||
if (wait) {
|
||||
await provisionComputer({ computer_id });
|
||||
} else {
|
||||
provisionComputer({ computer_id }).catch((error) => {
|
||||
logError({
|
||||
title: "Couldn't set a computer up again with its host directories",
|
||||
error,
|
||||
metadata: { computer_id },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
await logEvent({
|
||||
title: "host directories changed on a computer",
|
||||
category: "system",
|
||||
plain_text: `${computer.name || `Computer #${computer_id}`} is being set up again with ${mounts.length} host ${mounts.length == 1 ? "directory" : "directories"}.`,
|
||||
metadata: { computer_id, mounts: mounts.length },
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-applies the host directories a computer (or every computer a
|
||||
* workspace is on) should have, after a link, an unlink or an access
|
||||
* change. See `reconcileOne` for when a computer is left alone.
|
||||
*/
|
||||
export default async function reconcileComputerHostDirectories({
|
||||
computer_id,
|
||||
workspace_id,
|
||||
wait = false,
|
||||
}: Params): Promise<number[]> {
|
||||
if (!computer_id && !workspace_id) {
|
||||
throw new AppError("Pick a computer or a workspace.");
|
||||
}
|
||||
|
||||
const computer_ids = computer_id
|
||||
? [Number(computer_id)]
|
||||
: (
|
||||
await BunSQLite.sql<{ computer_id: number }>({
|
||||
sql: `SELECT computer_id FROM workspace_computers WHERE workspace_id = ?`,
|
||||
values: [Number(workspace_id)],
|
||||
})
|
||||
).payload?.map((row) => Number(row.computer_id)) || [];
|
||||
|
||||
const recreated: number[] = [];
|
||||
|
||||
for (const id of computer_ids) {
|
||||
if (await reconcileOne({ computer_id: id, wait })) recreated.push(id);
|
||||
}
|
||||
|
||||
return recreated;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { HostDirectoryAccess } from "@/src/dict/host-directory-dict";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import assertHostDirectoryManager from "./assert-host-directory-manager";
|
||||
import reconcileComputerHostDirectories from "./reconcile-computer-host-directories";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
host_directory_id: number | string;
|
||||
computer_id?: number | string;
|
||||
workspace_id?: number | string;
|
||||
access: HostDirectoryAccess;
|
||||
};
|
||||
|
||||
/**
|
||||
* How one link uses its folder: read and write, or read only. A read-only
|
||||
* mount is mounted read only, so it takes setting the computer up again
|
||||
* (`reconcileComputerHostDirectories`).
|
||||
*/
|
||||
export default async function setHostDirectoryAccess({
|
||||
user_id,
|
||||
host_directory_id,
|
||||
computer_id,
|
||||
workspace_id,
|
||||
access,
|
||||
}: Params) {
|
||||
await assertHostDirectoryManager({ user_id });
|
||||
|
||||
if (Boolean(computer_id) == Boolean(workspace_id)) {
|
||||
throw new AppError("Pick the computer or the workspace whose link changes.");
|
||||
}
|
||||
|
||||
if (access != "read-write" && access != "read-only") {
|
||||
throw new AppError("Pick read and write, or read only.");
|
||||
}
|
||||
|
||||
const table = computer_id ? "host_directory_computers" : "host_directory_workspaces";
|
||||
const column = computer_id ? "computer_id" : "workspace_id";
|
||||
const value = Number(computer_id || workspace_id);
|
||||
|
||||
const link = await BunSQLite.sql<{ id: number; access: string }>({
|
||||
sql: `SELECT id, access FROM ${table} WHERE host_directory_id = ? AND ${column} = ?`,
|
||||
values: [host_directory_id, value],
|
||||
});
|
||||
|
||||
const row = link.payload?.[0];
|
||||
|
||||
if (!row?.id) {
|
||||
throw new AppError("That host directory isn't linked there.");
|
||||
}
|
||||
|
||||
if (row.access == access) return;
|
||||
|
||||
const updated = await BunSQLite.sql({
|
||||
sql: `UPDATE ${table} SET access = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [access, Date.now(), row.id],
|
||||
});
|
||||
|
||||
if (!updated.success) {
|
||||
throw new AppError("Couldn't change how the folder is used.");
|
||||
}
|
||||
|
||||
await reconcileComputerHostDirectories(
|
||||
computer_id ? { computer_id: value } : { workspace_id: value },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import assertHostDirectoryManager from "./assert-host-directory-manager";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
host_directory_id: number | string;
|
||||
computer_id?: number | string;
|
||||
workspace_id?: number | string;
|
||||
gate_deletes: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether one link asks the user before a command deletes or moves
|
||||
* anything out of the folder (`host-directory-delete-guard`). It is read
|
||||
* on every command, so nothing is set up again.
|
||||
*/
|
||||
export default async function setHostDirectoryDeletes({
|
||||
user_id,
|
||||
host_directory_id,
|
||||
computer_id,
|
||||
workspace_id,
|
||||
gate_deletes,
|
||||
}: Params) {
|
||||
await assertHostDirectoryManager({ user_id });
|
||||
|
||||
if (Boolean(computer_id) == Boolean(workspace_id)) {
|
||||
throw new AppError("Pick the computer or the workspace whose link changes.");
|
||||
}
|
||||
|
||||
const table = computer_id ? "host_directory_computers" : "host_directory_workspaces";
|
||||
const column = computer_id ? "computer_id" : "workspace_id";
|
||||
const value = Number(computer_id || workspace_id);
|
||||
|
||||
const link = await BunSQLite.sql<{ id: number; gate_deletes: number }>({
|
||||
sql: `SELECT id, gate_deletes FROM ${table} WHERE host_directory_id = ? AND ${column} = ?`,
|
||||
values: [host_directory_id, value],
|
||||
});
|
||||
|
||||
const row = link.payload?.[0];
|
||||
|
||||
if (!row?.id) {
|
||||
throw new AppError("That host directory isn't linked there.");
|
||||
}
|
||||
|
||||
const current = Number(row.gate_deletes) != 0;
|
||||
|
||||
if (current == gate_deletes) return;
|
||||
|
||||
const updated = await BunSQLite.sql({
|
||||
sql: `UPDATE ${table} SET gate_deletes = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [gate_deletes ? 1 : 0, Date.now(), row.id],
|
||||
});
|
||||
|
||||
if (!updated.success) {
|
||||
throw new AppError("Couldn't change how deletes in the folder are handled.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import fs from "fs/promises";
|
||||
import type { BUN_SQLITE_COBBLE_HOST_DIRECTORIES } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import applyHostDirectoryGrant from "./apply-host-directory-grant";
|
||||
import assertHostDirectoryManager from "./assert-host-directory-manager";
|
||||
import grabComputerHostDirectories from "./grab-computer-host-directories";
|
||||
import reconcileComputerHostDirectories from "./reconcile-computer-host-directories";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
host_directory_id: number | string;
|
||||
computer_id?: number | string;
|
||||
workspace_id?: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Takes a host directory out of one computer or one workspace. The host
|
||||
* folder itself is untouched: only the mount goes, the next time the
|
||||
* computer is set up again (`reconcileComputerHostDirectories`), and the
|
||||
* empty folder it was mounted at is removed.
|
||||
*/
|
||||
export default async function unlinkHostDirectory({
|
||||
user_id,
|
||||
host_directory_id,
|
||||
computer_id,
|
||||
workspace_id,
|
||||
}: Params) {
|
||||
await assertHostDirectoryManager({ user_id });
|
||||
|
||||
if (Boolean(computer_id) == Boolean(workspace_id)) {
|
||||
throw new AppError("Pick the computer or the workspace to take it out of.");
|
||||
}
|
||||
|
||||
const directory = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_HOST_DIRECTORIES>({
|
||||
sql: `SELECT * FROM host_directories WHERE id = ?`,
|
||||
values: [host_directory_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!directory?.id) {
|
||||
throw new AppError("Host directory not found.");
|
||||
}
|
||||
|
||||
const table = computer_id ? "host_directory_computers" : "host_directory_workspaces";
|
||||
const column = computer_id ? "computer_id" : "workspace_id";
|
||||
const value = Number(computer_id || workspace_id);
|
||||
|
||||
const computer_ids = computer_id
|
||||
? [Number(computer_id)]
|
||||
: (
|
||||
await BunSQLite.sql<{ computer_id: number }>({
|
||||
sql: `SELECT computer_id FROM workspace_computers WHERE workspace_id = ?`,
|
||||
values: [value],
|
||||
})
|
||||
).payload?.map((row) => Number(row.computer_id)) || [];
|
||||
|
||||
const destinations: string[] = [];
|
||||
|
||||
for (const id of computer_ids) {
|
||||
const { mounts } = await grabComputerHostDirectories({
|
||||
computer_id: id,
|
||||
});
|
||||
|
||||
destinations.push(
|
||||
...mounts
|
||||
.filter((mount) => mount.host_directory_id == directory.id)
|
||||
.map((mount) => mount.destination),
|
||||
);
|
||||
}
|
||||
|
||||
const removed = await BunSQLite.sql({
|
||||
sql: `DELETE FROM ${table} WHERE host_directory_id = ? AND ${column} = ?`,
|
||||
values: [directory.id, value],
|
||||
});
|
||||
|
||||
if (!removed.success) {
|
||||
throw new AppError("Couldn't take the host directory out.");
|
||||
}
|
||||
|
||||
await applyHostDirectoryGrant({
|
||||
host_directory_id: directory.id,
|
||||
user_id,
|
||||
}).catch(() => {});
|
||||
|
||||
await reconcileComputerHostDirectories(
|
||||
computer_id ? { computer_id: value } : { workspace_id: value },
|
||||
);
|
||||
|
||||
for (const destination of destinations) {
|
||||
await fs.rmdir(destination).catch(() => {
|
||||
/**
|
||||
* Still mounted (the computer is busy and will be set up again
|
||||
* later), or holding something. Neither is an error here.
|
||||
*/
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_HOST_DIRECTORIES, BunSQLiteTables } from "@/db/types/db";
|
||||
import {
|
||||
HostDirectoryNameMaxChars,
|
||||
HostDirectorySourceMaxChars,
|
||||
} from "@/src/dict/host-directory-dict";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import hostDirectoryPath from "@/src/utils/host-directory-path";
|
||||
import applyHostDirectoryGrant from "./apply-host-directory-grant";
|
||||
import assertHostDirectoryManager from "./assert-host-directory-manager";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
host_directory_id: number | string;
|
||||
name?: string;
|
||||
/**
|
||||
* Its absolute path on the host machine.
|
||||
*/
|
||||
source?: string;
|
||||
reserved?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Renames a host directory, or points it at another folder. Its `slug` (the
|
||||
* name it is mounted under) is kept: moving it in a computer's folder would
|
||||
* leave the old one behind. A new path means every check of it is out of
|
||||
* date, so they are dropped and the computers mount it again
|
||||
* (`reconcileComputerHostDirectories`).
|
||||
*/
|
||||
export default async function updateHostDirectory({
|
||||
user_id,
|
||||
host_directory_id,
|
||||
name,
|
||||
source,
|
||||
reserved = [],
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_HOST_DIRECTORIES> {
|
||||
await assertHostDirectoryManager({ user_id });
|
||||
|
||||
const directory = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_HOST_DIRECTORIES>({
|
||||
sql: `SELECT * FROM host_directories WHERE id = ?`,
|
||||
values: [host_directory_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!directory?.id) {
|
||||
throw new AppError("Host directory not found.");
|
||||
}
|
||||
|
||||
const clean_name = name === undefined ? directory.name : String(name || "").trim();
|
||||
|
||||
if (!clean_name) {
|
||||
throw new AppError("A host directory needs a name.");
|
||||
}
|
||||
|
||||
if (clean_name.length > HostDirectoryNameMaxChars) {
|
||||
throw new AppError(`A host directory's name can't be longer than ${HostDirectoryNameMaxChars} characters.`);
|
||||
}
|
||||
|
||||
if (/[\0\n\r]/.test(clean_name)) {
|
||||
throw new AppError("A host directory's name can't have line breaks.");
|
||||
}
|
||||
|
||||
const clean_source =
|
||||
source === undefined ? String(directory.source || "") : hostDirectoryPath({ source, reserved });
|
||||
|
||||
if (clean_source.length > HostDirectorySourceMaxChars) {
|
||||
throw new AppError(`A host directory's path can't be longer than ${HostDirectorySourceMaxChars} characters.`);
|
||||
}
|
||||
|
||||
await BunSQLite.update<BUN_SQLITE_COBBLE_HOST_DIRECTORIES, (typeof BunSQLiteTables)[number]>({
|
||||
table: "host_directories",
|
||||
targetId: directory.id,
|
||||
data: { name: clean_name, source: clean_source },
|
||||
});
|
||||
|
||||
if (clean_source != directory.source) {
|
||||
await BunSQLite.sql({
|
||||
sql: `DELETE FROM host_directory_checks WHERE host_directory_id = ?`,
|
||||
values: [directory.id],
|
||||
});
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `DELETE FROM host_directory_grants WHERE host_directory_id = ?`,
|
||||
values: [directory.id],
|
||||
});
|
||||
|
||||
await applyHostDirectoryGrant({
|
||||
host_directory_id: directory.id,
|
||||
user_id,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
return { ...directory, name: clean_name, source: clean_source };
|
||||
}
|
||||
@@ -100,7 +100,7 @@ export default async function ingestKnowledgebaseDocument({
|
||||
const batch = chunks.slice(start, start + AppData.EmbeddingBatchSize);
|
||||
const embedded = await runWithFallbackScope({
|
||||
scope,
|
||||
task: () => embedText({ input: batch, signal }),
|
||||
task: () => embedText({ input: batch, purpose: "passage", signal }),
|
||||
});
|
||||
|
||||
model = embedded.model || model;
|
||||
|
||||
@@ -3,6 +3,9 @@ import AppError from "@/src/utils/app-error";
|
||||
import grabUserBot from "../bots/grab-user-bot";
|
||||
import grabUserWorkspace from "./grab-user-workspace";
|
||||
import assertCrewManager from "@/src/functions/backend/db/access/assert-crew-manager";
|
||||
import applyHostDirectoryGrant from "../host-directories/apply-host-directory-grant";
|
||||
import grabWorkspaceHostDirectoryIds from "../host-directories/grab-workspace-host-directory-ids";
|
||||
import reconcileComputerHostDirectories from "../host-directories/reconcile-computer-host-directories";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -12,7 +15,9 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Assigns one of the user's bots to one of their workspaces. Assigning a
|
||||
* bot that is already there is a no-op.
|
||||
* bot that is already there is a no-op. Through the workspace it reaches
|
||||
* its computers, so a host directory linked to one of them has to be
|
||||
* mounted in its own folder (`reconcileComputerHostDirectories`).
|
||||
*/
|
||||
export default async function addBotToWorkspace({
|
||||
user_id,
|
||||
@@ -32,4 +37,19 @@ export default async function addBotToWorkspace({
|
||||
sql: `INSERT OR IGNORE INTO workspace_bots (workspace_id, bot_id, created_at, updated_at) VALUES (?, ?, ?, ?)`,
|
||||
values: [workspace.id, bot.id, Date.now(), Date.now()],
|
||||
});
|
||||
|
||||
await reconcileComputerHostDirectories({ workspace_id: Number(workspace.id) });
|
||||
|
||||
/**
|
||||
* The folders mounted in this workspace now reach it, so each gives it
|
||||
* access, as every bot working there has it.
|
||||
*/
|
||||
for (const host_directory_id of await grabWorkspaceHostDirectoryIds({
|
||||
workspace_id: Number(workspace.id),
|
||||
})) {
|
||||
await applyHostDirectoryGrant({
|
||||
host_directory_id,
|
||||
retry: false,
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { WorkspaceWithActivity } from "@/src/types";
|
||||
import workspacesSql from "@/src/utils/crew-access/workspaces-sql";
|
||||
import grabCrewRole from "../access/grab-crew-role";
|
||||
import followedSessionSql from "../bot-sessions/followed-session-sql";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -19,8 +20,8 @@ export default async function grabUserWorkspaces({
|
||||
|
||||
const res = await BunSQLite.sql<WorkspaceWithActivity>({
|
||||
sql: `SELECT w.*,
|
||||
COALESCE((SELECT MAX(s.unread) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND s.ask_id IS NULL AND s.hook_id IS NULL), 0) AS unread,
|
||||
(SELECT MAX(s.last_activity_at) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND s.ask_id IS NULL AND s.hook_id IS NULL) AS last_activity_at,
|
||||
COALESCE((SELECT MAX(s.unread) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND ${followedSessionSql({ alias: "s" })}), 0) AS unread,
|
||||
(SELECT MAX(s.last_activity_at) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND ${followedSessionSql({ alias: "s" })}) AS last_activity_at,
|
||||
(SELECT v.visited_at FROM workspace_user_visits v WHERE v.workspace_id = w.id AND v.user_id = ?) AS last_visited_at
|
||||
FROM workspaces w
|
||||
WHERE w.archived = 0 AND ${access.sql}
|
||||
|
||||
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { WorkspaceActivityItem } from "@/src/types";
|
||||
import botFaceSql from "@/src/utils/bot-face-sql";
|
||||
import followedSessionSql from "../bot-sessions/followed-session-sql";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -32,7 +33,7 @@ export default async function grabWorkspaceActivity({
|
||||
(SELECT m.text FROM bot_messages m WHERE m.session_id = s.id ORDER BY m.created_at ASC, m.id ASC LIMIT 1) AS first_message_text
|
||||
FROM bot_sessions s
|
||||
JOIN bots b ON b.id = s.bot_id
|
||||
WHERE s.workspace_id = ? AND s.user_id = ? AND s.ask_id IS NULL AND s.hook_id IS NULL
|
||||
WHERE s.workspace_id = ? AND s.user_id = ? AND ${followedSessionSql({ alias: "s" })}
|
||||
AND EXISTS (SELECT 1 FROM bot_messages m WHERE m.session_id = s.id)
|
||||
AND (b.kind = 'coordinator' OR EXISTS (
|
||||
SELECT 1 FROM workspace_bots wb WHERE wb.workspace_id = s.workspace_id AND wb.bot_id = s.bot_id
|
||||
|
||||
@@ -45,6 +45,14 @@ type Params = {
|
||||
* the local one when the registry can't be reached.
|
||||
*/
|
||||
pull?: boolean;
|
||||
/**
|
||||
* The user's own folders on the host machine, mounted into the bot's
|
||||
* and the workspace's folders inside the workspace
|
||||
* (`hostDirectoryMountPlan`). Unlike the two above, docker may not
|
||||
* make one that isn't there: the container fails instead, since a
|
||||
* typo would otherwise become a folder docker owns.
|
||||
*/
|
||||
host_mounts?: { source: string; target: string; read_only?: boolean }[];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -73,6 +81,7 @@ export default async function createComputerContainer({
|
||||
memory_mb,
|
||||
browser_env = [],
|
||||
pull,
|
||||
host_mounts = [],
|
||||
}: Params) {
|
||||
const network = await ensureDockerNetwork();
|
||||
const host_dir = await resolveHostPath({ local_path: data_dir });
|
||||
@@ -113,9 +122,31 @@ export default async function createComputerContainer({
|
||||
Retries: AppData.ComputerHealthcheck.Retries,
|
||||
},
|
||||
HostConfig: {
|
||||
Binds: [
|
||||
`${host_dir}:${AppData.ComputerWorkspaceDir}`,
|
||||
`${browser_host_dir}:${AppData.ComputerBrowserProfileDir}`,
|
||||
/**
|
||||
* The `Mounts` form, not `Binds`: a host directory with
|
||||
* `CreateMountpoint` off fails the create instead of
|
||||
* becoming a root-owned folder on the host.
|
||||
*/
|
||||
Mounts: [
|
||||
{
|
||||
Type: "bind",
|
||||
Source: host_dir,
|
||||
Target: AppData.ComputerWorkspaceDir,
|
||||
BindOptions: { CreateMountpoint: true },
|
||||
},
|
||||
{
|
||||
Type: "bind",
|
||||
Source: browser_host_dir,
|
||||
Target: AppData.ComputerBrowserProfileDir,
|
||||
BindOptions: { CreateMountpoint: true },
|
||||
},
|
||||
...host_mounts.map((mount) => ({
|
||||
Type: "bind",
|
||||
Source: mount.source,
|
||||
Target: mount.target,
|
||||
ReadOnly: Boolean(mount.read_only),
|
||||
BindOptions: { CreateMountpoint: false },
|
||||
})),
|
||||
],
|
||||
NetworkMode: network,
|
||||
RestartPolicy: { Name: "unless-stopped" },
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user