Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78accbcc4f | ||
|
|
5601e2c2b8 | ||
|
|
7c678284ae | ||
|
|
8c868d6a04 |
@@ -95,7 +95,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
|
||||
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images/PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
|
||||
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch.
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
|
||||
@@ -117,8 +117,8 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix.
|
||||
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`).
|
||||
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
|
||||
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last.
|
||||
|
||||
### Live updates
|
||||
@@ -158,7 +158,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
|
||||
|
||||
### Tasks (the to-do tracker)
|
||||
|
||||
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title); API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id`; `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
|
||||
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id`; `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
|
||||
|
||||
### Envs
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.14.1",
|
||||
"version": "0.14.2",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import grabBotFile from "@/src/functions/backend/db/bot-files/grab-bot-file";
|
||||
import grabBotFileScope from "@/src/functions/backend/db/bot-files/grab-bot-file-scope";
|
||||
import userReachesFileScope from "@/src/functions/backend/db/bot-files/user-reaches-file-scope";
|
||||
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
|
||||
import describeToolUses from "@/src/harness/text/describe-tool-uses";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import replyClaimProblems from "@/src/utils/reply-claim-problems";
|
||||
import replyRefIds from "@/src/utils/reply-ref-ids";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
|
||||
type Params = {
|
||||
text: string;
|
||||
tool_uses: HarnessToolUse[];
|
||||
bot_id: number | string;
|
||||
user_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The run's folders (`grabRunScopes`).
|
||||
*/
|
||||
scopes: StorageScope[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks a chat reply's answer against what the app knows before it goes
|
||||
* out (`replyClaimProblems`): every file and task it names must exist for
|
||||
* the user (as their chips would open them), and work it says is under
|
||||
* way must have been started by this reply or still be open from this
|
||||
* conversation. Returns the note that sends the answer back to be written
|
||||
* again, or null when it holds up. Bots wrote "I'm scanning now" with the
|
||||
* scan's made-up results in the same answer, and the user acted on them.
|
||||
*/
|
||||
export default async function reviewBotReply({ text, tool_uses, bot_id, user_id, session_id, scopes }: Params) {
|
||||
if (!text.trim()) return null;
|
||||
|
||||
const missing_file_ids: number[] = [];
|
||||
|
||||
for (const file_id of replyRefIds({ text, kind: "file" })) {
|
||||
if (!(await fileExistsForUser({ file_id, user_id, scopes }))) missing_file_ids.push(file_id);
|
||||
}
|
||||
|
||||
const missing_task_ids: number[] = [];
|
||||
|
||||
for (const task_id of replyRefIds({ text, kind: "task" })) {
|
||||
const reached = await assertUserReachesTask({ user_id, task_id }).catch(() => null);
|
||||
|
||||
if (!reached?.id) missing_task_ids.push(task_id);
|
||||
}
|
||||
|
||||
const problems = replyClaimProblems({
|
||||
text,
|
||||
tool_uses,
|
||||
missing_file_ids,
|
||||
missing_task_ids,
|
||||
has_open_work: await hasOpenWork({ bot_id, session_id }),
|
||||
});
|
||||
|
||||
if (!problems.length) return null;
|
||||
|
||||
return `Your answer above was not sent: the app checked it against its record, and it doesn't hold up.
|
||||
|
||||
${problems.map((problem) => `- ${problem}`).join("\n")}
|
||||
|
||||
The tools you actually called in this reply: ${describeToolUses({ uses: tool_uses })}. Nothing else happened. Write the answer again, saying only what those tools returned and what the user told you. If the work still needs doing, call start_task now and say it's started; never describe results of work no tool did, and never promise a report nothing will send. If part of your answer was wrong, say so plainly.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a file chip would open for the user: in the run's folders, or
|
||||
* in another folder the user reaches (an answer passed on from a room).
|
||||
*/
|
||||
async function fileExistsForUser({
|
||||
file_id,
|
||||
user_id,
|
||||
scopes,
|
||||
}: {
|
||||
file_id: number;
|
||||
user_id: number | string;
|
||||
scopes: StorageScope[];
|
||||
}) {
|
||||
if ((await grabBotFile({ scopes, file_id }))?.id) return true;
|
||||
|
||||
const elsewhere = await grabBotFileScope({ file_id });
|
||||
|
||||
if (!elsewhere || !(await userReachesFileScope({ ...elsewhere, user_id }))) return false;
|
||||
|
||||
return Boolean((await grabBotFile({ scopes: [elsewhere], file_id }))?.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* A run of the bot's in this session, a job it handed over from here, or
|
||||
* a room it asked from here, still open: its result is still to come.
|
||||
*/
|
||||
async function hasOpenWork({ bot_id, session_id }: { bot_id: number | string; session_id: number | string }) {
|
||||
const jobs = await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM bots_queue
|
||||
WHERE status IN ('pending', 'processing') AND kind = 'task'
|
||||
AND ((bot_id = ? AND session_id = ?) OR requested_by_session_id = ?)
|
||||
LIMIT 1`,
|
||||
values: [Number(bot_id), Number(session_id), Number(session_id)],
|
||||
});
|
||||
|
||||
if (jobs.payload?.[0]) return true;
|
||||
|
||||
const rooms = await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM chatrooms WHERE status = 'open' AND requester_bot_id = ? AND origin_session_id = ? LIMIT 1`,
|
||||
values: [Number(bot_id), Number(session_id)],
|
||||
});
|
||||
|
||||
return Boolean(rooms.payload?.[0]);
|
||||
}
|
||||
@@ -53,6 +53,7 @@ import grabMessageRefNames from "@/src/functions/backend/db/bots/grab-message-re
|
||||
import withTakeOverRefs from "./with-take-over-refs";
|
||||
import stripAppRecords from "@/src/utils/strip-app-records";
|
||||
import hasUnansweredMessage from "./has-unanswered-message";
|
||||
import reviewBotReply from "./review-bot-reply";
|
||||
import grabAnsweredMessageId from "@/src/functions/backend/db/bots-queue/grab-answered-message-id";
|
||||
import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-answered";
|
||||
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
|
||||
@@ -85,7 +86,9 @@ type Params = BotJobContext & {
|
||||
* that's separate can be acknowledged at once (`send_message`) and done
|
||||
* after the current work. The job records the newest
|
||||
* one it read (`markReplyAnswered`). Finishes silently when an earlier
|
||||
* reply already read everything (`hasUnansweredMessage`).
|
||||
* reply already read everything (`hasUnansweredMessage`). An answer naming
|
||||
* files or tasks that don't exist, or saying work is under way when none
|
||||
* is, is written again once (`reviewBotReply`).
|
||||
*/
|
||||
export default async function runBotReply({
|
||||
bot,
|
||||
@@ -243,6 +246,10 @@ export default async function runBotReply({
|
||||
* workspace's admin.
|
||||
*/
|
||||
const powers = await grabBotRunPowers({ bot_id: bot.id, workspace_id });
|
||||
/**
|
||||
* A chatroom's turn is a reply too, and nobody follows that.
|
||||
*/
|
||||
const attended = !(await isHiddenSession({ session_id }));
|
||||
let led: WorkspaceAdminTools | null = null;
|
||||
|
||||
const tools = await grabBotChatTools({
|
||||
@@ -253,6 +260,7 @@ export default async function runBotReply({
|
||||
session_id,
|
||||
workspace_id,
|
||||
scopes,
|
||||
attended,
|
||||
message_id: job.message_id || undefined,
|
||||
onTakeOver: ({ ref }) => take_overs.push(ref),
|
||||
onPropose: ({ ref }) => proposals.push(ref),
|
||||
@@ -279,9 +287,9 @@ export default async function runBotReply({
|
||||
|
||||
/**
|
||||
* The user's own browsers, so a bot can browse from the chat with no
|
||||
* computer. A room's turn is a reply too, and nobody follows that.
|
||||
* computer.
|
||||
*/
|
||||
const browser_run_kind = (await isHiddenSession({ session_id })) ? "unattended" : "attended";
|
||||
const browser_run_kind = attended ? "attended" : "unattended";
|
||||
const browsers = await openBotBrowsers({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
@@ -422,6 +430,12 @@ export default async function runBotReply({
|
||||
signal,
|
||||
onStep: report,
|
||||
incoming,
|
||||
/**
|
||||
* Files, tasks and work the answer names are checked against
|
||||
* the app's record before it goes out.
|
||||
*/
|
||||
review: ({ text, tool_uses }) =>
|
||||
reviewBotReply({ text, tool_uses, bot_id: bot.id!, user_id, session_id, scopes }),
|
||||
});
|
||||
|
||||
if (job.id && answering_id) {
|
||||
|
||||
@@ -322,11 +322,22 @@ export default async function runBotTask({
|
||||
taken: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools].map((tool) => tool.name),
|
||||
});
|
||||
|
||||
/**
|
||||
* The install's limit, or less when the brief's writer set a
|
||||
* budget (`start_task` `max_steps`).
|
||||
*/
|
||||
const install_steps = await grabHarnessMaxToolSteps();
|
||||
const budget = Math.floor(Number(params.max_steps) || 0);
|
||||
const max_steps = budget > 0 ? Math.min(budget, install_steps) : install_steps;
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: [
|
||||
prompt,
|
||||
carry_over,
|
||||
TaskRunNote,
|
||||
budget > 0
|
||||
? `This run has at most ${max_steps} steps (model turns), set when it was queued. Plan for that: save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
|
||||
: "",
|
||||
scheduled ? ScheduledRunNote : "",
|
||||
hooked ? HookRunNote : "",
|
||||
install_request_id ? InstallRequestNote : "",
|
||||
@@ -382,7 +393,7 @@ export default async function runBotTask({
|
||||
},
|
||||
],
|
||||
tools: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools, ...knowledge.tools],
|
||||
max_steps: await grabHarnessMaxToolSteps(),
|
||||
max_steps,
|
||||
bot_id: bot.id,
|
||||
workspace_id,
|
||||
signal,
|
||||
|
||||
@@ -14,6 +14,7 @@ import TaskStatusMoves from "@/src/components/general/task-status-moves";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import TaskFactRow from "@/src/components/general/task-fact-row";
|
||||
import TaskNoteRow from "@/src/components/general/task-note-row";
|
||||
import TaskMarkdown from "@/src/components/general/task-markdown";
|
||||
import type { BotFace } from "@/src/dict/bot-dict";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
@@ -306,7 +307,7 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
) : null}
|
||||
|
||||
{task.description ? (
|
||||
<Span className="whitespace-pre-wrap text-[13px] leading-[19px] text-ink">{task.description}</Span>
|
||||
<TaskMarkdown text={task.description} />
|
||||
) : null}
|
||||
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import TaskMarkdown from "./task-markdown";
|
||||
|
||||
describe("TaskMarkdown", () => {
|
||||
test("renders the markdown, not as written", () => {
|
||||
const html = renderToString(<TaskMarkdown text={"## Steps\n\n- **Check** the [docs](https://example.com)"} />);
|
||||
|
||||
expect(html).not.toContain("## Steps");
|
||||
expect(html).not.toContain("**Check**");
|
||||
expect(html).toContain("<li");
|
||||
expect(html).toContain("Check");
|
||||
});
|
||||
|
||||
test("opens links in a new tab, bare ones too", () => {
|
||||
const html = renderToString(<TaskMarkdown text={"See [the docs](https://example.com) or https://example.org"} />);
|
||||
|
||||
expect(html).toContain('href="https://example.com"');
|
||||
expect(html).toContain('href="https://example.org"');
|
||||
expect(html.match(/target="_blank"/g)?.length).toBe(2);
|
||||
expect(html).toContain("noopener");
|
||||
});
|
||||
|
||||
test("shows refs as chips", () => {
|
||||
const html = renderToString(<TaskMarkdown text={"Ask [bot:2] about [task:20]."} />);
|
||||
|
||||
expect(html).not.toContain("[bot:2]");
|
||||
expect(html).toContain("bot 2");
|
||||
expect(html).toContain("Task 20");
|
||||
});
|
||||
|
||||
test("never renders raw HTML", () => {
|
||||
const html = renderToString(<TaskMarkdown text={"<script>alert(1)</script> <b>hi</b>"} />);
|
||||
|
||||
expect(html).not.toContain("<script>");
|
||||
expect(html).not.toContain("<b>");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useContext } from "react";
|
||||
import Markdown from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import { CrewBotsContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-bots-context";
|
||||
import { CrewWorkspacesContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-workspaces-context";
|
||||
import { MessageMarkdownComponents } from "@/src/pages/admin/bots/[bot_id]/(data)/message-markdown-components";
|
||||
import linkComputerRefs from "@/src/utils/link-computer-refs";
|
||||
|
||||
/**
|
||||
* Kept module-level: a new array on every render makes `react-markdown`
|
||||
* parse the text again.
|
||||
*/
|
||||
const RemarkPlugins = [remarkGfm];
|
||||
|
||||
type Props = {
|
||||
text: string;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A task's description or a note on it, rendered like a bot's message
|
||||
* (raw HTML never rendered, links in a new tab, refs as their chips). The
|
||||
* crew the chips link to is the page's own when no conversation around it
|
||||
* gives one. The message elements reach this file again through the task
|
||||
* chip, so they're read when it renders, never at load.
|
||||
*/
|
||||
export default function TaskMarkdown({ text, className }: Props) {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
const crew_bots = useContext(CrewBotsContext);
|
||||
const crew_workspaces = useContext(CrewWorkspacesContext);
|
||||
const bots = crew_bots.length ? crew_bots : pageProps?.workspace_bots || pageProps?.bots || [];
|
||||
const workspaces = crew_workspaces.length ? crew_workspaces : pageProps?.workspaces || [];
|
||||
|
||||
return (
|
||||
<CrewBotsContext.Provider value={bots}>
|
||||
<CrewWorkspacesContext.Provider value={workspaces}>
|
||||
<Stack className={twMerge("w-full min-w-0 gap-2! items-stretch", className)}>
|
||||
<Markdown remarkPlugins={RemarkPlugins} components={MessageMarkdownComponents}>
|
||||
{linkComputerRefs({ text })}
|
||||
</Markdown>
|
||||
</Stack>
|
||||
</CrewWorkspacesContext.Provider>
|
||||
</CrewBotsContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { TaskNote } from "@/src/types";
|
||||
import relativeTime from "@/src/utils/relative-time";
|
||||
import TaskMarkdown from "./task-markdown";
|
||||
|
||||
type Props = {
|
||||
note: TaskNote;
|
||||
@@ -10,7 +11,7 @@ type Props = {
|
||||
|
||||
/**
|
||||
* One note on an opened task: who wrote it (the user, or the bot by name),
|
||||
* how long ago, and what it says.
|
||||
* how long ago, and what it says (markdown, like a message).
|
||||
*/
|
||||
export default function TaskNoteRow({ note }: Props) {
|
||||
const author = note.author == "user" ? "You" : note.bot_name || "Bot";
|
||||
@@ -25,7 +26,7 @@ export default function TaskNoteRow({ note }: Props) {
|
||||
</Span>
|
||||
) : null}
|
||||
</Row>
|
||||
<Span className="whitespace-pre-wrap text-[13px] leading-[18px] text-ink">{note.text}</Span>
|
||||
{note.text ? <TaskMarkdown text={note.text} /> : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -639,6 +639,12 @@ export const AppData = {
|
||||
* reads it through `grabReplyMaxToolSteps`.
|
||||
*/
|
||||
BotReplyMaxToolSteps: 20,
|
||||
/**
|
||||
* From this many characters, a bot message whose run called no tools
|
||||
* shows "No tools used" under it (`MessageNoToolsChip`): a long report
|
||||
* with nothing behind it was made up, and the user acted on one.
|
||||
*/
|
||||
MessageNoToolsMinChars: 400,
|
||||
/**
|
||||
* Messages a chat reply may send while it works (`send_message`):
|
||||
* acknowledging something the user wrote meanwhile, a heads-up. Its
|
||||
|
||||
@@ -238,7 +238,7 @@ export const workspaceAdminsLine = ({ admins }: { admins: { id?: number | "" }[]
|
||||
*/
|
||||
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. End it with the next step you'd suggest, as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
|
||||
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. End it with the next step you'd suggest, as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
|
||||
|
||||
/**
|
||||
* Added to every run: the shared to-do list, and how a bot keeps it
|
||||
|
||||
@@ -373,4 +373,74 @@ describe("runTextLoop", () => {
|
||||
expect(seen[1]!.messages.at(-1)!.content).toContain("Also this.");
|
||||
expect(seen[1]!.messages.at(-1)!.content).toContain("You've used every step");
|
||||
});
|
||||
|
||||
test("writes an answer the review faults again, once, with its note and the tool calls", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ text: null, tool_calls: [{ id: "c1", name: "remember", arguments: '{"note":"x"}' }] },
|
||||
{ text: "I'm scanning now. Scan done: 5 contests." },
|
||||
{ text: "I haven't scanned yet." },
|
||||
{ text: "never reached" },
|
||||
]);
|
||||
const reviewed: { text: string; tools: string[] }[] = [];
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Scan." }],
|
||||
tools: [remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
review: async ({ text, tool_uses }) => {
|
||||
reviewed.push({ text, tools: tool_uses.map((use) => use.name) });
|
||||
return "Not sent: nothing scanned.";
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.text).toBe("I haven't scanned yet.");
|
||||
expect(reviewed).toEqual([{ text: "I'm scanning now. Scan done: 5 contests.", tools: ["remember"] }]);
|
||||
expect(seen[2]!.messages.slice(-2)).toEqual([
|
||||
{ role: "assistant", content: "I'm scanning now. Scan done: 5 contests." },
|
||||
{ role: "user", content: "Not sent: nothing scanned." },
|
||||
]);
|
||||
});
|
||||
|
||||
test("lets the answer through when the review passes it or throws", async () => {
|
||||
for (const review of [async () => null, async () => Promise.reject(new Error("db down"))]) {
|
||||
const { generate, seen } = scripted([{ text: "Fine." }]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Hi." }],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
review,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Fine.");
|
||||
expect(seen.length).toBe(1);
|
||||
}
|
||||
});
|
||||
|
||||
test("doesn't review the wrap up", async () => {
|
||||
const { generate } = scripted([
|
||||
{ text: null, tool_calls: [{ id: "c1", name: "remember", arguments: '{"note":"x"}' }] },
|
||||
{ text: "Out of steps." },
|
||||
]);
|
||||
let reviews = 0;
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Go." }],
|
||||
tools: [remember],
|
||||
max_steps: 1,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
review: async () => {
|
||||
reviews++;
|
||||
return "Not sent.";
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Out of steps.");
|
||||
expect(reviews).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -51,6 +51,13 @@ type Params = {
|
||||
* is written again with them in mind.
|
||||
*/
|
||||
incoming?: () => Promise<HarnessMessage[]>;
|
||||
/**
|
||||
* Checks an answer before it's returned, with the tool calls the run
|
||||
* made. A note sends the answer back to be written again with it, once
|
||||
* per run; null lets it through. Not on the wrap up, and a check that
|
||||
* throws lets the answer through.
|
||||
*/
|
||||
review?: (params: { text: string; tool_uses: HarnessToolUse[] }) => Promise<string | null | undefined>;
|
||||
/**
|
||||
* The bot the run is for: its own models are used where it has them.
|
||||
*/
|
||||
@@ -114,7 +121,8 @@ Don't repeat tool calls you have already made.`;
|
||||
* The text harness at work: the model answers or calls tools, tool results
|
||||
* go back to it, and so on until it answers without calling a tool. Tools
|
||||
* run one at a time, in order; images they return follow their results. Stays on one model unless it fails. After
|
||||
* `max_steps` turns the model is asked to wrap up without tools.
|
||||
* `max_steps` turns the model is asked to wrap up without tools. An answer
|
||||
* `review` finds fault with is written again once.
|
||||
*/
|
||||
export default async function runTextLoop({
|
||||
system,
|
||||
@@ -124,6 +132,7 @@ export default async function runTextLoop({
|
||||
signal = new AbortController().signal,
|
||||
onStep,
|
||||
incoming,
|
||||
review,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
generate = generateText,
|
||||
@@ -140,6 +149,7 @@ export default async function runTextLoop({
|
||||
};
|
||||
const tool_uses: HarnessToolUse[] = [];
|
||||
let prefer_key: string | undefined;
|
||||
let reviewed = false;
|
||||
|
||||
for (let index = 0; index <= max_steps; index++) {
|
||||
if (signal.aborted) {
|
||||
@@ -203,6 +213,17 @@ export default async function runTextLoop({
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!tool_calls.length && !wrap_up && review && !reviewed) {
|
||||
reviewed = true;
|
||||
|
||||
const note = await review({ text: answer.text || "", tool_uses }).catch(() => null);
|
||||
|
||||
if (note) {
|
||||
pushUserTurn({ transcript, content: note });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (!tool_calls.length) {
|
||||
return {
|
||||
text:
|
||||
|
||||
@@ -58,6 +58,11 @@ type Params = {
|
||||
* copied from one it can already read.
|
||||
*/
|
||||
scopes?: StorageScope[];
|
||||
/**
|
||||
* The user follows the conversation (not a chatroom's hidden session):
|
||||
* only then may the reply delete tasks.
|
||||
*/
|
||||
attended?: boolean;
|
||||
/**
|
||||
* Called when the bot asks the user to take over a computer.
|
||||
*/
|
||||
@@ -110,6 +115,7 @@ export default async function grabBotChatTools({
|
||||
workspace_id,
|
||||
message_id,
|
||||
scopes = [],
|
||||
attended,
|
||||
onTakeOver,
|
||||
onPropose,
|
||||
onWorkspaceAdmin,
|
||||
@@ -126,6 +132,7 @@ export default async function grabBotChatTools({
|
||||
is_coordinator: powers.is_coordinator,
|
||||
admin_workspace_ids: powers.admin_workspace_ids,
|
||||
scopes,
|
||||
can_delete_tasks: Boolean(attended),
|
||||
onPropose,
|
||||
onChatroom,
|
||||
})),
|
||||
|
||||
@@ -48,6 +48,10 @@ type Params = {
|
||||
* The run is a hook call, so it gets no hook tools.
|
||||
*/
|
||||
hooked?: boolean;
|
||||
/**
|
||||
* A chat reply the user follows, which may delete tasks.
|
||||
*/
|
||||
can_delete_tasks?: boolean;
|
||||
/**
|
||||
* In a chat reply: called with each hook proposal's ref, so the reply
|
||||
* carries its card. Without it the bot can't propose hooks.
|
||||
@@ -77,6 +81,7 @@ export default async function grabBotTools({
|
||||
admin_workspace_ids,
|
||||
scopes = [],
|
||||
hooked,
|
||||
can_delete_tasks,
|
||||
onPropose,
|
||||
onChatroom,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
@@ -106,6 +111,7 @@ export default async function grabBotTools({
|
||||
is_coordinator: Boolean(is_coordinator),
|
||||
admin_workspace_ids,
|
||||
workspace_id,
|
||||
can_delete: Boolean(can_delete_tasks) && !hooked,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import startTaskTool from "./start-task-tool";
|
||||
|
||||
const tool = startTaskTool({ user_id: 1, bot_id: 5, session_id: 9, computers: [] });
|
||||
|
||||
/**
|
||||
* The step budget the queuing bot sets, kept to what needs no database:
|
||||
* `runBotTask` caps the run at it, below the install's limit.
|
||||
*/
|
||||
describe("startTaskTool", () => {
|
||||
test("takes a step budget within the app's limit", () => {
|
||||
const brief = { title: "Find the contest", instructions: "Look it up." };
|
||||
|
||||
expect(tool.schema?.safeParse({ ...brief, max_steps: 20 }).success).toBe(true);
|
||||
expect(tool.schema?.safeParse(brief).success).toBe(true);
|
||||
expect(tool.schema?.safeParse({ ...brief, max_steps: 0 }).success).toBe(false);
|
||||
expect(tool.schema?.safeParse({ ...brief, max_steps: AppData.BotStepLimitMax + 1 }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
|
||||
import enqueueBotJob from "@/src/functions/backend/db/bots-queue/enqueue-bot-job";
|
||||
import countComputerTaskJobs from "@/src/functions/backend/db/bots-queue/count-computer-task-jobs";
|
||||
@@ -27,6 +28,7 @@ type Args = {
|
||||
instructions: string;
|
||||
computer_id?: number;
|
||||
separate?: boolean;
|
||||
max_steps?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -39,7 +41,10 @@ type Args = {
|
||||
* work (one task per computer, so a repeat would only wait behind it).
|
||||
* Different work is queued then and there with `separate`: nothing runs
|
||||
* when a run ends but posting its result, so a bot that said "once that's
|
||||
* done I'll start the next one" never did.
|
||||
* done I'll start the next one" never did. `max_steps` caps the run's
|
||||
* model turns below the install's limit (`params.max_steps`, read by
|
||||
* `runBotTask`): a bot told to "keep it to ~20 steps" only wrote it in
|
||||
* its brief, and the run searched on for 40 minutes.
|
||||
*/
|
||||
export default function startTaskTool({
|
||||
user_id,
|
||||
@@ -67,6 +72,15 @@ export default function startTaskTool({
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("For different work while another run of yours is open here on that computer: it's queued and starts when that one ends. Never to retry or redo the open run."),
|
||||
max_steps: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(AppData.BotStepLimitMax)
|
||||
.optional()
|
||||
.describe(
|
||||
"The most model turns the run may take (each turn is one or more tool calls), enforced by the app; leave out for the install's limit. Set it whenever the user asked to keep a run short or cheap, and for lookups and searches (about 15 to 30), so a run that can't find something stops and reports what it tried instead of searching on.",
|
||||
),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const same = await grabOpenBotTask({ bot_id, session_id, title: args.title });
|
||||
@@ -95,11 +109,12 @@ export default function startTaskTool({
|
||||
instructions: args.instructions,
|
||||
message_id,
|
||||
computer_id: computer_id || undefined,
|
||||
params: args.max_steps ? { max_steps: args.max_steps } : undefined,
|
||||
});
|
||||
|
||||
const ahead = computer_id ? await countComputerTaskJobs({ computer_id, except_job_id: job_id }) : 0;
|
||||
|
||||
return `Run #${job_id} queued; you'll work on it yourself in the background. It's not on the task list (list_tasks), so never tell the user to look for it there. ${
|
||||
return `Run #${job_id} queued${args.max_steps ? ` with at most ${args.max_steps} steps` : ""}; you'll work on it yourself in the background. It's not on the task list (list_tasks), so never tell the user to look for it there. ${
|
||||
ahead
|
||||
? `The computer has ${ahead} other ${ahead == 1 ? "run" : "runs"} queued or working (they go one at a time), so it waits for ${ahead == 1 ? "it" : "them"} first: tell the user it's queued behind other work, not that it's running. `
|
||||
: ""
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import deleteTaskTool from "./delete-task-tool";
|
||||
import grabBotTaskTools from "./grab-bot-task-tools";
|
||||
|
||||
/**
|
||||
* What needs no database: who gets the tool and what it tells the bot.
|
||||
* The delete itself, and its reach checks, reach the DB.
|
||||
*/
|
||||
describe("deleteTaskTool", () => {
|
||||
test("only a run that may delete gets it", async () => {
|
||||
const names = async (can_delete?: boolean) =>
|
||||
(await grabBotTaskTools({ user_id: 1, bot_id: 5, is_coordinator: false, can_delete })).map(
|
||||
(tool) => tool.name,
|
||||
);
|
||||
|
||||
expect(await names(true)).toContain("delete_task");
|
||||
expect(await names(false)).not.toContain("delete_task");
|
||||
expect(await names()).not.toContain("delete_task");
|
||||
});
|
||||
|
||||
test("takes a task id and says cancelling isn't deleting", () => {
|
||||
const tool = deleteTaskTool({ user_id: 1, bot_id: 5, is_coordinator: false });
|
||||
|
||||
expect(tool.schema?.safeParse({ task_id: 20 }).success).toBe(true);
|
||||
expect(tool.schema?.safeParse({}).success).toBe(false);
|
||||
expect(tool.description).toContain("Only when the user asked");
|
||||
expect(tool.description).toContain("cancelling isn't deleting");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { z } from "zod";
|
||||
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
|
||||
import deleteTask from "@/src/functions/backend/db/tasks/delete-task";
|
||||
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
is_coordinator: boolean;
|
||||
/**
|
||||
* The workspaces the bot is admin of (`grabBotRunPowers`).
|
||||
*/
|
||||
admin_workspace_ids?: number[];
|
||||
};
|
||||
|
||||
type Args = {
|
||||
task_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Lets a chat reply delete a task the user asked to have deleted, with its
|
||||
* notes and file links (`deleteTask`; the files stay where they live).
|
||||
* Without it, bots cancelled tasks and told the user they were removed.
|
||||
* The run must reach the task (`grabRunTask`) and so must its user
|
||||
* (`assertUserReachesTask`). Only chat replies get it: a routine, a hook
|
||||
* call or a chatroom run has no user asking, and a payload could ask for it.
|
||||
*/
|
||||
export default function deleteTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids = [] }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "delete_task",
|
||||
description: `Delete a task from the to-do list for good, with its notes and file links (the files themselves stay). Only when the user asked for that task, or tasks like it, to be deleted; work that was dropped but should stay on record is cancelled with update_task instead. Say "deleted" only after this call says so; cancelling isn't deleting.`,
|
||||
schema: z.object({
|
||||
task_id: z.number().int(),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
|
||||
|
||||
await assertUserReachesTask({ user_id, task_id: task.id! });
|
||||
await deleteTask({ user_id, task_id: task.id!, deleted_by_bot_id: bot_id });
|
||||
|
||||
return `Deleted task #${task.id} "${task.title || "Untitled"}". It no longer exists, so don't update or link it again.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-
|
||||
import grabStorageScopes from "@/src/utils/storage-access";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
import createTaskTool from "./create-task-tool";
|
||||
import deleteTaskTool from "./delete-task-tool";
|
||||
import listTasksTool from "./list-tasks-tool";
|
||||
import updateTaskTool from "./update-task-tool";
|
||||
|
||||
@@ -21,6 +22,11 @@ type Params = {
|
||||
*/
|
||||
admin_workspace_ids?: number[];
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* A chat reply the user follows: it also gets delete_task. Never a
|
||||
* routine, a hook call or a chatroom run.
|
||||
*/
|
||||
can_delete?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -30,6 +36,7 @@ type Params = {
|
||||
* move it along and file what they produced. The coordinator's create_task
|
||||
* may target any worker or workspace; its update_task may link any file it
|
||||
* can reach. A workspace admin's may give tasks there to the other members.
|
||||
* Only a chat reply the user follows deletes tasks (`can_delete`).
|
||||
*/
|
||||
export default async function grabBotTaskTools({
|
||||
user_id,
|
||||
@@ -37,6 +44,7 @@ export default async function grabBotTaskTools({
|
||||
is_coordinator,
|
||||
admin_workspace_ids = [],
|
||||
workspace_id,
|
||||
can_delete,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
let workers: BUN_SQLITE_COBBLE_BOTS[] = [];
|
||||
let members: BUN_SQLITE_COBBLE_BOTS[] = [];
|
||||
@@ -76,5 +84,6 @@ export default async function grabBotTaskTools({
|
||||
members,
|
||||
}),
|
||||
updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, scopes }),
|
||||
...(can_delete ? [deleteTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids })] : []),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import GroupTimestamp from "./group-timestamp";
|
||||
import MessageActions from "./message-actions";
|
||||
import MessageReactions from "./message-reactions";
|
||||
import MessageReplyQuote from "./message-reply-quote";
|
||||
import MessageNoToolsChip from "./message-no-tools-chip";
|
||||
import MessageUsageChip from "./message-usage-chip";
|
||||
import NeedsYouChip from "./needs-you-chip";
|
||||
import SpeakMessageButton from "./speak-message-button";
|
||||
@@ -85,6 +86,7 @@ function BotMessageLine({ message, bot_name, at }: Props) {
|
||||
{message.needs_you ? <NeedsYouChip /> : null}
|
||||
{at ? <GroupTimestamp at={at} /> : null}
|
||||
<MessageUsageChip usage={message.usage} />
|
||||
<MessageNoToolsChip message={message} />
|
||||
{can_speak ? (
|
||||
<SpeakMessageButton message_id={Number(message.id)} />
|
||||
) : null}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import toolLogCount from "@/src/utils/tool-log-count";
|
||||
|
||||
type Props = {
|
||||
message: Pick<BotMessageWithAttachments, "author" | "text" | "tool_log">;
|
||||
};
|
||||
|
||||
/**
|
||||
* "No tools used" under a long bot message whose run called no tool, in
|
||||
* the row beside its timestamp: such a message can only say what the bot
|
||||
* already knew, so a report of work in it wasn't done. A bot wrote a
|
||||
* contest scan with links and a file in one, and the user acted on it.
|
||||
*/
|
||||
export default function MessageNoToolsChip({ message }: Props) {
|
||||
if (message.author != "bot") return null;
|
||||
if ((message.text || "").length < AppData.MessageNoToolsMinChars) return null;
|
||||
if (toolLogCount({ tool_log: message.tool_log }) !== 0) return null;
|
||||
|
||||
return (
|
||||
<Span
|
||||
title="The app's record shows this message's run called no tools: nothing was browsed, saved or changed for it."
|
||||
className="text-[11px] leading-4 text-ink-secondary whitespace-nowrap cursor-help"
|
||||
>
|
||||
No tools used
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
@@ -27,6 +27,9 @@
|
||||
@source not "../styles/**";
|
||||
@source not "../utils/**";
|
||||
@source not "../websocket/**";
|
||||
/* Pages, hooks and types still name refs in their comments (`[task:ID]`), so
|
||||
the ref forms themselves are never utilities, wherever they're written. */
|
||||
@source not inline("[{bot,workspace,computer,file,folder,task,room,graphic,question,proposal,hook-proposal,secret,secret-request,take-over}:ID]");
|
||||
|
||||
/* Cobble design tokens (handoff `tokens/tokens.css`). Light on `:root`, dark
|
||||
on `.dark` (twui's dark variant). Exposed to Tailwind in `@theme inline`. */
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import claimsWorkUnderWay from "./claims-work-under-way";
|
||||
|
||||
describe("claimsWorkUnderWay", () => {
|
||||
test("catches the lines replies wrote before made-up results", () => {
|
||||
for (const text of [
|
||||
"I'm browsing the open contests on your account now, filtering for ones that fit your style.",
|
||||
"I'm scanning the open contests now with a fresh list. When it's back, I'll create proper tasks.",
|
||||
"I'm running the scan for real now: one pass over the open-contest listing.",
|
||||
"I'm reading contest #1's full brief in the background right now.",
|
||||
"Creating tasks now. Report follows in the next message.",
|
||||
"I'll report back with the links once that run completes.",
|
||||
"I’m checking your inbox now.",
|
||||
]) {
|
||||
expect(claimsWorkUnderWay({ text })).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("leaves answers that only report or offer alone", () => {
|
||||
for (const text of [
|
||||
"Done. Task #20 is cancelled with a note.",
|
||||
"Want me to start on contest 2 now?",
|
||||
"I'm sorry, that contest isn't open any more.",
|
||||
"I checked the board: 3 web design contests are open.",
|
||||
"Right now there are 147 open contests.",
|
||||
]) {
|
||||
expect(claimsWorkUnderWay({ text })).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
type Params = {
|
||||
text: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* How an answer says work is going on after it, or that a report will
|
||||
* follow: the line a reply writes once it started a run ("I'm browsing
|
||||
* the open contests now. I'll report back."). Written without starting
|
||||
* one, it was followed by results made up on the spot.
|
||||
*/
|
||||
const UnderWayPatterns = [
|
||||
/\bI(?:'|’)m\s+(?:now\s+)?[a-z]+ing\b[^.!?\n]{0,160}\bnow\b/i,
|
||||
/\bin the background\b/i,
|
||||
/\bI(?:'|’)ll\s+(?:report back|get back to you|let you know when|bring (?:you |it )?back|report (?:the|my) (?:results?|findings))/i,
|
||||
/\b(?:report|results?|details|update)\s+(?:follows|will follow|to follow|coming)\b/i,
|
||||
/\bin (?:my|the|a) (?:next|following) message\b/i,
|
||||
/\b(?:when|once) (?:it|that|the (?:run|scan|search|check))(?:'|’)?s? (?:back|done|finished|complete)\b/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* True when the answer says work is under way beyond it or that a report
|
||||
* will follow (`UnderWayPatterns`). Only a started run makes that true,
|
||||
* so a reply that says it without one is sent back (`reviewBotReply`).
|
||||
*/
|
||||
export default function claimsWorkUnderWay({ text }: Params) {
|
||||
return UnderWayPatterns.some((pattern) => pattern.test(text));
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import replyClaimProblems from "./reply-claim-problems";
|
||||
|
||||
const underWay = "I'm scanning the open contests now. When it's back, I'll create the tasks.";
|
||||
|
||||
describe("replyClaimProblems", () => {
|
||||
test("faults work said to be under way when nothing was started or is open", () => {
|
||||
const problems = replyClaimProblems({ text: underWay, tool_uses: [] });
|
||||
|
||||
expect(problems.length).toBe(1);
|
||||
expect(problems[0]).toContain("start_task");
|
||||
});
|
||||
|
||||
test("passes it once a run was started, handed over or a room asked, or one is open", () => {
|
||||
for (const name of ["start_task", "delegate_task", "ask_crew"]) {
|
||||
expect(replyClaimProblems({ text: underWay, tool_uses: [{ name, ok: true }] })).toEqual([]);
|
||||
}
|
||||
|
||||
expect(replyClaimProblems({ text: underWay, tool_uses: [], has_open_work: true })).toEqual([]);
|
||||
});
|
||||
|
||||
test("a start_task call that failed doesn't count", () => {
|
||||
expect(replyClaimProblems({ text: underWay, tool_uses: [{ name: "start_task", ok: false }] }).length).toBe(1);
|
||||
});
|
||||
|
||||
test("names files and tasks that don't exist", () => {
|
||||
const problems = replyClaimProblems({
|
||||
text: "Saved in [file:301]; see [task:20].",
|
||||
tool_uses: [{ name: "list_tasks", ok: true }],
|
||||
missing_file_ids: [301],
|
||||
missing_task_ids: [20],
|
||||
});
|
||||
|
||||
expect(problems.length).toBe(2);
|
||||
expect(problems[0]).toContain("[file:301]");
|
||||
expect(problems[1]).toContain("[task:20]");
|
||||
});
|
||||
|
||||
test("an answer that holds up has no problems", () => {
|
||||
expect(replyClaimProblems({ text: "Task #20 is cancelled.", tool_uses: [] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import claimsWorkUnderWay from "./claims-work-under-way";
|
||||
|
||||
type Params = {
|
||||
text: string;
|
||||
/**
|
||||
* Every tool call the reply made so far.
|
||||
*/
|
||||
tool_uses: HarnessToolUse[];
|
||||
/**
|
||||
* `[file:ID]` refs in the text that name no file the user can open.
|
||||
*/
|
||||
missing_file_ids?: number[];
|
||||
/**
|
||||
* `[task:ID]` refs in the text that name no task the user can open.
|
||||
*/
|
||||
missing_task_ids?: number[];
|
||||
/**
|
||||
* A run of the bot's, a job it handed over or a room it asked, still
|
||||
* open from this conversation: its result is still to come.
|
||||
*/
|
||||
has_open_work?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The tools whose work goes on after the reply and comes back to the
|
||||
* conversation.
|
||||
*/
|
||||
const WorkStartingTools = ["start_task", "delegate_task", "ask_crew"];
|
||||
|
||||
/**
|
||||
* What in a reply's answer the app's record contradicts: refs to files or
|
||||
* tasks that don't exist, and work said to be under way or a report
|
||||
* promised when nothing was started and nothing is open. Empty when the
|
||||
* answer holds up. Bots wrote "I'm scanning the contests now" and the
|
||||
* scan's results in one answer, with no tool called and a made-up file.
|
||||
*/
|
||||
export default function replyClaimProblems({
|
||||
text,
|
||||
tool_uses,
|
||||
missing_file_ids = [],
|
||||
missing_task_ids = [],
|
||||
has_open_work,
|
||||
}: Params): string[] {
|
||||
const problems: string[] = [];
|
||||
|
||||
if (missing_file_ids.length) {
|
||||
problems.push(
|
||||
`It names ${missing_file_ids.map((id) => `[file:${id}]`).join(", ")}, but no such file exists. A file exists only once write_file, make_pdf, generate_image or import_file saved it; list_files shows what's there.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (missing_task_ids.length) {
|
||||
problems.push(
|
||||
`It names ${missing_task_ids.map((id) => `[task:${id}]`).join(", ")}, which ${missing_task_ids.length == 1 ? "is" : "are"} no task the user can open (never created, or deleted). list_tasks shows what's there.`,
|
||||
);
|
||||
}
|
||||
|
||||
const started = tool_uses.some((use) => use.ok && WorkStartingTools.includes(use.name));
|
||||
|
||||
if (!started && !has_open_work && claimsWorkUnderWay({ text })) {
|
||||
problems.push(
|
||||
`It says work is under way or that a report will follow, but this reply started no run (start_task) and nothing of yours is open in this conversation. Nothing is running, so no result will come unless you call start_task now.`,
|
||||
);
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import replyRefIds from "./reply-ref-ids";
|
||||
|
||||
describe("replyRefIds", () => {
|
||||
test("reads each ref of the kind once, links and code spans included", () => {
|
||||
const text = "Notes in [file:294](99designs/notes.md), scan in `[file:301]`, again [file:294]; [task:20] and [ task:21 ].";
|
||||
|
||||
expect(replyRefIds({ text, kind: "file" })).toEqual([294, 301]);
|
||||
expect(replyRefIds({ text, kind: "task" })).toEqual([20]);
|
||||
});
|
||||
|
||||
test("finds nothing in plain text", () => {
|
||||
expect(replyRefIds({ text: "file 301 and task #20", kind: "file" })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
type Params = {
|
||||
text: string;
|
||||
/**
|
||||
* The ref's kind, as in `[file:12]` or `[task:20]`.
|
||||
*/
|
||||
kind: "file" | "task";
|
||||
};
|
||||
|
||||
/**
|
||||
* The ids of every `[<kind>:ID]` ref in a message, once each, in order:
|
||||
* what a reply names, for checking each exists before it goes out.
|
||||
*/
|
||||
export default function replyRefIds({ text, kind }: Params): number[] {
|
||||
const pattern = new RegExp(`\\[${kind}:\\s*(\\d+)\\s*\\]`, "gi");
|
||||
const ids: number[] = [];
|
||||
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
const id = Number(match[1]);
|
||||
|
||||
if (Number.isInteger(id) && id > 0 && !ids.includes(id)) ids.push(id);
|
||||
}
|
||||
|
||||
return ids;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import toolLogCount from "./tool-log-count";
|
||||
|
||||
describe("toolLogCount", () => {
|
||||
test("counts a recorded run's calls, none included", () => {
|
||||
expect(toolLogCount({ tool_log: "[]" })).toBe(0);
|
||||
expect(toolLogCount({ tool_log: '[{"name":"start_task","ok":true}]' })).toBe(1);
|
||||
});
|
||||
|
||||
test("is null when the run wasn't recorded", () => {
|
||||
expect(toolLogCount({ tool_log: null })).toBeNull();
|
||||
expect(toolLogCount({ tool_log: "" })).toBeNull();
|
||||
expect(toolLogCount({ tool_log: "{oops" })).toBeNull();
|
||||
expect(toolLogCount({ tool_log: "{}" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
type Params = {
|
||||
/**
|
||||
* A bot message's `tool_log` (JSON list of `{ name, ok }`).
|
||||
*/
|
||||
tool_log?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many tool calls a bot message's run made, or null when its run
|
||||
* wasn't recorded (a user message, an interim one, an older message).
|
||||
*/
|
||||
export default function toolLogCount({ tool_log }: Params): number | null {
|
||||
if (!tool_log) return null;
|
||||
|
||||
try {
|
||||
const uses = JSON.parse(tool_log);
|
||||
|
||||
return Array.isArray(uses) ? uses.length : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user