Compare commits

...
304 Commits
Author SHA1 Message Date
tben 9f03120526 Share one model bench between the queue and the API, and wake the jobs it parks
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A run-limits save cleared the API bundle's copy of the cooldowns while the queue kept its own benches, so a model set to rest until the setting changed stayed benched until a restart, and the job it deferred slept out its day-long available_at with nothing left to wait for.

The cooldown object now lives on a globalCache slot (cobble.harnessCooldowns), and both the run-limits save and queue startup release the jobs a rest parked ahead of time (releaseRestingBotJobs), sparing any job that really failed a turn.
2026-11-18 08:52:36 +01:00
tben 247ddd614d 0.24.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-17 20:26:05 +01:00
tben 16362595f9 Add export_file, and reconcile the files a task brief names before it starts 2026-11-17 20:07:31 +01:00
tben 3b5391f320 Open a task run with the user's own request, and never swap a named route 2026-11-17 19:41:35 +01:00
tben cd981228d5 Load a file preview and a computer's screen only when opened 2026-11-17 17:59:46 +01:00
tben 38e18cd2cf Bump version
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-17 17:48:46 +01:00
tben 799322fa13 Tell a browsing run to read the page as text before taking a screenshot 2026-11-17 17:32:49 +01:00
tben 96fa494c9e Read a vision image no larger than 1024 pixels on its longest side 2026-11-17 17:32:49 +01:00
tben 5b1ffd2202 Replace the header text area with authorization fields, and let a value point at an env
An MCP server's headers were one CodeEditor holding lines like
"Authorization: Bearer {{env.GITHUB_TOKEN}}", which had to be parsed by eye
and which silently lost how it was set up: a server saved with a key in its
own header reopened as Authorization "None" with the key as an extra header.

The form now asks for authorization directly - None, Bearer token, or API key
header with its own name - then lists any other header as a name and a value,
each added or removed on its own row. The values come from typed inputs, and
any of them can point at an env instead: a picker lists Settings >
Environment's general envs, and "New env" opens a small Key, Value,
Description modal over the form that saves a general secret and selects it
straight away. mcp-headers.ts composes and parses the map, so a bearer token
and an extra header can't both own Authorization, and a hand-written
"Authorization: Basic ..." stays a header of its own.

An MCP server's scheme is now stored (auth_scheme, auth_header), so editing
reads back the field it was written in; rows saved before the columns keep
being read the way they always were.

The browser form gets the same fields with literal values only, since browser
headers are never templated and pointing one at an install env would send that
secret to a member's own server.
2026-11-17 16:50:23 +01:00
tben 5a80f3c77b Wrap the env settings form and give an editing row its padding 2026-11-17 16:21:51 +01:00
tben 342f40620c Let any conversation's last message be run again, and say when nothing answered it
Run again only appeared on a failed reply's notice, so a stopped run or a
finished answer could not be repeated. It now sits on the bot's last word
whatever it was (answer, stopped notice, task failure), and a failed reply
keeps Retry worded for the failure.

The thinking row was also drawn from the thread's own guess, so a user
message left unanswered by a stopped or pruned run showed it forever with no
Stop beside it. The row now follows the conversation's read, and when the
thread ends on the user's message with nothing on its way it says "No answer
came." with the same button under it.
2026-11-17 16:21:51 +01:00
tben 74592067db Keep a redacted image reading for the run instead of re-reading it every turn
A browser or MCP image is always handed to the vision harness through a
redactor, and the reading cache skipped both itself and the cross-run one
whenever a redactor was set. So every turn read every screenshot again: one
reply spent 43 vision calls on 5 images, 13 of its 15 minutes.

A redacted part now keeps its reading in the run's own cache under its own
key, so it is read once per run; only unredacted readings reach the shared
cache, so a redacted reading can still never be served from an unredacted
one.
2026-11-17 16:21:51 +01:00
tben e8b4dafe55 Step through a conversation's images in the preview, bot and user
The preview's gallery was one message's images; now it is every image in the session (image attachments and named image files, in message order, deduped by URL), built by sessionImageGallery and provided by MessageThread through a context, falling back to the message's own images outside a thread. Add Previous/Next arrows at the far middle left and right of the preview, beside the header stepper and the arrow keys.
2026-11-17 14:51:00 +01:00
tben 0f335ae304 Fault a reply that writes a card ref only the app may write
The coordinator's last two replies ended with [suggestion:11] and
[suggestion:12], refs the model wrote itself after seeing a real
[suggestion:10] in an earlier message. Neither run called
suggest_next_steps, so no rows existed and the user read "next steps 11
(not available)". The reply review checked file, task and setting refs
but not the cards the app adds itself.

The review now faults any [suggestion:ID], [question:ID] or [plan:ID]
found in the model's raw answer: the app appends those refs after the
review, from the tool that made the card, so one already in the text is
made up or copied. The fault note tells the bot to take the ref out and
call suggest_next_steps, ask_user or create_plan if the card should be
there (AppCardRefTools, pinned to the declared tools by
tool-name-lists.test.ts). A [graphic:ID] is a ref the model is told to
write, so only one that doesn't exist for the user is faulted, through
grabBotGraphic.

Tests: a new review-bot-reply.test.ts covers each fault and the passing
cases; reply-ref-ids and reply-claim-problems tests grew with the new
kinds. The run-text-loop review test now mocks logError, so its "db
down" case stops writing error rows into the dev database.
2026-11-17 14:13:06 +01:00
tben 9c98620171 Show the images a bot message is about under its text
A bot message now renders its image attachments and every image [file:ID] it names as thumbnails under the text, on both the chat and crew-request lines. A file attached and named shows once; refs follow the renderer's code rules. Each opens the shared file preview with the message's images as one gallery.

Named files resolve through a cached read shared with the file chip (useBotFile/useReferencedFiles), and the files API and conversation props now carry thumbnail_url via one mapper. A thumbnail request serves the original when no smaller copy was made (mediaServeWritePath), since bot files keep no thumbnail.
2026-11-17 13:38:22 +01:00
tben 8bd968e040 Let a crew request's answer start runs and report each result back to the asker
A crew request closed on the asked bot's first reply, so an answer that
acknowledged the brief and kicked off a task was faulted as "only said the
work was under way" and the task's real result never reached the asker.

The request now stays working while any run it started is still open: the
ack is not relayed as the outcome, each started run carries the ask_id and
its result comes back to the asking bot's own conversation as it lands, and
the last result closes the request answered. The under-way fault uses the
reply review's exemption, so an answer that really called start_task or
delegate_task is not faulted for saying so; a promise with no tool call still
fails. A new update_requester tool lets the asked bot send an interim word to
the asker while the request is open, without opening another ask or session.
Stopping now reaches the visible answer session and any job carrying the
ask_id, and a follow-up ask from an answer session links as a child so the
depth and loop caps apply.

Image generation: DashScope/Model Studio hosts take references as the image
extension field on /images/generations (no multipart edits endpoint) and
answer with URLs, ignoring b64_json. A call that only reaches benched models
records a failed-call row per resting candidate so the message shows why
nothing was tried, and the error names Settings > Models.
2026-11-17 12:58:36 +01:00
tben bd1834e2b5 Fix the harness audit: runaway loops, secret leaks, SSRF, and dead guards
Work through the harness audit (.tmp/harness-audit-17-11-2026) in four
phases, with typecheck and the full test suite green after each.

High: bound the closing-tool loop and tell a mixed turn from a failed card
(H1); fire the over-quota warning that never could (H2); keep a crew-request
child task out of the user's browsers and propagate the run kind (H7); stop
a redacted image reading being served from the unredacted cache (H3); refuse
a member secret that repoints a wider-scope env and a templated MCP URL host
(H6); validate provider image URLs (https, internal-host refusal, redirect
re-check, byte cap, HarnessError wrapping) (H4); pin browser URLs to their
validated IPs, fail closed on the docker lookup, and cover IPv6 and every
IPAM config while keeping the LAN allowance (H5).

Medium: growth-only write quota (M7); empty /models no longer wipes the
catalog (M1); re-check a repaired answer before sending it (M3); stop
re-trimming a head+tail result to a stub (M4); place embeddings by index
(M5); header-only provider timeout with classified body aborts (M2); redact
key-shaped tokens from provider errors (M8); cap MCP pagination and HTTP
bodies, refuse redirects (M11); key the stdio pool per env and kill the
process tree (M12); close read-only classifier gaps (M13); snapshot every
repo a destructive command touches, ignored files for clean -x, and surface
a failed snapshot (M6); one shared video deadline and a download cap (M9);
check image dimensions before decode and honour abort (M10).

Low: explicit tool ok flag (L1); Retry-After floor (L2); forever-rest
sentinel in failure rows (L3); coordinator ignores workspace harness rows
(L4); task empty-report guard, plan-step open-work count, defensive turn
copy, exact truncation count (L5); encoding-aware secret redaction (L6);
quoted restore paths, unique snapshot names, prune by patch, room===0 guard
(L7); SHA-256 media keys, empty-transcript error, finite vectors (L8); gate
the image_edit hand-over on fallback and label failures per candidate (L9);
disambiguate long MCP tool names, redact setup logs, own-mode usage scope
(L10); doc corrections (L11).

Also close the latent reviewer findings reached along the way: an
already-aborted computer command (R2, bumps the computer image to 1.4.3),
the reference-blob URL path (R7), the never-throw usage guard (R11), core
chat fields spread first (R12), hardened tar import (R13), and a prompt
custom tool filling a secret value into the model's input - secret envs now
fill as their [KEY] marker there (R1).

Align the user-bubble clamp test with the bubble's 24rem height.
2026-11-17 11:57:01 +01:00
tben f1bf88c434 Send only the settings a model advertises, and retry a failed reply
A custom provider's /models lists ids only, so its models advertise no
parameters. The old rule read unknown support as accepts-everything, so a
temperature saved on another model rode to one that rejects it and every
reply failed. A model now takes only what its provider advertises: the form
hides Model settings for such models, the wire sends only advertised values,
and switching the model or provider clears the saved settings and voice.

A failed reply's notice carries its job (bot_messages.failed_job_id) and shows
Retry while it still needs you. Retrying re-queues a reply with params.retry_of,
clears the notice's needs_you, and bypasses the silent-finish gate. Failure
notices are the app's record, never the bot's words, so they stay out of history.
Replies only.
2026-11-17 08:36:33 +01:00
tben 4209fd9647 Bump version
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-17 04:54:41 +01:00
tben c21bafb737 Close the ways work went quiet, and ask before changing the crew
A review of the queue, the turn loop and the consent gates found 29 ways a
run could go silent, act on nobody's word, or lose what it produced. Each
one is fixed here.

Stuck and lost work:

- A task claim took three jobs for one computer, so every task slot sat
  waiting in `computer_lock` behind the one running, and replies stalled
  with them. A claim now takes one job per computer and skips a computer
  that already has one (`claim-bot-jobs`).
- A send stored the prompt and then enqueued in the same try: a throw left
  a message with no job behind it, so the thinking row stayed up for good.
  The insert, the enqueue (which deletes the message if it fails), the
  attachments and the push are now separate steps, and `client_id` makes a
  resend idempotent instead of posting the prompt twice.
- `open_jobs` in the catch-up read tells the thread whether a reply is
  still to come, so a job that ends without a message can't leave the row
  up (`grab-session-open-replies`, `useReplyCatchUp`).
- A completed job inserted its answer after marking itself done: a throw
  lost it, with no notice. The answer lands first (and is taken back if
  the completion fails), and nothing in the way of clearing up can lose it.
- A failed plan step left the plan active with nothing to advance it: it
  is paused now (`pause-failed-plan-step`).
- Deleting a bot left its open crew requests `working` forever, costing
  the asker its cap: they end with a reason and wake the asker
  (`end-asks-for-bot`).
- A deferral refunded the attempt even when the run had spent real tool
  work; cancelBotJob failed a possibly-running job without aborting it or
  fixing the face; a face stayed `working` while only pending jobs were
  left; a failed row with no bot was rescanned every poll. All four are
  fixed, and the face now has one place that decides it
  (`bot-face-after-job`, `answering-ask-face` keeps a crew request's
  answer on show).

Acting without consent:

- `set_workspace_computer` was the one workspace mutation with no role
  check.
- Any run could rewrite a bot's core instructions and core memory: those
  are the admin's now, and a refusal says what to use instead.
- Schedules and irreversible crew deletion are off for a hook call (whose
  payload is someone else's words) and for any run nobody is following.
- A hidden session no longer gets secret cards or questions nobody can
  answer; `can_ask` checks `isHiddenSession` too.
- Answering a secret card no longer closes it on a swallowed failure: the
  user gets a button that sends the bot the message it never got.
- Redaction skipped values under four characters, and `read_message_usage`
  answered for any job id, not the run's own session.

Silently lost or wasted work in the loop:

- A reply is cleaned before review (unresolved `[setting:]` refs, app
  record lines, work claims), and a refused closing tool or a card with no
  text no longer ends the run on a sentence that promises something that
  isn't there.
- The wrap up no longer marks a message answered, a session carry-over
  takes queued replies with it, and a trimmed remembered result is read
  again instead of answered with "its output is above".
- An oversized newest result is cut last instead of sent whole, an empty
  answer fails with a reason rather than an empty bubble, orphan question
  cards are deleted, a reply that ran out of steps marks its task
  exhausted, and a throwing review is logged instead of swallowed.

AGENTS.md's two drifted lines are corrected (the crew request's face and
the task run's `can_ask`).

Verification: bun run typecheck clean; bun run test 2117 pass, 0 fail.
2026-11-17 04:54:27 +01:00
tben 99f47ffe36 Bump version
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-16 12:32:36 +01:00
tben f068f7f58e Plan hard work with the user, then work it a step per reply
Replies that tried to do everything at once came out long and hard to
follow. A bot can now lay the work out as a plan instead.

`create_plan` stores one plan per conversation (`bot_plans`) and the reply
shows it as a card: its steps, where they stand and what it is for. The plan
goes nowhere until the user acts on it there, and they can rewrite its steps
first (steps already done stay as they are, `planStepsRewriteProblem`).

Once approved, each step is its own reply job (`params.plan_id`) with the
bot's tools, memory and browsers, one step per reply with a short report,
and `continueBotPlan` queues the next one: nothing follows while the user is
being asked something, while work was handed off (`WorkStartingTools`), or
when the plan was paused, ended or a reply already waits in the conversation.
A routine gets its plan approved at once and works it to the end in the run
(`ScheduledPlanNote`).

Bots are also told to keep a plan in memory when the same work comes back,
so a way of working survives as a runbook.

The card is built from spans, since its ref sits inside the message's
paragraph.
2026-11-16 07:39:22 +01:00
tben b860dfe859 Catch a forged app record by its shape, so the correction can be sent
A reply that claimed a start_task it never called was rightly stopped, but the
check searched the whole answer for the phrase, so the bot's own correction -
"the [App record: ...] line was mine, not the app's" - tripped the same fault.
Three faults, the rewrites ran out and the job failed: the lie stayed in the
thread and the apology never reached the user (message #801, run #468).

- app-record-claims: only a line in the app's record shape naming tools this
  reply didn't call is unsupported. A line the record supports - the old lie
  quoted after really calling start_task - and a mention inside a sentence or
  code span pass; strip-app-records now shares that one line shape.
- A fault note never quotes the text it faults or says "a report will follow",
  which is itself pattern 4: the note had been teaching the model the string
  that re-faulted it, and every reply's prompt already ships that shape in
  ActionCheckNote. Tests pin both.
- ask_crew left over from 03e062d's rename in WritingToolNames,
  WorkStartingTools, HandOverTaskNote and the hand-over description: a reply
  that really had asked the crew was faulted for saying it was working.
  tool-name-lists.test.ts pins those lists to the tools the harness declares.

Verification: bun run typecheck clean; bun run test 2052 pass, 0 fail
2026-11-16 06:07:33 +01:00
tben 5ba7747e11 Catch a reply that says it started a run it never started
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A reply claimed "I'm starting the hydration work as a single-route proof"
with no tool call behind it and the run ended there, so nothing ran. The
review missed it twice over: `claimsWorkUnderWay` had no pattern for the
phrasing (only "once the run is back|done|finished|complete", never
"once the run reports"), and the model wrote the app's own
"[App record: ...]" line itself, naming `update_task, start_task`, which
made the debug view read as tools having run.

The record line is the app's to write, so an answer forging one that
claims tools is now faulted and sent back; a mimic that only says
"called no tools" is still just stripped, so a formatting habit cannot
burn rewrites or fail a reply.

`update_task` also never moved `updated_at`, so a task whose status just
changed did not rise: `grab-tasks` orders by it, and the other task
helpers set it themselves.
2026-11-15 19:07:05 +01:00
tben ca070ccc35 v0.21.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-15 17:36:23 +01:00
tben 3268f049f9 Retry a ref chip's read, so its steps and card show without a reload
A failed or hung read was kept as a miss for the life of the page, so a [suggestion:ID] or [question:ID] pushed with a run showed 'not available', or nothing at all, until the page was reloaded. One loader now keeps only what was read, aborts a read that hangs, and tries again.
2026-11-15 17:36:23 +01:00
tben 2d57ba560c v0.21.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-15 10:34:59 +01:00
tben c1c307e51c Call a split task's work subtasks, and let a subtask open its parent 2026-11-15 10:32:39 +01:00
tben 7bc74dfe8e Split a workspace-wide task into parts, and let any task join or leave one
A workspace-wide task (`workspace_id`, `bot_id` null) can now be split into
parts: one bot each, one level deep, with `tasks.parent_task_id` pointing at
it. A bot task joins or leaves a parent through `update_task`
(`parent_task_id`, `unlink_parent`) and crew managers through "Make it a part
of..." and "Unlink from parent" on the task's panel; both sides get a note.

The parent stays open until someone verifies every part, and the rules live
in one place each: `subtaskLinkProblem`, `subtaskAttachProblem`,
`subtaskMoveProblem` (refused by `moveTask`, so promotion and hand-over both
decline a task that is a part or has parts) and `subtaskDeleteProblem`
(deletion takes finished parts with it, refuses while one is open).
`AppData.TaskSubtaskMaxPerParent` caps a parent's parts.

The workspace dashboard's task list now starts with the workspace-wide tasks
and then each bot's, cut to `AppData.TaskSectionShown` rows with the rest in
`WorkspaceTasksModal`, and a wide row wears the workspace's picture
(`WorkspaceAvatar`) instead of a crew glyph.
2026-11-15 10:04:53 +01:00
tben c705da17a1 v0.21.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-15 07:58:31 +01:00
tben f9f2a9b0b6 Hide a crew request's bar when there's no session to return to 2026-11-15 07:58:31 +01:00
tben 5d2ac342f0 Take a dropped session's job rows with it
Foreign keys are off outside the server process, so a helper that deletes a
parent row deletes its children. A crew request's hidden review session was
dropped with only its traces and tasks, leaving the review job that had just
ended, its queue updates and what its calls were billed pointing at a session
that no longer existed: the next `bun db:schema` refused the database
(bots_queue -> bot_sessions, token_usages -> bot_sessions).

The empty review session now goes through deleteSessionRows, and so does the
empty active session reopening closes, which had the same bare delete. Checked
against a copy of a real database: the review's session, job, updates, traces
and billed calls go together, while a session with an open job, with a message
or an answer's own session stays.
2026-11-15 07:50:58 +01:00
tben f453796a8d Let a bot's own models win in a workspace
Picking a model for one bot inside a workspace changed it for every bot
there: the Models modal saved the workspace's setting when it was opened
in a workspace (bot_harness_form), and resolution read the workspace row
before the bot's, so the group setting shadowed any per-bot pick.

A bot's own models now win, its workspace's apply to the bots that have
none of their own (the coordinator there included), then the defaults.
The modal in a workspace saves the bot's own models again ("Same as the
default" drops them), the workspace's Models page stays the group
fallback and the coordinator in a workspace still edits it, and the modals
name whose models they change. The picker that decides the order is its
own module, tested.
2026-11-15 07:44:25 +01:00
tben fac3f66896 Never send an answer the review still faults
The gate ran once per run, so a model that repeated itself word for
word had its claim delivered: a reply said a run was under way, was
sent back for it, and came back identical to the user.

Review now checks every answer the run writes, a bounded number of
times (AppData.HarnessReviewRewrites), tells a model that wrote the
same message back that it did (repeatedAnswerNote), and past the
bound returns review_note instead of the text: the reply job fails and
says so (BotJobFatalError), so nothing the app knows is wrong goes out.
2026-11-15 07:36:55 +01:00
tben 4292a2fa40 Spin the rail row of a bot that has work running
The face alone was too quiet at 32px: a bot answering elsewhere or working
on a task looked idle in the rail. A working bot now shows an arc in its own
colour where its relative time was, and the time comes back when the work
ends. Nothing goes on the stone: no ring, badge or corner mark.
2026-11-15 07:28:11 +01:00
tben 0d2c683933 Show a crew request's bar at the top of its conversation 2026-11-15 07:09:44 +01:00
tben 381e5d3107 v0.21.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-14 16:28:07 +01:00
tben c14df6c049 Show a task's id in the task list
A bot's list named its tasks by title alone, so a user reading a task's
`[task:ID]` in a message, a report or a debug log had no way to match it to
the row. Every row now carries `#<id>` after its title (a task with no title
keeps `Task <id>`), inside the same button, so clicking it opens the task.
The button's content wrapper shrinks, so a long title truncates and the id
stays visible.

Pinned by task-list-item.render.test.tsx.
2026-11-14 16:26:38 +01:00
tben ece7cdd36f Keep a question in the conversation it was asked in
A delegated job's report was relayed verbatim into the requester's
conversation, so a worker's [question:ID] showed the same card in two
sessions: answered in one, left waiting in the other (and the card sent
its answers to whichever bot's page was open, so the worker that asked
never heard).

stripQuestionRefs takes those refs out of text copied into another bot's
conversation (a relayed report, a crew request's outcome, an install
request's answer) and the relay says which bot is waiting instead. The
answer and skip routes now post the user's message into the question's
own session (postBotQuestionAnswers), never the page's bot.
2026-11-14 16:25:53 +01:00
tben ed13455d60 v0.21.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-14 15:29:24 +01:00
tben 03e062d9ec Ask another bot through the coordinator's gate, not a chatroom
A worker that needs another bot's work calls `ask_bot` with one brief. The
coordinator reviews it in one turn with no tools (`runAskReview`) and answers
bounded JSON: approve, redirect to a better bot, or refuse with a reason
(`AskDecisionSchema`, `applyAskDecision`). An approved request becomes one
reply job in a new session of the target's conversation for the request's
workspace (`enqueueAskAnswer`), so the run keeps its workspace context; the
brief lands there as a crew message naming that workspace, and the answer
comes back to the bot that asked as a message that wakes it (`finishAsk`).
The gate fails closed, and the app owns reach, membership, depth and the open
cap while the coordinator's instructions own the judgement.

The user can follow it: the target's row says which bot is answering whose
request, an outcome carries an `[ask:ID]` pill that opens the session it ran
in, and that session has a bar back to the conversation the request
interrupted. Requests read their status with `list_asks` instead of guessing
ids, and files the asker can't reach are copied into its folder.

Chatrooms are gone: the tables, the hidden room sessions, the pages, the
tools (`ask_crew`, `ask_member`, `answer_requester`, `refuse_request`), the
relay and the rail section. Ended requests are pruned after `ask_keep_days`
and `ask_max_per_place`, and the sessions of old chatrooms are deleted at
boot (`migrateChatroomsToAsks`).
2026-11-14 15:28:02 +01:00
tben 61d3b1de18 Replace a stale find, and answer a browser action that never settles
One production task run spent 58 turns building a single Canva text box and
reported nothing. Five browser_click calls each died on Playwright's 5
second action timeout, waiting for an element to be visible, enabled and
stable while the page animated, and the run only found browser_evaluate on
its own at turn 27. The same run called browser_find ten times, and every
one of those results stayed in the transcript for the rest of the run:
supersedeToolOutputs replaced only browser_snapshot, so the newest ten page
trees were resent on all 61 turns. 2.33M input tokens for one heading.

isSnapshot is isPageState now, matching browser_snapshot or browser_find.
Bucketing stays by tool name, so the newest snapshot and the newest find
each survive and one never evicts the other, and a failed call still
replaces nothing.

An action that timed out waiting for its element to settle is answered
with browserSettleTimeoutNote, from browserRecoveryHint: the page
animates, so the same call times out in the same place however often it is
made, and browser_evaluate drives it instead. It fires only on that one
failure and only for a browser tool, so a bad target still gets
Playwright's own message, which already names the fix. The 5 second
timeout is unchanged: the click still fails, it just fails usefully now.
SupersededSnapshotNote covers both readings, so it says "snapshot or find".
2026-11-14 13:10:52 +01:00
tben dd2447f262 Keep the work a destructive command would discard, and tell a run what is on disk
One production task run ended with three fixes written and none of them in
the tree: it had stashed its own work, run `git checkout -- .` and popped
the stash, and the pop restored the untracked files but not the tracked
edits. It spent the rest of the run re-reading the same file and reported
from memory, because the work it described was gone and nothing said so.

A command that would throw uncommitted work away (`isDestructiveGit`:
`git checkout --`, `restore`, `reset --hard`, `clean`, `stash`,
`switch -f`, `rm`, `worktree remove`) is now snapshotted first, into the
bot's own folder rather than the repository (`.cobble/pre-destructive/`,
newest 40 kept): the tracked diff, the index, and each untracked file as a
new-file diff, since a new module is what a run creates most often and what
`git clean` deletes. The tool result names the patch and how to apply it,
so a run that discarded its own edits can get them back instead of
rediscovering the loss. Verified against a real repository: modified file,
new file and nested new file all came back with `git apply` after
`git checkout -- .` and `git clean -fd`.

Repeats: `computer_bash` was never a repeat, so forty `cat` and `grep`
calls re-ran and re-entered the transcript every turn. It is keyed now
when the command provably only reads (`isReadOnlyCommand`: a read-only
program, no redirect, no `tee`/`xargs`, no writing git subcommand),
which also stops it clearing what was remembered.

Trimming was invisible: `fitTranscriptToContext` cuts old tool output down
to 60% of the working context, and the run kept asking again for what had
been cut. It is told now, every `AppData.HarnessTrimNoteEvery` trimmed
turns (`contextTrimmedNote`, traced as `trimmed`).

The wrap up is told what is on disk: a task run passes
`Params.wrap_up_note`, which runs `worktreeSummary` over the run's folders
(`git status --porcelain` and `git diff --stat` per repository, nested ones
included) and puts the machine's own account in front of the wrap-up
prompt. `TaskRunNote` also says the tree wins over the brief, and that
handing the rest on with `start_task` is finishing the task.

Debug view: `capTraceText` keeps a tool argument's `path` whole past
`BotTraceArgumentsMaxChars` (`toolArgumentPath`), so a trimmed write still
names the file it wrote.
2026-11-14 13:06:48 +01:00
tben c36f8e3736 v0.20.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-14 04:58:39 +01:00
tben 70ef0e6ae2 Ignore the Playwright MCP server's output folder 2026-11-14 04:56:36 +01:00
tben 2a7ea3c76b Cap the naming transcript, and tell a run its prompt no longer fits
A 30,000 character prompt is refused by default (bot_message_max_chars
is 20,000) and, once allowed, is stored and sent whole: nothing clips
user text. Two places then paid for it silently.

- name-bot-session.ts sent the session's opening verbatim, so a pasted
  brief cost a second copy of itself in the naming call. Each message
  is cut to BotSessionNameMessageChars (2,000) with a note that the
  opening goes on.
- fitTranscriptToContext never trims user messages (the request must
  not be lost mid-run), so a prompt over the working context was sent
  anyway and the run was never told. It now reports over_budget, and
  run-text-loop pushes oversizedRequestNote once: work in pieces, stop
  pasting whole files in, say what it could not reach.
2026-11-14 04:56:03 +01:00
tben 7ffce997ce Keep the answer a run writes before it puts up a card
A reply was only the run's last message, so an answer written in a turn
that also called a tool was dropped: a bot listed the PR links the user
asked for and then called list_tasks, which TaskReminderNote told it to
do after answering, and the user was sent the short "still open" line
alone. same for a count written next to ask_user.

A turn that answers and put up ask_user or suggest_next_steps now ends
the run with that answer (ClosingToolNames), after the usual review. Any
other tool after a written message tells the run once, answerNotSentNote,
that the message never went out.
2026-11-14 04:45:02 +01:00
tben d80899b756 Cut a long user message to twenty lines behind Read more 2026-11-14 04:41:38 +01:00
tben 3671d9b72e Release v0.20.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 18:54:55 +01:00
tben 78d7f66528 Show trace code blocks on the theme's sunken surface
The debug logs rendered tool arguments and answers through twui's default
CodeBlock, whose block is a fixed #28272b: in light mode the text stayed
dark on dark, and it came out larger than the log around it.

A shared SunkenCodeBlock puts code on the theme's surface at 13px with the
copy icon and label recoloured, and now backs the trace blocks, the
message code block and the file preview.
2026-11-13 18:52:51 +01:00
tben 09b8269ced Bound what one run may spend, and make it land the work
A task run on a production install spent 30M prompt tokens over 195 turns
and wrote none of the rows it was asked for. Everything it did was
research: it re-derived the same four facts five times, re-read its own
engine in slices twenty times, and re-paid for the same failing command
five times. Nothing in the harness ever asked when the work would start,
and the ceiling it could hit was 40M, past the point where reaching it
would have meant anything.

- `RunMaxPromptTokens` is 4M, not 40M: the bound that always holds (step
  limits are unlimited by default) now arrives while a run still has
  budget to act on it.
- A run is told once, a quarter in and only while it has produced nothing,
  to land one piece of the work end to end (`commitEarlyNote`,
  `isWritingTool`, `AppData.HarnessRunTokensCommitShare`). It is also told
  once at half the budget to land the rest (`tokensLowNote`), and the wrap
  up follows.
- A trimmed tool result keeps its start and its end (`TrimmedKeepChars`)
  instead of being replaced whole. It used to say "call it again if you
  still need it", so runs did, paying twice for output they already had.
- An identical call that failed is answered from its failure past one
  retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`,
  `failedToolCallNote`). `repeatToolCallKey` could only ever dedupe reads,
  so a broken command cost a turn every time it was repeated.
2026-11-13 18:47:56 +01:00
tben 8b30480ceb Load the debug view's own chunks, keeping the page in budget
The strip and the Details modal's Debug logs tab are lazy imports now:
most visits never open either, and together they tipped the
conversation page's initial JS 1 KB past its 450 KB budget (451 KB).
They load when they are opened (449 KB initial, budget holds), with
the panel chunk emitted beside the page bundle, so nothing is fetched
for a debug view nobody asked for.
2026-11-13 16:16:38 +01:00
tben 7356494ff2 Bump version to 0.20.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 16:12:05 +01:00
tben f08940341b Add a context window placeholder and reformat two files 2026-11-13 16:12:05 +01:00
tben 915692a9ee Show what a run did, step by step, in a debug view
A bot's thinking row now carries a bug button beside Stop: it opens a
250px strip under the row that streams the run's steps as they happen
and remembers being open per user, so it follows them across bots.
Hovering a line opens that step whole, from what the model reasoned
to what a tool was sent and answered.

Every step is kept in the new bot_job_traces table (turns, tool calls
and the loop's own events: wrap up, redraft, review, incoming, steps
running out), capped per entry and per run, redacted of env secrets,
and pruned after bot_trace_keep_days (7 by default, Settings >
General). A finished run's entries are tied to the message it ended
in, so that message's Details modal has a Debug logs tab, and its own
Copy debug logs.

The provider's reasoning is now read (reasoning, reasoning_content or
think tags) and kept for the debug view alone, never shown as the
answer. Tool calls report how long they took, and a read that was
answered from an earlier answer says which step answered it.
2026-11-13 16:11:58 +01:00
tben 8b1b7d9c64 Let a computer command run with no time limit at all
A bot's bash command was capped four times over, silently: 270 seconds in
`ComputerCommandMaxSeconds`, ten minutes by the harness's per-tool
deadline, two hours per task attempt, and an hour inside the agent. Long
scripts (a build, an install, a sweep) were cut with no way to ask for
more.

`computer_bash` now has no limit unless the bot names `timeout`, and then
that is what it asks for (`commandTimeoutSeconds`; `ComputerCommandMaxSeconds`
0 means no cap). A tool can name its own deadline now
(`HarnessTool.timeout_ms`, `null` for none) and `run-tool-call.ts` leaves
such a call to the run's signal. A task run has no attempt deadline
either (a reply keeps its two hours): Stop, a lost lock and the process
ending are what end it, and Stop still kills the command's whole process
group.

The agent has no ceiling left to hit. Measuring it turned up a last one:
Bun's `fetch` drops a connection that stays silent for about six minutes
(`TimeoutError` at 360s, whatever the `AbortSignal` says), so a long
command lost its output on the way home. The agent now opens the answer
and writes a space every `CommandHeartbeatMs` while the command runs, then
the JSON, which `JSON.parse` still reads.
2026-11-13 14:16:01 +01:00
tben 45556b3b7f Bump version to 0.19.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 13:31:34 +01:00
tben 956a6b9772 Restore a running reply's step after a reload
The thinking row's step only ever came from `server:bot-job-update`, so a
refreshed conversation sat on its label until the run's next step, and a
socket that dropped silently left it there.

The reply's step is read from the server now: with the history
(`grabSessionReplyStep` through `openSessionReplyStepSql`, the open reply
job's newest tool step) and by the catch-up (`session-messages`), which
replays it as the push it would have been. `use-reply-progress` takes it
as a seed and only ever moves forward in `bots_queue_updates` ids
(`isNewerStep`), so a read that lands just before a newer push cannot take
the row back a line, and a step from another session never shows.
2026-11-13 13:28:28 +01:00
tben 3209828723 Bump version to 0.19.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 12:56:37 +01:00
tben 0d38268fef Let a hand-over only move a task, and ask before work starts
Handing a task to another bot started it by default: it went to doing and
queued a run, so handing three tasks over "to wait for the go-ahead" ran
three jobs that each only reported they were waiting.

handOverTask now only moves the task, as to do, with no job; `start: true`
(the user asked for the work to begin now) is what sets it doing and queues
the run. hand_over_task and delegate_task pass that only when the user asked
and are told to ask first with one ask_user card for every task they named,
since a worker can't start a task once it has left its list. The UI's hand
over form gains a "Start it now" toggle, unchecked by default, and the
coordinator and workspace-admin prompts say the same.
2026-11-13 12:52:01 +01:00
tben 41be1b6fb1 Make a release mean the whole chain, watched to the end
CI / check (push) Canceled after 0s
2026-11-13 12:15:40 +01:00
tben 37bd3335ff Bump version to 0.19.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 12:12:22 +01:00
tben 0a6d7d7410 Let a worker hand on a task of its own, and stop rooms closing over live work
A worker told to hand its tasks to another bot had no tool for it: it asked
the crew instead, the coordinator answered over the Software Engineer's
still-running job (closing the room cancels it), and the answer said the
tasks were picked up. Nothing had moved.

hand_over_task passes an open task of the worker's own list to a bot it
could already ask, reporting back in its session. answer_requester and
refuse_request now refuse over a live job unless close_anyway says
otherwise. ask_user and suggest_next_steps stay out of hidden sessions,
where no card exists to answer and a bare ref reached the coordinator.
2026-11-13 12:12:18 +01:00
tben 7a0e16a6b5 Show what a chatroom's bots spent, message by message and in total 2026-11-13 11:55:58 +01:00
tben 0885e12a8b Bump version to 0.18.10
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 11:42:18 +01:00
tben 7da9003e7b Walk the user's earlier messages in the composer
Up recalls the message the user sent before (the newest from an empty
input, older ones from there), Down comes forward again and back to what
was being typed, a keystroke takes the input back, and an open mention
menu or a selection keeps the arrows. Only the user's own messages, never
a crew message.

A clear button (X, disabled while the input is empty) empties the text
without sending it, keeping the quote and the picked files.

The composer now reads ordered lists from digit markers only: Tiptap also
takes `a.` and `i.`, so a recalled "Ok. Do another pass on the browser."
came back as item 401 with "Ok." eaten as the marker, while the thread
(remark) always showed it as plain text.
2026-11-13 11:41:16 +01:00
tben b609d72888 Let a bot offer its next steps, one click from the input 2026-11-13 11:22:12 +01:00
tben 8e1084263c Bump version to 0.18.9
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 09:56:07 +01:00
tben e4e19ade1b Let a run have no limit, and make no limit the default
Every run limit was a number, so an install that wanted a bot to work
until the job was done had to guess at one, and the guess was wrong in
both directions: 300 steps cut long work short, and raising it to 10,000
made every short reply look like it had room to ramble.

- Each limit of Settings > General > Run limits can now be unlimited, and
  the three step limits are unlimited by default: a task, a chat reply and
  a routine or hook call run until their work is done, bounded by the
  job's own deadline and the run's prompt-token budget, which always
  holds. A failed model can rest for good too, until the setting changes
  or the app restarts.
- `RunLimit` (`src/utils/run-limit.ts`) is a number or `"unlimited"`, read
  by `read-run-limit` and saved as `-1` from the form (still `0` for the
  code's default), so no caller has to tell 0 from "no limit" any more.
- `run-text-loop` drops its step ceiling to Infinity, skips the low-steps
  warning and the notes that count steps left, and spends the model's own
  window when the working context is unlimited; a task run is told it has
  no step limit rather than "at most N steps", always plans first, and
  never ends exhausted.
- A rest with no end stays benched until the setting changes or the app
  restarts: saving the run limits clears the cooldowns, and the failure
  log and the "every model is resting" error say so instead of promising
  a retry in a minute.
- `token_usages` and `harness_call_failures` record `"unlimited"` as what
  the run was allowed, and the usage chip, the message details and the
  bot's own report say it rather than showing a number nobody set.
- The form labels each field (twui only draws its label with `showLabel`),
  reads a limit that's off as `Unlimited`, and fills in the default, or
  the number that was there, when its switch goes off.
- `BotStepLimitMax` is 10,000, so a limit the user picks can be as wide as
  the work needs.
2026-11-13 09:56:07 +01:00
tben 5b09e7a8db Let a bot name the setting that stopped it, and show what a run cost
A bot that hit a limit could only say "in Settings > General", and a
user asking why one answer cost so much got a guess: nothing told the bot
which page held the value, and the limits a run worked under were never
written down.

- `[setting:<section>:<field>]` renders as a pill naming the group and the
  field, opening `/admin/settings/general/<section>#<field>`
  (`src/dict/general-settings-dict.ts`, `SettingRefChip`), and every group
  of that page now has a page of its own with the same section in it:
  whoever may change it gets the form, everyone else reads the live values
  and who can raise them, since that is what a member sent there needs.
- `read_settings` gives every run the values, who may change them and the
  ref to write; `SettingsNote` tells it to name the setting, its value and
  its ref rather than pointing at a page in prose. `reviewBotReply` sends
  back a ref the app can't resolve, like a made-up file.
- `read_message_usage` reads a message's or a job's calls: the model, the
  prompt and cached tokens, what ran, and the cost drivers (steps resend
  the whole transcript, a long session re-reads it every reply), with the
  refs for the limits and for starting a session sooner.
- Every model call records the limits it ran under
  (`HarnessCallSettings.limits`, from `run-text-loop`), so a diagnosis
  compares then against today instead of assuming, and the message's
  details show them.
2026-11-13 08:47:56 +01:00
tben 1a2e7a25bb Let a provider declare its context window, and give runs room to work
A custom provider lists model ids and nothing else, so every
`harness_models.context_length` stayed null and `run-text-loop` assumed
32,000 for a model with a 1M window: 70% of that became the working
context, so the transcript was trimmed to 13,440 tokens and the run was
told to read the same files again, turn after turn, until its steps ran
out. The sync overwrites that column on every run, so editing the row by
hand never held.

- `harness_providers.context_length` is a field on the provider form
  (Settings > Models), and the sync writes it into every model that
  reports no window of its own (`modelContextLength`). Models that do
  report one keep theirs, so OpenRouter needs nothing.
- `HarnessUnknownContextWindow` (131,072) is what a run assumes when
  nothing declares a window, and `HarnessAutoMinContext` is back to
  32,000, its own job being the floor for automatic picks: at 131,072 it
  would have filtered out every 128k model.
- The defaults now suit work that takes hours: `HarnessContextBudgetTokens`
  200,000, `HarnessMaxToolSteps` 300, a task attempt at 2 hours, and tool
  results, file reads and task briefs large enough that a whole document
  arrives in one call (`HarnessToolResultMaxChars` 60,000 above
  `BotFileReadMaxChars` 55,000), so a run stops paying a call to see the
  rest of what it just read.
2026-11-13 07:30:32 +01:00
tben c892cda0eb Plan a task run before it starts, and read a file once
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A task run used to work out what the task was while spending its steps:
the same file read again to see it once more, the same folder listed
twice, a plan formed turn by turn at the price of a model call each.

- `planBotTask` spends one turn before the first step on the very system
  prompt the run then sends, so the provider's cache serves it and it
  costs little more than the plan. The bounded JSON plan
  (`BotTaskPlanSchema`) opens the run as `taskPlanNote` and shows as its
  first step line. `shouldPlanBotTask` keeps it off short runs and
  chatroom turns, and a plan that can't be written starts the run the way
  it always did.
- `runTextLoop` answers a read it already made from that answer
  (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`)
  instead of running it again; any non-read tool clears what was
  remembered, so a file read, edited and read again is read again.
2026-11-13 05:14:07 +01:00
tben b8fd60608d Stop letting a run that did nothing end as a finished task
Five honest "I did nothing" reports in a row left nothing to notice them
by, so the app now has an opinion of its own:

- A reply's wrap up offers start_task beside write_file and import_file,
  so work it can't finish in 20 steps is handed on with a brief instead of
  being promised for later.
- A run that used every step it had blocks the task it was handed
  (trackerTaskEnding), rather than leaving it open under a "run finished"
  note.
- A full workspace names the folder holding the space and whether the run
  can clear it (computerWorkspaceSpace), the agent reports the folder
  sizes with its usage, a failed measurement no longer reads as 0, and a
  daily cron logs a computer past 80% of its quota.
- A message's details count its run's calls by tool (MessageToolsRollup),
  so 242 calls read as one line rather than 242 rows.
2026-11-13 04:59:18 +01:00
tben 1bf50b717b Bump version to 0.18.7
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 04:42:16 +01:00
tben c6697c91cd Hold the full pull before letting go reloads it
Opening the room is easy to do by accident on a thread whose scroll is
already exhausted, so reaching the limit no longer reloads on its own: the
finger has to stay on the full room for half a second, which lights the icon
so the release is the user's decision, and a release before that closes the
room and reads nothing. A finger that rests fires no further touch moves, so
a timer notices the hold, not the moves, and dragging back down starts it
over.

The gesture's geometry and its hold now live in AppData with the other
conversation timings, and the refocus debounce both use-refocus and
use-connection-epoch were carrying separately is one AppData.RefocusGapMs.
2026-11-13 04:38:19 +01:00
tben 8d7309084f Refresh the conversation when the page comes back, and let a phone pull it
A thread that missed its pushes while the phone slept kept its thinking row
and a stale face until the page was reloaded. Every return to the page
(window focus, a hidden tab visible, back online) now reads the crew again
(api/admin/bots/live-crew -> cobble:live-crew-refreshed, taken by both
rails) and the session's latest messages, its bot's face and its task,
whether or not a reply is due, which is what the catch-up refused to do
before. The history is not reloaded: that would drop the older messages
loaded above it.

On a phone, pulling the thread up past its bottom lifts the newest message
off the edge, opening just enough room for a refresh icon (a ghost button,
no label) and letting go once that room is full reloads the conversation and
the rail, with the spinner up for at least a second. The room is written
straight onto the content as the finger moves, never through a render, the
pull owns the gesture until release, and a finger that rested first is a
selection, not a pull.
2026-11-13 04:27:08 +01:00
tben 6f26222e2c Bump version to 0.18.6
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-12 20:59:39 +01:00
tben 343fdb2d25 Make every bot ask before it widens a request
A production coordinator was asked only to create two bots. It placed
both in a workspace and handed each a task, then explained the extra
steps as the user's saved preference that new bots get put to work.

- RequestScopeNote, injected into every reply and task, says the request
  sets the scope, that memory, habits, routines and initiative never
  widen it, and that crew changes (create, place, remove, assign a
  computer, change a role) and handing work out (delegating, handing over
  a task or routine) happen only after the user asked for them: one
  ask_user card in a reply or task, and a proposal in the report where
  nobody watches (routine, hook call, chatroom).
- A decline is dropped, not done smaller and not re-offered.
- The memory sections of composeBotPrompt say memory shapes how the bot
  does the work, never what it does beyond the request.
- The default coordinator prompt says a request to create a bot is a
  request for that bot alone; existing installs keep their stored prompt
  and get the rule from the note.
2026-11-12 20:59:35 +01:00
tben 1a0bcb8360 Bump version to 0.18.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-12 20:47:51 +01:00
tben 181b7f9e30 Keep a profile's extension state and clear the host's old images
Recreating a profile's caches at every start also took Storage/ext,
which holds what an extension keeps rather than what Chrome rebuilds:
Cookie-Editor and every other extension lost their settings on each
container restart. Only caches go now, and the two GPU cache folders
that were missing are cleared with the rest.

A host updated for a year still held every older tag of the app's image
and every computer image the app had pulled, since the installer removed
only the tag the previous container ran. It removes them all now, and
docker refuses the ones a container uses.

Computers move to the image that reports its workspace: the layout name
changed, so migrateComputerLayout recreates each one, keeping its
workspace and browser profile.
2026-11-12 20:45:41 +01:00
tben d7e66a5123 Keep computer caches off the data volume and shrink data archives
One install's production archive was 2 GB: 2457 MB of computer
workspaces (983 MB of npm, pip and bun caches, plus 697 MB of
node_modules and 446 MB of pip installs), 993 MB of Chrome profile
caches, 148 MB of database snapshots and 15 MB of bun-sqlite scratch
space, against 178 MB of bot files. Runs had HOME on the mounted
workspace and no cache variables, so every side cache was persisted
forever, and the archiver tarred the whole volume with one exclusion.

- Runs keep their caches inside the container: computerCacheEnv points
  XDG_CACHE_HOME, npm_config_cache, PIP_CACHE_DIR,
  BUN_INSTALL_CACHE_DIR and PYTHONPYCACHEPREFIX at the account's own
  home, never the run's folder.
- prune-computer-caches (daily) clears what earlier runs left in bot
  folders, user folders, workspaces and Chrome profiles, skipping a
  computer with a task queued or running. The agent clears a profile's
  regenerable cache at each start and caps its HTTP cache.
- listArchiveExclusions is the one definition of what a data archive
  leaves out, as exact member paths (--no-wildcards --exclude-from):
  computers, Chrome profile caches, db/.backups and .bun-sqlite. A
  restore keeps the running install's db/.backups, since no archive
  carries them, and still leaves computer folders live.
- A computer's workspace has a quota (computer_workspace_quota_mb,
  Settings > General, default AppData.ComputerWorkspaceQuotaMb): the
  agent measures it, the app refuses a write past it and warns after
  computer_bash and browser calls.
- An upload's bytes go with the messages that carried them, and
  prune-orphan-media takes what is left after
  AppData.MediaOrphanKeepDays; moved-aside old computer homes are
  pruned after AppData.ComputerOldHomeKeepDays.
- install.sh removes the image the previous container ran and dangling
  layers, so updates stop accumulating gigabytes on the host.
2026-11-12 20:36:46 +01:00
tben 03e372d38d Keep the end of a long tool result and let the wrap up save the report
Two runs in a row measured to their last step with the report unwritten.
Long `du`/`find` output lost its tail twice (the bash tool kept 40k with
head and tail, then run-tool-call sliced the first 20k of it), so the
totals a sweep ends with were cut away and the run re-ran the command
until the steps ran out.

- run-tool-call and capToolOutput keep their result's start and end, the
  note sized before the cut so the whole result stays inside the cap.
- ComputerCommandMaxOutputChars matches HarnessToolResultMaxChars.
- The wrap up keeps write_file and import_file for a saving turn (then
  answers with no tools), so a run out of steps can still save its report.
- The save-first warning scales with the run (a tenth of its steps, never
  below HarnessStepsLowWarning) instead of a flat 5 steps.
2026-11-12 20:03:42 +01:00
tben 615ba5a9b9 Stop re-attaching and re-reading one old file on every reply
A reply was handed the files of the latest messages that have any, so in a
long conversation the last upload never aged out: one screenshot stayed
attached for session upon session, and since the text model is catalogued
text only it was read by the vision harness on every reply (7 calls, about
1,500 output tokens and 35 seconds each, in production).

- liveAttachmentMessages bounds an attachment by how far back it is too
  (BotReplyAttachmentMaxAgeMessages), then by BotReplyAttachmentMessages:
  older files are named, not attached.
- Readings are kept across runs in MediaReadings (HarnessMediaReadingsCached)
  keyed by imageReadingKey, so an image the conversation carries is read
  once rather than once per reply; a reading made to redact a secret is
  never kept there.
- The Models page says when the text model is listed as taking text only
  while "Use the model's own media reading" is on, which was silently
  useless for a provider that lists bare ids (guessModelModalities).
2026-11-12 19:21:12 +01:00
tben 6a808d8417 Bump version to 0.18.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-12 18:42:33 +01:00
tben 585b77eec1 Copy a message's whole details from its Details modal
The Details modal under a bot message now has a Copy report button: it
puts that message's whole details on the clipboard as one markdown
document, every call and failure it took included rather than only the
first the modal lists. The modal and the report share their at-a-glance
facts and the failure-source wording, and the route takes full=1 to list
up to AppData.MessageDetailsCopyMaxCalls calls.
2026-11-12 18:42:27 +01:00
tben 74693cccd3 Bump version to 0.18.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-11 04:39:23 +01:00
tben 115113247f Give the coordinator its skill, server and tool tools in a workspace too
- grabCoordinatorExtensionTools was pushed only in the coordinator's own
  chat: both workspace branches returned before it, so a runbook asked for
  inside a workspace had no propose_skill to write it with, and the bot
  saved a file and called the skill created
- Pushed before the workspace split, so it comes wherever the coordinator
  works; the tools still return nothing unless the run's user is the super
  admin, and each re-checks on call (assertSuperAdminRun)
- grab-bot-chat-tools.test.ts pins all three cases: a workspace, a
  workspace with no worker (the empty-crew return) and its own chat
- AGENTS.md records it
2026-11-11 04:39:20 +01:00
tben 14fc5e9d6e Bump version to 0.18.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-11 02:55:00 +01:00
tben 84ae51c621 Reset fallback models when changing the model provider in model settings 2026-11-11 02:49:28 +01:00
tben 60e3d3bfbf Pace task step budgets and prevent redundant pre-check queuing and question loops 2026-11-11 02:32:53 +01:00
tbenandClaude Opus 5.5 ab384ff175 Release v0.18.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 14:33:12 +01:00
tbenandClaude Opus 5.5 700a2bcd86 Describe each user's role per workspace for the bots there
A crew manager can now write who a user is in one workspace: plain text,
separate from the user's bio, which the user never sees or sets.
workspace_user_roles holds one role per user per workspace. Every bot in
that workspace reads the role in its prompt whenever it works for that
user, in chat replies, tasks, routines and hooks. The role never appears
in a bot's own chat or in another workspace.

The super admin can set anyone's role, their own included. An admin can
set anyone's except a super admin's (canSetWorkspaceUserRole, checked
again in setWorkspaceUserRole). Roles are set from the workspace's
settings (People: everyone who works there) and from the user's settings
(Roles in workspaces). The coordinator can set them too, through
list_workspace_people and set_user_workspace_role. Its saves count as
made by the run's user and are read back to check they took.

A role is kept when the user loses access to a workspace and comes back
with it. Deleting the workspace or the user deletes it explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 14:32:23 +01:00
tbenandClaude Opus 5.5 14d4c10782 Release v0.18.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:44:56 +01:00
tbenandClaude Opus 5.5 26424560da Open the computer picker from the computer line in the conversation header
The computer under the bot's name is now a button opening the same
computers modal as the menu's Computer row: switch computers when there's
more than one, or open one in the viewer. The menu's row stays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:44:26 +01:00
tbenandClaude Opus 5.5 ece7ebf1b2 Log model failures under LLM and show failed calls in message details
Model failures get their own LLM log category instead of System; older
"Model failed" rows move at boot. Each failed model call is also recorded
in harness_call_failures (model, pick, status, the provider's reason,
rest) and attached to the message its job posts, including the failure
notice, so a message's details list the calls that failed and why.
Failures are pruned with the logs' retention.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:14:54 +01:00
tbenandClaude Opus 5.5 7bdd288f36 Open the models modal from the model line in the conversation header
The model under the bot's name is now a button opening the same models
form as the bot's settings, for whoever can edit them there; others
still see plain text with who can change it. The menu's Models row stays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:04:10 +01:00
tben 9dab068827 Send question card answers without a confirm dialog 2026-11-08 13:02:09 +01:00
tbenandClaude Opus 5.5 ef84c8a245 Keep a running computer out of "failed", refuse runs on a down one, and show generated images
A layout migration whose image pull timed out left the old container
running but marked the computer failed, and nothing checked it again.
Now a setup that fails while the old container runs keeps it running
(retrying the migration after an hour), and a failed computer whose
container docker runs is revived by sync-computers and on first use.

start_task refused nothing, so a bot queued work on a failed computer
and the run retried three times before failing. start_task now refuses
a down computer, and a task run on one fails at once with a message
saying who can bring it back.

generate_image attaches what it makes unless told not to: a coordinator
asked the user to judge three versions it never sent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:02:03 +01:00
tbenandClaude Opus 5.5 4cfbf6f558 Add video generation and video editing models, and a generate_video tool
Two new harnesses, video and video_edit, with settings in Settings > Models
and per bot and workspace. Neither picks automatically (no video model is
free); video editing hands over to the video generation models that take
videos, as image editing does.

A video is a job at the provider: asked for, checked on until done, then
downloaded from the provider itself. OpenRouter takes frames, references
and videos to change; other providers get OpenAI's (Sora) form. Bots get
generate_video only while a video model is set up for them, and it saves
the video to their files like generate_image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 12:35:52 +01:00
tbenandClaude Opus 5.5 572b5d239a Make the chat message limit an app setting and show why a send failed
The composer only put a failed send's reason in the editor's tooltip, so a
message over the limit just came back with no visible error. It now checks
the length before sending and shows the reason under the input, as it does
for any failed send.

The limit moves from a literal 4000 in the schema to
AppData.BotMessageMaxChars (default 20,000), saved per install as
bot_message_max_chars under Settings > General > Messages (super admin),
and checked again by the send route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 12:00:55 +01:00
tbenandClaude Opus 5.5 419a50b95b Release v0.17.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 10:02:37 +01:00
tbenandClaude Opus 5.5 c4c86fc66b Set up a new install from a backup, and restart after a database restore
First-run setup can now restore another install's database file or
whole-data archive instead of creating a super admin. The upload is told
apart by its bytes, refused once any account exists or for a database
with no accounts, restored like Settings > Backups, and the app restarts
onto it.

Settings > Backups' database restore swapped in a new file from a
separate process while the server kept its handle on the old one, so
everything written until the next restart was lost. Database restores now
run in the background and restart the app, like data archive restores.
Log entries for a restore are queued in the data folder and written at
boot, into the restored database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 10:02:37 +01:00
tbenandClaude Opus 5.5 c924ff9776 Release v0.16.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 09:24:14 +01:00
tbenandClaude Opus 5.5 5d79c379dd Give task chips their colours in dark mode too
The chip is a twui ghost button, whose own dark fill and text won over
the chip's light-only classes, so in dark mode it lost its background
and took the wrong text colour. It now sets both for each theme, like
the link chips beside it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 09:23:42 +01:00
tbenandClaude Opus 5.5 ebc9ade7e0 Link bot messages to the tracker tasks they're about
Which tasks a message concerns is now the app's record, not the bot's
word: a run's task tools report every task they read in full, add, move
along or hand over, plus a handed-over job's task, into
bot_messages.task_ids (also on its failure notice and the report relayed
to the requester). The thread shows them under the message as chips with
title and status, read per viewer and only for tasks they reach, on
loads and live pushes alike.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 09:23:39 +01:00
tbenandClaude Opus 5.5 ea4b5c1bf2 Have bots check the next step with ask_user instead of deciding
The proactive note asked for a next-step question in text, the questions
note only allowed asking when the bot couldn't tell what the user would
pick, and the coordinator prompt said to pick a sensible default. Next
steps and choices that are the user's now go on an ask_user card, in
replies, user-started task reports and the coordinator's prompts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 08:53:37 +01:00
tbenandClaude Opus 5.5 4063cd3b22 Show a file's full path beside its size in the preview
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:57:14 +01:00
tbenandClaude Opus 5.5 3bd749428e Release v0.16.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:38:37 +01:00
tbenandClaude Opus 5.5 cd6702de55 Lead back to the last conversation from settings and the rail pages
The last-visited cookie now records the workspace too (`<bot>:<workspace>`),
the landing page still reading only the bot. Settings and the rail pages get
that conversation, access-checked, as `last_conversation`, shown above their
rail list as a way back naming the bot and its workspace.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:38:37 +01:00
tbenandClaude Opus 5.5 1a6ae71286 Keep replies on the picked model, with fallbacks of its own
A production chat dropped from the pinned DeepSeek to a free Nemotron
after one failed call mid-run, and every reply for the next half hour
ran on it: it called browser tools from chat replies, then said it had
no browser. Nothing recorded why.

- A failed model (or provider, for a key or credits) rests for the
  install's model rest, 2 minutes by default (Settings > General run
  limits, harness_model_rest_seconds), never longer, Retry-After
  included. A refused request (400, 422) benches nothing.
- The text model takes up to 3 fallback models, from any provider,
  tried in order after the pick and before the free automatic picks
  (fallback_model_ids in the setting's options; defaults, bots and
  workspaces).
- A run that fell back to an automatic pick goes back to the pick or
  its fallbacks once they've rested.
- Every model failure is logged with the provider's error and its rest.
- A message answered in place of the model ahead of it shows the
  fallback on its usage chip; the details list what failed and what
  was passed over while resting.
- A computer or browser tool called from a reply is told to start a
  task instead of getting a list of names.
- The work-under-way check catches "I'll open/drive/check ... now /
  directly / and see" with no run started.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:31:36 +01:00
tbenandClaude Opus 5.5 7cc881f1da Release v0.16.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:37:58 +01:00
tbenandClaude Opus 5.5 b717220bc3 Let task runs hear the user mid-run
A production run kept a verdict the user had overruled while it worked,
and the reply to the correction queued a second run that redid the first.

- Task runs the user follows take in what they write in the conversation
  since the run was queued: at the start, between steps, past a report
  not yet out, and by the wrap up (no steps left: the report says what it
  changes). A correction changes the work; anything else is left to the
  chat, and crew messages to the reply they wake. Routines, hook calls
  and rooms are unchanged.
- runTextLoop takes the caller's notes for what came in (incoming_notes)
  and, with a wrap_up note, reads it before the wrap up too.
- A reply is told which of the bot's runs are open in its session and
  hear the user, so a correction never starts another; start_task's
  open-run refusal says the same.
- The reply's message-to-turn reading is shared (messagesToTurns).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:32:17 +01:00
tbenandClaude Opus 5.5 6e153d311e Stop the crew asking for the same files three times
A production chat took three chatrooms to get two files from one bot,
hit the step limit twice with the report unwritten, and spent three runs
on hand-overs that only said they were waiting.

- A room's answer copies every file it names that the asking bot can't
  read (a member saves to its own folder) into the asker's folder under
  crew/room-<id>/, and points the refs at the copies.
- ask_crew refuses a second open request from the same place unless it's
  separate, and task runs, which see only their brief, are shown their
  bot's open and recent requests.
- update_task unlinks files with unlink_file_ids (a task holds 20), and
  list_tasks with task_id lists what's filed.
- A long run is told once, 5 steps before the wrap up, to save its report.
- delegate_task with start: false hands a task over without starting it.
- Prompt notes: task reports speak to the user as "you"; a bot goes with
  the user's reading once overruled; a crew answer isn't the go-ahead and
  silence isn't an answer.
- Quoting a message reads each ref chip as one inline label instead of a
  paragraph per chip; a copied chat says "Task #27", not "Task task #27".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:06:25 +01:00
tbenandClaude Opus 5.5 6532abc715 Release v0.16.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 05:55:47 +01:00
tbenandClaude Opus 5.5 be4eb13a7c Cut the tokens every run resends
Production spent 284M prompt tokens against 4M written: every turn resends
the system prompt, tool definitions and whole transcript, and on 1M-window
models a run was only trimmed near 730k tokens (one routine run spent 39M,
one task ran 401 steps).

- A working context (Settings > General, 80k tokens by default) caps what a
  turn sends whatever the model's window, counting tool definitions too.
  Old tool output, then long tool call arguments, are cut in one block
  down to 60% of it, so the cached start of the prompt holds between cuts.
- Routine runs and hook calls stop at 40 steps by default, and any run
  wraps up once it has sent 4M prompt tokens; both are settings.
- Only the newest page snapshot of each browser stays in a run, and
  browser results are capped at 12k characters.
- MCP server tools and a user's browser tools are listed by name and
  loaded with load_tools when their definitions are large, instead of
  riding along on every turn.
- token_usages records cached_tokens; the Usage page and message details
  show the cached share.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 05:55:47 +01:00
tbenandClaude Opus 5.5 86d171729f Keep chatroom work moving when the asked bot's computer is busy
A chatroom job no longer waits behind the job holding its computer (often
the asking bot's own run, which could take an hour): it runs beside it with
the shell and files but no browser. Room jobs no longer count when a bot's
face is put back after another job ends, so a bot doesn't show work in its
own chat that only happens in a room. ask_crew tells bots not to start a
task that needs the answer in the same reply.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 05:35:32 +01:00
tbenandClaude Opus 5.5 38648fc083 Release v0.15.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 12:57:54 +01:00
tbenandClaude Opus 5.5 6414d4e675 Let bots learn from the user's reactions
A reply's history now shows the user's own reactions on each bot message
in its app record, and the chat reply note tells the bot to save the
lasting preferences they show in its memory of that user. Adds a Dislike
reaction so a bot can tell what to avoid.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 12:57:54 +01:00
tbenandClaude Opus 5.5 ae64ef195d Release v0.15.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:37:53 +01:00
tbenandClaude Opus 5.5 06a4b7bb36 Step through a folder's images in the preview
An image opened from a list (a folder, the Files page, the chat's files
modal, a message's images) gets that list's images as a gallery:
Previous and Next in the header and the arrow keys step through them in
the same modal, each opening at its own fit, neighbours preloaded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:37:53 +01:00
tbenandClaude Opus 5.5 2c8023ee4b Release v0.15.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:02:22 +01:00
tbenandClaude Opus 5.5 c0e79ee39c Open folder chips in a modal and give image previews zoom and fits
A folder chip opens the folder's listing over the chat, files opening
their own preview on top; a modified click or Open in Files still goes
to the files browser. Image previews get a viewer: 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 and drag to pan. Escape closes only the top modal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:02:22 +01:00
tbenandClaude Opus 5.5 bc9739509c Release v0.15.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 10:27:02 +01:00
tbenandClaude Opus 5.5 4d6c330954 Have worker bots work in their own home on computers
A worker now works in /home/cb-<bot>/workspace/users/<user> (cwd, HOME
and ~), with its bot-wide folder at /home/cb-<bot>/workspace and, in a
workspace, the shared folder at /home/cb-<bot>/workspace/workspaces/<id>.
Only /home/cb-<bot>/workspace is kept: the agent makes it a link to the
bot's folder on the mounted workspace (bots/<bot>), and workspaces/<id>
in it a link to the workspace's shared folder, checking both on every
request and putting back one that's gone. Nothing on disk moves, so
existing work opens at the new paths.

Paths are checked on their real place (computerWorkspacePath), so the
real spelling still works, and shown to a worker its own way
(computerRunPath). Computer folder refs take either spelling. The
coordinator keeps working in the computer's workspace.

Computer image 1.3.0; the layout bump recreates every computer once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 10:27:02 +01:00
tbenandClaude Opus 5.5 78accbcc4f Release v0.14.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 08:48:20 +01:00
tbenandClaude Opus 5.5 5601e2c2b8 Keep ref forms out of the generated CSS
Comments in pages, hooks and types name refs like [task:ID], which
Tailwind read as arbitrary properties and emitted as "task: ID", so the
build warned it isn't a CSS property. The ref forms are now excluded as
candidates wherever they're written.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 08:48:20 +01:00
tbenandClaude Opus 5.5 7c678284ae Check replies against the app's record, budget runs and let bots delete tasks
A reply wrote "I'm scanning the contests now" and the scan's made-up
results in one answer, with no tool called and a file that didn't exist,
and the user built tasks on it. Before a reply goes out, reviewBotReply
now sends it back once when it names a file or task that doesn't exist
for the user, or says work is under way or a report will follow while
nothing was started and nothing is open from the conversation. A long
bot message whose run called no tools shows "No tools used".

start_task takes max_steps, enforced below the install's limit, and
task runs are told to stop and report when several tries leave them no
closer. Chat replies the user follows get delete_task (never routines,
hook calls or rooms), so a bot deletes a task instead of cancelling it
and calling it removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 08:48:20 +01:00
tbenandClaude Opus 5.5 8c868d6a04 Render task descriptions and notes as markdown
The task modal showed a task's description and notes as raw markdown.
Both now render through the message elements (TaskMarkdown): formatted,
raw HTML never rendered, links opening in a new tab and refs as their
chips, with the page's crew when no conversation gives one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 08:35:45 +01:00
tbenandClaude Opus 5.5 179ff03d20 Release v0.14.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 07:37:58 +01:00
tbenandClaude Opus 5.5 0a19c2a3a9 Let bots rename tasks and queue follow-up runs instead of promising them
update_task now takes a title and brief, refusing an open twin's title,
so a bot fixes a task's name instead of offering a second task. start_task
says different work is queued at once with separate, and the chat reply
note says nothing wakes a bot when a run ends, so it never promises to do
something once a run finishes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 07:37:58 +01:00
tbenandClaude Opus 5.5 c3be864136 Load message markdown in any order and link workspace refs in rooms
The file preview merged the message markdown elements at module load,
but those reach the preview again through their file chips, so loading
them first crashed. It merges them when it renders now. Chatrooms and
hook call threads give their chips the user's workspaces, so a
[workspace:ID] there links instead of showing its number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 07:28:16 +01:00
tbenandClaude Opus 5.5 e40fa823cb Show task refs as chips and link refs in a workspace's context
A bot's [task:ID] now renders as a chip that opens the task's detail
modal, and bots are told to write it when they name a task. The
workspace dashboard's context runs through linkComputerRefs with the
crew contexts, so bot and workspace mentions show as chips there too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 07:25:44 +01:00
tbenandClaude Opus 5.5 4593decc13 Look for nft in the computer image build instead of running it
CI / check (push) Canceled after 0s
nft opens a netlink socket even for --version, which the emulated arm64 build has none of, so the v0.14.0 computer image failed to build. 1.2.0 was never published, so the fixed build keeps that tag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 06:06:56 +01:00
tbenandClaude Opus 5.5 0512dd3e10 Release v0.14.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 05:56:20 +01:00
tbenandClaude Opus 5.5 f9f6fa5a93 Recover computers whose setup the app lost to a restart
A computer left 'creating' by a process that's gone stayed "Setting
up..." forever: the sync skipped it, and Retry and Rebuild were refused.
Setups and restarts now touch the row every 30s; one untouched for 3
minutes shows as failed with Retry, and sync-computers starts it again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 05:55:24 +01:00
tbenandClaude Opus 5.5 ddaf6aa720 Add a lightweight browser setting for computers on small hosts
A computer's browser settings get a Lightweight browser switch (off by
default). With it on, Chrome runs with --disable-gpu (the GPU process
loads no Mesa or LLVM, so WebGL is off), forced reduced motion, no
smooth scrolling, no component updates and none of its background
features (optimization guide downloads, media router, translate,
autofill lookups), and Xvnc caps the screen view at 20 updates a second.
On a 1-CPU computer this took idle CPU from about 18% to 7% and memory
from 482 to 401 MiB. Sites see no WebGL, which fingerprinting scores as
less ordinary, so it stays a per-computer choice.

Chrome reads only one --disable-features/--enable-features, so the
agent's list and the user's extra flags are merged (mergeFeatureFlags).

Computers' health checks also run every second during the start period
(Docker 25+), so a ready computer is marked healthy sooner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 05:45:10 +01:00
tbenandClaude Opus 5.5 876cc0ff4c Open up a worker's file copied for the browser
cp keeps the source's mode, and a worker's files are 0660, so the copy
staged for the browser couldn't be read by it. The copy is now chmod
0644; the stage folder itself stays the computer user's and the worker's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 05:45:10 +01:00
tbenandClaude Opus 5.5 4137fed085 Let the app container join extra docker networks from Settings
Settings > General gets a Docker networks section (super admin) listing
networks the app's own container joins, e.g. a tunnel's or a database's.
Computers never join them. Networks are picked from the ones docker
lists on this machine, minus host, none, the computers' network and any
the container is on for another reason.

The list is the app setting app_extra_networks, so it lives in the
database and outlasts install.sh recreating the container on an update.
The app joins the networks itself over the docker socket
(syncAppNetworks): at boot, on save (leaving removed ones) and every
five minutes, since a network removed and made again drops its members.
A missing network or a refusal is logged once and retried. Outside
docker (a dev server) the list is only kept. The installer's
--extra-network still works beside it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 05:35:35 +01:00
tben 3eced5886e Give worker bots their own accounts on computers
Every worker bot now works on a computer as its own Linux account
(cb-<bot id>, no sudo), owning its folder; a workspace's folder belongs
to a group its bots share. Only the coordinator works as gem, with sudo.
gem, and so Chrome, can't open worker folders: downloads, uploads and
files saved by name are copied by the worker's own account, and workers
open no file: URLs.

The computer's own services (agent, DevTools, Playwright MCP, VNC, ttyd)
are kept from worker accounts by an nftables rule, so containers get
NET_ADMIN; without the rule the agent refuses worker commands. The X
display needs gem's cookie. File reads for a worker are checked on the
open descriptor, and writes are made as the worker.

Workers ask the coordinator to install system packages with
request_install: a coordinator task in the super admin's conversation
weighs it and answers, and the answer wakes the worker. Stop ends a
worker's leftover processes on its computers.

Computer image 1.2.0; the layout bump recreates every computer once.
2026-11-06 05:22:10 +01:00
tbenandClaude Opus 5.5 877fcf82e0 Release v0.13.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:47:56 +01:00
tbenandClaude Opus 5.5 f6b5795ed6 Load only the computer view's mode on show, and reopen the last one
The computer modal kept every mode it had shown loaded in hidden frames,
so a Browser tab left behind the Shell still held the screen connection
(and kept the browser from parking). Now only the mode on show is
loaded: switching closes the other.

Each computer's last mode is remembered on the device (localStorage) and
opens next time; a take-over still opens in the mode the bot asked for,
and a mode the user can't open falls back to Browser.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:47:56 +01:00
tbenandClaude Opus 5.5 f08d12a176 Release v0.13.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:14:18 +01:00
tbenandClaude Opus 5.5 f61676ca08 Park an idle computer's browser so it stops burning CPU
The computer's screen has no GPU and no window manager, so the tab in
front is always on show and Chrome draws its animations in software at
full rate whether or not anyone watches: one animated site kept a
production computer at 200% CPU.

- The agent parks the browser after COBBLE_BROWSER_PARK_AFTER_SECONDS
  (default 180, 0 turns it off) without a /mcp call or a screen view: a
  blank tab goes in front of every site on show, as a person switching
  tabs would, so pages keep their connections and see nothing unusual.
  The next /mcp call or screen view brings them back before it goes
  through. Done over the agent's own small CDP client (the image's Node
  has no WebSocket).
- Chrome composites pages in software (--disable-gpu-compositing):
  about half the CPU while a bot works, WebGL unchanged.
- The managed policy sets TabDiscardingExceptions so a parked tab is
  never discarded and reloaded.
- The screen's websocket bridge now closes when a viewer goes away
  without a close frame; it used to stay half open for good.
- Computer image bumped to 1.1.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:06:46 +01:00
tbenandClaude Opus 5.5 4cc70e7f35 Release v0.13.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:28:42 +01:00
tbenandClaude Opus 5.5 e83e1e4951 Show the composer's Browser button only when the user has a browser
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:28:42 +01:00
tbenandClaude Opus 5.5 1543fa160f Release v0.13.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:02:09 +01:00
tbenandClaude Opus 5.5 72086ffa38 Replace the AIO sandbox with our own computer image
Computers now run our own image (computer/, Debian 13): real Google Chrome
on amd64 (Debian's Chromium on arm64), headful on Xvnc with no automation
flags, so sites like Google treat it as a normal browser. One small Node
agent supervises the screen, the session bus, Chrome, Playwright MCP and
ttyd, and serves a single token-guarded port.

- Browser view: the computer's screen over noVNC, so Chrome shows whole
  (tabs, address bar, menu, extensions, prompts); Ctrl/Cmd+V pastes the
  viewer's clipboard (HTTPS or localhost). Cookie-Editor is installed by
  default.
- Shell view (ttyd), for crew managers only.
- The /computers/<id>/ proxy passes only the view paths, never the agent's
  API or MCP.
- Per-computer browser settings (super admin): timezone, languages, screen,
  scale (125% by default, larger text in bots' screenshots), sandbox and
  extra Chrome / Playwright MCP flags, with unsafe flags refused.
- Rebuild computer: pulls the image again and recreates the container;
  files and logins stay.
- Bots' computer tools are the app's own (bash, read/write/edit file) plus
  Playwright MCP; downloads move into the run's folder, MCP's snapshot and
  console files point at the tools that read them.
- Release workflow builds and pushes ghcr.io/moduletrace/cobble-computer
  for amd64 and arm64 once per tag.

Existing computers are recreated on the new image at boot (files and
browser profiles stay); run db:schema for the new browser_settings column
(the installer does this).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:02:09 +01:00
tbenandClaude Opus 5.5 40af378915 Release v0.12.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 07:00:21 +01:00
tbenandClaude Opus 5.5 d8e63d1e3b Move the whole stone with its face
The stone breathes, rocks, hops, sinks or wobbles from its base under the
eyes' own motion. Transforms only: the outline and its cut never change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 07:00:21 +01:00
tbenandClaude Opus 5.5 7da2bd6941 Release v0.12.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 18:52:59 +01:00
tbenandClaude Opus 5.5 5842735813 Animate bot faces by state
Only the eyes move: idle blinks at a per-bot pace, working glances side
to side, done hops once, asleep breathes, needs-you nudges. Off under
reduced motion; the logo stays still.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 18:52:29 +01:00
tbenandClaude Opus 5.5 6312c92334 Show the sessions modal's empty note only when the list is empty
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 17:04:44 +01:00
tbenandClaude Opus 5.5 63d25337f5 Release v0.12.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 16:41:24 +01:00
tbenandClaude Opus 5.5 3cbfb4e3da Restore workspace-wide tasks, set by admin bots or by hand
A task still belongs to one bot by default. A workspace task can now be
workspace-wide (no bot) when asked for: every bot working there sees it,
works on it and logs what it did. On such a task update_task records each
call's status move and filed files as a note under the bot, 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) turn a bot's open workspace task
workspace-wide; hand-over gives one back to a single bot. Other bots can't
switch or claim tasks. The boot step that gave bot-less tasks a bot is
gone, and a leaving bot's workspace-wide tasks stay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 16:41:24 +01:00
tbenandClaude Opus 5.5 ace6a61a1a Release v0.12.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 15:24:18 +01:00
tbenandClaude Opus 5.5 d7ce96339b Let bots crop, resize and adjust images without a model
transform_image runs ordered steps (crop, resize, rotate, flip,
grayscale, blur, sharpen, adjust, trim) with sharp on raw pixels, so
the order is the bot's, after turning the source upright by EXIF. The
source is a file the run reaches or the user's own upload, checked like
a picture source, never SVG. Crops take pixels or percent, the result is
saved as a new file and a preview goes back to the bot so it can check
the crop landed.

It is named "transform", not "edit", so it can't be mistaken for the
image_edit model setting, and its description and generate_image's
point at each other: content changes go to generate_image with a
reference, cutting and adjusting to transform_image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 15:23:33 +01:00
tbenandClaude Opus 5.5 c60402831f Put a new workspace at the top of the rail
A workspace nobody visited yet ranks by when it was created, so one just
made leads the list instead of falling below every visited one and out
of the shown slice.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 15:15:37 +01:00
tbenandClaude Opus 5.5 b0bad82b78 Tell bots when a tool call names arguments the tool doesn't take
Zod dropped unknown keys silently, so a coordinator that sent the
workspace's id under the wrong name kept hearing that no id was given,
retried update_workspace fourteen times and blamed the tool. Unknown
arguments now come back as an error naming the tool's real ones.

The "No workspace has id" errors of update_workspace and create_bot now
list the workspaces as they are at call time, including one created
earlier in the same reply, and the coordinator's workspace tools are
offered even before the install has a workspace.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 15:15:37 +01:00
tbenandClaude Opus 5.5 76af8e2799 Release v0.12.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 09:14:15 +01:00
tbenandClaude Opus 5.5 d99dcc88ea Space out the no-bots empty state
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 08:42:10 +01:00
tbenandClaude Opus 5.5 92331f0db4 Let the text model read images itself when its setting allows
A "Use the model's own media reading" checkbox on the text model
settings (default, bot and workspace) lets a text model that takes image
input look at images itself: attachments, computer and browser
screenshots, MCP tool images and read_file images. Otherwise, or for a
model that can't see, the media reading model reads them as before.

Tools now return images instead of reading them; the run shows them in a
user turn after the tool results, fenced as tool output, and keeps only
the newest few so long runs don't resend every screenshot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 08:42:10 +01:00
tbenandClaude Opus 5.5 2de1dae706 Release v0.12.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 13:57:41 +01:00
tbenandClaude Opus 5.5 92a1dfce71 Document connecting a Flatpak browser
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 13:39:52 +01:00
tbenandClaude Opus 5.5 473f3e8b8c Let super admins restart a computer from its modal
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 13:30:07 +01:00
tbenandClaude Opus 5.5 cc95a2b5d7 Let bots use a user's own browser over MCP
Each user can add their running browsers in Settings > Browsers and pick
where they apply and which is the default, for all their bots, a bot or a
workspace. The computer's browser stays as the fallback. A browser only
serves its owner's runs; routines need its owner's say, and hook calls
and chatrooms never get one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 13:22:12 +01:00
tbenandClaude Opus 5.5 f1f48d842b Release v0.11.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 11:52:41 +01:00
tbenandClaude Opus 5.5 51b5fb28b1 List rail workspaces and bots by each user's last visit
The rail remembered one workspace in a cookie, so opening another sent the
previous one back to its old place, sometimes behind "See all". Record
visits per user in workspace_user_visits and bot_user_visits instead, so
the order follows the user across devices and survives sign-out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 11:52:08 +01:00
tbenandClaude Opus 5.5 224fd13a3b Release v0.11.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 11:16:48 +01:00
tbenandClaude Opus 5.5 0f28036c7b Let the coordinator list a workspace's bots from outside it
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 11:15:34 +01:00
tbenandClaude Opus 5.5 4d411d64fb Show open chatrooms in the conversation and let them be retried
The asking bot's conversation now shows where each bot in an open
request stands, linked to the room, until it closes. A failed or stopped
room can be tried again from its header, the Chatrooms list or the
coordinator's message: the same room reopens with a fresh turn budget.

A stopped room no longer leaves the thinking row up.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 11:11:27 +01:00
tbenandClaude Opus 5.5 03d8eb0ac7 Give hooks their own thread
Hook runs now work in a hidden session per hook, so their results stay
out of chats, rails, session lists and notifications. Clicking a hook
opens a modal with its details and a live thread of its calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 11:04:00 +01:00
tbenandClaude Opus 5.5 4674b37b85 Release v0.11.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 19:48:58 +01:00
tbenandClaude Opus 5.5 d352ac924a List the last visited workspace first in the rail
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 19:48:38 +01:00
tbenandClaude Opus 5.5 c1c866876e Show bot graphics at the conversation's full width
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 19:45:27 +01:00
tbenandClaude Opus 5.5 913a87d23c Add a settings icon beside the rail's user row
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 19:44:06 +01:00
tbenandClaude Opus 5.5 f2710eb640 Release v0.11.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 19:25:49 +01:00
tbenandClaude Opus 5.5 faa554d5e3 Open bot files in a preview modal instead of a new tab
Markdown rendered, CSV/TSV as a table, images, PDFs, audio, video and
sandboxed HTML in place, other text as code, with Download and Open in a
new tab. Used by file chips, message attachments, the files modal, task
files and the files browser.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 19:25:49 +01:00
tbenandClaude Opus 5.5 521c2bbac0 Release v0.10.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 18:43:10 +01:00
tbenandClaude Opus 5.5 de28d4d9f7 Let generate_image work from reference images, with an image editing model
generate_image takes reference images: files the run reaches as
[file:ID] refs, or the user's uploads by media id, up to four, each
checked like a picture source and limited to raster images.

Calls with references go to a new Image editing harness (no automatic
picks). While it has no model or is off, image generation takes them;
with its fallback on, image generation steps in after its pick fails.
Only models that take image input are tried with references, so none
drops them unseen. OpenRouter gets them on /images as input_references;
other providers as a multipart upload to /images/edits.

The Models pages show image editing's unset state as "Same as image
generation", and the models cache version is bumped so it shows at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 18:43:10 +01:00
tbenandClaude Opus 5.5 243c19e0c5 Release v0.9.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 18:26:20 +01:00
tbenandClaude Opus 5.5 1e7834ba7f Add a guided setup after signup, and a no-model notice in conversations
The first super admin now lands on Settings > Setup after signing up: a
skippable walk through the app name, connecting a model provider and
picking models, ending with where to go next. It stays under Settings to
come back to.

While a bot has no text model, its conversation shows a notice in the
thread (centred when empty): super admins get Connect a provider and
Guided setup, everyone else is told the super admin sets it up. The
models modal keeps it current.

The Models page's data and save logic move into useModelsOverview, shared
with the setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 18:26:20 +01:00
tbenandClaude Opus 5.5 c9a24c05af Release v0.8.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 11:10:23 +01:00
tbenandClaude Opus 5.5 d7dfe0e78e Let bots ask multiple-choice questions before acting
ask_user puts up to six questions on one card (radios for one pick,
checkboxes for several, an optional typed Other) as a [question:ID] chip.
The user's answers are checked against the questions, stored in
bot_questions and sent to the bot as their chat message; Skip says so.
Offered in chat replies and user-started tasks, never in routines, hook
calls or chatroom sessions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 11:10:23 +01:00
tbenandClaude Opus 5.5 07f87ce4ea Release v0.7.6
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 07:05:34 +01:00
tbenandClaude Opus 5.5 f84f0fd0d6 Name sessions opened by handed-off work, and hide empty ones from activity
A session the coordinator's delegation, a routine or a hook opened has
no user message and no reply, so it was never named and showed as
"Untitled conversation". Tasks now name their session too, and a session
with no user message is named from the bot's own messages. Until a
session is named, Latest activity shows what it opened with, and
sessions with no messages are left out of it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 07:05:34 +01:00
tbenandClaude Opus 5.5 b4b27dea10 Truncate long list row titles instead of overflowing on mobile
Stack lines its children up at the start, so a linked row title grew to
its full one-line width and pushed the card past the screen edge. The
link now fills the row and the title is a block, so it truncates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 07:05:34 +01:00
tbenandClaude Opus 5.5 596a417229 Release v0.7.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 06:27:06 +01:00
tbenandClaude Opus 5.5 623112fd19 Give every task a bot: drop shared workspace tasks
A workspace task with no bot was seen by every bot working there. Now a
task can't be saved without a bot, a worker reaches only its own (the
workspace admin and the coordinator still reach all), the workspace page
picks who has a new task, and a bot leaving a workspace or deleted passes
its tasks there to the workspace's admin bot, else the coordinator (also
at boot for rows without a bot).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 06:26:44 +01:00
tbenandClaude Opus 5.5 3e78d51b56 Keep bot messages inside the column on narrow screens
Lists no longer add twui's 25px list margin on top of full width,
markdown blocks and list items are capped at the column, long words
and inline code wrap anywhere, and ref chips with long labels truncate
instead of pushing the line past the edge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 06:23:09 +01:00
tbenandClaude Opus 5.5 4e20106c59 Release v0.7.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 05:49:42 +01:00
tbenandClaude Opus 5.5 c547e556ec Open a task in its own modal from its title, with status moves, and edit its brief in the code editor
The modal shows who has the task and where, who added it and when it
moved, its files and notes (each note naming its bot). The task form's
fields all show their labels.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 05:49:42 +01:00
tbenandClaude Opus 5.5 74da091dd4 Release v0.7.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 05:32:09 +01:00
tbenandClaude Opus 5.5 a33593460b Delete a task from its list row, keep the status chip unfilled in light mode
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 05:32:09 +01:00
tbenandClaude Opus 5.5 bd73ecbe12 Release v0.7.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 05:09:52 +01:00
tbenandClaude Opus 5.5 50dd6976ee Mark and round the uploaded icon's favicon, enlarge the square icon's mark
An uploaded image's favicon now carries the stone mark like the PWA
icons and is cut to a circle. The mark is larger on the favicon and on
the regular (rounded-square) icons, and the settings preview matches.
A render revision in the set's version gives re-saved icons a new URL
past the immutable cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 05:09:21 +01:00
tbenandClaude Opus 5.5 8c4658f6e3 Release v0.7.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 04:55:23 +01:00
tbenandClaude Opus 5.5 d3ce787087 Show every bot of a chatroom in its rail icon
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 04:54:55 +01:00
tbenandClaude Opus 5.5 d8193d08b7 Release v0.7.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 04:50:00 +01:00
tbenandClaude Opus 5.5 ba9705980e Keep logs for a set number of days
Logs grew forever. A daily prune-logs cron now deletes entries older
than the app setting logs_keep_days (Settings > General, super admin;
default AppData.LogsKeepDays, 90), with an index on logs.created_at.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 04:49:25 +01:00
tbenandClaude Opus 5.5 5f96004f13 Search files as the user types
The Files page and the conversation's files modal searched only on
Enter. Both now search by name or path a moment after the last
keystroke (useDebouncedValue, AppData.SearchDebounceMs), clearing shows
the whole list at once, and the modal drops an answer a newer request
overtook. The Files search box no longer locks while a folder loads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 04:46:39 +01:00
tbenandClaude Opus 5.5 ac3ebc43d4 Keep searchable text only in knowledgebases
Every bot file was chunked into bot_file_chunks and embedded into
bot_file_vectors, and uploads kept their extracted text in
media.text_content, which together took most of the database. Bot
files are no longer indexed: bots find them by name or path with
list_files and read them with read_file, and search_files, ingest_file
and the files modal's re-read button are gone. Attachments keep no
text; a reply reads a document from the file. Only knowledgebase
documents keep text.

The schema drops both tables and the ingest columns. At boot,
dropStoredFileText removes what older versions stored (file jobs,
upload text) and vacuums once much of the database is free. The
media:prune-text script it replaces is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 04:44:46 +01:00
tbenandClaude Opus 5.5 2896e76256 Stop computer bash commands on the computer itself
The sandbox ignores sandbox_execute_bash's timeout and runs every call in
one shared shell session, so a command that never ended (a network read
without a timeout, a prompt) kept running after the call gave up, and
every later command on that computer, from any run, timed out behind it.
Each command now runs in its own bash under coreutils timeout (at most
ComputerCommandMaxSeconds, below McpToolTimeoutMs), reading no input, and
says when it was stopped.

Replies' env list says where each key comes from and that workspace,
computer and install-wide envs reach every bot there, so bots stop
telling users a workspace's keys must be set per bot. The computer
prompt says installed programs may be gone after a restart. An empty
open-only task list says closed tasks aren't shown, and update_task says
when a status was already set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 04:34:39 +01:00
tbenandClaude Opus 5.5 e51f2aa9a4 Catch up on replies missed while the app was in the background
The reply catch-up read the page's stale face, so after an interim
message it stopped while the thinking row stayed up. It now reads the
live face, checks at once when the page comes back into view or online,
and replays the bot's face and task too, so a reply that ended silently
can't leave the bot working on screen.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 04:14:13 +01:00
tbenandClaude Opus 5.5 4061a317bc Release v0.6.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 19:42:10 +01:00
tbenandClaude Opus 5.5 a821013514 Clear finished jobs' steps a minute after they end
Job steps (bots_queue_updates) only feed the live working row, so the
new clear-job-steps cron deletes them shortly after a job ends, however
it ended, keeping their count on bots_queue.steps for the message
details. Not done the moment a job ends: the live relay would miss the
last ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 19:41:40 +01:00
tbenandClaude Opus 5.5 78503208e8 Release v0.6.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 19:34:13 +01:00
tbenandClaude Opus 5.5 8890d80e6e Tell replies their envs and call queued work runs
Chat replies now list the envs that reach them (keys and descriptions,
never values), so a bot no longer asks for keys that are set or "checks"
them with show_secret or printenv. request_secret refuses a key that's
already set unless the user asked to replace it, and search_computers
says envs aren't loaded in its shell.

start_task and delegate_task results say "Run #N" and that list_tasks
doesn't show it, since bots sent users to the to-do list for queue jobs.
start_task refuses a second open run in the session on the same
computer unless it's separate work, and says how many runs are ahead on
that computer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 19:33:45 +01:00
tbenandClaude Opus 5.5 f39c824c34 Release v0.6.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 19:23:17 +01:00
tbenandClaude Opus 5.5 96d3227bd0 Name the workspace in a bot's task status line
A task running in a workspace shows "Working on a task in <name>
workspace", so the bot's own chat and the main rail say where the work
is. Outside a workspace it stays "Working on a task".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 19:22:25 +01:00
tbenandClaude Opus 5.5 864dcce30a Scope workspace tasks to the bot that has them
A workspace's task now carries the bot that has it there (bot_id with
workspace_id), or none while it's shared. A bot reaches its own list and,
in its workspaces, its own tasks plus the shared ones; a workspace admin
every task there. Bots create workspace tasks for themselves by default,
take a shared one by starting it, and hand-overs record the new bot.
Removing or deleting a bot makes its workspace tasks shared again. The
conversation's Tasks modal shows that bot's tasks in the workspace.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 19:19:01 +01:00
tbenandClaude Opus 5.5 184407d76b Keep file refs working in answers passed on from chatrooms
A ref quoted alone in a code span now links like any ref, and refs
inside longer code stay literal instead of turning into broken link
text. A file chip opens a file from another bot's folder for a user
who reaches that folder, by the same rule as its bytes, so the
asked bot's files open from the asking bot's conversation. Bots are
told to keep refs out of backticks, and the coordinator to pass them
on as given.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 19:02:19 +01:00
tbenandClaude Opus 5.5 7b762fd384 Let workers ask each other through the coordinator in chatrooms
A worker asks for another bot's help with ask_crew. The coordinator
reads the request, asks the right bot (in a workspace, only its
members), and sends the answer back into the asking bot's
conversation, waking it. Each exchange is kept as a read-only
chatroom: listed in the main rail after the workspaces, or in the
workspace's rail for requests made there, with live status rows for
each bot while it's open and a Stop button.

Room sessions are hidden from every conversation list, other bots'
words reach the model fenced as data, and turns, nesting and open
rooms are capped. Closed rooms are pruned after a retention period
and past a cap per place (Settings > General).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 18:57:34 +01:00
tbenandClaude Opus 5.5 2d3c15e48b Open a bot's own files from a workspace conversation
A workspace run saves to the bot's own folder unless it picks the
workspace's, but a file chip in a workspace conversation only looked in
the workspace's folder, so those refs rendered as dead text. The chip
now sends both ids and the single-file lookup also searches the bot's
own folder for a user who reaches that bot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 17:41:46 +01:00
tbenandClaude Opus 5.5 211599e0fc Release v0.5.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 14:18:36 +01:00
tbenandClaude Opus 5.5 ac1048c8f3 Install Cookie-Editor in every computer's browser
A managed Chrome policy, written as root into each running computer's
container on provision and every sync-computers run, installs the
default extensions (normal_installed: can be turned off, not removed).
Existing computers get it without being recreated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 14:18:36 +01:00
tbenandClaude Opus 5.5 dd6b48fcf5 Release v0.5.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 13:38:07 +01:00
tbenandClaude Opus 5.5 6e678cbcde Let a new service worker take over by itself
The update popup showed on installed PWAs after an update had already
landed: the new worker sat waiting behind the open window. Nothing in the
worker is per-version, so it now skips the wait on install, and the
popup is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 13:38:07 +01:00
tbenandClaude Opus 5.5 fa7a89c64e Release v0.5.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 08:15:12 +01:00
tbenandClaude Opus 5.5 bea656ade8 Add bot graphics
Bots can now show a concept as a visual: create_graphic (with
update_graphic, read_graphic and list_graphics, on every run, no computer
needed) stores one HTML document in bot_graphics, per user like the
conversation, and the chat renders its [graphic:ID] ref as an inline card
sized to fit, with a large view and a page of its own (no rail).

Graphic HTML is treated as hostile: it is only served at /graphics/<id>
with a CSP sandbox allowing scripts under an origin of its own and no
network, loading only the vendored Chart.js and Mermaid from
/graphics-lib/. The document carries the app's theme vars and scrollbars,
reports its height to the thread, and a frame that navigates away is
closed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 08:11:15 +01:00
tbenandClaude Opus 5.5 51fd4d5538 Give each user message its own copy, reply and time
Two prompts sent close together (as while a bot is still answering)
shared one row under their group: every copy button bunched beside the
last message's time. Each user message now has its own row, with its
copy button, a new Reply button (once it is saved) and its own time.
copyableMessages is gone with the shared row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 07:40:22 +01:00
tbenandClaude Opus 5.5 c75d3fe62c Release v0.4.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:42:35 +01:00
tbenandClaude Opus 5.5 e7b23b7454 Add knowledgebases
Knowledgebases give bots RAG over documents, scoped like extensions: to
particular bots, to a workspace, or to every bot, with their own button
beside Tools in the composer. Documents are chunked and embedded by the
file-ingest worker with the install's embedding model, which is now an
install-wide setting rather than a per-bot one.

- Word search runs on an FTS5 index ranked by BM25, with a scored LIKE
  fallback for scripts written without spaces.
- Changing the embedding model re-indexes documents automatically.
- Ingest jobs wait without spending attempts while every embedding model
  rests, fail at once on errors retrying can't fix, and keep passages
  searchable by words when the model refuses.
- Settings > Knowledgebases shows each knowledgebase's and document's
  index state: spinner, warning, grey check (words only) or green check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:41:01 +01:00
tbenandClaude Opus 5.5 2259b6895f Release v0.3.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:07:44 +01:00
tbenandClaude Opus 5.5 2df1bf83f4 Show when each extension was last updated
MCP, skill and tool rows in Settings say "Updated 5m ago" beside how
they're reached and who gets them. updated_at now means a change to an
extension's settings (an edit, or any Access save): runs, connections and
MCP syncs keep their own last_checked_at / last_synced_at and no longer
touch it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:07:44 +01:00
tbenandClaude Opus 5.5 b9008b22cb Release v0.3.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:21:51 +01:00
tbenandClaude Opus 5.5 56f219b322 Clear session links no carry-over made, at boot
Sessions from v0.2.8 and earlier were linked to the one before them by
every rollover and New session, so production threads offered "Show the
previous session" (and prompts read summaries) for sessions nothing was
carried from. A link is kept only when the session opens with a message
carried from that session.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:21:51 +01:00
tbenandClaude Opus 5.5 c7e5ed401b Release v0.3.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:11:25 +01:00
tbenandClaude Opus 5.5 06a480cb0f Format the bot types dict
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:10:50 +01:00
tbenandClaude Opus 5.5 926bad6bea Make bot types an extension of the bot's kind
Coordinator and worker come from bots.kind; bot_types now only holds
workspace_admin (was admin), each row naming its workspace, with no scope
field. Rows from v0.2.8 and earlier are fixed at boot by migrateBotTypes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:05:18 +01:00
tbenandClaude Opus 5.5 657a76d868 Mark the session on screen as Current in the session lists
- The conversation page tells the rail and the sessions modal which
  session it shows (announceShownSession, useShownSession); they reload,
  so a session reopened by ?session_id= shows at once.
- Only that session is Current and greyed out (the active one without
  ?session_id=); the active row then leads back to it.
- The rail lists the session on screen even when it's older than its
  latest sessions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:56:13 +01:00
tbenandClaude Opus 5.5 cc109bc361 Carry conversations into new sessions with a visible summary
- Bots get continue_in_new_session: the bot writes a title and summary,
  the session closes for good (read-only) and the new one opens with the
  summary as a "Carried over from the last session" message that links
  back to the old session.
- Continue in new session (conversation menu, sessions modal) and the
  automatic rollover at the session length do the same; New session now
  starts a fresh, unlinked session.
- Session length is an app setting in Settings > General.
- ?session_id= opens a session; a carried-over one shows a bar linking to
  where the conversation went on instead of the composer.
- The thread can open the previous session above the current one (shown
  only, never in the prompt), and replies get search_past_sessions and
  read_past_session.
- Sessions are named from their opening messages, not their latest, and
  a carried summary is labelled as the earlier session's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:35:52 +01:00
tbenandClaude Opus 5.5 1e6833b5d8 Have hook runs point to the brief when it disagrees with memory
A hook run follows its brief over the bot's memory. When the two disagree,
the run now reports the conflict and says the brief needs changing, rather
than offering to fix its memory. In chat, a change to how a hook's calls are
handled is proposed as a new brief, not saved to memory or promised.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 18:43:09 +01:00
tbenandClaude Opus 5.5 aff4f12daa Release v0.2.8
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 18:19:38 +01:00
tbenandClaude Opus 5.5 88ccd366a2 Give the installer a banner, clearer step marks and clickable links
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 18:19:38 +01:00
tbenandClaude Opus 5.5 1c4be39047 Release v0.2.7
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 17:48:28 +01:00
tbenandClaude Opus 5.5 0e59559ea9 Keep every hook call's response, searchable by the user and the bot
A hook call used to record only how it was taken; its run's answer went
to the chat alone and was lost to the call once the job was pruned. Now
`bot_hook_events` keeps `response`, `response_message_id` and
`responded_at`, written on every call a run took in when that run ends
(completed, failed, lost, stopped or cancelled) by
`recordHookCallResponse` in the job helpers, and calls turn done or
failed. The Calls view searches what calls sent and what runs answered,
filters by status and pages; Show all loads one call whole. Bots get
`search_hook_calls` and `read_hook_call` for their own hooks (never in a
hook call's own run), with payloads always marked as outside data.
Calls are kept for the app setting `hook_events_keep_days` (Settings >
General, default now 30 days). The caller still only gets 202 Queued.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 17:47:28 +01:00
tbenandClaude Opus 5.5 fb4c89fca1 Tie each hook to a session, picked in the hook form
A hook's calls used to run in whatever session was active at the time.
Now `bot_hooks.session_id` pins them to one session, open or closed
(null still follows the active one). The hook form picks where it runs
(the bot's own chat or one of its workspaces) and a session there, or a
new one of its own started beside the active one so the chat on screen
stays. A bot's proposed hook gets the session it was proposed in, and a
missing session is replaced on the next call. Changing place or session
is refused while a run is open; the computer stays only if reachable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 17:08:12 +01:00
tbenandClaude Opus 5.5 69988e08fc Move secrets between users and computers without the model seeing them
A new personal env scope (paradigm user: one user's secret for one bot)
beats every other scope, reaches only that user's runs of that bot, and
is redacted like any secret. Bots take secrets in with request_secret,
which puts a [secret-request:ID] card in the chat: the user types the
value into a masked input there, never into a message, and the bot is
told only the key. Bots show secrets with capture_secret (a task's
computer tool that saves a file or a command's output straight to a
personal env, then redacts it from the rest of the run) and show_secret
(an env by key): both give a [secret:ID] chip whose Reveal and Copy fetch
the value on click, for its own user (personal) or a super admin
(anything else), logged by key. Values never go into messages, page
props, history, Copy chat or logs. Users manage their own secrets on
Settings > Secrets; the Environment page lists everyone's, remove only.
Deleting a bot or user removes its personal secrets, and SecretsNote
tells bots never to ask for or print secrets in chat.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 16:51:32 +01:00
tbenandClaude Opus 5.5 83ff79b9c3 Release v0.2.6
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:30:27 +01:00
tbenandClaude Opus 5.5 027c67c0a8 Say what a skill proposal changes, so a kept runbook never reads as saved
propose_skill took no strict schema, so a runbook sent under another key
was dropped and the saved one proposed again; the confirm still said
"Saved". Now an unknown key is an error, a change that changes nothing is
refused, and both the bot and the confirm outcome are told which fields
change and whether the runbook is among them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:29:55 +01:00
tbenandClaude Opus 5.5 b9c5311fde Keep computers' browser sessions across restarts and recreates
Each computer's Chrome profile now lives on the data volume
(DATA_DIR/computer-browsers/<id>, mounted at ~/.cobble-browser) and
Chrome is pointed at it with --user-data-dir. The sandbox image resets
its own profile's preferences to session-only cookies on every boot,
which signed every site out whenever Chrome exited. New profiles are
seeded with the image's preferences minus that rule, stale Singleton
links are removed before each provision, and existing computers are
recreated once (skipped while a job runs on them).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:26:18 +01:00
tbenandClaude Opus 5.5 380d3ebb2f Let bots manage their hooks, with the user confirming what widens them
Bots get list_hooks, pause_hook and delete_hook, which act directly since
they only take away. A new hook, or a new name, brief or filter, or
switching a paused one back on, goes through propose_hook: it stores a
hook_proposals row and puts a [hook-proposal:ID] card in the reply, which
the user it was proposed to confirms or rejects. The card is read from
what Confirm saves, with the bot's reason labelled as its own; confirming
checks everything again and saves through the Hooks modal's helpers. A
new hook's URL is shown on the card once, to the user only, never in the
outcome the bot is told. What calls a hook, its computers and its signing
are never proposed. Only chat replies propose, and a hook call's own run
gets no hook tools, so a caller's payload can't reach them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:18:54 +01:00
tbenandClaude Opus 5.5 045167715d Release v0.2.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 14:14:27 +01:00
tbenandClaude Opus 5.5 bd9744043e Let outside services and computers' browser notifications give bots work
A bot hook (bot_hooks) is a secret URL, POST /api/hooks/<token>, whose
calls queue the hook's brief plus the raw body as a task, per user and
bot like a routine. Only the token's hash is kept (shown once, rotatable);
an optional HMAC-SHA256 signing secret is stored encrypted. Calls are
rate limited per address and per hook, recorded in bot_hook_events
(pruned daily), deduplicated by delivery id, and a call while the last
run still waits joins its brief instead of queueing another. The payload
is fenced data and HookRunNote tells the bot never to take instructions
from it; failed runs retry like routines.

A hook can instead watch a computer's browser notifications: the app
installs a small watcher that owns org.freedesktop.Notifications on the
sandbox's session bus, so Chrome hands it every notification (it only
looks for that service at start-up, so Chrome is restarted once, never
mid-task), and it posts each one to its hooks, optionally filtered.
Computers reach the app at COMPUTER_APP_URL or the app container's name.

Users make hooks in the conversation's Hooks modal and manage them all
on /admin/routines; bots never create or change hooks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 14:06:59 +01:00
tbenandClaude Opus 5.5 a596722e59 Give modal content room at the top
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 14:06:59 +01:00
tbenandClaude Opus 5.5 2d85177c59 Let crew managers edit a bot's workspace instructions where they work with it
A bot's instructions and memory for one workspace were only reachable
from the workspace's settings. The editor is now shared and also opens
from the conversation menu in that workspace ("Instructions here",
loaded on open through api/admin/workspaces/workspace-bot) and from the
workspace rows on the bot's settings page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 13:17:32 +01:00
tbenandClaude Opus 5.5 84f8c0cac8 Let users copy the current chat session as markdown
The conversation header menu gets a Copy chat row that puts the active
session on the clipboard as one markdown document: a summary, then each
message under its author and time, with quotes, attachments and
reactions. Bot and workspace refs read as names, message headings drop
below the message headings and code blocks stay untouched. The clipboard
write starts on the click with a pending ClipboardItem so Safari allows
it after the fetch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 11:49:46 +01:00
tbenandClaude Opus 5.5 d7f88d8dd3 Keep a record of each run's tool calls so bots can't claim work they never did
The wrap-up turn now gets the run's actual tool calls, each bot message
keeps them as bot_messages.tool_log, and history follows recorded bot
messages with an [App record] line. The coordinator also gets update_bot
in workspaces, so it can fill a bot's core prompt from there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 11:32:56 +01:00
tbenandClaude Opus 5.5 93896646c7 Let the coordinator and workspace admins hand over tasks and routines
delegate_task takes a task_id to hand over a task already on a list: it
moves to the worker (a workspace's task stays on its list), goes to
doing, and the job is linked back so its end is noted on the task.
hand_over_schedule moves a bot's own routine to another bot, keeping its
workspace. Users get Hand over in the Tasks UI and both routine lists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 11:23:26 +01:00
tbenandClaude Opus 5.5 b4283b607e Release v0.2.4
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 10:38:25 +01:00
tbenandClaude Opus 5.5 e462806438 Let each install pick its app icon
Settings > General gets an App icon (super admin): one of the seven
stones, or an uploaded image with the picked stone as a top-left corner
mark (inside a round launcher's crop, clear of the browser's badge),
previewed in both launcher crops before saving.

Uploads are decoded and cropped to a stored square (no SVG); the set is
drawn into DATA_DIR/install-icon/<version>/ and served publicly and
immutable. The manifest, head icon links and push notifications point at
it; the ember stone keeps the stock icons. The generator shares the icon
renderer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 10:38:25 +01:00
tbenandClaude Opus 5.5 5a603bf61f Release v0.2.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 10:19:27 +01:00
tbenandClaude Opus 5.5 3b7c05bfa0 Name each install, fix the notification badge, switch to Archivo
- Settings > General: an App name (super admin) for the installed app.
  The manifest's name/short_name, the iOS head tags and the loading
  page's title use it, so two installs on one phone can be told apart.
- Notifications get a real badge (white stone silhouette): Android masks
  the badge by alpha, so the opaque app icon showed as a square.
- The loading and offline pages load the app's font.
- The font is now Archivo (variable, one request for every weight),
  matching the marketing site.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 10:17:40 +01:00
tbenandClaude Opus 5.5 89c4e26d06 Release v0.2.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:58:21 +01:00
tbenandClaude Opus 5.5 d67cd6a27a Close the proposal modal once a proposal is decided
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:57:28 +01:00
tbenandClaude Opus 5.5 2cbf6a6e6c Compress AGENTS.md to its rules, invariants and pointers
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:56:18 +01:00
tbenandClaude Opus 5.5 373210c2a5 Make the skill runbook limits a general setting
The longest runbook a skill may save and how much of it load_skill hands
back are now set on Settings > General (skill_body_max_chars,
skill_body_shown_chars), defaulting to AppData.SkillBodyMaxChars and
SkillBodyShownChars. Saving, confirming and proposing a skill check the
install's limit; a skill saved before it was lowered can still be toggled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:43:00 +01:00
tbenandClaude Opus 5.5 2408185a65 Release v0.2.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:25:43 +01:00
tbenandClaude Opus 5.5 577523de3c Only ignore the root logs folder
The bare "logs" pattern ignored every folder named logs, so
api/admin/logs/clear-logs.ts never reached the repository or the
production build. Anchor it to the root and add the route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:24:55 +01:00
tbenandClaude Opus 5.5 b9a49ee09c Fix data archives and restores failing on their own lock
startDataBackupRun already holds the backup run lock, but the archive
(createDataBackup) and restoreDataBackup took it again, so every run
failed a few seconds in with "Another backup or restore is already
running". The writer and the restore now take no lock of their own.

The run's notice (archiving, restoring, or why it failed) moves to its
own line under the actions row so the buttons don't shift, and archiving
reads in gray rather than the warning colour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:24:55 +01:00
tbenandClaude Opus 5.5 410d05e0b1 Release v0.2.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:06:34 +01:00
tbenandClaude Opus 5.5 19fac97d18 Default lucide icons to 16px
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:04:14 +01:00
tbenandClaude Opus 5.5 ea62dd11f0 Add bot types with a permission matrix, and workspace admin bots
A bot's powers came from bots.kind alone, so only the coordinator could
hand work to other bots. bot_types now works like user_types: a row with
no workspace holds everywhere (the coordinator), one with a workspace
only there (a workspace admin), and no row is a worker. bots.kind stays
the legacy marker of the one coordinator for who sees it.

The matrices in src/dict/bot-types-dict.ts say what each type may do,
whom it may direct and who grants it, read by one generic interpreter
(rbac/type-assignment.ts) that userTypeAssignment now wraps too. Every
run reads its powers once (grabBotRunPowers) and the chat tools, task
runs and task tools gate on them instead of kind; a run's powers are its
type's and its user's together.

In the workspace it leads, an admin hands tasks to the workers there
(results relayed back to it), sets their instructions, adds tasks to
their lists and keeps the workspace's context when its user may. Super
admins and admins grant it from the workspace's settings or the chat
header's menu, and the coordinator with set_bot_type. Admins are marked
with a filled green shield beside their name across the workspace, kept
live by pushBotUpdated's admin_workspace_ids.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:04:14 +01:00
tbenandClaude Opus 5.5 4161863587 Run whole-data archives and restores in the background
A data archive or restore ran inside its request, which sent nothing
until tar finished: Bun closes a silent socket after 10s (its default
idleTimeout in production) and a proxy cuts it at about 100s, so the
page showed a network error while the archive kept going, and a retry
said another backup was already running.

The routes now start the run (startDataBackupRun, refused while the
backup lock is held) and answer at once. The page follows it by polling
api/admin/backups/data-status: an archive reloads once written, a
restore once the status comes from a new process after its restart,
and a failure shows its error. A run in progress survives a reload.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 08:34:29 +01:00
tbenandClaude Opus 5.5 86becd50bc Keep every bot's computer work in its own workspace folder
Computers now mount only /home/gem/workspace from DATA_DIR/computers/<id>,
so only the workspace persists and goes into the data archive. An older
computer's whole home is moved aside to <id>-home-<ts> (kept, never
archived) and its container recreated once by sync-computers.

Each run works in bots/<bot>/users/<user> (also its cwd and HOME), with
bots/<bot> for work every user shares and workspaces/<id> shared by a
workspace's bots; the coordinator reaches the whole workspace. Computer
tools are gated by withComputerDirs: bash and code start there, file tool
paths and file: URLs outside the run's folders are refused, and so is sudo.
search_computers, import_file and script tools start there too.

The files browser shows members only the bots' folders they reach, their
own user folder in each and their workspaces', with names on the id folders.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 08:24:49 +01:00
tbenandClaude Opus 5.5 fefc295d15 Let the coordinator manage skills, MCP servers and tools, behind a confirm card
- Coordinator tools in its own chat (super admin only): list_extensions,
  set_extension_access, delete_extension, and update_skill /
  update_mcp_server / update_custom_tool for what can't change where
  anything is sent (on/off, names, arguments, left-out tools)
- Adding a skill, MCP server or tool, or changing a skill's words, a
  server's URL or headers or a tool's kind or config, goes through
  propose_skill / propose_mcp_server / propose_custom_tool: stored in
  extension_proposals with the bot's background check, shown as a
  [proposal:ID] chip that opens a card with Confirm and Reject
- The card's facts are worked out by the app from what Confirm saves: the
  host, every {{env.KEY}} and whether it's saved, the config; for a skill
  its links, hosts, tool names, mentions of secrets and a diff against
  the saved runbook
- Confirming decides once and checks again; a server or tool missing a key
  is saved switched off, and the outcome is posted to the bot in chat
- Never from a bot: stdio servers, a URL whose host a template decides,
  envs in a prompt tool, a key's value

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 06:08:09 +01:00
tbenandClaude Opus 5.5 e6c278198b Quiet the logs and capture the errors that were missing
- Activity page: "Delete all" empties the open tab (api/admin/logs/clear-logs,
  super admin only, logged under system)
- Stop logging every WebSocket connect
- Log unexpected API errors (safeErrorMessage -> logUnexpectedError), every
  failed bot job attempt and every job the queue lost
- Drop the cron jobs' console output; a failed model sync goes to the logs

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 05:11:31 +01:00
tbenandClaude Opus 5.5 3a9e57f682 Fix the usage page's tables, range tabs and day bars
- Both tables lay their heading and rows on one shared grid, so every
  figure sits under its own heading (twui's Row wrapped the cells).
- The selected range reads as pressed: ink-filled in a hairline track.
- Each day's bar opens a small summary card on hover or tap.
- twui 0.1.7 places popovers before paint, so opening one no longer
  makes the layout flicker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 05:01:24 +01:00
tbenandClaude Opus 5.5 b0fe619ae8 Let bots take in messages sent while they reply
A reply read the session once at the start, so a message sent while it
ran was never seen, and the follow-up reply queued for it then finished
silently: the message was saved before the reply, so the thread ended
with the bot. Those messages went unanswered.

The text loop now reads new user messages after every round of tools and
before an answer goes out, and the bot decides from what each one means
whether it changes the work (folded in, or the unsent answer redrafted)
or is a separate request, which it acknowledges at once with the new
send_message tool and does after the current work. Messages sent that
way are marked interim, so the thinking row stays up while the bot
works. A reply job records the newest user message it read, and a queued
reply only stays silent when a finished reply already read everything.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 04:49:10 +01:00
tbenandClaude Opus 5.5 c13b9ea826 Show how each bot message was generated
Every bot message gets an info button that opens its details: the
provider and model behind it, tokens and cost, the job that ran it, each
model used and every call in order. Each model call now records how it
was made in token_usages.settings (generation settings sent, whose
settings they were, pinned or automatic model, fallbacks), shown per
model in the modal.

Live replies now carry their token usage, from the job's push and the
live relay alike, so it shows without a reload.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 04:33:47 +01:00
tbenandClaude Opus 5.5 feec69adca Share every bot and workspace picture with everyone signed in
A bot's or workspace's picture was only shared when its media row carried
the bot-image or workspace-image paradigm. A picture set before pictures
were copied into their own row points at the chat upload itself, so only
its uploader could load it and everyone else saw the default icon. A
picture is now shared because a bot or workspace points at it, whatever
its paradigm; profile photos still have to be the user's primary one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 04:08:16 +01:00
tbenandClaude Opus 5.5 d542b4e9ad Load a conversation's history on the client
The conversation pages rendered their messages on the server, so a page
the back button restored from the back-forward cache showed an old
thread. The server now renders everything else (rail, header, composer)
and the history (active session, latest messages, active task) loads
from api/admin/bots/conversation-history once the page is on screen,
with a loading line under the header, and again on a pageshow restore.
Messages sent or pushed while it loads are merged with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 03:55:38 +01:00
tbenandClaude Opus 5.5 cdb93ac1bc Fix file access, XSS and access-control bugs from a security scan
- Media rows can no longer be created through the CRUD API, updates only
  take description fields on the caller's own row, and every media read
  or delete goes through mediaFilePath, which refuses paths outside
  DATA_DIR or inside the database folder.
- Uploads strip the file name and extension to safe characters and keep
  only title, description and summary from the request's media object.
- Folder imports no longer follow symlinks (walkRegularFiles), and the
  source path is quoted in the computer's shell.
- User and bot files are served with nosniff, and HTML, SVG, XML and
  scripts are sandboxed by CSP.
- Sandbox cookies are kept to the computer's prefix, and websocket
  upgrades on /ws and the computer proxy must come from the app's own
  address (README and Help note nginx's Host header).
- user_types CRUD writes go through the assignment matrix; members only
  read their own user record; read-only users can read CRUD again;
  grabUsers builds valid SQL for array search terms and bad pages; an
  admin media DELETE needs an id; read-only users can't delete media.
- Rate limits and the audit log use the connection's address, trusting
  forwarded headers only from a proxy, and login limits are split per
  address, per account from that address and per account overall.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 03:38:07 +01:00
tben 2e8e8de976 Release v0.1.8
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
2026-10-23 18:00:06 +01:00
tben e75ab28041 Open a computer chip in the viewer instead of switching to it
A computer a bot names in a reply is now a button that opens it in the
shared computer viewer modal, the bot's own computer included (sunken and
checked, as before). Switching stays in the header's computers modal, so
the chip has one job. A computer the bot can no longer use stays a plain
name.
2026-10-23 17:58:08 +01:00
tben 4261535741 Tell every bot its own id, in every run
The bot's id never reached its prompt: `composeBotPrompt` only took its
instructions, the appendix, its memory and its workspace, and
`grabBotPrompt` never passed `bot.id` or `bot.name` on. A bot could only
learn its id by accident, from a tool description that named it, so
"which bot am I" was unanswerable in most contexts.

- Open the prompt with who the bot is (`composeIdentity`): its name,
  whether it's the coordinator or a worker, its role, and its id, said
  to be how tools and refs point back at it. `grabBotPrompt` now passes
  the bot, which covers chat replies, tasks, routines and delegated
  tasks, since both runners build their prompt there.
- Turn the notes' example refs into functions bound to the running bot:
  `chatReplyNote`, `botFilesNote` and `coordinatorReplyNote` take its id,
  so the folder-ref example no longer points at a hardcoded `owner_id: 5`
  (another bot's folder) nor `[bot:3]`. ComputerFilesNote keeps the
  computer it's given.
- Stop `create_task` from hiding the worker's own id in its own chat.

Tests: four new `composeBotPrompt` cases pin the identity block (worker,
coordinator, unnamed, no bot at all), and a new `harness-prompts.test.ts`
checks each note's own-folder and self refs point at exactly the running
bot, for three ids.
2026-10-23 17:40:28 +01:00
tben 0166f31cfc Release v0.1.7
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
2026-10-23 16:50:51 +01:00
tben caa9ad87e4 Remove sticky breadcrumbs 2026-10-23 16:49:52 +01:00
tben 30a4df183c Give every admin page a breadcrumb trail
The trail is twui's Breadcrumbs reading Home, the sections and the page
off the address, rendered as the first thing in SettingsShell's content
column, so every page that is not a conversation gets one without a page
touching it.

The last crumb is named by the page's own title rather than the address:
a record reads Scout instead of its id, /admin/logs reads Activity, and
/admin/settings/mcps reads MCPs. That replaces the breadcrumb_title prop
the four settings record pages had to pass, so settings-breadcrumbs.tsx
goes.

hasBreadcrumbTrail drops the trail on the crew of bots, home, and on
anything outside /admin; the trailing slash and query string are ignored,
so a folder in the files browser keeps the trail of the page it is on.
2026-10-23 16:49:01 +01:00
tben ee687e1d31 Chunk Tailwind classes with tailwind-merge
Say it once in AGENTS.md: a className is twMerge(...) with one chunk per claim, so a later chunk beats an earlier one instead of depending on CSS source order.
2026-10-23 16:42:01 +01:00
tben 024d847b9a Let the install set how many steps a run may take
The two limits were compiled in: a task run stopped at
AppData.HarnessMaxToolSteps (200) and a chat reply at
AppData.BotReplyMaxToolSteps (8), so an install that needed a longer task
had to rebuild.

Both are now `app_settings` rows (`harness_max_tool_steps` and
`bot_reply_max_tool_steps`), read at the two loop call sites through
grabHarnessMaxToolSteps and grabReplyMaxToolSteps, and edited by the super
admin on Settings > General beside the prompt appendix. Zero clears a
limit back to the code default, like the bot file quota.

readStepLimit keeps the saved number only when it is a whole number of at
least 1 and no more than AppData.BotStepLimitMax (1000), so a blank, a
zero or a typo falls back instead of stopping every run before its first
turn, and a huge number still ends in the wrap-up report.

runTextLoop keeps AppData.HarnessMaxToolSteps as its default, so it stays
free of database reads and its tests run as they did.
2026-10-23 16:20:38 +01:00
tben 06586a6dc8 Release v0.1.6
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
2026-10-23 16:05:01 +01:00
tben 55fc5ee97b Follow the thread's bottom, and offer a jump back to it
Sending a message while scrolled up left it out of sight: the thread only
ever anchored its bottom, so nothing brought the view down. The column now
follows new messages while it sits at the bottom, stays put while it's
scrolled up, and always brings a message the user just sent into view.
While the thread sits above its bottom, "Jump to latest" floats over it.

Whether the thread is at its bottom is read from where the content ends
rather than from `scrollTop`, whose sign a reversed column reports
differently across engines. Content that grows after it lands (an image,
a wider window) is followed too, so the newest message never slips under
the composer.
2026-10-23 16:03:37 +01:00
tben d9aea8e9c8 Record what every model call spends, and show it
Nothing anywhere recorded what a model call cost: the harness used a
provider's usage numbers only to decide whether a turn had finished, then
dropped them. So a reply could not say what it took to make, one model
could not be compared with another on price, and there was no way to ask
what a day, a week or a month of the crew's work came to.

- `token_usages` records one row per call: user, bot, workspace, session,
  job and message, the harness, the provider and model that actually
  answered, the prompt and completion counts, and the cost when the
  provider reports one.
- `harness-usage-scope.ts` carries those ids in an AsyncLocalStorage
  scope that `run-bot-job.ts` enters once, so a run's turns, its session
  summary, its transcriptions, images and embeddings are all attributed
  without threading ids through every harness function. Nested runs merge
  rather than replace, and a null genuinely clears a field (a bot's own
  chat has no workspace).
- Work with no run behind it is charged to its owner instead:
  `run-with-fallback-scope.ts` reaches the workspace's creator else the
  bot's, and deliberately does not override a real run, so an ingest a
  bot asked for is not misattributed to the bot's owner.
- All six harnesses record through `withCandidates`'s `on_success`.
  Recording never throws: a model that answered must not lose its answer
  to a failed insert.
- A job's calls land before its message exists, so `complete-bot-job.ts`
  back-fills `message_id` once the message is inserted.
- The message's actions row shows what it cost, beside the timestamp and
  the play button, with the breakdown in its title.
- `/admin/usage` totals the install's spending for 7, 30 or 90 days: the
  total against the previous period, a day-by-day chart, a split per kind
  of call, and a table per model with the price per thousand tokens
  worked out from cost and tokens, which is what makes two models
  comparable. Crew managers only, since it is the whole install's work
  rather than one user's conversation. It sits with Routines and Activity
  in the user popover rather than under Settings, because it is a record
  of what happened, not something to configure.

Days are grouped in local time (`date(created_at / 1000, 'unixepoch',
'localtime')`), matching the local midnights the window builds and the
`YYYY-MM-DD` buckets it looks up. Grouping by the bare UTC day put a late
evening's calls under a name no bucket carried, so they vanished and the
chart's total silently disagreed with the totals card; a test pins it.

`canSeeRailItem` now decides who sees a popover or rail entry. The two
each filtered with their own inline rule and only one understood
`can_view`, so a gated page could be offered in the popover to everyone.
2026-10-23 15:41:41 +01:00
tben 0048324d8a Let a delegated task choose the workspace it runs in
delegate_task had no workspace argument: a task handed over from the
coordinator's own chat always ran in the worker's own chat, on that
worker's memory, files and directly assigned computers alone, even when
the work belonged to a workspace. The coordinator could not say where the
work goes, and the prompt never said the two differ.

- delegate_task takes an optional workspace_id: the worker runs the task
  in that workspace's context, with its own instructions and memory
  there, the project's files and the workspace's computers, and the
  result lands in its conversation in that workspace.
- A worker missing from that workspace is added first (pushBotCreated)
  and the reply says so.
- Handed over from inside a workspace the task always runs there; a
  different workspace_id is refused instead of ignored.
- The coordinator prompt, CoordinatorReplyNote and the tool description
  now spell the distinction out.
2026-10-23 14:25:21 +01:00
tben f7ef218507 Take the Gitea registry out of CI and mirror it separately
CI / check (push) Canceled after 0s
The Gitea registry is on a VPN, which a GitHub runner can never reach, so
the mirror step in the release workflow could only ever fail: its last four
releases reported a step that did nothing. The workflow now builds and
pushes to GHCR alone, which is the registry the installer defaults to, and
nothing in CI mentions Gitea.

The image reaches the Gitea registry through `scripts/mirror-gitea.sh`
(`bun run mirror:gitea`) instead, run in parallel with a release and from the
VPN side: it copies from the Gitea host over ssh, where skopeo can see both
registries, so nothing has to be installed there. `skopeo copy --all` keeps
the manifest list and its signatures, and every destination tag is read back
and compared with GHCR's digest, so a partial copy fails loudly instead of
being assumed to have worked. `latest` and `major.minor` are only moved while
that release still owns them in GHCR, so mirroring an older release never
rolls them back.

Neither direction can fail the other now, which is the point: a registry that
is down, slow or full no longer takes a release with it.
2026-10-23 12:03:23 +01:00
tben aac5d41474 Release v0.1.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
2026-10-23 10:21:06 +01:00
tben fcad4b49d6 Let a user stop a bot, and say the app is still alpha
The thinking row and the header menu both carry Stop while a bot has work
open for the user anywhere: every pending or processing job of that bot in
their conversations is failed as stopped, its task closed, a Stopped step
recorded and one closing message posted per session, so the thread stops
waiting and the bot goes idle. The handler running the job is aborted from
this process through a registry, so a job stuck waiting on a model stops at
once instead of on its next heartbeat, and a late face change after the
abort is dropped.

The release stage is now said in the app too: Settings > General reports
"Cobble v0.1.5 (alpha)" next to development, and the README and RELEASING.md
say what alpha means for installs.
2026-10-23 10:19:41 +01:00
tben 5beb5f3de4 Let a conversation's menu show the routines that run in it
The header menu had Tasks but nothing for the schedules whose results
land in that conversation. It now has Schedules, right under Tasks,
opened in a modal that lists only what runs there: a bot's own chat holds
the routines that run nowhere, a workspace only that bot's routines in
it (`routineScopeSql`, tested against SQLite).

The list loads when the modal opens, through
`api/admin/bots/list-routines`, which checks the user chats in that
conversation first, so the page props stay small. `grabCronJobs` gained
an optional `workspace_id`: left out it still means everywhere.

The routines page's row, form and edit modal moved to
`src/components/general/`, and its subtitle to `src/utils/`, since both
the page and the modal use them.
2026-10-23 07:23:15 +01:00
tben 796c53716f Show a mirror failure, and link the release's own range
CI / check (push) Canceled after 0s
2026-10-23 06:54:06 +01:00
tben 5af2f0362a Fetch the tags in CI so the publish tests can read them 2026-10-23 06:13:14 +01:00
tben b3afda9ed8 Stop the tamper test from tampering with its own prefix
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
2026-10-23 06:10:41 +01:00
tben eb29e2bca9 Bump the version to 0.1.4 2026-10-23 06:10:05 +01:00
tben 41bb4aaac2 Let a super admin read the database from the app
A new super admin settings page, /admin/settings/database, lists every
table with its record count and size, and one page of the open table's
records newest key first. Values are cut inside SQL (400 characters, with
a flag saying so) and a record opens whole in a modal, so a table of long
texts reads without shipping it all. A search matches every column's
text, word by word or as a phrase, which is the one thing that also works
on a virtual table. Nothing in it writes: the catalog, the records and
the single record are all reads, GET only.
2026-10-23 06:03:42 +01:00
tben 9b26c169d6 Let a text run take 200 steps
A task that works through a folder or a long computer session was
running out of steps before it could report.
2026-10-23 06:01:38 +01:00
tben b5c3b7d126 Share every picture with everyone signed in
A profile photo, a bot's picture and a workspace's picture all come from
one condition now (sharedPictureMediaSql), so a face is never blank just
because its owner isn't in the viewer's rail. Anything that isn't a
picture stays behind its own check.
2026-10-23 06:01:34 +01:00
tben 93e3a4e3b0 Say what media.text_content is for in the schema
The column holds extracted text only; raw binary never goes in it.
2026-10-23 06:01:24 +01:00
tben f2802c1bf3 Let bots set a picture from a file they can see
A coordinator asked to set an uploaded logo as a workspace picture could
not: the picture tools take a media id, and nothing ever gave the bot one.
Attachments reached the model as "[Attached image \"logo.png\"]", every
file tool answers with a [file:ID] ref, and an SVG is deliberately stored
as a document rather than an image.

- copyMediaAsPicture copies an approved image into a new picture row
  (bot-image/workspace-image). The source keeps its row and bytes, so a
  message that attached it still loads and changing a picture can never
  take a file away from a conversation.
- grabPictureSource resolves a picture by [file:ID] (the same scope gate
  every file tool uses) or by the user's own upload; parseFileRef reads
  the [file:12] form.
- The new set_picture tool ships on every run: a bot sets its own face,
  the coordinator can also dress a worker. update_workspace gained
  picture_file_id, and setBotPicture/setProfileImage share the copy and
  the delete.
- removeReplacedPicture deletes a replaced picture only when it really is
  one, never a chat upload.
- uploadAndRecordMedia writes images in their own format: PNG stays PNG
  with its transparency, WebP stays WebP, GIF becomes PNG, everything
  else JPEG, and the row records the real mime type (it used to say jpeg
  for every image).
- Pictures change live: BotUpdatedData carries image_media_id and a new
  server:workspace-updated pushes workspace pictures, relayed between
  processes.
- Attachments are labelled with their media id, and BotFilesNote tells a
  bot that a [file:ID] can become a picture.
- grabRunScopes is now the single source of a run's reachable folders,
  shared by the file tools, imports and the picture tools.
2026-10-23 05:24:55 +01:00
tben d3357cb7df Stop storing raw file bytes in media.text_content
`text_content` is an extracted-text cache, but nothing stopped it from
holding a dump of bytes:

- `fileToText` ended its switch with `default: return buffer.toString("utf-8")`
  and defaulted a missing extension to "txt", so any binary was decoded.
- Both extraction callers gated on `media_type == "document"`, and
  `attachmentFileKind` classes everything non-image/audio/video as a
  document: an SVG, a zip, a spreadsheet, a .bin.
- Nothing capped the length, so a 20 MB attachment could leave 20 MB of
  text in the database.
- `storeChatAttachments` copied the text onto a second `media` row, and
  `SELECT m.*` pulled the column into page props and API responses.

On a real install an SVG held 6852 characters of markup and a
`.designcraft` file held 142 KB of raw bytes.

Changes:

- `file-to-text.ts` lists the text extensions explicitly and returns
  undefined for anything else; no extension is no text.
- `can-extract-text.ts` is the one allowlist (reusing
  `BotTextFileExtensions`), used by both upload routes and by
  `uploadAndRecordMedia`; `extension-of.ts` is shared with the storage
  catalog instead of duplicated.
- `BotAttachmentTextStoreMaxChars` (200k) caps the column via
  `cap-text-content.ts`.
- `store-chat-attachments.ts` no longer copies the text; ingestion
  re-reads the bytes once.
- `media-columns.ts` selects every media column but `text_content`, which
  now has to be asked for (`grab-messages-media`'s reply path and
  ingestion do); the media CRUD routes sanitize rows they write.
- `ingest-bot-file.ts` decides on size alone, since a cached slice made
  an oversized file look already read.
- `bun run media:prune-text` cleans rows that were already stored
  (rerunnable, with a VACUUM hint).

Verified on the dev database: both bad rows cleared (146 KB), rerun
reports nothing to do.
2026-10-23 05:22:04 +01:00
tben 5475241371 Move the notification settings onto the general settings page 2026-10-23 04:11:21 +01:00
tben a5eb2b6a95 Let the coordinator set a workspace's picture
CI / check (push) Canceled after 0s
update_workspace now takes an image media id (or null to remove the
picture). updateWorkspace writes image_media_id through
resolveWorkspacePicture, which only accepts the caller's own image and
deletes the picture it replaced, so a bot can never show someone else's
file or drop a picture it is still using.
2026-10-22 21:10:06 +01:00
tben 34667581b6 Tighten the coordinator prompt around how a run actually works
The prompt had grown to a policy document: 13 sections, the same rules
repeated across them, and a state vocabulary no tool accepts. It also
never mentioned the reply/task split, so the model would burn a reply's
8 tool steps on work that belongs in a 50-step task.

- Lead with work placement: answer directly, start_task for its own long
  work, delegate_task for a worker, and say work is under way, not done.
- Replace the invented Requested/Queued/Verified list with the real
  TaskStatuses and update_task.
- Name the 19 tools it tells the coordinator to use, and which tool
  writes which instruction layer, instead of "the available tools".
- Give routines their own section; create_schedule was uncovered.
- Say each safety rule once, and keep the interrupt list short so the
  prompt reads as proactive rather than timid.
- Drop the commented-out previous prompt: that is git's job.

The test asserted a heading and a section that no longer exist, so it was
already failing. It now checks the heading, the SiteData name, the
absence of em dashes, the real statuses, and every tool named.
2026-10-22 20:14:08 +01:00
tben 2398314703 Give the coordinator a fuller prompt, and show bot instructions in find_bot
The coordinator's default prompt was a page of job descriptions. It now
states the working rules it kept getting wrong: a queued task is not a
running one, a tool result is the only proof an action happened, an
approved text is written whole, and an explicit constraint such as "no
computer" is binding. The prompt is attached at creation only, so this
reaches new installs and a coordinator whose prompt is still empty.

find_bot now returns each match's instructions, so the coordinator can
judge a worker by what it was told rather than by its name.

(The previous prompt is kept as a commented-out block at the bottom of the
file.)
2026-10-22 20:11:03 +01:00
tben e8e4df6f56 Publish releases from two scripts, one per remote
A release meant running the RELEASING.md checklist by hand: tag, push
twice, create the GitHub release, then remember the Gitea push. The two
scripts do the machine-checkable part of it, with the shared flow in
scripts/lib/ so they cannot drift apart: clean worktree, not behind the
remote, typecheck, tests and the install.sh syntax check, then the tag at
HEAD, the branch push and the release object.

Only the release object differs. GitHub creates it with gh, and publishing
it is what fires the image build. Gitea gets the same notes through its
API, with the token from GITEA_TOKEN or the one tea already stored, since
nothing there builds images.

Both accept --version (defaulting to package.json), --branch, --yes,
--dry-run and --skip-checks, and a rerun finishes a release that failed
half way instead of starting over: an existing tag is reused, a pushed ref
is skipped and an existing release is left alone. A tag sitting on another
commit is refused, since publishing would ship that commit's code.
2026-10-22 20:10:59 +01:00
2315 changed files with 119040 additions and 6631 deletions
+2
View File
@@ -16,3 +16,5 @@ coverage
logs
*.log
assets
# The computer image builds on its own (computer/Dockerfile).
computer
+4
View File
@@ -16,7 +16,11 @@ jobs:
check:
runs-on: ubuntu-latest
steps:
# The publish tests read real release tags out of the history, so a
# shallow, tagless clone makes them fail.
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: oven-sh/setup-bun@v2
with:
+76 -36
View File
@@ -1,9 +1,21 @@
name: Release image
# Builds and pushes the multi-arch image to GHCR, the registry the installer
# defaults to.
#
# The Gitea registry is on a VPN, which a GitHub runner can never reach, so CI
# does not touch it at all: `scripts/mirror-gitea.sh` copies a release into it
# from the VPN side, in parallel and after the fact. Keeping the two apart is
# what makes a registry outage unable to fail a release.
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
@@ -30,13 +42,6 @@ jobs:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to Gitea
uses: docker/login-action@v3
with:
registry: git.tben.me
username: ${{ secrets.GITEA_USERNAME }}
password: ${{ secrets.GITEA_TOKEN }}
# The version the app reports on Settings > General when the build
# isn't a published release.
- name: Read the source version
@@ -45,6 +50,11 @@ jobs:
set -euo pipefail
echo "version=$(sed -n -E 's/^[[:space:]]*"version": "([^"]+)",?$/\1/p' package.json | head -n1)" >> "$GITHUB_OUTPUT"
# The same four tags for every kind of build: a release gets its own
# version plus the moving `latest` and `major.minor`, so that
# scripts/mirror-gitea.sh can copy whichever of them still belong to
# it, and a dispatch build gets the commit tag only, since it is not a
# release and must not move `latest`.
- name: Work out image tags
id: tags
env:
@@ -57,32 +67,24 @@ jobs:
if [ "$EVENT" = "release" ] && [ -n "$RELEASE_TAG" ]; then
version="$RELEASE_TAG"
minor="$(printf '%s' "$version" | sed -E 's/^v?([0-9]+)\.([0-9]+).*/\1.\2/')"
ghcr="$(printf '%s\n' \
tags="$(printf '%s\n' \
"ghcr.io/moduletrace/cobble:latest" \
"ghcr.io/moduletrace/cobble:${version}" \
"ghcr.io/moduletrace/cobble:${minor}" \
"ghcr.io/moduletrace/cobble:${sha}")"
gitea="$(printf '%s\n' \
"git.tben.me/moduletrace/cobble:latest" \
"git.tben.me/moduletrace/cobble:${version}" \
"git.tben.me/moduletrace/cobble:${minor}" \
"git.tben.me/moduletrace/cobble:${sha}")"
else
version="$SOURCE_VERSION"
ghcr="ghcr.io/moduletrace/cobble:${sha}"
gitea="git.tben.me/moduletrace/cobble:${sha}"
tags="ghcr.io/moduletrace/cobble:${sha}"
fi
{
echo "version=$version"
echo "ghcr<<EOF"
echo "$ghcr"
echo "EOF"
echo "gitea<<EOF"
echo "$gitea"
echo "tags<<EOF"
echo "$tags"
echo "EOF"
} >> "$GITHUB_OUTPUT"
# The registry the installer defaults to, so this one must succeed.
# The only push CI makes. The installer defaults to this registry, so
# this step failing has to fail the release.
- name: Build and push to GHCR
uses: docker/build-push-action@v6
with:
@@ -92,26 +94,64 @@ jobs:
push: true
build-args: |
COBBLE_VERSION=${{ steps.tags.outputs.version }}
tags: ${{ steps.tags.outputs.ghcr }}
tags: ${{ steps.tags.outputs.tags }}
provenance: false
sbom: false
cache-from: type=gha
cache-to: type=gha,mode=max
# The mirror's registry, from the image just built: no second build,
# and Cloudflare rate limiting git.tben.me (429/1015 on blob uploads)
# can never fail a release the installer depends on.
- name: Mirror to Gitea
continue-on-error: true
# 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:
GITEA_TAGS: ${{ steps.tags.outputs.gitea }}
GHCR_IMAGES: ${{ steps.tags.outputs.ghcr }}
REBUILD: ${{ github.event.inputs.rebuild_computer }}
run: |
set -euo pipefail
first_ghcr="$(printf '%s\n' "$GHCR_IMAGES" | head -n1)"
args=()
while IFS= read -r tag; do
[ -n "$tag" ] || continue
args+=(--tag "${tag}")
done <<< "$GITEA_TAGS"
docker buildx imagetools create "${args[@]}" "${first_ghcr}"
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
+3 -2
View File
@@ -11,7 +11,7 @@ coverage
*.lcov
# logs
logs
/logs
!src/pages/admin/logs/
_.log
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
@@ -53,4 +53,5 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
/public/sitemap.xml
/public/robots.txt
/public/sitemap-chunks/
/.tmp
/.tmp
/.playwright-mcp
+225 -212
View File
File diff suppressed because one or more lines are too long
+44 -17
View File
@@ -5,7 +5,7 @@
<img src="docs/readme/lockup-dark.svg#gh-dark-mode-only" alt="Cobble" height="56">
</h1>
A crew of small AI worker bots you host yourself.
A crew of small AI worker bots you host yourself (alpha).
![Cobble: a crew of small AI worker bots you host yourself](docs/readme/hero-light.png#gh-light-mode-only)
![Cobble: a crew of small AI worker bots you host yourself](docs/readme/hero-dark.png#gh-dark-mode-only)
@@ -19,12 +19,18 @@ A crew of small AI worker bots you host yourself.
</div>
> **Alpha.** Cobble is still in alpha: interfaces, database schema and
> settings change between releases, and things break. Install it to try it
> out and to tell us what is wrong, but keep your own backups (Settings >
> Backups) and do not put it in front of work you cannot lose. Every release
> is a real release: the installer updates an existing install in place and
> keeps its data.
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.
@@ -49,16 +55,18 @@ your data on your own machine.
| Crew | One coordinator and as many workers as you need, each with a name, a role, a hue and its own core instructions |
| Rail | The coordinator, your recent workers and their latest sessions, then your workspaces, each row carrying its status line |
| Chat | Markdown with @-mentions for bots and #-mentions for workspaces, replies and quotes, reactions, attachments, older messages on scroll, drafts kept locally |
| Stop | Stop a bot from the thinking row or the header menu: its queued and running work stops at once, everywhere you chat with it, and it goes idle |
| Header | The bot's model, provider and computer at a glance, one click from either, and its picture, instructions and settings on the avatar |
| 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 |
| Tools | Install your own MCP servers and custom HTTP, script or prompt tools, and give them to bots or workspaces |
| Skills | Write runbooks your bots follow. Each bot sees what a skill is for and reads the whole thing only when it needs it |
| Knowledge | Knowledgebases of documents and notes, given to bots or workspaces: every reply starts from the passages that fit, searched by one embedding model |
| App | Installable PWA with Web Push, dark mode, and a rail built for a phone |
## Screenshots
@@ -82,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)
@@ -118,6 +126,10 @@ point that at `http://<this machine>:7227`:
sign-in cookies `Secure`; Caddy does this by default, and nginx needs
`proxy_set_header X-Forwarded-Proto $scheme;`.
- Pass `/ws` through as well as ordinary requests, including the upgrade.
- Keep the address the browser used in `Host` (or send it as
`X-Forwarded-Host`). Live updates and the computers' terminals only accept
a websocket from the app's own address; Caddy and Cloudflare Tunnel keep
it, and nginx needs `proxy_set_header Host $host;`.
- Give the proxy a real certificate. Browsers treat plain HTTP as unsafe, so
the installable app, offline support, Web Push notifications and voice
recording stay off until the address is HTTPS.
@@ -175,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
@@ -185,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
@@ -237,15 +250,29 @@ queue and Web Push.
## Images
Every release publishes a multi-arch image to both registries:
Every release publishes a multi-arch image to
`ghcr.io/moduletrace/cobble`, which is what the installer pulls. Tags are
`latest`, the release version, `major.minor` and the commit sha.
- `ghcr.io/moduletrace/cobble`
- `git.tben.me/moduletrace/cobble`
The same image is copied into `git.tben.me/moduletrace/cobble` by
`bun run mirror:gitea`, which runs after the build over the VPN (the Gitea
registry is not on the public internet, so GitHub Actions cannot reach it).
Install from Gitea with `--image git.tben.me/moduletrace/cobble`, or build
from source with `docker build -t cobble:local .` and
`--image cobble --version local --no-pull`.
Tags are `latest`, the release version, `major.minor` and the commit sha.
Install from Gitea with
`--image git.tben.me/moduletrace/cobble`, or build from source with
`docker build -t cobble:local .` and `--image cobble --version local --no-pull`.
A release is published from a clean `main` with the two scripts, which tag the
`package.json` version, push and create the release objects:
```bash
scripts/publish-github.sh # or: bun run publish:github
scripts/publish-gitea.sh # or: bun run publish:gitea
```
Both take `--version VERSION`, `--dry-run` and `--yes`. Only the GitHub release
builds the image, and the Gitea registry is filled in afterwards, once that
build has finished and from the VPN, by `bun run mirror:gitea`; see
[RELEASING.md](RELEASING.md) for the full checklist.
## Development
+50 -11
View File
@@ -3,10 +3,22 @@
Cobble ships as a multi-arch container image and a single `install.sh`.
The repository starts private and is made public at the launch gate below.
Cobble is in **alpha** (see the note in `README.md`). Every release published
before v1.0.0 is an alpha release: interfaces, the database schema and the
settings may change between them, so a release that needs a migration step
has to say so in its notes, and Settings > General keeps saying the stage
until v1.0.0.
## One-time setup
- [ ] `GITEA_USERNAME` and `GITEA_TOKEN` are set as GitHub Actions secrets.
The token needs package write on the Gitea `Moduletrace` org.
- [ ] `scripts/publish-gitea.sh` can reach Gitea: either `GITEA_TOKEN` is
exported locally, or `tea login add` has been run for the host (the
script then reads the token from `~/.config/tea/config.yml`). It needs
`write:repository` on the repository to create the release.
- [ ] `scripts/publish-github.sh` can publish releases: `gh auth login` has
been run, and the token has `repo` scope.
- [ ] The Gitea repository exists at `git.tben.me/Moduletrace/cobble` and
`main` is pushed to both remotes.
- [ ] The GHCR package is made public after the first image push
@@ -16,6 +28,16 @@ The repository starts private and is made public at the launch gate below.
## Every release
The two publish scripts below do steps 1 to 3, 6 and 10 for you: they run the
same checks, tag `HEAD` with `package.json`'s version, push `main` and the tag,
and create the release object. Everything else is still hand work.
`scripts/publish-github.sh` publishes to GitHub and, by publishing the
release, starts the image build. `scripts/publish-gitea.sh` publishes the same
release to the Gitea mirror. Both accept `--version VERSION` (defaulting to
`package.json`), `--branch`, `--yes`, `--dry-run` and `--skip-checks`; run
them in that order, since only the GitHub release builds images.
1. [ ] `bun run typecheck` and `bun run test` pass locally.
2. [ ] CI is green on `main` in GitHub Actions.
3. [ ] `bash -n install.sh` passes.
@@ -27,28 +49,45 @@ The repository starts private and is made public at the launch gate below.
- `--uninstall` keeps data, `--uninstall --purge` removes it
5. [ ] Update the version if the release changes it, including
`package.json`'s `version` (the image reports it on Settings > General
when it isn't built from a release tag).
when it isn't built from a release tag, and the publish scripts tag
with it).
6. [ ] Tag and publish a GitHub release:
git tag v0.1.0
git push origin main --tags
gh release create v0.1.0 --title v0.1.0 --generate-notes
scripts/publish-github.sh # or: bun run publish:github
# by hand, the script does this:
git tag -a v0.1.0 -m v0.1.0
git push origin main
git push origin refs/tags/v0.1.0
gh release create v0.1.0 --title v0.1.0 --notes-file notes.md --latest
7. [ ] The release workflow builds `linux/amd64` and `linux/arm64` and
pushes to both registries:
- `ghcr.io/moduletrace/cobble`
- `git.tben.me/moduletrace/cobble`
pushes to `ghcr.io/moduletrace/cobble`, the registry the installer
defaults to. It does not touch Gitea: that registry is on the VPN,
and a GitHub runner cannot reach it.
8. [ ] Check the manifests:
docker buildx imagetools inspect ghcr.io/moduletrace/cobble:latest
docker buildx imagetools inspect git.tben.me/moduletrace/cobble:latest
9. [ ] Confirm the GHCR package is public and pull it anonymously.
10. [ ] Push the tag to Gitea as well:
10. [ ] Once the build has finished, copy the image into the Gitea registry
from the VPN:
git push gitea main --tags
GITEA_TOKEN=... bun run mirror:gitea # or: scripts/mirror-gitea.sh
11. [ ] Update every install with the one-liner:
It copies the version and commit tags, plus `latest` and
`major.minor` while this release still owns them, and reads every
destination digest back. A failure here does not affect the release:
the installer keeps working from GHCR.
11. [ ] Publish the release to Gitea as well:
scripts/publish-gitea.sh # or: bun run publish:gitea
# by hand, the script does this:
git push gitea main
git push gitea refs/tags/v0.1.0
12. [ ] Update every install with the one-liner:
curl -fsSL https://url.moduletrace.com/cobble | sudo bash
+237 -4
View File
@@ -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.6",
"@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",
@@ -18,6 +18,7 @@
"@tiptap/react": "3.32.0",
"@tiptap/starter-kit": "3.32.0",
"ace-builds": "^1.44.0",
"chart.js": "^4.6.1",
"dayjs": "^1.11.23",
"gray-matter": "^4.0.3",
"html-to-react": "^1.7.0",
@@ -25,6 +26,7 @@
"lucide-react": "^1.59.0",
"mammoth": "^1.12.1",
"mdx": "^0.3.1",
"mermaid": "^12.2.0",
"next-mdx-remote": "^6.0.0",
"nodemailer": "^9.0.5",
"openai": "^7.4.0",
@@ -58,6 +60,7 @@
"@types/sanitize-html": "^2.16.2",
"@types/turndown": "^5.0.6",
"@types/web-push": "^3.6.4",
"marked": "17.0.6",
"tailwindcss": "^4.3.3",
},
"peerDependencies": {
@@ -71,6 +74,8 @@
"packages": {
"@alloc/quick-lru": ["@alloc/[email protected]", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
"@antfu/install-pkg": ["@antfu/[email protected]", "", { "dependencies": { "package-manager-detector": "^1.8.0", "tinyexec": "^1.3.1" } }, "sha512-sdg9NxU3zR4Mnawfbc/x6GB5Wf17WYud5qOuEuxXjaKpYpMkISSJEjItGebXJ2bQ4DIcly4NYH23mtkGJjvKUw=="],
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
"@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
@@ -81,6 +86,18 @@
"@bedrock-layout/use-stateful-ref": ["@bedrock-layout/[email protected]", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18" } }, "sha512-pzVUYMTa32E9dGa2xadOFej96gYJEHg+Qh4Tg0fMj6zYT4y5LZpE+XkCiPcFafR3kTFhqSGfjRTIJbnSyeEAxQ=="],
"@braintree/sanitize-url": ["@braintree/[email protected]", "", {}, "sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA=="],
"@chevrotain/cst-dts-gen": ["@chevrotain/[email protected]", "", { "dependencies": { "@chevrotain/gast": "13.2.0", "@chevrotain/types": "13.2.0" } }, "sha512-bA9dvWlhAUcHkNwU+8w9yiUxJPlj/Lm3VqS7MD+NbIR/7LmpNLuK/AWNFdCo/T3SK5ND0/UHf3IJvl/Jn/i6yg=="],
"@chevrotain/gast": ["@chevrotain/[email protected]", "", { "dependencies": { "@chevrotain/types": "13.2.0" } }, "sha512-bCARdAsG+eEbOveSXcOAC7pVxA04I1ionzeMOwIYf5NX7SaS7zgn4Dgug2BSqoL+iyKeMNSorQjsFSHJHsCNwg=="],
"@chevrotain/regexp-to-ast": ["@chevrotain/[email protected]", "", {}, "sha512-kxpUkLtiaK09ph+dib+Yvm+3sWSnuwlo25gqfKRgTPNmF6H7uW4gVkMjaRdtnN783S9sM6vUNWh9CsxYX4QwKw=="],
"@chevrotain/types": ["@chevrotain/[email protected]", "", {}, "sha512-7qrYHRlKfWf2AvBfJi5eVOrKAkbxvMFsy/iIHTGIiApNcEecCaVIdR+mIQhyCBsTDJxBz4JWXHMo6krbhR9hVg=="],
"@chevrotain/utils": ["@chevrotain/[email protected]", "", {}, "sha512-SzKYY68rseOrb9KILVzPsl6SjkQtdWw01SRGB5aCVI5kFcHltQsOYV3JB0Ffst72DgkvHCyDQ0NLwxtmCCf97Q=="],
"@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
"@emotion/is-prop-valid": ["@emotion/[email protected]", "", { "dependencies": { "@emotion/memoize": "^0.9.0" } }, "sha512-QgD4fyscGcbbKwJmqNvUMSE02OsHUa+lAWKdEUIJKgqe5IwRSKd7+KhibEWdaKwgjLj0DRSHA9biAIqGBk05lw=="],
@@ -147,6 +164,10 @@
"@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q=="],
"@iconify/types": ["@iconify/[email protected]", "", {}, "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg=="],
"@iconify/utils": ["@iconify/[email protected]", "", { "dependencies": { "@antfu/install-pkg": "^2.0.1", "@iconify/types": "^2.0.0", "import-meta-resolve": "^4.2.0" } }, "sha512-JZHlwdID+dy+lTgbYC8NEC4zeugqeYsc6jewvzb4c58kHauJn+X7rNwQjxz5p2qSjqaEeQoLkCIQ9v/H4PK0/w=="],
"@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
"@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.2" }, "os": "darwin", "cpu": "arm64" }, "sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg=="],
@@ -243,19 +264,23 @@
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@kurkle/color": ["@kurkle/[email protected]", "", {}, "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w=="],
"@mdx-js/mdx": ["@mdx-js/[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdx": "^2.0.0", "acorn": "^8.0.0", "collapse-white-space": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "estree-util-scope": "^1.0.0", "estree-walker": "^3.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "markdown-extensions": "^2.0.0", "recma-build-jsx": "^1.0.0", "recma-jsx": "^1.0.0", "recma-stringify": "^1.0.0", "rehype-recma": "^1.0.0", "remark-mdx": "^3.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "source-map": "^0.7.0", "unified": "^11.0.0", "unist-util-position-from-estree": "^2.0.0", "unist-util-stringify-position": "^4.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ=="],
"@mdx-js/react": ["@mdx-js/[email protected]", "", { "dependencies": { "@types/mdx": "^2.0.0" }, "peerDependencies": { "@types/react": ">=16", "react": ">=16" } }, "sha512-f++rKLQgUVYDAtECQ6fn/is15GkEH9+nZPM3MS0RcxVqoTfawHvDlSCH7JbMhAM6uJ32v3eXLvLmLvjGu7PTQw=="],
"@mermaid-js/parser": ["@mermaid-js/[email protected]", "", { "dependencies": { "@chevrotain/types": "~13.2.0" } }, "sha512-j37dj/h6p6pots1L7pLPPNuABEEu9WP4OYg9pW1g+nYG331j0+3canE9OagtYdytYvdSAMG+2fKU5cxep6LgjA=="],
"@mixmark-io/domino": ["@mixmark-io/[email protected]", "", {}, "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw=="],
"@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].6", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.6/twui-0.1.6.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-BFNIV1itkIYXmhq1rBJA8E8MjwN9AP7MESbOnzM0yUb6xbsOFIBbmlKfUu6kTr7QCl1TWNxWTGFPVmQ2S54cDA=="],
"@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=="],
@@ -393,12 +418,76 @@
"@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
"@types/d3": ["@types/[email protected]", "", { "dependencies": { "@types/d3-array": "*", "@types/d3-axis": "*", "@types/d3-brush": "*", "@types/d3-chord": "*", "@types/d3-color": "*", "@types/d3-contour": "*", "@types/d3-delaunay": "*", "@types/d3-dispatch": "*", "@types/d3-drag": "*", "@types/d3-dsv": "*", "@types/d3-ease": "*", "@types/d3-fetch": "*", "@types/d3-force": "*", "@types/d3-format": "*", "@types/d3-geo": "*", "@types/d3-hierarchy": "*", "@types/d3-interpolate": "*", "@types/d3-path": "*", "@types/d3-polygon": "*", "@types/d3-quadtree": "*", "@types/d3-random": "*", "@types/d3-scale": "*", "@types/d3-scale-chromatic": "*", "@types/d3-selection": "*", "@types/d3-shape": "*", "@types/d3-time": "*", "@types/d3-time-format": "*", "@types/d3-timer": "*", "@types/d3-transition": "*", "@types/d3-zoom": "*" } }, "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww=="],
"@types/d3-array": ["@types/[email protected]", "", {}, "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw=="],
"@types/d3-axis": ["@types/[email protected]", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw=="],
"@types/d3-brush": ["@types/[email protected]", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A=="],
"@types/d3-chord": ["@types/[email protected]", "", {}, "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg=="],
"@types/d3-color": ["@types/[email protected]", "", {}, "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="],
"@types/d3-contour": ["@types/[email protected]", "", { "dependencies": { "@types/d3-array": "*", "@types/geojson": "*" } }, "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg=="],
"@types/d3-delaunay": ["@types/[email protected]", "", {}, "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw=="],
"@types/d3-dispatch": ["@types/[email protected]", "", {}, "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA=="],
"@types/d3-drag": ["@types/[email protected]", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ=="],
"@types/d3-dsv": ["@types/[email protected]", "", {}, "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g=="],
"@types/d3-ease": ["@types/[email protected]", "", {}, "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA=="],
"@types/d3-fetch": ["@types/[email protected]", "", { "dependencies": { "@types/d3-dsv": "*" } }, "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA=="],
"@types/d3-force": ["@types/[email protected]", "", {}, "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw=="],
"@types/d3-format": ["@types/[email protected]", "", {}, "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g=="],
"@types/d3-geo": ["@types/[email protected]", "", { "dependencies": { "@types/geojson": "*" } }, "sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w=="],
"@types/d3-hierarchy": ["@types/[email protected]", "", {}, "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg=="],
"@types/d3-interpolate": ["@types/[email protected]", "", { "dependencies": { "@types/d3-color": "*" } }, "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA=="],
"@types/d3-path": ["@types/[email protected]", "", {}, "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg=="],
"@types/d3-polygon": ["@types/[email protected]", "", {}, "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA=="],
"@types/d3-quadtree": ["@types/[email protected]", "", {}, "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg=="],
"@types/d3-random": ["@types/[email protected]", "", {}, "sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA=="],
"@types/d3-scale": ["@types/[email protected]", "", { "dependencies": { "@types/d3-time": "*" } }, "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw=="],
"@types/d3-scale-chromatic": ["@types/[email protected]", "", {}, "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ=="],
"@types/d3-selection": ["@types/[email protected]", "", {}, "sha512-Qe/KWYhEiIIxGs7HrAAjMfShxKldx19SJtr5zu53f3afPsdZNz7HHtdTLXo/kqeiWNXVycI24kSnfzBYkTzpgw=="],
"@types/d3-shape": ["@types/[email protected]", "", { "dependencies": { "@types/d3-path": "*" } }, "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw=="],
"@types/d3-time": ["@types/[email protected]", "", {}, "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g=="],
"@types/d3-time-format": ["@types/[email protected]", "", {}, "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg=="],
"@types/d3-timer": ["@types/[email protected]", "", {}, "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw=="],
"@types/d3-transition": ["@types/[email protected]", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg=="],
"@types/d3-zoom": ["@types/[email protected]", "", { "dependencies": { "@types/d3-interpolate": "*", "@types/d3-selection": "*" } }, "sha512-0sE1406XBYJGiqD3AusTl9ZqC//2mIXix51tbom25gDCA8ri4xnSZg28CaSE8Srl6FClqABUKfsn0qghgdepMA=="],
"@types/debug": ["@types/[email protected]", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="],
"@types/estree": ["@types/[email protected]", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],
"@types/estree-jsx": ["@types/[email protected]", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="],
"@types/geojson": ["@types/[email protected]", "", {}, "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg=="],
"@types/hast": ["@types/[email protected]", "", { "dependencies": { "@types/unist": "*" } }, "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g=="],
"@types/lodash": ["@types/[email protected]", "", {}, "sha512-+K1NIO8I+F9/wNulfVvu23QYd0Pe9/OCqRrim4NoYIf1VoEDL90Ve4ClzpyqBLc7NpGGWRvYNCKZ1BE/Jpf8dQ=="],
@@ -421,6 +510,8 @@
"@types/sanitize-html": ["@types/[email protected]", "", { "dependencies": { "htmlparser2": "^12.0" } }, "sha512-kuAbgDCFv418flrp3z4o/4ufLA/5ovmXRH0L419iZCPGO7w00znjeDI5Wy/KZWNIBpDQc7hucCK+J5almB6FyA=="],
"@types/trusted-types": ["@types/[email protected]", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="],
"@types/turndown": ["@types/[email protected]", "", {}, "sha512-ru00MoyeeouE5BX4gRL+6m/BsDfbRayOskWqUvh7CLGW+UXxHQItqALa38kKnOiZPqJrtzJUgAC2+F0rL1S4Pg=="],
"@types/unist": ["@types/[email protected]", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
@@ -471,6 +562,8 @@
"@ungap/structured-clone": ["@ungap/[email protected]", "", {}, "sha512-60YRaenCQcVjYEKOcG824+DRGGIQ3VKErcBoAEDJZz5bKIs2ZG+X/H9Nk+Q6EVkwJk5QNApxbrc5QtBSwtrXAg=="],
"@upsetjs/venn.js": ["@upsetjs/[email protected]", "", { "optionalDependencies": { "d3-selection": "^3.0.0", "d3-transition": "^3.0.1" } }, "sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw=="],
"@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw=="],
"accepts": ["[email protected]", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
@@ -547,6 +640,10 @@
"chardet": ["[email protected]", "", {}, "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA=="],
"chart.js": ["[email protected]", "", { "dependencies": { "@kurkle/color": "^0.3.0" } }, "sha512-hJyniucsFmq//EvXYvJ6c6mahPoI3kaxdjVH8awTaJ/fDNWeSqqqArixMJWkWNN6fcYvPU3HneSANFNYtRi61g=="],
"chevrotain": ["[email protected]", "", { "dependencies": { "@chevrotain/cst-dts-gen": "13.2.0", "@chevrotain/gast": "13.2.0", "@chevrotain/regexp-to-ast": "13.2.0", "@chevrotain/types": "13.2.0", "@chevrotain/utils": "13.2.0" } }, "sha512-GTouk5YzgBxlTPCaDn5q0q2EJKkrYmnPF+HmF8v0Qo4r3iyPG7HJivkN1wthCXZcm3sIcZFpGTRovLPNdJNRCA=="],
"chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="],
"classnames": ["[email protected]", "", {}, "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow=="],
@@ -577,6 +674,8 @@
"cors": ["[email protected]", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
"cose-base": ["[email protected]", "", { "dependencies": { "layout-base": "^1.0.0" } }, "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg=="],
"crc-32": ["[email protected]", "", { "bin": { "crc32": "bin/crc32.njs" } }, "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ=="],
"cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
@@ -589,12 +688,86 @@
"currently-unhandled": ["[email protected]", "", { "dependencies": { "array-find-index": "^1.0.1" } }, "sha512-/fITjgjGU50vjQ4FH6eUoYu+iUoUKIXws2hL15JJpIR+BbTxaXQsMuuyjtNh2WqsSBS5nsaZHFsFecyw5CCAng=="],
"cytoscape": ["[email protected]", "", {}, "sha512-msY99tMY8iWTg+sIPGfSqDcPNOt4xcj+v/K/7qUFaCUxxlqnMkUYLBjRUzn9W5CU/R2hrmtJa5+UtovrEM2ctg=="],
"cytoscape-cose-bilkent": ["[email protected]", "", { "dependencies": { "cose-base": "^1.0.0" }, "peerDependencies": { "cytoscape": "^3.2.0" } }, "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ=="],
"cytoscape-fcose": ["[email protected]", "", { "dependencies": { "cose-base": "^2.2.0" }, "peerDependencies": { "cytoscape": "^3.2.0" } }, "sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ=="],
"d3": ["[email protected]", "", { "dependencies": { "d3-array": "3", "d3-axis": "3", "d3-brush": "3", "d3-chord": "3", "d3-color": "3", "d3-contour": "4", "d3-delaunay": "6", "d3-dispatch": "3", "d3-drag": "3", "d3-dsv": "3", "d3-ease": "3", "d3-fetch": "3", "d3-force": "3", "d3-format": "3", "d3-geo": "3", "d3-hierarchy": "3", "d3-interpolate": "3", "d3-path": "3", "d3-polygon": "3", "d3-quadtree": "3", "d3-random": "3", "d3-scale": "4", "d3-scale-chromatic": "3", "d3-selection": "3", "d3-shape": "3", "d3-time": "3", "d3-time-format": "4", "d3-timer": "3", "d3-transition": "3", "d3-zoom": "3" } }, "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA=="],
"d3-array": ["[email protected]", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg=="],
"d3-axis": ["[email protected]", "", {}, "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw=="],
"d3-brush": ["[email protected]", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-drag": "2 - 3", "d3-interpolate": "1 - 3", "d3-selection": "3", "d3-transition": "3" } }, "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ=="],
"d3-chord": ["[email protected]", "", { "dependencies": { "d3-path": "1 - 3" } }, "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g=="],
"d3-color": ["[email protected]", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="],
"d3-contour": ["[email protected]", "", { "dependencies": { "d3-array": "^3.2.0" } }, "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA=="],
"d3-delaunay": ["[email protected]", "", { "dependencies": { "delaunator": "5" } }, "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A=="],
"d3-dispatch": ["[email protected]", "", {}, "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg=="],
"d3-drag": ["[email protected]", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-selection": "3" } }, "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg=="],
"d3-dsv": ["[email protected]", "", { "dependencies": { "commander": "7", "iconv-lite": "0.6", "rw": "1" }, "bin": { "csv2json": "bin/dsv2json.js", "csv2tsv": "bin/dsv2dsv.js", "dsv2dsv": "bin/dsv2dsv.js", "dsv2json": "bin/dsv2json.js", "json2csv": "bin/json2dsv.js", "json2dsv": "bin/json2dsv.js", "json2tsv": "bin/json2dsv.js", "tsv2csv": "bin/dsv2dsv.js", "tsv2json": "bin/dsv2json.js" } }, "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q=="],
"d3-ease": ["[email protected]", "", {}, "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w=="],
"d3-fetch": ["[email protected]", "", { "dependencies": { "d3-dsv": "1 - 3" } }, "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw=="],
"d3-force": ["[email protected]", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-quadtree": "1 - 3", "d3-timer": "1 - 3" } }, "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg=="],
"d3-format": ["[email protected]", "", {}, "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg=="],
"d3-geo": ["[email protected]", "", { "dependencies": { "d3-array": "2.5.0 - 3" } }, "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q=="],
"d3-hierarchy": ["[email protected]", "", {}, "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA=="],
"d3-interpolate": ["[email protected]", "", { "dependencies": { "d3-color": "1 - 3" } }, "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g=="],
"d3-path": ["[email protected]", "", {}, "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ=="],
"d3-polygon": ["[email protected]", "", {}, "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg=="],
"d3-quadtree": ["[email protected]", "", {}, "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw=="],
"d3-random": ["[email protected]", "", {}, "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ=="],
"d3-sankey": ["[email protected]", "", { "dependencies": { "d3-array": "1 - 2", "d3-shape": "^1.2.0" } }, "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ=="],
"d3-scale": ["[email protected]", "", { "dependencies": { "d3-array": "2.10.0 - 3", "d3-format": "1 - 3", "d3-interpolate": "1.2.0 - 3", "d3-time": "2.1.1 - 3", "d3-time-format": "2 - 4" } }, "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ=="],
"d3-scale-chromatic": ["[email protected]", "", { "dependencies": { "d3-color": "1 - 3", "d3-interpolate": "1 - 3" } }, "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ=="],
"d3-selection": ["[email protected]", "", {}, "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ=="],
"d3-shape": ["[email protected]", "", { "dependencies": { "d3-path": "^3.1.0" } }, "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA=="],
"d3-time": ["[email protected]", "", { "dependencies": { "d3-array": "2 - 3" } }, "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q=="],
"d3-time-format": ["[email protected]", "", { "dependencies": { "d3-time": "1 - 3" } }, "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg=="],
"d3-timer": ["[email protected]", "", {}, "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA=="],
"d3-transition": ["[email protected]", "", { "dependencies": { "d3-color": "1 - 3", "d3-dispatch": "1 - 3", "d3-ease": "1 - 3", "d3-interpolate": "1 - 3", "d3-timer": "1 - 3" }, "peerDependencies": { "d3-selection": "2 - 3" } }, "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w=="],
"d3-zoom": ["[email protected]", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-drag": "2 - 3", "d3-interpolate": "1 - 3", "d3-selection": "2 - 3", "d3-transition": "2 - 3" } }, "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw=="],
"dagre-d3-es": ["[email protected]", "", { "dependencies": { "d3": "^7.9.0", "lodash-es": "^4.17.21" } }, "sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg=="],
"dayjs": ["[email protected]", "", {}, "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ=="],
"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"decode-named-character-reference": ["[email protected]", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="],
"delaunator": ["[email protected]", "", { "dependencies": { "robust-predicates": "^3.0.2" } }, "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ=="],
"depd": ["[email protected]", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"dequal": ["[email protected]", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="],
@@ -611,6 +784,8 @@
"domhandler": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.3.0" } }, "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w=="],
"dompurify": ["[email protected]", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w=="],
"domutils": ["[email protected]", "", { "dependencies": { "dom-serializer": "^3.0.0", "domelementtype": "^3.0.0", "domhandler": "^6.0.0" } }, "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA=="],
"duck": ["[email protected]", "", { "dependencies": { "underscore": "^1.13.1" } }, "sha512-wkctla1O6VfP89gQ+J/yDesM0S7B7XLXjKGzXxMDVFg7uEn706niAtyYovKbyq1oT9YwDcly721/iUWoc8MVRg=="],
@@ -621,6 +796,8 @@
"ee-first": ["[email protected]", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"elkjs": ["[email protected]", "", {}, "sha512-f/ZeWvW/BCXbhGEf1Ujp29EASo/lk1FDnETgNKwJrsVvGZhUWCZyg3xLJjAsxfOmt8KjswHmI5EwCQcPMpOYhQ=="],
"encodeurl": ["[email protected]", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
"enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="],
@@ -635,6 +812,8 @@
"es-object-atoms": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="],
"es-toolkit": ["[email protected]", "", {}, "sha512-3+AYXp9fmJ/UhHBMYj2/U+RaUouMD90SzoItyDOB2Za7W6dB7fQApFGnZPl2MF6K8/Tv1koh1JyirSx/kju6Pw=="],
"esast-util-from-estree": ["[email protected]", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "devlop": "^1.0.0", "estree-util-visit": "^2.0.0", "unist-util-position-from-estree": "^2.0.0" } }, "sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ=="],
"esast-util-from-js": ["[email protected]", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "acorn": "^8.0.0", "esast-util-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-8Ja+rNJ0Lt56Pcf3TAmpBZjmx8ZcK5Ts4cAzIOjsjevg9oSXJnl6SUQ2EevU8tv3h6ZLWmoKL5H4fgWvdvfETw=="],
@@ -717,6 +896,8 @@
"gray-matter": ["[email protected]", "", { "dependencies": { "js-yaml": "^3.13.1", "kind-of": "^6.0.2", "section-matter": "^1.0.0", "strip-bom-string": "^1.0.0" } }, "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q=="],
"hachure-fill": ["[email protected]", "", {}, "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg=="],
"has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
"hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
@@ -761,6 +942,8 @@
"immediate": ["[email protected]", "", {}, "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="],
"import-meta-resolve": ["[email protected]", "", {}, "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg=="],
"indent-string": ["[email protected]", "", { "dependencies": { "repeating": "^2.0.0" } }, "sha512-aqwDFWSgSgfRaEwao5lg5KEcVd/2a+D1rvoG7NdilmYz0NwRk6StWpWdz/Hpk34MKPpx7s8XxUqimfcQK6gGlg=="],
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
@@ -769,6 +952,8 @@
"inquirer": ["[email protected]", "", { "dependencies": { "@inquirer/ansi": "^2.0.5", "@inquirer/core": "^11.1.10", "@inquirer/prompts": "^8.4.3", "@inquirer/type": "^4.0.5", "mute-stream": "^3.0.0", "run-async": "^4.0.6", "rxjs": "^7.8.2" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-EPd3IqieHSavSOXh+LZhrIkdQcOELWeRblLT6kslQr+cF9XTh/HxZdSt1YkHH1iq4dvqBnV42uwg2YlorgOy6g=="],
"internmap": ["[email protected]", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
"ip-address": ["[email protected]", "", {}, "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg=="],
"ipaddr.js": ["[email protected]", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
@@ -823,10 +1008,16 @@
"jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],
"katex": ["[email protected]", "", { "dependencies": { "commander": "^15.0.0" }, "bin": { "katex": "cli.js" } }, "sha512-yvyz/2VMKqoho/35Hat5w37wIEdWJ5ElVMidTAlWrxr5uW4aBGsEpveTmKh18/zw08v/7lGswCPon4OhqmqrTA=="],
"khroma": ["[email protected]", "", {}, "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw=="],
"kind-of": ["[email protected]", "", {}, "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw=="],
"launder": ["[email protected]", "", { "dependencies": { "dayjs": "^1.11.23" } }, "sha512-DLg3HPnHUfBi5/MxMLmJD12dmlMpFEC2HgMW6vkZ/9JR0RU00kXoRGvDxAvFmdO0o610OA77i4FgNTLucmhDVg=="],
"layout-base": ["[email protected]", "", {}, "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg=="],
"lie": ["[email protected]", "", { "dependencies": { "immediate": "~3.0.5" } }, "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ=="],
"lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
@@ -861,6 +1052,8 @@
"lodash": ["[email protected]", "", {}, "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q=="],
"lodash-es": ["[email protected]", "", {}, "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A=="],
"lodash.camelcase": ["[email protected]", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="],
"log-symbols": ["[email protected]", "", { "dependencies": { "is-unicode-supported": "^2.0.0", "yoctocolors": "^2.1.1" } }, "sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg=="],
@@ -931,6 +1124,8 @@
"merge-descriptors": ["[email protected]", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
"mermaid": ["[email protected]", "", { "dependencies": { "@braintree/sanitize-url": "^7.1.2", "@iconify/utils": "^3.0.2", "@mermaid-js/parser": "^2.0.1", "@types/d3": "^7.4.3", "@upsetjs/venn.js": "^2.0.0", "chevrotain": "~13.2.0", "cytoscape": "^3.34.0", "cytoscape-cose-bilkent": "^4.1.0", "cytoscape-fcose": "^2.2.0", "d3": "^7.9.0", "d3-sankey": "^0.12.3", "dagre-d3-es": "7.0.14", "dayjs": "^1.11.21", "dompurify": "^3.4.12", "elkjs": "^0.9.3", "es-toolkit": "^1.45.1", "katex": "^0.18.0", "khroma": "^2.1.0", "marked": "^16.3.0", "roughjs": "^4.6.6", "stylis": "^4.3.6", "ts-dedent": "^2.2.0", "uuid": "^11.1.0 || ^12 || ^13 || ^14.0.0" } }, "sha512-w7nr/SFrLO7BaVTs3dQTvYSV6nYSBj0Yy9DjBhsIJtAcHqRzXSq4Pg32ujHZ/AdWsAMNEvvhbm5dt9E2tOiHzw=="],
"micromark": ["[email protected]", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA=="],
"micromark-core-commonmark": ["[email protected]", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg=="],
@@ -1045,6 +1240,8 @@
"orderedmap": ["[email protected]", "", {}, "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g=="],
"package-manager-detector": ["[email protected]", "", {}, "sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA=="],
"pako": ["[email protected]", "", {}, "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="],
"parse-entities": ["[email protected]", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="],
@@ -1059,6 +1256,8 @@
"parseurl": ["[email protected]", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
"path-data-parser": ["[email protected]", "", {}, "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w=="],
"path-exists": ["[email protected]", "", { "dependencies": { "pinkie-promise": "^2.0.0" } }, "sha512-yTltuKuhtNeFJKa1PiRzfLAU5182q1y4Eb4XCJ3PBqyzEDkAZRzBrKKBct682ls9reBVHf9udYLN5Nd+K1B9BQ=="],
"path-is-absolute": ["[email protected]", "", {}, "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg=="],
@@ -1083,6 +1282,10 @@
"pkce-challenge": ["[email protected]", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"points-on-curve": ["[email protected]", "", {}, "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A=="],
"points-on-path": ["[email protected]", "", { "dependencies": { "path-data-parser": "0.1.0", "points-on-curve": "0.2.0" } }, "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g=="],
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA=="],
"postcss-value-parser": ["[email protected]", "", {}, "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="],
@@ -1187,12 +1390,18 @@
"restore-cursor": ["[email protected]", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="],
"robust-predicates": ["[email protected]", "", {}, "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA=="],
"rope-sequence": ["[email protected]", "", {}, "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ=="],
"roughjs": ["[email protected]", "", { "dependencies": { "hachure-fill": "^0.5.2", "path-data-parser": "^0.1.0", "points-on-curve": "^0.2.0", "points-on-path": "^0.2.1" } }, "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ=="],
"router": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
"run-async": ["[email protected]", "", {}, "sha512-IoDlSLTs3Yq593mb3ZoKWKXMNu3UpObxhgA/Xuid5p4bbfi2jdY1Hj0m1K+0/tEuQTxIGMhQDqGjKb7RuxGpAQ=="],
"rw": ["[email protected]", "", {}, "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ=="],
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
"safe-buffer": ["[email protected]", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
@@ -1295,6 +1504,8 @@
"tapable": ["[email protected]", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="],
"tinyexec": ["[email protected]", "", {}, "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="],
"toidentifier": ["[email protected]", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"trim-lines": ["[email protected]", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="],
@@ -1303,6 +1514,8 @@
"trough": ["[email protected]", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="],
"ts-dedent": ["[email protected]", "", {}, "sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg=="],
"tslib": ["[email protected]", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="],
"turndown": ["[email protected]", "", { "dependencies": { "@mixmark-io/domino": "^2.2.0" } }, "sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ=="],
@@ -1417,6 +1630,16 @@
"body-parser/content-type": ["[email protected]", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="],
"cytoscape-fcose/cose-base": ["[email protected]", "", { "dependencies": { "layout-base": "^2.0.0" } }, "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g=="],
"d3-dsv/commander": ["[email protected]", "", {}, "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw=="],
"d3-dsv/iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
"d3-sankey/d3-array": ["[email protected]", "", { "dependencies": { "internmap": "^1.0.0" } }, "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ=="],
"d3-sankey/d3-shape": ["[email protected]", "", { "dependencies": { "d3-path": "1" } }, "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw=="],
"decode-named-character-reference/character-entities": ["[email protected]", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="],
"dom-serializer/domhandler": ["[email protected]", "", { "dependencies": { "domelementtype": "^3.0.0" } }, "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg=="],
@@ -1431,12 +1654,16 @@
"htmlparser2/domhandler": ["[email protected]", "", { "dependencies": { "domelementtype": "^3.0.0" } }, "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg=="],
"katex/commander": ["[email protected]", "", {}, "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg=="],
"lightningcss-wasm/napi-wasm": ["[email protected]", "", { "bundled": true }, "sha512-h/4nMGsHjZDCYmQVNODIrYACVJ+I9KItbG+0si6W/jSjdA9JbWDoU4LLeMXVcEQGHjttI2tuXqDrbGF7qkUHHg=="],
"loud-rejection/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
"mdast-util-find-and-replace/escape-string-regexp": ["[email protected]", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
"mermaid/marked": ["[email protected]", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA=="],
"negotiator/content-type": ["[email protected]", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="],
"normalize-package-data/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver" } }, "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g=="],
@@ -1459,6 +1686,12 @@
"@tailwindcss/postcss/postcss/source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"cytoscape-fcose/cose-base/layout-base": ["[email protected]", "", {}, "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg=="],
"d3-sankey/d3-array/internmap": ["[email protected]", "", {}, "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw=="],
"d3-sankey/d3-shape/d3-path": ["[email protected]", "", {}, "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg=="],
"html-to-react/htmlparser2/domelementtype": ["[email protected]", "", {}, "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="],
"html-to-react/htmlparser2/domutils": ["[email protected]", "", { "dependencies": { "dom-serializer": "^2.0.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3" } }, "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="],
+2
View File
@@ -0,0 +1,2 @@
**/*.test.ts
**/node_modules
+150
View File
@@ -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"]
+151
View File
@@ -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
```
+15
View File
@@ -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: "",
};
+38
View File
@@ -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",
];
+49
View File
@@ -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);
}
+121
View File
@@ -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();
});
}
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, test } from "bun:test";
import browserArgs, { DiskCacheMaxBytes } 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("caps the disk cache, so a profile can't grow by gigabytes", () => {
const args = browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1 });
expect(args).toContain(`--disk-cache-size=${DiskCacheMaxBytes}`);
expect(DiskCacheMaxBytes).toBe(512 * 1024 * 1024);
});
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");
});
});
+117
View File
@@ -0,0 +1,117 @@
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 on-disk HTTP cache, in bytes. Left to itself Chrome grows it to
a few gigabytes inside the profile, which is mounted and never shrinks;
what it holds is fetched again on demand.
*/
export const DiskCacheMaxBytes = 512 * 1024 * 1024;
/**
* 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)}`,
`--disk-cache-size=${DiskCacheMaxBytes}`,
...(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(",")}`,
];
}
+48
View File
@@ -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);
});
});
+14
View File
@@ -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);
});
});
+11
View File
@@ -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;
}
+22
View File
@@ -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 });
}
}
+15
View File
@@ -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"],
});
});
});
+14
View File
@@ -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],
};
}
+144
View File
@@ -0,0 +1,144 @@
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 has no time limit of its own: its caller asks for one (a
* bot's `computer_bash` leaves it out for long scripts) and the
* caller going away still kills it (`handle-exec`). Output past this is
* dropped, and the response says so.
*/
CommandMaxOutputBytes: 4 * 1024 * 1024,
/**
* A command sends nothing while it runs, and the app's HTTP client gives
* up on a connection that stays silent for minutes (Bun's own fetch cuts
* one after about six minutes), so the answer keeps it alive with a space
* this often. `JSON.parse` ignores the whitespace around the document.
*/
CommandHeartbeatMs: 15_000,
/**
* How long children get to exit on a stop before they're killed.
*/
StopGraceMs: 8000,
};
+147
View File
@@ -0,0 +1,147 @@
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 handleUsage from "./handle-usage";
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`).
* - `GET /api/usage`: how much the workspace holds.
* - `/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 });
if (pathname == "/api/usage" && req.method == "GET") return handleUsage({ req, res });
sendJson({ res, status: 404, body: { error: "Not Found" } });
}
+172
View File
@@ -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();
},
};
}
+41
View File
@@ -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]);
}
+199
View File
@@ -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,
);
}
+14
View File
@@ -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;
}
+24
View File
@@ -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();
});
});
+38
View File
@@ -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");
}
+32
View File
@@ -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}` });
}
}
+81
View File
@@ -0,0 +1,81 @@
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. It runs until
* it ends unless the caller gives `timeout_seconds`, and is killed if the
* caller goes away. Answers `{ output, exit_code, timed_out, truncated }`
* after a space every `CommandHeartbeatMs` while it runs, so a client that
* drops a silent connection keeps it.
*/
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);
/**
* A command has no time limit unless the caller asks for one: nothing,
* or 0, means it runs until it ends, the caller goes away (this
* response closes) or the container stops. A positive value is that
* many seconds, however long, so a bot's script is never cut short.
*/
const timeout_seconds = Number.isFinite(asked) && asked > 0 ? Math.ceil(asked) : null;
const controller = new AbortController();
res.on("close", () => {
if (!res.writableFinished) controller.abort();
});
/**
* A heartbeat into a socket the caller closed must not take the agent
* down, and there's nothing left to send it: stop the command.
*/
res.on("error", () => controller.abort());
const home = run_user ? run_user.home : AgentConfig.Home;
if (res.destroyed) return;
/**
* The result goes out as one JSON body once the command ends, which may
* be hours away, so the answer is opened now and kept alive with a space
* until then: a client that drops a silent connection (`fetch` does, at
* about six minutes) would otherwise lose the command's output and think
* it failed. A space before the document is still JSON.
*/
res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
const heartbeat = setInterval(() => {
if (!res.destroyed) res.write(" ");
}, AgentConfig.CommandHeartbeatMs);
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,
});
clearInterval(heartbeat);
if (!res.destroyed) res.end(JSON.stringify(result));
}
+60
View File
@@ -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);
}
+38
View File
@@ -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),
},
});
}
+70
View File
@@ -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);
}
}
+20
View File
@@ -0,0 +1,20 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { AgentConfig } from "./config";
import sendJson from "./send-json";
import { workspaceUsage } from "./workspace-usage";
/**
* `GET /api/usage`: what the computer's workspace holds, and its biggest
* folders (`workspaceUsage`). Only sizes: what may be written there is the
* app's call (`grabComputerWorkspaceQuotaBytes`), so changing the limit
* needs no new container. The folders are how a full one is told apart from
* a bot's own overrun, which the app says in its refusal.
*/
export default async function handleUsage({ res }: { req: IncomingMessage; res: ServerResponse }) {
const { bytes, folders } = await workspaceUsage();
sendJson({
res,
body: { used_bytes: bytes, workspace_dir: AgentConfig.WorkspaceDir, folders },
});
}
+15
View File
@@ -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);
});
});
+17
View File
@@ -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);
}
+19
View File
@@ -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;
}
}
+6
View File
@@ -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`);
}
+52
View File
@@ -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"]);
});
});
+44
View File
@@ -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}=`));
}
+175
View File
@@ -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();
});
}
+28
View File
@@ -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;
}
+14
View File
@@ -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());
}
+12
View File
@@ -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;
}
+71
View File
@@ -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(() => {});
}
}
+32
View File
@@ -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);
}
+41
View File
@@ -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,65 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pruneProfileCache from "./prune-profile-cache";
/**
* The profile is mounted from the data volume, so whatever this clears is
* gone for good. A cache comes back by itself, an extension's own state
* never does, so only caches may ever be in these lists.
*/
const roots: string[] = [];
function profile() {
const root = mkdtempSync(path.join(tmpdir(), "cobble-profile-"));
roots.push(root);
return root;
}
function write({ root, relative }: { root: string; relative: string }) {
const target = path.join(root, relative);
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(target, "x".repeat(1024));
}
function exists({ root, relative }: { root: string; relative: string }) {
return require("node:fs").existsSync(path.join(root, relative));
}
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
});
describe("pruneProfileCache", () => {
test("keeps an extension's own state", () => {
const root = profile();
write({ root, relative: "Default/Storage/ext/abc/def" });
write({ root, relative: "Default/Local Storage/leveldb/000003.log" });
pruneProfileCache({ profile_dir: root });
expect(exists({ root, relative: "Default/Storage/ext/abc/def" })).toBeTrue();
expect(exists({ root, relative: "Default/Local Storage/leveldb/000003.log" })).toBeTrue();
});
test("never touches a login, a permission or history", () => {
const root = profile();
write({ root, relative: "Default/Cookies" });
write({ root, relative: "Default/Login Data" });
write({ root, relative: "Default/Preferences" });
write({ root, relative: "Default/History" });
write({ root, relative: "Default/Extensions/abc/1.0/manifest.json" });
pruneProfileCache({ profile_dir: root });
for (const relative of ["Default/Cookies", "Default/Login Data", "Default/Preferences", "Default/History", "Default/Extensions/abc/1.0/manifest.json"]) {
expect(exists({ root, relative })).toBeTrue();
}
});
});
@@ -0,0 +1,97 @@
import { afterEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pruneProfileCache from "./prune-profile-cache";
/**
* The profile is mounted so logins survive a restart, and this runs at
* every start: a folder wrongly listed here would log the user out of
* every site, and one wrongly left out grows the volume forever.
*/
const dirs: string[] = [];
function profile() {
const dir = mkdtempSync(path.join(tmpdir(), "cobble-profile-"));
dirs.push(dir);
return dir;
}
function write({ root, relative, bytes }: { root: string; relative: string; bytes: number }) {
const target = path.join(root, relative);
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(target, "x".repeat(bytes));
}
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
describe("pruneProfileCache", () => {
test("clears a profile's caches and the ones Chrome keeps beside it", () => {
const root = profile();
write({ root, relative: "Default/Cache/data_0", bytes: 400 });
write({ root, relative: "Default/Code Cache/js/index", bytes: 300 });
write({ root, relative: "Default/Service Worker/CacheStorage/a/b", bytes: 200 });
write({ root, relative: "Profile 1/Cache/data_0", bytes: 100 });
write({ root, relative: "ShaderCache/data", bytes: 500 });
write({ root, relative: "GPUCache/data", bytes: 50 });
expect(pruneProfileCache({ profile_dir: root })).toBe(1550);
for (const gone of [
"Default/Cache",
"Default/Code Cache",
"Default/Service Worker/CacheStorage",
"Profile 1/Cache",
"ShaderCache",
"GPUCache",
]) {
expect(existsSync(path.join(root, gone))).toBe(false);
}
});
test("never touches a login, a permission or an extension", () => {
const root = profile();
write({ root, relative: "Default/Cookies", bytes: 10 });
write({ root, relative: "Default/Login Data", bytes: 10 });
write({ root, relative: "Default/Preferences", bytes: 10 });
write({ root, relative: "Default/Local Storage/leveldb/a.log", bytes: 10 });
write({ root, relative: "Default/Extensions/abc/1.0/page.html", bytes: 10 });
write({ root, relative: "Local State", bytes: 10 });
expect(pruneProfileCache({ profile_dir: root })).toBe(0);
for (const kept of [
"Default/Cookies",
"Default/Login Data",
"Default/Preferences",
"Default/Local Storage",
"Default/Extensions",
"Local State",
]) {
expect(existsSync(path.join(root, kept))).toBe(true);
}
});
test("a folder that isn't a profile is left alone", () => {
const root = profile();
write({ root, relative: "SomeOtherProfile/Cache/data_0", bytes: 400 });
expect(pruneProfileCache({ profile_dir: root })).toBe(0);
expect(readdirSync(root)).toEqual(["SomeOtherProfile"]);
});
test("an empty or missing profile frees nothing and throws nothing", () => {
const root = profile();
expect(pruneProfileCache({ profile_dir: root })).toBe(0);
expect(pruneProfileCache({ profile_dir: path.join(root, "missing") })).toBe(0);
});
});
+121
View File
@@ -0,0 +1,121 @@
import { readdirSync, rmSync, statSync } from "node:fs";
import path from "node:path";
import log from "./log";
/**
* Folders inside a browser profile that only ever hold what Chrome can
* download or build again. Cookies, logins, site permissions, history,
* local storage and extensions live elsewhere and are never touched: the
* profile is mounted so a computer keeps them across restarts.
*/
const RegenerableProfileDirs = [
"ShaderCache",
"GrShaderCache",
"GPUCache",
"GPUPersistentCache",
"GraphiteDawnCache",
"DawnGraphiteCache",
"DawnWebGPUCache",
"component_crx_cache",
"CertificateRevocation",
"optimization_guide_model_store",
];
/**
* The same, in each profile's own folder (`Default`, `Profile 1`, ...).
* Never `Local Storage`, `IndexedDB` or `Storage/ext`: those are what the
* extensions a computer keeps (Cookie-Editor among them) hold their own
* state in, which is not rebuilt by downloading anything.
*/
const RegenerableBrowserDirs = [
"Cache",
"Code Cache",
"GPUCache",
"GPUPersistentCache",
"GraphiteDawnCache",
"DawnGraphiteCache",
"DawnWebGPUCache",
"Service Worker/CacheStorage",
"Service Worker/ScriptCache",
];
/**
* Frees what Chrome downloaded or built last time it ran and will build
* again: extension assets, the component updater's CRX cache, model files,
* certificate revocation lists, HTTP and code caches. A profile otherwise
* grows by hundreds of megabytes and never shrinks.
*
* Only called while no browser runs (a cache cleared under a live Chrome
* leaves it writing into a deleted folder). Returns the bytes freed.
*/
export default function pruneProfileCache({ profile_dir }: { profile_dir: string }) {
let freed = 0;
for (const name of RegenerableProfileDirs) {
freed += freeDir({ target: path.join(profile_dir, name) });
}
for (const profile of safeReadDir({ target: profile_dir })) {
/**
* A profile's own folder: `Default` or `Profile <n>`, and
* `System Profile` for Chrome's own pages.
*/
if (!/^(Default|Profile \d+|System Profile)$/.test(profile)) continue;
for (const name of RegenerableBrowserDirs) {
freed += freeDir({ target: path.join(profile_dir, profile, name) });
}
}
if (freed > 0) log({ name: "browser", message: `cleared ${(freed / (1024 * 1024)).toFixed(1)} MB of regenerable profile cache` });
return freed;
}
/**
* Removes one folder with what is under it, returning the bytes.
*/
function freeDir({ target }: { target: string }) {
const size = dirSize({ target });
if (!size) return 0;
try {
rmSync(target, { recursive: true, force: true });
return size;
} catch {
/**
* Something that can't be removed is left for the next start; the
* browser comes up either way.
*/
return 0;
}
}
/**
* Bytes under one folder. Links are counted, never followed: a profile
* has none of its own, but a retired one might.
*/
function dirSize({ target }: { target: string }): number {
let stat;
try {
stat = statSync(target);
} catch {
return 0;
}
if (stat.isFile()) return stat.size;
if (!stat.isDirectory()) return 0;
return safeReadDir({ target }).reduce((total, entry) => total + dirSize({ target: path.join(target, entry) }), 0);
}
function safeReadDir({ target }: { target: string }) {
try {
return readdirSync(target);
} catch {
return [];
}
}
+13
View File
@@ -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);
}
+14
View File
@@ -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 };
}
+23
View File
@@ -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;
}
}
+73
View File
@@ -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 });
}
};
}
+45
View File
@@ -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;
}
+69
View File
@@ -0,0 +1,69 @@
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("runs to the end with no time limit", async () => {
const result = await runCommand({ ...base, timeout_seconds: null, command: "sleep 1; echo done" });
expect(result.output).toBe("done\n");
expect(result.exit_code).toBe(0);
expect(result.timed_out).toBe(false);
});
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);
});
});
+148
View File
@@ -0,0 +1,148 @@
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 };
/**
* Stop it after this many seconds, `null` for no time limit at all.
*/
timeout_seconds: number | null;
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 (when it has one), 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 = timeout_seconds == null
? undefined
: setTimeout(() => {
timed_out = true;
stop();
}, timeout_seconds * 1000);
const onAbort = () => stop();
signal?.addEventListener("abort", onAbort, { once: true });
// A signal that aborted before the command started never fires its
// event again, so the command would run on despite the caller having
// gone away (R2): stop it at once when it's already aborted.
if (signal?.aborted) stop();
const finish = (exit_code: number | null) => {
if (settled) return;
settled = true;
if (timer) 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;
}
+38
View File
@@ -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();
});
});
+73
View File
@@ -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;
}
+29
View File
@@ -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([]);
});
});
+33
View File
@@ -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;
}
+9
View File
@@ -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 };
}
+12
View File
@@ -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);
}
+62
View File
@@ -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);
}
+35
View File
@@ -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;
}
+236
View File
@@ -0,0 +1,236 @@
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 pruneProfileCache from "./prune-profile-cache";
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 });
/**
* No browser runs now (this is its start): the caches it built
* last time are free to go, so the profile stops growing.
*/
pruneProfileCache({ 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 },
);
}
+130
View File
@@ -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 {}
}
}
+14
View File
@@ -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(() => {});
}
}
+24
View File
@@ -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,
};
}
+13
View File
@@ -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));
}
}
+6
View File
@@ -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=");
});
+13
View File
@@ -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");
}
+65
View File
@@ -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");
});
});
+19
View File
@@ -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",
};
}
+137
View File
@@ -0,0 +1,137 @@
import { execFile } from "node:child_process";
import { AgentConfig } from "./config";
/**
* One folder inside the workspace, with what it holds: `bots/9` is a bot's
* folder, `workspaces/3` a workspace's shared one.
*/
export type WorkspaceFolderUsage = {
/**
* Relative to the workspace root, e.g. `bots/9`.
*/
path: string;
bytes: number;
};
/**
* What the workspace holds, and the biggest folders in it. The whole
* folder, every bot's and user's included, is what grows on the data
* volume; the folders are what says whose it is.
*/
export type WorkspaceUsage = {
bytes: number;
folders: WorkspaceFolderUsage[];
};
/**
* When the workspace was last measured, and what it held. A measurement
* that fails keeps the last one: reporting 0 would let writes through a
* quota the app can't see (and `du` on a workspace full of small files can
* outlast its timeout).
*/
let measured: { usage: WorkspaceUsage; at: number } | null = null;
/**
* Measuring walks the whole workspace, so a run writing several files in a
* row asks once. The app's quota is its own decision; this is only how
* much is there.
*/
const CacheMs = 10_000;
/**
* How many of the biggest folders are named: enough that the one filling
* the volume is there, few enough to say in a sentence.
*/
const FoldersShown = 5;
/**
* The workspace's folders whose size is reported: a bot's, a workspace's,
* and anything else sitting at the top.
*/
const GroupedFolders = ["bots", "workspaces"];
/**
* What the workspace holds, measured with `du` (which reads the folders in
* C) and reused for `CacheMs`.
*/
export async function workspaceUsage(): Promise<WorkspaceUsage> {
if (measured && Date.now() - measured.at < CacheMs) return measured.usage;
const usage = await measureWorkspace();
if (!usage) return measured?.usage || { bytes: 0, folders: [] };
measured = { usage, at: Date.now() };
return usage;
}
/**
* The workspace's size and its biggest folders through `du`, or null when
* it can't be read.
*/
function measureWorkspace() {
return new Promise<WorkspaceUsage | null>((resolve) => {
execFile(
"du",
["-B1", "--max-depth=2", "--", AgentConfig.WorkspaceDir],
{ timeout: 30_000, maxBuffer: 16 * 1024 * 1024 },
(error, stdout) => {
if (error) return resolve(null);
resolve(parseDu(String(stdout)));
},
);
});
}
/**
* `du`'s lines (`<bytes>\t<path>`) as the whole workspace and the folders
* that make it up: each bot's and each workspace's own, and whatever else
* sits at the top. A passthrough folder (`bots`, `workspaces`) is only
* counted through its children.
*/
function parseDu(stdout: string): WorkspaceUsage {
const root = AgentConfig.WorkspaceDir.replace(/\/+$/, "");
const deep: WorkspaceFolderUsage[] = [];
const shallow = new Map<string, number>();
let bytes = 0;
for (const line of stdout.split("\n")) {
const [size, path] = line.split("\t");
const value = Number(size);
if (!path || !Number.isFinite(value) || value <= 0) continue;
if (path == root) {
bytes = value;
continue;
}
const relative = path.startsWith(`${root}/`) ? path.slice(root.length + 1) : "";
const [top, second] = relative.split("/");
if (!top || !GroupedFolders.includes(top)) {
shallow.set(relative, value);
continue;
}
if (second) deep.push({ path: relative, bytes: value });
else shallow.set(relative, value);
}
const folders = [...deep, ...[...shallow].map(([path, value]) => ({ path, bytes: value }))];
/**
* A passthrough folder with children is only counted through them: its
* own total would show every bot's folder twice.
*/
const grouped = new Set(deep.map((folder) => folder.path.split("/")[0]));
return {
bytes: bytes || folders.reduce((total, folder) => total + folder.bytes, 0),
folders: folders
.filter((folder) => !(shallow.has(folder.path) && grouped.has(folder.path)))
.sort((left, right) => right.bytes - left.bytes)
.slice(0, FoldersShown),
};
}
+60
View File
@@ -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);
});
}
+16
View File
@@ -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);
}
+25
View File
@@ -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();
});
});
+37
View File
@@ -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]);
}
+81
View File
@@ -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;
});
+1998 -97
View File
File diff suppressed because it is too large Load Diff
+1263 -62
View File
File diff suppressed because it is too large Load Diff
+349
View File
@@ -0,0 +1,349 @@
# Plan: replace chatrooms with a reviewed `ask_bot`
Status: proposed (not started)
Owner: maintainer
Scope: remove the chatroom feature; replace `ask_crew` with a gated `ask_bot`
## Goal
A worker that needs something from another bot calls `ask_bot` with a target and a brief.
The coordinator reviews the request in **one turn, no tools**, and answers with a bounded
JSON decision: approve, redirect to another bot, or refuse with reasons. Approved requests
go to the target as a normal reply job; the target's answer comes back to the asking bot's
session as a fenced crew message that wakes it. Refusals and redirects bounce back the same
way. All multi-turn orchestration, the room entity, the room pages and the three coordinator
tools go away.
What does not change: `delegate_task` (coordinator and workspace admins, downward),
`hand_over_task` (worker, its own task only), and the rule that a worker directs no peer.
## Decisions
Recorded here so they are not relitigated mid-implementation.
1. **The gate has three outcomes, not two.** `approve | redirect | refuse`. `redirect` names
a reachable bot and a reason. Without it, a wrong `target_bot_id` is a wasted round trip and
the asker's routing guess becomes the system's failure mode. The redirect costs nothing
extra in the same turn.
2. **A target's non-answer is not a new state.** When the target replies "I do not have that",
that text is the answer. Status `answered`. No `declined` state: the asker reads the text
and decides. This keeps the machine at six states.
3. **Informational asks are gated too.** Gate everything, keep the gate cheap (one small turn,
no tools), instrument it. If the gate turns are mostly approving trivial reads, split by class
later with data. Do not pre-emptively trust the asker's own classification.
4. **Hidden sessions stay.** The room is currently the owner of the target's hidden session.
That machinery survives as `bot_sessions.ask_id`. "Delete chatrooms" means delete the room as
an entity, not delete the isolation mechanism.
5. **No `/admin/asks` page.** Requests and outcomes appear in the asking bot's session as messages,
as they do today. The ask row exists for caps, depth, dedupe, usage attribution and pruning,
not for a UI. A chip can be added later without a schema change.
6. **The gate fails closed.** If the coordinator's decision cannot be parsed after one retry, the
ask fails with "couldn't review". A gate that approves on a garbled answer is not a gate.
7. **Rules of engagement split.** Judgement ("is this within what the user asked for", "is this the
right bot") goes in the coordinator's instructions, global and per workspace. Hard rules stay in
code: reach, workspace membership, depth, open caps, no asks from hook calls or routines,
read-only and revoked users.
## The model
New table `bot_asks`:
| column | type | notes |
| --- | --- | --- |
| `id` | integer pk | |
| `user_id` | integer fk users | the user the run works for |
| `requester_bot_id` | integer fk bots | the worker asking |
| `target_bot_id` | integer fk bots | set by the tool, rewritable by a redirect |
| `workspace_id` | integer fk workspaces | null outside a workspace |
| `origin_session_id` | integer fk bot_sessions | where the outcome goes back |
| `parent_ask_id` | integer | the ask this one was asked from, if any (depth) |
| `title` | text | short label |
| `request` | text | the brief, markdown |
| `status` | text | see lifecycle |
| `gate_note` | text | the coordinator's reason, on approve, redirect and refuse |
| `outcome` | text | the target's answer, or why there is none |
| `session_id` | integer fk bot_sessions | the hidden session the target works in |
| `job_id` | integer | the target's job, so Stop can cancel it |
| `created_at` / `updated_at` | integer | |
Indexes: `(user_id, status)`, `(requester_bot_id, status)`, `(target_bot_id)`.
Schema changes beside it:
- `bot_sessions.ask_id` becomes the hidden-session marker, replacing `chatroom_id`.
- `bot_sessions.status` gains `ask`, replacing the `chatroom` value (`src/dict/bot-dict.ts:243`).
- `bot_messages.from_ask_id` replaces `from_chatroom_id` (`db/schema.ts:602-603`).
## Lifecycle
```
pending --refuse--> refused
| (outcome = reasons, wake asker)
|--approve/redirect--> working --answer--> answered (outcome = the answer, wake asker)
\--fail----> failed (outcome = why, wake asker)
pending|working --stop--> stopped (only tells the asker)
```
Six states, one wake per terminal state. Compare with `ChatroomStatuses` plus
`coordinator_turns`: the turn counter goes away entirely.
## Flow
1. A calls `ask_bot({ target_bot_id, title, request, separate? })` during a reply or a task run.
2. `askBotTool` (`src/harness/tools/bot/ask-bot-tool.ts`) checks, in this order:
- the run is not a hook call and not a routine,
- the target is in `chatroomAskableBots` (`grabCrewAsks` after rename) for this user and place,
- depth: `parent_ask_id` chain below `AppData.AskMaxDepth`,
- caps: fewer than `AppData.AskMaxOpenPerBot` open asks for this asker,
- dedupe: no other open ask to the same target unless `separate`.
3. It inserts `bot_asks` with status `pending`, then `enqueueAskReview` queues one
`kind: "reply"` job for the coordinator in a hidden ask session, with `params: { ask_id, stage: "review" }`.
4. The coordinator's job runs `reviewAsk` instead of the text loop. One model call, no tools,
`BotAskDecisionSchema`, system prompt from `composeBotPrompt` for the coordinator in that
workspace (so per-workspace rules apply) plus `AskRulesNote`.
5. `applyAskDecision`:
- `refuse`: status `refused`, `gate_note = reason`, outcome message to the origin session, wake A.
- `redirect`: validate the new target against the askable list, set `target_bot_id`,
`gate_note = reason`, then continue as approve.
- `approve`: status `working`, `ensureAskSession` for the target, the request inserted there as a
crew message fenced by `AskRequestNote`, queue the target's reply job with
`params: { ask_id, stage: "answer" }`.
6. The target's job is a normal reply run in its hidden session, with the normal tools. Its last
message is the answer (`answerNotSentNote` already guarantees only the last message is sent).
7. `onAskJobEnded`, called from `complete-bot-job.ts` and `fail-bot-job.ts`:
- reads the job's final message, runs `shareAskFiles` over it (copies `[file:ID]` and folder refs
the asker cannot reach into A's folder, repointing the refs),
- status `answered` or `failed`,
- `askOutcomeMessage` posts it into `origin_session_id` as a user-side crew message with
`from_ask_id`, fenced for the model, shown as coming from the coordinator,
- wakes A.
8. `stopAsk` / `stop-bot-jobs` cancels the target's job and marks `stopped`.
Depth: when the target itself calls `ask_bot`, `parent_ask_id` is its session's `ask_id`, so
A -> B -> C is capped by `AskMaxDepth` exactly as `ChatroomMaxDepth` did.
## The gate contract
```ts
// src/bots-queue/bot-ask-decision-schema.ts
export const BotAskDecisionSchema = z.object({
decision: z.enum(["approve", "redirect", "refuse"]),
target_bot_id: z.number().int().optional(), // required with redirect, must be askable
reason: z.string().trim().min(1).max(600),
});
```
`reviewAsk` mirrors `planBotTask` (`src/bots-queue/plan-bot-task.ts`): one turn, no tools, a
JSON-only instruction in `AskRulesNote`, `parseAskDecision` with one retry, then a failed ask.
The system prompt is the coordinator's own, so the provider cache serves it and the call is cheap.
Gate input, in the user turn: asker name, id and role; target name, id, role and description;
the workspace; the user and their role there; the askable bots; the open asks for that asker;
the title and the brief. Do not send the asker's transcript.
## Files
### Add
- `db/schema.ts` changes (see model) plus `db/types/db.ts` regenerated.
- `src/dict/ask-dict.ts`: `AskStatuses`, `AskOutcomeStatuses`, `AskReviewJobTitle`, setting keys.
- `src/data/app-data.ts`: `AskMaxOpenPerBot`, `AskMaxDepth`, `AskKeepDays`, `AskKeepDaysMax`,
`AskMaxPerPlace`, `AskMaxPerPlaceMax`, `AskSharedFilesMax`, `AskReasonMaxChars`, replacing the
`Chatroom*` block at lines 354-384.
- `src/functions/backend/db/asks/`:
`create-ask.ts`, `grab-ask.ts`, `grab-user-asks.ts`, `grab-crew-asks.ts`, `ensure-ask-session.ts`,
`enqueue-ask-review.ts`, `enqueue-ask-answer.ts`, `apply-ask-decision.ts`, `close-ask.ts`,
`on-ask-job-ended.ts`, `cancel-ask-jobs.ts`, `share-ask-files.ts`, `ask-outcome-message.ts`,
`ask-ancestry.ts`, `prune-asks.ts`, `prune-asks-sql.ts`, `stop-ask.ts`, `grab-ask-depth.ts`.
- `src/functions/backend/db/asks/migrate-chatrooms-to-asks.ts` (see Migration).
- `src/bots-queue/review-ask.ts`, `src/bots-queue/bot-ask-decision-schema.ts`,
`src/bots-queue/parse-ask-decision.ts`, each with a colocated test.
- `src/harness/tools/bot/ask-bot-tool.ts` and `ask-bot-tool.test.ts`.
- `src/utils/ask-status-line.ts` (the thinking row while an ask is pending), `src/utils/merge-ask.ts`
(push merge, replacing `merge-chatroom.ts`), `src/utils/can-retry-ask.ts`, `src/utils/ask-retry-note.ts`.
- `src/functions/backend/db/usage/grab-ask-usage.ts` (replaces `grab-chatroom-usage.ts`).
### Change
Session visibility, the single most important group. `chatroom_id IS NULL` is hand-written in
11 files. Replace all of them with one shared fragment (`visibleSessionSql` in
`src/functions/backend/db/bot-sessions/`) to stop the next marker from drifting the same way:
- `src/bots-queue/run-bot-reply.ts:204,252,423`
- `src/functions/backend/db/bot-sessions/grab-bot-sessions.ts`
- `src/functions/backend/db/bot-sessions/grab-past-session-messages.ts`
- `src/functions/backend/db/bot-sessions/past-session-messages-sql.ts`
- `src/functions/backend/db/bot-sessions/is-hidden-session.ts` (add the `ask` status)
- `src/functions/backend/db/bots/grab-bots.ts`
- `src/functions/backend/db/bots-queue/count-open-bot-jobs.ts`
- `src/functions/backend/db/bots-queue/grab-running-bot-job-face.ts`
- `src/functions/backend/db/workspaces/grab-user-workspaces.ts`
- `src/functions/backend/db/workspaces/grab-workspace-activity.ts`
- `src/live-relay/relay-changed-sessions.ts:26`
Queue dispatch and lifecycle:
- `src/bots-queue/run-bot-job.ts:55` - branch on `params.ask_id` and `stage` instead of
`bot.kind == "coordinator" && params.chatroom_id`.
- `src/bots-queue/index.ts` - no new job kind; `stage` in `params`.
- `src/functions/backend/db/bots-queue/complete-bot-job.ts`, `fail-bot-job.ts` - call
`onAskJobEnded`.
- `src/functions/backend/db/bots-queue/stop-bot-jobs.ts` - call `stopAsk`.
- `src/functions/backend/db/bots/insert-bot-message.ts` - `from_ask_id`, `is_crew_message`.
- `src/utils/is-crew-message.ts`, `src/utils/conversation-markdown.ts`.
Tools and prompts:
- `src/harness/tools/bot/grab-bot-tools.ts` - `ask_bot` instead of `ask_crew`.
- `src/harness/tools/bot/grab-bot-chat-tools.ts` - `onChatroom` becomes `onAsk` (or is dropped).
- `src/harness/tools/bot/grab-bot-chat-tools.test.ts` - expectations.
- `src/data/harness-prompts.ts` - delete `chatroomCoordinatorNote` (line 669); add `AskRulesNote`
(the gate's decision rules), `AskRequestNote` (fenced brief for the target) and
`AskOutcomeNote` (what A reads).
- `src/data/coordinator-system-prompt.ts` - describe the gate and the rules of engagement.
- `src/dict/bot-types-dict.ts:86-89` - comment only; the matrix does not change.
Live relay and UI:
- `src/live-relay/index.ts`, `src/live-relay/relay-new-bot-messages.ts`
- `server:chatroom-message` becomes `server:ask-message`.
- `src/pages/admin/bots/[bot_id]/(sections)/conversation.tsx` - drop `useConversationChatrooms`,
`chatroomHoldsReply`, the context provider (or keep the context, emptied).
- `src/pages/admin/bots/[bot_id]/(partials)/message-thread.tsx` - drop
`ConversationChatroomStatus` in the thread.
- `src/pages/admin/bots/[bot_id]/(partials)/crew-message-line.tsx` - drop the chatroom context.
- `src/pages/admin/bots/[bot_id]/(utils)/ref-chip-for-href.tsx` - drop `ChatroomRefChip`.
- `src/utils/link-refs-in-text.ts`, `src/utils/link-computer-refs.ts`,
`src/utils/link-computer-refs.test.ts` - drop the `[room:ID]` parser and test.
- `src/layouts/bots/(partials)/rail-crew-list.tsx:58`, `rail-workspace-list.tsx:89` - drop the
chatrooms section.
- `src/utils/is-pages-rail-path.ts` and its test.
- `src/dict/admin-sections-dict.ts:8` - drop `/admin/chatrooms`.
- `src/dict/general-settings-dict.ts:194-202` - the chatrooms group becomes asks retention
(`asks_keep_days`, `asks_max_per_place`).
- `src/dict/bot-dict.ts:243` - `chatroom` becomes `ask`.
- `src/pages/api/admin/bots/message-trace.ts`, `src/pages/api/admin/bots/files.ts` - the chatroom
room check becomes the ask check.
- `src/server.ts` - register `migrateChatroomsToAsks` beside `migrateBotTypes` (line 42).
- `AGENTS.md` - the chatroom section, the `ask_crew` references, the rail and settings lists.
### Delete
Pages and API:
- `src/pages/admin/chatrooms/` (all: `index.tsx`, `index.server.ts`, `(hooks)/use-live-chatrooms.ts`,
`(partials)/chatroom-list-row.tsx`, `(sections)/chatrooms-list.tsx`)
- `src/pages/admin/chatrooms/[chatroom_id]/` (all 16 files: `index.tsx`, `index.server.ts`, and
everything under `(functions)`, `(hooks)`, `(partials)`, `(sections)`)
- `src/pages/admin/workspaces/[workspace_id]/chatrooms/` (4 files)
- `src/pages/api/admin/chatrooms/` (4 routes) and `src/pages/api/admin/settings/chatroom-retention.ts`
- `src/pages/admin/settings/general/(partials)/chatroom-retention-form.tsx`,
`(sections)/chatroom-retention-section.tsx`
- `src/pages/admin/bots/[bot_id]/(hooks)/use-conversation-chatrooms.ts`,
`(data)/conversation-chatrooms-context.ts`,
`(partials)/conversation-chatroom-row.tsx`,
`(partials)/conversation-chatroom-status.tsx`,
`(partials)/chatroom-ref-chip.tsx`,
`(utils)/chatroom-holds-reply.ts`
- `src/layouts/bots/(hooks)/use-rail-chatrooms.ts`,
`(partials)/rail-chatroom-row.tsx`, `(partials)/rail-chatrooms-section.tsx`
- `src/components/general/chatroom-retry-button.tsx`, `chatroom-stone.tsx`,
`chatroom-stones.tsx`, `chatroom-stone-cluster.tsx`
Server and queue:
- `src/functions/backend/db/chatrooms/` (all 31 files)
- `src/bots-queue/run-chatroom-turn.ts`, `src/bots-queue/chatroom-turns.ts` and its test
- `src/harness/tools/chatroom/` (4 files)
Usage, pruning, relay, dict, utils:
- `src/functions/backend/db/usage/grab-chatroom-usage.ts`, `chatroom-usage-sql.ts`, its test
- `src/functions/backend/db/app-settings/grab-chatroom-retention.ts`
- `src/cron/prune-chatrooms/index.ts` (and its registration in `src/cron/index.ts`)
- `src/live-relay/relay-changed-chatrooms.ts`
- `src/functions/frontend/retry-chatroom-request.ts`
- `src/dict/chatroom-dict.ts`
- `src/utils/`: `chatroom-ref.ts`, `chatroom-href.ts`, `chatroom-status-line.ts`,
`chatroom-bot-statuses.ts`, `chatroom-open-jobs-warning.ts`, `chatroom-retry-note.ts`,
`chatroom-in-place.ts`, `chatroom-in-conversation.ts`, `can-retry-chatroom.ts`,
`merge-chatroom.ts`, and every matching `*.test.ts`
## Migration
`migrateChatroomsToAsks`, run at boot from `src/server.ts`:
1. If `bot_asks` is missing, return (a fresh install has nothing to move).
2. Delete the room side: `bots_queue` rows whose session is a room's, `bot_job_traces` for those
jobs, `bot_messages` for those sessions, then `bot_sessions` where `chatroom_id IS NOT NULL`.
Room history has no owner once the entity is gone.
3. Delete the outcome notices in normal sessions: `bot_messages.from_chatroom_id IS NOT NULL`.
They are transient notices that quote a room link which would render dead. Their text is
already in the asking bot's history as the crew message it answered, so nothing of substance is
lost. Do this before step 4.
4. `DROP INDEX IF EXISTS idx_bot_sessions_chatroom_id`, then `ALTER TABLE bot_sessions DROP COLUMN chatroom_id`,
`DROP TABLE IF EXISTS chatrooms` (drop the child column first: SQLite cannot drop a parent table
while a foreign key points at it).
5. Wrap 2 to 4 in a transaction and tolerate a `DROP COLUMN` failure with a logged warning: if the
bundled SQLite refuses, the column stays, always NULL, and is harmless because no code reads it.
6. `bun run db:schema` regenerates `db/types/db.ts`. Do not pass `--vector` (it wipes embeddings).
Rollback: the schema is additive except for the three drops. Keep the migration idempotent and
guarded by a version row in `app_settings` (`asks_migrated`), so a second boot is a no-op.
## Verification
- `bun run typecheck`.
- `bun run test`, with new tests for: the decision parser (approve, redirect to a non-askable bot,
refuse, garbage, garbage twice), the depth chain, the open cap and the dedupe, `shareAskFiles`,
`pruneAsksSql`, `onAskJobEnded` for answered and failed, and `migrateChatroomsToAsks` on a
fixture with a room, its sessions, messages and jobs.
- Regression tests that the session lists never show an ask session: one per entry point that used
`chatroom_id IS NULL`, now reading `visibleSessionSql`.
- Production build, then `bun run check:bundle` (deleting pages must not raise the conversation
page's budget).
- Browser check through the Playwright MCP at `http://localhost:8931/mcp`: seed two bots and the
coordinator, have A ask B for a file, watch A get woken, and have the gate refuse a bad request
and redirect a mis-addressed one. Screenshots to `.tmp/`, deleted after.
- `read_settings`/usage: an ask's model calls must appear in `/admin/usage`, proving attribution
survived the `chatroom_id` -> `ask_id` swap.
## Phases
1. **Schema and asks module.** Table, dict, constants, `create-ask`, `ensure-ask-session`,
`close-ask`, `on-ask-job-ended`, the gate (`review-ask`, schema, parser), queue dispatch.
Nothing user-facing switches yet. Typecheck and unit tests green.
2. **Tool and rules.** `ask_bot`, `grabBotTools` wiring, the three prompt notes, coordinator
system prompt, caps and dedupe. `ask_crew` and `createChatroom` stay in place behind the old
tool until phase 3, so both paths can be compared on the seeded instance.
3. **Remove the old path.** Delete chatrooms (every list above), the `[room:]` ref, the rail
section, the pages, the settings, the cron, the relay, the usage helper. Rewrite the session
visibility filters onto `visibleSessionSql` in one commit so a missed filter is visible.
4. **Migration and cleanup.** Boot migration, `db:schema`, `AGENTS.md`, tests, bundle check,
browser pass.
Each phase ends with `bun run typecheck` and `bun run test`, and nothing is committed until asked.
## Risks
- **A missed hidden-session filter.** Eleven files hand-write `chatroom_id IS NULL`. One miss leaks
crew traffic into a user's rails. Mitigation: `visibleSessionSql` in phase 3, before deleting the
old column, plus one test per entry point.
- **The gate is a single point of failure.** Every ask now depends on the coordinator's model and
queue. An install with a resting coordinator model refuses every ask. Mitigation: the gate uses
the same candidate fallback as any call; `failed` says "couldn't review, try again"; the fallback
chain is visible on the ask's usage row.
- **Latency and cost.** One extra model call per ask, on a small prompt. Measure before phase 3
with usage rows; if it dominates, split informational asks.
- **Bots over-asking.** With no room to read, a bot may ask instead of reading its own files.
`AskRulesNote` must say the asker should have what it needs locally first, and the cap plus the
gate's refusal cover the rest.
- **Depth regressions.** Removing the coordinator's multi-turn routing means the depth chain now
goes through `parent_ask_id` only. Test the two-hop case explicitly.
## Deferred
- An "ask" row under the asking bot's message (a `MessageAskChips` beside `MessageTaskChips`).
- A read-only `/admin/asks` list, if the message view proves insufficient.
- Splitting informational asks out of the gate, once usage data exists.
- `ask_bot` with more than one target in one call (the gate would pick). Not worth it yet.
+121 -23
View File
@@ -31,31 +31,70 @@ if [ -t 1 ]; then
C_RESET=$'\033[0m'
C_BOLD=$'\033[1m'
C_DIM=$'\033[2m'
C_UNDERLINE=$'\033[4m'
C_RED=$'\033[31m'
C_GREEN=$'\033[32m'
C_YELLOW=$'\033[33m'
C_BLUE=$'\033[34m'
C_CYAN=$'\033[36m'
# The ember stone's hue (--color-hue-ember in src/styles/main.css), in
# true colour where the terminal says it has it, else the nearest of 256.
case "${COLORTERM:-}" in
truecolor | 24bit) C_EMBER=$'\033[38;2;228;87;46m' ;;
*) C_EMBER=$'\033[38;5;166m' ;;
esac
# Clickable links (OSC 8) everywhere but the bare Linux console.
case "${TERM:-}" in
linux | dumb | "") LINKS=0 ;;
*) LINKS=1 ;;
esac
else
C_RESET=""
C_BOLD=""
C_DIM=""
C_UNDERLINE=""
C_RED=""
C_GREEN=""
C_YELLOW=""
C_BLUE=""
C_CYAN=""
C_EMBER=""
LINKS=0
fi
say() { printf '%s==>%s %s\n' "$C_BLUE" "$C_RESET" "$*"; }
ok() { printf '%s ok%s %s\n' "$C_GREEN" "$C_RESET" "$*"; }
warn() { printf '%swarn%s %s\n' "$C_YELLOW" "$C_RESET" "$*" >&2; }
say() { printf ' %s›%s %s\n' "$C_EMBER" "$C_RESET" "$*"; }
ok() { printf ' %s✓%s %s\n' "$C_GREEN" "$C_RESET" "$*"; }
warn() { printf ' %s!%s %s%s%s\n' "$C_YELLOW" "$C_RESET" "$C_YELLOW" "$*" "$C_RESET" >&2; }
fail() {
printf '%sfail%s %s\n' "$C_RED" "$C_RESET" "$*" >&2
printf ' %s✗ %s%s\n' "$C_RED" "$*" "$C_RESET" >&2
exit 1
}
# A URL, underlined and clickable where the terminal can.
link() {
if [ "$LINKS" = 1 ]; then
printf '\033]8;;%s\033\\%s%s%s%s\033]8;;\033\\' "$1" "$C_CYAN" "$C_UNDERLINE" "$1" "$C_RESET"
else
printf '%s%s%s%s' "$C_CYAN" "$C_UNDERLINE" "$1" "$C_RESET"
fi
}
# One line of the closing summary: a dim label, then its value.
summary_row() { printf ' %s%-12s%s %s\n' "$C_DIM" "$1" "$C_RESET" "$2"; }
banner() {
local s="$C_EMBER" w="$C_BOLD" d="$C_DIM" r="$C_RESET"
printf '\n'
printf ' %s ▄▄██████▄▄ %s\n' "$s" "$r"
printf ' %s ▄████████████%s %s █ █ █ %s\n' "$s" "$r" "$w" "$r"
printf ' %s ███ ███ ███%s %s ▄▄▄ ▄▄▄ █▄▄▄ █▄▄▄ █ ▄▄▄ %s\n' "$s" "$r" "$w" "$r"
printf ' %s █████████████%s %s█ █ █ █ █ █ █ █ █▄▄▄█%s\n' "$s" "$r" "$w" "$r"
printf ' %s ▀████████████%s %s▀▄▄▄ ▀▄▄▄▀ █▄▄▄▀ █▄▄▄▀ █ ▀▄▄▄▄%s\n' "$s" "$r" "$w" "$r"
printf ' %s ▀▀██████▀▀ %s %sa crew of small AI worker bots%s\n' "$s" "$r" "$d" "$r"
printf '\n'
}
on_error() {
local code=$?
printf '%sfail%s line %s exited with status %s\n' "$C_RED" "$C_RESET" "${BASH_LINENO[0]:-?}" "$code" >&2
printf ' %s✗ line %s exited with status %s%s\n' "$C_RED" "${BASH_LINENO[0]:-?}" "$code" "$C_RESET" >&2
exit "$code"
}
trap on_error ERR
@@ -509,7 +548,7 @@ host_ips() {
wait_for_health() {
local url start=0
url="$(health_url)"
say "Waiting for Cobble to answer at $url"
say "Waiting for Cobble to answer at $(link "$url")"
while [ "$start" -lt "$HEALTH_TIMEOUT_SECONDS" ]; do
if curl -fsS --max-time 3 -o /dev/null "$url" 2>/dev/null; then
ok "Cobble is healthy"
@@ -526,6 +565,58 @@ wait_for_health() {
fail "Cobble did not become healthy within ${HEALTH_TIMEOUT_SECONDS}s"
}
# ---------------------------------------------------------------- images
# Every release is a new image tag, and a host keeps every one of them
# otherwise: over a gigabyte each, so a year of updates can hold tens of
# gigabytes that nothing runs. Once the new container is healthy, the image
# the previous one ran is removed (the registry still has it) along with the
# layers nobody uses any more, and so is every older tag of the app's image
# and of the computer's, which the app pulls again when it needs one.
# MARK:old-image-tags
# The tags of one image repository in a `docker image ls --format
# '{{.Repository}} {{.Tag}}'` listing, except the tag being installed (an
# empty `keep` keeps none) and anything docker couldn't name.
old_image_tags() {
local listing="$1"
local repo="$2"
local keep="$3"
printf '%s\n' "$listing" | awk -v repo="$repo" -v keep="$keep" '
$1 == repo && $2 != "" && $2 != "<none>" && $2 != keep { print $2 }
'
}
# END:old-image-tags
prune_old_images() {
local previous="$1"
if [ -n "$previous" ] && [ "$previous" != "$IMAGE:$VERSION" ]; then
say "Removing the previous image ${previous}"
docker rmi "$previous" >/dev/null 2>&1 || true
fi
# Releases keep stacking up: an install updated twice a month holds
# every tag it ever ran. Docker refuses any image a container still
# uses, stopped ones included, so only what nothing runs goes.
local listing repo tag
listing="$(docker image ls --format '{{.Repository}} {{.Tag}}' 2>/dev/null || true)"
repo="$(printf '%s' "$IMAGE" | sed -E 's|:[^/:]+$||')"
for name in "$repo" "$repo-computer"; do
local keep=""
[ "$name" = "$repo" ] && keep="$VERSION"
while IFS= read -r tag; do
[ -z "$tag" ] && continue
say "Removing the older image ${name}:${tag}"
docker rmi "${name}:${tag}" >/dev/null 2>&1 || true
done <<< "$(old_image_tags "$listing" "$name" "$keep")"
done
docker image prune -f >/dev/null 2>&1 || true
}
backup_database() {
local data_source="$DATA_DIR"
if container_exists; then
@@ -687,6 +778,7 @@ run_container() {
--restart unless-stopped \
--init \
--network "$NETWORK" \
--add-host host.docker.internal:host-gateway \
-p "$BIND:$PORT:$PORT" \
--cpus "$CPUS" \
--memory "${MEMORY_MB}m" \
@@ -774,6 +866,8 @@ uninstall() {
# ---------------------------------------------------------------- main
banner
command -v curl >/dev/null 2>&1 || fail "curl is required"
ensure_docker
@@ -856,7 +950,7 @@ if [ "$FORCE" = 0 ] && container_matches; then
connect_extra_network
if curl -fsS --max-time 3 -o /dev/null "$(health_url)" 2>/dev/null; then
ok "Cobble is already up to date"
say "Healthy at http://$(health_host):$PORT"
say "Healthy at $(link "http://$(health_host):$PORT")"
exit 0
fi
warn "The container is running but not answering; recreating it"
@@ -867,6 +961,7 @@ if container_exists; then
# own layer, so lift it out before anything replaces the container.
rescue_container_data
backup_database
PREVIOUS_IMAGE_TAG="$(docker inspect -f '{{.Config.Image}}' "$CONTAINER" 2>/dev/null || true)"
say "Replacing the Cobble container"
docker stop -t 30 "$CONTAINER" >/dev/null 2>&1 || true
docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
@@ -878,28 +973,31 @@ connect_extra_network
wait_for_health
prune_old_images "${PREVIOUS_IMAGE_TAG:-}"
ok "Cobble is running"
printf '\n'
printf ' %s%s%s\n' "$C_BOLD" "Open Cobble" "$C_RESET"
printf ' %sOpen Cobble%s\n' "$C_BOLD" "$C_RESET"
if [ "$BIND" = "0.0.0.0" ]; then
while IFS= read -r ip; do
[ -n "$ip" ] && printf ' http://%s:%s\n' "$ip" "$PORT"
[ -n "$ip" ] && printf ' %s\n' "$(link "http://$ip:$PORT")"
done < <(host_ips)
fi
printf ' http://127.0.0.1:%s\n' "$PORT"
printf ' %s\n' "$(link "http://127.0.0.1:$PORT")"
printf '\n'
printf ' Put a reverse proxy or tunnel in front for HTTPS, and open that\n'
printf ' address instead. The installed app and notifications need it.\n'
printf ' %sPut a reverse proxy or tunnel in front for HTTPS, and open that\n' "$C_DIM"
printf ' address instead. The installed app and notifications need it.%s\n' "$C_RESET"
printf '\n'
printf ' First visit: create the super admin account.\n'
printf ' Data: %s\n' "$DATA_DIR"
printf ' Settings: %s\n' "$ENV_FILE"
printf ' Backups: %s\n' "$BACKUP_DIR"
printf ' Archives: %s\n' "$BACKUP_ARCHIVE_DIR_HOST"
printf ' Logs: docker logs -f %s\n' "$CONTAINER"
printf ' Update: curl -fsSL %s | sudo bash\n' "$INSTALL_URL"
printf ' Uninstall: curl -fsSL %s | sudo bash -s -- --uninstall\n' "$INSTALL_URL"
summary_row "First visit" "create the super admin account."
summary_row "Data" "$DATA_DIR"
summary_row "Settings" "$ENV_FILE"
summary_row "Backups" "$BACKUP_DIR"
summary_row "Archives" "$BACKUP_ARCHIVE_DIR_HOST"
printf '\n'
summary_row "Logs" "${C_BOLD}docker logs -f $CONTAINER${C_RESET}"
summary_row "Update" "${C_BOLD}curl -fsSL${C_RESET} $(link "$INSTALL_URL") ${C_BOLD}| sudo bash${C_RESET}"
summary_row "Uninstall" "${C_BOLD}curl -fsSL${C_RESET} $(link "$INSTALL_URL") ${C_BOLD}| sudo bash -s -- --uninstall${C_RESET}"
printf '\n'
if [ "$BIND" = "0.0.0.0" ]; then
printf ' %sThis port is reachable on your network, without encryption. Put a proxy or tunnel in front of it for HTTPS.%s\n\n' "$C_DIM" "$C_RESET"
printf ' %s!%s %sThis port is reachable on your network, without encryption. Put a proxy or tunnel in front of it for HTTPS.%s\n\n' "$C_YELLOW" "$C_RESET" "$C_DIM" "$C_RESET"
fi
+58
View File
@@ -182,6 +182,64 @@ describe("install.sh mount specs", () => {
}
});
describe("install.sh image pruning", () => {
const LISTING = [
"ghcr.io/moduletrace/cobble 0.18.2",
"ghcr.io/moduletrace/cobble 0.18.3",
"ghcr.io/moduletrace/cobble 0.18.4",
"ghcr.io/moduletrace/cobble-computer 1.3.0",
"ghcr.io/moduletrace/cobble-computer 1.4.0",
"ghcr.io/moduletrace/cobble-tools 9.9.9",
"<none> <none>",
].join("\n");
async function oldImageTags({ repo, keep }: { repo: string; keep: string }) {
const block = await readMarkedBlock({ name: "old-image-tags" });
const script = [block, `old_image_tags "$LISTING" "$repo" "$keep"`].join("\n");
const proc = Bun.spawn({
cmd: ["bash", "-c", script],
env: { ...process.env, LISTING, repo, keep },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, , code] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);
expect(code).toBe(0);
return stdout.trim().split("\n").filter(Boolean);
}
test("removes every older version of the app, keeping the one installed", async () => {
expect(
await oldImageTags({ repo: "ghcr.io/moduletrace/cobble", keep: "0.18.4" }),
).toEqual(["0.18.2", "0.18.3"]);
});
test("removes every computer image tag, since the app pulls one again", async () => {
expect(
await oldImageTags({ repo: "ghcr.io/moduletrace/cobble-computer", keep: "" }),
).toEqual(["1.3.0", "1.4.0"]);
});
test("never touches another repository's images", async () => {
// `cobble-tools` shares the prefix: a prefix match would take a
// project the installer knows nothing about.
const tags = await oldImageTags({
repo: "ghcr.io/moduletrace/cobble-tools",
keep: "",
});
expect(tags).toEqual(["9.9.9"]);
expect(
await oldImageTags({ repo: "ghcr.io/moduletrace/cobble", keep: "" }),
).not.toContain("9.9.9");
});
});
describe("install.sh data rescue", () => {
test("rescues the container's data before replacing it", async () => {
const source = await Bun.file(INSTALL_SCRIPT).text();
+12 -5
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.1.2",
"version": "0.24.2",
"module": "index.ts",
"type": "module",
"private": true,
@@ -8,7 +8,7 @@
"dev": "bun src/server.ts",
"gen:favicon": "bun src/scripts/generate-brand-assets.ts",
"build": "bunx bunext build",
"db:schema": "bunx bun-sqlite schema -t",
"db:schema": "bunx bun-sqlite schema -t -y",
"db:admin": "bunx bun-sqlite admin",
"db:backup": "bunx bun-sqlite backup",
"seed": "bun src/scripts/seed-super-admin.tsx",
@@ -16,7 +16,11 @@
"start": "MAIN_SERVER=1 NODE_ENV=production bun src/server.ts",
"typecheck": "tsc --noEmit",
"test": "bun test",
"check:bundle": "bun src/scripts/check-bundle-size.ts"
"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"
},
"devDependencies": {
"@next/mdx": "^16.3.0",
@@ -31,6 +35,7 @@
"@types/sanitize-html": "^2.16.2",
"@types/turndown": "^5.0.6",
"@types/web-push": "^3.6.4",
"marked": "17.0.6",
"tailwindcss": "^4.3.3"
},
"peerDependencies": {
@@ -40,8 +45,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.6",
"@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",
@@ -50,6 +55,7 @@
"@tiptap/react": "3.32.0",
"@tiptap/starter-kit": "3.32.0",
"ace-builds": "^1.44.0",
"chart.js": "^4.6.1",
"dayjs": "^1.11.23",
"gray-matter": "^4.0.3",
"html-to-react": "^1.7.0",
@@ -57,6 +63,7 @@
"lucide-react": "^1.59.0",
"mammoth": "^1.12.1",
"mdx": "^0.3.1",
"mermaid": "^12.2.0",
"next-mdx-remote": "^6.0.0",
"nodemailer": "^9.0.5",
"openai": "^7.4.0",
Binary file not shown.

After

Width:  |  Height:  |  Size: 760 B

+5 -2
View File
@@ -5,8 +5,11 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#fbfaf7" />
<meta name="robots" content="noindex" />
<title>cobble</title>
<title>{{name}}</title>
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Archivo:[email protected]&display=swap" />
<style>
:root {
--paper: #fbfaf7;
@@ -33,7 +36,7 @@ body {
padding: calc(24px + env(safe-area-inset-top)) 24px calc(24px + env(safe-area-inset-bottom));
background: var(--paper);
color: var(--ink);
font-family: "Lato", system-ui, -apple-system, "Segoe UI", sans-serif;
font-family: "Archivo", "Liberation Sans", system-ui, -apple-system, sans-serif;
-webkit-font-smoothing: antialiased;
}
main {
+4 -1
View File
@@ -6,6 +6,9 @@
<meta name="theme-color" content="#fbfaf7" />
<title>Offline | cobble</title>
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Archivo:[email protected]&display=swap" />
<style>
:root {
--paper: #fbfaf7;
@@ -32,7 +35,7 @@ body {
padding: calc(24px + env(safe-area-inset-top)) 24px calc(24px + env(safe-area-inset-bottom));
background: var(--paper);
color: var(--ink);
font-family: "Lato", system-ui, -apple-system, "Segoe UI", sans-serif;
font-family: "Archivo", "Liberation Sans", system-ui, -apple-system, sans-serif;
-webkit-font-smoothing: antialiased;
}
main {
+23 -8
View File
@@ -54,13 +54,22 @@ const ASSET_PATHS = ["/favicon.ico", "/favicon.png", "/apple-touch-icon.png"];
/**
* Never intercepted: live data, sockets, media bytes, proxied computers,
* auth side effects, and the worker itself.
* bot graphics, auth side effects, and the worker itself.
*/
const BYPASS_PREFIXES = ["/api/", "/ws", "/media", "/computers/"];
const BYPASS_PREFIXES = ["/api/", "/ws", "/media", "/computers/", "/graphics/", "/graphics-lib/"];
const BYPASS_PATHS = ["/sw.js", "/manifest.webmanifest", "/auth/logout", BUILD_INFO_URL];
/**
* Android draws a badge from its alpha alone, so it's the white stone on
* transparent (`PwaBadgePath`); the app icon sits on opaque paper and
* would show as a square.
*/
const DEFAULT_ICON = "/icons/icon-192.png";
const DEFAULT_BADGE = "/icons/icon-192.png";
const DEFAULT_BADGE = "/icons/badge-96.png";
function absoluteUrl(path) {
return new URL(path, self.location.origin).href;
}
function isAssetRequest(url) {
return (
@@ -76,7 +85,14 @@ function isBypassRequest(url) {
);
}
/**
* Nothing the worker holds belongs to one version (navigations go to the
* network, the code cache belongs to the build), so a new worker takes
* over at once instead of waiting for every tab to close. It never
* reloads a page: the open one keeps running, now served by it.
*/
self.addEventListener("install", (event) => {
self.skipWaiting();
event.waitUntil(
caches.open(CACHE_NAME).then((cache) =>
Promise.allSettled(SHELL.map((url) => cache.add(url))),
@@ -181,9 +197,8 @@ async function cacheFirst(request) {
}
/**
* The page asks for a new version from its update notice: nothing skips
* the wait until the user says so. The loading page asks too, since it
* isn't the app and nothing of the app's is running.
* The loading page asks a waiting worker to take over. Workers from
* before `install` skipped the wait on their own only answer this.
*/
self.addEventListener("message", (event) => {
if (event.data?.type === "SKIP_WAITING") {
@@ -203,8 +218,8 @@ self.addEventListener("push", (event) => {
const title = payload.title || "Cobble";
const options = {
body: payload.body || "",
icon: payload.icon || DEFAULT_ICON,
badge: payload.badge || DEFAULT_BADGE,
icon: absoluteUrl(payload.icon || DEFAULT_ICON),
badge: absoluteUrl(payload.badge || DEFAULT_BADGE),
tag: payload.tag || undefined,
renotify: Boolean(payload.tag),
requireInteraction: Boolean(payload.requireInteraction),
+324
View File
@@ -0,0 +1,324 @@
#!/usr/bin/env bash
# Shared helpers for the publish scripts.
#
# . "$(dirname "$0")/lib/publish-common.sh"
#
# Never run this file: it only defines functions and constants, so the
# scripts own their own `set -Eeuo pipefail` and a test can source it
# without changing the caller's shell options.
# MARK:preamble
if [ -t 1 ]; then
C_RESET=$'\033[0m'
C_BOLD=$'\033[1m'
C_DIM=$'\033[2m'
C_RED=$'\033[31m'
C_GREEN=$'\033[32m'
C_YELLOW=$'\033[33m'
C_BLUE=$'\033[34m'
else
C_RESET=""
C_BOLD=""
C_DIM=""
C_RED=""
C_GREEN=""
C_YELLOW=""
C_BLUE=""
fi
DRY_RUN="${DRY_RUN:-0}"
ASSUME_YES="${ASSUME_YES:-0}"
RELEASE_NOTES_MAX_COMMITS="${RELEASE_NOTES_MAX_COMMITS:-100}"
step() { printf '\n%s==>%s %s\n' "$C_BLUE$C_BOLD" "$C_RESET" "$*"; }
ok() { printf '%s ok%s %s\n' "$C_GREEN" "$C_RESET" "$*"; }
warn() { printf '%swarn%s %s\n' "$C_YELLOW" "$C_RESET" "$*" >&2; }
detail() { printf ' %s%s%s\n' "$C_DIM" "$*" "$C_RESET"; }
fail() {
printf '%sfail%s %s\n' "$C_RED" "$C_RESET" "$*" >&2
exit 1
}
# Runs a command, or prints it when the script was asked for a dry run.
# Only use this for commands that can be spelled as a single command.
run() {
if [ "$DRY_RUN" = "1" ]; then
printf ' %s[dry run]%s %s\n' "$C_DIM" "$C_RESET" "$*"
return 0
fi
"$@"
}
is_dry_run() { [ "$DRY_RUN" = "1" ]; }
# END:preamble
# MARK:require-cmd
require_cmd() {
local name="$1"
local hint="${2:-}"
if ! command -v "$name" >/dev/null 2>&1; then
if [ -n "$hint" ]; then
fail "Missing '$name'. $hint"
fi
fail "Missing '$name'."
fi
}
# END:require-cmd
# Moves into the top of the checkout and remembers it as ROOT.
require_repo_root() {
ROOT="$(git rev-parse --show-toplevel 2>/dev/null)" || fail "Not inside a git checkout."
cd "$ROOT"
export ROOT
}
# MARK:git-state
require_clean_worktree() {
local dirty
dirty="$(git status --porcelain --untracked-files=no)"
if [ -n "$dirty" ]; then
printf '%s\n' "$dirty" >&2
fail "The working tree has uncommitted changes. Commit or stash them before publishing."
fi
}
require_on_branch() {
local branch="$1"
local current
current="$(git rev-parse --abbrev-ref HEAD)"
if [ "$current" != "$branch" ]; then
fail "On '$current', not '$branch'. Check out $branch before publishing (or pass --branch)."
fi
}
require_remote() {
local remote="$1"
if ! git remote get-url "$remote" >/dev/null 2>&1; then
fail "No '$remote' git remote. Add it with: git remote add $remote <url>"
fi
}
# Fails when the remote branch has commits HEAD does not have. HEAD being
# ahead is fine: the script pushes.
require_not_behind() {
local remote="$1"
local branch="$2"
local counts ahead behind
# A remote with no branch yet is not behind: the first push creates it.
if ! git ls-remote --exit-code --heads "$remote" "refs/heads/$branch" >/dev/null 2>&1; then
detail "$remote has no $branch yet; the first push creates it."
return 0
fi
git fetch --quiet "$remote" "$branch" || fail "Could not fetch $remote/$branch."
if ! git rev-parse -q --verify "refs/remotes/$remote/$branch" >/dev/null; then
return 0
fi
counts="$(git rev-list --left-right --count "HEAD...$remote/$branch")"
ahead="$(printf '%s' "$counts" | cut -f1)"
behind="$(printf '%s' "$counts" | cut -f2)"
if [ "$behind" != "0" ]; then
fail "$remote/$branch has $behind commit(s) HEAD does not have. Pull before publishing."
fi
if [ "$ahead" != "0" ]; then
detail "HEAD is $ahead commit(s) ahead of $remote/$branch; they are pushed with the release."
fi
}
# Prints the tag already on the remote for a version, or nothing.
remote_tag_exists() {
local remote="$1"
local tag="$2"
local found
found="$(git ls-remote --tags "$remote" "refs/tags/$tag" 2>/dev/null || true)"
[ -n "$found" ] && printf 'yes'
}
local_tag_exists() {
git rev-parse -q --verify "refs/tags/$1" >/dev/null
}
# Creates the annotated tag when it is missing, and reuses an existing one.
ensure_tag() {
local tag="$1"
local message="${2:-$1}"
if local_tag_exists "$tag"; then
ok "Tag $tag already exists locally; reusing it."
return 0
fi
run git tag -a "$tag" -m "$message"
}
# END:git-state
# MARK:remote-url
# Splits a git remote URL into REMOTE_HOST, REMOTE_OWNER and REMOTE_REPO.
# Understands git@host:owner/repo.git, ssh://git@host[:port]/owner/repo.git
# and https://host[:port]/owner/repo.git.
parse_remote_url() {
local url="$1"
local rest path
case "$url" in
*://*)
rest="${url#*://}"
rest="${rest#*@}"
REMOTE_HOST="${rest%%/*}"
path="${rest#*/}"
;;
*@*:*)
rest="${url#*@}"
REMOTE_HOST="${rest%%:*}"
path="${rest#*:}"
;;
*)
fail "Could not read a host out of the remote URL '$url'."
;;
esac
path="${path#/}"
path="${path%.git}"
REMOTE_OWNER="${path%%/*}"
REMOTE_REPO="${path##*/}"
if [ -z "$REMOTE_HOST" ] || [ -z "$REMOTE_OWNER" ] || [ -z "$REMOTE_REPO" ]; then
fail "Could not read owner and repository out of the remote URL '$url'."
fi
}
# END:remote-url
# MARK:version
VERSION_PATTERN='^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.+-]+)?$'
# Turns `0.1.2` or `v0.1.2` into `v0.1.2`.
normalize_version() {
local raw="$1"
printf 'v%s' "${raw#v}"
}
# Refuses anything that is not a release version, so a typo never becomes a
# tag that the release workflow cannot read a major.minor from.
validate_version() {
local raw="$1"
local bare="${raw#v}"
if ! printf '%s' "$bare" | grep -Eq "$VERSION_PATTERN"; then
fail "Version '$raw' is not a release version. Expected vMAJOR.MINOR.PATCH, e.g. v0.1.2."
fi
}
# The version in package.json, read the same way the release workflow reads it.
source_version() {
sed -n -E 's/^[[:space:]]*"version": "([^"]+)",?$/\1/p' "${ROOT:?}/package.json" | head -n1
}
# The newest release tag before `to`, or nothing when there is none.
previous_tag() {
local to="$1"
git -C "${ROOT:?}" describe --tags --abbrev=0 --match 'v[0-9]*' "${to}^" 2>/dev/null || true
}
# END:version
# MARK:notes
# Builds a release body from the commit log, so the Gitea mirror gets notes
# too (only GitHub can generate them itself).
release_notes() {
local from=""
local to=""
local compare_url=""
while [ $# -gt 0 ]; do
case "$1" in
--from) from="$2"; shift 2 ;;
--to) to="$2"; shift 2 ;;
--compare-url) compare_url="$2"; shift 2 ;;
*) fail "release_notes: unknown argument '$1'." ;;
esac
done
if [ -z "$to" ]; then
fail "release_notes: --to is required."
fi
local range="$to"
if [ -n "$from" ]; then
range="$from..$to"
fi
local commits total
commits="$(git -C "${ROOT:?}" log --no-merges --pretty=format:'- %s (%h)' --max-count="$RELEASE_NOTES_MAX_COMMITS" "$range")"
total="$(git -C "$ROOT" log --no-merges --oneline "$range" | wc -l | tr -d ' ')"
printf '## Changes\n\n'
if [ -z "$commits" ]; then
printf 'No commits listed.\n'
else
printf '%s\n' "$commits"
if [ "$total" -gt "$RELEASE_NOTES_MAX_COMMITS" ]; then
printf '\n_Showing the newest %s of %s commits._\n' "$RELEASE_NOTES_MAX_COMMITS" "$total"
fi
fi
if [ -n "$compare_url" ]; then
printf '\n**Full changelog**: %s\n' "$compare_url"
fi
}
# END:notes
# MARK:json-escape
# Escapes a string for a JSON body. jq is used when it is installed, since it
# handles every control character; the bash fallback covers the ones release
# notes actually contain.
json_escape() {
local text="$1"
if command -v jq >/dev/null 2>&1; then
# `-s` produces one JSON string; the quotes it wraps it in are the
# characters the caller's template adds, so they come back off.
local escaped
escaped="$(printf '%s' "$text" | jq -R -s '.')"
escaped="${escaped:1:${#escaped}-2}"
printf '%s' "$escaped"
return 0
fi
local out=""
local char
local i=0
local length=${#text}
while [ "$i" -lt "$length" ]; do
char="${text:$i:1}"
case "$char" in
'\') out+='\\' ;;
'"') out+='\"' ;;
$'\n') out+='\n' ;;
$'\r') out+='\r' ;;
$'\t') out+='\t' ;;
$'\b') out+='\b' ;;
$'\f') out+='\f' ;;
*) out+="$char" ;;
esac
i=$((i + 1))
done
printf '%s' "$out"
}
# END:json-escape
# MARK:confirm
confirm() {
local prompt="$1"
local answer=""
if [ "$ASSUME_YES" = "1" ]; then
return 0
fi
if [ ! -t 0 ]; then
fail "Not a terminal, so nothing was confirmed. Rerun with --yes to publish without a prompt."
fi
read -r -p "$prompt [y/N] " answer || true
case "$answer" in
y | Y | yes | YES) return 0 ;;
*) fail "Cancelled." ;;
esac
}
# END:confirm
+230
View File
@@ -0,0 +1,230 @@
#!/usr/bin/env bash
# The release flow both publish scripts share: argument parsing, preflight
# checks, tag preparation and the push.
#
# . "$(dirname "$0")/lib/publish-common.sh"
# . "$(dirname "$0")/lib/publish-release.sh"
#
# What differs between the two remotes is only the last step: the GitHub
# release object (which the release workflow builds the images from) and the
# Gitea one. Everything before that lives here, so the two scripts cannot
# drift apart.
# Defaults, overridden by the flags in parse_publish_args.
BRANCH="main"
VERSION_RAW=""
TAG=""
SKIP_CHECKS=0
HELP=0
REMAINING_ARGS=()
NOTES_FILE=""
TAG_CREATED=0
parse_publish_args() {
while [ $# -gt 0 ]; do
case "$1" in
-h | --help) HELP=1; shift ;;
--yes | -y) ASSUME_YES=1; shift ;;
--dry-run) DRY_RUN=1; shift ;;
--branch) BRANCH="${2:?--branch needs a value}"; shift 2 ;;
--version) VERSION_RAW="${2:?--version needs a value}"; shift 2 ;;
--skip-checks) SKIP_CHECKS=1; shift ;;
*)
REMAINING_ARGS+=("$1")
shift
;;
esac
done
DRY_RUN="${DRY_RUN:-0}"
ASSUME_YES="${ASSUME_YES:-0}"
}
# Fails when the platform script was handed a flag it does not know.
reject_unknown_args() {
local script="$1"
if [ "${#REMAINING_ARGS[@]}" -eq 0 ]; then
return 0
fi
printf 'Unknown argument: %s\n\n' "${REMAINING_ARGS[*]}" >&2
"$script" --help >&2
exit 2
}
# MARK:preflight
preflight() {
local remote="$1"
require_repo_root
require_cmd git
require_cmd "bun" "Install Bun: https://bun.sh"
step "Checking the checkout"
require_clean_worktree
ok "The working tree has nothing uncommitted."
require_on_branch "$BRANCH"
ok "On $BRANCH."
require_remote "$remote"
ok "Remote '$remote' is $(git remote get-url "$remote")."
require_not_behind "$remote" "$BRANCH"
ok "$remote/$BRANCH has nothing HEAD is missing."
}
# END:preflight
# MARK:resolve-version
# Sets TAG (vX.Y.Z) from --version, else from package.json.
resolve_version() {
step "Resolving the version"
if [ -z "$VERSION_RAW" ]; then
VERSION_RAW="$(source_version)"
if [ -z "$VERSION_RAW" ]; then
fail "No version in package.json and none passed with --version."
fi
detail "Read from package.json: $VERSION_RAW"
fi
validate_version "$VERSION_RAW"
TAG="$(normalize_version "$VERSION_RAW")"
ok "Releasing $TAG."
if [ "$TAG" != "v$(source_version)" ]; then
warn "package.json says $(source_version) but the release is $TAG. Bump package.json's version with the release so a dev build reports the same number (RELEASING.md, step 5)."
fi
}
# END:resolve-version
# MARK:checks
# The release gate from RELEASING.md that a machine can check.
run_release_checks() {
if [ "$SKIP_CHECKS" = "1" ]; then
warn "Skipping typecheck, tests and the installer syntax check (--skip-checks)."
return 0
fi
step "Running the release checks"
run bun run typecheck
ok "Type-check passed."
run bun run test
ok "Tests passed."
run bash -n install.sh
ok "install.sh parses."
}
# END:checks
# MARK:tag
# Creates the tag at HEAD, or verifies the existing one is at HEAD.
prepare_tag() {
step "Preparing the tag $TAG"
if local_tag_exists "$TAG"; then
local tagged
tagged="$(git rev-list -n1 "$TAG")"
if [ "$tagged" != "$(git rev-parse HEAD)" ]; then
fail "Tag $TAG already exists on ${tagged:0:12}, not on HEAD ($(git rev-parse --short HEAD)). Publishing would ship the code that tag was made from. Move it with: git tag -f -a $TAG -m '$TAG'"
fi
ok "Tag $TAG already points at HEAD; reusing it."
return 0
fi
run git tag -a "$TAG" -m "$TAG"
if [ "$DRY_RUN" != "1" ]; then
TAG_CREATED=1
fi
ok "Tagged HEAD as $TAG."
}
# END:tag
# MARK:notes-file
# Writes release_notes into NOTES_FILE, which the caller cleans up. The
# compare base is the host's /compare/ path; the tag range is added here,
# since only this side knows which tag came before (a bare /compare/ opens
# the host's default comparison rather than this release's).
build_compare_url() {
local compare_base="$1"
local from="$2"
if [ -z "$from" ]; then
printf '%s' "$compare_base"
return 0
fi
printf '%s%s...%s' "$compare_base" "$from" "$TAG"
}
write_notes_file() {
local compare_base="$1"
local compare_url=""
local from=""
# A dry run makes no tag, so the notes are read up to HEAD instead.
local to="$TAG"
if ! local_tag_exists "$to"; then
to="HEAD"
fi
from="$(previous_tag "$to")"
if [ -n "$from" ]; then
detail "Changes since $from."
else
detail "No earlier tag, so every commit is listed."
fi
compare_url="$(build_compare_url "$compare_base" "$from")"
NOTES_FILE="$(mktemp -t cobble-release-notes.XXXXXX)"
release_notes --from "$from" --to "$to" --compare-url "$compare_url" >"$NOTES_FILE"
ok "Wrote the release notes to $NOTES_FILE."
}
cleanup_notes() {
if [ -n "$NOTES_FILE" ] && [ -f "$NOTES_FILE" ]; then
rm -f "$NOTES_FILE"
fi
}
# END:notes-file
# MARK:push
# Pushes the branch, then the tag. A tag the remote already has is left alone,
# so a rerun after a failed release object finishes the job instead of
# failing on the push.
push_branch_and_tag() {
local remote="$1"
step "Pushing to $remote"
run git push "$remote" "$BRANCH"
ok "Pushed $BRANCH."
if [ -n "$(remote_tag_exists "$remote" "$TAG")" ]; then
ok "$remote already has $TAG; not pushing it again."
return 0
fi
run git push "$remote" "refs/tags/$TAG"
ok "Pushed $TAG."
}
# END:push
# MARK:reuse-release
# A release object that already exists is left as it is, so rerunning the
# script never fails on it and never overwrites a body someone edited.
release_already_exists() {
local description="$1"
warn "$description for $TAG already exists; leaving it untouched."
warn "Delete it first if it needs to be recreated."
}
# END:reuse-release
print_release_summary() {
local remote="$1"
local branch="$2"
local release_url="$3"
step "Published $TAG"
printf ' %sremote%s %s\n' "$C_DIM" "$C_RESET" "$remote ($(git remote get-url "$remote"))"
printf ' %sbranch%s %s\n' "$C_DIM" "$C_RESET" "$branch"
printf ' %stag%s %s\n' "$C_DIM" "$C_RESET" "$TAG"
if [ -n "$release_url" ]; then
printf ' %srelease%s %s\n' "$C_DIM" "$C_RESET" "$release_url"
fi
if [ "$DRY_RUN" = "1" ]; then
printf '\n%sDry run: nothing was tagged, pushed or published.%s\n' "$C_YELLOW" "$C_RESET"
fi
}
+318
View File
@@ -0,0 +1,318 @@
#!/usr/bin/env bash
# Copies a published Cobble image from GHCR into the Gitea registry.
#
# scripts/mirror-gitea.sh
#
# The Gitea registry is on the VPN and GitHub Actions runners are on the
# public internet, so CI can never reach it. The release workflow therefore
# builds and pushes to GHCR only, and this script mirrors the result
# separately: a registry that is unreachable, slow or full can never fail a
# release the installer depends on.
#
# It copies from the Gitea host itself, because that host reaches GHCR over
# the public internet and its own registry over the docker network it shares
# with it. Nothing has to be installed on that host: skopeo runs there in a
# container.
#
# `skopeo copy --all` keeps the manifest list and its signatures, so every
# architecture comes across and the digest is unchanged. Each destination tag
# is then read back and compared, so a partial copy is reported as a failure
# instead of being assumed to have worked.
#
# Run it after scripts/publish-github.sh: that release is what builds the
# image, so there is nothing to copy until it has finished.
set -Eeuo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/publish-common.sh
. "$SCRIPT_DIR/lib/publish-common.sh"
# shellcheck source=lib/publish-release.sh
. "$SCRIPT_DIR/lib/publish-release.sh"
SOURCE_REPO="${MIRROR_SOURCE_REPO:-moduletrace/cobble}"
SOURCE_REGISTRY_HOST="${MIRROR_SOURCE_REGISTRY_HOST:-ghcr.io}"
HOST="${MIRROR_HOST:-10.7.0.4}"
HOST_USER="${MIRROR_HOST_USER:-root}"
REGISTRY_HOST="${MIRROR_REGISTRY_HOST:-gitea:3000}"
REGISTRY_REPO="${MIRROR_REGISTRY_REPO:-moduletrace/cobble}"
# The name a person types, which is not the one the copy uses: the host
# reaches its registry by docker network name, while an install reaches it
# through the proxy in front of it.
REGISTRY_PUBLIC_HOST="${MIRROR_REGISTRY_PUBLIC_HOST:-git.tben.me}"
NETWORK="${MIRROR_NETWORK:-cloudflare}"
SKOPEO_IMAGE="${MIRROR_SKOPEO_IMAGE:-quay.io/skopeo/stable:latest}"
MIRROR_USER="${MIRROR_USER:-cobble}"
CONNECT_TIMEOUT="${MIRROR_CONNECT_TIMEOUT:-10}"
usage() {
cat <<EOF
Copies a published Cobble image from GHCR into the Gitea registry.
Usage: scripts/mirror-gitea.sh [options]
Options:
--version VERSION Version to mirror, with or without the leading v.
Defaults to package.json's version.
--yes, -y Do not prompt.
--dry-run Print what would run, copy nothing.
-h, --help Show this help.
The version is copied as vX.Y.Z and sha-<commit>. It is copied as latest and
major.minor too, but only while it is still the newest release in GHCR, so
mirroring an older release never rolls those two tags backwards. Every
destination is read back and its digest compared with GHCR's.
Run it after scripts/publish-github.sh, and after the image build for that
release has finished.
Environment:
GITEA_TOKEN Token for the registry (required).
MIRROR_HOST The Gitea host to copy from over the VPN.
Default: 10.7.0.4
MIRROR_HOST_USER Its ssh user. Default: root
MIRROR_REGISTRY_HOST The registry as that host sees it, by its docker
network name. Default: gitea:3000
MIRROR_REGISTRY_PUBLIC_HOST
The registry's public name, for the pull command
it prints. Default: git.tben.me
MIRROR_SOURCE_REGISTRY_HOST
Where the release workflow pushed.
Default: ghcr.io
MIRROR_NETWORK The docker network the registry is on, so the
copy container can resolve it.
Default: cloudflare
MIRROR_USER The registry user for basic auth. Default: cobble
MIRROR_SKOPEO_IMAGE The skopeo image the host runs.
Default: quay.io/skopeo/stable:latest
DRY_RUN=1, ASSUME_YES=1 Same as --dry-run and --yes.
EOF
}
parse_publish_args "$@"
if [ "$HELP" = "1" ]; then
usage
exit 0
fi
reject_unknown_args "$0"
# MARK:mirror-tags
# The moving tag a release owns: major.minor, read from the version the same
# way the release workflow reads it, so the two never disagree.
mirror_minor_tag() {
printf '%s' "${1#v}" | sed -E 's/^([0-9]+)\.([0-9]+).*/\1.\2/'
}
# The commit tag for a release: the first 12 characters of the commit the
# tag points at, which is `sha-${GITHUB_SHA::12}` in the workflow.
mirror_sha_tag() {
local sha
sha="$(git rev-parse -q --verify "refs/tags/$1^{commit}" 2>/dev/null || true)"
if [ -z "$sha" ]; then
return 1
fi
printf 'sha-%s' "${sha:0:12}"
}
# The tags this release owns outright, which no newer release claims.
mirror_fixed_tags() {
local sha_tag
printf '%s\n' "$1"
if sha_tag="$(mirror_sha_tag "$1")"; then
printf '%s\n' "$sha_tag"
fi
}
# The tags a newer release takes over.
mirror_moving_tags() {
printf 'latest\n%s\n' "$(mirror_minor_tag "$1")"
}
# END:mirror-tags
# MARK:mirror-guard
# Whether this release may still write the moving tags. It may while GHCR's
# `latest` is its own image: once a newer release has moved `latest`, copying
# an older version into the Gitea registry must not drag it back.
mirror_owns_moving_tags() {
if [ -z "$2" ]; then
# Nothing to compare against, so this release is taken as the newest.
return 0
fi
[ "$1" = "$2" ]
}
# END:mirror-guard
# MARK:mirror-digest
MANIFEST_ACCEPT="application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json"
# Reads a tag's digest from GHCR over the public internet. The token is
# anonymous: the image is public, and a registry answers a bare manifest
# request with 401 until it is given one.
github_registry_digest() {
local tag="$1"
local token
token="$(
curl -sSf "https://$SOURCE_REGISTRY_HOST/token?scope=repository:$SOURCE_REPO:pull" 2>/dev/null |
sed -n 's/.*"token":"\([^"]*\)".*/\1/p'
)" || return 1
if [ -z "$token" ]; then
return 1
fi
curl -sSf -o /dev/null -D- \
-H "Authorization: Bearer $token" \
-H "Accept: $MANIFEST_ACCEPT" \
"https://$SOURCE_REGISTRY_HOST/v2/$SOURCE_REPO/manifests/$tag" 2>/dev/null |
tr -d '\r' | sed -n 's/^docker-content-digest: //Ip' | head -n1
}
# END:mirror-digest
# MARK:mirror-remote
# Runs a bash script on the Gitea host, which is the one place that reaches
# both registries. The script arrives on stdin, so nothing is installed there
# and no quoting has to survive a round trip through ssh.
mirror_on_host() {
ssh -o BatchMode=yes -o ConnectTimeout="$CONNECT_TIMEOUT" "$HOST_USER@$HOST" \
"MIRROR_NETWORK='$NETWORK' MIRROR_SKOPEO_IMAGE='$SKOPEO_IMAGE' bash -s"
}
# Reads a destination tag's digest back from the registry. Empty means the
# tag is not there, which a caller reports differently from a mismatch.
mirror_digest_on_host() {
mirror_on_host <<REMOTE
set -uo pipefail
docker run --rm --network "\$MIRROR_NETWORK" "\$MIRROR_SKOPEO_IMAGE" \\
inspect --tls-verify=false --creds '$MIRROR_USER:$GITEA_TOKEN' \\
--format '{{.Digest}}' 'docker://$REGISTRY_HOST/$REGISTRY_REPO:$1' 2>/dev/null | tail -n1
REMOTE
}
# Copies one tag, leaving skopeo's output in MIRROR_COPY_LOG so a failure can
# be shown without streaming its progress into the report.
mirror_copy_on_host() {
MIRROR_COPY_LOG="$(mktemp -t cobble-mirror.XXXXXX)"
mirror_on_host <<REMOTE >"$MIRROR_COPY_LOG" 2>&1
set -uo pipefail
docker run --rm --network "\$MIRROR_NETWORK" "\$MIRROR_SKOPEO_IMAGE" \\
copy --all --retry-times 5 \\
--src-tls-verify=true --dest-tls-verify=false \\
--dest-creds '$MIRROR_USER:$GITEA_TOKEN' \\
'docker://$SOURCE_REGISTRY_HOST/$SOURCE_REPO:$1' \\
'docker://$REGISTRY_HOST/$REGISTRY_REPO:$2'
REMOTE
}
# END:mirror-remote
# MARK:mirror-main
require_repo_root
step "Resolving the version"
if [ -z "$VERSION_RAW" ]; then
VERSION_RAW="$(source_version)"
if [ -z "$VERSION_RAW" ]; then
fail "No version in package.json and none passed with --version."
fi
detail "Read from package.json: $VERSION_RAW"
fi
validate_version "$VERSION_RAW"
TAG="$(normalize_version "$VERSION_RAW")"
ok "Mirroring $TAG."
require_cmd git
require_cmd ssh "Install an ssh client."
require_cmd curl "Install curl."
if [ -z "${GITEA_TOKEN:-}" ]; then
fail "No Gitea token. Set GITEA_TOKEN to a token whose user can push packages to the $REGISTRY_REPO owner."
fi
step "Checking the released image in $SOURCE_REGISTRY_HOST"
SOURCE_DIGEST="$(github_registry_digest "$TAG")" ||
fail "No $TAG in $SOURCE_REGISTRY_HOST/$SOURCE_REPO. Publish the GitHub release first: scripts/publish-github.sh builds the image."
if [ -z "$SOURCE_DIGEST" ]; then
fail "No $TAG in $SOURCE_REGISTRY_HOST/$SOURCE_REPO. Publish the GitHub release first: scripts/publish-github.sh builds the image."
fi
ok "$TAG is $SOURCE_DIGEST."
LATEST_DIGEST="$(github_registry_digest latest || true)"
TAGS_TO_COPY="$(mirror_fixed_tags "$TAG")"
MOVING_SKIPPED=""
if mirror_owns_moving_tags "$SOURCE_DIGEST" "$LATEST_DIGEST"; then
TAGS_TO_COPY="$(
printf '%s\n%s\n' "$TAGS_TO_COPY" "$(mirror_moving_tags "$TAG")" |
awk 'NF && !seen[$0]++'
)"
else
MOVING_SKIPPED="$(mirror_moving_tags "$TAG" | tr '\n' ' ')"
fi
step "Mirroring $TAG into the Gitea registry"
printf ' %shost%s %s\n' "$C_DIM" "$C_RESET" "$HOST_USER@$HOST"
printf ' %sregistry%s %s/%s\n' "$C_DIM" "$C_RESET" "$REGISTRY_HOST" "$REGISTRY_REPO"
printf ' %ssource%s %s/%s\n' "$C_DIM" "$C_RESET" "$SOURCE_REGISTRY_HOST" "$SOURCE_REPO"
printf ' %stags%s %s\n' "$C_DIM" "$C_RESET" "$(printf '%s' "$TAGS_TO_COPY" | tr '\n' ' ')"
if [ -n "$MOVING_SKIPPED" ]; then
warn "$SOURCE_REGISTRY_HOST/$SOURCE_REPO:latest belongs to a newer release, so ${MOVING_SKIPPED% } is left where it is."
fi
step "Checking the Gitea host"
if is_dry_run; then
detail "[dry run] ssh -o BatchMode=yes $HOST_USER@$HOST 'bash -s'"
remote_hostname="$HOST"
else
remote_hostname="$(
mirror_on_host <<'REMOTE'
hostname
REMOTE
)" || fail "Could not reach $HOST_USER@$HOST over ssh. The Gitea host is on the VPN: connect to it first."
ok "Reached $remote_hostname."
fi
confirm "Mirror $TAG into $REGISTRY_HOST/$REGISTRY_REPO?"
failed=0
for dest_tag in $TAGS_TO_COPY; do
step "Copying $TAG to $dest_tag"
if is_dry_run; then
detail "[dry run] skopeo copy --all $SOURCE_REGISTRY_HOST/$SOURCE_REPO:$TAG -> $REGISTRY_HOST/$REGISTRY_REPO:$dest_tag"
continue
fi
if ! mirror_copy_on_host "$TAG" "$dest_tag"; then
sed -n '$!{/^$/d};p' "${MIRROR_COPY_LOG:-/dev/null}" 2>/dev/null | tail -n 8 >&2
warn "The copy to $dest_tag failed."
failed=1
continue
fi
# The digest is what makes the two registries the same image: a copy that
# stored a different manifest list would read back differently here.
copied_digest="$(mirror_digest_on_host "$dest_tag")"
if [ "$copied_digest" != "$SOURCE_DIGEST" ]; then
warn "$dest_tag reads back as ${copied_digest:-nothing}, not $SOURCE_DIGEST."
failed=1
continue
fi
ok "$dest_tag is $SOURCE_DIGEST."
done
if [ -n "${MIRROR_COPY_LOG:-}" ] && [ -f "$MIRROR_COPY_LOG" ]; then
rm -f "$MIRROR_COPY_LOG"
fi
step "Mirrored $TAG"
printf ' %sregistry%s %s/%s\n' "$C_DIM" "$C_RESET" "$REGISTRY_HOST" "$REGISTRY_REPO"
printf ' %stags%s %s\n' "$C_DIM" "$C_RESET" "$(printf '%s' "$TAGS_TO_COPY" | tr '\n' ' ')"
printf ' %sdigest%s %s\n' "$C_DIM" "$C_RESET" "$SOURCE_DIGEST"
if [ "$DRY_RUN" = "1" ]; then
printf '\n%sDry run: copied nothing.%s\n' "$C_YELLOW" "$C_RESET"
fi
if [ "$failed" = "1" ]; then
fail "The Gitea registry does not match $SOURCE_REGISTRY_HOST/$SOURCE_REPO. The release itself is unaffected: the installer defaults to GHCR."
fi
printf '\nAn install that can reach the Gitea registry can pull it with:\n'
printf ' curl -fsSL https://url.moduletrace.com/cobble | sudo bash -s -- --image %s/%s:%s\n' \
"$REGISTRY_PUBLIC_HOST" "$REGISTRY_REPO" "$TAG"
# END:mirror-main
+226
View File
@@ -0,0 +1,226 @@
#!/usr/bin/env bash
# Publishes a Cobble release to the Gitea mirror.
#
# scripts/publish-gitea.sh
#
# Runs the same release gate as the GitHub script, tags HEAD with the
# package.json version, pushes main and the tag to the `gitea` remote, then
# creates the Gitea release over the API.
#
# Gitea has no release workflow, so nothing is built here: the image is built
# once by .github/workflows/release.yml and copied into the Gitea registry by
# scripts/mirror-gitea.sh, run from the VPN side, since a GitHub runner can
# never reach it. This script only publishes the source and the release
# object.
#
# The token comes from GITEA_TOKEN, or from the Gitea section of ~/.config/tea
# if the tea CLI is installed. It needs the `write:repository` scope on the
# repository, which is what the repo scope gives.
set -Eeuo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/publish-common.sh
. "$SCRIPT_DIR/lib/publish-common.sh"
# shellcheck source=lib/publish-release.sh
. "$SCRIPT_DIR/lib/publish-release.sh"
REMOTE="gitea"
TEA_CONFIG="${TEA_CONFIG:-$HOME/.config/tea/config.yml}"
usage() {
cat <<EOF
Publishes a Cobble release to the Gitea mirror.
Usage: scripts/publish-gitea.sh [options]
Options:
--version VERSION Version to release, with or without the leading v.
Defaults to package.json's version.
--branch NAME Branch to publish from (default: main).
--yes, -y Do not prompt.
--dry-run Print what would run, change nothing locally or remotely.
--skip-checks Skip typecheck, tests and the install.sh syntax check.
-h, --help Show this help.
The release body is the commit log since the previous tag, the same text the
GitHub script publishes, since only GitHub can generate notes itself.
Environment:
GITEA_TOKEN Token with write:repository on the repository.
TEA_CONFIG The tea CLI config to read a token from.
Default: ~/.config/tea/config.yml
DRY_RUN=1, ASSUME_YES=1 Same as --dry-run and --yes.
EOF
}
parse_publish_args "$@"
if [ "$HELP" = "1" ]; then
usage
exit 0
fi
reject_unknown_args "$0"
trap cleanup_notes EXIT
# MARK:tea-token
# Reads the token tea stored for a host, so an existing `tea login` is enough.
tea_token_for_host() {
local host="$1"
local config="${2:-$TEA_CONFIG}"
if [ ! -f "$config" ]; then
return 0
fi
if command -v python3 >/dev/null 2>&1; then
python3 - "$config" "$host" <<'PY'
import re
import sys
path, host = sys.argv[1], sys.argv[2]
text = open(path, encoding="utf-8").read()
token = None
current = None
for line in text.splitlines():
line = line.rstrip()
if line.startswith("- name:"):
current = line.split(":", 1)[1].strip().strip('"').strip("'")
continue
match = re.match(r"\s+url:\s*(.+)$", line)
if match:
url = match.group(1).strip().strip('"').strip("'")
current = re.sub(r"^[a-z]+://", "", url)
current = current.split("/")[0].split("@")[-1]
continue
match = re.match(r"\s+token:\s*(.+)$", line)
if match and current == host:
token = match.group(1).strip().strip('"').strip("'")
if token:
print(token)
PY
return 0
fi
# No python: the token line of the first login block that names the host.
awk -v host="$host" '
/- name:/ { block = $0; next }
/url:/ { block = block " " $0 }
/token:/ {
if (index(block, host) > 0) {
sub(/^[^:]*:[[:space:]]*/, "", $0)
gsub(/["'"'"']/, "", $0)
print $0
exit
}
}
' "$config"
}
# END:tea-token
require_repo_root
preflight "$REMOTE"
resolve_version
remote_url="$(git remote get-url "$REMOTE")"
parse_remote_url "$remote_url"
API_URL="${GITEA_API_URL:-https://${REMOTE_HOST}/api/v1}"
REPO_SLUG="${REMOTE_OWNER}/${REMOTE_REPO}"
COMPARE_URL="https://${REMOTE_HOST}/${REPO_SLUG}/compare/"
step "Checking the Gitea token"
TOKEN="${GITEA_TOKEN:-}"
if [ -z "$TOKEN" ]; then
TOKEN="$(tea_token_for_host "$REMOTE_HOST" | head -n1)"
if [ -n "$TOKEN" ]; then
detail "Using the token from $TEA_CONFIG."
fi
fi
if [ -z "$TOKEN" ]; then
fail "No Gitea token. Set GITEA_TOKEN, or run 'tea login add --url https://$REMOTE_HOST --token <token>'."
fi
ok "A token for $REMOTE_HOST is set."
require_cmd curl "Install curl."
run_release_checks
prepare_tag
write_notes_file "$COMPARE_URL"
step "Publishing $TAG to Gitea ($REPO_SLUG)"
printf ' %sremote%s %s\n' "$C_DIM" "$C_RESET" "$remote_url"
printf ' %sapi%s %s\n' "$C_DIM" "$C_RESET" "$API_URL"
printf ' %snotes%s %s\n' "$C_DIM" "$C_RESET" "$NOTES_FILE"
confirm "Publish $TAG to Gitea?"
push_branch_and_tag "$REMOTE"
if is_dry_run; then
# Nothing is asked of the server during a dry run.
release_status="404"
else
release_status="$(
curl -s -o /dev/null -w '%{http_code}' \
-H "Authorization: token $TOKEN" \
-H "Accept: application/json" \
"$API_URL/repos/$REPO_SLUG/releases/tags/$TAG" || printf '000'
)"
fi
if [ "$release_status" = "200" ]; then
release_already_exists "The Gitea release"
else
body="$(cat "$NOTES_FILE")"
payload="$(printf '{"tag_name":"%s","target_commitish":"%s","name":"%s","body":"%s","draft":false,"prerelease":false}' \
"$TAG" \
"$BRANCH" \
"$TAG" \
"$(json_escape "$body")")"
# MARK:create-release
if is_dry_run; then
detail "[dry run] POST $API_URL/repos/$REPO_SLUG/releases"
detail "[dry run] $payload"
api_status="201"
else
response_file="$(mktemp -t cobble-gitea-release.XXXXXX)"
api_status="$(
printf '%s' "$payload" |
curl -s -o "$response_file" -w '%{http_code}' \
-X POST \
-H "Authorization: token $TOKEN" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
--data-binary @- \
"$API_URL/repos/$REPO_SLUG/releases" || printf '000'
)"
fi
# END:create-release
case "$api_status" in
201 | 200)
ok "Created the Gitea release."
;;
409)
release_already_exists "The Gitea release"
;;
*)
if [ -n "${response_file:-}" ] && [ -s "$response_file" ]; then
printf '%s\n' "$(cat "$response_file")" >&2
fi
if [ -n "${response_file:-}" ]; then
rm -f "$response_file"
fi
if [ "$api_status" = "403" ]; then
fail "Gitea answered HTTP 403: the token's user cannot write to $REPO_SLUG. The tags and $BRANCH still push over SSH, but creating a release needs the token's user to be a writer (write or admin) on the repository. Check it with: curl -s -H \"Authorization: token \$GITEA_TOKEN\" $API_URL/repos/$REPO_SLUG | grep -o '\"permissions\":{[^}]*}'"
fi
fail "Gitea answered HTTP $api_status for the release."
;;
esac
if [ -n "${response_file:-}" ]; then
rm -f "$response_file"
fi
fi
print_release_summary "$REMOTE" "$BRANCH" "https://${REMOTE_HOST}/${REPO_SLUG}/releases/tag/$TAG"
printf '\nThe image is built by the GitHub release, which cannot reach this registry.\nOnce that build has finished, copy it in over the VPN with:\n'
printf ' bun run mirror:gitea\n'
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env bash
# Publishes a Cobble release to GitHub.
#
# scripts/publish-github.sh
#
# Runs the release gate from RELEASING.md (clean tree, typecheck, tests,
# installer syntax), tags HEAD with the package.json version, pushes main and
# the tag to the `origin` remote, then creates the GitHub release. Publishing
# that release is what fires .github/workflows/release.yml, which builds the
# multi-arch image and pushes it to GHCR, the registry the installer defaults
# to. It never pushes to Gitea: that registry is on the VPN, out of a
# runner's reach, so scripts/mirror-gitea.sh copies the image separately.
#
# Run scripts/publish-gitea.sh afterwards for the source mirror's own release
# object, and scripts/mirror-gitea.sh once the image build has finished.
set -Eeuo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/publish-common.sh
. "$SCRIPT_DIR/lib/publish-common.sh"
# shellcheck source=lib/publish-release.sh
. "$SCRIPT_DIR/lib/publish-release.sh"
REMOTE="origin"
usage() {
cat <<EOF
Publishes a Cobble release to GitHub.
Usage: scripts/publish-github.sh [options]
Options:
--version VERSION Version to release, with or without the leading v.
Defaults to package.json's version.
--branch NAME Branch to publish from (default: main).
--yes, -y Do not prompt.
--dry-run Print what would run, change nothing locally or remotely.
--skip-checks Skip typecheck, tests and the install.sh syntax check.
-h, --help Show this help.
The release object is created with the commit log since the previous tag as
its body, and marked latest on GitHub. The tag is pushed before the release
is created, so a rerun after a failure finishes the job.
Environment:
DRY_RUN=1, ASSUME_YES=1 Same as --dry-run and --yes.
EOF
}
parse_publish_args "$@"
if [ "$HELP" = "1" ]; then
usage
exit 0
fi
reject_unknown_args "$0"
trap cleanup_notes EXIT
require_cmd gh "Install the GitHub CLI: https://cli.github.com"
preflight "$REMOTE"
resolve_version
remote_url="$(git remote get-url "$REMOTE")"
parse_remote_url "$remote_url"
COMPARE_URL="https://${REMOTE_HOST}/${REMOTE_OWNER}/${REMOTE_REPO}/compare/"
step "Checking the GitHub login"
if [ "$DRY_RUN" = "1" ]; then
detail "[dry run] gh auth status"
else
gh auth status >/dev/null 2>&1 || fail "The GitHub CLI is not logged in. Run: gh auth login"
ok "gh is logged in."
fi
run_release_checks
prepare_tag
write_notes_file "$COMPARE_URL"
step "Publishing $TAG to GitHub ($REMOTE_OWNER/$REMOTE_REPO)"
printf ' %sremote%s %s\n' "$C_DIM" "$C_RESET" "$remote_url"
printf ' %snotes%s %s\n' "$C_DIM" "$C_RESET" "$NOTES_FILE"
confirm "Publish $TAG to GitHub and start the image build?"
push_branch_and_tag "$REMOTE"
if gh release view "$TAG" -R "$REMOTE_OWNER/$REMOTE_REPO" >/dev/null 2>&1; then
release_already_exists "The GitHub release"
else
# Publishing the release is what starts the image build.
run gh release create "$TAG" \
--repo "$REMOTE_OWNER/$REMOTE_REPO" \
--title "$TAG" \
--notes-file "$NOTES_FILE" \
--target "$BRANCH" \
--latest
ok "Created the GitHub release; the release workflow is building the images."
fi
print_release_summary "$REMOTE" "$BRANCH" "https://github.com/${REMOTE_OWNER}/${REMOTE_REPO}/releases/tag/$TAG"
printf '\nThe release workflow builds and pushes the images; follow it with:\n gh run watch\n'
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More