Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a808d8417 | ||
|
|
585b77eec1 | ||
|
|
74693cccd3 | ||
|
|
115113247f | ||
|
|
14fc5e9d6e | ||
|
|
84ae51c621 | ||
|
|
60e3d3bfbf | ||
|
|
ab384ff175 | ||
|
|
700a2bcd86 | ||
|
|
14d4c10782 | ||
|
|
26424560da | ||
|
|
ece7ebf1b2 | ||
|
|
7bdd288f36 | ||
|
|
9dab068827 | ||
|
|
ef84c8a245 | ||
|
|
4cfbf6f558 | ||
|
|
572b5d239a | ||
|
|
419a50b95b | ||
|
|
c4c86fc66b | ||
|
|
c924ff9776 | ||
|
|
5d79c379dd | ||
|
|
ebc9ade7e0 | ||
|
|
ea4b5c1bf2 | ||
|
|
4063cd3b22 | ||
|
|
3bd749428e | ||
|
|
cd6702de55 | ||
|
|
1a6ae71286 | ||
|
|
7cc881f1da | ||
|
|
b717220bc3 | ||
|
|
6e153d311e | ||
|
|
6532abc715 | ||
|
|
be4eb13a7c | ||
|
|
86d171729f | ||
|
|
38648fc083 | ||
|
|
6414d4e675 | ||
|
|
ae64ef195d | ||
|
|
06a4b7bb36 | ||
|
|
2c8023ee4b | ||
|
|
c0e79ee39c | ||
|
|
bc9739509c | ||
|
|
4d6c330954 | ||
|
|
78accbcc4f | ||
|
|
5601e2c2b8 | ||
|
|
7c678284ae | ||
|
|
8c868d6a04 | ||
|
|
179ff03d20 | ||
|
|
0a19c2a3a9 | ||
|
|
c3be864136 | ||
|
|
e40fa823cb | ||
|
|
4593decc13 | ||
|
|
0512dd3e10 | ||
|
|
f9f6fa5a93 | ||
|
|
ddaf6aa720 | ||
|
|
876cc0ff4c | ||
|
|
4137fed085 | ||
|
|
3eced5886e | ||
|
|
877fcf82e0 | ||
|
|
f6b5795ed6 | ||
|
|
f08d12a176 | ||
|
|
f61676ca08 | ||
|
|
4cc70e7f35 | ||
|
|
e83e1e4951 | ||
|
|
1543fa160f | ||
|
|
72086ffa38 | ||
|
|
40af378915 | ||
|
|
d8e63d1e3b | ||
|
|
7da2bd6941 | ||
|
|
5842735813 | ||
|
|
6312c92334 | ||
|
|
63d25337f5 | ||
|
|
3cbfb4e3da |
@@ -16,3 +16,5 @@ coverage
|
||||
logs
|
||||
*.log
|
||||
assets
|
||||
# The computer image builds on its own (computer/Dockerfile).
|
||||
computer
|
||||
|
||||
@@ -11,6 +11,11 @@ on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
rebuild_computer:
|
||||
description: Rebuild the computer image even if its version is already published (picks up a newer Chrome).
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -94,3 +99,59 @@ jobs:
|
||||
sbom: false
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
# The computers' image (computer/), versioned by its tag in
|
||||
# AppData.ComputerImage rather than the app's version: a release builds it
|
||||
# only when that tag isn't published yet (or when a dispatch asks), so
|
||||
# computers already running it are never changed under them.
|
||||
computer-image:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: docker/setup-qemu-action@v3
|
||||
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to GHCR
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Read the computer image's tag
|
||||
id: computer
|
||||
env:
|
||||
REBUILD: ${{ github.event.inputs.rebuild_computer }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
image="$(sed -n -E 's/^[[:space:]]*ComputerImage: "([^"]+)",?$/\1/p' src/data/app-data.ts | head -n1)"
|
||||
case "$image" in
|
||||
ghcr.io/moduletrace/cobble-computer:*) ;;
|
||||
*) echo "AppData.ComputerImage isn't a ghcr.io/moduletrace/cobble-computer tag: '$image'" >&2; exit 1 ;;
|
||||
esac
|
||||
build=true
|
||||
if [ "$REBUILD" != "true" ] && docker manifest inspect "$image" > /dev/null 2>&1; then
|
||||
build=false
|
||||
fi
|
||||
{
|
||||
echo "image=$image"
|
||||
echo "build=$build"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push the computer image
|
||||
if: steps.computer.outputs.build == 'true'
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./computer
|
||||
file: ./computer/Dockerfile
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
${{ steps.computer.outputs.image }}
|
||||
ghcr.io/moduletrace/cobble-computer:latest
|
||||
provenance: false
|
||||
sbom: false
|
||||
cache-from: type=gha,scope=computer
|
||||
cache-to: type=gha,mode=max,scope=computer
|
||||
|
||||
@@ -54,13 +54,13 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### Auth
|
||||
|
||||
- **Guard:** `src/pages/__root.server.ts` on every request. No public pages: anything outside `AdminSections` (`src/dict/admin-sections-dict.ts`) and `/auth` redirects to `/admin/bots`. No users -> `/auth/signup` (first-run super admin only, which then opens the skippable guided setup `/admin/settings/setup`: app name, provider, models, where to go next; it stays under Settings); unauthenticated `/admin/*` -> `/auth/login`; authenticated `/auth/*` (not logout) -> `/admin/bots`; unknown `/admin/settings/*` -> `/admin/settings/general`.
|
||||
- **Guard:** `src/pages/__root.server.ts` on every request. No public pages: anything outside `AdminSections` (`src/dict/admin-sections-dict.ts`) and `/auth` redirects to `/admin/bots`. No users -> `/auth/signup` (first-run super admin only, which then opens the skippable guided setup `/admin/settings/setup`: app name, provider, models, where to go next; it stays under Settings; or Restore from a backup: another install's database file or data archive, told apart by their bytes, through public `api/auth/bootstrap-restore`, refused once any user exists or for a database with no users, restored like Settings > Backups and then the app restarts, the page polling `bootstrap-status` and going to the login); unauthenticated `/admin/*` -> `/auth/login`; authenticated `/auth/*` (not logout) -> `/admin/bots`; unknown `/admin/settings/*` -> `/admin/settings/general`.
|
||||
- **Session:** AES-256-GCM cookie (key from `ENCRYPTION_KEY`/`ENCRYPTION_SALT`) plus CSRF cookie, `Secure` only over HTTPS (`isSecureRequest`, honours `X-Forwarded-Proto`). `userAuth` (`src/functions/backend/auth/user-auth.ts`) checks expiry (60 days), CSRF (constant-time) and re-reads `user_types` every request.
|
||||
- **Login:** email/username + password (`api/auth/password-login.ts`, rate limited). No emailed codes or resets. Google login only for existing accounts, when `GOOGLE_CLIENT_ID` is set. Sessions issued by `login-user.ts`.
|
||||
- **Passwords:** bcrypt in `user_passwords` (never in `users`; blocked from CRUD via `src/dict/private-tables.ts`).
|
||||
- **User types** (`src/dict/user-types-dict.ts`, the only definition): `super_admin` (user #1), `admin` (only the super admin grants it), `member` (default), `read_only` (non-GET CRUD blocked), `revoked`. A user needs at least one type to sign in.
|
||||
- **RBAC:** `src/utils/check-user-access.ts` plus the matrix engine in `src/utils/rbac/` (`userTypeAssignment` over `UserTypeAssignmentMatrix`/`UserTypeDeletionMatrix`).
|
||||
- **Audit:** `src/functions/backend/logger.ts` (`logEvent`/`logError` -> `logs`). Auth events, cron runs, every unexpected API error (`safeErrorMessage` -> `logUnexpectedError`, not for `AppError`), every failed or lost bot job. WebSocket connects are not logged. Kept for the app setting `logs_keep_days` (default `AppData.LogsKeepDays`), deleted by the daily `prune-logs`.
|
||||
- **Audit:** `src/functions/backend/logger.ts` (`logEvent`/`logError` -> `logs`). Auth events, cron runs, every unexpected API error (`safeErrorMessage` -> `logUnexpectedError`, not for `AppError`), every failed or lost bot job, every failed model call (category `llm`, `logCandidateFailure`; older `system` rows moved at boot by `migrateLlmLogs`). WebSocket connects are not logged. Kept for the app setting `logs_keep_days` (default `AppData.LogsKeepDays`), deleted by the daily `prune-logs`.
|
||||
|
||||
### WebSocket
|
||||
|
||||
@@ -90,36 +90,38 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet). Enums in `src/dict/bot-dict.ts`.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
|
||||
- **Routes:** `/admin/bots` reopens the last visited bot (cookie `cobble_last_visited_bot_id`, never a workspace conversation) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
|
||||
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
|
||||
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
|
||||
- **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.
|
||||
- **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. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown), checked by the composer before it sends (the reason shows under the input) and again by the route.
|
||||
- **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). Parsers in `src/utils/*-ref.ts`. 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.
|
||||
- **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.
|
||||
- **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 `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/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.
|
||||
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), 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. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). 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. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
|
||||
- **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).
|
||||
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`.
|
||||
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
|
||||
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
|
||||
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages. Tasks don't get files yet.
|
||||
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
|
||||
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
|
||||
- **Pictures:** `image_media_id` (private media, `bot-image`/`workspace-image`), via `set-profile-image.ts`, the `set_picture` tool or `update_workspace`. Bytes are **copied**, never moved; only picture-paradigm rows are deleted on replace. Format kept by `imageOutputFormat`.
|
||||
- **Colour:** only `src/utils/bot-color.ts` resolves/validates colours and stones (`resolveBotColor`, `resolveBotStone`, `botColorNeedsPaperFace`); new bots get `pick-free-color.ts`.
|
||||
- **Avatars:** `BotStone` draws the stone inline with the colour as SVG `fill` and the face as eyes. Coordinator: ink body, paper eyes. **Never put a stone in a circle/badge or add outline/shadow.** The wordmark is vector (`Wordmark`), never live text.
|
||||
- **Avatars:** `BotStone` draws the stone inline with the colour as SVG `fill` and the face as eyes. Coordinator: ink body, paper eyes. Each face moves the stone and its eyes (keyframes `stone-*` in `main.css`; body in `BotStone`, transforms only from its base, never redrawing the outline or cut; eyes in `BotStoneFace`: idle blinks at a per-bot pace, working glances, done hops once, asleep breathes, needs-you nudges; off under reduced motion; `still` for the logo). **Never put a stone in a circle/badge or add outline/shadow.** The wordmark is vector (`Wordmark`), never live text.
|
||||
- **Copy helpers:** `src/utils/crew-status.ts`, `src/utils/relative-time.ts` (relative timestamps only).
|
||||
|
||||
### Prompt and memory
|
||||
|
||||
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context and the bot's instructions there, then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`.
|
||||
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`.
|
||||
|
||||
### Queue (`bots_queue`)
|
||||
|
||||
- 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.
|
||||
- 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`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
|
||||
- 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.
|
||||
- **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.
|
||||
- **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. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
|
||||
|
||||
### Live updates
|
||||
|
||||
@@ -127,22 +129,24 @@ Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`),
|
||||
|
||||
### Chatrooms (`chatrooms`)
|
||||
|
||||
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions; their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
|
||||
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
|
||||
|
||||
### Workspaces
|
||||
|
||||
`workspaces` (`description`, shared `system_prompt`, default `computer_id` (not an FK), `archived`), `workspace_bots` (per-bot instructions and memory there; coordinator is an implicit member), `workspace_computers`. First computer linked becomes the default. Workspace models win over a bot's own, then the defaults. A bot's instructions and memory there (`WorkspaceBotModal`/`WorkspaceBotForm`, crew managers) open from the workspace's settings, the bot's settings and the conversation menu's "Instructions here" (loaded on open). Helpers in `src/functions/backend/db/workspaces/` are access-checked; structural ones are crew-manager only.
|
||||
`workspaces` (`description`, shared `system_prompt`, default `computer_id` (not an FK), `archived`), `workspace_bots` (per-bot instructions and memory there; coordinator is an implicit member), `workspace_computers`. First computer linked becomes the default. Workspace models win over a bot's own, then the defaults. **A user's role in a workspace** (`workspace_user_roles`, plain text, one per user and workspace) tells every bot there who it's working for; it's not their bio, the user never sees or sets it, and only crew managers set it, an admin never a super admin's (`canSetWorkspaceUserRole`, checked in `setWorkspaceUserRole`). Set from the workspace's settings (People, everyone who works there: `workspacePeopleSql`), the user's settings (Roles in workspaces) and by the coordinator (`list_workspace_people`/`set_user_workspace_role`, replies and tasks, saved as the run's user so the same rule holds). It stays when access is taken away, shown and used only while they work there. A bot's instructions and memory there (`WorkspaceBotModal`/`WorkspaceBotForm`, crew managers) open from the workspace's settings, the bot's settings and the conversation menu's "Instructions here" (loaded on open). Helpers in `src/functions/backend/db/workspaces/` are access-checked; structural ones are crew-manager only.
|
||||
|
||||
### Computers
|
||||
|
||||
- An AIO sandbox per docker container on `AppData.DockerNetworkName`, managed over the docker socket (`src/functions/backend/docker/`). `containers` records every container except the app's own. `createComputer` + background `provisionComputer` (status `creating` until the health check passes). Resource changes recreate the container.
|
||||
- **Our own image** (`computer/`, Debian 13, `AppData.ComputerImage`, or the app setting `COMPUTER_IMAGE`), one docker container per computer on `AppData.DockerNetworkName`, managed over the docker socket (`src/functions/backend/docker/`). Google Chrome on amd64, Debian's Chromium on arm64 (Google ships no arm64 Linux Chrome), headful on Xvnc (an X server that is also a VNC server, on loopback), never launched by automation (no automation flags), so it's as close to a real browser as possible. Inside, one agent (`computer/agent/`, Node, no dependencies, bundled by Bun at image build) supervises Xvnc, the session bus, Chrome, Playwright MCP and ttyd and serves one port: `/health` (open), `/api/exec`, `/api/files/*` (shell and files, as `gem` or, with `run_as`, a worker's own account), `/mcp` (proxied to Playwright MCP on loopback, `--shared-browser-context --codegen none --no-webmcp`), `/desktop/` (the screen: noVNC, its `websockify` socket bridged to Xvnc by the agent), `/terminal/` (ttyd). Every request but `/health` needs the computer's token (`computerToken`: HMAC of the id with `ENCRYPTION_KEY`, given as `COBBLE_COMPUTER_TOKEN`), so another computer's bot can't drive it; the app's client is `src/functions/backend/computers/`. **Any change under `computer/` bumps the tag in `AppData.ComputerImage`** (the release workflow builds a tag only once; `bun run build:computer` builds it locally); bump `ComputerWorkspaceLayout` too when existing computers must move to it. `containers` records every container except the app's own. `createComputer` + background `provisionComputer` (status `creating` until the health check passes; while setting up or restarting it touches the row every `ComputerSetupHeartbeatMs`, `keepComputerSetupAlive`, so one the app lost to a restart (`computerSetupInterrupted`) shows as failed with Retry and `sync-computers` starts it again). A setup that fails while the old container still runs (a new image that couldn't be pulled) keeps it running on its old layout (`setup_failed_at`, migration retried after `AppData.ComputerMigrateRetryMs`), and a `failed` row whose container docker runs anyway is revived (`reviveFailedComputer`, from `sync-computers` and `grabComputerMcpUrl`). Resource changes recreate the container.
|
||||
- Only `/home/gem/workspace` is mounted, from `DATA_DIR/computers/<id>` (with `bots/`, `workspaces/`, marker `AppData.ComputerWorkspaceMarker`), plus the browser profile; the rest of home lives in the container.
|
||||
- **Browser profile:** `DATA_DIR/computer-browsers/<id>` mounted at `~/.cobble-browser`, which Chrome is pointed at (`BROWSER_EXTRA_ARGS=--user-data-dir=... --password-store=basic`), so logins, extensions and site permissions survive restarts and recreates. Never use the image's `~/.config/browser`: every boot overwrites its `Default/Preferences` with session-only cookies. Seed prefs (`computer-browser-preferences.ts`) are written only when missing; stale `Singleton*` links are removed before each provision. Bumping `AppData.ComputerWorkspaceLayout` recreates every computer once (`migrateComputerLayout`, skipped while a job runs on it). Default extensions (`ComputerBrowserExtensions`, `normal_installed`: can be turned off, not removed) come from a managed policy written as root into the running container (`syncComputerBrowserPolicy`, on provision and every `sync-computers` run), not a mount, so existing computers get new ones without a recreate; Chrome installs them live. Deleting a computer keeps its directory. Outside docker (dev) containers are reached by IP (`pickReachableAddress`).
|
||||
- **Browser profile:** `DATA_DIR/computer-browsers/<id>` mounted at `~/.cobble-browser`, which the agent starts Chrome with (`--user-data-dir`, `--password-store=basic` so the cookies' key is the same in every container), so logins, extensions and site permissions survive restarts and recreates. Seed prefs (`computer-browser-preferences.ts`) are written only when missing; stale `Singleton*` links are removed before each provision and before each Chrome start. The agent stops Chrome with TERM on `docker stop`, so the profile is saved. **An idle browser is parked:** the virtual screen has no GPU or window manager, so the tab in front is always on show and drawn in software at full rate (one animated site took a core or two); after `COBBLE_BROWSER_PARK_AFTER_SECONDS` (default 180) without a `/mcp` call or screen view the agent puts a blank tab in front of each site on show (`createBrowserParking`, over its own CDP client), and the next `/mcp` call or view brings them back first. Pages are composited in software (`--disable-gpu-compositing`, WebGL unchanged) and the policy sets `TabDiscardingExceptions: ["*"]` so a parked tab never reloads. Bumping `AppData.ComputerWorkspaceLayout` recreates every computer once (`migrateComputerLayout`, skipped while a job runs on it). Default extensions (`ComputerBrowserExtensions`: Cookie-Editor, `normal_installed`: can be turned off, not removed) come from a managed policy written as root into the running container (`syncComputerBrowserPolicy`, on provision and every `sync-computers` run), not a mount, so existing computers get new ones without a recreate; Chrome installs them live. Deleting a computer keeps its directory. Outside docker (dev) containers are reached by IP (`pickReachableAddress`).
|
||||
- **Settings per computer** (super admin, its settings page): resources, and its browser (`browser_settings`, `ComputerBrowserSettingsSchema`: timezone, languages, screen, scale (Chrome's device scale factor, 125% by default: larger text in bots' screenshots), sandbox, lightweight (for small hosts: `--disable-gpu`, so the GPU process loads no Mesa and WebGL is off, reduced motion, no smooth scrolling or component downloads, Xvnc at `LightweightFrameRate` fps), extra Chrome and Playwright MCP flags), passed as env (`computerBrowserEnv`); saving either recreates the container. Chrome reads only one `--disable-features=`/`--enable-features=`, so `browserArgs` merges the agent's with the extra flags' (`mergeFeatureFlags`). Flags that would open DevTools or MCP around the token are refused (`ComputerBlockedBrowserArgs`/`ComputerBlockedMcpArgs`) and dropped again by the agent (`computer/agent/blocked-args.ts`; keep both alike). **Rebuild** (`api/admin/computers/rebuild-computer`) pulls the image again (keeping the local one when the registry has none) and recreates the container; files and logins stay.
|
||||
- One main computer (`ensureMainComputer`), whose coordinator grant is locked (`isLockedComputerAccess`). With `MAIN_COMPUTER_URL` set (dev) it isn't provisioned. Only super admins create/delete/retry/restart computers. Restart (`ComputerRestartButton`, in the shared viewer modal, so every computer modal has it) restarts the same container, so what's installed stays, even with a job on it (`restartComputer`, clearing Chrome's `Singleton*` links while stopped; a container docker lost is provisioned instead).
|
||||
- A bot's effective computers (`grab-bot-computers`): the workspace's in a workspace; otherwise direct grants plus its workspaces' (coordinator: all); `bots.computer_id` first. Only a `running` (healthy) computer is reached (`grabComputerMcpUrl` `ready`, `computerNotReadyMessage`).
|
||||
- **Folders (enforced in tools, not a Linux user):** a run works only in `bots/<bot>/users/<user>` (cwd, `HOME`), `bots/<bot>` and `workspaces/<workspace>` (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`; the file tools' `sudo` refused; bash runs as `gem`, who has sudo, so packages can be installed, and they're lost when the container is recreated).
|
||||
- **Bash on a computer:** the sandbox ignores `sandbox_execute_bash`'s `timeout` and runs every call in one shared shell session, so a command that never ends blocked every later one on that computer, from any run, and Stop never killed it. `withCommandTimeout` runs each in its own `bash -c` under coreutils `timeout` (at most `AppData.ComputerCommandMaxSeconds`, below `McpToolTimeoutMs`), stdin from `/dev/null`. Never `exit` in a wrapper (it would kill the session shell).
|
||||
- **Viewing:** `/computers/<id>/` proxy (`handleComputerProxy`, strips app cookies, bridges websockets). `ComputerView` modes: browser, terminal, code, desktop (noVNC; the only one with Chrome's toolbar). **Take-over:** `ask_user_to_take_over` writes `[take-over:ID:mode]`; "Hand back" sends a chat message; tasks stop and report rather than wait.
|
||||
- **Folders:** a run works only in its user's folder (cwd, `HOME`), its bot's and its workspace's (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`). **A worker sees them through its home:** `/home/cb-<bot>/workspace` (a link the agent keeps to `bots/<bot>`, checked every request by `ensureRunUser`; the rest of the home stays in the container and is never kept), with `users/<user>` and, in a workspace, `workspaces/<id>` (a link to the shared `workspaces/<id>`) inside it; the coordinator works in `bots/<bot>/users/<user>` and reaches the whole workspace. Paths are checked on their real place (`computerWorkspacePath`) and shown to a worker its way (`computerRunPath`); computer folder refs take either spelling. Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
|
||||
- **Installs:** workers install pip/npm packages into `~/.local` of their folder themselves; anything needing root goes through `request_install` (worker task runs the user follows) -> `install_requests` -> a coordinator task on that computer in the super admin's coordinator conversation (`createInstallRequest`, fenced `installRequestBlock`, `InstallRequestNote`, `answer_install_request`); when that job ends however it ends (`settleInstallRequest`, from the job helpers) the answer lands in the worker's session as a crew message (`from_install_request_id`, `isCrewMessage`) and wakes it. Stop also ends a worker's leftover processes on its computers (`endWorkerProcesses`).
|
||||
- **Tools:** the app's own `computer_bash`, `computer_read_file`, `computer_write_file`, `computer_edit_file` (`src/harness/tools/computer/`, paths through `resolveComputerPath`) plus Playwright MCP's `browser_*` (minus `ComputerMcpExcludedTools`: close, resize, config, `browser_run_code_unsafe`; `withComputerDirs` checks `file:` URLs, `paths` and `filename`). Playwright MCP returns only `browser_snapshot` inline: actions save their snapshot and console log in its own folder (`ComputerBrowserOutputDir`, outside every run's folders), so `withBrowserOutputs` turns those links into the tool that reads them, and moves what Chrome finished downloading (`ComputerBrowserDownloadsDir`; Playwright over CDP never sees downloads) into the run's `downloads/` after each browser call. Each command is its own `bash -c` in its own process group, stdin `/dev/null`, killed with its children at its timeout (at most `AppData.ComputerCommandMaxSeconds`) or when the call is aborted (Stop), so nothing blocks the computer; background work (`nohup ... &`) doesn't hold the call.
|
||||
- **Viewing:** `/computers/<id>/` proxy (`handleComputerProxy`, strips app cookies, adds the token, bridges websockets) passes **only the view paths** (`computerProxyPathAllowed`), never the agent's API or `/mcp` (those are the app's tools, with the folder rules). Modes (`ComputerViewModes`, `computerViewModesFor`): **Browser**, the computer's screen (noVNC, scaled to the frame; its size is the computer's setting, a viewer can't resize it), so Chrome shows whole: tab strip, address bar, menu, extensions, drop-downs and prompts (no window manager, Chrome's window fills the screen), and **Shell** (ttyd as `gem`, for crew managers only, `crew_only`: it reads every folder there). Never draw a stand-in browser UI around a page: the user wants Chrome itself. `computer/novnc/cobble-clipboard.js` (added to noVNC's page) makes Ctrl/Cmd+V paste the user's clipboard and copies the computer's back; browsers allow that only over HTTPS or localhost (otherwise noVNC's side panel). Chrome's `--window-size` is in scaled units, so the agent divides it by the scale. No code editor in the image; a mode can be added to `ComputerViewModes`. Old `[take-over:ID:code|desktop]` refs open the first mode; take-overs ask only for modes every user can open. **Take-over:** `ask_user_to_take_over` writes `[take-over:ID:mode]`; "Hand back" sends a chat message; tasks stop and report rather than wait.
|
||||
|
||||
### Schedules (routines in the UI)
|
||||
|
||||
@@ -152,17 +156,17 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
|
||||
|
||||
A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, public, no session), that queues a hook's brief plus the raw body as a task, per user and bot like a routine (runs act as the owner, who must still reach the bot and not be read-only). Only the token's prefix and SHA-256 are stored (shown once; "New URL" rotates it); an optional HMAC-SHA256 signing secret is stored encrypted (`verifyHookSignature`). Order in the route: rate limit per IP, lookup (same 404 for every miss), rate limit per hook, signature, then `fireBotHook`. Calls are recorded in `bot_hook_events` with idempotency on the sender's delivery header; when a run ends (completed, failed, lost, stopped, cancelled) every call it took in gets its `response` and turns `done`/`failed` (`recordHookCallResponse`, called from the job helpers, not the handler). Calls are searchable by payload/response (`searchHookCallsSql`; Calls view, bot tools `search_hook_calls`/`read_hook_call`) and pruned daily after the app setting `hook_events_keep_days` (default `AppData.BotHookEventsKeepDays`). The caller only ever gets `202 Queued`. A call while the last run is still pending and untried joins its brief (`mergeHookCallSql`) instead of queueing another. The payload is fenced data (`hookPayloadBlock`), and `HookRunNote` tells the bot never to take instructions from it. Failed runs retry like routines and keep why in `last_error`. Users make hooks in the conversation's Hooks modal and manage all of theirs on `/admin/routines`. **A hook has its own thread, never a chat:** its runs work in a hidden session per place (`bot_sessions.hook_id`, status `hook`, `ensureHookSession`), so **every session query that lists or picks a conversation must also exclude them** (`hook_id IS NULL`). Like rooms they change no faces, are never named, push no messages or notifications (`pushBotNotice`, `relayNewBotMessages`); take-over is off for them. A failed run shows only in the thread and in `last_error`. The thread is `bot_hook_events` (`HookDetailModal`, opened from a hook's title; live through `server:hook-call-updated` from the relay). `bot_hooks.session_id` is unused. Deleting a hook deletes its sessions (`deleteHookSessionRows`; one with an open run waits for the daily prune). Moving a hook is refused while a run is open; the computer is kept only if reachable there. **A bot never makes or changes a hook on its own:** `list_hooks`, `search_hook_calls`, `read_hook_call`, `pause_hook` and `delete_hook` act directly (they only read or take away); a new hook, or a new name, brief or filter, or switching one back on, goes through `propose_hook` -> `hook_proposals` -> `[hook-proposal:ID]` card, described from the data and confirmed by that user (`checkHookProposal` runs again on confirm). What calls a hook, its computers and its signing are never proposed. A new hook's URL shows on the card only, never in the outcome the bot is told. Only chat replies propose; a hook call's own run gets no hook tools.
|
||||
|
||||
**Browser notifications:** a hook with `source = browser_notifications` is called by a watcher on `watch_computer_id` instead of an outside service. The watcher (`src/data/notify-watch-script.ts`, Python + GLib, run as `gem` from `~/.cobble/`) owns `org.freedesktop.Notifications` on the sandbox's session bus, so Chrome hands it every notification, push ones included, instead of its silent built-in message center, and it posts each as JSON (`origin`, `title`, `body`) to the URLs in `~/.cobble/notify-hooks`. Chrome only looks for that service when it starts, so `syncComputerNotifyWatch` restarts Chrome once after starting the watcher (its sandbox supervisor brings it back), never while a task works on that computer. The hook's token is kept encrypted (`watch_token`) to rewrite that list after a container is recreated; `sync-notify-watchers` (every 5 minutes) and every change to such a hook resync it. `watch_filter` keeps only matching notifications (others are recorded as `ignored`). Computers reach the app at `COMPUTER_APP_URL` (an app setting; needed for a dev server outside docker), else the app container's name on the docker network. Sites still need notification permission in that computer's browser (a `Browser.grantPermissions` over CDP lasts only for that CDP session). Anything on the computer can read the list and call those hooks, which is one more reason payloads are only data.
|
||||
**Browser notifications:** a hook with `source = browser_notifications` is called by a watcher on `watch_computer_id` instead of an outside service. The watcher (`src/data/notify-watch-script.ts`, Python + GLib, run as `gem` from `~/.cobble/`) owns `org.freedesktop.Notifications` on the computer's session bus (started by the agent; Chrome's pid and bus are in `/run/cobble/browser.pid|json`), so Chrome hands it every notification, push ones included, instead of its silent built-in message center, and it posts each as JSON (`origin`, `title`, `body`) to the URLs in `~/.cobble/notify-hooks`. Chrome only looks for that service when it starts, so `syncComputerNotifyWatch` restarts Chrome once after starting the watcher (the agent brings it back), never while a task works on that computer. The hook's token is kept encrypted (`watch_token`) to rewrite that list after a container is recreated; `sync-notify-watchers` (every 5 minutes) and every change to such a hook resync it. `watch_filter` keeps only matching notifications (others are recorded as `ignored`). Computers reach the app at `COMPUTER_APP_URL` (an app setting; needed for a dev server outside docker), else the app container's name on the docker network. Sites still need notification permission in that computer's browser (on the computer's screen: `chrome://settings/content/notifications`; a `Browser.grantPermissions` over CDP lasts only for that CDP session). Anything on the computer can read the list and call those hooks, which is one more reason payloads are only data.
|
||||
|
||||
### Tasks (the to-do tracker)
|
||||
|
||||
`tasks` (**every task belongs to a bot**, the coordinator included, never shared: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there, enforced by `taskScopeValues`; a worker reaches only its own, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; a bot removed from a workspace or deleted passes its tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`, also run at boot for rows without a bot)), `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`; 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 unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) 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` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `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
|
||||
|
||||
Set in Settings > Environment (super admin), not `.env`. `envs` (private; encrypted `value`; `paradigm` general|workspace|computer|bot|user; one per key and scope, enforced in `saveEnv`). Cached per process. App settings (`EnvDict` in `src/dict/env-dict.ts`) via `grabEnv` (general value, else `process.env`); `ProcessOnlyEnvKeys` can't be saved. Precedence for runs: user > bot > computer > workspace > general (`resolveScopedEnvs`, `grabRunEnvs`; pass the run's `user_id`). Written to `~/.cobble/env` and `env.json` on the computer each task run (only task tools load them; `search_computers` doesn't); bots see keys and descriptions, never values (tasks in their prompt, replies through `composeEnvsNote` from `grabReachableEnvs`, so they never ask for or test a key that's set); every computer tool result goes through `redactSecrets`.
|
||||
Set in Settings > Environment (super admin), not `.env`. `envs` (private; encrypted `value`; `paradigm` general|workspace|computer|bot|user; one per key and scope, enforced in `saveEnv`). Cached per process. App settings (`EnvDict` in `src/dict/env-dict.ts`) via `grabEnv` (general value, else `process.env`); `ProcessOnlyEnvKeys` can't be saved. Precedence for runs: user > bot > computer > workspace > general (`resolveScopedEnvs`, `grabRunEnvs`; pass the run's `user_id`). Written to `~/.cobble/env` and `env.json` in the run account's home on the computer each task run (only task tools load them; `search_computers` doesn't); bots see keys and descriptions, never values (tasks in their prompt, replies through `composeEnvsNote` from `grabReachableEnvs`, so they never ask for or test a key that's set); every computer tool result goes through `redactSecrets`.
|
||||
|
||||
**Secrets never pass through the model.** A `user` env is one user's secret for one bot (`saveUserSecret`, reach-checked), set from the chat, listed on Settings > Secrets (own) and Environment (everyone's, remove only). In: `request_secret` (refused for a key that already reaches the run, unless the user asked to `replace` it) -> `secret_requests` -> `[secret-request:ID]` card (masked input, `answer-request`), then a chat message naming only the key. Out: `capture_secret` (task computer tool: a file via `/v1/file/download` or a command's output, saved straight to a `user` env and added to the run's redaction list) and `show_secret` (an env by key) give `[secret:ID]`; the chip fetches the value only on click (`api/admin/secrets/reveal-secret`, `canRevealEnv`: a personal one only its own user, anything else only a super admin). Never put a value in a message, page prop, log or tool result. `SecretsNote` tells bots never to ask for secrets in chat.
|
||||
**Secrets never pass through the model.** A `user` env is one user's secret for one bot (`saveUserSecret`, reach-checked), set from the chat, listed on Settings > Secrets (own) and Environment (everyone's, remove only). In: `request_secret` (refused for a key that already reaches the run, unless the user asked to `replace` it) -> `secret_requests` -> `[secret-request:ID]` card (masked input, `answer-request`), then a chat message naming only the key. Out: `capture_secret` (task computer tool: a file via the agent's `/api/files/download` or a command's output, saved straight to a `user` env and added to the run's redaction list) and `show_secret` (an env by key) give `[secret:ID]`; the chip fetches the value only on click (`api/admin/secrets/reveal-secret`, `canRevealEnv`: a personal one only its own user, anything else only a super admin). Never put a value in a message, page prop, log or tool result. `SecretsNote` tells bots never to ask for secrets in chat.
|
||||
|
||||
### PWA and notifications
|
||||
|
||||
@@ -179,7 +183,7 @@ Set in Settings > Environment (super admin), not `.env`. `envs` (private; encryp
|
||||
|
||||
- Files live on the data volume, not on computers: `DATA_DIR/bots/<id>` and `DATA_DIR/workspaces/<id>`. Catalog `bot_files`, bytes in private `media` (`bot-file`) written by `recordBotFile`. Reach via `grabStorageScopes`; paths via `resolveBotPath` (no absolute, `..`, NUL, symlink escape); quota checked by `assertStorageRoom`.
|
||||
- Tools in `src/harness/tools/storage/` (every run). `attach` puts a file on the reply. `grabConversationFiles` must list the **whole** folder tree, or nested `[file:ID]` refs render dead. A workspace run saves to the bot's own folder unless it picks the workspace's, so a chip in a workspace conversation looks up both (`api/admin/bots/files?file_id=` with `bot_id` and `workspace_id`).
|
||||
- `import_file` copies from a computer through the sandbox's streaming `GET /v1/file/download`, **never through its shell** (`/v1/shell/exec` caps output at ~30K chars and silently truncated imports). Size read first, `change_policy=abort`, length checked.
|
||||
- `import_file` copies from a computer through the agent's streaming `GET /api/files/download`, **never through its shell** (a shell's output is capped and once silently truncated imports). Size read first, the agent cuts a file that changes mid-send, length checked.
|
||||
- **Only knowledgebases store text.** Bot files and uploads are never indexed and keep no extracted text (`media.text_content` only for knowledgebase documents); bots find files by name or path (`list_files` `search`) and read them with `read_file`, and the Files searches match names only. Text that should be searchable goes in a knowledgebase. `dropStoredFileText` clears what older versions stored, at boot, and vacuums when much of the file is free.
|
||||
- **Foreign keys are off per connection** unless `enableForeignKeys` ran (only `src/server.ts` does). Scripts never fire `ON DELETE CASCADE`, so **any helper that deletes a parent row must delete its children explicitly** (as `deleteBotFile`, `purgeStorage`, `deleteSkill` do). A leftover child fails the next `bun run db:schema` with a foreign key violation.
|
||||
|
||||
@@ -189,7 +193,7 @@ A bot shows a concept as a visual with `create_graphic` (plus `update_graphic`/`
|
||||
|
||||
### Browsers (`browsers`, `browser_access`)
|
||||
|
||||
A user's own running browser, reached over a browser MCP server they run beside it (Settings > Browsers). **It serves only its owner's runs**, since it holds their logins: every helper takes the session's `user_id`, and nobody sees anyone else's, super admins included. A row in `browser_access` makes a browser available in a scope (a bot, a workspace, or both null for all the user's bots) and at most one row per scope is the default; `browser_id` null there means the computer's browser, winning over a wider scope. Adding a browser gives it to no bot. Default order (`pickDefaultBrowser`): workspace > bot > all bots > computer. The computer's browser stays as the fallback. `BrowserDefaultPicker` is the one control, on Settings > Browsers, bot and workspace settings and under the composer. Runs get tools through `openBotBrowsers` (`<slug>__<tool>`, from `tools_cache`, connecting on the first call) and `composeBrowsersNote`, in replies too, so a bot can browse from the chat. `browserRunAllowed`: routines only with `allow_routines`, hook calls and chatroom runs never. **Never use `openMcpServer` or `fillTemplate` for a browser:** its URL and headers are a member's own text, and `{{env.KEY}}` would send install secrets to their server. The URL goes through `assertBrowserUrl` on save, test and each connection (refuses the computers' docker network, link-local, and loopback in production; the docker gateway stays allowed, it's the host), and redirects are refused (`no_redirects`). Headers are encrypted and never reach a page. Playwright MCP needs `--allowed-hosts` naming exactly the URL's host and port; `install.sh` adds `host.docker.internal`. A Flatpak browser takes the same flags through `flatpak run <app id>`, Playwright MCP staying on the host; it needs the host network and home (Flathub Chromium has both; its `/tmp` is private). New browsers start without `BrowserDefaultExcludedTools`. No cron lists tools: a sleeping laptop isn't a fault.
|
||||
A user's own running browser, reached over a browser MCP server they run beside it (Settings > Browsers). **It serves only its owner's runs**, since it holds their logins: every helper takes the session's `user_id`, and nobody sees anyone else's, super admins included. A row in `browser_access` makes a browser available in a scope (a bot, a workspace, or both null for all the user's bots) and at most one row per scope is the default; `browser_id` null there means the computer's browser, winning over a wider scope. Adding a browser gives it to no bot. Default order (`pickDefaultBrowser`): workspace > bot > all bots > computer. The computer's browser stays as the fallback. `BrowserDefaultPicker` is the one control, on Settings > Browsers, bot and workspace settings and under the composer (only once the user has a browser, `has_browsers`). Runs get tools through `openBotBrowsers` (`<slug>__<tool>`, from `tools_cache`, connecting on the first call) and `composeBrowsersNote`, in replies too, so a bot can browse from the chat. `browserRunAllowed`: routines only with `allow_routines`, hook calls and chatroom runs never. **Never use `openMcpServer` or `fillTemplate` for a browser:** its URL and headers are a member's own text, and `{{env.KEY}}` would send install secrets to their server. The URL goes through `assertBrowserUrl` on save, test and each connection (refuses the computers' docker network, link-local, and loopback in production; the docker gateway stays allowed, it's the host), and redirects are refused (`no_redirects`). Headers are encrypted and never reach a page. Playwright MCP needs `--allowed-hosts` naming exactly the URL's host and port; `install.sh` adds `host.docker.internal`. A Flatpak browser takes the same flags through `flatpak run <app id>`, Playwright MCP staying on the host; it needs the host network and home (Flathub Chromium has both; its `/tmp` is private). New browsers start without `BrowserDefaultExcludedTools`. No cron lists tools: a sleeping laptop isn't a fault.
|
||||
|
||||
### Knowledgebases
|
||||
|
||||
@@ -203,29 +207,33 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
|
||||
### Harness (the model layer, `src/harness/`)
|
||||
|
||||
- **Harnesses** (`src/dict/harness-dict.ts`): `text` (always on), `vision`, `transcription`, `speech`, `image`, `image_edit`, `embedding`. One `harness_settings` row each (provider, pinned model or automatic, `fallback`, `enabled`, `options`). Transcription, speech and embedding have no automatic picks: unavailable until a model is picked.
|
||||
- **Images:** `generate_image` takes reference images (`references` as `[file:ID]`, `reference_media_ids` for uploads, checked like a picture source by `loadReferenceImages`). With references the call goes to `image_edit` (no automatic picks; `HarnessFallbacks` hands it to `image` while unpicked or off, and after its pick fails when `fallback` is on), and only models that take image input are tried (`orderImageCandidates`), never one that would drop them. OpenRouter takes references on `/images` (`input_references`), other providers as multipart on `image_edit_path` (`/images/edits`).
|
||||
- **Harnesses** (`src/dict/harness-dict.ts`): `text` (always on), `vision`, `transcription`, `speech`, `image`, `image_edit`, `video`, `video_edit`, `embedding`. One `harness_settings` row each (provider, pinned model or automatic, `fallback`, `enabled`, `options`). Transcription, speech, video and embedding have no automatic picks: unavailable until a model is picked.
|
||||
- **Images:** `generate_image` attaches what it makes to the reply unless `attach: false` (a coordinator once asked a user to judge three versions they were never sent). It takes reference images (`references` as `[file:ID]`, `reference_media_ids` for uploads, checked like a picture source by `loadReferenceImages`). With references the call goes to `image_edit` (no automatic picks; `HarnessFallbacks` hands it to `image` while unpicked or off, and after its pick fails when `fallback` is on), and only models that take image input are tried (`orderImageCandidates`), never one that would drop them. OpenRouter takes references on `/images` (`input_references`), other providers as multipart on `image_edit_path` (`/images/edits`).
|
||||
- **Videos:** `generate_video` (`src/harness/video/`), offered only while `video` or `video_edit` has a model for the bot there (no video model is free). A video is a job at the provider: asked for at `video_path`, checked every `AppData.VideoPollIntervalMs` for at most `VideoMaxWaitMs` (below the tool timeout), downloaded from the provider itself (`<video_path>/<id>/content`, never a URL it hands back, so the key stays home). Still images go as first/last frames or references; videos to change (inline `data:` URLs, `VideoSourceMaxBytes`) go to `video_edit`'s pick, which hands over to the `video` models that take videos like `image_edit` does (`orderVideoCandidates`). OpenRouter takes JSON (`frame_images`, `input_references` with `video_url`); other providers get OpenAI's (Sora) form with one start image and no videos.
|
||||
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
|
||||
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model, caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`), trims old tool output to fit context. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`; a long run is told once, `AppData.HarnessStepsLowWarning` steps before the wrap up, to save its report, since the wrap up has no tools) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up).
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`.
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
|
||||
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access). New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
|
||||
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
|
||||
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
|
||||
|
||||
### Token usage
|
||||
|
||||
- Every model call writes a `token_usages` row via `record-harness-usage.ts` (never throws) in `withCandidates`'s `on_success`, with the provider/model that actually answered and the call's settings (`HarnessCallSettings`).
|
||||
- Attribution through an `AsyncLocalStorage` scope (`src/harness/usage/harness-usage-scope.ts`) entered once in `run-bot-job.ts`; merged, not replaced; `null` clears a field. `withUsageScope` / `runWithFallbackScope` for calls outside a run. No owner, no row.
|
||||
- `complete-bot-job.ts` back-fills `message_id` for the job's calls. Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`).
|
||||
- Every failed model call also writes a `harness_call_failures` row (`recordHarnessFailure`, beside the log in `withCandidates`: model, pick, HTTP status, the provider's reason, rest), same attribution, no foreign keys, pruned with the logs' retention by `prune-logs`.
|
||||
- `attachJobCallsToMessage` back-fills `message_id` for the job's calls and failures, from `complete-bot-job.ts` and `notify-bot-job-failed.ts` (so a failure notice shows why). Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`, failed calls listed with their reasons).
|
||||
- `/admin/usage` (crew managers). **Days are local, not UTC:** group with `date(created_at / 1000, 'unixepoch', 'localtime')`; never name a local day with `toISOString().slice(0, 10)` (`bucket-usage-days.test.ts` pins this). Bars use static `h-*` classes from `(data)/usage-bar-heights.ts`.
|
||||
|
||||
### Installer and release
|
||||
|
||||
- `install.sh` (`curl -fsSL https://url.moduletrace.com/cobble | sudo bash`) is the only install and update path; idempotent; `--uninstall [--purge]`. Never regenerates secrets; backs up the DB before replacing the container. Everything persistent lives in `$COBBLE_HOME/data` (default `/opt/cobble`).
|
||||
- **Mount specs:** `source:destination[:options]`, options (`z`, `ro`) comma-separated in the **third** field. Never append an option to the destination (`$DATA_DIR:/data,z` mounts a directory literally named `/data,z` and loses all data on update). `install.test.ts` runs the marked `selinux-detection` and `mount-specs` blocks. `/data` must stay a bind mount (`resolveHostPath` maps it to host paths for computers).
|
||||
- **App networks:** extra docker networks for the app's own container (never computers) are the app setting `app_extra_networks` (Settings > General, super admin, picked from the networks docker lists, `listJoinableNetworks`), joined by the app itself over the docker socket (`syncAppNetworks`) at boot, on save and every 5 minutes, so they outlast `install.sh` recreating the container; the installer's `--extra-network` still works beside it.
|
||||
- Plain HTTP only; TLS is the proxy's job. Container: `--network cobble`, `.env` read-only at `/app/.env`, docker socket, `MAIN_SERVER=1`, `--init`, `--cpus 1 --memory 2048m` by default.
|
||||
- Publishing: `scripts/publish-github.sh` / `publish-gitea.sh` sharing `scripts/lib/publish-*.sh` (tested by `scripts/publish-tools.test.ts`). A GitHub release triggers `.github/workflows/release.yml` (amd64 + arm64 to `ghcr.io/moduletrace/cobble`); `mirror-gitea.sh` copies to `git.tben.me/moduletrace/cobble` (CI can't reach the VPN). **Bump `package.json`'s `version` with a release.** CI (`ci.yml`) runs typecheck and tests. Dockerfile pins Bun 1.4.3.
|
||||
|
||||
@@ -236,7 +244,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Rail pages** (`src/dict/rail-pages-dict.ts`): Routines, Files, Usage (crew managers), Activity (`/admin/logs`, super admin), Help (`(data)/help-topics.ts`). Visibility via `canSeeRailItem` for both the popover and the aside.
|
||||
- **Settings** (`src/dict/settings-pages-dict.ts`; add a sub page = folder + dict entry): `general` (theme per device, plus super-admin app settings: prompt append, run limits, skill limits; crew-manager storage quota; running version), `setup` (super admin; shares the Models page's server props and `useModelsOverview`), `profile`, `notifications`, `change-password`, `secrets`, `browsers`, `models`, `environment`, `backups` and `database` (super admin), `bots`, `workspaces`, `computers`, `mcps`, `tools`, `skills`, `knowledgebases` (crew managers), `users` (`canListUsers`).
|
||||
- Settings pages use `SettingsShell` (breadcrumbs via `admin-breadcrumbs.tsx`), `SettingsGroup` blocks (no cards) and the sticky `SettingsSaveBar`. Saves don't reload. Keep save notices in component state (`useFormInit` clears `status` on change). Lists share `SettingsList`/`SettingsListRow`/`SettingsRowAction`. Row actions are icon-only (`RowIconButton`).
|
||||
- **Backups:** DB snapshots (synchronous) and whole-data archives of `DATA_DIR` into `BACKUP_ARCHIVE_DIR`. Archives and restores outlast a request, so the route only starts the run (`startDataBackupRun`, which holds `with-backup-run-lock.ts`) and the page polls `data-status`. A restore takes a safety archive first, then restarts the process.
|
||||
- **Backups:** DB snapshots (synchronous) and whole-data archives of `DATA_DIR` into `BACKUP_ARCHIVE_DIR`. Archives and restores outlast a request, so the route only starts the run (`startDataBackupRun`, which holds `with-backup-run-lock.ts`) and the page polls `data-status`. A restore takes a safety archive first, then restarts the process. **A database snapshot restore restarts too** (also a background run, `db_restore`): `bun-sqlite import` swaps in a new file from another process, and this process's handle would stay on the old one, so nothing may be written to the database between a restore and the restart (log entries go through `queueBootLog`, written by `flushBootLogs` at boot).
|
||||
- **Database browser:** strictly read-only; values cut in SQL; state in the address via `databaseHref`.
|
||||
- Add flow (`(partials)/add-flow.tsx`) from the rail's Add icon: bot, workspace, computer (super admin). Page heroes use `AdminHero`.
|
||||
|
||||
|
||||
@@ -29,9 +29,8 @@ A crew of small AI worker bots you host yourself (alpha).
|
||||
Cobble is a self-hosted crew of small AI worker bots. You get a coordinator
|
||||
and a set of workers, each with its own job, models, memory and workspace.
|
||||
They talk to you in one chat, share workspaces, run routines on a schedule,
|
||||
and drive their own computers: Docker sandboxes with a browser, a terminal,
|
||||
a code editor and a desktop that a bot can use and hand back to you when it
|
||||
needs help.
|
||||
and drive their own computers: lean Docker sandboxes with a real Chrome and
|
||||
a shell, which a bot can use and hand back to you when it needs help.
|
||||
|
||||
It is an install, not a SaaS. One SQLite database, one Docker container, and
|
||||
your data on your own machine.
|
||||
@@ -61,7 +60,7 @@ your data on your own machine.
|
||||
| Workspaces | A shared home for a group of bots: shared context, per-workspace instructions and memory, a default computer, and a dashboard |
|
||||
| Memory | Each bot keeps core memory, memory about you, and workspace memory, and rewrites it as it works |
|
||||
| Routines | Cron schedules per bot, written in chat, that queue a task on its own |
|
||||
| Computers | Docker sandboxes with browser, terminal, code editor and desktop, opened from the chat and handed back to you mid-task |
|
||||
| Computers | Docker sandboxes with a real headful Chrome and a shell, shown live in the chat and handed back to you mid-task |
|
||||
| Files | Bots keep files on your data volume, search them by meaning, and attach the ones they make to a reply |
|
||||
| Models | OpenRouter, OpenAI, Anthropic, Gemini, DeepSeek, Groq, Mistral, xAI, Ollama or any OpenAI-compatible server, per bot and per harness |
|
||||
| Voice | Dictate into the composer, play any bot reply, with speech-to-text and text-to-speech models of your choice |
|
||||
@@ -91,7 +90,7 @@ The app serves plain HTTP on the port it prints, usually
|
||||
`http://<your-ip>:7227`. Put a reverse proxy or tunnel in front of it for
|
||||
HTTPS (see [HTTPS](#https)), then open the proxy's address and create the
|
||||
super admin account. The first signup also creates the coordinator and the
|
||||
main computer, which pulls the sandbox image in the background. Give it a
|
||||
main computer, which pulls the computer image in the background. Give it a
|
||||
few minutes.
|
||||
|
||||
Then open **Settings > Models**, add an OpenRouter key (or another provider)
|
||||
@@ -188,7 +187,7 @@ You ── chat ── Coordinator ── delegates ── Workers
|
||||
│ cron schedules │
|
||||
└── Computers ─────────────┘
|
||||
docker sandboxes:
|
||||
browser, terminal, code, desktop
|
||||
real Chrome, shell
|
||||
```
|
||||
|
||||
- **Coordinator** is yours alone. It plans, delegates to workers, and keeps
|
||||
@@ -198,9 +197,10 @@ You ── chat ── Coordinator ── delegates ── Workers
|
||||
- **Workspaces** group bots around a subject. Models, instructions, memory
|
||||
and the default computer resolve per workspace before per bot.
|
||||
- **Routines** are cron schedules that queue a task without you asking.
|
||||
- **Computers** are per-install Docker containers. Bots use them through the
|
||||
sandbox's tools, and you can open the same machine in the browser and take
|
||||
over.
|
||||
- **Computers** are per-install Docker containers of Cobble's own image
|
||||
(`computer/`: Debian 13, Google Chrome on a virtual screen, Playwright MCP
|
||||
and a shell). Bots drive the browser and the shell, and you can watch the
|
||||
same browser live in the chat and take over.
|
||||
|
||||
Each conversation is split into sessions, so a long-running bot does not grow
|
||||
one endless thread: the bot names a session, summarizes it, and carries the
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
"@floating-ui/dom": "1.8.0",
|
||||
"@modelcontextprotocol/sdk": "^1.32.1",
|
||||
"@moduletrace/bun-sqlite": "^1.3.0",
|
||||
"@moduletrace/bunext": "^1.3.3",
|
||||
"@moduletrace/twui": "^0.1.7",
|
||||
"@moduletrace/bunext": "^1.3.5",
|
||||
"@moduletrace/twui": "^0.1.10",
|
||||
"@tiptap/extension-bubble-menu": "3.32.0",
|
||||
"@tiptap/extension-mention": "3.32.0",
|
||||
"@tiptap/extension-placeholder": "3.32.0",
|
||||
@@ -277,9 +277,9 @@
|
||||
|
||||
"@moduletrace/bun-sqlite": ["@moduletrace/[email protected]", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Fbun-sqlite/-/1.3.0/bun-sqlite-1.3.0.tgz", { "dependencies": { "@inquirer/prompts": "^8.3.0", "chalk": "^5.6.2", "commander": "^14.0.3", "inquirer": "^13.3.2", "lodash": "^4.17.23", "sqlite-vec": "^0.1.7-alpha.2" }, "peerDependencies": { "typescript": "^5" }, "bin": { "bun-sqlite": "dist/commands/index.js" } }, "sha512-5xZg36vvT7uIpJSzeXW+debQ19Q7m99aUt2OvTEpWZvlnp0ePL9J6/1ibq2IPBmLpRZdif5Tq76ipiwwSN63jg=="],
|
||||
|
||||
"@moduletrace/bunext": ["@moduletrace/[email protected].3", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Fbunext/-/1.3.3/bunext-1.3.3.tgz", { "dependencies": { "@tailwindcss/postcss": "^4.3.3", "@types/bun": "1.3.14", "@types/node": "^24.10.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "bun-plugin-tailwind": "^0.1.2", "chalk": "^5.6.2", "chokidar": "^5.0.0", "commander": "^14.0.2", "esbuild": "^0.28.2", "lightningcss-wasm": "^1.32.0", "lodash": "^4.18.1", "ora": "^9.0.0", "postcss": "^8.5.30", "react": "^19.3.0", "react-dom": "^19.3.0", "tailwindcss": "^4.3.3", "typescript": "^5.0.0", "uuid": "^14.0.2" }, "bin": { "bunext": "dist/commands/index.js" } }, "sha512-bbUtQaigsDPUQf6vtDOSCo8GYR7Gnw2ny1Fi3JtUnKsYsYQEcEadzmqntAgf7rLcKc12dadDUgFLxru+jiA92g=="],
|
||||
"@moduletrace/bunext": ["@moduletrace/[email protected].5", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Fbunext/-/1.3.5/bunext-1.3.5.tgz", { "dependencies": { "@tailwindcss/postcss": "^4.3.3", "@types/bun": "1.3.14", "@types/node": "^24.10.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "bun-plugin-tailwind": "^0.1.2", "chalk": "^5.6.2", "chokidar": "^5.0.0", "commander": "^14.0.2", "esbuild": "^0.28.2", "lightningcss-wasm": "^1.32.0", "lodash": "^4.18.1", "ora": "^9.0.0", "postcss": "^8.5.30", "react": "^19.3.0", "react-dom": "^19.3.0", "tailwindcss": "^4.3.3", "typescript": "^5.0.0", "uuid": "^14.0.2" }, "bin": { "bunext": "dist/commands/index.js" } }, "sha512-Es59Dvq3/eF726+SOHPiKtlJ87UFmyJZI4gpeciW/fA/3ZwOWws2Mm3oD6eZnOj9BP/zlBKOWA9DPTl35IP3lg=="],
|
||||
|
||||
"@moduletrace/twui": ["@moduletrace/[email protected].7", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.7/twui-0.1.7.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-/Y9QyhtQsoEAJO+ahlGYQaYMx3gUWS+DlSkaBVjAIY5V9OQ6i7qhhqMNcmnfOi9m3eyAze1uW00jox+RDUqLpA=="],
|
||||
"@moduletrace/twui": ["@moduletrace/[email protected].10", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.10/twui-0.1.10.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-eShpG6jK7qr2+oG7Pq4PvHnvAOUPkbxMCf9BVfiuJqUdtuaQSo2jqcggGAonGDu4p8Nn/KWTd2KrypE/+W4wTg=="],
|
||||
|
||||
"@next/mdx": ["@next/[email protected]", "", { "dependencies": { "source-map": "^0.7.0" }, "peerDependencies": { "@mdx-js/loader": ">=0.15.0", "@mdx-js/react": ">=0.15.0" }, "optionalPeers": ["@mdx-js/loader", "@mdx-js/react"] }, "sha512-Vpfuf928ACvx4AOdDXWx/cj13Ak6xlvMn3QCkjvfQMmLnQWCesQTeY01CPDbIyZvjY+NOwP7bvbvJ2ghkj/3GA=="],
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
**/*.test.ts
|
||||
**/node_modules
|
||||
@@ -0,0 +1,150 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
#
|
||||
# A Cobble computer: a real, headful browser on a virtual screen, plus a
|
||||
# shell, in one lean Debian 13 container. The app reaches everything on one
|
||||
# port (8080) through the agent in agent/:
|
||||
#
|
||||
# /api/... shell and files
|
||||
# /mcp Playwright MCP, attached to the browser over CDP
|
||||
# /desktop/ the screen itself (noVNC over the agent's own websocket
|
||||
# bridge to Xvnc): the whole Chrome window, tabs and menus
|
||||
# /terminal/ a shell in the browser (ttyd)
|
||||
#
|
||||
# Google Chrome on amd64 (the real "Google Chrome" brand, Widevine, full
|
||||
# codecs); Google ships no Linux arm64 build, so arm64 gets Debian's
|
||||
# Chromium. Chrome never auto-updates in here: rebuild the image instead.
|
||||
#
|
||||
# DEBIAN_MIRROR (a build arg, e.g. http://cdn-aws.deb.debian.org/debian)
|
||||
# fetches Debian's packages from another mirror when deb.debian.org is slow
|
||||
# from where the image is built; the image is the same either way.
|
||||
|
||||
# --- The agent, bundled for Node -----------------------------------------------
|
||||
FROM oven/bun:1.4.3-debian AS agent
|
||||
WORKDIR /build
|
||||
COPY agent ./agent
|
||||
RUN bun build agent/main.ts --target=node --format=esm --outfile=dist/agent.mjs
|
||||
|
||||
# --- noVNC, the screen's viewer: the project's release, checked against its
|
||||
# hash (Debian's package pulls websockify and numpy, which the agent's own
|
||||
# bridge makes unneeded). It connects by itself, reconnects, and scales the
|
||||
# screen to its frame; its socket is fixed to the agent's. novnc/ adds
|
||||
# clipboard sync (Ctrl+V pastes what the user copied).
|
||||
FROM debian:trixie-slim AS novnc
|
||||
ARG NOVNC_VERSION=1.6.0
|
||||
ARG NOVNC_SHA256=5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa
|
||||
ARG DEBIAN_MIRROR
|
||||
RUN if [ -n "$DEBIAN_MIRROR" ]; then sed -i "s|http://deb.debian.org/debian|$DEBIAN_MIRROR|g" /etc/apt/sources.list.d/debian.sources; fi \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates curl \
|
||||
&& curl -fsSL -o /tmp/novnc.tgz "https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz" \
|
||||
&& echo "${NOVNC_SHA256} /tmp/novnc.tgz" | sha256sum -c - \
|
||||
&& mkdir -p /opt/novnc \
|
||||
&& tar xzf /tmp/novnc.tgz -C /opt/novnc --strip-components=1 \
|
||||
&& cd /opt/novnc \
|
||||
&& rm -rf tests docs snap utils po .github karma.conf.cjs eslint.config.mjs \
|
||||
&& echo '{"autoconnect":true,"reconnect":true,"reconnect_delay":1000,"resize":"scale"}' > defaults.json \
|
||||
&& echo '{"host":"","port":0,"path":"websockify"}' > mandatory.json
|
||||
COPY novnc/cobble-clipboard.js /opt/novnc/cobble-clipboard.js
|
||||
RUN grep -q '</head>' /opt/novnc/vnc.html \
|
||||
&& sed -i 's|</head>| <script type="module" src="./cobble-clipboard.js"></script>\n</head>|' /opt/novnc/vnc.html \
|
||||
&& grep -q cobble-clipboard /opt/novnc/vnc.html
|
||||
|
||||
# --- Playwright MCP, installed once (no npm in the final image) ------------------
|
||||
FROM debian:trixie-slim AS mcp
|
||||
ARG PLAYWRIGHT_MCP_VERSION=0.0.84
|
||||
ARG DEBIAN_MIRROR
|
||||
RUN if [ -n "$DEBIAN_MIRROR" ]; then sed -i "s|http://deb.debian.org/debian|$DEBIAN_MIRROR|g" /etc/apt/sources.list.d/debian.sources; fi \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates nodejs npm \
|
||||
&& npm install --prefix /opt/playwright-mcp --omit=dev --no-audit --no-fund "@playwright/mcp@${PLAYWRIGHT_MCP_VERSION}" \
|
||||
&& /opt/playwright-mcp/node_modules/.bin/playwright-mcp --version
|
||||
|
||||
# --- The computer ----------------------------------------------------------------
|
||||
FROM debian:trixie-slim
|
||||
ARG TARGETARCH
|
||||
|
||||
LABEL org.opencontainers.image.title="Cobble computer" \
|
||||
org.opencontainers.image.description="A Cobble bot's computer: a real headful browser and a shell." \
|
||||
org.opencontainers.image.source="https://github.com/Moduletrace/cobble" \
|
||||
org.opencontainers.image.licenses="MIT"
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
LANG=C.UTF-8 \
|
||||
TZ=UTC \
|
||||
PIP_BREAK_SYSTEM_PACKAGES=1
|
||||
|
||||
ARG DEBIAN_MIRROR
|
||||
RUN if [ -n "$DEBIAN_MIRROR" ]; then sed -i "s|http://deb.debian.org/debian|$DEBIAN_MIRROR|g" /etc/apt/sources.list.d/debian.sources; fi \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
# What bots reach for on a shell; anything else the coordinator
|
||||
# installs (worker bots have no sudo).
|
||||
bash ca-certificates curl wget git jq less nano procps psmisc sudo \
|
||||
unzip zip xz-utils file openssh-client tzdata tini \
|
||||
# Worker bots' own accounts: their folders shared with gem through
|
||||
# ACLs, and kept off the services on loopback by nftables.
|
||||
acl nftables \
|
||||
python3 python3-pip python3-venv nodejs \
|
||||
# The notification watcher (Python + GLib on the session bus).
|
||||
python3-gi gir1.2-glib-2.0 dbus-daemon dbus-session-bus-common \
|
||||
# The screen (Xvnc: an X server that is also a VNC server, on
|
||||
# loopback), and Mesa so WebGL runs without a GPU.
|
||||
tigervnc-standalone-server libgl1-mesa-dri libegl1 libgles2 \
|
||||
# The fonts a normal desktop install ships.
|
||||
fonts-dejavu fonts-liberation fonts-liberation2 fonts-noto-core \
|
||||
fonts-noto-cjk fonts-noto-color-emoji fonts-noto-mono fonts-noto-ui-core \
|
||||
fonts-cantarell fonts-urw-base35 \
|
||||
libu2f-udev xdg-utils \
|
||||
&& if [ "$TARGETARCH" = "amd64" ]; then \
|
||||
curl -fsSL https://dl.google.com/linux/linux_signing_key.pub -o /usr/share/keyrings/google-chrome.asc \
|
||||
&& echo "deb [arch=amd64 signed-by=/usr/share/keyrings/google-chrome.asc] https://dl.google.com/linux/chrome/deb/ stable main" \
|
||||
> /etc/apt/sources.list.d/google-chrome.list \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends google-chrome-stable \
|
||||
&& google-chrome-stable --version; \
|
||||
else \
|
||||
apt-get install -y --no-install-recommends chromium \
|
||||
&& chromium --version; \
|
||||
fi \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/* /var/tmp/* /tmp/* /usr/share/doc/* /usr/share/man/*
|
||||
|
||||
# The Shell view: ttyd, a terminal in the browser (Debian 13 doesn't package
|
||||
# it), the project's static build, checked against its published hashes.
|
||||
ARG TTYD_VERSION=1.7.7
|
||||
RUN set -eu; \
|
||||
case "$TARGETARCH" in \
|
||||
amd64) arch=x86_64; sum=8a217c968aba172e0dbf3f34447218dc015bc4d5e59bf51db2f2cd12b7be4f55 ;; \
|
||||
arm64) arch=aarch64; sum=b38acadd89d1d396a0f5649aa52c539edbad07f4bc7348b27b4f4b7219dd4165 ;; \
|
||||
*) echo "No ttyd build for $TARGETARCH" >&2; exit 1 ;; \
|
||||
esac; \
|
||||
curl -fsSL -o /usr/local/bin/ttyd "https://github.com/tsl0922/ttyd/releases/download/${TTYD_VERSION}/ttyd.${arch}"; \
|
||||
echo "${sum} /usr/local/bin/ttyd" | sha256sum -c -; \
|
||||
chmod 755 /usr/local/bin/ttyd; \
|
||||
ttyd --version
|
||||
|
||||
# The computer's user, with sudo: the services run as it, and so does the
|
||||
# coordinator, which installs what worker bots ask for (it's lost when the
|
||||
# container is recreated). Worker bots get accounts of their own, without
|
||||
# sudo, made by the agent. Chrome and Chromium read managed policies (the
|
||||
# app's default extensions) from the same folder. nft is only looked for,
|
||||
# never run: it opens a netlink socket even for --version, which an
|
||||
# emulated (arm64 on amd64) build doesn't have.
|
||||
RUN setpriv --version && setfacl --version && command -v nft \
|
||||
&& useradd --create-home --uid 1000 --shell /bin/bash gem \
|
||||
&& echo 'gem ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/gem \
|
||||
&& chmod 440 /etc/sudoers.d/gem \
|
||||
&& mkdir -p /home/gem/workspace /home/gem/.cobble-browser /etc/opt/chrome/policies/managed /etc/chromium \
|
||||
&& rm -rf /etc/chromium/policies \
|
||||
&& ln -s /etc/opt/chrome/policies /etc/chromium/policies \
|
||||
&& chown -R gem:gem /home/gem
|
||||
|
||||
COPY --from=mcp /opt/playwright-mcp /opt/playwright-mcp
|
||||
COPY --from=agent /build/dist /opt/cobble-agent
|
||||
COPY --from=novnc /opt/novnc /opt/novnc
|
||||
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=10s --timeout=5s --start-period=60s --retries=3 \
|
||||
CMD curl -fsS -o /dev/null http://127.0.0.1:8080/health || exit 1
|
||||
|
||||
ENTRYPOINT ["/usr/bin/tini", "--", "node", "/opt/cobble-agent/agent.mjs"]
|
||||
@@ -0,0 +1,151 @@
|
||||
# Cobble computer
|
||||
|
||||
The image every Cobble computer runs: a real, headful browser on a virtual
|
||||
screen and a shell, in one lean Debian 13 (trixie) container. It replaces the
|
||||
AIO sandbox, whose browser sites like Google turned away.
|
||||
|
||||
```
|
||||
app ──http:8080──► agent ─┬─ /api/exec, /api/files/* shell and files, as gem or a worker bot
|
||||
├─ /terminal/ ─► ttyd (a shell in the browser)
|
||||
├─ /mcp ─► Playwright MCP ──CDP 127.0.0.1:9222──► Google Chrome
|
||||
└─ /desktop/ noVNC ──websocket──► VNC 127.0.0.1:5900 (headful)
|
||||
│ │
|
||||
Xvnc :99 (1920x1080) ◄───────┘
|
||||
```
|
||||
|
||||
- **Browser:** Google Chrome on amd64 (the real "Google Chrome" Client Hints
|
||||
brand, Widevine, full codecs); Debian's Chromium on arm64, where Google
|
||||
ships no Linux build. It runs headful on Xvnc with a normal profile and no
|
||||
automation flags: the app attaches over CDP, it never launches it, so
|
||||
`navigator.webdriver` is false. WebGL runs on Mesa's software renderer;
|
||||
pages are composited in software (`--disable-gpu-compositing`, half the
|
||||
CPU of compositing through Mesa).
|
||||
- **Parking:** with no GPU and no window manager, the tab in front is always
|
||||
on show, so its animations are drawn at full rate whether or not anyone
|
||||
watches (one animated site can take a core or two). After
|
||||
`COBBLE_BROWSER_PARK_AFTER_SECONDS` without a `/mcp` call or a screen view,
|
||||
the agent puts a blank tab in front of every site on show (over DevTools,
|
||||
as a person switching tabs would: the site keeps its connections, Chrome
|
||||
just stops drawing it). The next `/mcp` call or screen view brings them
|
||||
back before it goes through. Tabs are never discarded (managed policy), so
|
||||
a parked one never reloads.
|
||||
- **Agent** (`agent/`): the container's main process (under tini). It keeps
|
||||
Xvnc, the session bus, Chrome, Playwright MCP and ttyd running (each restarted
|
||||
when it exits), stops them in order on `docker stop` so Chrome saves its
|
||||
profile, and serves the app on port 8080. Node, no dependencies; bundled by
|
||||
Bun when the image is built.
|
||||
- **Screen** (`/desktop/`): the virtual screen itself, so Chrome shows as
|
||||
it is: its tab strip, address bar, menu, extensions, drop-downs and
|
||||
prompts. The screen is Xvnc (an X server that is also a VNC server, on
|
||||
loopback, no password); noVNC (the project's release, settings in its
|
||||
`defaults.json`/`mandatory.json`) draws it scaled to the window, and the
|
||||
agent bridges noVNC's websocket to Xvnc itself (no websockify). The
|
||||
screen's size is a setting; a viewer can't resize it. `novnc/cobble-clipboard.js`
|
||||
makes Ctrl/Cmd+V on the screen paste the viewer's clipboard (browsers allow
|
||||
that over HTTPS or localhost), and copies the computer's back.
|
||||
- **Shell** (`/terminal/`): ttyd, a terminal in the browser, as `gem`.
|
||||
|
||||
No window manager, desktop or code editor: the image stays small and starts
|
||||
fast.
|
||||
|
||||
## Accounts
|
||||
|
||||
The services run as `gem` (passwordless sudo), and so do the coordinator's
|
||||
commands. Every worker bot works as its own account, `cb-<bot id>` (uid and
|
||||
gid `100000 + id`, no sudo), made by the agent the first time the app acts
|
||||
for it (`run_as`). Its folder `bots/<id>` is its own (`2770`), and a
|
||||
workspace's folder `workspaces/<id>` (root's) belongs to the group `cw-<id>`
|
||||
its bots join. A worker works through its home: `/home/cb-<id>/workspace`
|
||||
is a link to `bots/<id>` (the only part of its home that's kept, since the
|
||||
home itself lives in the container), its users' folders are `users/<user>`
|
||||
in it, and in a workspace `workspaces/<workspace id>` in it is a link to
|
||||
that workspace's folder. The agent checks both links on every request for
|
||||
the worker and puts back one that's gone (whatever sits in its place is
|
||||
moved aside). `gem`, and so Chrome, can't open either: the app passes a
|
||||
worker's uploads, downloads and files saved by name through a folder of the
|
||||
call's own, copied by the worker's account (`sudo -u`), and a worker can't
|
||||
open `file:` URLs. Its env files live in its own home.
|
||||
|
||||
A worker can't reach the computer's own services: an nftables rule
|
||||
(`guardServicePorts`, which needs `--cap-add NET_ADMIN`) resets its
|
||||
connections to the agent, Chrome's DevTools, Playwright MCP, VNC and ttyd,
|
||||
and the X display asks for gem's cookie (`XAUTHORITY`). If the rule can't be
|
||||
set, the agent refuses everything asked for a worker. Workers install
|
||||
Python and Node packages into their own folder (`pip install --user`,
|
||||
`npm install -g` into `~/.local`); system packages are the coordinator's
|
||||
(`request_install` in the app), lost when the container is recreated.
|
||||
|
||||
## API
|
||||
|
||||
Every path but `/health` needs `Authorization: Bearer $COBBLE_COMPUTER_TOKEN`
|
||||
when that's set (the app sets it per computer).
|
||||
|
||||
| Path | |
|
||||
| --- | --- |
|
||||
| `GET /health` | 200 once Chrome's DevTools and Playwright MCP answer |
|
||||
| `GET /api/info` | home, workspace, user, browser binary and version, whether workers are guarded |
|
||||
| `POST /api/exec` | `{ command, timeout_seconds?, cwd?, run_as? }`: one `bash -c` as `gem` (or, with `run_as: { bot_id, workspace_id? }`, as that worker's account), own process group, no stdin, killed with its children at the timeout or when the request goes away. `{ output, exit_code, timed_out, truncated }` |
|
||||
| `GET /api/files/stat?path=` | `{ exists, type, size, mtime_ms }`; with `run_as_bot_id` (and `run_as_workspace_id`) only inside that worker's folders and home |
|
||||
| `GET /api/files/download?path=` | the bytes; the connection is cut if the file changes mid-send; `run_as_*` as for stat |
|
||||
| `POST /api/files/write` | `{ path, content, encoding?: "utf8" \| "base64", mode?, run_as? }`, owned by `gem`, or written by the worker's own account |
|
||||
| `/mcp` | Playwright MCP (`--shared-browser-context --codegen none --no-webmcp --file-paths absolute`, its files in `~/.cobble/playwright`, capped at 256 MB); Chrome saves downloads in `~/Downloads` |
|
||||
| `/desktop/` | the screen (noVNC); `/desktop/websockify` is its websocket to Xvnc |
|
||||
| `/terminal/` | a shell in the browser (ttyd, as `gem`, in the workspace) |
|
||||
|
||||
## Settings
|
||||
|
||||
| Env | Default | |
|
||||
| --- | --- | --- |
|
||||
| `COBBLE_COMPUTER_TOKEN` | none (open) | the token the API asks for |
|
||||
| `COBBLE_BROWSER_PROFILE_DIR` | `/home/gem/.cobble-browser` | Chrome's profile (mount it to keep logins) |
|
||||
| `COBBLE_SCREEN` | `1920x1080` | the virtual screen, and the window that fills it |
|
||||
| `COBBLE_BROWSER_SCALE` | `1.25` | how large Chrome draws pages (its device scale factor, 1 to 3): larger text in screenshots |
|
||||
| `COBBLE_BROWSER_LANG`, `COBBLE_BROWSER_ACCEPT_LANG` | `en-US`, `en-US,en` | keep them, and `TZ`, matched to where the traffic comes from |
|
||||
| `COBBLE_BROWSER_SANDBOX` | `true` | Chrome's sandbox; it's turned off by itself when the host blocks user namespaces |
|
||||
| `COBBLE_BROWSER_PARK_AFTER_SECONDS` | `180` | idle this long, the sites on show are parked behind a blank tab; `0` never parks |
|
||||
| `COBBLE_BROWSER_ARGS` | | more Chrome flags, space separated (ones that would open DevTools or move the profile are dropped) |
|
||||
| `COBBLE_MCP_ARGS` | | more Playwright MCP flags, e.g. `--caps vision` (where it listens and which browser it drives can't be changed) |
|
||||
| `TZ` | `UTC` | the browser's timezone |
|
||||
|
||||
Chrome's sandbox needs user namespaces, so run the container with
|
||||
`--security-opt seccomp=unconfined` (the app does), a big `/dev/shm`
|
||||
(`--shm-size 2g`), and `--cap-add NET_ADMIN` for worker accounts.
|
||||
|
||||
## Building
|
||||
|
||||
The app runs the tag in `AppData.ComputerImage`
|
||||
(`ghcr.io/moduletrace/cobble-computer:<version>`). Any change here bumps that
|
||||
tag; the release workflow builds a tag once (a dispatch with
|
||||
`rebuild_computer` rebuilds it, for a newer Chrome).
|
||||
|
||||
```sh
|
||||
bun run build:computer # builds AppData.ComputerImage for this machine
|
||||
docker run -d --name cobble-computer-dev --shm-size 2g \
|
||||
--security-opt seccomp=unconfined --cap-add NET_ADMIN -p 8170:8080 \
|
||||
ghcr.io/moduletrace/cobble-computer:1.3.0
|
||||
```
|
||||
|
||||
A computer run by hand like that has no token, so anyone who reaches its port
|
||||
drives its browser: bind it to localhost. Point a dev server at it with the
|
||||
`MAIN_COMPUTER_URL` app setting (`http://localhost:8170`).
|
||||
|
||||
To bump Playwright MCP or ttyd, change `PLAYWRIGHT_MCP_VERSION` or `TTYD_VERSION` (and its two hashes) in the Dockerfile.
|
||||
|
||||
## Known limits
|
||||
|
||||
- **IP reputation matters more than the browser.** A data-center IP is
|
||||
flagged by Cloudflare and others however real the browser is.
|
||||
- **No GPU:** WebGL reports Mesa llvmpipe, plausible for a Linux box.
|
||||
- **Native popups aren't in the live view:** a drop-down opens as the view's
|
||||
own list; the browser's own menus and permission bubbles don't show (use
|
||||
`chrome://settings/content` in the address bar for site permissions).
|
||||
- **Automation can still be noticed** by its behaviour (instant clicks, no
|
||||
mouse movement). When a challenge shows, take over and solve it; the bot
|
||||
carries on in the same session.
|
||||
|
||||
When deb.debian.org is slow from where you build, fetch Debian's packages from
|
||||
another mirror (the image is the same):
|
||||
|
||||
```sh
|
||||
bun run build:computer --build-arg DEBIAN_MIRROR=http://cdn-aws.deb.debian.org/debian
|
||||
```
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* What the health check and `/api/info` report, kept current by the
|
||||
* services as they start and stop.
|
||||
*/
|
||||
export const AgentState = {
|
||||
browser_binary: "",
|
||||
browser_version: "",
|
||||
browser_sandbox: true,
|
||||
/**
|
||||
* Whether worker accounts are kept off the services on loopback
|
||||
* (`guardServicePorts`); without it their commands are refused.
|
||||
*/
|
||||
workers_guarded: false,
|
||||
guard_error: "",
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Flags the computer's own settings may not pass to Chrome
|
||||
* (`COBBLE_BROWSER_ARGS`): they'd open its DevTools to the network (around
|
||||
* the token), move its profile, or break the agent's hold on it. The app
|
||||
* refuses the same ones (`ComputerBlockedBrowserArgs`); keep them alike.
|
||||
*/
|
||||
export const BrowserBlockedArgs = [
|
||||
"--remote-debugging-port",
|
||||
"--remote-debugging-address",
|
||||
"--remote-debugging-pipe",
|
||||
"--remote-allow-origins",
|
||||
"--user-data-dir",
|
||||
"--headless",
|
||||
];
|
||||
|
||||
/**
|
||||
* Flags the computer's own settings may not pass to Playwright MCP
|
||||
* (`COBBLE_MCP_ARGS`): where it listens and what it drives are the
|
||||
* agent's, so it stays on loopback behind the token, on this browser.
|
||||
* The app refuses the same ones (`ComputerBlockedMcpArgs`).
|
||||
*/
|
||||
export const McpBlockedArgs = [
|
||||
"--host",
|
||||
"--port",
|
||||
"--allowed-hosts",
|
||||
"--allowed-origins",
|
||||
"--cdp-endpoint",
|
||||
"--cdp-header",
|
||||
"--extension",
|
||||
"--config",
|
||||
"--browser",
|
||||
"--executable-path",
|
||||
"--user-data-dir",
|
||||
"--isolated",
|
||||
"--shared-browser-context",
|
||||
"--output-dir",
|
||||
"--file-paths",
|
||||
];
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import { connect } from "node:net";
|
||||
import type { Duplex } from "node:stream";
|
||||
|
||||
type Params = {
|
||||
req: IncomingMessage;
|
||||
socket: Duplex;
|
||||
head: Buffer;
|
||||
/**
|
||||
* The loopback port of the service behind this path.
|
||||
*/
|
||||
port: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Joins a websocket upgrade to a service on loopback (the web terminal)
|
||||
* byte for byte: its handshake is sent on as it came, path and
|
||||
* subprotocol included, with a loopback Host and without the caller's
|
||||
* Origin or the app's token; then every frame passes untouched.
|
||||
*/
|
||||
export default function bridgeLoopbackSocket({ req, socket, head, port }: Params) {
|
||||
const skipped = new Set(["host", "origin", "authorization"]);
|
||||
const lines = [`GET ${req.url || "/"} HTTP/1.1`, `Host: 127.0.0.1:${port}`];
|
||||
|
||||
for (let index = 0; index < req.rawHeaders.length; index += 2) {
|
||||
const name = req.rawHeaders[index]!;
|
||||
|
||||
if (!skipped.has(name.toLowerCase())) lines.push(`${name}: ${req.rawHeaders[index + 1]}`);
|
||||
}
|
||||
|
||||
const upstream = connect(port, "127.0.0.1", () => {
|
||||
upstream.write([...lines, "", ""].join("\r\n"));
|
||||
|
||||
if (head.length) upstream.write(head);
|
||||
|
||||
upstream.pipe(socket);
|
||||
socket.pipe(upstream);
|
||||
});
|
||||
|
||||
const close = () => {
|
||||
upstream.destroy();
|
||||
socket.destroy();
|
||||
};
|
||||
|
||||
upstream.on("error", close);
|
||||
socket.on("error", close);
|
||||
upstream.on("close", close);
|
||||
socket.on("close", close);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import { connect } from "node:net";
|
||||
import type { Duplex } from "node:stream";
|
||||
import encodeWebsocketFrame from "./encode-websocket-frame";
|
||||
import readWebsocketFrames from "./read-websocket-frames";
|
||||
import websocketAccept from "./websocket-accept";
|
||||
|
||||
type Params = {
|
||||
req: IncomingMessage;
|
||||
socket: Duplex;
|
||||
head: Buffer;
|
||||
/**
|
||||
* Xvnc's port, on loopback.
|
||||
*/
|
||||
port: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Carries noVNC's websocket to the screen's VNC server (Xvnc speaks plain
|
||||
* TCP), what websockify would do: each frame's payload goes to the VNC
|
||||
* server as bytes, and what it sends back goes out as binary frames. Pings
|
||||
* are answered, and a close on either side closes both.
|
||||
*/
|
||||
export default function bridgeVncSocket({ req, socket, head, port }: Params) {
|
||||
const key = req.headers["sec-websocket-key"];
|
||||
|
||||
if (typeof key != "string" || String(req.headers.upgrade || "").toLowerCase() != "websocket") {
|
||||
socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
|
||||
return;
|
||||
}
|
||||
|
||||
const protocols = String(req.headers["sec-websocket-protocol"] || "")
|
||||
.split(",")
|
||||
.map((protocol) => protocol.trim());
|
||||
const upstream = connect(port, "127.0.0.1");
|
||||
let connected = false;
|
||||
let closed = false;
|
||||
|
||||
const close = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
upstream.destroy();
|
||||
socket.destroy();
|
||||
};
|
||||
|
||||
const send = (frame: Buffer) => {
|
||||
if (!socket.write(frame)) upstream.pause();
|
||||
};
|
||||
|
||||
const feed = readWebsocketFrames({
|
||||
max_payload: 16 * 1024 * 1024,
|
||||
onFrame: ({ opcode, payload }) => {
|
||||
if (opcode <= 0x2) {
|
||||
if (!upstream.write(payload)) socket.pause();
|
||||
} else if (opcode == 0x8) {
|
||||
socket.end(encodeWebsocketFrame({ opcode: 0x8, payload: payload.subarray(0, 2) }));
|
||||
upstream.end();
|
||||
} else if (opcode == 0x9) {
|
||||
send(encodeWebsocketFrame({ opcode: 0xa, payload }));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const read = (chunk: Buffer) => {
|
||||
try {
|
||||
feed(chunk);
|
||||
} catch {
|
||||
close();
|
||||
}
|
||||
};
|
||||
|
||||
upstream.on("connect", () => {
|
||||
connected = true;
|
||||
|
||||
socket.write(
|
||||
[
|
||||
"HTTP/1.1 101 Switching Protocols",
|
||||
"Upgrade: websocket",
|
||||
"Connection: Upgrade",
|
||||
`Sec-WebSocket-Accept: ${websocketAccept({ key })}`,
|
||||
...(protocols.includes("binary") ? ["Sec-WebSocket-Protocol: binary"] : []),
|
||||
"",
|
||||
"",
|
||||
].join("\r\n"),
|
||||
);
|
||||
|
||||
if (head.length) read(head);
|
||||
socket.on("data", read);
|
||||
});
|
||||
|
||||
upstream.on("data", (chunk: Buffer) => send(encodeWebsocketFrame({ opcode: 0x2, payload: chunk })));
|
||||
upstream.on("drain", () => socket.resume());
|
||||
socket.on("drain", () => upstream.resume());
|
||||
|
||||
upstream.on("error", () => {
|
||||
if (!connected && !closed) {
|
||||
closed = true;
|
||||
socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");
|
||||
return;
|
||||
}
|
||||
|
||||
close();
|
||||
});
|
||||
|
||||
upstream.on("end", () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
socket.end(encodeWebsocketFrame({ opcode: 0x8, payload: Buffer.from([0x03, 0xe8]) }));
|
||||
});
|
||||
|
||||
socket.on("error", close);
|
||||
socket.on("close", close);
|
||||
// The HTTP server keeps upgraded sockets half open: a viewer that went
|
||||
// away without a close frame (a dropped network, a killed tab) only
|
||||
// ends its side, and would otherwise hold the bridge and Xvnc's
|
||||
// connection (and keep the browser from parking) for good.
|
||||
socket.on("end", close);
|
||||
upstream.on("close", () => {
|
||||
if (!closed) close();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import browserArgs from "./browser-args";
|
||||
|
||||
const base = {
|
||||
profile_dir: "/p",
|
||||
cdp_port: 9222,
|
||||
lang: "en-US",
|
||||
accept_lang: "en-US,en",
|
||||
sandbox: true,
|
||||
};
|
||||
|
||||
describe("browserArgs", () => {
|
||||
test("fills the screen at 100% without a scale flag", () => {
|
||||
const args = browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1 });
|
||||
|
||||
expect(args).toContain("--window-size=1920,1080");
|
||||
expect(args.some((arg) => arg.startsWith("--force-device-scale-factor"))).toBe(false);
|
||||
});
|
||||
|
||||
test("sizes the window in scaled units, so it still fits the screen", () => {
|
||||
expect(browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1.25 })).toEqual(
|
||||
expect.arrayContaining(["--window-size=1536,864", "--force-device-scale-factor=1.25"]),
|
||||
);
|
||||
expect(browserArgs({ ...base, screen: { width: 1366, height: 768 }, scale: 1.25 })).toContain("--window-size=1092,614");
|
||||
});
|
||||
|
||||
test("keeps WebGL but composites in software", () => {
|
||||
const args = browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1 });
|
||||
|
||||
expect(args).toEqual(expect.arrayContaining(["--ignore-gpu-blocklist", "--disable-gpu-compositing"]));
|
||||
});
|
||||
|
||||
test("a lightweight browser turns the GPU off and drops the WebGL flags", () => {
|
||||
const args = browserArgs({ ...base, screen: { width: 1366, height: 768 }, scale: 1, lightweight: true });
|
||||
|
||||
expect(args).toEqual(
|
||||
expect.arrayContaining([
|
||||
"--disable-gpu",
|
||||
"--force-prefers-reduced-motion",
|
||||
"--disable-smooth-scrolling",
|
||||
"--disable-component-update",
|
||||
]),
|
||||
);
|
||||
expect(args).not.toContain("--ignore-gpu-blocklist");
|
||||
expect(args).not.toContain("--disable-gpu-compositing");
|
||||
});
|
||||
|
||||
test("folds the user's --disable-features into the lightweight list", () => {
|
||||
const args = browserArgs({
|
||||
...base,
|
||||
screen: { width: 1366, height: 768 },
|
||||
scale: 1,
|
||||
lightweight: true,
|
||||
extra: ["--disable-features=Foo,Translate", "--mute-audio"],
|
||||
});
|
||||
const features = args.filter((arg) => arg.startsWith("--disable-features="));
|
||||
|
||||
expect(features).toHaveLength(1);
|
||||
expect(features[0]!.split("=")[1]!.split(",")).toEqual(expect.arrayContaining(["MediaRouter", "Translate", "Foo"]));
|
||||
expect(args).toContain("--mute-audio");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import mergeFeatureFlags from "./merge-feature-flags";
|
||||
|
||||
type Params = {
|
||||
profile_dir: string;
|
||||
cdp_port: number;
|
||||
screen: { width: number; height: number };
|
||||
/**
|
||||
* Chrome's device scale factor; 1 leaves the flag out.
|
||||
*/
|
||||
scale: number;
|
||||
lang: string;
|
||||
accept_lang: string;
|
||||
sandbox: boolean;
|
||||
/**
|
||||
* For small hosts: no Mesa in the GPU process (so no WebGL), reduced motion, no
|
||||
* smooth scrolling and none of Chrome's background downloads. Pages
|
||||
* draw and load with less CPU, but the browser looks less like a plain
|
||||
* desktop install.
|
||||
*/
|
||||
lightweight?: boolean;
|
||||
extra?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Chrome's background work a lightweight browser goes without: on-device
|
||||
* model and hint downloads, casting, translate prompts, autofill lookups.
|
||||
*/
|
||||
const LightweightDisabledFeatures = [
|
||||
"OptimizationGuideModelDownloading",
|
||||
"OptimizationHintsFetching",
|
||||
"OptimizationTargetPrediction",
|
||||
"OptimizationHints",
|
||||
"MediaRouter",
|
||||
"DialMediaRouteProvider",
|
||||
"Translate",
|
||||
"AutofillServerCommunication",
|
||||
];
|
||||
|
||||
/**
|
||||
* Chrome's flags: a normal headful browser on the virtual screen, its
|
||||
* window filling it, its DevTools port on loopback. Nothing that changes
|
||||
* what a page sees beyond what a plain desktop install would show (no
|
||||
* automation flags: the app attaches over CDP, it never launches it). The
|
||||
* basic password store keeps the cookies' key the same in every
|
||||
* container, so a profile carried over stays signed in. Feature lists are
|
||||
* merged with the extra flags' own, since Chrome reads only one of each.
|
||||
*/
|
||||
export default function browserArgs({ profile_dir, cdp_port, screen, scale, lang, accept_lang, sandbox, lightweight = false, extra = [] }: Params) {
|
||||
const args = [
|
||||
`--user-data-dir=${profile_dir}`,
|
||||
`--remote-debugging-port=${cdp_port}`,
|
||||
"--password-store=basic",
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
"--hide-crash-restore-bubble",
|
||||
"--window-position=0,0",
|
||||
// Chrome reads the window size in scaled units: divided by the
|
||||
// scale, the window fills the screen exactly.
|
||||
`--window-size=${Math.floor(screen.width / scale)},${Math.floor(screen.height / scale)}`,
|
||||
...(scale == 1 ? [] : [`--force-device-scale-factor=${scale}`]),
|
||||
...(lightweight ? lightweightArgs() : desktopGpuArgs()),
|
||||
/**
|
||||
* The image is updated instead; this keeps Chrome from nagging.
|
||||
*/
|
||||
"--simulate-outdated-no-au=Tue, 31 Dec 2099 23:59:59 GMT",
|
||||
`--lang=${lang}`,
|
||||
`--accept-lang=${accept_lang}`,
|
||||
...(sandbox ? [] : ["--no-sandbox", "--test-type"]),
|
||||
...extra,
|
||||
];
|
||||
|
||||
return mergeFeatureFlags({ args });
|
||||
}
|
||||
|
||||
/**
|
||||
* The GPU flags of an ordinary computer.
|
||||
*/
|
||||
function desktopGpuArgs() {
|
||||
return [
|
||||
/**
|
||||
* Without a GPU Chrome would turn WebGL off, which is a glaring
|
||||
* tell; with it, WebGL runs on Mesa's software renderer, as on a
|
||||
* real Linux box without GPU drivers.
|
||||
*/
|
||||
"--ignore-gpu-blocklist",
|
||||
/**
|
||||
* ...but compositing the page in software, as Chrome does with
|
||||
* the GPU blocklisted: half the CPU of drawing every frame through
|
||||
* Mesa, and WebGL still runs (and names Mesa) as before.
|
||||
*/
|
||||
"--disable-gpu-compositing",
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* A lightweight browser's flags: the GPU process stays (Chrome composites
|
||||
* in it) but never loads Mesa or LLVM, so WebGL is off; sites that respect reduced motion stop animating, scrolls
|
||||
* jump instead of drawing every step, and nothing downloads in the
|
||||
* background.
|
||||
*/
|
||||
function lightweightArgs() {
|
||||
return [
|
||||
"--disable-gpu",
|
||||
"--force-prefers-reduced-motion",
|
||||
"--disable-smooth-scrolling",
|
||||
"--disable-component-update",
|
||||
`--disable-features=${LightweightDisabledFeatures.join(",")}`,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import pageNeedsParking from "./page-needs-parking";
|
||||
import parkAfterMs from "./park-after-ms";
|
||||
import shouldParkBrowser from "./should-park-browser";
|
||||
|
||||
const idle = { now: 1_000_000, last_active_at: 1_000_000 - 180_000, checked_at: 0, viewers: 0, holds: 0, park_after_ms: 180_000 };
|
||||
|
||||
describe("shouldParkBrowser", () => {
|
||||
test("parks once it sat unused and unwatched long enough", () => {
|
||||
expect(shouldParkBrowser(idle)).toBe(true);
|
||||
expect(shouldParkBrowser({ ...idle, last_active_at: idle.now - 179_999 })).toBe(false);
|
||||
});
|
||||
|
||||
test("never while someone watches the screen or a tool call runs", () => {
|
||||
expect(shouldParkBrowser({ ...idle, viewers: 1 })).toBe(false);
|
||||
expect(shouldParkBrowser({ ...idle, holds: 1 })).toBe(false);
|
||||
});
|
||||
|
||||
test("looks only once per idle stretch", () => {
|
||||
expect(shouldParkBrowser({ ...idle, checked_at: idle.last_active_at + 1 })).toBe(false);
|
||||
expect(shouldParkBrowser({ ...idle, checked_at: idle.last_active_at - 1 })).toBe(true);
|
||||
});
|
||||
|
||||
test("0 turns it off", () => {
|
||||
expect(shouldParkBrowser({ ...idle, park_after_ms: 0, last_active_at: 0 })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pageNeedsParking", () => {
|
||||
test("sites do, Chrome's own pages don't", () => {
|
||||
expect(pageNeedsParking({ url: "https://www.youtube.com/watch?v=x" })).toBe(true);
|
||||
expect(pageNeedsParking({ url: "file:///tmp/a.html" })).toBe(true);
|
||||
|
||||
for (const url of ["about:blank", "chrome://newtab/", "chrome-untrusted://new-tab-page/", "chrome-error://chromewebdata/", "devtools://devtools/x"]) {
|
||||
expect(pageNeedsParking({ url })).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("parkAfterMs", () => {
|
||||
test("whole seconds, 0 for off, else 3 minutes", () => {
|
||||
expect(parkAfterMs({ text: "60" })).toBe(60_000);
|
||||
expect(parkAfterMs({ text: "0" })).toBe(0);
|
||||
expect(parkAfterMs({ text: undefined })).toBe(180_000);
|
||||
expect(parkAfterMs({ text: "-5" })).toBe(180_000);
|
||||
expect(parkAfterMs({ text: "1.5" })).toBe(180_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import browserScale from "./browser-scale";
|
||||
|
||||
describe("browserScale", () => {
|
||||
test("reads a factor", () => {
|
||||
expect(browserScale({ text: "1.25" })).toBe(1.25);
|
||||
expect(browserScale({ text: "2" })).toBe(2);
|
||||
expect(browserScale({ text: "1" })).toBe(1);
|
||||
});
|
||||
|
||||
test("falls back to 1.25 for nothing or anything out of range", () => {
|
||||
for (const text of [undefined, "", "abc", "0.5", "4", "-1"]) expect(browserScale({ text })).toBe(1.25);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Chrome's device scale factor from `COBBLE_BROWSER_SCALE` (e.g. `1`),
|
||||
* else 1.25: text is larger in bots' screenshots, and 1920x1080 reads as
|
||||
* 1536x864, the most common laptop. Kept between 1 and 3. The app's
|
||||
* `ComputerDefaultBrowserScale` is the same default.
|
||||
*/
|
||||
export default function browserScale({ text }: { text?: string }) {
|
||||
const scale = Number(text);
|
||||
|
||||
return text && Number.isFinite(scale) && scale >= 1 && scale <= 3 ? scale : 1.25;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { readdirSync, rmSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* Removes the `Singleton*` links a browser leaves in its profile when it
|
||||
* was stopped uncleanly (the container killed): another container's
|
||||
* hostname in them makes Chrome refuse the profile. Only called while no
|
||||
* browser runs.
|
||||
*/
|
||||
export default function clearProfileLocks({ profile_dir }: { profile_dir: string }) {
|
||||
let names: string[] = [];
|
||||
|
||||
try {
|
||||
names = readdirSync(profile_dir);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const name of names) {
|
||||
if (name.startsWith("Singleton")) rmSync(path.join(profile_dir, name), { force: true });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import commandArgv from "./command-argv";
|
||||
|
||||
describe("commandArgv", () => {
|
||||
test("bash -c on its own", () => {
|
||||
expect(commandArgv({ command: "ls -la" })).toEqual({ file: "bash", args: ["-c", "ls -la"] });
|
||||
});
|
||||
|
||||
test("through setpriv as another account, with its groups", () => {
|
||||
expect(commandArgv({ command: "id", as: { uid: 100_007, gid: 100_007 } })).toEqual({
|
||||
file: "setpriv",
|
||||
args: ["--reuid", "100007", "--regid", "100007", "--init-groups", "--", "bash", "-c", "id"],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* The program and arguments that run one `bash -c` command: as the
|
||||
* agent's own uid/gid, or through `setpriv` as another account with its
|
||||
* groups (`--init-groups`; Node's own `uid`/`gid` would drop them, and a
|
||||
* worker's workspace groups with them).
|
||||
*/
|
||||
export default function commandArgv({ command, as }: { command: string; as?: { uid: number; gid: number } }) {
|
||||
if (!as) return { file: "bash", args: ["-c", command] };
|
||||
|
||||
return {
|
||||
file: "setpriv",
|
||||
args: ["--reuid", String(as.uid), "--regid", String(as.gid), "--init-groups", "--", "bash", "-c", command],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { BrowserBlockedArgs, McpBlockedArgs } from "./blocked-args";
|
||||
import safeExtraArgs from "./safe-extra-args";
|
||||
import browserScale from "./browser-scale";
|
||||
import parkAfterMs from "./park-after-ms";
|
||||
import screenSize from "./screen-size";
|
||||
|
||||
const env = process.env;
|
||||
|
||||
/**
|
||||
* Everything the computer's agent is set up with. The user, home and
|
||||
* folders match what the app mounts (`AppData.ComputerHomeDir`,
|
||||
* `ComputerWorkspaceDir`, `ComputerBrowserProfileDir`).
|
||||
*/
|
||||
export const AgentConfig = {
|
||||
/**
|
||||
* The one port the app reaches: the API, `/mcp`, the screen and the
|
||||
* shell.
|
||||
*/
|
||||
Port: Number(env.COBBLE_AGENT_PORT || 8080),
|
||||
/**
|
||||
* Sent by the app as `Authorization: Bearer <token>`. Without one set,
|
||||
* every request is let in (a computer run by hand for development).
|
||||
*/
|
||||
Token: env.COBBLE_COMPUTER_TOKEN || "",
|
||||
/**
|
||||
* The computer's own user, with passwordless sudo: the services run as
|
||||
* it, and so do the coordinator's commands. Worker bots get accounts of
|
||||
* their own (`runUserFor`).
|
||||
*/
|
||||
User: "gem",
|
||||
Uid: 1000,
|
||||
Gid: 1000,
|
||||
Home: "/home/gem",
|
||||
/**
|
||||
* A worker bot's account is `cb-<bot id>`, uid and gid
|
||||
* `WorkerIdBase + bot id`, without sudo; a workspace's group is
|
||||
* `cw-<id>`, gid `WorkspaceGroupBase + id`. Ids above `MaxRunId` are
|
||||
* refused, so the ranges never meet. Keep alike the app's
|
||||
* `computerWorkerAccount`.
|
||||
*/
|
||||
WorkerIdBase: 100_000,
|
||||
WorkspaceGroupBase: 10_000_000,
|
||||
MaxRunId: 9_000_000,
|
||||
/**
|
||||
* The X display's cookie (gem's alone): without it nothing reaches the
|
||||
* screen, so a worker can't watch or type into Chrome.
|
||||
*/
|
||||
XAuthority: "/run/cobble/xauth",
|
||||
WorkspaceDir: "/home/gem/workspace",
|
||||
ProfileDir: env.COBBLE_BROWSER_PROFILE_DIR || "/home/gem/.cobble-browser",
|
||||
/**
|
||||
* The browser's pid and environment (`browser.pid`, `browser.json`),
|
||||
* the session bus and the runtime dir, for what runs beside it (the
|
||||
* notification watcher).
|
||||
*/
|
||||
RunDir: "/run/cobble",
|
||||
Display: ":99",
|
||||
Screen: screenSize({ text: env.COBBLE_SCREEN }),
|
||||
/**
|
||||
* How large Chrome draws pages (its device scale factor): above 1, text
|
||||
* is larger in screenshots and pages are laid out narrower.
|
||||
*/
|
||||
Scale: browserScale({ text: env.COBBLE_BROWSER_SCALE }),
|
||||
Lang: env.COBBLE_BROWSER_LANG || "en-US",
|
||||
AcceptLang: env.COBBLE_BROWSER_ACCEPT_LANG || env.COBBLE_BROWSER_LANG || "en-US,en",
|
||||
/**
|
||||
* `false` turns Chrome's sandbox off from the start. It's also turned
|
||||
* off by itself when Chrome says the host gives it none.
|
||||
*/
|
||||
BrowserSandbox: (env.COBBLE_BROWSER_SANDBOX || "true").toLowerCase() != "false",
|
||||
/**
|
||||
* `true` runs a lightweight browser for small hosts (`browserArgs`'s
|
||||
* `lightweight`) and caps the screen's updates at
|
||||
* `LightweightFrameRate`.
|
||||
*/
|
||||
BrowserLightweight: (env.COBBLE_BROWSER_LIGHTWEIGHT || "").toLowerCase() == "true",
|
||||
/**
|
||||
* The screen's updates a second with a lightweight browser (Xvnc's
|
||||
* `-FrameRate`, 60 otherwise): less to encode and send while a page
|
||||
* animates.
|
||||
*/
|
||||
LightweightFrameRate: 20,
|
||||
/**
|
||||
* More Chrome flags, space separated.
|
||||
*/
|
||||
BrowserExtraArgs: safeExtraArgs({ text: env.COBBLE_BROWSER_ARGS, blocked: BrowserBlockedArgs }),
|
||||
/**
|
||||
* Without a browser tool call or a screen view for this long, the
|
||||
* sites on show are sent behind a blank tab so their animations stop
|
||||
* costing CPU (`createBrowserParking`); 0 never does.
|
||||
*/
|
||||
BrowserParkAfterMs: parkAfterMs({ text: env.COBBLE_BROWSER_PARK_AFTER_SECONDS }),
|
||||
/**
|
||||
* Chrome's DevTools port, on loopback only: Playwright MCP reaches it
|
||||
* from inside the container.
|
||||
*/
|
||||
CdpPort: 9222,
|
||||
McpPort: 8931,
|
||||
McpCli: "/opt/playwright-mcp/node_modules/@playwright/mcp/cli.js",
|
||||
/**
|
||||
* More Playwright MCP flags, space separated (e.g. `--caps vision`),
|
||||
* without the ones that would move it off loopback or this browser.
|
||||
*/
|
||||
McpExtraArgs: safeExtraArgs({ text: env.COBBLE_MCP_ARGS, blocked: McpBlockedArgs }),
|
||||
/**
|
||||
* The shell's web terminal (ttyd), on loopback, served under
|
||||
* `/terminal/` behind the token.
|
||||
*/
|
||||
TerminalPort: 7681,
|
||||
/**
|
||||
* Where Playwright MCP writes snapshots, console logs and downloads
|
||||
* (the app's `AppData.ComputerBrowserOutputDir`), oldest evicted past
|
||||
* the size.
|
||||
*/
|
||||
McpOutputDir: "/home/gem/.cobble/playwright",
|
||||
McpOutputMaxBytes: 256 * 1024 * 1024,
|
||||
/**
|
||||
* The screen's VNC server (Xvnc), on loopback, reached through the
|
||||
* agent's own websocket bridge at `/desktop/websockify`.
|
||||
*/
|
||||
VncPort: 5900,
|
||||
/**
|
||||
* noVNC, the screen's viewer, served at `/desktop/`.
|
||||
*/
|
||||
NoVncDir: env.COBBLE_NOVNC_DIR || "/opt/novnc",
|
||||
/**
|
||||
* A command's timeout when it names none, and the most it may ask for.
|
||||
*/
|
||||
CommandDefaultSeconds: 270,
|
||||
CommandMaxSeconds: 3600,
|
||||
/**
|
||||
* Output past this is dropped (and the response says so).
|
||||
*/
|
||||
CommandMaxOutputBytes: 4 * 1024 * 1024,
|
||||
/**
|
||||
* How long children get to exit on a stop before they're killed.
|
||||
*/
|
||||
StopGraceMs: 8000,
|
||||
};
|
||||
@@ -0,0 +1,144 @@
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
||||
import { AgentState } from "./agent-state";
|
||||
import { AgentConfig } from "./config";
|
||||
import handleExec from "./handle-exec";
|
||||
import handleFileDownload from "./handle-file-download";
|
||||
import handleFileStat from "./handle-file-stat";
|
||||
import handleFileWrite from "./handle-file-write";
|
||||
import isAuthorized from "./is-authorized";
|
||||
import isPortAnswering from "./is-port-answering";
|
||||
import log from "./log";
|
||||
import bridgeLoopbackSocket from "./bridge-loopback-socket";
|
||||
import bridgeVncSocket from "./bridge-vnc-socket";
|
||||
import type { BrowserParking } from "./create-browser-parking";
|
||||
import proxyLoopback from "./proxy-loopback";
|
||||
import sendJson from "./send-json";
|
||||
import serveStaticFile from "./serve-static-file";
|
||||
|
||||
/**
|
||||
* The agent's one port:
|
||||
*
|
||||
* - `GET /health` (open): 200 once the browser and its tools answer.
|
||||
* - `GET /api/info`, `POST /api/exec`, `GET /api/files/stat|download`,
|
||||
* `POST /api/files/write`: the app's shell and file access, as gem or
|
||||
* as a worker bot's own account (`run_as`).
|
||||
* - `/mcp`: Playwright MCP, driving the computer's browser.
|
||||
* - `/desktop/` and its `/desktop/websockify` websocket: the screen
|
||||
* (noVNC over Xvnc), Chrome's whole window.
|
||||
* - `/terminal/` and its websocket: a shell in the browser (ttyd).
|
||||
*
|
||||
* Everything but the health check needs the computer's token. Browser
|
||||
* tool calls and screen views wake a parked browser first (`parking`).
|
||||
*/
|
||||
export default function createAgentServer({ parking }: { parking: BrowserParking }) {
|
||||
const server = createServer((req, res) => {
|
||||
route({ req, res, parking }).catch((error) => {
|
||||
log({ name: "agent", message: `${req.method} ${req.url} failed: ${error?.message || error}` });
|
||||
|
||||
if (!res.headersSent) sendJson({ res, status: 500, body: { error: String(error?.message || error) } });
|
||||
else res.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
server.on("upgrade", (req, socket, head) => {
|
||||
const pathname = new URL(req.url || "/", "http://agent").pathname;
|
||||
|
||||
const authorized = isAuthorized({ headers: req.headers, token: AgentConfig.Token });
|
||||
|
||||
if (authorized && pathname == "/desktop/websockify") {
|
||||
const watching = parking.watch();
|
||||
|
||||
socket.once("close", watching.done);
|
||||
bridgeVncSocket({ req, socket, head, port: AgentConfig.VncPort });
|
||||
return;
|
||||
}
|
||||
|
||||
if (authorized && pathname.startsWith("/terminal/")) {
|
||||
bridgeLoopbackSocket({ req, socket, head, port: AgentConfig.TerminalPort });
|
||||
return;
|
||||
}
|
||||
|
||||
socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n");
|
||||
});
|
||||
|
||||
/**
|
||||
* Commands and event streams can run long; the app keeps its own
|
||||
* timeouts.
|
||||
*/
|
||||
server.requestTimeout = 0;
|
||||
server.headersTimeout = 60_000;
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
async function route({ req, res, parking }: { req: IncomingMessage; res: ServerResponse; parking: BrowserParking }) {
|
||||
const { pathname } = new URL(req.url || "/", "http://agent");
|
||||
|
||||
if (pathname == "/health") {
|
||||
const [browser, mcp] = await Promise.all([
|
||||
isPortAnswering({ url: `http://127.0.0.1:${AgentConfig.CdpPort}/json/version` }),
|
||||
isPortAnswering({ url: `http://127.0.0.1:${AgentConfig.McpPort}/mcp` }),
|
||||
]);
|
||||
|
||||
return sendJson({ res, status: browser && mcp ? 200 : 503, body: { ok: browser && mcp, browser, mcp } });
|
||||
}
|
||||
|
||||
if (!isAuthorized({ headers: req.headers, token: AgentConfig.Token })) {
|
||||
return sendJson({ res, status: 401, body: { error: "Unauthorized" } });
|
||||
}
|
||||
|
||||
if (pathname == "/mcp" || pathname.startsWith("/mcp/")) {
|
||||
// A GET is the session's event stream, open for as long as the
|
||||
// session: only calls hold parking off while they run.
|
||||
const holding = req.method == "GET" ? undefined : parking.hold();
|
||||
|
||||
if (holding) res.once("close", holding.done);
|
||||
|
||||
await parking.wake();
|
||||
|
||||
return proxyLoopback({ req, res, port: AgentConfig.McpPort, unavailable: "The browser tools aren't answering yet." });
|
||||
}
|
||||
|
||||
if (pathname == "/terminal") {
|
||||
res.writeHead(302, { location: "terminal/" }).end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname.startsWith("/terminal/")) {
|
||||
return proxyLoopback({ req, res, port: AgentConfig.TerminalPort, unavailable: "The shell isn't answering yet." });
|
||||
}
|
||||
|
||||
if (pathname == "/" || pathname == "/desktop") {
|
||||
res.writeHead(302, { location: "desktop/" }).end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname == "/desktop/") return serveStaticFile({ res, root: AgentConfig.NoVncDir, name: "vnc.html" });
|
||||
if (pathname.startsWith("/desktop/")) {
|
||||
return serveStaticFile({ res, root: AgentConfig.NoVncDir, name: pathname.slice("/desktop/".length) });
|
||||
}
|
||||
|
||||
if (pathname == "/api/info" && req.method == "GET") {
|
||||
return sendJson({
|
||||
res,
|
||||
body: {
|
||||
home_dir: AgentConfig.Home,
|
||||
workspace_dir: AgentConfig.WorkspaceDir,
|
||||
user: AgentConfig.User,
|
||||
workers_guarded: AgentState.workers_guarded,
|
||||
browser: {
|
||||
binary: AgentState.browser_binary,
|
||||
version: AgentState.browser_version,
|
||||
sandbox: AgentState.browser_sandbox,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (pathname == "/api/exec" && req.method == "POST") return handleExec({ req, res });
|
||||
if (pathname == "/api/files/stat" && req.method == "GET") return handleFileStat({ req, res });
|
||||
if (pathname == "/api/files/download" && req.method == "GET") return handleFileDownload({ req, res });
|
||||
if (pathname == "/api/files/write" && req.method == "POST") return handleFileWrite({ req, res });
|
||||
|
||||
sendJson({ res, status: 404, body: { error: "Not Found" } });
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import log from "./log";
|
||||
import openCdpConnection, { type CdpConnection } from "./open-cdp-connection";
|
||||
import parkBrowserTabs, { type ParkedTab } from "./park-browser-tabs";
|
||||
import shouldParkBrowser from "./should-park-browser";
|
||||
import unparkBrowserTabs from "./unpark-browser-tabs";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Chrome's DevTools port, on loopback.
|
||||
*/
|
||||
cdp_port: number;
|
||||
/**
|
||||
* Unused and unwatched this long parks the browser; 0 never does.
|
||||
*/
|
||||
park_after_ms: number;
|
||||
/**
|
||||
* How often idleness is checked.
|
||||
*/
|
||||
check_every_ms?: number;
|
||||
};
|
||||
|
||||
export type BrowserParking = {
|
||||
/**
|
||||
* Someone is about to use the browser: brings parked tabs back first.
|
||||
* Resolves once it's as it was left (never rejects).
|
||||
*/
|
||||
wake: () => Promise<void>;
|
||||
/**
|
||||
* A browser tool call started: nothing is parked until `done` runs.
|
||||
*/
|
||||
hold: () => { done: () => void };
|
||||
/**
|
||||
* A screen view opened: brings the tabs back and parks nothing while
|
||||
* it's open. Returns what to call when it closes.
|
||||
*/
|
||||
watch: () => { done: () => void };
|
||||
/**
|
||||
* Chrome started again: its old tabs are gone, so nothing is parked.
|
||||
*/
|
||||
browserRestarted: () => void;
|
||||
};
|
||||
|
||||
const CdpTimeoutMs = 10_000;
|
||||
|
||||
/**
|
||||
* Keeps an idle browser from burning CPU. The computer's screen has no GPU
|
||||
* and no window manager, so the tab in front is always "on show" and its
|
||||
* animations are drawn in software at full rate even when nobody watches.
|
||||
* After `park_after_ms` without a browser tool call or a screen view,
|
||||
* every site on show goes to the background behind a blank tab
|
||||
* (`parkBrowserTabs`), what a person switching tabs does, so pages see
|
||||
* nothing out of the ordinary; the next tool call or view brings them back
|
||||
* before it goes through. One operation at a time.
|
||||
*/
|
||||
export default function createBrowserParking({ cdp_port, park_after_ms, check_every_ms = 15_000 }: Params): BrowserParking {
|
||||
let last_active_at = Date.now();
|
||||
let checked_at = 0;
|
||||
let viewers = 0;
|
||||
let holds = 0;
|
||||
let parked: ParkedTab[] = [];
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
let parking = false;
|
||||
|
||||
const touch = () => {
|
||||
last_active_at = Date.now();
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs one operation after the ones before it, over its own DevTools
|
||||
* connection.
|
||||
*/
|
||||
const run = (task: (cdp: CdpConnection) => Promise<void>) => {
|
||||
queue = queue.then(async () => {
|
||||
let cdp: CdpConnection | undefined;
|
||||
|
||||
try {
|
||||
cdp = await openCdpConnection({ port: cdp_port, timeout_ms: CdpTimeoutMs });
|
||||
await task(cdp);
|
||||
} catch (error: any) {
|
||||
log({ name: "parking", message: `couldn't reach the browser: ${error?.message || error}` });
|
||||
} finally {
|
||||
cdp?.close();
|
||||
}
|
||||
});
|
||||
|
||||
return queue;
|
||||
};
|
||||
|
||||
const idle = () =>
|
||||
shouldParkBrowser({ now: Date.now(), last_active_at, checked_at, viewers, holds, park_after_ms });
|
||||
|
||||
const park = () =>
|
||||
run(async (cdp) => {
|
||||
// Used again while it waited its turn.
|
||||
if (!idle()) return;
|
||||
|
||||
const tabs = await parkBrowserTabs({ cdp });
|
||||
|
||||
checked_at = Date.now();
|
||||
parked.push(...tabs);
|
||||
|
||||
if (tabs.length) log({ name: "parking", message: `idle: parked ${tabs.length} tab${tabs.length == 1 ? "" : "s"}` });
|
||||
});
|
||||
|
||||
const wake = () => {
|
||||
touch();
|
||||
|
||||
// Quick when nothing is parked or being parked (a park waiting its
|
||||
// turn sees the browser in use and does nothing).
|
||||
if (!parked.length && !parking) return Promise.resolve();
|
||||
|
||||
return run(async (cdp) => {
|
||||
if (!parked.length) return;
|
||||
|
||||
const tabs = parked;
|
||||
|
||||
parked = [];
|
||||
await unparkBrowserTabs({ cdp, parked: tabs });
|
||||
log({ name: "parking", message: `in use: brought back ${tabs.length} tab${tabs.length == 1 ? "" : "s"}` });
|
||||
});
|
||||
};
|
||||
|
||||
if (park_after_ms > 0) {
|
||||
setInterval(() => {
|
||||
if (parking || !idle()) return;
|
||||
|
||||
parking = true;
|
||||
park().finally(() => {
|
||||
parking = false;
|
||||
});
|
||||
}, check_every_ms).unref();
|
||||
}
|
||||
|
||||
return {
|
||||
wake,
|
||||
hold: () => {
|
||||
holds++;
|
||||
touch();
|
||||
|
||||
let released = false;
|
||||
|
||||
return {
|
||||
done: () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
holds--;
|
||||
touch();
|
||||
},
|
||||
};
|
||||
},
|
||||
watch: () => {
|
||||
viewers++;
|
||||
wake();
|
||||
|
||||
let released = false;
|
||||
|
||||
return {
|
||||
done: () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
viewers--;
|
||||
touch();
|
||||
},
|
||||
};
|
||||
},
|
||||
browserRestarted: () => {
|
||||
parked = [];
|
||||
checked_at = 0;
|
||||
touch();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
type Params = {
|
||||
opcode: number;
|
||||
payload: Buffer;
|
||||
/**
|
||||
* Four bytes to mask the payload with, as a client must (the agent's
|
||||
* own DevTools client); a server's frames go unmasked.
|
||||
*/
|
||||
mask?: Buffer;
|
||||
};
|
||||
|
||||
/**
|
||||
* One whole frame (RFC 6455) around a payload: unmasked, as a server
|
||||
* sends it, unless a `mask` is given.
|
||||
*/
|
||||
export default function encodeWebsocketFrame({ opcode, payload, mask }: Params) {
|
||||
const length = payload.length;
|
||||
const mask_bit = mask ? 0x80 : 0;
|
||||
let header: Buffer;
|
||||
|
||||
if (length < 126) {
|
||||
header = Buffer.from([0x80 | opcode, mask_bit | length]);
|
||||
} else if (length < 65536) {
|
||||
header = Buffer.alloc(4);
|
||||
header[0] = 0x80 | opcode;
|
||||
header[1] = mask_bit | 126;
|
||||
header.writeUInt16BE(length, 2);
|
||||
} else {
|
||||
header = Buffer.alloc(10);
|
||||
header[0] = 0x80 | opcode;
|
||||
header[1] = mask_bit | 127;
|
||||
header.writeBigUInt64BE(BigInt(length), 2);
|
||||
}
|
||||
|
||||
if (!mask) return Buffer.concat([header, payload]);
|
||||
|
||||
const masked = Buffer.from(payload);
|
||||
|
||||
for (let index = 0; index < masked.length; index++) masked[index]! ^= mask[index & 3]!;
|
||||
|
||||
return Buffer.concat([header, mask.subarray(0, 4), masked]);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { chmod, chown, lstat, mkdir, readlink, rename, stat, symlink, unlink } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { AgentConfig } from "./config";
|
||||
import commandArgv from "./command-argv";
|
||||
import log from "./log";
|
||||
import type { RunUser } from "./run-user-for";
|
||||
|
||||
const run = promisify(execFile);
|
||||
|
||||
/**
|
||||
* Accounts already set up since the agent started. They live in the
|
||||
* container, so a recreated one starts with none and they're made again.
|
||||
*/
|
||||
const ready = new Set<string>();
|
||||
|
||||
let queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
/**
|
||||
* Makes a worker's account and, in a workspace, its group (idempotent,
|
||||
* one at a time), and hands it its folders: its home (private), the bot's
|
||||
* folder (its own) and the workspace's (its group's). Neither gem nor any
|
||||
* other worker can read them; the coordinator, as gem, uses sudo. Then,
|
||||
* on every call, makes sure of the links the worker works through
|
||||
* (`keepLinks`): only the bot's folder is kept, so a write through a link
|
||||
* that's gone would land somewhere a recreate wipes.
|
||||
*/
|
||||
export default async function ensureRunUser({ run_user }: { run_user: RunUser }) {
|
||||
const key = `${run_user.uid}:${run_user.workspace?.gid || 0}`;
|
||||
|
||||
if (!ready.has(key)) {
|
||||
await serially(async () => {
|
||||
if (ready.has(key)) return;
|
||||
|
||||
await setUp({ run_user });
|
||||
ready.add(key);
|
||||
});
|
||||
}
|
||||
|
||||
if (!(await linksInPlace({ run_user }))) await serially(() => keepLinks({ run_user }));
|
||||
}
|
||||
|
||||
function serially(work: () => Promise<void>) {
|
||||
const next = queue.then(work);
|
||||
|
||||
queue = next.catch(() => {});
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
async function setUp({ run_user }: { run_user: RunUser }) {
|
||||
const { name, uid, gid, home, workspace } = run_user;
|
||||
|
||||
if (!(await exists({ db: "group", key: name }))) await run("groupadd", ["-g", String(gid), name]);
|
||||
|
||||
if (!(await exists({ db: "passwd", key: name }))) {
|
||||
await run("useradd", ["-l", "-M", "-u", String(uid), "-g", String(gid), "-d", home, "-s", "/bin/bash", name]);
|
||||
}
|
||||
|
||||
if (workspace) {
|
||||
if (!(await exists({ db: "group", key: workspace.name }))) {
|
||||
await run("groupadd", ["-g", String(workspace.gid), workspace.name]);
|
||||
}
|
||||
|
||||
const { stdout } = await run("id", ["-nG", name]);
|
||||
|
||||
if (!stdout.split(/\s+/).includes(workspace.name)) await run("usermod", ["-aG", workspace.name, name]);
|
||||
}
|
||||
|
||||
for (const dir of [home, path.posix.join(home, ".cobble")]) {
|
||||
await mkdir(dir, { recursive: true });
|
||||
await chown(dir, uid, gid);
|
||||
await chmod(dir, 0o700);
|
||||
}
|
||||
|
||||
await shareFolder({ dir: run_user.bot_dir, uid, gid });
|
||||
|
||||
/**
|
||||
* Root owns a workspace's folder (no worker can change its mode), its
|
||||
* bots share it through the group.
|
||||
*/
|
||||
if (workspace) await shareFolder({ dir: workspace.dir, uid: 0, gid: workspace.gid });
|
||||
|
||||
await keepLinks({ run_user });
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the worker's links lead where they should: `workspace` in its
|
||||
* home to the bot's folder, and in a workspace, `workspaces/<id>` in the
|
||||
* bot's folder to the workspace's shared one. Only reads.
|
||||
*/
|
||||
async function linksInPlace({ run_user }: { run_user: RunUser }) {
|
||||
if (!(await isLinkTo({ link: run_user.kept_dir, target: run_user.bot_dir }))) return false;
|
||||
|
||||
return !run_user.workspace || isLinkTo({ link: run_user.workspace.link, target: run_user.workspace.dir });
|
||||
}
|
||||
|
||||
async function isLinkTo({ link, target }: { link: string; target: string }) {
|
||||
const info = await lstat(link).catch(() => null);
|
||||
|
||||
return !!info?.isSymbolicLink() && (await readlink(link).catch(() => "")) == target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the worker's links back where they're missing or lead elsewhere.
|
||||
* Whatever else sits in a link's place is moved aside, never deleted.
|
||||
* The home's link is made as root (the home is a real folder in root's
|
||||
* /home, so nothing in its path is the worker's to swap); the shared
|
||||
* folder's, inside the bot's folder (the worker's own), by the worker's
|
||||
* account, so a link it left there can't send root anywhere.
|
||||
*/
|
||||
async function keepLinks({ run_user }: { run_user: RunUser }) {
|
||||
const { kept_dir, bot_dir, workspace } = run_user;
|
||||
|
||||
if (!(await isLinkTo({ link: kept_dir, target: bot_dir }))) {
|
||||
const info = await lstat(kept_dir).catch(() => null);
|
||||
|
||||
if (info?.isSymbolicLink()) await unlink(kept_dir);
|
||||
else if (info) await rename(kept_dir, `${kept_dir}.before-${Date.now()}`);
|
||||
|
||||
await symlink(bot_dir, kept_dir);
|
||||
}
|
||||
|
||||
if (workspace && !(await isLinkTo({ link: workspace.link, target: workspace.dir }))) {
|
||||
const link = quoted({ text: workspace.link });
|
||||
const target = quoted({ text: workspace.dir });
|
||||
const argv = commandArgv({
|
||||
command: [
|
||||
`umask 007`,
|
||||
`mkdir -p "$(dirname ${link})"`,
|
||||
`if [ -L ${link} ]; then ln -sfn ${target} ${link}; elif [ -e ${link} ]; then mv ${link} ${link}.before-$(date +%s) && ln -s ${target} ${link}; else ln -s ${target} ${link}; fi`,
|
||||
].join(" && "),
|
||||
as: { uid: run_user.uid, gid: run_user.gid },
|
||||
});
|
||||
|
||||
await run(argv.file, argv.args, { cwd: "/", timeout: 30_000 });
|
||||
}
|
||||
}
|
||||
|
||||
function quoted({ text }: { text: string }) {
|
||||
return `'${text.replaceAll("'", `'\\''`)}'`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives a folder to its owner and group (`2770`: new files keep the
|
||||
* group), with default ACLs so what's made inside stays open to the group
|
||||
* (a workspace's bots) and closed to everyone else. gem gets no way in:
|
||||
* 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.
|
||||
*/
|
||||
async function shareFolder({ dir, uid, gid }: { dir: string; uid: number; gid: number }) {
|
||||
await makeParents({ dir });
|
||||
await mkdir(dir, { recursive: true });
|
||||
|
||||
const info = await stat(dir);
|
||||
|
||||
/**
|
||||
* Already handed over: only its own mode is put back (its owner may
|
||||
* have changed it), never walked again, so a worker can't have root
|
||||
* walk a tree it keeps changing.
|
||||
*/
|
||||
if (info.uid == uid && info.gid == gid) {
|
||||
if ((info.mode & 0o7777) != 0o2770) await chmod(dir, 0o2770);
|
||||
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) => {
|
||||
log({ name: "agent", message: `couldn't set default ACLs on ${dir}: ${error?.stderr || error?.message || error}` });
|
||||
});
|
||||
|
||||
await chmod(dir, 0o2770);
|
||||
}
|
||||
|
||||
/**
|
||||
* `bots/` and `workspaces/` themselves stay gem's and open to all, so a
|
||||
* worker can walk to its own folder.
|
||||
*/
|
||||
async function makeParents({ dir }: { dir: string }) {
|
||||
const parent = path.posix.dirname(dir);
|
||||
const created = await mkdir(parent, { recursive: true });
|
||||
|
||||
if (created) {
|
||||
await chown(parent, AgentConfig.Uid, AgentConfig.Gid);
|
||||
await chmod(parent, 0o755);
|
||||
}
|
||||
}
|
||||
|
||||
async function exists({ db, key }: { db: "group" | "passwd"; key: string }) {
|
||||
return run("getent", [db, key]).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { existsSync } from "node:fs";
|
||||
|
||||
/**
|
||||
* Google Chrome where it exists (amd64), else Debian's Chromium (arm64).
|
||||
*/
|
||||
export const BrowserBinaries = ["/usr/bin/google-chrome-stable", "/usr/bin/chromium"];
|
||||
|
||||
export default function findBrowserBinary() {
|
||||
const found = BrowserBinaries.find((binary) => existsSync(binary));
|
||||
|
||||
if (!found) throw new Error(`No browser installed (looked for ${BrowserBinaries.join(", ")}).`);
|
||||
|
||||
return found;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import guardRuleset from "./guard-ruleset";
|
||||
|
||||
describe("guardRuleset", () => {
|
||||
test("resets the worker uids' connections to the service ports", () => {
|
||||
const rules = guardRuleset({ uid_from: 100_001, uid_to: 9_100_000, ports: [9222, 5900, 7681, 5900] });
|
||||
|
||||
expect(rules).toContain("delete table inet cobble_guard");
|
||||
expect(rules).toContain("type filter hook output priority filter; policy accept;");
|
||||
expect(rules).toContain("meta skuid 100001-9100000 tcp dport { 5900, 7681, 9222 } reject with tcp reset");
|
||||
});
|
||||
|
||||
test("replaces the table whole: added, deleted, then written", () => {
|
||||
const lines = guardRuleset({ uid_from: 1, uid_to: 2, ports: [1] }).split("\n");
|
||||
|
||||
expect(lines.slice(0, 3)).toEqual(["add table inet cobble_guard", "delete table inet cobble_guard", "table inet cobble_guard {"]);
|
||||
});
|
||||
|
||||
test("refuses nothing to guard", () => {
|
||||
expect(() => guardRuleset({ uid_from: 1, uid_to: 2, ports: [] })).toThrow();
|
||||
expect(() => guardRuleset({ uid_from: 1, uid_to: 2, ports: [0, 70000] })).toThrow();
|
||||
expect(() => guardRuleset({ uid_from: 5, uid_to: 2, ports: [1] })).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
type Params = {
|
||||
/**
|
||||
* The worker accounts' uids, inclusive.
|
||||
*/
|
||||
uid_from: number;
|
||||
uid_to: number;
|
||||
/**
|
||||
* The computer's own services: none of them asks who's connecting.
|
||||
*/
|
||||
ports: number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The nftables rules that keep worker accounts off the computer's own
|
||||
* services on loopback (the screen, the shell, Chrome's DevTools,
|
||||
* Playwright MCP, the agent): their connections are reset. It replaces
|
||||
* the table whole, so applying it twice is the same as once.
|
||||
*/
|
||||
export default function guardRuleset({ uid_from, uid_to, ports }: Params) {
|
||||
const list = [...new Set(ports.map((port) => Math.trunc(port)).filter((port) => port > 0 && port < 65536))].sort(
|
||||
(a, b) => a - b,
|
||||
);
|
||||
|
||||
if (!list.length) throw new Error("No ports to guard.");
|
||||
if (!(uid_from > 0 && uid_to >= uid_from)) throw new Error("No uids to guard.");
|
||||
|
||||
return [
|
||||
"add table inet cobble_guard",
|
||||
"delete table inet cobble_guard",
|
||||
"table inet cobble_guard {",
|
||||
" chain output {",
|
||||
" type filter hook output priority filter; policy accept;",
|
||||
` meta skuid ${Math.trunc(uid_from)}-${Math.trunc(uid_to)} tcp dport { ${list.join(", ")} } reject with tcp reset`,
|
||||
" }",
|
||||
"}",
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { AgentState } from "./agent-state";
|
||||
import { AgentConfig } from "./config";
|
||||
import guardRuleset from "./guard-ruleset";
|
||||
import log from "./log";
|
||||
|
||||
/**
|
||||
* Keeps worker accounts off the services on loopback (`guardRuleset`),
|
||||
* which needs the container's `NET_ADMIN`. Until it's in place
|
||||
* (`AgentState.workers_guarded`), worker commands are refused: run
|
||||
* without it, a worker could reach the shell as gem, and so root.
|
||||
*/
|
||||
export default function guardServicePorts() {
|
||||
try {
|
||||
const rules = guardRuleset({
|
||||
uid_from: AgentConfig.WorkerIdBase + 1,
|
||||
uid_to: AgentConfig.WorkerIdBase + AgentConfig.MaxRunId,
|
||||
ports: [AgentConfig.Port, AgentConfig.VncPort, AgentConfig.CdpPort, AgentConfig.McpPort, AgentConfig.TerminalPort],
|
||||
});
|
||||
|
||||
execFileSync("nft", ["-f", "-"], { input: rules, stdio: ["pipe", "ignore", "pipe"], timeout: 10_000 });
|
||||
execFileSync("nft", ["list", "table", "inet", "cobble_guard"], { stdio: "ignore", timeout: 10_000 });
|
||||
|
||||
AgentState.workers_guarded = true;
|
||||
AgentState.guard_error = "";
|
||||
log({ name: "agent", message: "worker accounts are kept off the computer's services" });
|
||||
} catch (error: any) {
|
||||
AgentState.workers_guarded = false;
|
||||
AgentState.guard_error = String(error?.stderr || error?.message || error).trim().slice(0, 500);
|
||||
log({ name: "agent", message: `couldn't guard the services from worker accounts, so worker commands are refused: ${AgentState.guard_error}` });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { AgentConfig } from "./config";
|
||||
import readJsonBody from "./read-json-body";
|
||||
import requestRunUser from "./request-run-user";
|
||||
import runCommand from "./run-command";
|
||||
import sendJson from "./send-json";
|
||||
import userEnv from "./user-env";
|
||||
import workerEnv from "./worker-env";
|
||||
|
||||
/**
|
||||
* `POST /api/exec` `{ command, timeout_seconds?, cwd?, run_as? }`: runs
|
||||
* one bash command as the computer's user (`runCommand`), or with
|
||||
* `run_as: { bot_id, workspace_id? }` as that worker bot's own account
|
||||
* (`requestRunUser`), from its home unless `cwd` is given. The command is
|
||||
* killed if the caller goes away. Answers `{ output, exit_code,
|
||||
* timed_out, truncated }`.
|
||||
*/
|
||||
export default async function handleExec({ req, res }: { req: IncomingMessage; res: ServerResponse }) {
|
||||
const body = await readJsonBody({ req, max_bytes: 1024 * 1024 });
|
||||
|
||||
if (typeof body?.command != "string" || !body.command.trim()) {
|
||||
return sendJson({ res, status: 400, body: { error: "Give the command." } });
|
||||
}
|
||||
|
||||
const run_user = await requestRunUser({ res, run_as: body.run_as });
|
||||
|
||||
if (run_user === undefined) return;
|
||||
|
||||
const asked = Number(body.timeout_seconds);
|
||||
const timeout_seconds = Number.isFinite(asked) && asked > 0
|
||||
? Math.min(Math.ceil(asked), AgentConfig.CommandMaxSeconds)
|
||||
: AgentConfig.CommandDefaultSeconds;
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
res.on("close", () => {
|
||||
if (!res.writableFinished) controller.abort();
|
||||
});
|
||||
|
||||
const home = run_user ? run_user.home : AgentConfig.Home;
|
||||
|
||||
const result = await runCommand({
|
||||
command: body.command,
|
||||
cwd: typeof body.cwd == "string" && body.cwd.startsWith("/") ? body.cwd : home,
|
||||
env: run_user ? workerEnv({ run_user }) : userEnv(),
|
||||
...(run_user ? { as: { uid: run_user.uid, gid: run_user.gid } } : { uid: AgentConfig.Uid, gid: AgentConfig.Gid }),
|
||||
timeout_seconds,
|
||||
max_output_bytes: AgentConfig.CommandMaxOutputBytes,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!res.destroyed) sendJson({ res, body: result });
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import openRunFile from "./open-run-file";
|
||||
import queryPath from "./query-path";
|
||||
import queryRunAs from "./query-run-as";
|
||||
import requestRunUser from "./request-run-user";
|
||||
import sendJson from "./send-json";
|
||||
|
||||
/**
|
||||
* `GET /api/files/download?path=`: the file byte for byte, with its
|
||||
* length. When it changes while it's sent, the connection is cut, so the
|
||||
* caller sees a short body instead of a mix of two versions. With
|
||||
* `run_as_bot_id` (and `run_as_workspace_id`), only inside that worker's
|
||||
* own folders (`openRunFile`).
|
||||
*/
|
||||
export default async function handleFileDownload({ req, res }: { req: IncomingMessage; res: ServerResponse }) {
|
||||
const file = queryPath({ req });
|
||||
|
||||
if (!file) return sendJson({ res, status: 400, body: { error: "Give an absolute path." } });
|
||||
|
||||
const run_user = await requestRunUser({ res, run_as: queryRunAs({ req }) });
|
||||
|
||||
if (run_user === undefined) return;
|
||||
|
||||
const handle = await openRunFile({ file, run_user });
|
||||
const before = await handle?.stat().catch(() => null);
|
||||
|
||||
if (!handle || !before) {
|
||||
await handle?.close().catch(() => {});
|
||||
return sendJson({ res, status: 404, body: { error: "There's no such file." } });
|
||||
}
|
||||
|
||||
if (!before.isFile()) {
|
||||
await handle.close().catch(() => {});
|
||||
return sendJson({ res, status: 400, body: { error: "That isn't a file." } });
|
||||
}
|
||||
|
||||
res.writeHead(200, {
|
||||
"content-type": "application/octet-stream",
|
||||
"content-length": before.size,
|
||||
"cache-control": "no-store",
|
||||
});
|
||||
|
||||
const stream = handle.createReadStream({ autoClose: false });
|
||||
|
||||
stream.on("error", () => {
|
||||
res.destroy();
|
||||
handle.close().catch(() => {});
|
||||
});
|
||||
stream.on("end", async () => {
|
||||
const after = await handle.stat().catch(() => null);
|
||||
|
||||
await handle.close().catch(() => {});
|
||||
|
||||
if (!after || after.size != before.size || after.mtimeMs != before.mtimeMs) res.destroy();
|
||||
});
|
||||
res.on("close", () => {
|
||||
if (!stream.readableEnded) handle.close().catch(() => {});
|
||||
});
|
||||
stream.pipe(res);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import openRunFile from "./open-run-file";
|
||||
import queryPath from "./query-path";
|
||||
import queryRunAs from "./query-run-as";
|
||||
import requestRunUser from "./request-run-user";
|
||||
import sendJson from "./send-json";
|
||||
|
||||
/**
|
||||
* `GET /api/files/stat?path=`: `{ exists, type, size, mtime_ms }`. With
|
||||
* `run_as_bot_id` (and `run_as_workspace_id`), only inside that worker's
|
||||
* own folders (`openRunFile`).
|
||||
*/
|
||||
export default async function handleFileStat({ req, res }: { req: IncomingMessage; res: ServerResponse }) {
|
||||
const file = queryPath({ req });
|
||||
|
||||
if (!file) return sendJson({ res, status: 400, body: { error: "Give an absolute path." } });
|
||||
|
||||
const run_user = await requestRunUser({ res, run_as: queryRunAs({ req }) });
|
||||
|
||||
if (run_user === undefined) return;
|
||||
|
||||
const handle = await openRunFile({ file, run_user });
|
||||
const info = await handle?.stat().catch(() => null);
|
||||
|
||||
await handle?.close().catch(() => {});
|
||||
|
||||
if (!info) return sendJson({ res, body: { exists: false } });
|
||||
|
||||
sendJson({
|
||||
res,
|
||||
body: {
|
||||
exists: true,
|
||||
type: info.isFile() ? "file" : info.isDirectory() ? "directory" : "other",
|
||||
size: info.size,
|
||||
mtime_ms: Math.round(info.mtimeMs),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { chown, mkdir, rename, writeFile } from "node:fs/promises";
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import path from "node:path";
|
||||
import { AgentConfig } from "./config";
|
||||
import readJsonBody from "./read-json-body";
|
||||
import requestRunUser from "./request-run-user";
|
||||
import sendJson from "./send-json";
|
||||
import writeFileAs from "./write-file-as";
|
||||
|
||||
/**
|
||||
* `POST /api/files/write` `{ path, content, encoding?: "utf8" | "base64",
|
||||
* mode?, run_as? }`: writes a whole file (through a temporary one, then
|
||||
* renamed), creating its folders, all owned by the computer's user, or
|
||||
* with `run_as: { bot_id, workspace_id? }` written by that worker bot's
|
||||
* own account (`writeFileAs`). `mode` is the file's permission bits as a
|
||||
* number (e.g. 384 for 0600).
|
||||
*/
|
||||
export default async function handleFileWrite({ req, res }: { req: IncomingMessage; res: ServerResponse }) {
|
||||
const body = await readJsonBody({ req, max_bytes: 64 * 1024 * 1024 });
|
||||
const file = typeof body?.path == "string" && body.path.startsWith("/") && !body.path.includes("\0")
|
||||
? path.posix.normalize(body.path)
|
||||
: null;
|
||||
|
||||
if (!file) return sendJson({ res, status: 400, body: { error: "Give an absolute path." } });
|
||||
if (typeof body.content != "string") return sendJson({ res, status: 400, body: { error: "Give the content." } });
|
||||
|
||||
const bytes = Buffer.from(body.content, body.encoding == "base64" ? "base64" : "utf8");
|
||||
const mode = Number.isInteger(body.mode) ? Number(body.mode) & 0o777 : 0o644;
|
||||
|
||||
const run_user = await requestRunUser({ res, run_as: body.run_as });
|
||||
|
||||
if (run_user === undefined) return;
|
||||
|
||||
if (run_user) {
|
||||
try {
|
||||
await writeFileAs({ run_user, file, bytes, mode });
|
||||
} catch (error: any) {
|
||||
return sendJson({ res, status: 403, body: { error: String(error?.message || error) } });
|
||||
}
|
||||
|
||||
return sendJson({ res, body: { ok: true, size: bytes.length } });
|
||||
}
|
||||
|
||||
await makeOwnedDirs({ dir: path.posix.dirname(file) });
|
||||
|
||||
const temp = `${file}.cobble-${process.pid}-${Date.now()}`;
|
||||
|
||||
await writeFile(temp, bytes, { mode });
|
||||
await chown(temp, AgentConfig.Uid, AgentConfig.Gid);
|
||||
await rename(temp, file);
|
||||
|
||||
sendJson({ res, body: { ok: true, size: bytes.length } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a folder and its missing parents, each new one owned by the
|
||||
* computer's user.
|
||||
*/
|
||||
async function makeOwnedDirs({ dir }: { dir: string }) {
|
||||
const created = await mkdir(dir, { recursive: true });
|
||||
|
||||
if (!created) return;
|
||||
|
||||
let current = dir;
|
||||
|
||||
while (current.length >= created.length) {
|
||||
await chown(current, AgentConfig.Uid, AgentConfig.Gid).catch(() => {});
|
||||
current = path.posix.dirname(current);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import isAuthorized from "./is-authorized";
|
||||
|
||||
describe("isAuthorized", () => {
|
||||
test("lets everything in without a token", () => {
|
||||
expect(isAuthorized({ headers: {}, token: "" })).toBe(true);
|
||||
});
|
||||
|
||||
test("needs the exact bearer token", () => {
|
||||
expect(isAuthorized({ headers: { authorization: "Bearer abc" }, token: "abc" })).toBe(true);
|
||||
expect(isAuthorized({ headers: { authorization: "Bearer abd" }, token: "abc" })).toBe(false);
|
||||
expect(isAuthorized({ headers: { authorization: "Bearer ab" }, token: "abc" })).toBe(false);
|
||||
expect(isAuthorized({ headers: {}, token: "abc" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import type { IncomingHttpHeaders } from "node:http";
|
||||
|
||||
/**
|
||||
* Whether a request carries the computer's token (`Authorization: Bearer
|
||||
* <token>`), compared in constant time. Everything passes when no token is
|
||||
* set.
|
||||
*/
|
||||
export default function isAuthorized({ headers, token }: { headers: IncomingHttpHeaders; token: string }) {
|
||||
if (!token) return true;
|
||||
|
||||
const given = String(headers.authorization || "").replace(/^Bearer\s+/i, "");
|
||||
const a = Buffer.from(given);
|
||||
const b = Buffer.from(token);
|
||||
|
||||
return a.length == b.length && timingSafeEqual(a, b);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
type Params = {
|
||||
url: string;
|
||||
timeout_ms?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether something answers `url` with a status below 500.
|
||||
*/
|
||||
export default async function isPortAnswering({ url, timeout_ms = 2000 }: Params) {
|
||||
try {
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(timeout_ms) });
|
||||
|
||||
await res.body?.cancel().catch(() => {});
|
||||
|
||||
return res.status < 500;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* One line on the agent's output (the container's log).
|
||||
*/
|
||||
export default function log({ name, message }: { name: string; message: string }) {
|
||||
process.stdout.write(`[${new Date().toISOString()}] [${name}] ${message}\n`);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { AgentConfig } from "./config";
|
||||
import createAgentServer from "./create-agent-server";
|
||||
import createBrowserParking from "./create-browser-parking";
|
||||
import guardServicePorts from "./guard-service-ports";
|
||||
import log from "./log";
|
||||
import prepareRunDirs from "./prepare-run-dirs";
|
||||
import startServices from "./start-services";
|
||||
import type { Supervised } from "./supervise-process";
|
||||
import writeXAuthority from "./write-x-authority";
|
||||
|
||||
/**
|
||||
* The computer's agent, its container's main process (under tini): starts
|
||||
* the browser and what it needs, and serves the app on one port. Worker
|
||||
* bots' accounts are kept off its services (`guardServicePorts`) and the
|
||||
* screen asks for gem's cookie (`writeXAuthority`). On TERM
|
||||
* (docker stop) it stops them in order, so Chrome saves its profile.
|
||||
*/
|
||||
async function main() {
|
||||
prepareRunDirs();
|
||||
writeXAuthority();
|
||||
guardServicePorts();
|
||||
|
||||
let services: Supervised[] = [];
|
||||
let stopping = false;
|
||||
|
||||
const stop = async () => {
|
||||
if (stopping) return;
|
||||
|
||||
stopping = true;
|
||||
log({ name: "agent", message: "stopping" });
|
||||
|
||||
for (const service of services) await service.stop({ grace_ms: AgentConfig.StopGraceMs });
|
||||
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
process.on("SIGTERM", stop);
|
||||
process.on("SIGINT", stop);
|
||||
|
||||
const parking = createBrowserParking({ cdp_port: AgentConfig.CdpPort, park_after_ms: AgentConfig.BrowserParkAfterMs });
|
||||
|
||||
createAgentServer({ parking }).listen(AgentConfig.Port, "0.0.0.0", () => {
|
||||
log({ name: "agent", message: `listening on ${AgentConfig.Port}${AgentConfig.Token ? "" : " (no token set: open to anyone who reaches it)"}` });
|
||||
});
|
||||
|
||||
services = await startServices({ parking });
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
log({ name: "agent", message: `couldn't start: ${error?.stack || error}` });
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import mergeFeatureFlags from "./merge-feature-flags";
|
||||
|
||||
describe("mergeFeatureFlags", () => {
|
||||
test("folds every --disable-features into one, at the first one's place", () => {
|
||||
expect(
|
||||
mergeFeatureFlags({
|
||||
args: ["--a", "--disable-features=Translate,MediaRouter", "--b", "--disable-features=MediaRouter,Foo"],
|
||||
}),
|
||||
).toEqual(["--a", "--disable-features=Translate,MediaRouter,Foo", "--b"]);
|
||||
});
|
||||
|
||||
test("keeps --enable-features apart from --disable-features", () => {
|
||||
expect(mergeFeatureFlags({ args: ["--enable-features=A", "--disable-features=B", "--enable-features=C"] })).toEqual([
|
||||
"--enable-features=A,C",
|
||||
"--disable-features=B",
|
||||
]);
|
||||
});
|
||||
|
||||
test("leaves other flags alone and drops an empty list", () => {
|
||||
expect(mergeFeatureFlags({ args: ["--mute-audio", "--disable-features="] })).toEqual(["--mute-audio"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* The flags whose values Chrome reads only once: a second
|
||||
* `--disable-features=` replaces the first, so the agent's own list and the
|
||||
* user's extra flags would drop each other.
|
||||
*/
|
||||
const FeatureFlags = ["--disable-features", "--enable-features"];
|
||||
|
||||
/**
|
||||
* Chrome's flags with every `--disable-features=` (and `--enable-features=`)
|
||||
* folded into one flag, at the first one's place, each feature kept once in
|
||||
* the order given.
|
||||
*/
|
||||
export default function mergeFeatureFlags({ args }: { args: string[] }) {
|
||||
const features = new Map<string, string[]>();
|
||||
const merged: string[] = [];
|
||||
|
||||
for (const arg of args) {
|
||||
const flag = FeatureFlags.find((name) => arg.startsWith(`${name}=`));
|
||||
|
||||
if (!flag) {
|
||||
merged.push(arg);
|
||||
continue;
|
||||
}
|
||||
|
||||
const values = arg
|
||||
.slice(flag.length + 1)
|
||||
.split(",")
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
if (!features.has(flag)) {
|
||||
features.set(flag, []);
|
||||
merged.push(flag);
|
||||
}
|
||||
|
||||
const list = features.get(flag)!;
|
||||
|
||||
for (const value of values) if (!list.includes(value)) list.push(value);
|
||||
}
|
||||
|
||||
return merged
|
||||
.map((arg) => (features.has(arg) ? `${arg}=${features.get(arg)!.join(",")}` : arg))
|
||||
.filter((arg) => !FeatureFlags.some((flag) => arg == `${flag}=`));
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { request } from "node:http";
|
||||
import type { Duplex } from "node:stream";
|
||||
import encodeWebsocketFrame from "./encode-websocket-frame";
|
||||
import readWebsocketFrames from "./read-websocket-frames";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Chrome's DevTools port, on loopback.
|
||||
*/
|
||||
port: number;
|
||||
/**
|
||||
* How long connecting, and each command, may take.
|
||||
*/
|
||||
timeout_ms: number;
|
||||
};
|
||||
|
||||
export type CdpConnection = {
|
||||
/**
|
||||
* Runs one DevTools command (on a page's session when `session_id` is
|
||||
* given) and resolves with its result; rejects with Chrome's error.
|
||||
*/
|
||||
send: (params: { method: string; params?: Record<string, unknown>; session_id?: string }) => Promise<any>;
|
||||
close: () => void;
|
||||
};
|
||||
|
||||
type Pending = {
|
||||
resolve: (result: any) => void;
|
||||
reject: (error: Error) => void;
|
||||
timer: NodeJS.Timeout;
|
||||
};
|
||||
|
||||
/**
|
||||
* The agent's own DevTools client: one websocket to the browser's
|
||||
* endpoint (`/json/version`), commands matched to their answers by id,
|
||||
* events ignored. The image's Node has no WebSocket of its own, so the
|
||||
* frames are the agent's (masked, as a client's must be).
|
||||
*/
|
||||
export default async function openCdpConnection({ port, timeout_ms }: Params): Promise<CdpConnection> {
|
||||
const version = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(timeout_ms) });
|
||||
const { webSocketDebuggerUrl } = (await version.json()) as { webSocketDebuggerUrl?: string };
|
||||
|
||||
if (!webSocketDebuggerUrl) throw new Error("The browser named no DevTools endpoint.");
|
||||
|
||||
const socket = await upgrade({ url: webSocketDebuggerUrl, timeout_ms });
|
||||
const pending = new Map<number, Pending>();
|
||||
let next_id = 0;
|
||||
let closed = false;
|
||||
let fragments: Buffer[] = [];
|
||||
|
||||
const close = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
|
||||
for (const { reject, timer } of pending.values()) {
|
||||
clearTimeout(timer);
|
||||
reject(new Error("The DevTools connection closed."));
|
||||
}
|
||||
|
||||
pending.clear();
|
||||
socket.destroy();
|
||||
};
|
||||
|
||||
const write = ({ opcode, payload }: { opcode: number; payload: Buffer }) => {
|
||||
socket.write(encodeWebsocketFrame({ opcode, payload, mask: randomBytes(4) }));
|
||||
};
|
||||
|
||||
const onMessage = (text: string) => {
|
||||
let message: { id?: number; result?: unknown; error?: { message?: string } };
|
||||
|
||||
try {
|
||||
message = JSON.parse(text);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const waiting = message.id == undefined ? undefined : pending.get(message.id);
|
||||
|
||||
if (!waiting) return;
|
||||
|
||||
pending.delete(message.id!);
|
||||
clearTimeout(waiting.timer);
|
||||
|
||||
if (message.error) waiting.reject(new Error(message.error.message || "DevTools refused the command."));
|
||||
else waiting.resolve(message.result);
|
||||
};
|
||||
|
||||
const feed = readWebsocketFrames({
|
||||
from: "server",
|
||||
max_payload: 64 * 1024 * 1024,
|
||||
onFrame: ({ fin, opcode, payload }) => {
|
||||
if (opcode == 0x1 || opcode == 0x0) {
|
||||
fragments.push(payload);
|
||||
|
||||
if (!fin) return;
|
||||
|
||||
const whole = Buffer.concat(fragments);
|
||||
|
||||
fragments = [];
|
||||
onMessage(whole.toString("utf8"));
|
||||
} else if (opcode == 0x8) {
|
||||
close();
|
||||
} else if (opcode == 0x9) {
|
||||
write({ opcode: 0xa, payload });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
socket.on("data", (chunk: Buffer) => {
|
||||
try {
|
||||
feed(chunk);
|
||||
} catch {
|
||||
close();
|
||||
}
|
||||
});
|
||||
socket.on("error", close);
|
||||
socket.on("close", close);
|
||||
|
||||
return {
|
||||
close,
|
||||
send: ({ method, params = {}, session_id }) => {
|
||||
if (closed) return Promise.reject(new Error("The DevTools connection closed."));
|
||||
|
||||
const id = ++next_id;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
reject(new Error(`${method} took too long.`));
|
||||
}, timeout_ms);
|
||||
|
||||
pending.set(id, { resolve, reject, timer });
|
||||
write({
|
||||
opcode: 0x1,
|
||||
payload: Buffer.from(JSON.stringify({ id, method, params, ...(session_id ? { sessionId: session_id } : {}) })),
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The websocket handshake to a `ws://` URL on loopback, resolving with
|
||||
* the upgraded socket.
|
||||
*/
|
||||
function upgrade({ url, timeout_ms }: { url: string; timeout_ms: number }) {
|
||||
const target = new URL(url);
|
||||
|
||||
return new Promise<Duplex>((resolve, reject) => {
|
||||
const req = request({
|
||||
host: target.hostname,
|
||||
port: target.port,
|
||||
path: target.pathname,
|
||||
headers: {
|
||||
Connection: "Upgrade",
|
||||
Upgrade: "websocket",
|
||||
"Sec-WebSocket-Version": "13",
|
||||
"Sec-WebSocket-Key": randomBytes(16).toString("base64"),
|
||||
},
|
||||
timeout: timeout_ms,
|
||||
});
|
||||
|
||||
req.on("upgrade", (_res, socket, head) => {
|
||||
if (head.length) socket.unshift(head);
|
||||
resolve(socket);
|
||||
});
|
||||
req.on("response", (res) => {
|
||||
res.resume();
|
||||
reject(new Error(`DevTools answered ${res.statusCode} instead of a websocket.`));
|
||||
});
|
||||
req.on("timeout", () => req.destroy(new Error("DevTools didn't answer.")));
|
||||
req.on("error", reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { constants } from "node:fs";
|
||||
import { open, readlink } from "node:fs/promises";
|
||||
import type { RunUser } from "./run-user-for";
|
||||
|
||||
/**
|
||||
* Opens a file (or folder) for reading. For a worker it must turn out to
|
||||
* be inside the worker's own folders once open (its real path, read from
|
||||
* the open descriptor, so a link swapped in meanwhile changes nothing):
|
||||
* the agent reads as root, and a worker's link in its folder could point
|
||||
* anywhere. Returns null when there's nothing there or it's outside.
|
||||
*/
|
||||
export default async function openRunFile({ file, run_user }: { file: string; run_user: RunUser | null }) {
|
||||
/**
|
||||
* Never waits: a pipe someone left there would hold the open forever.
|
||||
*/
|
||||
const handle = await open(file, constants.O_RDONLY | constants.O_NONBLOCK).catch(() => null);
|
||||
|
||||
if (!handle || !run_user) return handle;
|
||||
|
||||
const real = await readlink(`/proc/self/fd/${handle.fd}`).catch(() => "");
|
||||
const roots = [run_user.bot_dir, run_user.home, ...(run_user.workspace ? [run_user.workspace.dir] : [])];
|
||||
|
||||
if (roots.some((root) => real == root || real.startsWith(`${root}/`))) return handle;
|
||||
|
||||
await handle.close().catch(() => {});
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Chrome's own pages (New Tab, settings, error pages, blank tabs) draw
|
||||
* next to nothing when they sit still; only sites are worth parking.
|
||||
*/
|
||||
const ChromePagePattern = /^(about|chrome|chrome-untrusted|chrome-error|devtools):/i;
|
||||
|
||||
/**
|
||||
* Whether a tab on show costs anything to keep drawing: a site does (its
|
||||
* animations, video and ads run at full rate while it's in front),
|
||||
* Chrome's own pages don't.
|
||||
*/
|
||||
export default function pageNeedsParking({ url }: { url: string }) {
|
||||
return !ChromePagePattern.test(url.trim());
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* How long an idle browser waits before its tabs are parked, from a whole
|
||||
* number of seconds (`COBBLE_BROWSER_PARK_AFTER_SECONDS`): 0 turns parking
|
||||
* off, anything unreadable is the default, 3 minutes.
|
||||
*/
|
||||
export default function parkAfterMs({ text }: { text?: string }) {
|
||||
const value = String(text ?? "").trim();
|
||||
|
||||
if (!/^\d+$/.test(value)) return 180_000;
|
||||
|
||||
return Number(value) * 1000;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { CdpConnection } from "./open-cdp-connection";
|
||||
import pageNeedsParking from "./page-needs-parking";
|
||||
|
||||
export type ParkedTab = {
|
||||
/**
|
||||
* The site's tab, sent to the background.
|
||||
*/
|
||||
page_id: string;
|
||||
/**
|
||||
* The blank tab put in front of it.
|
||||
*/
|
||||
blank_id: string;
|
||||
};
|
||||
|
||||
type TargetInfo = { targetId: string; type: string; url: string };
|
||||
|
||||
/**
|
||||
* Sends every site on show to the background, as a person switching tabs
|
||||
* would: a blank tab opens in front of it in its window. A background tab
|
||||
* keeps its connections and logins, but Chrome stops drawing it and slows
|
||||
* its timers, so it costs next to nothing (in front, the virtual screen's
|
||||
* software rendering draws its animations at full rate whether or not
|
||||
* anyone watches). Returns what to bring back.
|
||||
*/
|
||||
export default async function parkBrowserTabs({ cdp }: { cdp: CdpConnection }): Promise<ParkedTab[]> {
|
||||
const { targetInfos } = (await cdp.send({ method: "Target.getTargets" })) as { targetInfos: TargetInfo[] };
|
||||
const parked: ParkedTab[] = [];
|
||||
|
||||
for (const target of targetInfos) {
|
||||
if (target.type != "page" || !pageNeedsParking({ url: target.url })) continue;
|
||||
if (!(await isOnShow({ cdp, target_id: target.targetId }))) continue;
|
||||
|
||||
// In front of its own window: a new tab opens in the window used last.
|
||||
await cdp.send({ method: "Target.activateTarget", params: { targetId: target.targetId } });
|
||||
|
||||
const { targetId } = (await cdp.send({ method: "Target.createTarget", params: { url: "about:blank" } })) as {
|
||||
targetId: string;
|
||||
};
|
||||
|
||||
parked.push({ page_id: target.targetId, blank_id: targetId });
|
||||
}
|
||||
|
||||
return parked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a tab is the one on show in its window (the page itself says,
|
||||
* which also covers a window of its own).
|
||||
*/
|
||||
async function isOnShow({ cdp, target_id }: { cdp: CdpConnection; target_id: string }) {
|
||||
let session_id: string | undefined;
|
||||
|
||||
try {
|
||||
({ sessionId: session_id } = await cdp.send({
|
||||
method: "Target.attachToTarget",
|
||||
params: { targetId: target_id, flatten: true },
|
||||
}));
|
||||
|
||||
const { result } = await cdp.send({
|
||||
method: "Runtime.evaluate",
|
||||
params: { expression: "document.visibilityState", returnByValue: true },
|
||||
session_id,
|
||||
});
|
||||
|
||||
return result?.value == "visible";
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
if (session_id) await cdp.send({ method: "Target.detachFromTarget", params: { sessionId: session_id } }).catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { chmodSync, chownSync, mkdirSync } from "node:fs";
|
||||
import { AgentConfig } from "./config";
|
||||
|
||||
/**
|
||||
* The folders the services need, owned by the computer's user: the run
|
||||
* dir (bus, pid, state), its private runtime dir, the X socket dir, and
|
||||
* the home folders (a fresh mount may arrive owned by root). The
|
||||
* workspace stays open to all, so a worker reaches its own folder in it.
|
||||
*/
|
||||
export default function prepareRunDirs() {
|
||||
const { Uid, Gid } = AgentConfig;
|
||||
|
||||
for (const [dir, mode] of [
|
||||
[AgentConfig.RunDir, 0o755],
|
||||
[`${AgentConfig.RunDir}/xdg`, 0o700],
|
||||
// Workers walk through to the workspace, but can't list gem's home.
|
||||
[AgentConfig.Home, 0o711],
|
||||
[AgentConfig.WorkspaceDir, 0o755],
|
||||
[AgentConfig.ProfileDir, 0o700],
|
||||
[`${AgentConfig.Home}/.cobble`, 0o700],
|
||||
// The browser's downloads, until the app moves them into a run's
|
||||
// folder: no worker reads another's.
|
||||
[`${AgentConfig.Home}/Downloads`, 0o700],
|
||||
] as const) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
chownSync(dir, Uid, Gid);
|
||||
chmodSync(dir, mode);
|
||||
}
|
||||
|
||||
mkdirSync("/tmp/.X11-unix", { recursive: true });
|
||||
chmodSync("/tmp/.X11-unix", 0o1777);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { request, type IncomingMessage, type ServerResponse } from "node:http";
|
||||
import sendJson from "./send-json";
|
||||
|
||||
type Params = {
|
||||
req: IncomingMessage;
|
||||
res: ServerResponse;
|
||||
/**
|
||||
* The loopback port of the service behind this path.
|
||||
*/
|
||||
port: number;
|
||||
/**
|
||||
* Said when it doesn't answer.
|
||||
*/
|
||||
unavailable: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Streams a request to a service on loopback (Playwright MCP, the web
|
||||
* terminal) and its answer back, event streams included, as if it came
|
||||
* from there: their host checks only let loopback hosts in, and the
|
||||
* app's token stays here.
|
||||
*/
|
||||
export default function proxyLoopback({ req, res, port, unavailable }: Params) {
|
||||
const headers = { ...req.headers, host: `127.0.0.1:${port}` };
|
||||
|
||||
delete headers.authorization;
|
||||
delete headers.origin;
|
||||
|
||||
const upstream = request({ host: "127.0.0.1", port, method: req.method, path: req.url, headers }, (answer) => {
|
||||
res.writeHead(answer.statusCode || 502, answer.headers);
|
||||
answer.pipe(res);
|
||||
});
|
||||
|
||||
upstream.on("error", () => {
|
||||
if (!res.headersSent) sendJson({ res, status: 502, body: { error: unavailable } });
|
||||
else res.destroy();
|
||||
});
|
||||
|
||||
res.on("close", () => upstream.destroy());
|
||||
req.pipe(upstream);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* The absolute, normalised `path` a request names in its query, or null.
|
||||
*/
|
||||
export default function queryPath({ req }: { req: IncomingMessage }) {
|
||||
const value = new URL(req.url || "/", "http://agent").searchParams.get("path") || "";
|
||||
|
||||
if (!value.startsWith("/") || value.includes("\0")) return null;
|
||||
|
||||
return path.posix.normalize(value);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { IncomingMessage } from "node:http";
|
||||
|
||||
/**
|
||||
* The worker a GET request acts for (`run_as_bot_id`, `run_as_workspace_id`
|
||||
* in its query), in `requestRunUser`'s shape, or null for gem's own.
|
||||
*/
|
||||
export default function queryRunAs({ req }: { req: IncomingMessage }) {
|
||||
const params = new URL(req.url || "/", "http://agent").searchParams;
|
||||
const bot_id = params.get("run_as_bot_id");
|
||||
|
||||
if (!bot_id) return null;
|
||||
|
||||
return { bot_id, workspace_id: params.get("run_as_workspace_id") || null };
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { IncomingMessage } from "node:http";
|
||||
|
||||
/**
|
||||
* A request's JSON body (at most `max_bytes`), or null when it isn't JSON.
|
||||
*/
|
||||
export default async function readJsonBody({ req, max_bytes }: { req: IncomingMessage; max_bytes: number }): Promise<any> {
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
|
||||
for await (const chunk of req) {
|
||||
size += chunk.length;
|
||||
|
||||
if (size > max_bytes) throw new Error(`The body is over ${max_bytes} bytes.`);
|
||||
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
export type WebsocketFrame = {
|
||||
fin: boolean;
|
||||
opcode: number;
|
||||
payload: Buffer;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
onFrame: (frame: WebsocketFrame) => void;
|
||||
/**
|
||||
* A frame claiming more than this ends the connection.
|
||||
*/
|
||||
max_payload: number;
|
||||
/**
|
||||
* Who sends the frames: a client (a browser, the default) always
|
||||
* masks them, a server (Chrome's DevTools, to the agent's own client)
|
||||
* never does.
|
||||
*/
|
||||
from?: "client" | "server";
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads websocket frames (RFC 6455) from a byte stream fed in any chunks:
|
||||
* returns the function to feed them to, which calls `onFrame` with each
|
||||
* whole frame, unmasked. Throws on a frame masked the wrong way for its
|
||||
* sender, or an oversized one.
|
||||
*/
|
||||
export default function readWebsocketFrames({ onFrame, max_payload, from = "client" }: Params) {
|
||||
let buffer: Buffer = Buffer.alloc(0);
|
||||
|
||||
return (chunk: Buffer) => {
|
||||
buffer = buffer.length ? Buffer.concat([buffer, chunk]) : chunk;
|
||||
|
||||
while (buffer.length >= 2) {
|
||||
const first = buffer[0]!;
|
||||
const second = buffer[1]!;
|
||||
const masked = Boolean(second & 0x80);
|
||||
let length = second & 0x7f;
|
||||
let offset = 2;
|
||||
|
||||
if (from == "client" && !masked) throw new Error("A client frame came unmasked.");
|
||||
if (from == "server" && masked) throw new Error("A server frame came masked.");
|
||||
|
||||
if (length == 126) {
|
||||
if (buffer.length < 4) return;
|
||||
length = buffer.readUInt16BE(2);
|
||||
offset = 4;
|
||||
} else if (length == 127) {
|
||||
if (buffer.length < 10) return;
|
||||
const long = buffer.readBigUInt64BE(2);
|
||||
if (long > BigInt(max_payload)) throw new Error("A frame was too large.");
|
||||
length = Number(long);
|
||||
offset = 10;
|
||||
}
|
||||
|
||||
if (length > max_payload) throw new Error("A frame was too large.");
|
||||
|
||||
const mask_length = masked ? 4 : 0;
|
||||
|
||||
if (buffer.length < offset + mask_length + length) return;
|
||||
|
||||
const payload = Buffer.from(buffer.subarray(offset + mask_length, offset + mask_length + length));
|
||||
|
||||
if (masked) {
|
||||
const mask = buffer.subarray(offset, offset + 4);
|
||||
|
||||
for (let index = 0; index < payload.length; index++) payload[index]! ^= mask[index & 3]!;
|
||||
}
|
||||
|
||||
buffer = buffer.subarray(offset + mask_length + length);
|
||||
onFrame({ fin: Boolean(first & 0x80), opcode: first & 0x0f, payload });
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { ServerResponse } from "node:http";
|
||||
import { AgentState } from "./agent-state";
|
||||
import ensureRunUser from "./ensure-run-user";
|
||||
import runUserFor, { type RunUser } from "./run-user-for";
|
||||
import sendJson from "./send-json";
|
||||
|
||||
/**
|
||||
* The worker account a request asks to act as (`run_as: { bot_id,
|
||||
* workspace_id? }`), set up and ready, or null for gem's own (the
|
||||
* coordinator, the app's own commands). For a bad id, and while worker
|
||||
* accounts can't be kept off the services (`AgentState.workers_guarded`:
|
||||
* acting as one then isn't safe), it answers the request with the error
|
||||
* itself and returns undefined.
|
||||
*/
|
||||
export default async function requestRunUser({ res, run_as }: { res: ServerResponse; run_as: unknown }): Promise<RunUser | null | undefined> {
|
||||
if (run_as == null) return null;
|
||||
|
||||
const refuse = ({ status, message }: { status: number; message: string }) => {
|
||||
sendJson({ res, status, body: { error: message } });
|
||||
return undefined;
|
||||
};
|
||||
|
||||
if (typeof run_as != "object") return refuse({ status: 400, message: "run_as must be { bot_id, workspace_id? }." });
|
||||
|
||||
let run_user: RunUser;
|
||||
|
||||
try {
|
||||
const { bot_id, workspace_id } = run_as as { bot_id?: unknown; workspace_id?: unknown };
|
||||
|
||||
run_user = runUserFor({ bot_id, workspace_id });
|
||||
} catch (error: any) {
|
||||
return refuse({ status: 400, message: String(error?.message || error) });
|
||||
}
|
||||
|
||||
if (!AgentState.workers_guarded) {
|
||||
return refuse({
|
||||
message: `This computer can't keep its bots apart, so it runs nothing for a worker bot: its firewall couldn't be set up (${AgentState.guard_error || "unknown error"}). Rebuild the computer from its settings; its container needs NET_ADMIN.`,
|
||||
status: 503,
|
||||
});
|
||||
}
|
||||
|
||||
await ensureRunUser({ run_user });
|
||||
|
||||
return run_user;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import runCommand from "./run-command";
|
||||
|
||||
const base = {
|
||||
cwd: "/tmp",
|
||||
env: { PATH: process.env.PATH },
|
||||
timeout_seconds: 10,
|
||||
max_output_bytes: 1024,
|
||||
};
|
||||
|
||||
describe("runCommand", () => {
|
||||
test("returns output in order and the exit code", async () => {
|
||||
const result = await runCommand({ ...base, command: "echo one; echo two >&2; exit 3" });
|
||||
|
||||
expect(result.output).toBe("one\ntwo\n");
|
||||
expect(result.exit_code).toBe(3);
|
||||
expect(result.timed_out).toBe(false);
|
||||
});
|
||||
|
||||
test("reads no input", async () => {
|
||||
const result = await runCommand({ ...base, command: "read -r line; echo \"got:$line:$?\"" });
|
||||
|
||||
expect(result.output).toBe("got::1\n");
|
||||
});
|
||||
|
||||
test("stops a command past its timeout, with its children", async () => {
|
||||
const started = Date.now();
|
||||
const result = await runCommand({ ...base, timeout_seconds: 1, command: "sleep 30 & sleep 30" });
|
||||
|
||||
expect(result.timed_out).toBe(true);
|
||||
expect(result.exit_code).toBe(124);
|
||||
expect(Date.now() - started).toBeLessThan(5000);
|
||||
});
|
||||
|
||||
test("doesn't wait for background work", async () => {
|
||||
const started = Date.now();
|
||||
const result = await runCommand({ ...base, command: "sleep 5 & echo started" });
|
||||
|
||||
expect(result.output).toBe("started\n");
|
||||
expect(Date.now() - started).toBeLessThan(2000);
|
||||
});
|
||||
|
||||
test("cuts long output", async () => {
|
||||
const result = await runCommand({ ...base, max_output_bytes: 10, command: "printf '%050d' 0" });
|
||||
|
||||
expect(result.output.length).toBe(10);
|
||||
expect(result.truncated).toBe(true);
|
||||
});
|
||||
|
||||
test("is killed when aborted", async () => {
|
||||
const controller = new AbortController();
|
||||
|
||||
setTimeout(() => controller.abort(), 200);
|
||||
|
||||
const started = Date.now();
|
||||
const result = await runCommand({ ...base, signal: controller.signal, command: "sleep 30" });
|
||||
|
||||
expect(result.exit_code).not.toBe(0);
|
||||
expect(Date.now() - started).toBeLessThan(3000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import commandArgv from "./command-argv";
|
||||
import { killGroup } from "./supervise-process";
|
||||
|
||||
type Params = {
|
||||
command: string;
|
||||
cwd: string;
|
||||
env: NodeJS.ProcessEnv;
|
||||
uid?: number;
|
||||
gid?: number;
|
||||
/**
|
||||
* Another account to run it as, with its groups (a worker's): `uid`
|
||||
* and `gid` are then left out.
|
||||
*/
|
||||
as?: { uid: number; gid: number };
|
||||
timeout_seconds: number;
|
||||
max_output_bytes: number;
|
||||
/**
|
||||
* Aborting (the caller went away, the run was stopped) kills it.
|
||||
*/
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
export type CommandResult = {
|
||||
output: string;
|
||||
exit_code: number | null;
|
||||
timed_out: boolean;
|
||||
truncated: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs one command in its own `bash -c`, in its own process group, with
|
||||
* no input (a prompt fails at once instead of waiting). stdout and stderr
|
||||
* come back together, in order, cut at `max_output_bytes`. Past its
|
||||
* timeout, or when aborted, the whole group gets TERM, then KILL 5s later.
|
||||
* It resolves when bash exits, not when every pipe closes, so work left in
|
||||
* the background (`nohup ... &`) keeps running without holding the call.
|
||||
*/
|
||||
export default function runCommand({
|
||||
command,
|
||||
cwd,
|
||||
env,
|
||||
uid,
|
||||
gid,
|
||||
as,
|
||||
timeout_seconds,
|
||||
max_output_bytes,
|
||||
signal,
|
||||
}: Params): Promise<CommandResult> {
|
||||
return new Promise((resolve) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
let truncated = false;
|
||||
let timed_out = false;
|
||||
let settled = false;
|
||||
|
||||
const argv = commandArgv({ command, as });
|
||||
const child = spawn(argv.file, argv.args, {
|
||||
cwd,
|
||||
env,
|
||||
...(as ? {} : { uid, gid }),
|
||||
detached: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
const keep = (chunk: Buffer) => {
|
||||
if (size >= max_output_bytes) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const room = max_output_bytes - size;
|
||||
|
||||
if (chunk.length > room) truncated = true;
|
||||
|
||||
const part = chunk.length > room ? chunk.subarray(0, room) : chunk;
|
||||
|
||||
chunks.push(part);
|
||||
size += part.length;
|
||||
};
|
||||
|
||||
child.stdout?.on("data", keep);
|
||||
child.stderr?.on("data", keep);
|
||||
|
||||
let kill_timer: NodeJS.Timeout | undefined;
|
||||
|
||||
const stop = () => {
|
||||
if (!child.pid || child.exitCode != null) return;
|
||||
|
||||
killGroup({ pid: child.pid, signal: "SIGTERM" });
|
||||
kill_timer = setTimeout(() => child.pid && killGroup({ pid: child.pid, signal: "SIGKILL" }), 5000);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
timed_out = true;
|
||||
stop();
|
||||
}, timeout_seconds * 1000);
|
||||
|
||||
const onAbort = () => stop();
|
||||
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
|
||||
const finish = (exit_code: number | null) => {
|
||||
if (settled) return;
|
||||
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
clearTimeout(kill_timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
|
||||
/**
|
||||
* A moment for what's still in the pipes, then let go of them:
|
||||
* a background job may hold them open for hours.
|
||||
*/
|
||||
setTimeout(() => {
|
||||
child.stdout?.destroy();
|
||||
child.stderr?.destroy();
|
||||
resolve({
|
||||
output: Buffer.concat(chunks).toString("utf8"),
|
||||
exit_code: timed_out ? 124 : exit_code,
|
||||
timed_out,
|
||||
truncated,
|
||||
});
|
||||
}, 50);
|
||||
};
|
||||
|
||||
child.on("error", (error) => {
|
||||
keep(Buffer.from(`${error.message}\n`));
|
||||
finish(127);
|
||||
});
|
||||
|
||||
child.on("exit", (code, exit_signal) => finish(code ?? (exit_signal ? 128 + signalNumber({ signal: exit_signal }) : null)));
|
||||
});
|
||||
}
|
||||
|
||||
function signalNumber({ signal }: { signal: NodeJS.Signals }) {
|
||||
return ({ SIGHUP: 1, SIGINT: 2, SIGKILL: 9, SIGTERM: 15 } as Record<string, number>)[signal] || 0;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import runUserFor from "./run-user-for";
|
||||
|
||||
describe("runUserFor", () => {
|
||||
test("names a worker's account from its bot id", () => {
|
||||
expect(runUserFor({ bot_id: 7 })).toEqual({
|
||||
name: "cb-7",
|
||||
uid: 100_007,
|
||||
gid: 100_007,
|
||||
home: "/home/cb-7",
|
||||
kept_dir: "/home/cb-7/workspace",
|
||||
bot_dir: "/home/gem/workspace/bots/7",
|
||||
workspace: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("adds the workspace's group", () => {
|
||||
expect(runUserFor({ bot_id: "3", workspace_id: "12" }).workspace).toEqual({
|
||||
name: "cw-12",
|
||||
gid: 10_000_012,
|
||||
dir: "/home/gem/workspace/workspaces/12",
|
||||
link: "/home/gem/workspace/bots/3/workspaces/12",
|
||||
});
|
||||
});
|
||||
|
||||
test("no workspace for 0, null or an empty id", () => {
|
||||
for (const workspace_id of [0, null, undefined, ""]) expect(runUserFor({ bot_id: 1, workspace_id }).workspace).toBeNull();
|
||||
});
|
||||
|
||||
test("refuses ids that aren't whole numbers in range", () => {
|
||||
for (const bot_id of [0, -1, 1.5, "1; rm -rf /", "../2", 9_000_001, null, undefined, "", "0x10"]) {
|
||||
expect(() => runUserFor({ bot_id })).toThrow();
|
||||
}
|
||||
|
||||
expect(() => runUserFor({ bot_id: 1, workspace_id: "x" })).toThrow();
|
||||
expect(() => runUserFor({ bot_id: 1, workspace_id: 9_000_001 })).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import path from "node:path";
|
||||
import { AgentConfig } from "./config";
|
||||
|
||||
export type RunUser = {
|
||||
name: string;
|
||||
uid: number;
|
||||
gid: number;
|
||||
/**
|
||||
* Its home, in the container (the env files live there).
|
||||
*/
|
||||
home: string;
|
||||
/**
|
||||
* `workspace` in its home: a link to `bot_dir`, the only part of its
|
||||
* home that's kept. The app names every worker path through it.
|
||||
*/
|
||||
kept_dir: string;
|
||||
/**
|
||||
* The bot's folder in the workspace, owned by the account.
|
||||
*/
|
||||
bot_dir: string;
|
||||
/**
|
||||
* The workspace the run is in: its shared folder belongs to this group,
|
||||
* which the account joins, and `link` (`workspaces/<id>` in the bot's
|
||||
* folder) leads to it.
|
||||
*/
|
||||
workspace: { name: string; gid: number; dir: string; link: string } | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The account a worker bot's commands run as on this computer
|
||||
* (`cb-<bot id>`, no sudo) and, in a workspace, the group its bots share
|
||||
* (`cw-<id>`). Keep alike the app's `computerWorkerAccount` and
|
||||
* `computerRunDirs`. Throws for an id that isn't a whole number in range.
|
||||
*/
|
||||
export default function runUserFor({ bot_id, workspace_id }: { bot_id: unknown; workspace_id?: unknown }): RunUser {
|
||||
const bot = runId({ value: bot_id });
|
||||
|
||||
if (!bot) throw new Error("Give the bot's id.");
|
||||
|
||||
const workspace = workspace_id == null || workspace_id === "" || Number(workspace_id) == 0 ? null : runId({ value: workspace_id });
|
||||
|
||||
if (workspace_id != null && workspace_id !== "" && Number(workspace_id) != 0 && !workspace) {
|
||||
throw new Error("That workspace id isn't valid.");
|
||||
}
|
||||
|
||||
const id = AgentConfig.WorkerIdBase + bot;
|
||||
const name = `cb-${bot}`;
|
||||
const home = `/home/${name}`;
|
||||
const bot_dir = path.posix.join(AgentConfig.WorkspaceDir, "bots", String(bot));
|
||||
|
||||
return {
|
||||
name,
|
||||
uid: id,
|
||||
gid: id,
|
||||
home,
|
||||
kept_dir: path.posix.join(home, "workspace"),
|
||||
bot_dir,
|
||||
workspace: workspace
|
||||
? {
|
||||
name: `cw-${workspace}`,
|
||||
gid: AgentConfig.WorkspaceGroupBase + workspace,
|
||||
dir: path.posix.join(AgentConfig.WorkspaceDir, "workspaces", String(workspace)),
|
||||
link: path.posix.join(bot_dir, "workspaces", String(workspace)),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function runId({ value }: { value: unknown }) {
|
||||
const id = typeof value == "number" ? value : typeof value == "string" && /^\d+$/.test(value) ? Number(value) : NaN;
|
||||
|
||||
return Number.isSafeInteger(id) && id > 0 && id <= AgentConfig.MaxRunId ? id : null;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { BrowserBlockedArgs, McpBlockedArgs } from "./blocked-args";
|
||||
import safeExtraArgs from "./safe-extra-args";
|
||||
|
||||
describe("safeExtraArgs", () => {
|
||||
test("keeps ordinary flags", () => {
|
||||
expect(safeExtraArgs({ text: " --force-dark-mode --window-name=x ", blocked: BrowserBlockedArgs })).toEqual([
|
||||
"--force-dark-mode",
|
||||
"--window-name=x",
|
||||
]);
|
||||
});
|
||||
|
||||
test("drops flags that would open DevTools or move the profile", () => {
|
||||
expect(
|
||||
safeExtraArgs({
|
||||
text: "--remote-debugging-address=0.0.0.0 --REMOTE-DEBUGGING-PORT=1 --user-data-dir=/tmp --mute-audio",
|
||||
blocked: BrowserBlockedArgs,
|
||||
}),
|
||||
).toEqual(["--mute-audio"]);
|
||||
});
|
||||
|
||||
test("keeps Playwright MCP on loopback and this browser", () => {
|
||||
expect(safeExtraArgs({ text: "--host=0.0.0.0 --port 9 --caps vision --cdp-endpoint=x", blocked: McpBlockedArgs })).toEqual(["--caps", "vision"]);
|
||||
});
|
||||
|
||||
test("nothing set is nothing", () => {
|
||||
expect(safeExtraArgs({ text: undefined, blocked: McpBlockedArgs })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
type Params = {
|
||||
/**
|
||||
* Space separated flags, as set (no quoting).
|
||||
*/
|
||||
text?: string;
|
||||
blocked: readonly string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Extra flags from the computer's settings, without the blocked ones,
|
||||
* whatever case they're in: `--name=value`, or `--name` and the value
|
||||
* after it (a word not starting with `-`).
|
||||
*/
|
||||
export default function safeExtraArgs({ text, blocked }: Params) {
|
||||
const words = String(text || "")
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
const kept: string[] = [];
|
||||
|
||||
for (let index = 0; index < words.length; index++) {
|
||||
const word = words[index]!;
|
||||
const [name, value] = [word.split("=")[0]!.toLowerCase(), word.includes("=")];
|
||||
|
||||
if (!blocked.includes(name)) {
|
||||
kept.push(word);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!value && words[index + 1] && !words[index + 1]!.startsWith("-")) index++;
|
||||
}
|
||||
|
||||
return kept;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* A screen size from `WIDTHxHEIGHT`, else 1920x1080 (the most common
|
||||
* desktop, so the browser's screen gives nothing away).
|
||||
*/
|
||||
export default function screenSize({ text }: { text?: string }) {
|
||||
const match = String(text || "").match(/^(\d{3,5})x(\d{3,5})$/);
|
||||
|
||||
return match ? { width: Number(match[1]), height: Number(match[2]) } : { width: 1920, height: 1080 };
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { ServerResponse } from "node:http";
|
||||
|
||||
export default function sendJson({ res, status = 200, body }: { res: ServerResponse; status?: number; body: unknown }) {
|
||||
const text = JSON.stringify(body);
|
||||
|
||||
res.writeHead(status, {
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
"content-length": Buffer.byteLength(text),
|
||||
"cache-control": "no-store",
|
||||
});
|
||||
res.end(text);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import type { ServerResponse } from "node:http";
|
||||
import path from "node:path";
|
||||
|
||||
const Types: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".json": "application/json; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
".png": "image/png",
|
||||
".ico": "image/x-icon",
|
||||
".oga": "audio/ogg",
|
||||
".mp3": "audio/mpeg",
|
||||
".woff": "font/woff",
|
||||
".ttf": "font/ttf",
|
||||
};
|
||||
|
||||
type Params = {
|
||||
res: ServerResponse;
|
||||
/**
|
||||
* The folder served (noVNC's).
|
||||
*/
|
||||
root: string;
|
||||
/**
|
||||
* The path asked for, below it.
|
||||
*/
|
||||
name: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A file from a folder of the image (noVNC), kept inside it and limited to
|
||||
* the kinds a web page loads; anything else is a 404. Never cached: the
|
||||
* image's version is the only one there is.
|
||||
*/
|
||||
export default async function serveStaticFile({ res, root, name }: Params) {
|
||||
let decoded = "";
|
||||
|
||||
try {
|
||||
decoded = decodeURIComponent(name);
|
||||
} catch {
|
||||
decoded = "";
|
||||
}
|
||||
|
||||
const file = path.resolve(root, `.${path.posix.sep}${decoded}`);
|
||||
const type = Types[path.extname(file).toLowerCase()];
|
||||
const inside = file.startsWith(`${path.resolve(root)}${path.sep}`);
|
||||
const bytes = decoded && type && inside ? await readFile(file).catch(() => null) : null;
|
||||
|
||||
if (!bytes) {
|
||||
res.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(200, {
|
||||
"content-type": type!,
|
||||
"content-length": bytes.length,
|
||||
"cache-control": "no-cache",
|
||||
"x-content-type-options": "nosniff",
|
||||
});
|
||||
res.end(bytes);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
type Params = {
|
||||
now: number;
|
||||
/**
|
||||
* When the browser was last used or watched.
|
||||
*/
|
||||
last_active_at: number;
|
||||
/**
|
||||
* When the open tabs were last parked (or found not worth it), 0 for
|
||||
* never: nothing changed since, so they aren't looked at again.
|
||||
*/
|
||||
checked_at: number;
|
||||
/**
|
||||
* Screen views open now.
|
||||
*/
|
||||
viewers: number;
|
||||
/**
|
||||
* Browser tool calls running now.
|
||||
*/
|
||||
holds: number;
|
||||
/**
|
||||
* Idle this long parks it; 0 never does.
|
||||
*/
|
||||
park_after_ms: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the browser has sat unused and unwatched long enough to park
|
||||
* its tabs, and hasn't been parked since it was last used.
|
||||
*/
|
||||
export default function shouldParkBrowser({ now, last_active_at, checked_at, viewers, holds, park_after_ms }: Params) {
|
||||
if (park_after_ms <= 0 || viewers > 0 || holds > 0) return false;
|
||||
if (checked_at >= last_active_at) return false;
|
||||
|
||||
return now - last_active_at >= park_after_ms;
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { AgentState } from "./agent-state";
|
||||
import browserArgs from "./browser-args";
|
||||
import clearProfileLocks from "./clear-profile-locks";
|
||||
import type { BrowserParking } from "./create-browser-parking";
|
||||
import { AgentConfig } from "./config";
|
||||
import findBrowserBinary from "./find-browser-binary";
|
||||
import isPortAnswering from "./is-port-answering";
|
||||
import log from "./log";
|
||||
import superviseProcess, { type Supervised } from "./supervise-process";
|
||||
import userEnv from "./user-env";
|
||||
import waitUntil from "./wait-until";
|
||||
|
||||
/**
|
||||
* Says the host gives Chrome no sandbox (user namespaces blocked).
|
||||
*/
|
||||
const NoSandboxPattern = /no usable sandbox|setuid sandbox|user namespaces|clone\(\) failed/i;
|
||||
|
||||
/**
|
||||
* Starts and keeps running, as the computer's user: the virtual screen
|
||||
* (Xvnc, an X server that is also a VNC server on loopback, so the screen
|
||||
* view shows Chrome's whole window), the session bus (where the notification watcher meets Chrome),
|
||||
* Chrome, Playwright MCP once Chrome's DevTools port answers, and the web
|
||||
* terminal (ttyd, a login shell in the workspace). Each one comes back
|
||||
* when it exits (a new Chrome tells `parking` its old tabs are gone).
|
||||
* Returns them in the order they stop.
|
||||
*/
|
||||
export default async function startServices({ parking }: { parking: BrowserParking }): Promise<Supervised[]> {
|
||||
const { Uid: uid, Gid: gid, RunDir, Screen } = AgentConfig;
|
||||
const binary = findBrowserBinary();
|
||||
|
||||
AgentState.browser_binary = binary;
|
||||
AgentState.browser_version = readVersion({ binary });
|
||||
AgentState.browser_sandbox = AgentConfig.BrowserSandbox;
|
||||
|
||||
log({ name: "agent", message: `${AgentState.browser_version} at ${binary}` });
|
||||
|
||||
const display = superviseProcess({
|
||||
name: "display",
|
||||
command: "Xvnc",
|
||||
args: () => [
|
||||
AgentConfig.Display,
|
||||
"-geometry",
|
||||
`${Screen.width}x${Screen.height}`,
|
||||
"-depth",
|
||||
"24",
|
||||
"-dpi",
|
||||
"96",
|
||||
"-nolisten",
|
||||
"tcp",
|
||||
// Only what holds gem's cookie reaches the screen, never a
|
||||
// worker bot's account.
|
||||
"-auth",
|
||||
AgentConfig.XAuthority,
|
||||
"-desktop",
|
||||
"Computer",
|
||||
// VNC on loopback only, without a password: the agent's token
|
||||
// guards the one way in (`/desktop/websockify`).
|
||||
"-localhost",
|
||||
"-interface",
|
||||
"127.0.0.1",
|
||||
"-rfbport",
|
||||
String(AgentConfig.VncPort),
|
||||
"-SecurityTypes",
|
||||
"None",
|
||||
"-AlwaysShared",
|
||||
// The screen size is a setting (and what sites see); a viewer
|
||||
// only scales it.
|
||||
"-AcceptSetDesktopSize=0",
|
||||
...(AgentConfig.BrowserLightweight ? ["-FrameRate", String(AgentConfig.LightweightFrameRate)] : []),
|
||||
],
|
||||
env: () => userEnv(),
|
||||
uid,
|
||||
gid,
|
||||
});
|
||||
|
||||
const bus = superviseProcess({
|
||||
name: "bus",
|
||||
command: "dbus-daemon",
|
||||
args: () => ["--session", "--nofork", "--nopidfile", `--address=unix:path=${RunDir}/bus`],
|
||||
env: () => userEnv(),
|
||||
uid,
|
||||
gid,
|
||||
});
|
||||
|
||||
await waitUntil({ check: async () => Boolean(display.pid()), every_ms: 100 });
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
const browser = superviseProcess({
|
||||
name: "browser",
|
||||
command: binary,
|
||||
args: () => {
|
||||
clearProfileLocks({ profile_dir: AgentConfig.ProfileDir });
|
||||
|
||||
return browserArgs({
|
||||
profile_dir: AgentConfig.ProfileDir,
|
||||
cdp_port: AgentConfig.CdpPort,
|
||||
screen: Screen,
|
||||
scale: AgentConfig.Scale,
|
||||
lang: AgentConfig.Lang,
|
||||
accept_lang: AgentConfig.AcceptLang,
|
||||
sandbox: AgentState.browser_sandbox,
|
||||
lightweight: AgentConfig.BrowserLightweight,
|
||||
extra: AgentConfig.BrowserExtraArgs,
|
||||
});
|
||||
},
|
||||
env: () => userEnv(),
|
||||
cwd: AgentConfig.Home,
|
||||
uid,
|
||||
gid,
|
||||
onStart: ({ pid }) => {
|
||||
parking.browserRestarted();
|
||||
writeBrowserState({ pid });
|
||||
},
|
||||
onExit: ({ uptime_ms, tail }) => {
|
||||
if (AgentState.browser_sandbox && uptime_ms < 20_000 && NoSandboxPattern.test(tail)) {
|
||||
AgentState.browser_sandbox = false;
|
||||
log({ name: "browser", message: `the host gives Chrome no sandbox; running it without one. ${tail.slice(-300)}` });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
await waitUntil({
|
||||
check: () => isPortAnswering({ url: `http://127.0.0.1:${AgentConfig.CdpPort}/json/version` }),
|
||||
every_ms: 500,
|
||||
});
|
||||
|
||||
log({ name: "browser", message: `DevTools answers on ${AgentConfig.CdpPort}` });
|
||||
|
||||
const mcp = superviseProcess({
|
||||
name: "mcp",
|
||||
command: process.execPath,
|
||||
args: () => [
|
||||
AgentConfig.McpCli,
|
||||
"--cdp-endpoint",
|
||||
`http://127.0.0.1:${AgentConfig.CdpPort}`,
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
String(AgentConfig.McpPort),
|
||||
"--shared-browser-context",
|
||||
"--ignore-roots",
|
||||
"--allow-unrestricted-file-access",
|
||||
"--codegen",
|
||||
"none",
|
||||
"--no-webmcp",
|
||||
// Snapshots, console logs and downloads it writes to files: the
|
||||
// app moves downloads into the run's folders and points the
|
||||
// model at the tools that read the rest, so the paths are
|
||||
// absolute and the folder is kept small.
|
||||
"--output-dir",
|
||||
AgentConfig.McpOutputDir,
|
||||
"--output-max-size",
|
||||
String(AgentConfig.McpOutputMaxBytes),
|
||||
"--file-paths",
|
||||
"absolute",
|
||||
...AgentConfig.McpExtraArgs,
|
||||
],
|
||||
env: () => userEnv(),
|
||||
cwd: AgentConfig.WorkspaceDir,
|
||||
uid,
|
||||
gid,
|
||||
});
|
||||
|
||||
const terminal = superviseProcess({
|
||||
name: "terminal",
|
||||
command: "ttyd",
|
||||
args: () => [
|
||||
"--interface",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
String(AgentConfig.TerminalPort),
|
||||
"--base-path",
|
||||
"/terminal",
|
||||
"--writable",
|
||||
"--cwd",
|
||||
AgentConfig.WorkspaceDir,
|
||||
"--client-option",
|
||||
"titleFixed=Shell",
|
||||
"--client-option",
|
||||
"disableLeaveAlert=true",
|
||||
"bash",
|
||||
"--login",
|
||||
],
|
||||
env: () => ({ ...userEnv(), TERM: "xterm-256color" }),
|
||||
cwd: AgentConfig.WorkspaceDir,
|
||||
uid,
|
||||
gid,
|
||||
});
|
||||
|
||||
return [terminal, mcp, browser, bus, display];
|
||||
}
|
||||
|
||||
/**
|
||||
* The browser's version line, e.g. `Google Chrome 142.0.7444.59`.
|
||||
*/
|
||||
function readVersion({ binary }: { binary: string }) {
|
||||
try {
|
||||
return execFileSync(binary, ["--version"], { encoding: "utf8", timeout: 10_000 }).trim();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the browser runs and with what, for what runs beside it (the
|
||||
* notification watcher restarts Chrome by its pid, and reads when it
|
||||
* started from the pid file's time).
|
||||
*/
|
||||
function writeBrowserState({ pid }: { pid: number }) {
|
||||
const env = userEnv();
|
||||
|
||||
writeFileSync(`${AgentConfig.RunDir}/browser.pid`, `${pid}\n`, { mode: 0o644 });
|
||||
writeFileSync(
|
||||
`${AgentConfig.RunDir}/browser.json`,
|
||||
`${JSON.stringify({
|
||||
browser: {
|
||||
pid,
|
||||
binary: AgentState.browser_binary,
|
||||
env: {
|
||||
DISPLAY: env.DISPLAY,
|
||||
DBUS_SESSION_BUS_ADDRESS: env.DBUS_SESSION_BUS_ADDRESS,
|
||||
XDG_RUNTIME_DIR: env.XDG_RUNTIME_DIR,
|
||||
},
|
||||
},
|
||||
})}\n`,
|
||||
{ mode: 0o644 },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import log from "./log";
|
||||
|
||||
export type SupervisedExit = {
|
||||
code: number | null;
|
||||
signal: NodeJS.Signals | null;
|
||||
/**
|
||||
* How long it ran.
|
||||
*/
|
||||
uptime_ms: number;
|
||||
/**
|
||||
* The end of what it printed.
|
||||
*/
|
||||
tail: string;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
name: string;
|
||||
command: string;
|
||||
/**
|
||||
* Read again before each start, so a restart can change them.
|
||||
*/
|
||||
args: () => string[];
|
||||
env: () => NodeJS.ProcessEnv;
|
||||
cwd?: string;
|
||||
uid?: number;
|
||||
gid?: number;
|
||||
onStart?: (params: { pid: number }) => void;
|
||||
onExit?: (params: SupervisedExit) => void;
|
||||
};
|
||||
|
||||
export type Supervised = {
|
||||
pid: () => number | undefined;
|
||||
stop: (params: { grace_ms: number }) => Promise<void>;
|
||||
};
|
||||
|
||||
const TailBytes = 4000;
|
||||
|
||||
/**
|
||||
* Runs a long-lived child and starts it again whenever it exits, waiting
|
||||
* longer each time it dies young (0.5s doubling to 10s, back to 0.5s after
|
||||
* it ran for 30s). It runs in its own process group, so a stop reaches
|
||||
* everything it started: TERM, then KILL after `grace_ms`.
|
||||
*/
|
||||
export default function superviseProcess({ name, command, args, env, cwd, uid, gid, onStart, onExit }: Params): Supervised {
|
||||
let child: ChildProcess | undefined;
|
||||
let stopped = false;
|
||||
let delay_ms = 500;
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
|
||||
const start = () => {
|
||||
if (stopped) return;
|
||||
|
||||
const started_at = Date.now();
|
||||
let tail = "";
|
||||
|
||||
const keep = (chunk: Buffer) => {
|
||||
tail = (tail + chunk.toString("utf8")).slice(-TailBytes);
|
||||
};
|
||||
|
||||
child = spawn(command, args(), {
|
||||
cwd,
|
||||
env: env(),
|
||||
uid,
|
||||
gid,
|
||||
detached: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
child.stdout?.on("data", keep);
|
||||
child.stderr?.on("data", keep);
|
||||
|
||||
child.on("error", (error) => {
|
||||
log({ name, message: `couldn't start: ${error.message}` });
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
const uptime_ms = Date.now() - started_at;
|
||||
|
||||
child = undefined;
|
||||
onExit?.({ code, signal, uptime_ms, tail });
|
||||
|
||||
if (stopped) return;
|
||||
|
||||
delay_ms = uptime_ms > 30_000 ? 500 : Math.min(delay_ms * 2, 10_000);
|
||||
log({ name, message: `exited (${signal || code}) after ${Math.round(uptime_ms / 1000)}s; starting again in ${delay_ms}ms` });
|
||||
timer = setTimeout(start, delay_ms);
|
||||
});
|
||||
|
||||
if (child.pid) onStart?.({ pid: child.pid });
|
||||
};
|
||||
|
||||
start();
|
||||
|
||||
return {
|
||||
pid: () => child?.pid,
|
||||
stop: async ({ grace_ms }) => {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
|
||||
const running = child;
|
||||
|
||||
if (!running?.pid) return;
|
||||
|
||||
const exited = new Promise<void>((resolve) => running.once("exit", () => resolve()));
|
||||
|
||||
killGroup({ pid: running.pid, signal: "SIGTERM" });
|
||||
|
||||
const timeout = new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), grace_ms));
|
||||
|
||||
if ((await Promise.race([exited, timeout])) == "timeout") {
|
||||
killGroup({ pid: running.pid, signal: "SIGKILL" });
|
||||
await exited;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Signals a whole process group, ignoring one that's already gone.
|
||||
*/
|
||||
export function killGroup({ pid, signal }: { pid: number; signal: NodeJS.Signals }) {
|
||||
try {
|
||||
process.kill(-pid, signal);
|
||||
} catch {
|
||||
try {
|
||||
process.kill(pid, signal);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { CdpConnection } from "./open-cdp-connection";
|
||||
import type { ParkedTab } from "./park-browser-tabs";
|
||||
|
||||
/**
|
||||
* Puts parked sites back in front and closes the blank tabs that covered
|
||||
* them, last parked first, so the browser is as it was left. A tab that
|
||||
* went away meanwhile is skipped.
|
||||
*/
|
||||
export default async function unparkBrowserTabs({ cdp, parked }: { cdp: CdpConnection; parked: ParkedTab[] }) {
|
||||
for (const { page_id, blank_id } of [...parked].reverse()) {
|
||||
await cdp.send({ method: "Target.activateTarget", params: { targetId: page_id } }).catch(() => {});
|
||||
await cdp.send({ method: "Target.closeTarget", params: { targetId: blank_id } }).catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { AgentConfig } from "./config";
|
||||
|
||||
/**
|
||||
* The environment everything run as the computer's user gets: its own
|
||||
* home and identity, the virtual screen and the session bus, and nothing
|
||||
* of the agent's own (its token never reaches a command).
|
||||
*/
|
||||
export default function userEnv({ extra = {} }: { extra?: NodeJS.ProcessEnv } = {}): NodeJS.ProcessEnv {
|
||||
return {
|
||||
PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
|
||||
HOME: AgentConfig.Home,
|
||||
USER: AgentConfig.User,
|
||||
LOGNAME: AgentConfig.User,
|
||||
SHELL: "/bin/bash",
|
||||
LANG: process.env.LANG || "C.UTF-8",
|
||||
TZ: process.env.TZ || "UTC",
|
||||
DISPLAY: AgentConfig.Display,
|
||||
XAUTHORITY: AgentConfig.XAuthority,
|
||||
XDG_RUNTIME_DIR: `${AgentConfig.RunDir}/xdg`,
|
||||
DBUS_SESSION_BUS_ADDRESS: `unix:path=${AgentConfig.RunDir}/bus`,
|
||||
PIP_BREAK_SYSTEM_PACKAGES: "1",
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Params = {
|
||||
check: () => Promise<boolean>;
|
||||
every_ms: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolves once `check` passes, trying every `every_ms`.
|
||||
*/
|
||||
export default async function waitUntil({ check, every_ms }: Params) {
|
||||
while (!(await check())) {
|
||||
await new Promise((resolve) => setTimeout(resolve, every_ms));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import websocketAccept from "./websocket-accept";
|
||||
|
||||
test("answers the RFC 6455 example key", () => {
|
||||
expect(websocketAccept({ key: "dGhlIHNhbXBsZSBub25jZQ==" })).toBe("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
/**
|
||||
* The GUID RFC 6455 joins to the client's key.
|
||||
*/
|
||||
const WebsocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
|
||||
/**
|
||||
* The `Sec-WebSocket-Accept` answer to a client's `Sec-WebSocket-Key`.
|
||||
*/
|
||||
export default function websocketAccept({ key }: { key: string }) {
|
||||
return createHash("sha1").update(key + WebsocketGuid).digest("base64");
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import encodeWebsocketFrame from "./encode-websocket-frame";
|
||||
import readWebsocketFrames, { type WebsocketFrame } from "./read-websocket-frames";
|
||||
|
||||
/**
|
||||
* A client frame as a browser sends it: masked.
|
||||
*/
|
||||
function clientFrame({ opcode, payload }: { opcode: number; payload: Buffer }) {
|
||||
return encodeWebsocketFrame({ opcode, payload, mask: Buffer.from([1, 2, 3, 4]) });
|
||||
}
|
||||
|
||||
function collect({ from }: { from?: "client" | "server" } = {}) {
|
||||
const frames: WebsocketFrame[] = [];
|
||||
const feed = readWebsocketFrames({ onFrame: (frame) => frames.push(frame), max_payload: 1 << 20, from });
|
||||
|
||||
return { frames, feed };
|
||||
}
|
||||
|
||||
describe("websocket frames", () => {
|
||||
test("reads short, 16-bit and 64-bit lengths, unmasked", () => {
|
||||
const { frames, feed } = collect();
|
||||
|
||||
for (const size of [5, 300, 70_000]) feed(clientFrame({ opcode: 2, payload: Buffer.alloc(size, size % 251) }));
|
||||
|
||||
expect(frames.map((frame) => frame.payload.length)).toEqual([5, 300, 70_000]);
|
||||
expect(frames.every((frame) => frame.fin && frame.opcode == 2)).toBe(true);
|
||||
expect(frames[1]!.payload.every((byte) => byte == 300 % 251)).toBe(true);
|
||||
});
|
||||
|
||||
test("waits for a frame split across chunks, and reads two in one chunk", () => {
|
||||
const { frames, feed } = collect();
|
||||
const one = clientFrame({ opcode: 2, payload: Buffer.from("hello") });
|
||||
const two = clientFrame({ opcode: 9, payload: Buffer.from("ping") });
|
||||
const both = Buffer.concat([one, two]);
|
||||
|
||||
for (let index = 0; index < both.length; index += 3) feed(both.subarray(index, index + 3));
|
||||
|
||||
expect(frames.map((frame) => [frame.opcode, frame.payload.toString()])).toEqual([
|
||||
[2, "hello"],
|
||||
[9, "ping"],
|
||||
]);
|
||||
});
|
||||
|
||||
test("refuses unmasked and oversized frames", () => {
|
||||
const { feed } = collect();
|
||||
|
||||
expect(() => feed(encodeWebsocketFrame({ opcode: 2, payload: Buffer.from("x") }))).toThrow("unmasked");
|
||||
expect(() => collect().feed(clientFrame({ opcode: 2, payload: Buffer.alloc((1 << 20) + 1) }))).toThrow("too large");
|
||||
});
|
||||
|
||||
test("masks a client's frame as RFC 6455 says", () => {
|
||||
const frame = clientFrame({ opcode: 1, payload: Buffer.from("abcd") });
|
||||
|
||||
expect([...frame]).toEqual([0x81, 0x84, 1, 2, 3, 4, 0x61 ^ 1, 0x62 ^ 2, 0x63 ^ 3, 0x64 ^ 4]);
|
||||
});
|
||||
|
||||
test("reads a server's unmasked frames, and refuses masked ones from it", () => {
|
||||
const { frames, feed } = collect({ from: "server" });
|
||||
|
||||
for (const size of [3, 300, 70_000]) feed(encodeWebsocketFrame({ opcode: 1, payload: Buffer.alloc(size, 7) }));
|
||||
|
||||
expect(frames.map((frame) => frame.payload.length)).toEqual([3, 300, 70_000]);
|
||||
expect(() => collect({ from: "server" }).feed(clientFrame({ opcode: 1, payload: Buffer.from("x") }))).toThrow("masked");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { RunUser } from "./run-user-for";
|
||||
|
||||
/**
|
||||
* The environment a worker's commands get: its own home and identity,
|
||||
* and nothing of gem's (no screen, no session bus, no cookie), so it can
|
||||
* reach neither the browser nor gem's services.
|
||||
*/
|
||||
export default function workerEnv({ run_user }: { run_user: RunUser }): NodeJS.ProcessEnv {
|
||||
return {
|
||||
PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
|
||||
HOME: run_user.home,
|
||||
USER: run_user.name,
|
||||
LOGNAME: run_user.name,
|
||||
SHELL: "/bin/bash",
|
||||
LANG: process.env.LANG || "C.UTF-8",
|
||||
TZ: process.env.TZ || "UTC",
|
||||
PIP_BREAK_SYSTEM_PACKAGES: "1",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import commandArgv from "./command-argv";
|
||||
import type { RunUser } from "./run-user-for";
|
||||
import workerEnv from "./worker-env";
|
||||
|
||||
/**
|
||||
* Writes the bytes (read from its input) to a temporary file beside the
|
||||
* target, then renames it over, creating the folders first.
|
||||
*/
|
||||
const WriteScript = `
|
||||
const fs = require("fs"), path = require("path");
|
||||
const [file, mode] = [process.argv[1], parseInt(process.argv[2], 8)];
|
||||
const chunks = [];
|
||||
process.stdin.on("data", (c) => chunks.push(c));
|
||||
process.stdin.on("end", () => {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const temp = file + ".cobble-" + process.pid + "-" + Date.now();
|
||||
fs.writeFileSync(temp, Buffer.concat(chunks), { mode });
|
||||
fs.chmodSync(temp, mode);
|
||||
fs.renameSync(temp, file);
|
||||
});
|
||||
`;
|
||||
|
||||
/**
|
||||
* Writes a whole file as a worker's account, by a process running as it,
|
||||
* so its permissions decide where it may write: never as root, which
|
||||
* would follow a link the worker left in its folder to anywhere.
|
||||
*/
|
||||
export default function writeFileAs({ run_user, file, bytes, mode }: { run_user: RunUser; file: string; bytes: Buffer; mode: number }) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const quoted = (text: string) => `'${text.replaceAll("'", `'\\''`)}'`;
|
||||
const argv = commandArgv({
|
||||
command: `exec ${quoted(process.execPath)} -e ${quoted(WriteScript)} ${quoted(file)} ${mode.toString(8)}`,
|
||||
as: { uid: run_user.uid, gid: run_user.gid },
|
||||
});
|
||||
const child = spawn(argv.file, argv.args, { cwd: "/", env: workerEnv({ run_user }), stdio: ["pipe", "ignore", "pipe"] });
|
||||
const errors: Buffer[] = [];
|
||||
const timer = setTimeout(() => child.kill("SIGKILL"), 60_000);
|
||||
|
||||
child.stderr?.on("data", (chunk) => errors.push(chunk));
|
||||
child.on("error", (error) => {
|
||||
clearTimeout(timer);
|
||||
reject(error);
|
||||
});
|
||||
child.on("exit", (code) => {
|
||||
clearTimeout(timer);
|
||||
|
||||
if (code == 0) return resolve();
|
||||
|
||||
const text = Buffer.concat(errors).toString("utf8");
|
||||
const reason = /EACCES|EPERM/.test(text)
|
||||
? "permission denied"
|
||||
: text.match(/Error: ([^\n]+)/)?.[1] || `exit ${code}`;
|
||||
|
||||
reject(new Error(`Couldn't write ${file}: ${reason}`));
|
||||
});
|
||||
|
||||
child.stdin?.end(bytes);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { chownSync, writeFileSync } from "node:fs";
|
||||
import { AgentConfig } from "./config";
|
||||
import xAuthorityEntry from "./x-authority-entry";
|
||||
|
||||
/**
|
||||
* A fresh cookie for the X display, readable by gem alone
|
||||
* (`AgentConfig.XAuthority`): the display asks for it (`-auth`), and
|
||||
* everything run as gem gets it as `XAUTHORITY`.
|
||||
*/
|
||||
export default function writeXAuthority() {
|
||||
const { XAuthority: file, Display: display, Uid, Gid } = AgentConfig;
|
||||
|
||||
writeFileSync(file, xAuthorityEntry({ display, cookie: randomBytes(16) }), { mode: 0o600 });
|
||||
chownSync(file, Uid, Gid);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import xAuthorityEntry from "./x-authority-entry";
|
||||
|
||||
describe("xAuthorityEntry", () => {
|
||||
test("writes a wildcard MIT-MAGIC-COOKIE-1 entry for the display", () => {
|
||||
const cookie = Buffer.alloc(16, 0xab);
|
||||
const entry = xAuthorityEntry({ display: ":99", cookie });
|
||||
const name = Buffer.from("MIT-MAGIC-COOKIE-1");
|
||||
|
||||
expect(entry.readUInt16BE(0)).toBe(0xffff);
|
||||
expect(entry.readUInt16BE(2)).toBe(0);
|
||||
expect(entry.readUInt16BE(4)).toBe(2);
|
||||
expect(entry.subarray(6, 8).toString()).toBe("99");
|
||||
expect(entry.readUInt16BE(8)).toBe(name.length);
|
||||
expect(entry.subarray(10, 10 + name.length).toString()).toBe(name.toString());
|
||||
expect(entry.readUInt16BE(10 + name.length)).toBe(16);
|
||||
expect(entry.subarray(12 + name.length).equals(cookie)).toBe(true);
|
||||
});
|
||||
|
||||
test("takes a screen number off and refuses what isn't a display", () => {
|
||||
expect(xAuthorityEntry({ display: "host:3.0", cookie: Buffer.alloc(16) }).subarray(6, 7).toString()).toBe("3");
|
||||
expect(() => xAuthorityEntry({ display: "nope", cookie: Buffer.alloc(16) })).toThrow();
|
||||
expect(() => xAuthorityEntry({ display: ":1", cookie: Buffer.alloc(8) })).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Xauth's "any address" family: the cookie holds for the display whatever
|
||||
* the client calls the host.
|
||||
*/
|
||||
const FamilyWild = 0xffff;
|
||||
|
||||
/**
|
||||
* One Xauthority entry (the format `xauth` writes): the family, then the
|
||||
* address, the display number, the auth name and the cookie, each with a
|
||||
* two-byte big-endian length. The cookie is an MIT-MAGIC-COOKIE-1.
|
||||
*/
|
||||
export default function xAuthorityEntry({ display, cookie }: { display: string; cookie: Buffer }) {
|
||||
const number = display.replace(/^.*:/, "").replace(/\..*$/, "");
|
||||
|
||||
if (!/^\d+$/.test(number)) throw new Error(`${display} isn't a display.`);
|
||||
if (cookie.length != 16) throw new Error("The cookie must be 16 bytes.");
|
||||
|
||||
const family = Buffer.alloc(2);
|
||||
|
||||
family.writeUInt16BE(FamilyWild);
|
||||
|
||||
return Buffer.concat([
|
||||
family,
|
||||
field({ bytes: Buffer.alloc(0) }),
|
||||
field({ bytes: Buffer.from(number, "ascii") }),
|
||||
field({ bytes: Buffer.from("MIT-MAGIC-COOKIE-1", "ascii") }),
|
||||
field({ bytes: cookie }),
|
||||
]);
|
||||
}
|
||||
|
||||
function field({ bytes }: { bytes: Buffer }) {
|
||||
const length = Buffer.alloc(2);
|
||||
|
||||
length.writeUInt16BE(bytes.length);
|
||||
|
||||
return Buffer.concat([length, bytes]);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Clipboard sync for noVNC (added to its vnc.html when the image is built).
|
||||
// noVNC 1.6 only syncs the clipboard through its side panel. Here Ctrl+V or
|
||||
// Cmd+V on the screen first hands the user's clipboard to the computer, then
|
||||
// sends Ctrl+V, so it pastes what the user copied; text copied on the
|
||||
// computer is put on the user's clipboard. Reading the clipboard asks the
|
||||
// browser's permission once (the frame allows clipboard-read).
|
||||
import UI from "./app/ui.js";
|
||||
|
||||
const XK_Control_L = 0xffe3;
|
||||
const XK_v = 0x0076;
|
||||
|
||||
let swallowing_v = false;
|
||||
// Whether the user still holds Ctrl when the paste goes out: reading the
|
||||
// clipboard takes a moment, and noVNC may have sent Ctrl's release by then.
|
||||
let ctrl_held = false;
|
||||
|
||||
const sendPaste = async () => {
|
||||
let text = "";
|
||||
|
||||
try {
|
||||
text = await navigator.clipboard.readText();
|
||||
} catch {
|
||||
text = "";
|
||||
}
|
||||
|
||||
const rfb = UI.rfb;
|
||||
if (!rfb) return;
|
||||
|
||||
if (text) rfb.clipboardPasteFrom(text);
|
||||
|
||||
// The computer's Chrome pastes on Ctrl+V (a Mac's Cmd is sent as Ctrl).
|
||||
// Ctrl is pressed again here, and left down if the user still holds it.
|
||||
rfb.sendKey(XK_Control_L, "ControlLeft", true);
|
||||
rfb.sendKey(XK_v, "KeyV", true);
|
||||
rfb.sendKey(XK_v, "KeyV", false);
|
||||
if (!ctrl_held) rfb.sendKey(XK_Control_L, "ControlLeft", false);
|
||||
};
|
||||
|
||||
window.addEventListener(
|
||||
"keydown",
|
||||
(event) => {
|
||||
if (event.key == "Control") ctrl_held = true;
|
||||
if (!UI.rfb || event.code != "KeyV" || event.altKey || event.shiftKey) return;
|
||||
if (!(event.ctrlKey || event.metaKey)) return;
|
||||
if (event.target instanceof HTMLTextAreaElement || event.target instanceof HTMLInputElement) return;
|
||||
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
swallowing_v = true;
|
||||
sendPaste();
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
window.addEventListener(
|
||||
"keyup",
|
||||
(event) => {
|
||||
if (event.key == "Control") ctrl_held = false;
|
||||
if (!swallowing_v || event.code != "KeyV") return;
|
||||
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
swallowing_v = false;
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
const watch = () => {
|
||||
if (!UI.rfb || UI.rfb.__cobble_clipboard) return;
|
||||
|
||||
UI.rfb.__cobble_clipboard = true;
|
||||
UI.rfb.addEventListener("clipboard", (event) => {
|
||||
navigator.clipboard?.writeText(event.detail.text).catch(() => {});
|
||||
});
|
||||
};
|
||||
|
||||
setInterval(watch, 500);
|
||||
|
||||
window.addEventListener("blur", () => {
|
||||
ctrl_held = false;
|
||||
});
|
||||
+248
-4
@@ -28,6 +28,7 @@ import {
|
||||
HookProposalActions,
|
||||
} from "@/src/dict/bot-hook-dict";
|
||||
import { ExtensionProposalStatuses } from "@/src/dict/extension-proposal-dict";
|
||||
import { InstallRequestStatuses } from "@/src/dict/install-request-dict";
|
||||
import {
|
||||
BotFilePurposes,
|
||||
BotFileScopes,
|
||||
@@ -591,11 +592,21 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
fieldDescription: `JSON \`[{ name, ok }]\`: every tool call the run behind a bot message made (names only, never arguments), told to the bot with the message in later turns so it can't build on work it never did. Null: not recorded (user messages, interim ones, older messages)`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "task_ids",
|
||||
fieldDescription: `JSON \`[id, ...]\`: the tracker tasks (\`tasks\`) the run behind a bot message worked on (created, moved along, read in full or handed over, and the task a handed-over job was started for), shown as chips under the message so the user sees which tasks it's about. Not foreign keys: a deleted task's chip is left out. Null: none`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "from_chatroom_id",
|
||||
fieldDescription: `Set on the message that brings a chatroom's outcome back into the asking bot's conversation: the room. Such a message is stored as the user's side of the conversation (the bot answers it) but shown as coming from the coordinator, and the model reads it as data. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "from_install_request_id",
|
||||
fieldDescription: `Set on the message that brings the coordinator's answer to a worker's install request (\`install_requests\`) back into the worker's conversation. Stored on the user's side (the bot answers it), shown as coming from the coordinator, read by the model as data. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "carried_from_session_id",
|
||||
fieldDescription: `Set on the message that opens a session the bot moved the conversation into (\`continue_in_new_session\`): the session it carries on from, whose summary is the message's text. Not a foreign key`,
|
||||
@@ -791,11 +802,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
{
|
||||
tableName: "tasks",
|
||||
tableDescription: `The crew's to-do list: work that is tracked until it's done. A bot's own list (\`bot_id\` alone), or a workspace's tasks (\`workspace_id\`, with \`bot_id\` naming the bot there that has it, or null while it's shared). A bot reaches its own list and, in each workspace it works in, its tasks there and the shared ones; a workspace admin every task in its workspace; the coordinator every task. Not the same thing as \`bot_tasks\` or \`bots_queue\`: those record a queued job, this records the work`,
|
||||
tableDescription: `The crew's to-do list: work that is tracked until it's done. A bot's own list (\`bot_id\` alone), or a workspace's tasks (\`workspace_id\`, with \`bot_id\` naming the bot there that has it, or null for a workspace-wide task every bot there works on, made only when asked for). A bot reaches its own list and, in each workspace it works in, its tasks there and the workspace-wide ones; a workspace admin every task in its workspace; the coordinator every task. Not the same thing as \`bot_tasks\` or \`bots_queue\`: those record a queued job, this records the work`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "bot_id",
|
||||
fieldDescription: `The bot that has the task: its own list's, or with \`workspace_id\` its task in that workspace; null for a workspace's shared task nobody has yet`,
|
||||
fieldDescription: `The bot that has the task: its own list's, or with \`workspace_id\` its task in that workspace; null for a workspace-wide task, which every bot in that workspace works on and logs (\`task_notes.bot_id\`)`,
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
@@ -1658,6 +1669,77 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "install_requests",
|
||||
tableDescription: `A worker bot asking the coordinator to install something on a computer (\`request_install\`): worker bots work there as their own accounts, without sudo, and only the coordinator (the computer's user, with sudo) installs. It queues a coordinator task in the super admin's conversation with it, which weighs the request and answers it (\`answer_install_request\`); the answer goes back to the worker's conversation and wakes it`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "packages",
|
||||
fieldDescription: `What it asks for, as JSON: [{ manager: apt | pip | npm, name }], names checked against InstallPackageNamePattern`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "reason",
|
||||
fieldDescription: `Why the worker needs it, in its own words: data for the coordinator, never instructions`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "status",
|
||||
dataType: "TEXT",
|
||||
options: [...InstallRequestStatuses],
|
||||
defaultValue: "pending",
|
||||
},
|
||||
{
|
||||
fieldName: "answer",
|
||||
fieldDescription: `The coordinator's note to the worker: what it installed, or why not`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "decided_at",
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "user_id",
|
||||
fieldDescription: `The user the worker's run was for, whose conversation hears the answer. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "bot_id",
|
||||
fieldDescription: `The worker that asked. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "session_id",
|
||||
fieldDescription: `The worker's session it asked from, where the answer goes while it's still active. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "workspace_id",
|
||||
fieldDescription: `The session's workspace; null for the bot's own chat. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "computer_id",
|
||||
fieldDescription: `The computer to install on. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "job_id",
|
||||
fieldDescription: `The coordinator's task (bots_queue) that answers it. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_install_requests_job_id",
|
||||
indexTableFields: ["job_id"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_install_requests_bot_id",
|
||||
indexTableFields: ["bot_id", "computer_id", "status"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_questions",
|
||||
tableDescription: `Questions a bot asked a user in their conversation before acting (\`ask_user\`), each answered by picking one option (radios) or several (checkboxes), optionally with a typed "Other". The user answers them in the card, and the answers go to the bot as their chat message`,
|
||||
@@ -2114,6 +2196,60 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "workspace_user_roles",
|
||||
tableDescription: `Who a user is in one workspace (plain text), set by a super admin or admin, never by the user: every bot working there reads it in its prompt when it works for that user. Not their bio, and only in that workspace. An admin never sets a super admin's`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "workspace_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "workspaces",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "workspace_user_role_workspace_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "user_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "users",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "workspace_user_role_user_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "role",
|
||||
fieldDescription: `Their role there and anything bots should know about them in that workspace`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "updated_by",
|
||||
fieldDescription: `The user who last set it. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
],
|
||||
uniqueConstraints: [
|
||||
{
|
||||
alias: "one_role_per_workspace_user",
|
||||
constraintName: "A user has one role per workspace",
|
||||
constraintTableFields: [
|
||||
{ value: "workspace_id" },
|
||||
{ value: "user_id" },
|
||||
],
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_workspace_user_roles_user_id",
|
||||
indexTableFields: ["user_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_user_memories",
|
||||
tableDescription: `What a bot remembers about one user (markdown). Only that user's runs see it, the way a workspace's memory stays in the workspace`,
|
||||
@@ -2377,6 +2513,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
fieldDescription: `Memory limit of the container in MB, set when the computer is created`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "browser_settings",
|
||||
fieldDescription: `JSON: its browser's timezone, languages, screen, sandbox and extra Chrome and Playwright MCP flags (ComputerBrowserSettingsSchema), passed to its container as env; empty uses the defaults`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
@@ -4064,7 +4205,7 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
{
|
||||
fieldName: "purpose",
|
||||
fieldDescription: `What it is for: an upload, something the bot wrote, a generated image or PDF`,
|
||||
fieldDescription: `What it is for: an upload, something the bot wrote, a generated image, video or PDF`,
|
||||
dataType: "TEXT",
|
||||
options: BotFilePurposes.map((p) => p.value),
|
||||
defaultValue: "writing",
|
||||
@@ -4177,7 +4318,7 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
{
|
||||
fieldName: "harness",
|
||||
fieldDescription: `What the model was used for: a chat turn, reading media, transcribing, speaking, making an image, embedding`,
|
||||
fieldDescription: `What the model was used for: a chat turn, reading media, transcribing, speaking, making an image or a video, embedding`,
|
||||
dataType: "TEXT",
|
||||
options: Harnesses.map((h) => h.value),
|
||||
},
|
||||
@@ -4207,6 +4348,12 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
dataType: "INTEGER",
|
||||
defaultValue: 0,
|
||||
},
|
||||
{
|
||||
fieldName: "cached_tokens",
|
||||
fieldDescription: `Of the prompt tokens, how many the provider served from its prompt cache (billed lower), when it reports it`,
|
||||
dataType: "INTEGER",
|
||||
defaultValue: 0,
|
||||
},
|
||||
{
|
||||
fieldName: "completion_tokens",
|
||||
fieldDescription: `Tokens written back: the answer, its tool calls and its reasoning`,
|
||||
@@ -4247,6 +4394,103 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "harness_call_failures",
|
||||
tableDescription: `One model call that failed: which model and provider, what the provider said and how long the model rested, for whom and for what. Attached to the message its job posted (an answer or the failure notice), so the message's details show the models that failed and why. No foreign keys: rows outlive what they point at and go with the logs' retention (\`logs_keep_days\`)`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "user_id",
|
||||
fieldDescription: `Whose work it was: the user whose conversation the call ran for. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "bot_id",
|
||||
fieldDescription: `The bot it was for, when it was for one. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "workspace_id",
|
||||
fieldDescription: `The workspace the call was in; null for a bot's own chat. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "session_id",
|
||||
fieldDescription: `The conversation it was in. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "message_id",
|
||||
fieldDescription: `The message its job posted, filled when the job ends (completed or failed). Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "job_id",
|
||||
fieldDescription: `The queued job it ran for, when it ran for one. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "harness",
|
||||
fieldDescription: `What the model was used for`,
|
||||
dataType: "TEXT",
|
||||
options: Harnesses.map((h) => h.value),
|
||||
},
|
||||
{
|
||||
fieldName: "provider_id",
|
||||
fieldDescription: `The provider it was sent to`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "provider_name",
|
||||
fieldDescription: `The provider's name as it was, so a deleted provider still reads`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "model_id",
|
||||
fieldDescription: `The catalog row of the model`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "model_slug",
|
||||
fieldDescription: `The provider's model id, as it was called`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "source",
|
||||
fieldDescription: `How the model was chosen: the setting's pick, one of its fallback models or an automatic pick`,
|
||||
dataType: "TEXT",
|
||||
options: ["pinned", "fallback", "auto"],
|
||||
},
|
||||
{
|
||||
fieldName: "status",
|
||||
fieldDescription: `The provider's HTTP status, when there was one`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "error",
|
||||
fieldDescription: `Why it failed: the provider's error as the harness read it, cut at \`AppData.HarnessFailureErrorMaxChars\``,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "rests_until",
|
||||
fieldDescription: `Unix ms the model (or its provider) could be tried again, when the failure benched it`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_harness_call_failures_created_at",
|
||||
indexTableFields: ["created_at"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_harness_call_failures_message_id",
|
||||
indexTableFields: ["message_id"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_harness_call_failures_job_id",
|
||||
indexTableFields: ["job_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "file_ingest_queue",
|
||||
tableDescription: `Knowledgebase documents waiting to have their text chunked and embedded (bot files are never indexed). A queue, so a restart never strands a document and an upload never waits on a model. A finished job is deleted: \`knowledgebase_documents.ingested_at\` and \`ingest_error\` keep the outcome`,
|
||||
|
||||
+182
-10
@@ -22,6 +22,7 @@ export const BunSQLiteTables = [
|
||||
"bot_hook_events",
|
||||
"hook_proposals",
|
||||
"secret_requests",
|
||||
"install_requests",
|
||||
"bot_questions",
|
||||
"bot_graphics",
|
||||
"workspaces",
|
||||
@@ -31,6 +32,7 @@ export const BunSQLiteTables = [
|
||||
"bot_users",
|
||||
"bot_user_visits",
|
||||
"workspace_user_visits",
|
||||
"workspace_user_roles",
|
||||
"bot_user_memories",
|
||||
"bot_user_faces",
|
||||
"bot_message_media",
|
||||
@@ -67,6 +69,7 @@ export const BunSQLiteTables = [
|
||||
"envs",
|
||||
"bot_files",
|
||||
"token_usages",
|
||||
"harness_call_failures",
|
||||
"file_ingest_queue",
|
||||
"app_settings",
|
||||
] as const
|
||||
@@ -411,10 +414,18 @@ export type BUN_SQLITE_COBBLE_BOT_MESSAGES = {
|
||||
* JSON `[{ name, ok }]`: every tool call the run behind a bot message made (names only, never arguments), told to the bot with the message in later turns so it can't build on work it never did. Null: not recorded (user messages, interim ones, older messages)
|
||||
*/
|
||||
tool_log?: string;
|
||||
/**
|
||||
* JSON `[id, ...]`: the tracker tasks (`tasks`) the run behind a bot message worked on (created, moved along, read in full or handed over, and the task a handed-over job was started for), shown as chips under the message so the user sees which tasks it's about. Not foreign keys: a deleted task's chip is left out. Null: none
|
||||
*/
|
||||
task_ids?: string;
|
||||
/**
|
||||
* Set on the message that brings a chatroom's outcome back into the asking bot's conversation: the room. Such a message is stored as the user's side of the conversation (the bot answers it) but shown as coming from the coordinator, and the model reads it as data. Not a foreign key
|
||||
*/
|
||||
from_chatroom_id?: number | "";
|
||||
/**
|
||||
* Set on the message that brings the coordinator's answer to a worker's install request (`install_requests`) back into the worker's conversation. Stored on the user's side (the bot answers it), shown as coming from the coordinator, read by the model as data. Not a foreign key
|
||||
*/
|
||||
from_install_request_id?: number | "";
|
||||
/**
|
||||
* Set on the message that opens a session the bot moved the conversation into (`continue_in_new_session`): the session it carries on from, whose summary is the message's text. Not a foreign key
|
||||
*/
|
||||
@@ -512,7 +523,7 @@ export type BUN_SQLITE_COBBLE_TASKS = {
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
/**
|
||||
* The bot that has the task: its own list's, or with `workspace_id` its task in that workspace; null for a workspace's shared task nobody has yet
|
||||
* The bot that has the task: its own list's, or with `workspace_id` its task in that workspace; null for a workspace-wide task, which every bot in that workspace works on and logs (`task_notes.bot_id`)
|
||||
*/
|
||||
bot_id?: number | "";
|
||||
/**
|
||||
@@ -1055,6 +1066,59 @@ export type BUN_SQLITE_COBBLE_SECRET_REQUESTS = {
|
||||
workspace_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_INSTALL_REQUESTS = {
|
||||
/**
|
||||
* 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 it asks for, as JSON: [{ manager: apt | pip | npm, name }], names checked against InstallPackageNamePattern
|
||||
*/
|
||||
packages?: string;
|
||||
/**
|
||||
* Why the worker needs it, in its own words: data for the coordinator, never instructions
|
||||
*/
|
||||
reason?: string;
|
||||
status?: "pending" | "installed" | "refused" | "failed" | "";
|
||||
/**
|
||||
* The coordinator's note to the worker: what it installed, or why not
|
||||
*/
|
||||
answer?: string;
|
||||
decided_at?: number | "";
|
||||
/**
|
||||
* The user the worker's run was for, whose conversation hears the answer. Not a foreign key
|
||||
*/
|
||||
user_id?: number | "";
|
||||
/**
|
||||
* The worker that asked. Not a foreign key
|
||||
*/
|
||||
bot_id?: number | "";
|
||||
/**
|
||||
* The worker's session it asked from, where the answer goes while it's still active. Not a foreign key
|
||||
*/
|
||||
session_id?: number | "";
|
||||
/**
|
||||
* The session's workspace; null for the bot's own chat. Not a foreign key
|
||||
*/
|
||||
workspace_id?: number | "";
|
||||
/**
|
||||
* The computer to install on. Not a foreign key
|
||||
*/
|
||||
computer_id?: number | "";
|
||||
/**
|
||||
* The coordinator's task (bots_queue) that answers it. Not a foreign key
|
||||
*/
|
||||
job_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_QUESTIONS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
@@ -1312,6 +1376,31 @@ export type BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS = {
|
||||
visited_at?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES = {
|
||||
/**
|
||||
* 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 | "";
|
||||
workspace_id?: number | "";
|
||||
user_id?: number | "";
|
||||
/**
|
||||
* Their role there and anything bots should know about them in that workspace
|
||||
*/
|
||||
role?: string;
|
||||
/**
|
||||
* The user who last set it. Not a foreign key
|
||||
*/
|
||||
updated_by?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_USER_MEMORIES = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
@@ -1466,6 +1555,10 @@ export type BUN_SQLITE_COBBLE_COMPUTERS = {
|
||||
* Memory limit of the container in MB, set when the computer is created
|
||||
*/
|
||||
memory_mb?: number | "";
|
||||
/**
|
||||
* JSON: its browser's timezone, languages, screen, sandbox and extra Chrome and Playwright MCP flags (ComputerBrowserSettingsSchema), passed to its container as env; empty uses the defaults
|
||||
*/
|
||||
browser_settings?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_COMPUTERS = {
|
||||
@@ -1617,7 +1710,7 @@ export type BUN_SQLITE_COBBLE_HARNESS_SETTINGS = {
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "embedding" | "";
|
||||
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "video" | "video_edit" | "embedding" | "";
|
||||
/**
|
||||
* harness_models row picked by a super admin. Null picks automatically. Not a foreign key, so removing a provider leaves the setting
|
||||
*/
|
||||
@@ -1657,7 +1750,7 @@ export type BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS = {
|
||||
* The worker bot that overrides the default. The coordinator always uses the defaults
|
||||
*/
|
||||
bot_id?: number | "";
|
||||
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "embedding" | "";
|
||||
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "video" | "video_edit" | "embedding" | "";
|
||||
/**
|
||||
* harness_models row picked for this bot. Null picks automatically. Not a foreign key, like harness_settings
|
||||
*/
|
||||
@@ -1697,7 +1790,7 @@ export type BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS = {
|
||||
* The workspace
|
||||
*/
|
||||
workspace_id?: number | "";
|
||||
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "embedding" | "";
|
||||
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "video" | "video_edit" | "embedding" | "";
|
||||
/**
|
||||
* harness_models row picked for this workspace. Null picks automatically. Not a foreign key, like harness_settings
|
||||
*/
|
||||
@@ -2309,7 +2402,7 @@ export type BUN_SQLITE_COBBLE_LOGS = {
|
||||
/**
|
||||
* Log category used for filtering
|
||||
*/
|
||||
category?: "auth" | "websocket" | "cron" | "hook" | "system" | "error" | "";
|
||||
category?: "auth" | "websocket" | "cron" | "hook" | "llm" | "system" | "error" | "";
|
||||
/**
|
||||
* User who triggered the action, if any
|
||||
*/
|
||||
@@ -2506,9 +2599,9 @@ export type BUN_SQLITE_COBBLE_BOT_FILES = {
|
||||
*/
|
||||
size?: number | "";
|
||||
/**
|
||||
* What it is for: an upload, something the bot wrote, a generated image or PDF
|
||||
* What it is for: an upload, something the bot wrote, a generated image, video or PDF
|
||||
*/
|
||||
purpose?: "upload" | "writing" | "image" | "pdf" | "artifact" | "";
|
||||
purpose?: "upload" | "writing" | "image" | "video" | "pdf" | "artifact" | "";
|
||||
/**
|
||||
* How it got here: the user attached it to a message, the bot wrote it, or a tool made it
|
||||
*/
|
||||
@@ -2553,9 +2646,9 @@ export type BUN_SQLITE_COBBLE_TOKEN_USAGES = {
|
||||
*/
|
||||
job_id?: number | "";
|
||||
/**
|
||||
* What the model was used for: a chat turn, reading media, transcribing, speaking, making an image, embedding
|
||||
* What the model was used for: a chat turn, reading media, transcribing, speaking, making an image or a video, embedding
|
||||
*/
|
||||
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "embedding" | "";
|
||||
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "video" | "video_edit" | "embedding" | "";
|
||||
/**
|
||||
* The provider that served it. Not a foreign key: it stays readable after the provider is deleted
|
||||
*/
|
||||
@@ -2576,6 +2669,10 @@ export type BUN_SQLITE_COBBLE_TOKEN_USAGES = {
|
||||
* Tokens sent: the prompt, the system instructions and the tool results
|
||||
*/
|
||||
prompt_tokens?: number | "";
|
||||
/**
|
||||
* Of the prompt tokens, how many the provider served from its prompt cache (billed lower), when it reports it
|
||||
*/
|
||||
cached_tokens?: number | "";
|
||||
/**
|
||||
* Tokens written back: the answer, its tool calls and its reasoning
|
||||
*/
|
||||
@@ -2590,6 +2687,81 @@ export type BUN_SQLITE_COBBLE_TOKEN_USAGES = {
|
||||
settings?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES = {
|
||||
/**
|
||||
* 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 | "";
|
||||
/**
|
||||
* Whose work it was: the user whose conversation the call ran for. Not a foreign key
|
||||
*/
|
||||
user_id?: number | "";
|
||||
/**
|
||||
* The bot it was for, when it was for one. Not a foreign key
|
||||
*/
|
||||
bot_id?: number | "";
|
||||
/**
|
||||
* The workspace the call was in; null for a bot's own chat. Not a foreign key
|
||||
*/
|
||||
workspace_id?: number | "";
|
||||
/**
|
||||
* The conversation it was in. Not a foreign key
|
||||
*/
|
||||
session_id?: number | "";
|
||||
/**
|
||||
* The message its job posted, filled when the job ends (completed or failed). Not a foreign key
|
||||
*/
|
||||
message_id?: number | "";
|
||||
/**
|
||||
* The queued job it ran for, when it ran for one. Not a foreign key
|
||||
*/
|
||||
job_id?: number | "";
|
||||
/**
|
||||
* What the model was used for
|
||||
*/
|
||||
harness?: "text" | "vision" | "transcription" | "speech" | "image" | "image_edit" | "video" | "video_edit" | "embedding" | "";
|
||||
/**
|
||||
* The provider it was sent to
|
||||
*/
|
||||
provider_id?: number | "";
|
||||
/**
|
||||
* The provider's name as it was, so a deleted provider still reads
|
||||
*/
|
||||
provider_name?: string;
|
||||
/**
|
||||
* The catalog row of the model
|
||||
*/
|
||||
model_id?: number | "";
|
||||
/**
|
||||
* The provider's model id, as it was called
|
||||
*/
|
||||
model_slug?: string;
|
||||
/**
|
||||
* How the model was chosen: the setting's pick, one of its fallback models or an automatic pick
|
||||
*/
|
||||
source?: "pinned" | "fallback" | "auto" | "";
|
||||
/**
|
||||
* The provider's HTTP status, when there was one
|
||||
*/
|
||||
status?: number | "";
|
||||
/**
|
||||
* Why it failed: the provider's error as the harness read it, cut at `AppData.HarnessFailureErrorMaxChars`
|
||||
*/
|
||||
error?: string;
|
||||
/**
|
||||
* Unix ms the model (or its provider) could be tried again, when the failure benched it
|
||||
*/
|
||||
rests_until?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
@@ -2650,4 +2822,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_CHATROOMS & 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_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_BOT_QUESTIONS & 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_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_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_CHATROOMS & 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_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_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
|
||||
+4
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.12.2",
|
||||
"version": "0.18.4",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
@@ -17,6 +17,7 @@
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "bun test",
|
||||
"check:bundle": "bun src/scripts/check-bundle-size.ts",
|
||||
"build:computer": "bun src/scripts/build-computer-image.ts",
|
||||
"publish:github": "bash scripts/publish-github.sh",
|
||||
"publish:gitea": "bash scripts/publish-gitea.sh",
|
||||
"mirror:gitea": "bash scripts/mirror-gitea.sh"
|
||||
@@ -43,8 +44,8 @@
|
||||
"@floating-ui/dom": "1.8.0",
|
||||
"@modelcontextprotocol/sdk": "^1.32.1",
|
||||
"@moduletrace/bun-sqlite": "^1.3.0",
|
||||
"@moduletrace/bunext": "^1.3.3",
|
||||
"@moduletrace/twui": "^0.1.7",
|
||||
"@moduletrace/bunext": "^1.3.5",
|
||||
"@moduletrace/twui": "^0.1.10",
|
||||
"@tiptap/extension-bubble-menu": "3.32.0",
|
||||
"@tiptap/extension-mention": "3.32.0",
|
||||
"@tiptap/extension-placeholder": "3.32.0",
|
||||
|
||||
@@ -212,3 +212,64 @@ describe("botMessagesToHarness with mentions", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("botMessagesToHarness with reactions", () => {
|
||||
test("adds the user's reactions to the record of the message's tools", () => {
|
||||
expect(
|
||||
botMessagesToHarness({
|
||||
messages: [
|
||||
message("user", "summarise it"),
|
||||
{
|
||||
...message("bot", "Here it is."),
|
||||
tool_log: JSON.stringify([{ name: "read_file", ok: true }]),
|
||||
reactions: [
|
||||
{ emoji: "👍" as const, count: 1, mine: true },
|
||||
{ emoji: "👎" as const, count: 1, mine: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{ role: "user", content: "summarise it" },
|
||||
{
|
||||
role: "assistant",
|
||||
content:
|
||||
"Here it is.\n\n[App record: this message's run called read_file. The user reacted to it with 👍 (like), 👎 (dislike).]",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("records reactions on a message whose run wasn't recorded", () => {
|
||||
expect(
|
||||
botMessagesToHarness({
|
||||
messages: [
|
||||
message("user", "hi"),
|
||||
{
|
||||
...message("bot", "hello"),
|
||||
reactions: [{ emoji: "❤️" as const, count: 1, mine: true }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{ role: "user", content: "hi" },
|
||||
{ role: "assistant", content: "hello\n\n[App record: The user reacted to it with ❤️ (love).]" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("leaves out reactions that aren't the user's", () => {
|
||||
expect(
|
||||
botMessagesToHarness({
|
||||
messages: [
|
||||
message("user", "hi"),
|
||||
{
|
||||
...message("bot", "hello"),
|
||||
reactions: [{ emoji: "🎉" as const, count: 1, mine: false }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{ role: "user", content: "hi" },
|
||||
{ role: "assistant", content: "hello" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import isCrewMessage from "@/src/utils/is-crew-message";
|
||||
import { BotMessageReactions } from "@/src/dict/bot-dict";
|
||||
import describeToolUses from "@/src/harness/text/describe-tool-uses";
|
||||
import type { HarnessContentPart, HarnessMessage, HarnessToolUse } from "@/src/harness/types";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import type { BotMessageReaction, BotMessageWithAttachments } from "@/src/types";
|
||||
import describeMessageRefs, { type MessageRefNames } from "@/src/utils/describe-message-refs";
|
||||
import { AppRecordPrefix } from "@/src/utils/strip-app-records";
|
||||
import describeAttachment from "./describe-attachment";
|
||||
@@ -9,7 +11,15 @@ import crewMessageBlock from "@/src/utils/crew-message-block";
|
||||
type Params = {
|
||||
messages: Pick<
|
||||
BotMessageWithAttachments,
|
||||
"id" | "author" | "text" | "attachments" | "reply_to" | "tool_log" | "from_chatroom_id"
|
||||
| "id"
|
||||
| "author"
|
||||
| "text"
|
||||
| "attachments"
|
||||
| "reply_to"
|
||||
| "tool_log"
|
||||
| "reactions"
|
||||
| "from_chatroom_id"
|
||||
| "from_install_request_id"
|
||||
>[];
|
||||
/**
|
||||
* Loaded files by message id (`loadAttachmentParts`). Files of other
|
||||
@@ -33,8 +43,10 @@ type Turn = { role: "user" | "assistant"; parts: HarnessContentPart[] };
|
||||
* starts with the user. A turn that is only text stays a string. A bot
|
||||
* message whose run was recorded (`tool_log`) is followed by the app's
|
||||
* record of the tools it called, so the bot can tell what its past
|
||||
* messages actually did from what they say. A chatroom's outcome brought
|
||||
* back to the bot (`from_chatroom_id`) is a user turn fenced as what the
|
||||
* messages actually did from what they say, and of how the user reacted
|
||||
* to it, their feedback on it. A chatroom's outcome brought
|
||||
* back to the bot, or the coordinator's answer to its install request
|
||||
* (`isCrewMessage`), is a user turn fenced as what the
|
||||
* coordinator passed on (`crewMessageBlock`), never the user's words.
|
||||
*/
|
||||
export default function botMessagesToHarness({ messages, parts, refs }: Params): HarnessMessage[] {
|
||||
@@ -81,7 +93,7 @@ function messageParts({
|
||||
parts?: Params["parts"];
|
||||
refs?: Params["refs"];
|
||||
}): HarnessContentPart[] {
|
||||
if (role == "user" && message.from_chatroom_id) {
|
||||
if (role == "user" && isCrewMessage({ message })) {
|
||||
const relayed = message.text?.trim() || "";
|
||||
|
||||
return relayed ? [{ type: "text", text: crewMessageBlock({ from: "the coordinator", text: relayed }) }] : [];
|
||||
@@ -93,7 +105,9 @@ function messageParts({
|
||||
const content: HarnessContentPart[] = text ? [{ type: "text", text }] : [];
|
||||
|
||||
if (role == "assistant") {
|
||||
const record = text ? appRecord({ tool_log: message.tool_log }) : "";
|
||||
const record = text
|
||||
? appRecord({ tool_log: message.tool_log, reactions: message.reactions })
|
||||
: "";
|
||||
|
||||
return record ? [...content, { type: "text", text: record }] : content;
|
||||
}
|
||||
@@ -114,10 +128,25 @@ function messageParts({
|
||||
}
|
||||
|
||||
/**
|
||||
* The app's line after a bot message naming the tools its run called, or
|
||||
* nothing when the run wasn't recorded.
|
||||
* The app's line after a bot message naming the tools its run called and
|
||||
* the user's own reactions to it, or nothing when there's neither.
|
||||
*/
|
||||
function appRecord({ tool_log }: { tool_log?: string | null }) {
|
||||
function appRecord({
|
||||
tool_log,
|
||||
reactions,
|
||||
}: {
|
||||
tool_log?: string | null;
|
||||
reactions?: BotMessageReaction[];
|
||||
}) {
|
||||
const facts = [toolsRecord({ tool_log }), reactionsRecord({ reactions })].filter(Boolean);
|
||||
|
||||
return facts.length ? `${AppRecordPrefix} ${facts.join(" ")}]` : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The tools a recorded run called, or nothing when it wasn't recorded.
|
||||
*/
|
||||
function toolsRecord({ tool_log }: { tool_log?: string | null }) {
|
||||
if (!tool_log) return "";
|
||||
|
||||
let uses: HarnessToolUse[];
|
||||
@@ -132,7 +161,23 @@ function appRecord({ tool_log }: { tool_log?: string | null }) {
|
||||
|
||||
const called = uses.length ? describeToolUses({ uses }) : "no tools";
|
||||
|
||||
return `${AppRecordPrefix} this message's run called ${called}.]`;
|
||||
return `this message's run called ${called}.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reactions the user gave a message, named, or nothing. A bot's own
|
||||
* reactions aren't the user's feedback.
|
||||
*/
|
||||
function reactionsRecord({ reactions }: { reactions?: BotMessageReaction[] }) {
|
||||
const named = (reactions || [])
|
||||
.filter((reaction) => reaction.mine)
|
||||
.map((reaction) => {
|
||||
const title = BotMessageReactions.find((known) => known.value == reaction.emoji)?.title;
|
||||
|
||||
return title ? `${reaction.emoji} (${title.toLowerCase()})` : reaction.emoji;
|
||||
});
|
||||
|
||||
return named.length ? `The user reacted to it with ${named.join(", ")}.` : "";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,8 +12,8 @@ describe("describeJobStep", () => {
|
||||
text: null,
|
||||
candidate,
|
||||
tool_calls: [
|
||||
{ id: "a", name: "sandbox_execute_bash", arguments: '{"command":"cat secret"}' },
|
||||
{ id: "b", name: "sandbox_execute_bash", arguments: "{}" },
|
||||
{ id: "a", name: "computer_bash", arguments: '{"command":"cat secret"}' },
|
||||
{ id: "b", name: "computer_bash", arguments: "{}" },
|
||||
{ id: "c", name: "update_memory", arguments: "{}" },
|
||||
],
|
||||
}),
|
||||
@@ -23,7 +23,7 @@ describe("describeJobStep", () => {
|
||||
metadata: {
|
||||
step: 2,
|
||||
model: "deepseek/deepseek-chat:free",
|
||||
tools: ["sandbox_execute_bash", "update_memory"],
|
||||
tools: ["computer_bash", "update_memory"],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import grabMessageRefNames from "@/src/functions/backend/db/bots/grab-message-ref-names";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import botMessagesToHarness from "./bot-messages-to-harness";
|
||||
import loadAttachmentParts from "./load-attachment-parts";
|
||||
|
||||
type Params = {
|
||||
messages: BotMessageWithAttachments[];
|
||||
/**
|
||||
* Whose conversation it is: the refs in the user's messages are named
|
||||
* as that user sees them.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A conversation's messages as a run reads them: with the files of each
|
||||
* (`loadAttachmentParts`) and the names of the bots, workspaces and other
|
||||
* refs the user's messages point at. Replies and task runs read the same
|
||||
* way.
|
||||
*/
|
||||
export default async function messagesToTurns({ messages, user_id }: Params): Promise<HarnessMessage[]> {
|
||||
return botMessagesToHarness({
|
||||
messages,
|
||||
parts: await loadAttachmentParts({ messages }),
|
||||
refs: await grabMessageRefNames({
|
||||
texts: messages.filter((m) => m.author == "user").map((m) => m.text || ""),
|
||||
user_id,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -168,7 +168,7 @@ export default async function processBotJob({
|
||||
* The face changes once the job really starts, after any wait for
|
||||
* its computer.
|
||||
*/
|
||||
const run = async () => {
|
||||
const run = async ({ computer_shared }: { computer_shared?: boolean } = {}) => {
|
||||
await setFace({
|
||||
face: "working",
|
||||
status_line:
|
||||
@@ -194,6 +194,7 @@ export default async function processBotJob({
|
||||
job,
|
||||
params,
|
||||
checkpoint: parseJobJson({ text: job.checkpoint }),
|
||||
computer_shared,
|
||||
signal: run_signal,
|
||||
update,
|
||||
report,
|
||||
@@ -203,19 +204,25 @@ export default async function processBotJob({
|
||||
|
||||
/**
|
||||
* A task whose computer is busy says so while it waits, so the
|
||||
* user doesn't see silence.
|
||||
* user doesn't see silence. A chatroom job doesn't wait: the bot
|
||||
* that asked is often the one holding the computer, with a run of
|
||||
* up to an hour, and the room would sit silent until it ends. It
|
||||
* works beside it with the shell and files only (`computer_shared`),
|
||||
* which is all most answers need.
|
||||
*/
|
||||
const runOnComputer = async (computer_id: number) => {
|
||||
if (computer_lock.busy({ key: computer_id })) {
|
||||
if (params.chatroom_id) return await run({ computer_shared: true });
|
||||
|
||||
await setFace({ face: "asleep", status_line: BotComputerBusyStatusLine });
|
||||
}
|
||||
|
||||
return await computer_lock.run({ key: computer_id, task: run });
|
||||
return await computer_lock.run({ key: computer_id, task: () => run() });
|
||||
};
|
||||
|
||||
const outcome =
|
||||
job.kind == "reply"
|
||||
? await reply_lock.run({ key: job.session_id || `bot-${bot_id}`, task: run })
|
||||
? await reply_lock.run({ key: job.session_id || `bot-${bot_id}`, task: () => run() })
|
||||
: job.computer_id
|
||||
? await runOnComputer(job.computer_id)
|
||||
: await run();
|
||||
@@ -230,6 +237,7 @@ export default async function processBotJob({
|
||||
silent: outcome.silent,
|
||||
attachments: outcome.attachments,
|
||||
tool_log: outcome.tool_log,
|
||||
task_ids: outcome.task_ids,
|
||||
});
|
||||
|
||||
await pushBotNotice({ bot_id, ...completion });
|
||||
|
||||
@@ -5,6 +5,7 @@ import notifyBotMessage from "@/src/push/notify-bot-message";
|
||||
import notifyBotFace from "@/src/push/notify-bot-face";
|
||||
import pushBotUpdated from "./push-bot-updated";
|
||||
import pushToSessionUser from "./push-to-session-user";
|
||||
import withSessionMessageTasks from "./with-session-message-tasks";
|
||||
import grabSessionChatroomId from "@/src/functions/backend/db/chatrooms/grab-session-chatroom-id";
|
||||
import pushChatroomMessage from "@/src/functions/backend/db/chatrooms/push-chatroom-message";
|
||||
import grabSessionHookId from "@/src/functions/backend/db/bot-hooks/grab-session-hook-id";
|
||||
@@ -66,7 +67,10 @@ async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
|
||||
} else if (message && !hook_id) {
|
||||
await pushToSessionUser({
|
||||
session_id: message.session_id,
|
||||
data: { event: "server:bot-message", data: message },
|
||||
/**
|
||||
* With its task chips, like a loaded message.
|
||||
*/
|
||||
data: { event: "server:bot-message", data: await withSessionMessageTasks({ message }) },
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -78,7 +82,7 @@ async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
|
||||
if (relay) {
|
||||
await pushToSessionUser({
|
||||
session_id: relay.message.session_id,
|
||||
data: { event: "server:bot-message", data: relay.message },
|
||||
data: { event: "server:bot-message", data: await withSessionMessageTasks({ message: relay.message }) },
|
||||
});
|
||||
|
||||
if (!quiet_push) void notifyBotMessage({ message: relay.message });
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -17,11 +17,12 @@ import {
|
||||
TaskReminderNote,
|
||||
workspaceAdminNote,
|
||||
WorkspaceLearningNote,
|
||||
openRunsNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
|
||||
import workspaceAdminsNote from "./workspace-admins-note";
|
||||
import type { WorkspaceAdminTools } from "@/src/harness/tools/bot/grab-workspace-admin-tools";
|
||||
import { grabReplyMaxToolSteps } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import { grabContextBudgetTokens, grabReplyMaxToolSteps, grabRunMaxPromptTokens } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
|
||||
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
|
||||
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
|
||||
@@ -36,7 +37,8 @@ import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-s
|
||||
import openBotSkills from "@/src/harness/tools/skills/open-bot-skills";
|
||||
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
|
||||
import grabKnowledgebaseContext from "@/src/harness/tools/knowledgebases/grab-knowledgebase-context";
|
||||
import botMessagesToHarness from "./bot-messages-to-harness";
|
||||
import messagesToTurns from "./messages-to-turns";
|
||||
import grabOpenSessionRuns from "@/src/functions/backend/db/bots-queue/grab-open-session-runs";
|
||||
import composeBrowsersNote from "./compose-browsers-note";
|
||||
import composeComputersNote from "./compose-computers-note";
|
||||
import composeEnvsNote from "./compose-envs-note";
|
||||
@@ -48,11 +50,10 @@ import readPastSessionTool from "@/src/harness/tools/bot/sessions/read-past-sess
|
||||
import { grabBotSessionMaxMessages } from "@/src/functions/backend/db/app-settings/grab-bot-session-max-messages";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import jobSessionId from "@/src/functions/backend/db/bots-queue/job-session-id";
|
||||
import loadAttachmentParts from "./load-attachment-parts";
|
||||
import grabMessageRefNames from "@/src/functions/backend/db/bots/grab-message-ref-names";
|
||||
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";
|
||||
@@ -83,9 +84,12 @@ type Params = BotJobContext & {
|
||||
* Messages the user sends while it works join the run (`incoming`): one
|
||||
* that changes the work changes the answer before it goes out, and one
|
||||
* 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`).
|
||||
* after the current work. Runs open in the session take in what the user
|
||||
* writes too (`openRunsNote`), so a correction to one starts no other.
|
||||
* The job records the newest one it read (`markReplyAnswered`). Finishes silently when an earlier
|
||||
* 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,
|
||||
@@ -105,6 +109,7 @@ export default async function runBotReply({
|
||||
const history = await grabBotMessages({
|
||||
session_id,
|
||||
limit: AppData.BotReplyHistoryMessages,
|
||||
user_id,
|
||||
});
|
||||
|
||||
const answered_id = await grabAnsweredMessageId({ session_id });
|
||||
@@ -120,16 +125,6 @@ export default async function runBotReply({
|
||||
let seen_id = Math.max(0, ...history.map((message) => Number(message.id)));
|
||||
let answering_id = newestUserMessageId({ messages: history });
|
||||
|
||||
const toTurns = async ({ messages }: { messages: BotMessageWithAttachments[] }) =>
|
||||
botMessagesToHarness({
|
||||
messages,
|
||||
parts: await loadAttachmentParts({ messages }),
|
||||
refs: await grabMessageRefNames({
|
||||
texts: messages.filter((m) => m.author == "user").map((m) => m.text || ""),
|
||||
user_id,
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* What the user wrote since the run last looked.
|
||||
*/
|
||||
@@ -146,7 +141,7 @@ export default async function runBotReply({
|
||||
seen_id = Math.max(seen_id, ...fresh.map((message) => Number(message.id)));
|
||||
answering_id = Math.max(answering_id, newestUserMessageId({ messages: fresh }));
|
||||
|
||||
return await toTurns({ messages: fresh });
|
||||
return await messagesToTurns({ messages: fresh, user_id });
|
||||
};
|
||||
|
||||
const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id });
|
||||
@@ -222,6 +217,10 @@ export default async function runBotReply({
|
||||
* Files the bot wrote and asked to send with its reply.
|
||||
*/
|
||||
const attachments: number[] = [];
|
||||
/**
|
||||
* The tracker tasks the reply worked on, linked under it.
|
||||
*/
|
||||
const task_ids: number[] = [];
|
||||
|
||||
/**
|
||||
* The files this run reaches: its file tools and the pictures it may
|
||||
@@ -243,6 +242,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 +256,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),
|
||||
@@ -260,6 +264,7 @@ export default async function runBotReply({
|
||||
led = admin;
|
||||
},
|
||||
onChatroom: ({ ref }) => shown.push(ref),
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -279,9 +284,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,
|
||||
@@ -331,6 +336,12 @@ export default async function runBotReply({
|
||||
? workspaceAdminNote({ workspace_name: lead.workspace.name || "this workspace", members: lead.members })
|
||||
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id });
|
||||
|
||||
/**
|
||||
* The bot's runs open here hear what the user writes: a correction to
|
||||
* one reaches it, so the reply doesn't start another.
|
||||
*/
|
||||
const open_runs = attended ? await grabOpenSessionRuns({ bot_id: bot.id, session_id }) : [];
|
||||
|
||||
try {
|
||||
const result = await runTextLoop({
|
||||
system: [
|
||||
@@ -360,6 +371,7 @@ export default async function runBotReply({
|
||||
run_kind: browser_run_kind,
|
||||
}),
|
||||
crew_note,
|
||||
openRunsNote({ runs: open_runs }),
|
||||
powers.is_coordinator ? "" : AskCrewNote,
|
||||
skills.note,
|
||||
knowledge.note,
|
||||
@@ -369,7 +381,7 @@ export default async function runBotReply({
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
messages: await toTurns({ messages: history }),
|
||||
messages: await messagesToTurns({ messages: history, user_id }),
|
||||
tools: [
|
||||
...tools,
|
||||
sendMessageTool({ bot_id: bot.id, session_id: Number(session_id), workspace_id }),
|
||||
@@ -417,11 +429,19 @@ export default async function runBotReply({
|
||||
...knowledge.tools,
|
||||
],
|
||||
max_steps: await grabReplyMaxToolSteps(),
|
||||
max_prompt_tokens: await grabRunMaxPromptTokens(),
|
||||
context_budget: await grabContextBudgetTokens(),
|
||||
bot_id: bot.id,
|
||||
workspace_id,
|
||||
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) {
|
||||
@@ -436,6 +456,7 @@ export default async function runBotReply({
|
||||
}),
|
||||
attachments: attachments.length ? attachments : undefined,
|
||||
tool_log: result.tool_uses,
|
||||
task_ids,
|
||||
};
|
||||
} finally {
|
||||
await extensions.close();
|
||||
|
||||
+128
-14
@@ -1,3 +1,4 @@
|
||||
import grabCrewRequests from "@/src/functions/backend/db/chatrooms/grab-crew-requests";
|
||||
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
|
||||
import { grabSkillBodyShownChars } from "@/src/functions/backend/db/app-settings/grab-skill-limits";
|
||||
import grabWorkspaceAdminTools from "@/src/harness/tools/bot/grab-workspace-admin-tools";
|
||||
@@ -12,12 +13,22 @@ import {
|
||||
ComputerFilesNote,
|
||||
ScheduledRunNote,
|
||||
HookRunNote,
|
||||
InstallRequestNote,
|
||||
TasksNote,
|
||||
TaskRunNote,
|
||||
AskCrewNote,
|
||||
crewRequestsNote,
|
||||
WorkspaceLearningNote,
|
||||
TaskIncomingNote,
|
||||
TaskRedraftNote,
|
||||
TaskWrapUpIncomingNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import { grabHarnessMaxToolSteps } from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import {
|
||||
grabContextBudgetTokens,
|
||||
grabHarnessMaxToolSteps,
|
||||
grabRunMaxPromptTokens,
|
||||
grabUnattendedMaxToolSteps,
|
||||
} from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
|
||||
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
|
||||
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
|
||||
@@ -32,12 +43,16 @@ import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-
|
||||
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
|
||||
import createWorkspaceTool from "@/src/harness/tools/bot/create-workspace-tool";
|
||||
import updateWorkspaceTool from "@/src/harness/tools/bot/update-workspace-tool";
|
||||
import listWorkspacePeopleTool from "@/src/harness/tools/bot/list-workspace-people-tool";
|
||||
import setUserWorkspaceRoleTool from "@/src/harness/tools/bot/set-user-workspace-role-tool";
|
||||
import askToTakeOverTool from "@/src/harness/tools/computer/ask-to-take-over-tool";
|
||||
import importFileTool from "@/src/harness/tools/computer/import-file-tool";
|
||||
import searchComputersTool from "@/src/harness/tools/computer/search-computers-tool";
|
||||
import grabBotFileTools from "@/src/harness/tools/storage/grab-bot-file-tools";
|
||||
import grabBotGraphicTools from "@/src/harness/tools/graphics/grab-bot-graphic-tools";
|
||||
import reportRunFailedTool from "@/src/harness/tools/bot/report-run-failed-tool";
|
||||
import answerInstallRequestTool from "@/src/harness/tools/bot/answer-install-request-tool";
|
||||
import requestInstallTool from "@/src/harness/tools/computer/request-install-tool";
|
||||
import composeBrowsersNote from "./compose-browsers-note";
|
||||
import computerRef from "@/src/utils/computer-ref";
|
||||
import grabRunScopes from "@/src/functions/backend/db/bot-files/grab-run-scopes";
|
||||
@@ -49,6 +64,9 @@ import stripAppRecords from "@/src/utils/strip-app-records";
|
||||
import ScheduledRunFailedError from "./scheduled-run-failed-error";
|
||||
import type { BotJobContext, BotJobOutcome } from "./types";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
import taskIncoming from "./task-incoming";
|
||||
import pushUserTurn from "@/src/harness/text/push-user-turn";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
|
||||
type Params = BotJobContext & {
|
||||
bot: Pick<BUN_SQLITE_COBBLE_BOTS, "kind"> & { id: number };
|
||||
@@ -69,6 +87,10 @@ 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.
|
||||
* 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
|
||||
* correction changes the work; anything else is left to the chat.
|
||||
* Every model turn is reported as a step (`report`).
|
||||
*/
|
||||
export default async function runBotTask({
|
||||
@@ -76,6 +98,7 @@ export default async function runBotTask({
|
||||
user_id,
|
||||
job,
|
||||
params,
|
||||
computer_shared,
|
||||
signal,
|
||||
report,
|
||||
}: Params): Promise<BotJobOutcome> {
|
||||
@@ -90,10 +113,15 @@ export default async function runBotTask({
|
||||
* changed, whose chips the report always carries.
|
||||
*/
|
||||
const shown: string[] = [];
|
||||
/**
|
||||
* The tracker tasks the run worked on, linked under its report.
|
||||
*/
|
||||
const task_ids: number[] = [];
|
||||
|
||||
const computer = job.computer_id
|
||||
? await openComputerTools({
|
||||
computer_id: job.computer_id,
|
||||
browser: !computer_shared,
|
||||
bot_id: bot.id,
|
||||
user_id,
|
||||
workspace_id,
|
||||
@@ -145,6 +173,11 @@ export default async function runBotTask({
|
||||
* chatroom's session is hidden from them.
|
||||
*/
|
||||
const can_ask = Boolean(session_id) && !scheduled && !hooked && !params.chatroom_id;
|
||||
/**
|
||||
* The coordinator weighing a worker's install request
|
||||
* (`request_install`): it answers it with answer_install_request.
|
||||
*/
|
||||
const install_request_id = powers.is_coordinator ? Number(params.install_request_id) || 0 : 0;
|
||||
let failure = null as string | null;
|
||||
|
||||
/**
|
||||
@@ -167,7 +200,14 @@ export default async function runBotTask({
|
||||
*/
|
||||
const admin_tools =
|
||||
!powers.is_coordinator && workspace_id && powers.is_workspace_admin
|
||||
? (await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, scopes })).tools
|
||||
? (await grabWorkspaceAdminTools({
|
||||
bot,
|
||||
user_id,
|
||||
workspace_id,
|
||||
powers,
|
||||
scopes,
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
})).tools
|
||||
: [];
|
||||
|
||||
const tools = [
|
||||
@@ -181,6 +221,7 @@ export default async function runBotTask({
|
||||
admin_workspace_ids: powers.admin_workspace_ids,
|
||||
scopes,
|
||||
hooked,
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
})),
|
||||
...admin_tools,
|
||||
...(powers.is_coordinator
|
||||
@@ -194,6 +235,12 @@ export default async function runBotTask({
|
||||
workspace_id,
|
||||
scopes,
|
||||
}),
|
||||
listWorkspacePeopleTool({ workspaces: coordinator_workspaces, workspace_id }),
|
||||
setUserWorkspaceRoleTool({
|
||||
user_id,
|
||||
workspaces: coordinator_workspaces,
|
||||
workspace_id,
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
]
|
||||
@@ -235,6 +282,23 @@ export default async function runBotTask({
|
||||
]
|
||||
: []),
|
||||
...(scheduled || hooked ? [reportRunFailedTool({ onFail: ({ reason }) => (failure = reason) })] : []),
|
||||
/**
|
||||
* A worker has no sudo on its computer: it asks the
|
||||
* coordinator to install, from a task the user follows (the
|
||||
* answer wakes it there).
|
||||
*/
|
||||
...(computer && dirs.run_as && can_ask && job.computer_id && !powers.is_coordinator
|
||||
? [
|
||||
requestInstallTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
computer_id: job.computer_id,
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(install_request_id && job.id ? [answerInstallRequestTool({ request_id: install_request_id, job_id: job.id })] : []),
|
||||
...(computer?.tools || []),
|
||||
...(job.computer_id
|
||||
? [
|
||||
@@ -297,13 +361,54 @@ 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`). A routine run or a hook call,
|
||||
* which nobody watches, gets the smaller unattended limit (never
|
||||
* more than a task's).
|
||||
*/
|
||||
const task_steps = await grabHarnessMaxToolSteps();
|
||||
const install_steps =
|
||||
scheduled || hooked ? Math.min(task_steps, await grabUnattendedMaxToolSteps()) : task_steps;
|
||||
const budget = Math.floor(Number(params.max_steps) || 0);
|
||||
const max_steps = budget > 0 ? Math.min(budget, install_steps) : install_steps;
|
||||
|
||||
/**
|
||||
* What the user wrote since the run was queued, for a run they
|
||||
* follow: what's there now goes after the brief.
|
||||
*/
|
||||
const incoming =
|
||||
can_ask && session_id
|
||||
? await taskIncoming({ session_id, queued_at: Number(job.created_at) || Date.now(), user_id })
|
||||
: null;
|
||||
const arrived = (await incoming?.take()) || [];
|
||||
const brief: HarnessMessage = {
|
||||
role: "user",
|
||||
content: composeJobBrief({
|
||||
title: job.title,
|
||||
instructions: job.instructions,
|
||||
params,
|
||||
}),
|
||||
};
|
||||
const opening: HarnessMessage[] = [brief];
|
||||
|
||||
if (arrived.length) {
|
||||
pushUserTurn({ transcript: opening, content: TaskIncomingNote });
|
||||
|
||||
for (const turn of arrived) {
|
||||
if (turn.role == "user") pushUserTurn({ transcript: opening, content: turn.content });
|
||||
}
|
||||
}
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: [
|
||||
prompt,
|
||||
carry_over,
|
||||
TaskRunNote,
|
||||
`This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: pace yourself, 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 : "",
|
||||
botFilesNote({ bot_id: bot.id }),
|
||||
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
|
||||
TasksNote,
|
||||
@@ -321,7 +426,12 @@ export default async function runBotTask({
|
||||
? ""
|
||||
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
|
||||
powers.is_coordinator || hooked ? "" : AskCrewNote,
|
||||
computer
|
||||
powers.is_coordinator || hooked || params.chatroom_id
|
||||
? ""
|
||||
: crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id }) }),
|
||||
computer && computer_shared
|
||||
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files and code runners) while another run uses it, so you have its shell and files but not its browser. If the answer needs the browser, say so in your report instead of waiting.`
|
||||
: computer
|
||||
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}`
|
||||
: workspace_id
|
||||
? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.`
|
||||
@@ -345,23 +455,26 @@ export default async function runBotTask({
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: composeJobBrief({
|
||||
title: job.title,
|
||||
instructions: job.instructions,
|
||||
params,
|
||||
}),
|
||||
},
|
||||
],
|
||||
messages: opening,
|
||||
tools: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools, ...knowledge.tools],
|
||||
max_steps: await grabHarnessMaxToolSteps(),
|
||||
max_steps,
|
||||
max_prompt_tokens: await grabRunMaxPromptTokens(),
|
||||
context_budget: await grabContextBudgetTokens(),
|
||||
bot_id: bot.id,
|
||||
workspace_id,
|
||||
signal,
|
||||
onStep: (step) =>
|
||||
report({ ...step, text: step.text && computer ? computer.redact(step.text) : step.text }),
|
||||
...(incoming
|
||||
? {
|
||||
incoming: incoming.take,
|
||||
incoming_notes: {
|
||||
working: TaskIncomingNote,
|
||||
redraft: TaskRedraftNote,
|
||||
wrap_up: TaskWrapUpIncomingNote,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
if (failure) {
|
||||
@@ -378,6 +491,7 @@ export default async function runBotTask({
|
||||
}),
|
||||
attachments: attachments.length ? attachments : undefined,
|
||||
tool_log: result.tool_uses,
|
||||
task_ids,
|
||||
};
|
||||
} finally {
|
||||
await extensions?.close();
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import taskIncomingBaselineSql from "./task-incoming-baseline-sql";
|
||||
|
||||
/**
|
||||
* A task run reads what the user wrote in its session after it was
|
||||
* queued. Run against real SQLite.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE bot_messages (id INTEGER PRIMARY KEY, session_id INTEGER, author TEXT, created_at INTEGER)`);
|
||||
db.run(`INSERT INTO bot_messages VALUES
|
||||
(1, 1, 'user', 100),
|
||||
(2, 1, 'bot', 200),
|
||||
(3, 2, 'user', 250),
|
||||
(4, 1, 'user', 300),
|
||||
(5, 1, 'bot', 400)`);
|
||||
|
||||
function baseline({ session_id, queued_at }: { session_id: number; queued_at: number }) {
|
||||
const { sql, values } = taskIncomingBaselineSql({ session_id, queued_at });
|
||||
|
||||
return (db.query(sql).get(...values) as { id: number }).id;
|
||||
}
|
||||
|
||||
describe("taskIncomingBaselineSql", () => {
|
||||
test("is the session's newest message when the run was queued", () => {
|
||||
expect(baseline({ session_id: 1, queued_at: 250 })).toBe(2);
|
||||
expect(baseline({ session_id: 1, queued_at: 300 })).toBe(4);
|
||||
});
|
||||
|
||||
test("ignores other sessions", () => {
|
||||
expect(baseline({ session_id: 2, queued_at: 260 })).toBe(3);
|
||||
expect(baseline({ session_id: 1, queued_at: 260 })).toBe(2);
|
||||
});
|
||||
|
||||
test("is 0 when the session had nothing yet", () => {
|
||||
expect(baseline({ session_id: 1, queued_at: 50 })).toBe(0);
|
||||
expect(baseline({ session_id: 9, queued_at: 500 })).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { SqlCondition } from "@/src/utils/crew-access/types";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
/**
|
||||
* When the run was queued (`bots_queue.created_at`, ms).
|
||||
*/
|
||||
queued_at: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The SQL for the newest message a session had when a run was queued:
|
||||
* what the user writes after it is new to the run, however long it waited
|
||||
* for its computer or how often it was tried. Selects one `id` column, 0
|
||||
* for an empty session.
|
||||
*/
|
||||
export default function taskIncomingBaselineSql({ session_id, queued_at }: Params): SqlCondition {
|
||||
return {
|
||||
sql: `SELECT COALESCE(MAX(id), 0) AS id FROM bot_messages WHERE session_id = ? AND created_at <= ?`,
|
||||
values: [Number(session_id), Number(queued_at)],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
import isCrewMessage from "@/src/utils/is-crew-message";
|
||||
import messagesToTurns from "./messages-to-turns";
|
||||
import taskIncomingBaselineSql from "./task-incoming-baseline-sql";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
/**
|
||||
* When the run was queued (`bots_queue.created_at`, ms).
|
||||
*/
|
||||
queued_at: number;
|
||||
/**
|
||||
* Whose conversation it is.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the user writes in a task run's conversation, for the run to take
|
||||
* in (`runTextLoop`'s `incoming`): each `take` returns the messages since
|
||||
* the last, starting from when the run was queued. A crew message (a
|
||||
* room's outcome, an install answer) is left to the reply it wakes.
|
||||
*/
|
||||
export default async function taskIncoming({ session_id, queued_at, user_id }: Params) {
|
||||
const { sql, values } = taskIncomingBaselineSql({ session_id, queued_at });
|
||||
const res = await BunSQLite.sql<{ id: number }>({ sql, values });
|
||||
|
||||
let seen_id = Number(res.payload?.[0]?.id) || 0;
|
||||
|
||||
const take = async (): Promise<HarnessMessage[]> => {
|
||||
const fresh = await grabBotMessages({
|
||||
session_id,
|
||||
after_id: seen_id,
|
||||
author: "user",
|
||||
limit: AppData.BotReplyHistoryMessages,
|
||||
});
|
||||
|
||||
if (!fresh.length) return [];
|
||||
|
||||
seen_id = Math.max(seen_id, ...fresh.map((message) => Number(message.id)));
|
||||
|
||||
const from_user = fresh.filter((message) => !isCrewMessage({ message }));
|
||||
|
||||
return from_user.length ? await messagesToTurns({ messages: from_user, user_id }) : [];
|
||||
};
|
||||
|
||||
return { take };
|
||||
}
|
||||
@@ -9,6 +9,12 @@ export type BotJobContext = {
|
||||
* Saved by an earlier attempt, if the job was picked up again.
|
||||
*/
|
||||
checkpoint: Record<string, unknown> | null;
|
||||
/**
|
||||
* The job runs on its computer beside another job that holds it (a
|
||||
* chatroom job, which never waits for a busy computer): it gets the
|
||||
* computer's shell and files, never its browser.
|
||||
*/
|
||||
computer_shared?: boolean;
|
||||
/**
|
||||
* Aborted when the job is cancelled or lost to another handler. Stop
|
||||
* work and return; the result is discarded.
|
||||
@@ -51,6 +57,11 @@ export type BotJobOutcome = {
|
||||
* the result message as `tool_log`.
|
||||
*/
|
||||
tool_log?: HarnessToolUse[];
|
||||
/**
|
||||
* The tracker tasks the run worked on (`onTask` from its task tools),
|
||||
* kept on the result message as `task_ids`.
|
||||
*/
|
||||
task_ids?: number[];
|
||||
};
|
||||
|
||||
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
|
||||
import withMessageTasks from "@/src/functions/backend/db/bots/with-message-tasks";
|
||||
|
||||
type Params = {
|
||||
message: BUN_SQLITE_COBBLE_BOT_MESSAGES;
|
||||
};
|
||||
|
||||
/**
|
||||
* A message about to be pushed, with the tracker tasks it's about as its
|
||||
* session's user sees them (`withMessageTasks`). Without any, or when the
|
||||
* session is gone, it's returned as it is.
|
||||
*/
|
||||
export default async function withSessionMessageTasks({ message }: Params) {
|
||||
if (!message.task_ids || !message.session_id) return message;
|
||||
|
||||
const session = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
|
||||
sql: `SELECT user_id FROM bot_sessions WHERE id = ? LIMIT 1`,
|
||||
values: [message.session_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!session?.user_id) return message;
|
||||
|
||||
return (await withMessageTasks({ messages: [message], user_id: session.user_id }))[0] ?? message;
|
||||
}
|
||||
@@ -157,7 +157,7 @@ export default function BotSessionsModal({
|
||||
))}
|
||||
{sessions.loading ? (
|
||||
<LoadingBlock className="w-full h-[300px]" />
|
||||
) : sessions.sessions.length ? (
|
||||
) : !sessions.sessions.length ? (
|
||||
<Span className="px-3 py-6 text-[13px] leading-[18px] text-ink-secondary">
|
||||
{sessions.query.trim()
|
||||
? `No session matches "${sessions.query.trim()}".`
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { BotFace } from "@/src/dict/bot-dict";
|
||||
import { StoneEyes } from "@/src/data/stone-geometry";
|
||||
import StoneEyeDot from "./stone-eye-dot";
|
||||
import StoneEyeLidded from "./stone-eye-lidded";
|
||||
import StoneEyeArc from "./stone-eye-arc";
|
||||
import StoneEyeFlat from "./stone-eye-flat";
|
||||
|
||||
type Props = {
|
||||
face: BotFace;
|
||||
/**
|
||||
* Fill class for solid eyes.
|
||||
*/
|
||||
fill_class: string;
|
||||
/**
|
||||
* Stroke class for arc eyes.
|
||||
*/
|
||||
stroke_class: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The eyes for each face. Geometry follows the handoff face states:
|
||||
* idle dots, working half-lidded, done upward arcs, asleep one flattened
|
||||
* dot, needs-you dot plus arc.
|
||||
*/
|
||||
export default function BotStoneEyes({ face, fill_class, stroke_class }: Props) {
|
||||
const { left, right, centre } = StoneEyes;
|
||||
|
||||
switch (face) {
|
||||
case "working":
|
||||
return (
|
||||
<>
|
||||
<StoneEyeLidded {...left} className={fill_class} />
|
||||
<StoneEyeLidded {...right} className={fill_class} />
|
||||
</>
|
||||
);
|
||||
case "done":
|
||||
return (
|
||||
<>
|
||||
<StoneEyeArc {...left} className={stroke_class} />
|
||||
<StoneEyeArc {...right} className={stroke_class} />
|
||||
</>
|
||||
);
|
||||
case "asleep":
|
||||
return <StoneEyeFlat {...centre} className={fill_class} />;
|
||||
case "needs-you":
|
||||
return (
|
||||
<>
|
||||
<StoneEyeDot {...left} className={fill_class} />
|
||||
<StoneEyeArc {...right} className={stroke_class} />
|
||||
</>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<>
|
||||
<StoneEyeDot {...left} className={fill_class} />
|
||||
<StoneEyeDot {...right} className={fill_class} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,24 @@
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import type { BotFace } from "@/src/dict/bot-dict";
|
||||
import { StoneEyes } from "@/src/data/stone-geometry";
|
||||
import StoneEyeDot from "./stone-eye-dot";
|
||||
import StoneEyeLidded from "./stone-eye-lidded";
|
||||
import StoneEyeArc from "./stone-eye-arc";
|
||||
import StoneEyeFlat from "./stone-eye-flat";
|
||||
import BotStoneEyes from "./bot-stone-eyes";
|
||||
|
||||
/**
|
||||
* Idle blinks at three paces (`--animate-stone-blink-*` in `main.css`), so
|
||||
* stones side by side never blink in step. Literal class names, so Tailwind
|
||||
* sees them.
|
||||
*/
|
||||
const BlinkClasses = [
|
||||
"animate-stone-blink-a",
|
||||
"animate-stone-blink-b",
|
||||
"animate-stone-blink-c",
|
||||
] as const;
|
||||
|
||||
const FaceMotionClasses: Record<Exclude<BotFace, "idle">, string> = {
|
||||
working: "animate-stone-glance",
|
||||
done: "animate-stone-hop",
|
||||
asleep: "animate-stone-breathe",
|
||||
"needs-you": "animate-stone-nudge",
|
||||
};
|
||||
|
||||
type Props = {
|
||||
face: BotFace;
|
||||
@@ -15,46 +30,46 @@ type Props = {
|
||||
* Stroke class for arc eyes.
|
||||
*/
|
||||
stroke_class: string;
|
||||
/**
|
||||
* Leave the eyes still (the logo, static marks).
|
||||
*/
|
||||
still?: boolean;
|
||||
/**
|
||||
* Any whole number, the same for the same bot: picks its blink pace.
|
||||
*/
|
||||
motion_seed?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The face is the status. Geometry follows the handoff face states:
|
||||
* idle dots, working half-lidded, done upward arcs, asleep one flattened
|
||||
* dot, needs-you dot plus arc.
|
||||
* The face is the status, and each face moves its own way: idle blinks,
|
||||
* working glances side to side, done hops once, asleep breathes, needs-you
|
||||
* nudges. Only the eyes move; reduced motion keeps them still.
|
||||
*/
|
||||
export default function BotStoneFace({ face, fill_class, stroke_class }: Props) {
|
||||
const { left, right, centre } = StoneEyes;
|
||||
export default function BotStoneFace({
|
||||
face,
|
||||
fill_class,
|
||||
stroke_class,
|
||||
still,
|
||||
motion_seed = 0,
|
||||
}: Props) {
|
||||
const motion_class =
|
||||
face === "idle" || !FaceMotionClasses[face]
|
||||
? BlinkClasses[Math.abs(motion_seed) % BlinkClasses.length]
|
||||
: FaceMotionClasses[face];
|
||||
|
||||
switch (face) {
|
||||
case "working":
|
||||
return (
|
||||
<>
|
||||
<StoneEyeLidded {...left} className={fill_class} />
|
||||
<StoneEyeLidded {...right} className={fill_class} />
|
||||
</>
|
||||
);
|
||||
case "done":
|
||||
return (
|
||||
<>
|
||||
<StoneEyeArc {...left} className={stroke_class} />
|
||||
<StoneEyeArc {...right} className={stroke_class} />
|
||||
</>
|
||||
);
|
||||
case "asleep":
|
||||
return <StoneEyeFlat {...centre} className={fill_class} />;
|
||||
case "needs-you":
|
||||
return (
|
||||
<>
|
||||
<StoneEyeDot {...left} className={fill_class} />
|
||||
<StoneEyeArc {...right} className={stroke_class} />
|
||||
</>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<>
|
||||
<StoneEyeDot {...left} className={fill_class} />
|
||||
<StoneEyeDot {...right} className={fill_class} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<g
|
||||
className={twMerge(
|
||||
"origin-center transform-fill",
|
||||
!still && motion_class,
|
||||
"motion-reduce:animate-none",
|
||||
)}
|
||||
>
|
||||
<BotStoneEyes
|
||||
face={face}
|
||||
fill_class={fill_class}
|
||||
stroke_class={stroke_class}
|
||||
/>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,19 @@ import {
|
||||
import { botColorNeedsPaperFace, resolveBotStone } from "@/src/utils/bot-color";
|
||||
import BotStoneFace from "./bot-stone-face";
|
||||
|
||||
/**
|
||||
* How the whole stone moves for each face (`--animate-stone-body-*` in
|
||||
* `main.css`). Only transforms: the outline and its one flat cut are never
|
||||
* redrawn. The eyes move on top of this (`BotStoneFace`).
|
||||
*/
|
||||
const BodyMotionClasses: Record<BotFace, string> = {
|
||||
idle: "animate-stone-body-idle",
|
||||
working: "animate-stone-body-working",
|
||||
done: "animate-stone-body-done",
|
||||
asleep: "animate-stone-body-asleep",
|
||||
"needs-you": "animate-stone-body-needs-you",
|
||||
};
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* The bot's identity colour (`#rrggbb`). Omit (or `null`) for the
|
||||
@@ -37,6 +50,11 @@ type Props = {
|
||||
* stone (the default), so the stone is decorative.
|
||||
*/
|
||||
label?: string;
|
||||
/**
|
||||
* Leave the eyes still. Every face moves by default (`BotStoneFace`);
|
||||
* the logo and other static marks pass this.
|
||||
*/
|
||||
still?: boolean;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
@@ -44,6 +62,8 @@ type Props = {
|
||||
* # Bot Stone
|
||||
* @description A Cobble bot avatar: a stone with exactly one flat cut and two
|
||||
* eyes. Never put it in a circle, ring or badge, or add an outline or shadow.
|
||||
* The stone and its eyes move with its face unless `still`; it may hop a
|
||||
* little past its box, so it draws `overflow-visible`.
|
||||
*/
|
||||
export default function BotStone({
|
||||
color,
|
||||
@@ -52,6 +72,7 @@ export default function BotStone({
|
||||
face = "idle",
|
||||
size = 32,
|
||||
label,
|
||||
still,
|
||||
className,
|
||||
}: Props) {
|
||||
const is_coordinator = !color;
|
||||
@@ -65,6 +86,14 @@ export default function BotStone({
|
||||
const paper_face = is_coordinator || botColorNeedsPaperFace({ color: color! });
|
||||
const eye_fill = paper_face ? "fill-paper" : "fill-dark";
|
||||
const eye_stroke = paper_face ? "stroke-paper" : "stroke-dark";
|
||||
/**
|
||||
* The same bot always blinks at the same pace; different bots rarely
|
||||
* share one.
|
||||
*/
|
||||
const motion_seed = [...`${color || ""}${stone || hue || ""}`].reduce(
|
||||
(sum, char) => sum + char.charCodeAt(0),
|
||||
0,
|
||||
);
|
||||
|
||||
return (
|
||||
<svg
|
||||
@@ -74,18 +103,32 @@ export default function BotStone({
|
||||
role={label ? "img" : undefined}
|
||||
aria-label={label || undefined}
|
||||
aria-hidden={label ? undefined : true}
|
||||
className={twMerge("shrink-0", className)}
|
||||
className={twMerge(
|
||||
"shrink-0",
|
||||
!still && "overflow-visible",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<path
|
||||
d={body_path}
|
||||
fill={is_coordinator ? undefined : color!}
|
||||
className={is_coordinator ? "fill-ink" : undefined}
|
||||
/>
|
||||
<BotStoneFace
|
||||
face={face}
|
||||
fill_class={eye_fill}
|
||||
stroke_class={eye_stroke}
|
||||
/>
|
||||
<g
|
||||
className={twMerge(
|
||||
"origin-bottom transform-fill",
|
||||
!still && BodyMotionClasses[face],
|
||||
"motion-reduce:animate-none",
|
||||
)}
|
||||
>
|
||||
<path
|
||||
d={body_path}
|
||||
fill={is_coordinator ? undefined : color!}
|
||||
className={is_coordinator ? "fill-ink" : undefined}
|
||||
/>
|
||||
<BotStoneFace
|
||||
face={face}
|
||||
fill_class={eye_fill}
|
||||
stroke_class={eye_stroke}
|
||||
still={still}
|
||||
motion_seed={motion_seed}
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,17 +5,13 @@ type Props = {
|
||||
computer_id: number;
|
||||
name: string;
|
||||
mode: ComputerViewMode;
|
||||
/**
|
||||
* The mode on show; the others stay loaded but hidden.
|
||||
*/
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* One of a computer's apps in a frame. A raw iframe: twui has no
|
||||
* equivalent.
|
||||
*/
|
||||
export default function ComputerViewFrame({ computer_id, name, mode, active }: Props) {
|
||||
export default function ComputerViewFrame({ computer_id, name, mode }: Props) {
|
||||
const title = ComputerViewModes.find((m) => m.value == mode)?.title || mode;
|
||||
|
||||
return (
|
||||
@@ -23,7 +19,7 @@ export default function ComputerViewFrame({ computer_id, name, mode, active }: P
|
||||
src={computerViewUrl({ computer_id, mode })}
|
||||
title={`${name}: ${title}`}
|
||||
allow="clipboard-read; clipboard-write; fullscreen"
|
||||
className={`absolute inset-0 w-full h-full border-0 bg-sunken ${active ? "" : "hidden"}`}
|
||||
className="absolute inset-0 w-full h-full border-0 bg-sunken"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* One mode in a computer view's toolbar (Browser, Terminal, Code).
|
||||
* One mode in a computer view's toolbar (`ComputerViewModes`).
|
||||
*/
|
||||
export default function ComputerViewModeButton({ title, active, onPick }: Props) {
|
||||
return (
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import { useState } from "react";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
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 { ExternalLink } from "lucide-react";
|
||||
import { ComputerViewModes, type ComputerViewMode } from "@/src/dict/computer-dict";
|
||||
import type { ComputerViewMode } from "@/src/dict/computer-dict";
|
||||
import readComputerViewMode from "@/src/functions/frontend/read-computer-view-mode";
|
||||
import rememberComputerViewMode from "@/src/functions/frontend/remember-computer-view-mode";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import computerViewModesFor from "@/src/utils/computer-view-modes-for";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import computerViewUrl from "@/src/utils/computer-view-url";
|
||||
import pickComputerViewMode from "@/src/utils/pick-computer-view-mode";
|
||||
import ComputerViewFrame from "./computer-view-frame";
|
||||
import ComputerViewModeButton from "./computer-view-mode-button";
|
||||
|
||||
@@ -15,41 +23,52 @@ type Props = {
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The mode it opens in.
|
||||
* The mode it opens in (a take-over names one); without it, the mode
|
||||
* the computer was last viewed in on this device.
|
||||
*/
|
||||
default_mode?: ComputerViewMode;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A computer the user can work on: its browser, terminal or code editor
|
||||
* (`ComputerViewModes`), served through the app (`/computers/<id>/`).
|
||||
* A mode stays open once visited, so switching back keeps its state.
|
||||
* A computer the user can work on: its screen (Chrome as it is), and its
|
||||
* shell for crew managers (`computerViewModesFor`), served through the app
|
||||
* (`/computers/<id>/`). The mode tabs show once there's more than one
|
||||
* mode. Only the mode on show is loaded: switching closes the other (its
|
||||
* screen or shell connection goes with it, and an unwatched browser can
|
||||
* park). The mode on show is remembered per computer on this device and
|
||||
* opens next time.
|
||||
*/
|
||||
export default function ComputerView({ computer_id, name, default_mode, className }: Props) {
|
||||
const [mode, setMode] = useState<ComputerViewMode>(
|
||||
default_mode || ComputerViewModes[0].value,
|
||||
const { user_types } = useContext(AppContext);
|
||||
const modes = computerViewModesFor({ can_manage_crew: canManageCrew({ user_types: user_types || [] }) });
|
||||
const [mode, setMode] = useState<ComputerViewMode>(() =>
|
||||
pickComputerViewMode({ modes, requested: default_mode, remembered: readComputerViewMode({ computer_id }) }),
|
||||
);
|
||||
const [visited, setVisited] = useState<ComputerViewMode[]>([mode]);
|
||||
|
||||
const pick = ({ value }: { value: ComputerViewMode }) => {
|
||||
setMode(value);
|
||||
setVisited((prev) => (prev.includes(value) ? prev : [...prev, value]));
|
||||
};
|
||||
useEffect(() => {
|
||||
rememberComputerViewMode({ computer_id, mode });
|
||||
}, [computer_id, mode]);
|
||||
|
||||
const pick = ({ value }: { value: ComputerViewMode }) => setMode(value);
|
||||
|
||||
return (
|
||||
<Stack className={`w-full min-h-0 gap-0! items-stretch ${className || ""}`}>
|
||||
<Stack className={twMerge("w-full min-h-0 gap-0! items-stretch", className)}>
|
||||
<Row className="w-full gap-1! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline">
|
||||
<Row role="tablist" aria-label={`${name} modes`} className="gap-1! flex-nowrap">
|
||||
{ComputerViewModes.map((item) => (
|
||||
<ComputerViewModeButton
|
||||
key={item.value}
|
||||
title={item.title}
|
||||
active={item.value == mode}
|
||||
onPick={() => pick({ value: item.value })}
|
||||
/>
|
||||
))}
|
||||
</Row>
|
||||
{modes.length > 1 ? (
|
||||
<Row role="tablist" aria-label={`${name} modes`} className="gap-1! flex-nowrap">
|
||||
{modes.map((item) => (
|
||||
<ComputerViewModeButton
|
||||
key={item.value}
|
||||
title={item.title}
|
||||
active={item.value == mode}
|
||||
onPick={() => pick({ value: item.value })}
|
||||
/>
|
||||
))}
|
||||
</Row>
|
||||
) : (
|
||||
<Span className="px-2 text-[13px] leading-[18px] font-bold text-ink">{modes[0]!.title}</Span>
|
||||
)}
|
||||
<Link
|
||||
href={computerViewUrl({ computer_id, mode })}
|
||||
target="_blank"
|
||||
@@ -62,15 +81,7 @@ export default function ComputerView({ computer_id, name, default_mode, classNam
|
||||
</Link>
|
||||
</Row>
|
||||
<Stack className="relative grow min-h-0 gap-0! items-stretch bg-sunken">
|
||||
{visited.map((value) => (
|
||||
<ComputerViewFrame
|
||||
key={value}
|
||||
computer_id={computer_id}
|
||||
name={name}
|
||||
mode={value}
|
||||
active={value == mode}
|
||||
/>
|
||||
))}
|
||||
<ComputerViewFrame key={mode} computer_id={computer_id} name={name} mode={mode} />
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user