Compare commits

...
30 Commits
Author SHA1 Message Date
tben 197c8f4e2e v0.27.12
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-23 12:12:52 +01:00
tben 70733e2358 Show the bot's computer live in its panel
The Tools tab's Computer section now embeds the computer's screen, so the
user watches it work without leaving the conversation; a click opens the
viewer. The bot's computers carry their container status, so a stopped one
gets no frame to fail in.
2026-11-23 12:12:42 +01:00
tben 2221113e91 Put the bot panel's memory under Settings
One short memory editor did not earn a tab of its own, so the panel is
Settings (profile, instructions, memory) and Tools.
2026-11-23 11:55:20 +01:00
tben fa81e93792 Tidy the composer tools row
Drop the separator dot between the tools and the browser buttons, fold
the modal trigger's class through twMerge, and tidy formatting.
2026-11-23 11:45:19 +01:00
tben 402df96b76 Open the bot panel from a bot's stones in the thread
The stones beside a bot's messages, its thinking row and its unanswered
row now open the bot panel when tapped, as the header stone and name do,
for crew managers only. BotPanelTrigger takes a size and a class and
keeps the header's behaviour by default.
2026-11-23 11:45:15 +01:00
tben fd823f39e8 Release 0.27.11
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-23 10:59:51 +01:00
tben ea0e3fa014 Hold a conversation to one send, and move a plan only from its card
Two sends landing together both read the same full session, so one rolled it
over and the other wrote into the session that call had just closed: the
message and its reply went where the user never saw them. Sending a message
and answering a card now hold a per-conversation lock, a rollover that writes
nothing returns the conversation's current session, and the composer holds
its send until it answers.

A finished plan step now ends on an ask_user card the app moves the plan
from, so nothing has to be prompted along in the chat: a step's reply is sent
back until the card is up, the answer starts the next step, and an ordinary
reply can no longer finish a step the app then leaves sitting. A plan whose
step isn't running has Continue on its card. Task runs carry the step too.

A run's system prompt listed all 1,234 connector tools it could load, one
description line each: 203,000 characters on every turn. A namespace of 40
tools or more is now named on one line, about 49,000 tokens less per turn.
2026-11-23 10:57:12 +01:00
tben 69919fcd77 Add backups from a provider and a model, one row at a time
Each backup slot was a dropdown listing every model of every provider
flat, so a backup was a wall of near-identical names from providers the
user never picked. The saved backups now read as rows, each named with
its provider and removable, and "Add backup" opens a modal that picks the
provider first and then its models, the same way the main pick works. A
model already on the list, or the pick itself, is never offered twice.
2026-11-23 09:54:25 +01:00
tben 403688e455 Show a computer take-over as a card, and stop waiting once the user writes
The card carries the computer's big picture, the mode and the button that
opens it, and stands as a block of its own in the message instead of a pill
lost in the text. It says "Waiting for you" only while no user message
follows the one it was written in, so handing the computer back - a chat
message - ends the wait and the tag goes back to the mode.
2026-11-23 09:40:30 +01:00
tben 1a68dd7e19 Merge pull request 'docs: rewrite README for clarity and conversion' (#1) from docs/readme-rewrite into main
CI / check (push) Canceled after 0s
Reviewed-on: #1
2026-11-23 09:06:01 +01:00
tben 63512b75ce Correct four README claims and move the demo shot list
CI / check (pull_request) Canceled after 0s
The coordinator does run tasks on computers, so it never "does the work
itself" was wrong. Bot files are found by name or path, not searched by
meaning. Data leaves the box wherever the user points a bot, not only to
the model provider. A hand-over leaves the same browser and files, so say
that instead of "it carries on".

The seven-beat GIF shot list moves out of a 32-line comment in the
README into docs/readme/DEMO.md, and the Gitea link keeps its canonical
capitalisation.
2026-11-23 09:01:28 +01:00
tben 0fd348f158 docs: rewrite README for clarity and conversion
CI / check (pull_request) Canceled after 0s
- Hero states the product in one line
- Install command above the fold
- New comparison section
- Star CTA added
- Contributing section expanded
- Demo GIF placeholder added, commented out
2026-11-23 07:45:47 +00:00
tben aef7169173 Release 0.27.10
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-23 07:33:39 +01:00
tben 712145582e Test that an active plan marks a reply due 2026-11-23 07:32:23 +01:00
tben 1b26c5b42f Stand the thinking row at once when a plan is approved 2026-11-23 07:26:44 +01:00
tben 3e13d02341 Adopt only the account a sign-in here made, so a provider leftover cannot double a card
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A fresh app adopted the first connected account its provider listed, even
when no request here started it. A leftover at the provider (a sign-in made
there, or an earlier attempt's) took that card, and the user's own sign-in
was then claimed beside it, so every connect in production made two cards
for one mailbox.

A row is now made only for a connected account a pending request names, an
unfinished sign-in stores nothing, and the insert refuses a second row for
the same provider account when a poll and the cron reach it at once.

Release 0.27.9.
2026-11-23 05:57:53 +01:00
tben a5dbde1da7 Release 0.27.8
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 18:04:53 +01:00
tben 51747c069f Let a connector given to a workspace reach every account connected for it
A workspace's connector gave every member its tools but no account, so a
member with no sign-in of their own was told nothing was connected while
the super admin's account sat unused. Account reach now follows the
workspace grant, whoever connected the account, and the run names them.

The Composio listing also filtered on `user_id`, which it ignores, so one
person's sync adopted the whole project's accounts: it takes `user_ids`.
2026-11-22 18:04:48 +01:00
tben 3f551e7352 Release 0.27.7
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 17:24:14 +01:00
tben fdd1e8a757 Let a Composio toolkit sign in with its own scheme, and stop adopting a replaced app's leftovers 2026-11-22 17:20:41 +01:00
tben 60022d8220 Split the bot panel into Settings, Memory and Tools
The drawer held only the bot's profile. Its memory and everything it works
with now have tabs of their own, the last one sharing the composer's own
list of tools and knowledgebases.

- Memory: core memory, plus the workspace's memory for the bot when the
  conversation is in one. New `update-bot-memory` route; the workspace
  request's fields are optional so a memory-only save cannot blank the
  instructions there.
- Tools: computer, tools/skills/MCPs with connectors and browsers, and
  knowledgebases.
2026-11-22 16:49:44 +01:00
tben 4837bf325e Reconnect the row the request names, and check a cached session's account 2026-11-22 16:28:36 +01:00
tben 383ef82400 Release 0.27.6
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 16:00:46 +01:00
tben 7e1135beb1 Start a folder at the top and never show the last one's entries
A folder opened from the popup kept the previous folder's rows, trail and name until its own listing arrived, and it kept that listing's scroll offset, so a folder opened part-way down or at its bottom. The listing is now handed back only for the volume and path it belongs to, shows a loading line meanwhile, and is keyed by folder and search so each one starts at the top. The trail is built from the path at once instead of waiting for the listing, and the file preview header puts the size and full path on their own line so a phone no longer squeezes them into a character column.
2026-11-22 15:56:19 +01:00
tben b30d6118fe Transcribe on Alibaba's native route, and card the composer error
The Token Plan host has no /audio/transcriptions: its ASR model is served at the DashScope host root, with the audio inline as a data URL and the model's own format and language hints. Async-only slugs (filetrans, paraformer) are refused with the synchronous model to pick instead. The image helpers that recognise those hosts move to one shared module.

A failed send, or a failed dictation, now shows as a dismissible card under the composer in the error or warning tint rather than a line of grey text.
2026-11-22 15:51:38 +01:00
tben 35b9808d97 Close a phone panel with the swipe back off its edge
An open panel now answers the swipe that undoes the one which opened it: a left drag closes the rail's drawer, a right drag the bot panel, through a panel-local listener sharing swipe-gesture.ts with the page swipes. SidePanel carries the bot panel's phone width (420px, at most 92vw) for both, and field detection moves to touch-in-field.ts so both hooks ignore a touch in a field.
2026-11-22 15:36:07 +01:00
tben 7460163287 Keep suggested next steps inside their chips on a phone 2026-11-22 15:30:41 +01:00
tben da6a73f740 Release 0.27.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 12:35:22 +01:00
tben 2afe35954c Size runs to the model's own window, and stop a run reading notes instead of answers
The working context was 70% of the model's window, and a model whose
catalog never declared one got 70% of a guessed 131,072: a chat on a
custom provider was told it had 91,750 tokens, then had every tool result
trimmed to a bare note, including a 14-character shell answer, and spent
its remaining steps reading nothing.

- workingContextTokens: the declared window less the room the answer
  needs (max_output_tokens, else a tenth clamped to 8,000-64,000),
  capped by grabContextBudgetTokens when an install sets one.
- An undeclared window is assumed to be 1,000,000, and the guess is not
  silent: the picker marks such a model and the Models page says what a
  run works to. A provider that refuses the prompt for size stops the
  run with its own limit (fatal: no fallback, no rest, no retry).
- fitTranscriptToContext: a result under 2,000 characters is never cut,
  a trimmed one keeps its start and its end, and the newest turn's
  results are cut last. over_budget says whether the static prompt or
  the request is over; the static case stops the run at once instead of
  trimming every turn.
- Built-in tools are deferred by family (groupTools, ToolGroups) on a
  model short of window; load_tools takes a family name or a prefix.
  Wrap-up tools, closing tools and load_tools are never deferred.
- Usage reports what the app's own prompt and tools took before the
  conversation did.
2026-11-22 12:35:17 +01:00
tben 5ea9b608be Refuse a connector account the provider no longer has, and stop adopting duplicates
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 10:56:35 +01:00
177 changed files with 4969 additions and 1341 deletions
+9 -8
View File
File diff suppressed because one or more lines are too long
+211 -165
View File
@@ -5,69 +5,104 @@
<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 (alpha).
### A crew of small AI worker bots you host yourself
![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)
Not a chat box with a system prompt. A coordinator, a team of workers, and real
Docker computers with a browser and a shell that they actually operate.
[![CI](https://github.com/Moduletrace/cobble/actions/workflows/ci.yml/badge.svg)](https://github.com/Moduletrace/cobble/actions/workflows/ci.yml)
[![GitHub stars](https://img.shields.io/github/stars/Moduletrace/cobble?style=flat&color=0e1116)](https://github.com/Moduletrace/cobble/stargazers)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Website](https://img.shields.io/badge/website-cobble.moduletrace.org-0e1116)](https://cobble.moduletrace.org)
[![Bun](https://img.shields.io/badge/runs%20on-Bun-14151a?logo=bun&logoColor=white)](https://bun.sh)
[![Runs on Bun](https://img.shields.io/badge/runs%20on-Bun-14151a?logo=bun&logoColor=white)](https://bun.sh)
```bash
curl -fsSL https://url.moduletrace.com/cobble | sudo bash
```
One command. One SQLite file. Your machine. No account, no per-seat pricing.
<br>
<!-- Demo GIF: shot list in docs/readme/DEMO.md. -->
<!-- ![Cobble in action: delegating to a crew, a bot driving a real browser, a handoff to the human, a finished pull request](docs/readme/demo.gif) -->
![Cobble: a self-hosted crew of small AI worker bots](docs/readme/hero-light.png#gh-light-mode-only)
![Cobble: a self-hosted crew of small AI worker bots](docs/readme/hero-dark.png#gh-dark-mode-only)
[Website](https://cobble.moduletrace.org) · [Install](#install) · [Features](#features) · [Development](#development) · [Architecture](AGENTS.md)
</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: lean Docker sandboxes with a real Chrome and
a shell, which a bot can use and hand back to you when it needs help.
> **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.
It is an install, not a SaaS. One SQLite database, one Docker container, and
your data on your own machine.
## The problem with one big assistant
**Why small workers instead of one big assistant**
You give an agent a task. It works for forty turns. Somewhere in the middle it
loses the thread, forgets what it already tried, or quietly stops and says it is
done. You cannot see what it is doing, you cannot stop it cleanly, and the whole
thing lives in someone else's cloud with your files in it.
- **A crew, not a chat.** Each worker has one job and only loads the context
for it. A five-bot crew does five things in parallel, and each one stays
cheap and focused.
Cobble splits that agent into a crew and gives the crew a machine:
- **A crew, not a chat.** Each worker has one job and only loads the context for
it. A five-bot crew does five things in parallel, and each one stays cheap
and focused. The coordinator plans and delegates; the workers do the work.
- **Bots you can see through.** The face on each stone is the status: idle,
working, done, asleep, needs you. You read the whole crew at a glance
instead of asking each one what it is doing.
- **Real computers.** Workers run on your own sandboxed machines, with
browser, terminal, files and desktop, not just a tool loop.
working, done, asleep, needs you. You read the whole crew at a glance instead
of asking each one what it is doing.
- **Real computers.** Workers run on your own sandboxed Docker machines, with a
real headful Chrome on a virtual screen, a shell, files and a desktop. Not
just a tool loop that can call `curl`.
- **A human in the loop that works.** When a bot hits a login wall or a captcha,
it hands the live browser back to you mid-task. You act, you hand it back, and
it continues from the same browser and the same files. No restart, no lost
state.
- **Yours.** Self-hosted, MIT, one SQLite file to back up, no account and no
per-seat billing.
per-seat billing. Your keys stay on your machine.
## Where Cobble fits
| | One big chat assistant | A hosted agent platform | Cobble |
|---|---|---|---|
| Runs on your hardware | No | No | Yes, one container plus one per computer |
| Parallel work | Manually, one thread | Often | Yes, one worker per job |
| Real browser and shell | No | Sometimes, headless | Yes, headful Chrome plus a shell, visible live |
| Human takes over mid-task | Copy and paste | Rarely | Yes, live, same session |
| Your data leaves the box | Yes | Yes | Only where you point it: your provider, the tools you give a bot |
| Cost model | Per seat | Per seat plus usage | Your hardware, your API keys |
| Licence | Proprietary | Proprietary | MIT |
If you want a single assistant that writes emails, a chat app is cheaper. If you
want a team that ships work on machines you control, that is this.
## Features
| Area | What you get |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 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 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 |
| Area | What you get |
| --- | --- |
| 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 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, find them by name or path, 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
@@ -77,44 +112,72 @@ their instructions there, and its computers.
![A workspace dashboard in Cobble](docs/readme/workspace-light.png#gh-light-mode-only)
![A workspace dashboard in Cobble, dark mode](docs/readme/workspace-dark.png#gh-dark-mode-only)
## How it fits together
```
You ── chat ── Coordinator ── delegates ── Workers
│ │
├── Workspaces ──────────┤
│ context, memory, bots │
├── Routines ────────────┤
│ cron schedules │
└── Computers ───────────┘
docker sandboxes:
real Chrome, shell
```
- **Coordinator** is yours alone. It plans, delegates to workers, and keeps the
crew in order. It is the only bot that reaches every worker.
- **Workers** are the crew. Each has a job, its own instructions and memory, and
its own models if you want to tune cost per bot.
- **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 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
summary into the next one.
## Install
On a Linux machine with Docker (the installer adds Docker when it is
missing):
On a Linux machine with Docker (the installer adds Docker when it is missing):
```bash
curl -fsSL https://url.moduletrace.com/cobble | sudo bash
```
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 computer image in the background. Give it a
few minutes.
`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 computer image in the background. Give it a few minutes.
Then open **Settings > Models**, add an OpenRouter key (or another provider)
and wait for the model list to sync. This is what the bots think with.
Then open **Settings > Models**, add an OpenRouter key (or another provider) and
wait for the model list to sync. This is what the bots think with.
### Requirements
- Linux amd64 or arm64, with Docker. The installer installs Docker from
get.docker.com when it is missing.
- 2 CPU cores, 4 GB RAM and 20 GB free disk for the app plus one computer.
Each computer is its own container with its own memory limit.
- Docker Desktop on macOS works for development and small installs, but
Linux is the supported host.
- 2 CPU cores, 4 GB RAM and 20 GB free disk for the app plus one computer. Each
computer is its own container with its own memory limit.
- Docker Desktop on macOS works for development and small installs, but Linux is
the supported host.
- Port 7227, or another port with `--port`.
- A reverse proxy or tunnel in front for HTTPS. The app itself serves plain
HTTP and never handles certificates.
- A reverse proxy or tunnel in front for HTTPS. The app itself serves plain HTTP
and never handles certificates.
The installer binds to `0.0.0.0` so the app is reachable from your phone on
the same network. Use `--bind 127.0.0.1` when a reverse proxy is the only
thing that should reach it.
The installer binds to `0.0.0.0` so the app is reachable from your phone on the
same network. Use `--bind 127.0.0.1` when a reverse proxy is the only thing that
should reach it.
The app container itself is limited to 1 CPU and 2 GB of memory, since the
heavy work happens in the computers' own containers. Change that with
`--cpus` and `--memory`; each computer keeps its own limits.
The app container itself is limited to 1 CPU and 2 GB of memory, since the heavy
work happens in the computers' own containers. Change that with `--cpus` and
`--memory`; each computer keeps its own limits.
## HTTPS
@@ -127,21 +190,21 @@ point that at `http://<this machine>:7227`:
`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.
`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.
Nothing on the machine needs a certificate installed: the browser only ever
talks to the proxy. See the Help page in the app for the common proxy fixes.
## Update and uninstall
The same script is the updater. It keeps the database, media, computers'
home directories and generated secrets, backs up the database before
replacing the container, and does nothing when the image has not changed.
The same script is the updater. It keeps the database, media, computers' home
directories and generated secrets, backs up the database before replacing the
container, and does nothing when the image has not changed.
```bash
curl -fsSL https://url.moduletrace.com/cobble | sudo bash
@@ -157,54 +220,24 @@ curl -fsSL https://url.moduletrace.com/cobble | sudo bash -s -- --uninstall --pu
### Options
| Option | Meaning |
| --------------------- | ---------------------------------------------------------- |
| `--home DIR` | Install directory, default `/opt/cobble` |
| `--data-dir DIR` | Data directory mounted at `/data`, default `HOME/data` |
| `--port PORT` | Host port, default `7227` |
| `--bind ADDRESS` | Host address to publish on, default `0.0.0.0` |
| `--cpus N` | CPU cores for the app container, default `1` |
| `--memory MB` | Memory for the app container in MB, default `2048` |
| `--image IMAGE` | Container image, default `ghcr.io/moduletrace/cobble` |
| `--version TAG` | Image tag, default `latest` |
| Option | Meaning |
| --- | --- |
| `--home DIR` | Install directory, default `/opt/cobble` |
| `--data-dir DIR` | Data directory mounted at `/data`, default `HOME/data` |
| `--port PORT` | Host port, default `7227` |
| `--bind ADDRESS` | Host address to publish on, default `0.0.0.0` |
| `--cpus N` | CPU cores for the app container, default `1` |
| `--memory MB` | Memory for the app container in MB, default `2048` |
| `--image IMAGE` | Container image, default `ghcr.io/moduletrace/cobble` |
| `--version TAG` | Image tag, default `latest` |
| `--extra-network NET` | Join another Docker network, for a tunnel or reverse proxy |
| `--force` | Recreate the container even when it is current |
| `--no-pull` | Use an image that is already on the machine |
| `--skip-backup` | Update without a database backup |
| `--no-docker-install` | Fail instead of installing Docker |
| `--yes`, `-y` | Accept the defaults without asking |
| `--uninstall` | Stop and remove the app container |
| `--purge` | With `--uninstall`, also delete the data directory |
## How it fits together
```
You ── chat ── Coordinator ── delegates ── Workers
│ │
├── Workspaces ────────────┤
│ context, memory, bots │
├── Routines ──────────────┤
│ cron schedules │
└── Computers ─────────────┘
docker sandboxes:
real Chrome, shell
```
- **Coordinator** is yours alone. It plans, delegates to workers, and keeps
the crew in order. It is the only bot that reaches every worker.
- **Workers** are the crew. Each has a job, its own instructions and memory,
and its own models if you want to tune cost per bot.
- **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 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
summary into the next one.
| `--force` | Recreate the container even when it is current |
| `--no-pull` | Use an image that is already on the machine |
| `--skip-backup` | Update without a database backup |
| `--no-docker-install` | Fail instead of installing Docker |
| `--yes`, `-y` | Accept the defaults without asking |
| `--uninstall` | Stop and remove the app container |
| `--purge` | With `--uninstall`, also delete the data directory |
## Data and settings
@@ -227,38 +260,37 @@ Everything that must survive an update lives under the install directory:
`.env` holds the port and the encryption keys. The keys encrypt sessions and
settings, so keep a copy and do not rotate them without re-entering provider
keys and other secrets. Provider keys, MCP servers, tools and app settings
are managed in the app, not in `.env`.
keys and other secrets. Provider keys, MCP servers, tools and app settings are
managed in the app, not in `.env`.
Edit `.env` and run `docker restart cobble` to apply changes. The installer
only appends missing values and keeps what is already there, apart from the
port it manages.
Edit `.env` and run `docker restart cobble` to apply changes. The installer only
appends missing values and keeps what is already there, apart from the port it
manages.
Settings > Backups makes two kinds of copy. Database snapshots (bun-sqlite's
`backup` command) stay in `data/db/.backups` and can be restored from the
app. Whole-data archives are a `tar.gz` of the entire `data/` directory,
written to `backups-archives/` (mounted at `/backups-archives`, the
`BACKUP_ARCHIVE_DIR` setting); every entry sits under one folder named after
the archive, so extracting one by hand drops a single folder. Each group
can create a copy, restore from one (a listed row, or a file uploaded from
the button beside Create), download it and delete it; the newest five
archives are kept.
`backup` command) stay in `data/db/.backups` and can be restored from the app.
Whole-data archives are a `tar.gz` of the entire `data/` directory, written to
`backups-archives/` (mounted at `/backups-archives`, the `BACKUP_ARCHIVE_DIR`
setting); every entry sits under one folder named after the archive, so
extracting one by hand drops a single folder. Each group can create a copy,
restore from one (a listed row, or a file uploaded from the button beside
Create), download it and delete it; the newest five archives are kept.
The app container is started with the Docker socket mounted and
`MAIN_SERVER=1`, so it can create computer containers and run cron, the
queue and Web Push.
`MAIN_SERVER=1`, so it can create computer containers and run cron, the queue
and Web Push.
## Images
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.
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.
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
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
@@ -291,32 +323,31 @@ Open `http://localhost:7227`. With no users, every page goes to
SEED_SUPER_ADMIN_PASSWORD=... bun run seed
```
The development server serves plain HTTP, the same as the container. To try
the app from a phone, run a proxy or tunnel in front of it (see
[HTTPS](#https)); the installed app, Web Push and voice need that secure
context.
The development server serves plain HTTP, the same as the container. To try the
app from a phone, run a proxy or tunnel in front of it (see [HTTPS](#https)); the
installed app, Web Push and voice need that secure context.
| Command | Purpose |
| ---------------------- | ----------------------------------- |
| `bun run dev` | Development server |
| `bun run start` | Production server on the host |
| `bun run typecheck` | Type-check |
| `bun run test` | Run the test suite |
| `bun run check:bundle` | Bundle budget after a build |
| `bun run seed` | Create the super admin from the CLI |
| `bun run seed:bots` | Add a sample crew |
| `bun run db:schema` | Sync the schema and types |
| `bun run gen:favicon` | Regenerate favicons and PWA assets |
| Command | Purpose |
| --- | --- |
| `bun run dev` | Development server |
| `bun run start` | Production server on the host |
| `bun run typecheck` | Type-check |
| `bun run test` | Run the test suite |
| `bun run check:bundle` | Bundle budget after a build |
| `bun run seed` | Create the super admin from the CLI |
| `bun run seed:bots` | Add a sample crew |
| `bun run db:schema` | Sync the schema and types |
| `bun run gen:favicon` | Regenerate favicons and PWA assets |
Plain Node does not work: the app runs on Bun. The stack is Bun,
[`@moduletrace/bunext`](https://github.com/Moduletrace/bunext) for
filesystem routing, SQLite via
[`@moduletrace/bun-sqlite`](https://github.com/Moduletrace/bun-sqlite),
Tailwind CSS and the `@moduletrace/twui` component library. The model layer is
one adapter over OpenAI-compatible APIs, so any compatible provider works.
[`@moduletrace/bunext`](https://github.com/Moduletrace/bunext) for filesystem
routing, SQLite via
[`@moduletrace/bun-sqlite`](https://github.com/Moduletrace/bun-sqlite), Tailwind
CSS and the `@moduletrace/twui` component library. The model layer is one
adapter over OpenAI-compatible APIs, so any compatible provider works.
See [AGENTS.md](AGENTS.md) for the full architecture, routes, queue, harness
and data model. CI runs type-check and tests on every push and pull request;
See [AGENTS.md](AGENTS.md) for the full architecture, routes, queue, harness and
data model. CI runs type-check and tests on every push and pull request;
releases are built by GitHub Actions and pushed to both registries. See
[RELEASING.md](RELEASING.md) for the release and launch checklist.
@@ -325,9 +356,24 @@ releases are built by GitHub Actions and pushed to both registries. See
Issues and pull requests are welcome, in English, on either
[GitHub](https://github.com/Moduletrace/cobble) or
[Gitea](https://git.tben.me/Moduletrace/cobble). Run `bun run typecheck` and
`bun run test` before opening a pull request, and read
[AGENTS.md](AGENTS.md) first: it documents the conventions the code follows.
`bun run test` before opening a pull request, and read [AGENTS.md](AGENTS.md)
first: it documents the conventions the code follows.
Good first contributions right now: a worker role that ships as a one-click
template, an MCP server integration that other people would install, a missing
proxy recipe for the Help page, or a test around a bug you hit while installing.
## License
MIT. See [LICENSE](LICENSE).
---
<div align="center">
**If Cobble saves you from stitching three tools together, star the repo.**
It is the fastest way to help other people find it.
[![Star Cobble](https://img.shields.io/github/stars/Moduletrace/cobble?style=social)](https://github.com/Moduletrace/cobble/stargazers)
</div>
+5
View File
@@ -2012,6 +2012,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
dataType: "INTEGER",
defaultValue: 0,
},
{
fieldName: "plan_id",
fieldDescription: `The plan whose step ended on this card: its first option continues the plan, anything else pauses it. Empty for an ordinary question. Not a foreign key`,
dataType: "INTEGER",
},
],
indexes: [
{
+4
View File
@@ -1305,6 +1305,10 @@ export type BUN_SQLITE_COBBLE_BOT_QUESTIONS = {
* Asked in a Plan mode reply: their answer and skip are run in Plan mode too, since answering is not a way out of the mode
*/
plan_mode?: number | "";
/**
* The plan whose step ended on this card: its first option continues the plan, anything else pauses it. Empty for an ordinary question. Not a foreign key
*/
plan_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_SUGGESTIONS = {
+35
View File
@@ -0,0 +1,35 @@
# Demo GIF
The demo recording is a placeholder. `README.md` carries the image line commented
out, pointing at `docs/readme/demo.gif`, which does not exist yet.
## To go live
1. Record the loop below and save it as `docs/readme/demo.gif`, under 8 MB
(GitHub renders anything bigger badly, and the point is that it plays
instantly on the repo page).
2. Uncomment the image line near the top of `README.md`.
## Shot list
Target 12 to 18 seconds, 960px wide, loop, no audio.
1. **0.0s** The rail. Coordinator at top, four workers below with different
faces. Mouse hovers one, its status line reads "working".
2. **2.5s** Cut to the chat. You type: "Check whether the staging site still
returns 200 and open a PR if the footer link is broken." Send.
3. **4.5s** The coordinator delegates. Two worker faces go to "working" in the
rail at the same time.
4. **6.5s** Cut to the live computer view. Chrome is open, the bot is scrolling
the staging site. The cursor moves on its own. Terminal panel beside it shows
curl output.
5. **10.0s** The bot hits a login wall. Face flips to "needs you". Card appears
asking to take over. You click, type the password, hand it back.
6. **12.5s** The bot finishes. PR link appears in chat. Worker faces go to
"done".
7. **15.0s** Pull back to the rail. Whole crew idle, everything green, one line
of summary text.
That sequence is the entire product in one loop: delegate, parallel work, a real
browser, a human handoff, a shipped artifact. Do not replace it with a
screenshot carousel.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.27.3",
"version": "0.27.12",
"module": "index.ts",
"type": "module",
"private": true,
+29 -4
View File
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test";
import planStepReviewNote from "./plan-step-review";
const plan = { id: 3, title: "Open the shop", current_step: 1 };
const plan = { id: 3, title: "Open the shop", current_step: 1, total_steps: 3 };
const note = ({ on_step = true, uses = [], status }: { on_step?: boolean; uses?: { name: string; ok: boolean }[]; status?: "done" | "working" | "blocked" }) =>
planStepReviewNote({ plan, on_step, tool_uses: uses, status });
@@ -12,12 +12,37 @@ describe("planStepReviewNote", () => {
expect(note({ uses: [{ name: "write_file", ok: true }] })).toContain("complete_plan_step");
});
test("finishing the step passes", () => {
expect(note({ uses: [{ name: "complete_plan_step", ok: true }] })).toBeNull();
test("a finished step without its card is sent back for the card", () => {
const fault = note({ uses: [{ name: "complete_plan_step", ok: true }] });
expect(fault).toContain("ask_user");
expect(fault).toContain("Continue to step 3");
expect(fault).toContain("Pause the plan");
});
test("finishing the step and putting the card up passes", () => {
const uses = [
{ name: "complete_plan_step", ok: true },
{ name: "ask_user", ok: true },
];
expect(note({ uses })).toBeNull();
});
test("the last step's card offers to finish the plan", () => {
const last = { ...plan, current_step: 2 };
expect(
planStepReviewNote({
plan: last,
on_step: true,
tool_uses: [{ name: "complete_plan_step", ok: true }],
}),
).toContain("Finish the plan");
});
test("a failed finish does not pass", () => {
expect(note({ uses: [{ name: "complete_plan_step", ok: false }] })).toContain("did not finish it");
expect(note({ uses: [{ name: "complete_plan_step", ok: false }] })).toContain("complete_plan_step");
});
test("asking, changing the plan or handing work on ends the step honestly", () => {
+17 -16
View File
@@ -1,11 +1,12 @@
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
import type { HarnessToolUse } from "@/src/harness/types";
import { WorkStartingTools } from "@/src/utils/should-continue-plan";
import PlanWorkStartingTools from "@/src/utils/plan-work-starting-tools";
type PlanStep = {
id: number;
title: string;
current_step: number | null;
total_steps: number;
};
type Params = {
@@ -22,35 +23,35 @@ type Params = {
};
/**
* The tools that end a step without finishing it, and are meant to: the run
* asks the user, changes the plan, or hands work on whose report comes
* later. A run that did none of these and never called
* `complete_plan_step` did something else entirely (a step of its own, a
* plan written to a file), and the app would otherwise carry the plan on
* past the step it never did.
* The tools that end a step without its card, and are meant to: the run
* asks the user (the card itself), changes the plan (its card takes over),
* or hands work on whose report comes later. Anything else that ends a step
* leaves the plan waiting on nothing, and the user has to say "move on".
*/
const EndingTools = ["ask_user", "update_plan", ...WorkStartingTools];
const EndingTools = ["ask_user", "update_plan", ...PlanWorkStartingTools];
/**
* Checks a plan step's reply before it goes out: the run works one step,
* and must either finish it or say why it can't. Returns a note that sends
* the answer back to the model, or null when the reply ends the step the
* way the plan expects.
* Checks a plan step's reply before it goes out: the step ends on a card
* whose first option continues the plan, so the plan moves on from the card
* in front of the user, never from the bot remembering to ask. A reply that
* reports the step and ends is sent back.
*/
export default function planStepReviewNote({ plan, on_step, tool_uses, status }: Params) {
if (!on_step || !plan || plan.current_step == null) return null;
/**
* A reply that started work or says what stopped it already ends the
* step honestly; the plan waits on the user or the run it started.
* A reply that says what stopped it, or hands the work to a run of its
* own, ends the step where the user can see it.
*/
if (status == "working" || status == "blocked") return null;
const ended = tool_uses.some((use) => use.ok && (use.name == "complete_plan_step" || EndingTools.includes(use.name)));
const ended = tool_uses.some((use) => use.ok && EndingTools.includes(use.name));
if (ended) return null;
const step = plan.current_step + 1;
const next = step + 1;
const last_step = next > plan.total_steps;
return `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and did not finish it. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences. If it needs the user, ask with ask_user. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`;
return `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and ended without the step's card, so the plan has nothing to move on from. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences, and put the card up in the same turn with ask_user. The card asks "Continue with the plan?": first option "${last_step ? "Finish the plan" : `Continue to step ${next}`}", second option "Pause the plan", then any choice the step really needs. If it needs the user for something else, ask that on the card too. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`;
}
-20
View File
@@ -31,8 +31,6 @@ import grabJobUserId from "@/src/functions/backend/db/bots-queue/grab-job-user-i
import runBotJob from "./run-bot-job";
import parseJobJson from "./parse-job-json";
import nameBotSession from "./name-bot-session";
import wakeBotsQueue from "./wake-bots-queue";
import continueBotPlan from "@/src/functions/backend/db/bot-plans/continue-bot-plan";
import pushBotSession from "./push-bot-session";
import grabSessionAskId from "@/src/functions/backend/db/bot-sessions/grab-session-ask-id";
import { registerJobAbort, unregisterJobAbort } from "./job-abort-registry";
@@ -325,24 +323,6 @@ export default async function processBotJob({
await pushBotNotice({ bot_id, ...completion });
/**
* A run that worked a step of a plan hands it on: the next step is
* queued here, once this reply is out, so each step is its own
* message (`continueBotPlan` holds it when the user is needed or
* the run started work of its own).
*/
if (outcome.plan_id) {
await continueBotPlan({
plan_id: outcome.plan_id,
session_id: Number(completion.message?.session_id || job.session_id),
needs_you: Boolean(outcome.needs_you),
started_work: Boolean(outcome.started_work),
tool_names: (outcome.tool_log || []).map((use) => use.name),
}).then((job_id) => {
if (job_id) wakeBotsQueue();
});
}
/**
* Once the first exchange is sent, the bot names the session and
* previews it. After the reply is pushed, so it never waits on it;
+11 -3
View File
@@ -45,6 +45,7 @@ import runTextLoop from "@/src/harness/text/run-text-loop";
import type { HarnessTool } from "@/src/harness/types";
import grabBotChatTools from "@/src/harness/tools/bot/grab-bot-chat-tools";
import gatePlanModeTools from "@/src/harness/tools/bot/plan-mode-tools";
import groupTools from "@/src/harness/tools/group-tools";
import grabBotFileTools from "@/src/harness/tools/storage/grab-bot-file-tools";
import grabBotGraphicTools from "@/src/harness/tools/graphics/grab-bot-graphic-tools";
import grabRunScopes from "@/src/functions/backend/db/bot-files/grab-run-scopes";
@@ -415,6 +416,7 @@ export default async function runBotReply({
onTask: ({ task_id }) => task_ids.push(task_id),
onAttach: ({ media_id }) => attachments.push(media_id),
plan_mode,
plan_id: on_plan_step ? plan?.id : null,
});
/**
@@ -590,6 +592,12 @@ export default async function runBotReply({
* when it was asked in it (`postBotQuestionAnswers`).
*/
plan_mode,
/**
* The plan whose step this reply works, when it does:
* the card it ends on is the plan's next move
* (`postBotQuestionAnswers`).
*/
plan_id: on_plan_step ? plan?.id : null,
onAsk: ({ ref }) => proposals.push(ref),
redact: redact_reply,
}),
@@ -714,7 +722,9 @@ export default async function runBotReply({
.filter(Boolean)
.join("\n\n"),
messages: await messagesToTurns({ messages: history, user_id }),
tools: plan_mode ? gatePlanModeTools({ tools: reply_tools }) : reply_tools,
tools: plan_mode
? gatePlanModeTools({ tools: groupTools({ tools: reply_tools }) })
: groupTools({ tools: reply_tools }),
max_steps: reply_max_steps,
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
@@ -803,11 +813,9 @@ export default async function runBotReply({
* on while its reports said something else.
*/
needs_you: answer_parts.needs_you || result.status == "blocked" || undefined,
started_work: result.status == "working" || undefined,
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
plan_id: on_plan_step ? plan?.id : undefined,
plan_message_id: message_plan_id ?? (on_plan_step ? plan?.id : undefined),
/**
* A reply handed a tracker task (`params.tracker_task_id`) that
+64 -3
View File
@@ -29,6 +29,7 @@ import {
TaskWrapUpIncomingNote,
taskPlanNote,
wrapUpWorktreeNote,
PlanStepNote,
} from "@/src/data/harness-prompts";
import {
grabContextBudgetTokens,
@@ -38,6 +39,8 @@ import {
} from "@/src/functions/backend/db/app-settings/grab-run-limits";
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
import toBotPlanView from "@/src/functions/backend/db/bot-plans/to-bot-plan-view";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import runTextLoop from "@/src/harness/text/run-text-loop";
import redactTrace from "@/src/harness/trace/redact-trace";
@@ -51,6 +54,7 @@ import openBotExtensions, { type OpenBotExtensions } from "@/src/harness/tools/e
import openBotSkills, { type OpenBotSkills } from "@/src/harness/tools/skills/open-bot-skills";
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools";
import groupTools from "@/src/harness/tools/group-tools";
import grabCoordinatorKnowledgebaseTools from "@/src/harness/tools/bot/knowledgebases/grab-coordinator-knowledgebase-tools";
import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-session";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
@@ -85,6 +89,7 @@ import stripAppRecords from "@/src/utils/strip-app-records";
import ScheduledRunFailedError from "./scheduled-run-failed-error";
import BotJobFatalError from "./bot-job-fatal-error";
import reviewRunAnswer from "./review-run-answer";
import planStepReviewNote from "./plan-step-review";
import deleteBotQuestion from "@/src/functions/backend/db/bot-questions/delete-bot-question";
import type { BotJobContext, BotJobOutcome } from "./types";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -255,6 +260,22 @@ export default async function runBotTask({
* request's run works in a session nobody reads from this bot's chat.
*/
const can_ask = Boolean(session_id) && !scheduled && !hooked && !hidden;
/**
* The plan whose step queued this run (`send_reply`'s work or
* `start_task`, both carrying `params.plan_id`): a long step is
* exactly where a bot forgets the plan, so the run works that step
* and its report ends on the card that moves the plan on.
*/
const plan_row = Number(params.plan_id)
? await grabBotPlan({ plan_id: Number(params.plan_id) }).catch(() => null)
: null;
const plan = plan_row ? toBotPlanView({ row: plan_row }) : null;
/**
* Only a run the user follows can end on the plan's card, so only
* one of those is held to it: a routine's or a hook's run has no
* card to put up and reports as usual.
*/
const on_plan_step = can_ask && Boolean(plan && plan.status == "active" && plan.current_step != null);
/**
* The coordinator weighing a worker's install request
* (`request_install`): it answers it with answer_install_request.
@@ -300,6 +321,21 @@ export default async function runBotTask({
onTask: ({ task_id }) => task_ids.push(task_id),
})),
...admin_tools,
/**
* The plan's own step: it finishes the step, or says the plan
* is wrong. Writing or cancelling a plan is a reply's job, never
* a run's, so those stay out.
*/
...(on_plan_step
? grabBotPlanTools({
user_id,
bot_id: bot.id,
session_id: session_id!,
workspace_id,
on_step: true,
onPlan: ({ ref }) => shown.push(ref),
})
: []),
/**
* Part of a crew request (`start_task`/`delegate_task` in an
* answer session): the bot can send the asker an interim word
@@ -386,6 +422,7 @@ export default async function runBotTask({
session_id,
workspace_id,
in_task: true,
plan_id: on_plan_step ? plan?.id : null,
onAsk: ({ ref }) => take_overs.push(ref),
redact: redact_text,
}),
@@ -621,6 +658,12 @@ export default async function runBotTask({
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
named_files_note,
TasksNote,
/**
* The plan's step this run works: it finishes that step, or asks
* the user on the card, and the report says which. This is the
* note a long step would otherwise lose the plan without.
*/
on_plan_step && plan ? PlanStepNote({ plan }) : "",
ActionCheckNote,
RequestScopeNote({ can_ask }),
can_ask ? QuestionsNote : "",
@@ -696,7 +739,8 @@ export default async function runBotTask({
const result = await runTextLoop({
system,
messages: opening,
tools: [
tools: groupTools({
tools: [
...tools,
/**
* A task report ends with `send_reply`, the same protocol a
@@ -712,6 +756,7 @@ export default async function runBotTask({
message_id: job.message_id || undefined,
job_id: job.id,
run_kind: browser_run_kind,
plan_id: on_plan_step ? plan?.id : null,
onQueue: ({ job_id }) => queued_jobs.push(job_id),
}),
startTaskTool({
@@ -721,13 +766,15 @@ export default async function runBotTask({
computers,
message_id: job.message_id || undefined,
run_kind: browser_run_kind,
plan_id: on_plan_step ? plan?.id : null,
}),
...extensions.tools,
...browsers.tools,
...connectors.tools,
...skills.tools,
...knowledge.tools,
],
],
}),
max_steps,
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
@@ -772,8 +819,21 @@ export default async function runBotTask({
* is where a report names a file or task that isn't there, or
* says work is under way when none is. A note sends it back;
* one the review keeps faulting is never posted.
*
* A report of a plan's step is also held to the step's ending:
* the plan moves on from its card, so a report without one
* leaves the plan waiting on the user to say "move on".
*/
review: reviewRunAnswer({ bot_id: bot.id, user_id, session_id, scopes, job_id: job.id }),
review: ({ text, tool_uses, status }) =>
reviewRunAnswer({ bot_id: bot.id, user_id, session_id, scopes, job_id: job.id })({
text,
tool_uses,
status,
}).then((note) => {
if (note) return note;
return planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status });
}),
/**
* A report goes out only through `send_reply`, so it can't say
* work is under way with the run's own open job behind it.
@@ -843,6 +903,7 @@ export default async function runBotTask({
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
plan_message_id: on_plan_step ? plan?.id : undefined,
/**
* The wrap up was announced (`steps` counts its turns), so the
* run never got to the end of the work it was given.
+3 -15
View File
@@ -74,25 +74,13 @@ export type BotJobOutcome = {
* (`noteTrackerTask`).
*/
exhausted?: boolean;
/**
* The plan this run worked a step of (`params.plan_id`): the app queues
* its next step once the reply is out (`continueBotPlan`), unless the
* run asked for the user or started work that runs on its own.
*/
plan_id?: number;
/**
* The plan the reply's message belongs to: the step it worked, or the
* one it wrote. Kept on the message as a chip (`bot_messages.plan_id`),
* separately from `plan_id`, since a plan that is only written is not
* worked on.
* one it wrote. Kept on the message as a chip (`bot_messages.plan_id`).
* A plan never queues its own next step: that starts from the card under
* the step's report, answered by the user.
*/
plan_message_id?: number;
/**
* The closing `send_reply` queued a run (`status: "working"`): its report
* is still to come, so the plan waits for it instead of queueing its
* next step (`continueBotPlan`).
*/
started_work?: boolean;
};
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
@@ -7,6 +7,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
import type { ComputerViewMode } from "@/src/dict/computer-dict";
import ComputerRestartButton from "./computer-restart-button";
import ComputerView from "./computer-view";
import { twMerge } from "tailwind-merge";
type Props = {
open: boolean;
@@ -56,7 +57,12 @@ export default function ComputerViewerModal({
}}
className="max-w-[95vw]! h-[90vh] p-0 bg-paper flex flex-col overflow-hidden"
>
<Row className="w-full gap-3! flex-nowrap items-center pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
<Row
className={twMerge(
"w-full gap-3! xl:flex-nowrap pl-5 pr-5 xl:pr-14 py-3 border-0 border-b border-solid border-hairline",
"items-start xl:items-center flex-col xl:flex-row",
)}
>
<Stack className="min-w-0 gap-0! items-start">
<H2 className="text-base! leading-6! tracking-normal! font-bold text-ink truncate w-full">
{name}
+33 -33
View File
@@ -84,44 +84,44 @@ export default function FilePreviewModal({
}}
className="max-w-[95vw]! w-[95vw] h-[90vh] p-0 bg-paper flex flex-col overflow-hidden"
>
<Row className="w-full gap-3! flex-nowrap items-center pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
<Stack className="min-w-0 grow gap-0! items-start">
<Stack className="w-full min-w-0 gap-1! items-stretch pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
<Row className="w-full gap-3! flex-wrap sm:flex-nowrap items-center">
<H2
title={name}
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate w-full"
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate min-w-0 w-full sm:w-auto sm:grow"
>
{base_name}
</H2>
<FilePreviewDetails size={size} full_path={full_path} />
</Stack>
{stepping ? (
<FilePreviewStepper
index={index}
count={count}
onPrevious={() => step({ by: -1 })}
onNext={() => step({ by: 1 })}
/>
) : null}
<Link
href={url}
download={base_name}
title={`Download ${base_name}`}
className={ActionClassName}
>
<Download size={16} aria-hidden />
<Span className="hidden sm:inline">Download</Span>
</Link>
<Link
href={url}
target="_blank"
rel="noopener noreferrer"
title="Open in a new tab"
aria-label="Open in a new tab"
className={ActionClassName}
>
<SquareArrowOutUpRight size={16} aria-hidden />
</Link>
</Row>
{stepping ? (
<FilePreviewStepper
index={index}
count={count}
onPrevious={() => step({ by: -1 })}
onNext={() => step({ by: 1 })}
/>
) : null}
<Link
href={url}
download={base_name}
title={`Download ${base_name}`}
className={ActionClassName}
>
<Download size={16} aria-hidden />
<Span className="hidden sm:inline">Download</Span>
</Link>
<Link
href={url}
target="_blank"
rel="noopener noreferrer"
title="Open in a new tab"
aria-label="Open in a new tab"
className={ActionClassName}
>
<SquareArrowOutUpRight size={16} aria-hidden />
</Link>
</Row>
<FilePreviewDetails size={size} full_path={full_path} />
</Stack>
<Stack className="relative grow min-h-0 gap-0! items-stretch w-full">
<FilePreviewBody
key={url}
@@ -11,7 +11,12 @@ import useStorageFolder from "@/src/hooks/use-storage-folder";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import { storagePathName, storageSpecHref, type StorageSpec } from "@/src/utils/storage-volumes";
import {
storageBreadcrumbs,
storagePathName,
storageSpecHref,
type StorageSpec,
} from "@/src/utils/storage-volumes";
import FilesBreadcrumbRow from "./files-breadcrumb-row";
import FilesSearchInput from "./files-search-input";
import StorageEntryRow from "./storage-entry-row";
@@ -38,8 +43,14 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
const [search, set_search] = useState("");
const query = useDebouncedValue({ value: search.trim() });
const { folder, loading, error } = useStorageFolder({ spec, path, search: query });
const name = folder?.breadcrumbs.at(-1)?.name || folder?.label || storagePathName({ volume: spec.volume, path });
const crumbs = useMemo(
() => storageBreadcrumbs({ spec, path }),
[spec.volume, spec.owner_id, path],
);
const name =
crumbs.at(-1)?.name ||
folder?.label ||
storagePathName({ volume: spec.volume, path });
const gallery = useMemo(
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
[folder],
@@ -69,7 +80,7 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
{name}
</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{folderSummary({ folder })}
{folderSummary({ folder, loading })}
</Span>
</Stack>
<Link
@@ -82,10 +93,13 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
</Link>
</Row>
<Stack className="w-full gap-0! items-stretch px-5">
<FilesBreadcrumbRow crumbs={folder?.breadcrumbs || []} onOpenFolder={openFolder} />
<FilesBreadcrumbRow crumbs={crumbs} onOpenFolder={openFolder} />
<FilesSearchInput value={search} onChange={set_search} />
</Stack>
<Stack className="grow min-h-0 w-full mt-2 gap-0! items-stretch overflow-y-auto px-5 pb-4">
<Stack
key={`${path}|${query}`}
className="grow min-h-0 w-full mt-2 gap-0! items-stretch overflow-y-auto px-5 pb-4"
>
{folder?.entries.length ? (
folder.entries.map((entry) => (
<StorageEntryRow
@@ -98,10 +112,10 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
))
) : (
<Span className="py-8 text-[13px] leading-[18px] text-ink-secondary">
{emptyFolderText({ folder, search, loading, error })}
{emptyFolderText({ folder, search: query, loading, error })}
</Span>
)}
</Stack>
</Modal>
);
}
}
@@ -54,6 +54,17 @@ describe("SidePanel", () => {
expect(html.match(/data-no-swipe/g)?.length).toBe(2);
});
test("the rail's drawer and the bot panel open to the same phone width", () => {
const html = renderToString(
<SidePanel side="left" open onClose={onClose} label="Bots">
<p>crew</p>
</SidePanel>,
);
expect(html).toContain("w-[420px]");
expect(html).toContain("max-w-[92vw]");
});
test("a panel that is also part of the page is never inert", () => {
const html = renderToString(
<SidePanel
+17 -3
View File
@@ -1,8 +1,10 @@
"use client";
import type { ReactNode } from "react";
import { useRef, type ReactNode, type RefObject } from "react";
import Stack from "@moduletrace/twui/layout/Stack";
import { twMerge } from "tailwind-merge";
import useSwipeToClose from "@/src/hooks/use-swipe-to-close";
import sidePanelCloseSwipe from "@/src/utils/side-panel-close-swipe";
type Props = {
/** Which edge it slides in from. */
@@ -34,7 +36,10 @@ const Edges = {
* to wait on a timer for an exit to play.
*
* The panel carries `data-no-swipe`, so a phone's sideways swipes never
* start on it or on its backdrop: what is open stays the one on top.
* start on it or on its backdrop: what is open stays the one on top. An
* open panel closes on the one swipe it does answer, a drag back towards the
* edge it slid in from (`useSwipeToClose`), which is the way back out of the
* swipe that opened it.
*/
export default function SidePanel({
side,
@@ -48,6 +53,14 @@ export default function SidePanel({
}: Props) {
const edge = Edges[side];
const hidden = !open && inertWhenClosed;
const panel_ref = useRef<HTMLDivElement>(null);
useSwipeToClose({
panel_ref,
enabled: open,
direction: sidePanelCloseSwipe({ side }),
on_close: onClose,
});
return (
<>
@@ -64,8 +77,9 @@ export default function SidePanel({
aria-hidden={hidden || undefined}
inert={hidden}
data-no-swipe
componentRef={panel_ref as RefObject<HTMLDivElement>}
className={twMerge(
"fixed inset-y-0 z-40 w-[280px] max-w-[85vw] shrink-0 h-full gap-0! items-stretch bg-paper border-0 border-solid border-hairline shadow-popover transition-transform duration-[var(--m-base)] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",
"fixed inset-y-0 z-40 w-[420px] max-w-[92vw] shrink-0 h-full gap-0! items-stretch bg-paper border-0 border-solid border-hairline shadow-popover transition-transform duration-[var(--m-base)] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",
edge.place,
open ? "translate-x-0" : edge.closed,
className,
+11 -3
View File
@@ -6,7 +6,10 @@ import syncConnectorConnection from "@/src/functions/backend/db/connectors/sync-
/**
* Keeps every connection's app list current, reads the tools of the apps
* someone actually gave to a bot or workspace (never all of them: a
* provider lists hundreds), and checks the accounts a sign-in left waiting.
* provider lists hundreds), and keeps accounts in line with the provider:
* the ones a sign-in left waiting, and connected ones an hour later, so an
* account deleted at the provider shows as revoked (and offers Reconnect)
* without waiting for a run to fail.
* Each connection is synced with its own key, so a refused one only affects
* the apps it read.
*/
@@ -37,13 +40,18 @@ export default async function syncConnectors() {
await syncConnector({ connector_id: connector.id });
}
const now = Date.now();
const stale_after = now - 60 * 60 * 1000;
const waiting =
(
await BunSQLite.sql<{ connector_id: number; user_id: number }>({
sql: `SELECT connector_id, user_id FROM connector_requests WHERE status = 'pending' AND expires_at > ?
UNION
SELECT connector_id, user_id FROM connector_accounts WHERE status != 'connected'`,
values: [Date.now()],
SELECT connector_id, user_id FROM connector_accounts WHERE status != 'connected'
UNION
SELECT connector_id, user_id FROM connector_accounts
WHERE status = 'connected' AND (last_checked_at IS NULL OR last_checked_at < ?)`,
values: [now, stale_after],
})
).payload || [];
+40 -16
View File
@@ -545,15 +545,15 @@ export const AppData = {
HarnessAutoMinContext: 32_000,
/**
* The window a run assumes for a model whose catalog never said
* (`run-text-loop.ts`): a custom provider lists ids and nothing else,
* and at 32000 the base prompt alone (system and tool definitions,
* ~25000 tokens here) was already past the 70% working window, so every
* turn trimmed the output the run was reading. 70% of this is the
* widest such a model is ever given, whatever
* `harness_context_budget_tokens` asks for, so it must stay at or above
* that budget.
* (`run-text-loop.ts`): a custom provider lists ids and nothing else.
* It is a guess, and the provider has the last word: a model that is
* smaller refuses a prompt past its real window, and that refusal
* stops the run with the provider's own message, which names the
* limit to set on the model (`Settings > Models`). Never learn a
* smaller window into this: a run that quietly assumed 131072 here
* gave a model a 91,750-token working context and went blind.
*/
HarnessUnknownContextWindow: 131_072,
HarnessUnknownContextWindow: 1_000_000,
/**
* A provider's declared window (`harness_providers.context_length`),
* handed to the models it lists without one of their own: the least and
@@ -694,15 +694,17 @@ export const AppData = {
*/
HarnessReplyDraftsMax: 2,
/**
* The working context: how many tokens (estimated) of system prompt,
* tool definitions and transcript a run sends per turn before old tool
* output is trimmed, whatever the model's window. Every turn resends
* all of it, so a run that only trims at a 1M window pays for its whole
* history on every step. The install may save its own
* (`harness_context_budget_tokens`), read through
* `grabContextBudgetTokens`.
* An optional tighter cap on the working context: how many tokens
* (estimated) of system prompt, tool definitions and transcript a run
* sends per turn before old tool output is trimmed. Unlimited by
* default, so the model's own window decides (minus the reserve it
* needs for its answer, `workingContextTokens`): an install that
* saved `harness_context_budget_tokens` asks for less, for a model
* whose window it pays for by the token. Every turn resends all of
* it, so a run that only trims at a 1M window pays for its whole
* history on every step; that is what this setting is for.
*/
HarnessContextBudgetTokens: 200_000,
HarnessContextBudgetTokens: UnlimitedLimit,
/**
* The least a saved working context may be: below it a run would trim
* the output it is reading right now (one full tool result is ~20000
@@ -733,11 +735,33 @@ export const AppData = {
* pass this many characters; below it they're simply all given.
*/
HarnessDeferToolsMinChars: 6000,
/**
* The bot's own tools (tasks, schedules, hooks, files, plans, crew,
* knowledgebases, graphics) are deferred the same way, but only when
* they are both this large and past `HarnessDeferBuiltinToolsShare` of
* the working context: at 25 tools they were ~33k tokens of every
* turn, which on a 131k-window model left the conversation about 50k
* to work in. Deferring costs a turn to load them, so a model with a
* window that holds them comfortably keeps them inline.
*/
HarnessDeferBuiltinToolsMinChars: 20_000,
/**
* Share of the working context the bot's own tool definitions must
* pass before they are deferred rather than sent every turn.
*/
HarnessDeferBuiltinToolsShare: 0.1,
/**
* How much of a deferred tool's description its line in the list
* shows.
*/
HarnessDeferredToolLineChars: 140,
/**
* Tools of one namespace (one connector's, one MCP server's) past which
* the list names them without their descriptions: one GitHub account's
* 905 tools came to 148,000 characters that way, sent with every turn
* of every run.
*/
HarnessDeferredNamespaceMin: 40,
/**
* Images one tool call may hand back (the rest are dropped), and how
* many of the newest tool images stay in a run's transcript: every
+10 -3
View File
@@ -323,13 +323,20 @@ describe("plan notes", () => {
expect(PlansNote).toContain("nothing of it starts until the user approves it");
});
test("tells the run to work its step only, then report in two or three sentences", () => {
test("tells the run to work its step only, report briefly, then put the card up", () => {
const note = PlanStepNote({ plan });
expect(note).toContain("This reply works step 2 only: Score them");
expect(note).toContain("One step per reply");
expect(note).toContain("This run works step 2 only: Score them");
expect(note).toContain("One step per run");
expect(note).toContain("two or three sentences");
expect(note).toContain("complete_plan_step");
expect(note).toContain("Every finished step ends on a card");
expect(note).toContain('"Continue to step 3"');
expect(note).toContain('"Pause the plan"');
});
test("the last step's card offers to finish the plan", () => {
expect(PlanStepNote({ plan: { ...plan, current_step: 2 } })).toContain('"Finish the plan"');
});
test("lists the steps with where each one stands and what it produced", () => {
+46 -13
View File
@@ -577,20 +577,50 @@ export const repairedAnswerNote = `_Part of this answer was left out: it describ
/**
* Told once, when the prompt no longer fits the working context even after
* everything trimmable was trimmed: what is left is what the user wrote,
* which the app never cuts. A run that keeps reading whole files into the
* conversation only makes the next turn larger, and its answer is paid for
* out of whatever room is left. Told rather than trimming the request: the
* model has to know it may not be seeing all of a pasted brief, so it says
* what it could not reach instead of inventing the rest.
* everything trimmable was trimmed. What is left is the conversation, most
* of it what the user wrote, which the app never cuts, and the app's own
* instructions and tool definitions, which it cannot cut either. A run that
* keeps reading whole files into the conversation only makes the next turn
* larger, and its answer is paid for out of whatever room is left. Told
* rather than trimming the request: the model has to know it may not be
* seeing all of a pasted brief, so it says what it could not reach instead
* of inventing the rest.
*/
export const oversizedRequestNote = ({ budget }: { budget: number }) =>
`This conversation is already larger than the working context this model may be sent (about ${budget.toLocaleString("en-US")} tokens), and none of what is over is yours to trim: the app cuts tool output, never what the user wrote. Every turn resends all of it, so reading more makes the next one worse.
export const oversizedRequestNote = ({ budget, base, conversation }: { budget: number; base: number; conversation: number }) =>
`This conversation is already larger than the working context this model may be sent (about ${budget.toLocaleString("en-US")} tokens), and everything the app is allowed to cut has been cut. Of what is left, about ${base.toLocaleString("en-US")} tokens are the app's own instructions and tool definitions, and about ${conversation.toLocaleString("en-US")} are the conversation itself. Every turn resends all of it, so reading more makes the next one worse.
From here: stop pulling whole files, whole pages or entire command outputs into the conversation. Work from what you already have, read only the piece you need (a line range, a filter, grep), write what must be kept to a file rather than into a message, and answer on this turn.
If what you need sits in a part of the request you cannot reach in one piece, say plainly what you could and could not read, and ask the user to attach it as a file, put it in a knowledgebase, or point you at a path. A guess presented as a reading of it is worse than saying it was too long.`;
/**
* The failure a run stops on when its instructions and tool definitions
* alone are past the working context (`fitTranscriptToContext`'s
* `over_budget: "static"`). Nothing can be trimmed into that room, so a
* run that went on trimmed every tool result of every turn and answered
* from nothing: one read a 14-character shell answer as "Trimmed: 14
* characters" for thirty steps. The user is told the arithmetic and where
* to fix it, instead of watching a bot go blind.
*/
export const staticPromptOverBudgetNote = ({
working,
window,
assumed,
base,
system,
tools,
}: {
working: number;
window: number;
assumed: boolean;
base: number;
system: number;
tools: number;
}) =>
`This run stopped before its first answer: the model's working context is about ${working.toLocaleString("en-US")} tokens${assumed ? " (the model declares no context window, so the app assumed one)" : ` (a ${window.toLocaleString("en-US")} token window)`}, and this run's own instructions and tool definitions already take about ${base.toLocaleString("en-US")} of them (system prompt about ${system.toLocaleString("en-US")}, tools about ${tools.toLocaleString("en-US")}), which leaves no room for the conversation. Nothing was trimmed, because trimming could not have helped.
If the model's real window is bigger than that, set it on its provider in Settings > Models. If it is not, choose a model with a larger window for this bot, or give it fewer extensions (MCP servers, browsers and connectors add tool definitions to every turn).`;
/**
* Told when the app has had to trim earlier tool output from the transcript
* (`fitTranscriptToContext`'s `trimmed` count, every
@@ -1004,6 +1034,8 @@ Plan #${plan.id} "${plan.title}" is on its card in this conversation, waiting fo
export const PlanStepNote = ({ plan }: { plan: PlanPrompt }) => {
const index = plan.current_step ?? 0;
const step = plan.steps[index];
const next = index + 2;
const next_label = next > plan.steps.length ? "Finish the plan" : `Continue to step ${next}`;
return `# Your plan, step ${index + 1} of ${plan.steps.length}
@@ -1011,13 +1043,14 @@ Plan #${plan.id} "${plan.title}".${plan.goal ? ` Goal: ${plan.goal}` : ""}
${planStepLines({ plan })}
This reply works step ${index + 1} only: ${step?.text || ""}
This run works step ${index + 1} only: ${step?.text || ""}
- One step per reply. The app wakes you for the next one when this finishes, so don't start it now and don't do two.
- One step per run. The next step starts when the user answers this report's card, so don't start it now and don't do two.
- Finish it with complete_plan_step: one or two lines on what it produced (the number, the path, the link). Then write your report to the user.
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan and the step after this one, so repeating it only makes the reply longer than it needs to be.
- If the step can't be done from here (it needs the user, a login or a decision they alone can make), don't finish it: ask one question with ask_user and say the plan is holding at this step.
- If what you found means the rest of the plan is wrong, change it with update_plan, in the same reply, and say what changed.`;
- **Every finished step ends on a card.** Call ask_user in the same turn as the report (beside the send_reply that sends it): one question, "Continue with the plan?", whose first option is "${next_label}", whose second is "Pause the plan", after those any choice this step really needs. The user answers in one click and the app starts the next step, so nothing waits on them typing "move on": a report without the card is sent back.
- If the step can't be done from here (it needs the user, a login or a decision they alone can make), don't finish it: ask that question on the card, and say the plan is holding at this step.
- If what you found means the rest of the plan is wrong, change it with update_plan, in the same run, and say what changed.`;
};
/**
@@ -1033,7 +1066,7 @@ Plan #${plan.id} "${plan.title}" is approved and in progress${index == null ? ""
${planStepLines({ plan })}
- If the user's message is about this plan's work, work that step and only that step, then complete_plan_step with what it produced, then a short report.
- Its steps are worked one per reply, each ending on a card the user answers to start the next one. This reply isn't working a step, so don't work one here: if they ask you to carry on, say the next step is step ${(index ?? 0) + 1} and they start it from the plan's card (Continue on the plan, under the report above), then answer whatever else they asked.
- If they asked something else, answer that and leave the plan where it is: it carries on from there.
- The steps are theirs to change on the card. If the work moved on from one of them, update_plan and say what changed.`;
};
@@ -70,8 +70,9 @@ export async function grabRunMaxPromptTokens() {
/**
* The working context a run keeps per turn, in estimated tokens: the
* install's own (`harness_context_budget_tokens`), else
* `AppData.HarnessContextBudgetTokens`. Unlimited keeps the model's whole
* window.
* `AppData.HarnessContextBudgetTokens`. Unlimited (the default) keeps the
* model's own window, less the reserve its answer needs
* (`workingContextTokens`), so this is only a way to hold runs below that.
*/
export async function grabContextBudgetTokens() {
return readRunLimit({
@@ -1,66 +0,0 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
import shouldContinuePlan from "@/src/utils/should-continue-plan";
import enqueuePlanStep from "./enqueue-plan-step";
import grabBotPlan from "./grab-bot-plan";
type Params = {
plan_id: number | string;
session_id: number | string;
/**
* The reply asked the user something (`ask_user`), so it waits on them
* rather than carrying on.
*/
needs_you?: boolean;
/**
* The tools the run called: one that starts work (a task, a hand-over,
* a request to another bot) has a report still to come, so the plan
* waits for it instead of talking over it.
*/
tool_names?: string[];
/**
* The reply queued a run (`send_reply` with work), whose report is still
* to come: the plan waits for it rather than working over it.
*/
started_work?: boolean;
};
/**
* Carries a plan on after a run finished a step: the bot reports the step it
* finished, and this wakes it for the next one, so the work runs through the
* plan step by step without the user nudging it each time.
*
* Nothing is queued when the run is waiting on the user, when it started
* work whose report is still to come, when the plan was paused or cancelled
* meanwhile, or when the conversation already has a reply waiting (a message
* the user sent mid-step, whose own run picks the plan up from there).
*/
export default async function continueBotPlan({ plan_id, session_id, needs_you, tool_names, started_work }: Params) {
const row = await grabBotPlan({ plan_id });
const steps = parseBotPlanSteps({ text: row.steps });
const waiting = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bots_queue
WHERE session_id = ? AND kind = 'reply' AND status IN ('pending', 'processing')
LIMIT 1`,
values: [Number(session_id)],
})
).payload?.[0];
const carry_on = shouldContinuePlan({
status: row.status || "",
needs_you,
tool_names,
started_work,
plan_session_id: row.session_id,
session_id,
has_pending_step: currentPlanStepIndex({ steps }) != null,
has_waiting_reply: Boolean(waiting),
});
if (!carry_on) return null;
return await enqueuePlanStep({ plan_id: row.id });
}
@@ -1,3 +1,4 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { BotReplyJobTitle } from "@/src/dict/bot-queue-dict";
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
@@ -27,6 +28,17 @@ export default async function enqueuePlanStep({ plan_id }: Params) {
if (currentPlanStepIndex({ steps }) == null) return null;
/**
* A step is already queued or running for this plan: Continue twice, or
* Continue while the step works, must not start a second run on it.
*/
const open = await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bots_queue WHERE session_id = ? AND status IN ('pending', 'processing') AND json_extract(params, '$.plan_id') = ? LIMIT 1`,
values: [Number(row.session_id), Number(row.id)],
});
if ((open.payload || []).length > 0) return null;
const user_id = Number(row.user_id);
const job_id = await enqueueBotJob({
@@ -18,21 +18,26 @@ type Params = {
* changes nothing and a finished plan never comes back.
*
* Returns the row as it now stands and whether it just started, which is
* when the bot is woken for its first step.
* when the bot is woken for the step it stands on.
*/
export default async function setBotPlanStatus({ plan_id, user_id, status }: Params) {
const row = await grabBotPlan({ plan_id, user_id });
const current = row.status as BotPlanState;
if (current == status) return { row, started: false };
const steps = parseBotPlanSteps({ text: row.steps });
const caught_up = currentPlanStepIndex({ steps }) == null;
/**
* Already where it's being sent: nothing changes, but "active" is also
* how the user starts a step that isn't running (Continue on the card),
* so it wakes the bot when a step is still left.
*/
if (current == status) return { row, started: status == "active" && !caught_up };
if (current == "done" || current == "cancelled") {
throw new AppError(`This plan is ${current}: it can't be picked up again.`);
}
const steps = parseBotPlanSteps({ text: row.steps });
const caught_up = currentPlanStepIndex({ steps }) == null;
if (status == "active") {
if (current != "planned" && current != "paused") {
throw new AppError(`This plan is ${current}: it isn't paused.`);
@@ -11,6 +11,11 @@ type Params = {
* Asked in a Plan mode reply: the answers are run in Plan mode too.
*/
plan_mode?: boolean;
/**
* The plan whose step ended on these questions: its first option
* continues the plan, anything else pauses it.
*/
plan_id?: number | string | null;
title: string;
questions: BotQuestionItem[];
};
@@ -19,7 +24,7 @@ type Params = {
* Stores questions a bot asks the user, pending until they answer or skip
* them in its card. Returns its id.
*/
export default async function createBotQuestion({ user_id, bot_id, session_id, workspace_id, plan_mode, title, questions }: Params) {
export default async function createBotQuestion({ user_id, bot_id, session_id, workspace_id, plan_mode, plan_id, title, questions }: Params) {
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_QUESTIONS, (typeof BunSQLiteTables)[number]>({
table: "bot_questions",
data: [
@@ -32,6 +37,7 @@ export default async function createBotQuestion({ user_id, bot_id, session_id, w
session_id: Number(session_id),
workspace_id: workspace_id ? Number(workspace_id) : undefined,
plan_mode: plan_mode ? 1 : 0,
plan_id: plan_id ? Number(plan_id) : undefined,
},
],
});
@@ -11,9 +11,17 @@ import type { BotQuestionView } from "@/src/types";
* The side-effect helpers are mocked; the branch under test is the one that
* carries the mode from the card onto the message and the job.
*/
let question: { bot_id: number; session_id: number; workspace_id: number | null; plan_mode: number };
let question: {
bot_id: number;
session_id: number;
workspace_id: number | null;
plan_mode: number;
plan_id?: number | null;
};
let inserted: Array<Record<string, unknown>> = [];
let enqueued: Array<Record<string, unknown>> = [];
let step_jobs: number[] = [];
let paused: Array<Record<string, unknown>> = [];
let pushed: number[] = [];
mock.module("@/src/functions/backend/db/bot-questions/grab-bot-question", () => ({
@@ -47,6 +55,21 @@ mock.module("@/src/bots-queue/push-bot-notice", () => ({
pushed.push(message.id);
},
}));
mock.module("@/src/functions/backend/db/bot-plans/enqueue-plan-step", () => ({
default: async ({ plan_id }: { plan_id: number }) => {
step_jobs.push(plan_id);
return 900;
},
}));
mock.module("@/src/functions/backend/db/bot-plans/set-bot-plan-status", () => ({
default: async (params: Record<string, unknown>) => {
paused.push(params);
return { row: { id: params.plan_id }, started: false };
},
}));
mock.module("@/src/bots-queue/push-bot-plan", () => ({
default: async () => {},
}));
mock.module("@/src/bots-queue/wake-bots-queue", () => ({
default: () => {},
}));
@@ -68,9 +91,11 @@ const view = {
} as unknown as BotQuestionView;
beforeEach(() => {
question = { bot_id: 1, session_id: 135, workspace_id: null, plan_mode: 0 };
question = { bot_id: 1, session_id: 135, workspace_id: null, plan_mode: 0, plan_id: null };
inserted = [];
enqueued = [];
step_jobs = [];
paused = [];
pushed = [];
});
@@ -93,4 +118,40 @@ describe("postBotQuestionAnswers", () => {
expect(inserted[0]!.plan_mode).toBe(false);
expect(enqueued[0]!.params).toBeUndefined();
});
test("a plan's card answered Continue starts the next step, with no other reply", async () => {
question.plan_id = 3;
await postBotQuestionAnswers({ view, user_id: 1 });
expect(step_jobs).toEqual([3]);
expect(enqueued).toHaveLength(0);
expect(paused).toHaveLength(0);
});
test("any other answer to a plan's card pauses the plan and still answers", async () => {
question.plan_id = 3;
await postBotQuestionAnswers({
view: { ...view, answers: [{ choices: [1], other: "" }] } as unknown as BotQuestionView,
user_id: 1,
});
expect(paused).toHaveLength(1);
expect(paused[0]!.status).toBe("paused");
expect(step_jobs).toEqual([]);
expect(enqueued).toHaveLength(1);
});
test("a skipped plan card holds the plan rather than moving it on", async () => {
question.plan_id = 3;
await postBotQuestionAnswers({
view: { ...view, status: "skipped" } as unknown as BotQuestionView,
user_id: 1,
});
expect(step_jobs).toEqual([]);
expect(paused).toHaveLength(1);
});
});
@@ -1,13 +1,18 @@
import type { BUN_SQLITE_COBBLE_BOT_QUESTIONS, BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
import { logError } from "@/src/functions/backend/logger";
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
import type { BotQuestionView } from "@/src/types";
import botQuestionAnswersText from "@/src/utils/bot-question-answers-text";
import planContinueAnswer from "@/src/utils/plan-continue-answer";
import conversationLock from "../bot-sessions/conversation-lock";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
import insertUserMessage from "../bots/insert-user-message";
import enqueueBotReply from "../bots-queue/enqueue-bot-reply";
import setBotPlanStatus from "../bot-plans/set-bot-plan-status";
import enqueuePlanStep from "../bot-plans/enqueue-plan-step";
import grabBotQuestion from "./grab-bot-question";
type Params = {
@@ -21,6 +26,11 @@ type Params = {
* which wakes it. The route posts this, not the card's page: the same
* conversation can be on screen in several places, and an answer belongs
* where the question was asked, never to whichever bot's page was open.
*
* A card a plan's step ended on is the plan's own next move: Continue
* starts its next step, and anything else pauses it, so the plan never
* waits on the user to say "move on" in the chat.
*
* Best effort: a failure is logged and never undoes the answer.
*/
export default async function postBotQuestionAnswers({ view, user_id }: Params) {
@@ -29,34 +39,74 @@ export default async function postBotQuestionAnswers({ view, user_id }: Params)
if (!row.bot_id) return;
const session = await pickSession({ row, user_id });
const workspace_id = row.workspace_id || null;
const bot_id = Number(row.bot_id);
/**
* Asked in Plan mode, answered and skipped in it: a question is
* about what to plan, so its answer must not unlock the write
* tools (the only ways out are Tab and approving a plan).
*/
const plan_mode = Boolean(row.plan_mode);
await conversationLock.run({
key: `${user_id}:${bot_id}:${workspace_id || 0}`,
task: async () => {
const session = await pickSession({ row, user_id });
const message = await insertUserMessage({
bot_id: Number(row.bot_id),
session_id: Number(session.id),
workspace_id: session.workspace_id || null,
text: botQuestionAnswersText({ view }),
plan_mode,
/**
* Asked in Plan mode, answered and skipped in it: a question
* is about what to plan, so its answer must not unlock the
* write tools (the only ways out are Tab and approving a
* plan).
*/
const plan_mode = Boolean(row.plan_mode);
const message = await insertUserMessage({
bot_id,
session_id: Number(session.id),
workspace_id,
text: botQuestionAnswersText({ view }),
plan_mode,
});
await pushBotNotice({ bot_id, message });
const plan_id = Number(row.plan_id) || 0;
const continue_plan = plan_id > 0 && planContinueAnswer({ view });
if (plan_id > 0 && !continue_plan) {
await setBotPlanStatus({ plan_id, user_id, status: "paused" })
.then(async () => {
await pushBotPlan({
plan_id,
session_id: Number(session.id),
bot_id,
});
})
.catch(() => null);
}
if (continue_plan) {
const step_job = await enqueuePlanStep({ plan_id }).catch(() => null);
/**
* The plan runs its step as its own run, which reads the
* answer above in the conversation. Only when that can't
* be queued does the answer get an ordinary reply, so it
* is never left unanswered.
*/
if (step_job) {
wakeBotsQueue();
return;
}
}
await enqueueBotReply({
user_id,
bot_id,
session_id: Number(session.id),
message_id: Number(message.id),
...(plan_mode ? { params: { plan_mode: true } } : {}),
});
wakeBotsQueue();
},
});
await pushBotNotice({ bot_id: row.bot_id, message });
await enqueueBotReply({
user_id,
bot_id: row.bot_id,
session_id: Number(session.id),
message_id: Number(message.id),
...(plan_mode ? { params: { plan_mode: true } } : {}),
});
wakeBotsQueue();
} catch (error: unknown) {
await logError({
title: `A bot's question answers didn't reach it`,
@@ -163,5 +163,16 @@ export default async function carryOverBotSession({
values: [next.id!, active.id],
});
/**
* The plan comes with the conversation. A step and its card are read
* from the session the plan is filed under, so one left on the closed
* session leaves the thread the user is in with no plan, no bar and no
* card to answer, and the bot forgets the work it was in the middle of.
*/
await BunSQLite.sql({
sql: `UPDATE bot_plans SET session_id = ?, updated_at = ? WHERE session_id = ? AND status IN ('planned', 'active', 'paused')`,
values: [next.id!, now, active.id],
});
return message;
}
@@ -0,0 +1,13 @@
import createKeyLock from "@/src/utils/create-key-lock";
/**
* One conversation's writes go one at a time. Reading the active session,
* storing the message and queueing its reply belong together: two sends in
* flight together (a double submit, a retry firing beside the first) both
* read the same full session, one rolls the conversation over, and the
* other writes into the session that was just closed, where the user never
* sees it.
*/
const conversationLock = createKeyLock();
export default conversationLock;
@@ -49,7 +49,16 @@ export default async function rollOverBotSession({
}).catch(() => null);
});
if (!message) return active;
if (!message) {
/**
* The conversation may have moved on under this call (a send that
* rolled it over first): the message goes into the session that is
* current now, never the closed one it was about to be written in.
*/
const current = await grabActiveBotSession({ user_id, bot_id, workspace_id });
return current?.id ? current : active;
}
await pushBotNotice({ bot_id, message, quiet_push: true });
@@ -1,4 +1,4 @@
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
import type { ComputerWithStatus } from "@/src/types";
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
@@ -30,10 +30,11 @@ export default async function grabBotComputers({
bot_id,
workspace_id,
include_workspace_computers = true,
}: Params): Promise<BUN_SQLITE_COBBLE_COMPUTERS[]> {
}: Params): Promise<ComputerWithStatus[]> {
if (workspace_id) {
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_COMPUTERS>({
sql: `SELECT c.* FROM computers c
const res = await BunSQLite.sql<ComputerWithStatus>({
sql: `SELECT c.*, co.status AS status FROM computers c
LEFT JOIN containers co ON co.id = c.container_id
JOIN workspace_computers wc ON wc.computer_id = c.id AND wc.workspace_id = ?
JOIN workspaces w ON w.id = wc.workspace_id AND w.archived = 0
WHERE (
@@ -55,8 +56,9 @@ export default async function grabBotComputers({
)`
: "";
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_COMPUTERS>({
sql: `SELECT c.* FROM computers c
const res = await BunSQLite.sql<ComputerWithStatus>({
sql: `SELECT c.*, co.status AS status FROM computers c
LEFT JOIN containers co ON co.id = c.container_id
WHERE (
(SELECT kind FROM bots WHERE id = ?) = 'coordinator'
OR c.id IN (SELECT computer_id FROM bot_computers WHERE bot_id = ?)
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS, BUN_SQLITE_COBBLE_CONNECTORS } from "@/db/types/db";
import type { BotConnectorEntry, ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
import botConnectorsSql from "@/src/utils/bot-connectors-sql";
import connectorAccountReachSql from "@/src/utils/connector-account-reach-sql";
import attachConnectorAccountScopes from "./attach-connector-account-scopes";
import parseConnectorAccountRow from "./parse-connector-account-row";
import parseConnectorRow from "./parse-connector-row";
@@ -18,10 +19,11 @@ type ConnectorRow = BUN_SQLITE_COBBLE_CONNECTORS & { connection_name?: string };
/**
* The connectors a conversation's bot can use for this user, with the
* accounts that reach there: this user's own (whatever their status, so a
* pending sign-in still shows), and any connected account given to this
* bot, this workspace or every bot, named with its owner. Each app says
* where it comes from: the install, this workspace, this user's own
* attachment, or an account given here.
* pending sign-in still shows), every connected account of a connector given
* to this workspace, and any connected account given to this bot, this
* workspace or every bot, named with its owner. Each app says where it comes
* from: the install, this workspace, this user's own attachment, or an
* account given here.
*/
export default async function grabBotConnectors({
user_id,
@@ -44,6 +46,7 @@ export default async function grabBotConnectors({
const connection_names = new Map(found.map((row) => [Number(row.id), row.connection_name || ""]));
const ids = connectors.map((connector) => connector.id);
const placeholders = ids.map(() => "?").join(", ");
const workspace_reach = connectorAccountReachSql({ workspace_id });
const [account_res, workspace_res, bot_res] = await Promise.all([
BunSQLite.sql<AccountRow>({
@@ -57,13 +60,18 @@ export default async function grabBotConnectors({
a.all_bots = 1
OR EXISTS (SELECT 1 FROM connector_account_bots ab WHERE ab.account_id = a.id AND ab.bot_id = ?)
${workspace_id ? `OR EXISTS (SELECT 1 FROM connector_account_workspaces aw WHERE aw.account_id = a.id AND aw.workspace_id = ?)` : ""}
${workspace_reach.sql}
)
)
)
ORDER BY a.id ASC`,
values: workspace_id
? [...ids, Number(user_id), Number(bot_id), Number(workspace_id)]
: [...ids, Number(user_id), Number(bot_id)],
values: [
...ids,
Number(user_id),
Number(bot_id),
...(workspace_id ? [Number(workspace_id)] : []),
...workspace_reach.values,
],
}),
BunSQLite.sql<{ connector_id: number }>({
sql: `SELECT connector_id FROM workspace_connectors WHERE connector_id IN (${placeholders})`,
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS, BUN_SQLITE_COBBLE_CONNECTORS } from "@/db/types/db";
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
import botConnectorsSql from "@/src/utils/bot-connectors-sql";
import connectorAccountReachSql from "@/src/utils/connector-account-reach-sql";
import attachConnectorAccountScopes from "./attach-connector-account-scopes";
import parseConnectorAccountRow from "./parse-connector-account-row";
import parseConnectorRow from "./parse-connector-row";
@@ -19,9 +20,10 @@ type Params = {
export type RunConnector = {
connector: ConnectorRecord;
/**
* The accounts the run may use for it: the user's own, and every one
* given to this bot, this workspace or every bot. Empty means nothing
* to call with: the card asks them to connect one.
* The accounts the run may use for it: the user's own, every connected
* account of a connector given to this workspace, and every one given to
* this bot, this workspace or every bot. Empty means nothing to call
* with: the card asks them to connect one.
*/
accounts: ConnectorAccountRecord[];
};
@@ -31,9 +33,9 @@ type AccountRow = BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & { owner_name?: string }
/**
* The connectors one run reaches (`botConnectorsSql`) with the accounts it
* may act through: its own user's, never another person's unless that
* account was given to this bot, this workspace or every bot. A connector
* reaches a run without any account; it only becomes callable once there is
* one.
* account was given to this bot, this workspace or every bot, or its app was
* given to this workspace. A connector reaches a run without any account; it
* only becomes callable once there is one.
*/
export default async function grabRunConnectors({ user_id, bot_id, workspace_id }: Params): Promise<RunConnector[]> {
const found =
@@ -47,6 +49,7 @@ export default async function grabRunConnectors({ user_id, bot_id, workspace_id
const connectors = found.map((row) => parseConnectorRow({ row }));
const ids = connectors.map((connector) => connector.id);
const workspace_reach = connectorAccountReachSql({ workspace_id });
const rows =
(
await BunSQLite.sql<AccountRow>({
@@ -60,9 +63,10 @@ export default async function grabRunConnectors({ user_id, bot_id, workspace_id
OR a.all_bots = 1
OR EXISTS (SELECT 1 FROM connector_account_bots b WHERE b.account_id = a.id AND b.bot_id = ?)
OR EXISTS (SELECT 1 FROM connector_account_workspaces w WHERE w.account_id = a.id AND w.workspace_id = ?)
${workspace_reach.sql}
)
ORDER BY a.id ASC`,
values: [...ids, Number(user_id), Number(bot_id), Number(workspace_id || 0)],
values: [...ids, Number(user_id), Number(bot_id), Number(workspace_id || 0), ...workspace_reach.values],
})
).payload || [];
@@ -0,0 +1,85 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import insertConnectorAccountSql from "@/src/functions/backend/db/connectors/insert-connector-account-sql";
function scratch() {
const db = new Database(":memory:");
db.run(`CREATE TABLE connector_accounts (
id INTEGER PRIMARY KEY,
created_at INTEGER,
updated_at INTEGER,
connector_id INTEGER,
user_id INTEGER,
label TEXT,
slug TEXT,
provider_account_id TEXT,
status TEXT,
is_default INTEGER,
connected_at INTEGER,
last_checked_at INTEGER,
last_error TEXT
)`);
return db;
}
function insert(db: Database, { label, slug }: { label: string; slug: string }) {
const statement = insertConnectorAccountSql({
now: 1000,
connector_id: 1,
user_id: 1,
label,
slug,
provider_account_id: "ca_one",
status: "connected",
});
db.query(statement.sql).run(...statement.values);
}
describe("insertConnectorAccountSql", () => {
test("inserts the sign-in once", () => {
const db = scratch();
insert(db, { label: "Ben", slug: "ben" });
const rows = db.query(`SELECT label, slug, status, is_default, last_error FROM connector_accounts`).all();
expect(rows).toEqual([{ label: "Ben", slug: "ben", status: "connected", is_default: 0, last_error: "" }]);
});
test("keeps the row a second sync already wrote for the same account", () => {
const db = scratch();
insert(db, { label: "Ben", slug: "ben" });
insert(db, { label: "Ben again", slug: "ben-2" });
const rows = db.query(`SELECT label, slug FROM connector_accounts`).all();
expect(rows).toEqual([{ label: "Ben", slug: "ben" }]);
});
test("adds a different account of the same app", () => {
const db = scratch();
insert(db, { label: "Ben", slug: "ben" });
const statement = insertConnectorAccountSql({
now: 1000,
connector_id: 1,
user_id: 1,
label: "Ben work",
slug: "ben-work",
provider_account_id: "ca_two",
status: "connected",
});
db.query(statement.sql).run(...statement.values);
expect(db.query(`SELECT provider_account_id FROM connector_accounts ORDER BY id`).all()).toEqual([
{ provider_account_id: "ca_one" },
{ provider_account_id: "ca_two" },
]);
});
});
@@ -0,0 +1,50 @@
import type { ProviderAccountStatus } from "@/src/harness/connectors/connector-provider";
type Params = {
now: number;
connector_id: number;
user_id: number;
label: string;
slug: string;
provider_account_id: string;
status: ProviderAccountStatus;
};
/**
* One row per provider account, even when two syncs (a poll beside the cron)
* reach it at once: the statement itself refuses a second row, so neither can
* insert the same sign-in twice.
*/
export default function insertConnectorAccountSql({
now,
connector_id,
user_id,
label,
slug,
provider_account_id,
status,
}: Params) {
return {
sql: `INSERT INTO connector_accounts
(created_at, updated_at, connector_id, user_id, label, slug, provider_account_id, status, is_default, connected_at, last_checked_at, last_error)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ''
WHERE NOT EXISTS (
SELECT 1 FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND provider_account_id = ?
)`,
values: [
now,
now,
connector_id,
user_id,
label,
slug,
provider_account_id,
status,
status == "connected" ? now : null,
now,
connector_id,
user_id,
provider_account_id,
],
};
}
@@ -2,21 +2,18 @@ import { describe, expect, test } from "bun:test";
import shouldAdoptConnectorAccount from "@/src/functions/backend/db/connectors/should-adopt-connector-account";
describe("shouldAdoptConnectorAccount", () => {
test("adopts a connected account whether or not a request claims it", () => {
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false })).toBe(true);
test("adopts a connected account its own sign-in made", () => {
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: true, claimed: false })).toBe(true);
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: true })).toBe(true);
});
test("adopts a pending account a request here started", () => {
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true })).toBe(true);
test("leaves a connected account nothing here asked for at the provider", () => {
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false })).toBe(false);
});
test("adopts a pending account that reconnects a row", () => {
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: false })).toBe(true);
});
test("skips a pending account nothing here started", () => {
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: false })).toBe(false);
test("leaves an unfinished sign-in alone until it connects", () => {
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: false })).toBe(false);
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true })).toBe(false);
expect(shouldAdoptConnectorAccount({ status: "expired", reconnect: false, claimed: false })).toBe(false);
});
});
@@ -9,12 +9,14 @@ type Params = {
};
/**
* Whether a provider account becomes a local row. A connected one always does.
* A pending one does only when a request here started it or reconnects it: an
* abandoned sign-in at the provider must not arrive as a second account, which
* is how a reconnect once left a never connected duplicate beside the account
* it replaced.
* Whether a provider account becomes a local row: only one a request here
* started or is reconnecting, and only once it is connected. One card per
* sign-in, so an account the provider already held (a leftover from an earlier
* attempt, or a sign-in made at the provider itself) never arrives as a second
* card of the same mailbox. A sign-in that hasn't finished has no card either:
* a link that connects under another id would leave a dead row beside the real
* one.
*/
export default function shouldAdoptConnectorAccount({ status, reconnect, claimed }: Params) {
return reconnect || status == "connected" || claimed;
return status == "connected" && (reconnect || claimed);
}
@@ -0,0 +1,21 @@
/**
* The row an id-less reconnect replaces. The production fault this pins:
* 0.27.6 fell back to the one dead row with the requested name, so a new
* mailbox that arrived while a dead row existed took that row's label and
* namespace. Only a pending request that names a row may hand it over.
*/
import { expect, test } from "bun:test";
import { pendingReconnectRow } from "./sync-connector-accounts";
test("an id-less reconnect names the row its request does", () => {
expect(pendingReconnectRow([{ account_id: 5, provider_account_id: "" }])).toBe(5);
});
test("a reconnect the provider gave an id for is not an id-less one", () => {
expect(pendingReconnectRow([{ account_id: 5, provider_account_id: "ca_new" }])).toBeNull();
});
test("a plain sign-in (no row) and no request name nothing", () => {
expect(pendingReconnectRow([])).toBeNull();
expect(pendingReconnectRow([{ account_id: 0, provider_account_id: "" }])).toBeNull();
});
@@ -7,6 +7,7 @@ import connectorSlug from "@/src/utils/connector-slug";
import grabConnector from "./grab-connector";
import parseConnectorAccountRow from "./parse-connector-account-row";
import shouldAdoptConnectorAccount from "./should-adopt-connector-account";
import insertConnectorAccountSql from "./insert-connector-account-sql";
type Params = {
user_id: number | string;
@@ -20,10 +21,15 @@ type Params = {
/**
* Reads the user's accounts for a connector at its provider and brings the
* local rows in line: new sign-ins are added (the first connected one is the
* default), ones the provider reports expired say so, and ones it no longer
* lists are marked revoked without losing their label. Pending connect
* requests are closed as soon as an account is connected.
* local rows in line: the account a sign-in here made is added (the first
* connected one is the default), ones the provider reports expired say so, and
* ones it no longer lists are marked revoked without losing their label.
* Pending connect requests are closed as soon as the account they made is
* connected.
*
* One card per sign-in: an account no request here made is left at the
* provider, so a leftover from an earlier attempt there cannot arrive as a
* second card of the same mailbox beside the one its own sign-in made.
*/
export default async function syncConnectorAccounts({ user_id, connector_id, label }: Params) {
const connector = await grabConnector({ connector_id });
@@ -39,36 +45,54 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
const requests = (
await BunSQLite.sql<{ account_id: number; provider_account_id: string }>({
sql: `SELECT account_id, provider_account_id FROM connector_requests WHERE connector_id = ? AND user_id = ? AND status = 'pending' AND provider_account_id != ''`,
sql: `SELECT account_id, provider_account_id FROM connector_requests WHERE connector_id = ? AND user_id = ? AND status = 'pending'`,
values: [connector.id, Number(user_id)],
})
).payload || [];
const reconnect_for = new Map(
requests.filter((row) => Number(row.account_id) != 0).map((row) => [String(row.provider_account_id), Number(row.account_id)]),
requests
.filter((row) => Number(row.account_id) != 0 && row.provider_account_id)
// A row disconnected since is no target: that sign-in arrives as a new one.
.filter((request) => local.some((account) => Number(account.id) == Number(request.account_id)))
.map((row) => [String(row.provider_account_id), Number(row.account_id)]),
);
let reconnect_row = pendingReconnectRow(requests);
// A row disconnected since is no target: that sign-in arrives as a new one.
if (reconnect_row && !local.some((row) => Number(row.id) == reconnect_row)) reconnect_row = null;
/**
* A sign-in only becomes a row once it is connected, or while the request
* that started it is still open. A pending account nothing here asked for
* is an abandoned or replaced sign-in at the provider (Composio keeps one
* A sign-in only becomes a row once it is connected, and only the account
* its own request names. A pending account nothing here asked for is an
* abandoned or replaced sign-in at the provider (Composio keeps one
* `INITIALIZING` per abandoned link), and adopting it would put a second,
* never connected account beside the one a reconnect replaced.
*/
const claimed = new Set(requests.map((row) => String(row.provider_account_id)));
const claimed = new Set(requests.map((row) => String(row.provider_account_id || "")).filter(Boolean));
/**
* A new sign-in the provider named no account for: the first connected
* account it didn't already have is that sign-in, once.
*/
let unclaimed_sign_in = requests.some((row) => Number(row.account_id) == 0 && !row.provider_account_id);
const seen = new Set(accounts.map((account) => account.provider_account_id));
const now = Date.now();
const hasConnected = local.some((row) => row.status == "connected");
for (const row of local) {
if (seen.has(String(row.provider_account_id || ""))) continue;
/**
* A listing that names no account is the provider unable to answer, not
* every account deleted there: revoking them all would put Reconnect on
* cards that are fine.
*/
if (accounts.length) {
for (const row of local) {
if (seen.has(String(row.provider_account_id || ""))) continue;
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`,
values: [now, now, Number(row.id)],
});
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`,
values: [now, now, Number(row.id)],
});
}
}
let firstConnected: number | null = hasConnected ? null : 0;
let firstConnected: number | null = local.some((row) => row.status == "connected") ? null : 0;
for (const account of accounts) {
const provider_account_id = String(account.provider_account_id);
@@ -77,8 +101,11 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
if (
!shouldAdoptConnectorAccount({
status: account.status,
reconnect: Boolean(reconnect_id),
claimed: claimed.has(provider_account_id),
reconnect: Boolean(reconnect_id) || Boolean(reconnect_row),
claimed:
claimed.has(provider_account_id) ||
(unclaimed_sign_in &&
!local.some((row) => String(row.provider_account_id || "") == provider_account_id)),
})
)
continue;
@@ -89,9 +116,11 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
account,
fallback_label: label,
reconnect_id,
reconnect_row,
});
if (account.status != "connected") continue;
reconnect_row = null;
unclaimed_sign_in = false;
if (firstConnected === 0) {
const created = (
@@ -125,6 +154,12 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
return grabUserAccounts({ connector_id: connector.id, user_id: Number(user_id) });
}
export function pendingReconnectRow(requests: Array<{ account_id: number; provider_account_id: string }>) {
const named = requests.find((row) => Number(row.account_id) != 0 && !row.provider_account_id);
return Number(named?.account_id || 0) || null;
}
type UpsertParams = {
connector_id: number;
user_id: number;
@@ -135,9 +170,15 @@ type UpsertParams = {
* sign-in takes its place instead of arriving as a second account.
*/
reconnect_id?: number;
/**
* That row when the provider gave the sign-in no id at all: the request
* names it, so it's never guessed from a name or a sole dead row, which
* would hand a new mailbox the dead one's label and namespace.
*/
reconnect_row?: number | null;
};
async function upsertAccount({ connector_id, user_id, account, fallback_label, reconnect_id }: UpsertParams) {
async function upsertAccount({ connector_id, user_id, account, fallback_label, reconnect_id, reconnect_row }: UpsertParams) {
const now = Date.now();
if (reconnect_id) {
@@ -187,32 +228,25 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label, r
}
/**
* A reconnect the provider gave no id for still lands on the row it
* replaces: one dead row with this account's name is that row, and a
* second one with the same name would be the duplicate this prevents.
* An id-less reconnect lands on the row it replaces, named by its request.
* A row that is merely dead is not it: a new mailbox that arrives while
* one dead row exists would otherwise take that row's name and namespace.
* Only a connected account takes it, since an abandoned link at the
* provider stays pending, and only once.
*/
const name = account.label || fallback_label || "";
const dead = name
? ((
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status IN ('revoked', 'expired') AND lower(label) = lower(?) ORDER BY id ASC`,
values: [connector_id, user_id, name],
})
).payload || [])
: [];
if (dead.length == 1) {
const row = dead[0]!;
if (reconnect_row) {
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET provider_account_id = ?, status = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ? WHERE id = ?`,
sql: `UPDATE connector_accounts SET provider_account_id = ?, status = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ?
WHERE id = ? AND connector_id = ? AND user_id = ?`,
values: [
account.provider_account_id,
account.status,
account.status == "connected" ? now : null,
now,
now,
Number(row.id),
reconnect_row,
connector_id,
user_id,
],
});
@@ -226,30 +260,24 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label, r
})
).payload?.map((row) => row.slug) || [];
const display_name = name || "Account";
const display_name = account.label || fallback_label || "Account";
let slug = connectorSlug({ name: display_name, max: 12, fallback: "account" });
for (let index = 2; taken.includes(slug); index++) {
slug = `${connectorSlug({ name: display_name, max: 8, fallback: "account" })}-${index}`;
}
await BunSQLite.sql({
sql: `INSERT INTO connector_accounts
(created_at, updated_at, connector_id, user_id, label, slug, provider_account_id, status, is_default, connected_at, last_checked_at, last_error)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, '')`,
values: [
now,
now,
connector_id,
user_id,
display_name,
slug,
account.provider_account_id,
account.status,
account.status == "connected" ? now : null,
now,
],
const { sql, values } = insertConnectorAccountSql({
now,
connector_id,
user_id,
label: display_name,
slug,
provider_account_id: account.provider_account_id,
status: account.status,
});
await BunSQLite.sql({ sql, values });
}
type SettleParams = {
@@ -280,7 +308,7 @@ async function settleRequests({ connector_id, user_id, provider_account_ids }: S
WHERE a.connector_id = connector_requests.connector_id
AND a.user_id = connector_requests.user_id
AND a.status = 'connected'
AND a.created_at >= connector_requests.created_at
AND (a.created_at >= connector_requests.created_at OR a.id = connector_requests.account_id)
))
)`,
values: [now, connector_id, user_id, now, ...provider_account_ids],
@@ -56,6 +56,7 @@ export default async function grabHarnessModelEntries({
voices: model.voices,
input_modalities: model.input_modalities,
supported_parameters: model.supported_parameters,
context_length: model.context_length,
},
};
});
@@ -14,6 +14,13 @@ export type RunUsageLimits = {
steps: RunLimit | null;
run_tokens: RunLimit | null;
context_tokens: RunLimit | null;
/**
* How much of the working context the app's own prompt and tool
* definitions took before the conversation did, when the run recorded
* them: the usual answer to "why was there room for so little".
*/
system_tokens?: number;
tools_tokens?: number;
};
/**
@@ -137,6 +144,8 @@ const limitsOf = ({ calls }: { calls: RunUsageCall[] }): RunUsageLimits | null =
steps: kept(limits.steps),
run_tokens: kept(limits.run_tokens),
context_tokens: kept(limits.context_tokens),
...(typeof limits.system_tokens == "number" ? { system_tokens: limits.system_tokens } : {}),
...(typeof limits.tools_tokens == "number" ? { tools_tokens: limits.tools_tokens } : {}),
};
};
@@ -202,27 +202,3 @@ export function canSeePath({ resolved, path }: { resolved: ResolvedStorageSpec;
function joinPath({ relative, name }: { relative: string; name: string }) {
return relative ? `${relative}/${name}` : name;
}
/**
* The breadcrumb trail of a folder, from the volume's top: one crumb per
* segment, each with the address that opens it.
*/
export function storageBreadcrumbs({
spec,
path: relative,
}: {
spec: StorageSpec;
path?: string | null;
}) {
const segments = (relative || "").split("/").filter(Boolean);
const crumbs = [{ name: "", href: storageSpecHref({ spec }) }];
for (let i = 1; i <= segments.length; i++) {
crumbs.push({
name: segments[i - 1] || "",
href: storageSpecHref({ spec, path: segments.slice(0, i).join("/") }),
});
}
return crumbs;
}
+2 -1
View File
@@ -27,7 +27,8 @@ type Params = {
/**
* Turns speech into text with the transcription harness: its
* speech-to-text model gets the file at `/audio/transcriptions`.
* speech-to-text model gets the file, at `/audio/transcriptions` or, on
* Alibaba's hosts, at their native multimodal route.
*/
export default async function transcribeAudio({
audio,
@@ -0,0 +1,14 @@
import { expect, test } from "bun:test";
import connectorAccountGoneMessage from "./connector-account-gone";
test("names the account, the provider and where to reconnect", () => {
const message = connectorAccountGoneMessage({
connector_name: "Gmail",
label: "Benoti Sanchez Gmail",
provider_title: "Composio",
});
expect(message).toContain('The Gmail account "Benoti Sanchez Gmail"');
expect(message).toContain("no longer exists at Composio");
expect(message).toContain("Settings > Connectors");
});
@@ -0,0 +1,16 @@
type Params = {
connector_name: string;
label: string;
provider_title: string;
};
/**
* A row can outlive the account it names: a sign-in is deleted at the
* provider (a second one replaced it, a connection was cleared there) while
* the local row still says connected. Pinning that id would make the provider
* fall back to whatever account it does have, so the run would answer from a
* mailbox nobody chose. The tool refuses instead, naming the fix.
*/
export default function connectorAccountGoneMessage({ connector_name, label, provider_title }: Params) {
return `The ${connector_name} account "${label}" no longer exists at ${provider_title}, so this didn't run. Reconnect it in Settings > Connectors.`;
}
@@ -1,10 +1,21 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTOR_SESSIONS } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { ConnectorProviders } from "@/src/dict/connector-dict";
import AppError from "@/src/utils/app-error";
import { decrypt, encrypt } from "@/src/utils/crypt";
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
import connectorAccountGoneMessage from "./connector-account-gone";
import type { ConnectorProvider } from "./connector-provider";
/**
* When each account was last checked against the provider, per process: the
* check is a listing of every account the user has, and a cached session is
* used many times a minute.
*/
const accountChecks = new Map<string, number>();
const AccountCheckEveryMs = 5 * 60 * 1000;
/**
* The endpoint one account's tools live at, cached in `connector_sessions`
* because asking the provider costs a call and the session expires.
@@ -45,6 +56,55 @@ async function readCachedHeaders({ headers }: { headers: string | null }): Promi
}
}
/**
* A row can name an account the provider no longer has (a second sign-in
* replaced it, a connection was cleared there). A session pinned to that id
* is not refused: the provider answers from whichever account it does have,
* so a bot read a mailbox the user never chose. The row is marked revoked
* (its card then offers Reconnect) and the call stops instead.
*
* The check lists every account the user has, so it is remembered per account
* for `AccountCheckEveryMs`: a cached session is checked too, at that pace
* rather than on every tool call.
*/
async function assertAccountStillThere({ connector, provider, user_id, account, now }: Params & { now: number }) {
const key = `${connector.id}:${account.provider_account_id}`;
if (now - (accountChecks.get(key) || 0) < AccountCheckEveryMs) return;
if (accountChecks.size > 1000) accountChecks.clear();
accountChecks.set(key, now);
let accounts: Awaited<ReturnType<ConnectorProvider["accounts"]>>;
try {
accounts = await provider.accounts({ app: connector.app, user_id });
} catch {
// The provider is the one to say why the session failed; a list that
// can't be read is not proof the account is gone.
return;
}
if (accounts.some((entry) => entry.provider_account_id == account.provider_account_id)) return;
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`,
values: [now, now, Number(account.id)],
});
const provider_title =
ConnectorProviders.find((entry) => entry.value == connector.provider)?.title || connector.provider;
throw new AppError(
connectorAccountGoneMessage({
connector_name: connector.name,
label: account.label,
provider_title,
}),
);
}
export default async function ensureConnectorEndpoint({
connector,
provider,
@@ -52,6 +112,9 @@ export default async function ensureConnectorEndpoint({
account,
}: Params): Promise<ConnectorEndpointResult> {
const now = Date.now();
await assertAccountStillThere({ connector, provider, user_id, account, now });
const cached = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_SESSIONS>({
sql: `SELECT * FROM connector_sessions WHERE connector_id = ? AND user_id = ? AND provider_account_id = ? LIMIT 1`,
@@ -156,6 +156,7 @@ describe("composioConnectorProvider", () => {
const session = calls.find((call) => call.url.pathname.endsWith("/tool_router/session"))!;
expect(session.body.multi_account).toEqual({ enable: true, max_accounts_per_toolkit: 5 });
expect(session.body.auth_configs).toEqual({ gmail: "ac_1" });
const link = calls.find((call) => call.url.pathname.endsWith("/tool_router/session/trs_1/link"))!;
@@ -190,8 +191,69 @@ describe("composioConnectorProvider", () => {
expect(made.body.use_composio_managed_auth).toBe(true);
});
test("makes a custom sign-in setup for a toolkit Composio manages no credentials for", async () => {
const { fetchImpl, calls } = stub({
answer: ({ url, method }) => {
if (url.pathname.endsWith("/toolkits/gitea")) {
return { body: { composio_managed_auth_schemes: [], auth_config_details: [{ mode: "API_KEY" }] } };
}
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
if (url.pathname.endsWith("/link")) {
return { status: 201, body: { redirect_url: "https://connect/gitea" } };
}
if (!url.pathname.endsWith("/auth_configs")) return { body: {} };
return method == "POST" ? { status: 201, body: { auth_config: { id: "ac_gitea" } } } : { body: { items: [] } };
},
});
const started = await composioConnectorProvider({ key: "k", fetchImpl }).startConnect({
app: "gitea",
user_id: 4,
label: "Self-hosted",
});
expect(started.auth_config_id).toBe("ac_gitea");
const made = calls.find((call) => call.url.pathname.endsWith("/auth_configs") && call.method == "POST")!;
expect(made.body).toEqual({
toolkit: { slug: "gitea" },
auth_config: { type: "use_custom_auth", authScheme: "API_KEY" },
});
const session = calls.find((call) => call.url.pathname.endsWith("/tool_router/session"))!;
expect(session.body.auth_configs).toEqual({ gitea: "ac_gitea" });
});
test("reuses a sign-in setup the toolkit can use, whatever its scheme", async () => {
const { fetchImpl, calls } = stub({
answer: ({ url }) => {
if (url.pathname.endsWith("/toolkits/gitea")) {
return { body: { composio_managed_auth_schemes: [], auth_config_details: [{ mode: "API_KEY" }] } };
}
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
if (url.pathname.endsWith("/link")) {
return { status: 201, body: { redirect_url: "https://connect/gitea" } };
}
return { body: { items: [{ id: "ac_dash", auth_scheme: "API_KEY" }] } };
},
});
const started = await composioConnectorProvider({ key: "k", fetchImpl }).startConnect({
app: "gitea",
user_id: 4,
label: "Work",
});
expect(started.auth_config_id).toBe("ac_dash");
expect(calls.some((call) => call.url.pathname.endsWith("/auth_configs") && call.method == "POST")).toBe(false);
});
test("maps account statuses and keeps the provider's id", async () => {
const { fetchImpl } = stub({
const { fetchImpl, calls } = stub({
answer: () => ({
body: {
items: [
@@ -208,6 +270,9 @@ describe("composioConnectorProvider", () => {
{ provider_account_id: "ca_1", status: "connected", label: "work@x" },
{ provider_account_id: "ca_2", status: "expired", label: undefined },
]);
expect(calls[0]!.url.searchParams.get("toolkit_slugs")).toBe("gmail");
expect(calls[0]!.url.searchParams.get("user_ids")).toBe("cobble-user-4");
expect(calls[0]!.url.searchParams.get("user_id")).toBeNull();
});
test("executes one tool with the account named in the call", async () => {
+63 -9
View File
@@ -128,29 +128,76 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
return items;
}
/**
* How a toolkit can be signed in: the schemes Composio manages itself and
* every scheme it accepts. Empty when the toolkit can't be read, which
* leaves the managed OAuth setup that every OAuth app has.
*/
async function toolkitAuthMethods({ app }: { app: string }): Promise<{ managed: string[]; schemes: string[] }> {
try {
const toolkit = await request<any>({
path: `/toolkits/${encodeURIComponent(app)}`,
what: `the ${app} sign-in methods`,
});
return {
managed: (toolkit.composio_managed_auth_schemes || []).map((scheme: string) =>
String(scheme).toUpperCase(),
),
schemes: (toolkit.auth_config_details || [])
.map((detail: any) => String(detail.mode || "").toUpperCase())
.filter(Boolean),
};
} catch {
return { managed: [], schemes: [] };
}
}
/**
* The sign-in setup a link belongs to. Composio wants an auth config on
* every link, and makes a managed one for a toolkit that has none yet,
* so a fresh install can connect an app without visiting its dashboard.
* A toolkit Composio manages no credentials for (Gitea, whose key and
* instance URL are the user's own) gets a custom setup of its own scheme
* instead, which the hosted sign-in page fills in.
*/
async function authConfigFor({ app, auth_config_id }: { app: string; auth_config_id?: string | null }) {
if (auth_config_id) return auth_config_id;
const existing = await listAllPages<any>({
path: "/auth_configs",
query: { toolkit_slug: app },
what: `the ${app} sign-in setups`,
});
const usable = existing.find((item) => item.auth_scheme == "OAUTH2") || existing[0];
const [existing, methods] = await Promise.all([
listAllPages<any>({
path: "/auth_configs",
query: { toolkit_slug: app },
what: `the ${app} sign-in setups`,
}),
toolkitAuthMethods({ app }),
]);
const usable = (item: any) =>
!methods.schemes.length || methods.schemes.includes(String(item.auth_scheme || "").toUpperCase());
const reusable =
existing.find((item) => usable(item) && String(item.auth_scheme).toUpperCase() == "OAUTH2") ||
existing.find(usable);
if (usable?.id) return String(usable.id);
if (reusable?.id) return String(reusable.id);
// Nothing known about the toolkit means an OAuth app that Composio
// manages, as before.
const managed = !methods.schemes.length || methods.managed.length > 0;
try {
const created = await request<any>({
path: "/auth_configs",
method: "POST",
what: `a sign-in setup for ${app}`,
body: { toolkit: { slug: app }, auth_scheme: "OAUTH2", use_composio_managed_auth: true },
body: managed
? {
toolkit: { slug: app },
auth_scheme: methods.managed.includes("OAUTH2")
? "OAUTH2"
: methods.managed[0] || "OAUTH2",
use_composio_managed_auth: true,
}
: { toolkit: { slug: app }, auth_config: { type: "use_custom_auth", authScheme: methods.schemes[0] } },
});
const id = created.auth_config?.id || created.id;
@@ -246,6 +293,9 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
body: {
user_id: `cobble-user-${user_id}`,
toolkits: { enable: [app] },
// The link names no auth config, so the session is what
// pins the setup a toolkit with several of them uses.
auth_configs: { [app]: config },
multi_account: { enable: true, max_accounts_per_toolkit: MaxAccountsPerToolkit },
},
});
@@ -280,7 +330,11 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
async accounts({ app, user_id }) {
const items = await listAllPages<any>({
path: "/connected_accounts",
query: { user_id: `cobble-user-${user_id}`, toolkit_slug: app },
// The listing filters on the plural names only: `toolkit_slug`
// and `user_id` are ignored and answer with the whole
// project's accounts, which is how one user's sync took over
// another's account.
query: { user_ids: `cobble-user-${user_id}`, toolkit_slugs: app },
what: `the ${app} accounts`,
});
+13
View File
@@ -26,6 +26,12 @@ type Params = {
* instead of leaving the bot to guess one.
*/
model_name?: string;
/**
* No fallback and no retry can help: another model fails the same way
* (or the caller's own prompt is the problem), so the run stops with
* this message rather than spending the next candidate on it.
*/
fatal?: boolean;
};
/**
@@ -57,6 +63,11 @@ export default class HarnessError extends Error {
method?: string;
url?: string;
model_name?: string;
/**
* Nothing else can be tried: `withCandidates` rethrows it at once,
* without resting the candidate or falling back to another model.
*/
fatal: boolean;
constructor({
message,
@@ -70,6 +81,7 @@ export default class HarnessError extends Error {
method,
url,
model_name,
fatal = false,
}: Params) {
super(message);
this.name = "HarnessError";
@@ -83,5 +95,6 @@ export default class HarnessError extends Error {
this.method = method;
this.url = url;
this.model_name = model_name;
this.fatal = fatal;
}
}
@@ -0,0 +1,32 @@
import { describe, expect, test } from "bun:test";
import isContextOverflowError from "./is-context-overflow-error";
describe("isContextOverflowError", () => {
test.each([
"This model's maximum context length is 131072 tokens",
"context_length_exceeded",
"The prompt is too long for this model",
"Please reduce the length of the messages",
"input length and max_tokens exceed the model's context",
"This request exceeds the maximum number of tokens",
"Your request is 200000 tokens which exceeds the maximum",
])("reads %p as a window the prompt went past", (detail) => {
expect(isContextOverflowError({ status: 400, detail })).toBe(true);
});
test("a plain 400 about something else is not a context overflow", () => {
expect(isContextOverflowError({ status: 400, detail: "Invalid `temperature`: must be between 0 and 2" })).toBe(
false,
);
});
test("a server error or a rate limit is never read as one, whatever it says", () => {
expect(isContextOverflowError({ status: 500, detail: "maximum context length" })).toBe(false);
expect(isContextOverflowError({ status: 429, detail: "context length exceeded" })).toBe(false);
});
test("an empty detail is not one", () => {
expect(isContextOverflowError({ status: 400 })).toBe(false);
expect(isContextOverflowError({ status: 400, detail: "" })).toBe(false);
});
});
@@ -0,0 +1,45 @@
/**
* The shapes providers use when the prompt was too long for the model it
* was sent to. Their message carries the real limit and what was sent
* ("prompt is too long: 1,038,402 tokens > 1,000,000 maximum"), which is
* the only place a model with no declared window states its window.
*/
const ContextOverflowPhrases = [
"maximum context length",
"context length exceeded",
"context_length_exceeded",
"prompt is too long",
"reduce the length of the messages",
"input length and max_tokens exceed",
"exceeds the maximum number of tokens",
"maximum number of input tokens",
];
/**
* "1,038,402 tokens > 1,000,000 maximum": a count compared against a
* limit, which no other kind of 400 phrases that way.
*/
const OverLimitTokens = /\b\d[\d,]{2,}\s*tokens?\b[^.]{0,30}\b(maximum|max|limit)\b/;
type Params = {
status: number;
/**
* The provider's own words, already read out of its error body.
*/
detail?: string;
};
/**
* Whether a provider refused a call because the prompt did not fit its
* model. A 400 usually means "only another model can help", but this one
* means the window this run was sized for is too big: no fallback model
* and no retry fixes it, and the message says what the real limit is
* (`isContextOverflowError` -> `toHarnessError`).
*/
export default function isContextOverflowError({ status, detail }: Params) {
if (status != 400 && status != 413 && status != 422) return false;
const text = (detail || "").toLowerCase();
return ContextOverflowPhrases.some((phrase) => text.includes(phrase)) || OverLimitTokens.test(text);
}
@@ -0,0 +1,59 @@
import HarnessError from "../../harness-error";
/**
* Alibaba's native routes (images, speech) live at the host root, beside
* `<base>/compatible-mode/v1`, never under it.
*/
export const NativeGenerationPath = "/api/v1/services/aigc/multimodal-generation/generation";
/**
* The host root: the native routes live beside `<base>/compatible-mode/v1`,
* never under it.
*/
export function dashScopeOrigin({ base_url }: { base_url: string }) {
try {
return new URL(base_url).origin;
} catch {
throw new HarnessError({
message: `The provider's base URL can't be read as an address: ${base_url}`,
retryable: false,
});
}
}
/**
* Alibaba's Token Plan host. Its models are served only by the native
* calls; the compatible routes 404, and trying one first benches the model
* before the request that works.
*/
export function isTokenPlanHost({ base_url }: { base_url?: string | null }) {
if (!base_url) return false;
try {
return new URL(base_url).hostname.startsWith("token-plan.");
} catch {
return false;
}
}
/**
* A DashScope or Model Studio host, where the native calls take the
* provider's own extensions (`image` references, audio input). The shared
* `dashscope` hosts and the workspace `maas` hosts both count; a custom
* provider pointed elsewhere keeps the standard behaviour.
*/
export function isDashScopeHost({ base_url }: { base_url?: string | null }) {
if (!base_url) return false;
try {
const host = new URL(base_url).hostname;
return (
host == "dashscope.aliyuncs.com" ||
host == "dashscope-intl.aliyuncs.com" ||
host.endsWith(".maas.aliyuncs.com")
);
} catch {
return false;
}
}
@@ -1,6 +1,7 @@
import { AppData } from "@/src/data/app-data";
import HarnessError from "../../harness-error";
import type { HarnessCandidate, HarnessImageOutput } from "../../types";
import { dashScopeOrigin, NativeGenerationPath } from "./dashscope-hosts";
import downloadProviderFile from "./download-provider-file";
import providerRequest from "./provider-request";
@@ -24,8 +25,6 @@ type Params = {
* how the native API takes image editing too. The answer carries image URLs,
* downloaded here under the same guards as every other provider URL.
*/
export const NativeImagePath = "/api/v1/services/aigc/multimodal-generation/generation";
export default async function generateImageNative({
candidate,
prompt,
@@ -40,8 +39,8 @@ export default async function generateImageNative({
const res = await providerRequest({
provider,
base_url: nativeOrigin({ base_url: provider.base_url }),
path: NativeImagePath,
base_url: dashScopeOrigin({ base_url: provider.base_url }),
path: NativeGenerationPath,
json: {
model: model.slug,
input: {
@@ -90,7 +89,7 @@ export default async function generateImageNative({
if (!urls.length) {
throw new HarnessError({
message: `${name}: no image came back from ${NativeImagePath}.`,
message: `${name}: no image came back from ${NativeGenerationPath}.`,
retryable: true,
candidate_key: candidate.key,
});
@@ -112,21 +111,6 @@ export default async function generateImageNative({
return { images };
}
/**
* The host root: the native routes live beside `<base>/compatible-mode/v1`,
* never under it.
*/
function nativeOrigin({ base_url }: { base_url: string }) {
try {
return new URL(base_url).origin;
} catch {
throw new HarnessError({
message: `The provider's base URL can't be read as an address: ${base_url}`,
retryable: false,
});
}
}
/**
* The tool's size is a plain `1024x1024`; the native API wants
* `1024*1024` and ignores anything that isn't a pair of pixels.
@@ -0,0 +1,109 @@
import HarnessError from "../../harness-error";
import type { HarnessCandidate } from "../../types";
import { dashScopeOrigin, NativeGenerationPath } from "./dashscope-hosts";
import providerRequest from "./provider-request";
type Params = {
candidate: HarnessCandidate;
audio: { data: Uint8Array; format: string };
language?: string;
signal: AbortSignal;
};
/**
* What the audio formats the browser records are called as MIME types.
* DashScope takes a data URL, and Safari's `audio/mp4` recording arrives
* here as `m4a`, which no browser spells as a MIME type.
*/
const AudioMimeTypes: Record<string, string> = {
m4a: "audio/mp4",
mp4: "audio/mp4",
mp3: "audio/mpeg",
ogg: "audio/ogg",
opus: "audio/ogg",
};
/**
* Qwen-ASR on Alibaba's native multimodal route. The Token Plan host and the
* workspace Model Studio hosts have no `/audio/transcriptions` at all: the
* model is asked on the host root (beside `compatible-mode/v1`) with the
* audio inline as a data URL, and answers its transcript at `output.text`.
*
* The formats Alibaba documents are wav, mp3 and opus, but live calls take
* every format the recorders here produce (webm, m4a, ogg) when the label
* matches the bytes, so the browser's own recording is sent as it is rather
* than re-encoded first.
*/
export default async function transcribeNative({
candidate,
audio,
language,
signal,
}: Params): Promise<{ text: string }> {
const { provider, model } = candidate;
const name = provider.name || "Alibaba Cloud";
const format = audio.format.toLowerCase();
const mime_type = AudioMimeTypes[format] || `audio/${format}`;
const data_url = `data:${mime_type};base64,${Buffer.from(audio.data).toString("base64")}`;
const hint = languageHint({ language });
const res = await providerRequest({
provider,
base_url: dashScopeOrigin({ base_url: provider.base_url }),
path: NativeGenerationPath,
json: {
model: model.slug,
input: {
messages: [
{
role: "user",
content: [{ type: "input_audio", input_audio: { data: data_url } }],
},
],
},
parameters: {
format,
...(hint ? { language_hints: [hint] } : {}),
},
},
signal,
candidate_key: candidate.key,
});
const json = await res.json().catch(() => null);
/**
* A cut-off or malformed answer is a failed call, not silence: saying
* it failed lets the harness try the next model instead of handing the
* user an empty transcript.
*/
if (json === null) {
throw new HarnessError({
message: `${name} returned an unreadable transcript.`,
retryable: true,
candidate_key: candidate.key,
});
}
const text = String(json?.output?.text ?? json?.text ?? "").trim();
if (!text) {
throw new HarnessError({
message: `${name} returned an empty transcript.`,
retryable: true,
candidate_key: candidate.key,
});
}
return { text };
}
/**
* `language_hints` takes a language (`en`), not a locale (`en-US`), so the
* browser's BCP-47 tag is cut to its primary subtag.
*/
function languageHint({ language }: { language?: string }) {
const primary = language?.trim().split(/[-_]/)[0]?.toLowerCase() ?? "";
return /^[a-z]{2,3}$/.test(primary) ? primary : undefined;
}
@@ -2,6 +2,7 @@ import { AppData } from "@/src/data/app-data";
import HarnessError from "../../harness-error";
import type { HarnessAdapter, HarnessCandidate, HarnessImageOutput } from "../../types";
import grabProviderPreset from "../grab-provider-preset";
import { isDashScopeHost, isTokenPlanHost } from "./dashscope-hosts";
import downloadProviderFile from "./download-provider-file";
import generateImageNative from "./dashscope-native-image";
import imageRequestFields from "./image-request-fields";
@@ -217,37 +218,5 @@ async function editForm({ model, prompt, n, size, references, signal }: EditForm
* Alibaba's DashScope and Model Studio (`maas`) hosts serve the OpenAI
* images protocol with their own quirks: references go in the `image`
* extension field on `/images/generations` (no multipart `/images/edits`),
* and the response is always URLs. The shared `dashscope` hosts and the
* workspace `maas` hosts both count; a custom provider pointed elsewhere
* keeps the standard behaviour.
* and the response is always URLs.
*/
/**
* Alibaba's Token Plan host. Its image models are served only by the native
* call; the compatible `/images/generations` path 404s, and trying it first
* benches the model before the picture is made.
*/
export function isTokenPlanHost({ base_url }: { base_url?: string | null }) {
if (!base_url) return false;
try {
return new URL(base_url).hostname.startsWith("token-plan.");
} catch {
return false;
}
}
function isDashScopeHost({ base_url }: { base_url?: string | null }) {
if (!base_url) return false;
try {
const host = new URL(base_url).hostname;
return (
host == "dashscope.aliyuncs.com" ||
host == "dashscope-intl.aliyuncs.com" ||
host.endsWith(".maas.aliyuncs.com")
);
} catch {
return false;
}
}
@@ -3,9 +3,14 @@ import HarnessError from "../../harness-error";
import type { HarnessCandidate } from "../../types";
let payload: unknown = { text: "hello world" };
let request: any = null;
mock.module("./provider-request", () => ({
default: async () => ({ json: async () => payload }),
default: async (args: any) => {
request = args;
return { json: async () => payload };
},
}));
const { default: transcribe } = await import("./transcribe");
@@ -23,6 +28,7 @@ const signal = new AbortController().signal;
afterAll(() => mock.restore());
beforeEach(() => {
payload = { text: "hello world" };
request = null;
});
describe("transcribe", () => {
@@ -64,4 +70,82 @@ describe("transcribe", () => {
expect(result.usage).toEqual({ prompt_tokens: 10, completion_tokens: 2 });
});
});
test("Alibaba's hosts are asked on the native route, not /audio/transcriptions", async () => {
payload = { output: { text: " 你好 " } };
const result = await transcribe({
candidate: tokenPlanCandidate({ slug: "qwen-audio-3.0-asr-flash" }),
audio,
signal,
});
expect(result.text).toBe("你好");
expect(request.path).toBe("/api/v1/services/aigc/multimodal-generation/generation");
expect(request.base_url).toBe("https://token-plan.ap-southeast-1.maas.aliyuncs.com");
expect(request.form).toBeUndefined();
expect(request.json.model).toBe("qwen-audio-3.0-asr-flash");
expect(request.json.input.messages[0].content[0]).toEqual({
type: "input_audio",
input_audio: { data: "data:audio/wav;base64,AQID" },
});
expect(request.json.parameters).toEqual({ format: "wav" });
});
test("the native call labels the recording's format and cuts the language to its primary subtag", async () => {
payload = { output: { text: "hello" } };
await transcribe({
candidate: tokenPlanCandidate({ slug: "qwen-audio-3.0-asr-flash" }),
audio: { data: new Uint8Array([1, 2, 3]), format: "webm" },
language: "en-US",
signal,
});
expect(request.json.input.messages[0].content[0].input_audio.data).toStartWith(
"data:audio/webm;base64,",
);
expect(request.json.parameters).toEqual({ format: "webm", language_hints: ["en"] });
});
test("a model that only transcribes as a job is refused without a call", async () => {
const error = await transcribe({
candidate: tokenPlanCandidate({ slug: "qwen3-asr-flash-filetrans" }),
audio,
signal,
}).catch((thrown: unknown) => thrown);
expect(error).toBeInstanceOf(HarnessError);
expect(error).toMatchObject({ retryable: false });
expect(request).toBeNull();
});
test("an ASR model on another provider keeps the OpenAI-style upload", async () => {
payload = { text: "hello" };
await transcribe({
candidate: {
...candidate,
model: { slug: "qwen3-asr-flash" },
} as unknown as HarnessCandidate,
audio,
signal,
});
expect(request.path).toBe("/audio/transcriptions");
expect(request.form).toBeInstanceOf(FormData);
});
});
function tokenPlanCandidate({ slug }: { slug: string }) {
return {
key: `transcription:${slug}`,
provider: {
kind: "custom",
base_url: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
name: "Alibaba Cloud Token Plan",
},
model: { slug },
source: "pinned",
} as unknown as HarnessCandidate;
}
@@ -1,10 +1,25 @@
import HarnessError from "../../harness-error";
import type { HarnessAdapter } from "../../types";
import { isDashScopeHost } from "./dashscope-hosts";
import transcribeNative from "./dashscope-native-transcribe";
import providerRequest from "./provider-request";
/**
* The native Qwen-ASR models: the only synchronous speech models Alibaba's
* DashScope/Model Studio hosts serve, at their own route rather than
* `/audio/transcriptions`.
*/
const NativeAsrModel = /asr|paraformer/i;
/**
* File transcription is a job at the provider (submit, then poll), which
* this adapter doesn't run: it would queue a task and wait for nothing.
*/
const AsyncOnlyAsrModel = /filetrans|paraformer/i;
/**
* `POST /audio/transcriptions` as an OpenAI-style file upload, which
* OpenRouter, OpenAI, Groq and local servers all take.
* OpenRouter, OpenAI, Groq and local servers all take. Alibaba's hosts have
* no such route, so their ASR models go to the native call instead.
*/
const transcribe: HarnessAdapter["transcribe"] = async ({
candidate,
@@ -12,6 +27,18 @@ const transcribe: HarnessAdapter["transcribe"] = async ({
language,
signal,
}) => {
if (isDashScopeHost({ base_url: candidate.provider.base_url }) && NativeAsrModel.test(candidate.model.slug)) {
if (AsyncOnlyAsrModel.test(candidate.model.slug)) {
throw new HarnessError({
message: `${candidate.provider.name || "Alibaba Cloud"}: ${candidate.model.slug} only transcribes as an asynchronous job, which this harness doesn't run. Pick a synchronous ASR model such as qwen-audio-3.0-asr-flash.`,
retryable: false,
candidate_key: candidate.key,
});
}
return await transcribeNative({ candidate, audio, language, signal });
}
const form = new FormData();
form.append("model", candidate.model.slug);
@@ -159,4 +159,32 @@ describe("toHarnessError", () => {
expect(error.message.match(/images\/generations/g)?.length).toBe(1);
});
test("a prompt past the model's window is fatal, keeps the provider's limit and says what to set", () => {
const error = toHarnessError({
status: 400,
body: JSON.stringify({
error: { message: "This model's maximum context length is 65536 tokens. However, your messages resulted in 99812 tokens." },
}),
provider_name: "Nvidia Cloud",
});
expect(error.fatal).toBe(true);
expect(error.retryable).toBe(false);
expect(error.provider_wide).toBe(false);
expect(error.message).toContain("maximum context length is 65536 tokens");
expect(error.message).toContain("Set this model's context window under Settings > Models");
expect(error.message).toContain("assumed to have 1,000,000");
});
test("any other 400 is only about the model, never fatal", () => {
const error = toHarnessError({
status: 400,
body: JSON.stringify({ error: { message: "temperature is not supported" } }),
provider_name: "Example",
});
expect(error.fatal).toBe(false);
expect(error.message).not.toContain("Settings > Models");
});
});
+18 -1
View File
@@ -1,4 +1,5 @@
import HarnessError from "../harness-error";
import isContextOverflowError from "./is-context-overflow-error";
import parseRetryAt from "./parse-retry-at";
import redactProviderError from "./redact-provider-error";
@@ -26,6 +27,8 @@ type Params = {
* the same way, so it is `provider_wide`
* - 408, 409, 425, 429, 5xx: `retryable`, with `retry_at` when the
* provider says
* - a 400 saying the prompt did not fit the model's window: `fatal`, and
* the run stops with the provider's own limit (`isContextOverflowError`)
* - anything else (400, 403, 404, 422): only another model can help. A
* 403 is about the model (OpenRouter refuses some free models to most
* apps), not the key
@@ -54,12 +57,26 @@ export default function toHarnessError({
address = addressText({ detail, method, url }),
hint = missing_endpoint ? " - no endpoint at that address; check the provider's base URL" : "";
/**
* A prompt that did not fit the model's window is the one 400 no
* fallback model or retry fixes: the run was sized for a window this
* model does not have, and the provider has just said what it is. The
* run stops with this message, so the user reads the real limit rather
* than a bot that trimmed every result and answered from nothing.
*/
const overflow = isContextOverflowError({ status, detail: provider_detail });
const advice = overflow
? "\nSet this model's context window under Settings > Models: a model with none declared is assumed to have 1,000,000."
: "";
const retryable = [408, 409, 425, 429].includes(status) || status >= 500;
return new HarnessError({
message: redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, 400),
message: `${redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, overflow ? 320 : 400)}${advice}`,
status,
retryable,
fatal: overflow,
retry_at: retryable && headers ? parseRetryAt({ headers }) : undefined,
provider_wide: status == 401 || status == 402,
candidate_key,
@@ -70,6 +70,36 @@ describe("withCandidates", () => {
expect(tried).toEqual(["b"]);
});
test("a fatal failure is thrown at once, with no fallback and nothing rested", async () => {
const cooldowns = createCooldowns();
const tried: string[] = [];
const a = candidate("a");
const b = candidate("b");
const fatal = new HarnessError({
message: "prompt is too long for this model",
status: 400,
fatal: true,
candidate_key: a.key,
});
const call = withCandidates({
harness: "text",
candidates: [a, b],
cooldowns,
run: async (c) => {
tried.push(c.model.slug);
throw fatal;
},
});
await expect(call).rejects.toBe(fatal);
// A smaller window is not a fault of the model: no other model can
// answer the same prompt, so none is tried and none is rested.
expect(tried).toEqual(["a"]);
expect(cooldowns.get({ key: a.key })).toBeUndefined();
});
test("tries the preferred model first", async () => {
const tried: string[] = [];
+23 -1
View File
@@ -69,7 +69,8 @@ type Params<T> = {
* install's model rest (`coolDown`) and is logged.
*
* Throws a `HarnessError`: `unavailable` when there is nothing to try,
* otherwise the last failure, `retryable` if any failure was.
* otherwise the last failure, `retryable` if any failure was. A `fatal`
* failure is rethrown at once: no cooldown, no next candidate.
*/
export default async function withCandidates<T>({
harness,
@@ -166,6 +167,27 @@ export default async function withCandidates<T>({
} catch (error: unknown) {
if (!(error instanceof HarnessError)) throw error;
if (error.code == "aborted") throw error;
/**
* A fatal failure is the run's own: another model fails the same
* way, and the message (the provider's own limit, or the app's
* arithmetic on a window) is what the user needs to read. It
* rests nothing and falls back to nothing. It is still written
* down as a failed call, so the notice the message carries can
* say which model refused it and why.
*/
if (error.fatal) {
error.model_name ||= candidate.model.slug;
if (log_failures) {
await recordHarnessFailure({
harness: harness_of?.get(candidate.key) || harness,
candidate,
error,
});
}
throw error;
}
/**
* The model's own name goes on the failure: a tool tells the bot
@@ -0,0 +1,36 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import type { HarnessTool } from "../types";
import deferredToolsNote from "./deferred-tools-note";
function tool({ name, group }: { name: string; group?: string }) {
return { name, description: `Does ${name}.`, group } as unknown as HarnessTool;
}
describe("deferredToolsNote", () => {
test("a big namespace is one line of names, not a line per description", () => {
const count = AppData.HarnessDeferredNamespaceMin;
const tools = Array.from({ length: count }, (_, index) => tool({ name: `github__TOOL_${index}` }));
const note = deferredToolsNote({ tools });
expect(note).toContain(`- github (${count} tools): github__TOOL_0, github__TOOL_1,`);
expect(note).not.toContain("Does github__TOOL_0.");
expect(note.split("\n")).toHaveLength(2);
});
test("a small namespace still names each tool", () => {
const note = deferredToolsNote({ tools: [tool({ name: "gmail__SEND" }), tool({ name: "gmail__FETCH" })] });
expect(note).toContain("- gmail__SEND: Does gmail__SEND.");
expect(note).toContain("- gmail__FETCH: Does gmail__FETCH.");
});
test("a family and a tool with no namespace are listed as before", () => {
const note = deferredToolsNote({
tools: [tool({ name: "read_file", group: "files" }), tool({ name: "browser_click" })],
});
expect(note).toContain("- files: read_file (load the family by its name)");
expect(note).toContain("- browser_click: Does browser_click.");
});
});
+34 -6
View File
@@ -3,14 +3,42 @@ import type { HarnessTool } from "../types";
import { LoadToolsToolName } from "../tools/load-tools-tool";
/**
* The system prompt's list of the tools a run may load (`load_tools`):
* each by name with the start of its description, so the model knows
* what is there without every definition riding along on each turn.
* The system prompt's list of the tools a run may load (`load_tools`): the
* bot's own tools by family, each with the names in it, and every extension
* tool by name with the start of its description, so the model knows what is
* there without every definition riding along on each turn.
*
* A namespace (one connector's or MCP server's tools) that offers many
* tools is listed by name alone, on one line: one GitHub account's 905 tools
* came to 148,000 characters with their descriptions, sent with every turn
* of every run. Their names still cost 34,000 characters, which is the price
* of a bot finding the one tool it needs without loading 905 definitions.
*/
export default function deferredToolsNote({ tools }: { tools: HarnessTool[] }) {
const lines = tools.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`);
const families = new Map<string, string[]>();
const loose = new Map<string, HarnessTool[]>();
return `Tools you can load: these are available to you but not loaded yet, to keep each step small. Call ${LoadToolsToolName} with the names you need (one call can load several), then call them. Don't load what you won't use.\n${lines.join("\n")}`;
for (const tool of tools) {
if (tool.group) {
families.set(tool.group, [...(families.get(tool.group) ?? []), tool.name]);
continue;
}
const prefix = tool.name.includes("__") ? tool.name.slice(0, tool.name.indexOf("__")) : "";
loose.set(prefix, [...(loose.get(prefix) ?? []), tool]);
}
const lines = [
...[...families].map(([group, names]) => `- ${group}: ${names.join(", ")} (load the family by its name)`),
...[...loose].flatMap(([prefix, names]) =>
prefix && names.length >= AppData.HarnessDeferredNamespaceMin
? [`- ${prefix} (${names.length} tools): ${names.map((tool) => tool.name).join(", ")}`]
: names.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`),
),
];
return `Tools you can load: these are available to you but not loaded yet, to keep each step small. Call ${LoadToolsToolName} with what you need (one call can load several), then call them: exact names, a family's name for all of it, or "<prefix>*". Don't load what you won't use.\n${lines.join("\n")}`;
}
function shortDescription({ text }: { text: string }) {
@@ -18,4 +46,4 @@ function shortDescription({ text }: { text: string }) {
const max = AppData.HarnessDeferredToolLineChars;
return line.length > max ? `${line.slice(0, max - 3).trimEnd()}...` : line;
}
}
@@ -23,7 +23,7 @@ function transcript(): HarnessMessage[] {
];
}
const params = { system: "s", context_length: 200, keep_last: 4 };
const params = { system: "s", working_tokens: 140, keep_last: 4 };
describe("fitTranscriptToContext keeps a head+tail trim across passes (M4)", () => {
test("a long result is cut to its start and end, not replaced whole", () => {
@@ -54,3 +54,89 @@ describe("fitTranscriptToContext keeps a head+tail trim across passes (M4)", ()
expect(messages[0]!.content as string).toContain("_END_MARKER");
});
});
describe("fitTranscriptToContext never leaves a run reading a note instead of an answer", () => {
test("a result short enough to keep whole is kept whole", () => {
const messages: HarnessMessage[] = [
{ role: "tool", tool_call_id: "c1", content: "/usr/bin/pdftoppm" },
];
// Far below the result, so every pass that could cut it runs.
const result = fitTranscriptToContext({ system: "s", transcript: messages, working_tokens: 10 });
expect(result.trimmed).toBe(0);
expect(messages[0]!.content).toBe("/usr/bin/pdftoppm");
});
test("the newest turn's results are cut last, only once the older ones are gone", () => {
const old = `OLD_START_${"x".repeat(30_000)}_OLD_END`;
const fresh = `FRESH_START_${"y".repeat(6000)}_FRESH_END`;
const messages: HarnessMessage[] = [
{ role: "tool", tool_call_id: "old", content: old },
{ role: "user", content: "u1" },
{
role: "assistant",
content: "a1",
tool_calls: [{ id: "new", name: "computer_bash", arguments: "{}" }],
},
{ role: "tool", tool_call_id: "new", content: fresh },
];
// Enough room once the older result is cut, so the newest one stays.
const result = fitTranscriptToContext({
system: "s",
transcript: messages,
working_tokens: 5_000,
keep_last: 0,
});
expect(result.trimmed).toBe(1);
expect(messages[0]!.content as string).toContain("OLD_START_");
expect(messages[3]!.content).toBe(fresh);
});
});
describe("fitTranscriptToContext names what is over the working context", () => {
test("its own instructions alone past the context is static", () => {
const result = fitTranscriptToContext({
system: "x".repeat(3_000),
transcript: [],
working_tokens: 500,
});
expect(result.over_budget).toBe("static");
expect(result.base).toBe(result.system_tokens);
});
test("tool definitions count toward the static part", () => {
const result = fitTranscriptToContext({
system: "s",
transcript: [],
working_tokens: 500,
tools_chars: 3_000,
});
expect(result.over_budget).toBe("static");
expect(result.tools_tokens).toBe(1_000);
});
test("a conversation the user made too long is the request", () => {
const result = fitTranscriptToContext({
system: "s",
transcript: [{ role: "user", content: "y".repeat(3_000) }],
working_tokens: 500,
keep_last: 0,
});
expect(result.over_budget).toBe("request");
// The user's own text is never cut.
expect(result.trimmed).toBe(0);
});
test("a prompt that fits says nothing is over", () => {
const result = fitTranscriptToContext({ system: "s", transcript: [], working_tokens: 500 });
expect(result.over_budget).toBe(false);
});
});
+78 -55
View File
@@ -8,30 +8,35 @@ type Params = {
*/
transcript: HarnessMessage[];
/**
* The model's context window, in tokens.
* The working context (`workingContextTokens`): the most a turn may
* send, the model's window less the room its answer needs, or the
* install's own tighter cap.
*/
context_length: number;
/**
* The working context (`grabContextBudgetTokens`): the most the prompt
* may be per turn, whatever the window. Left out, only the window
* limits it.
*/
budget_tokens?: number;
working_tokens: number;
/**
* Characters of the tool definitions sent with every turn: they count
* against the budget like the prompt.
*/
tools_chars?: number;
/**
* The newest messages, never trimmed: the model needs them to go on.
* The newest messages: the passes that cut everything else leave them
* alone, so the turn the run is working from keeps its answer. Only the
* last resort (still over budget with nothing older left to cut) cuts
* their tool results, and what the user wrote is never cut at all.
*/
keep_last?: number;
};
/**
* Share of the window the prompt may fill; the rest is for the answer.
* Why the prompt still doesn't fit:
* - `static`: the system prompt and tool definitions alone are past the
* working context, so no amount of trimming can help and the run must
* stop and say so
* - `request`: what is over is the conversation itself, most often what
* the user wrote, which is never cut
*/
const PromptShare = 0.7;
export type OverBudgetCause = "static" | "request";
/**
* Once over budget, trimming goes on down to this share of it. Cutting in
* one block, rather than one message each turn, keeps the start of the
@@ -54,6 +59,14 @@ const MediaTokens = 1500;
* and its totals, as `truncate` does) is usually all the run still needs.
*/
const TrimmedKeepChars = 500;
/**
* A result no longer than this is kept whole. Cutting it saved nothing
* worth a note, and a short result used to be replaced by the note alone:
* a 14-character answer from a shell reached the model as "Trimmed: 14
* characters", so the run was reading nothing at all and went on doing it
* for the rest of its steps.
*/
const ResultKeepWholeChars = TrimmedKeepChars * 4;
/**
* Tool call arguments longer than this (a file written whole) are cut on
* the second pass, after the tool results.
@@ -62,35 +75,51 @@ const ArgumentsKeepChars = 1500;
/**
* Keeps a long tool run inside its working context: once the estimated
* prompt (system, tool definitions, transcript) passes the budget (the
* working context, or 70% of the window when that is smaller), the
* oldest tool results, then long tool call arguments, then the oldest
* assistant texts are replaced with a note of what was cut, down to 60%
* of the budget. Returns how many messages were trimmed, and whether the
* prompt still doesn't fit (nothing trimmable was left: the conversation
* is the user's own text, which is never cut).
* prompt (system, tool definitions, transcript) passes it, the oldest tool
* results, then long tool call arguments, then the oldest assistant texts
* are replaced with a note of what was cut, down to 60% of it. The newest
* turn's results are cut last, and only once everything older is gone.
* Reports how many messages were trimmed, and, when the prompt still
* doesn't fit, whether the static part is the cause.
*/
export default function fitTranscriptToContext({
system,
transcript,
context_length,
budget_tokens,
working_tokens,
tools_chars = 0,
keep_last = 4,
}: Params) {
const window_budget = Math.floor(context_length * PromptShare);
const budget = budget_tokens && budget_tokens > 0 ? Math.min(window_budget, budget_tokens) : window_budget;
let total =
estimateTokens({ text: system }) +
Math.ceil(tools_chars / CharsPerToken) +
transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
const budget = working_tokens;
const system_tokens = estimateTokens({ text: system });
const tools_tokens = Math.ceil(tools_chars / CharsPerToken);
const base = system_tokens + tools_tokens;
let total = base + transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
let trimmed = 0;
if (total <= budget) return { trimmed, estimated_tokens: total, budget, over_budget: false };
if (total <= budget) {
return {
trimmed,
estimated_tokens: total,
budget,
base,
system_tokens,
tools_tokens,
over_budget: false as false | OverBudgetCause,
};
}
const target = Math.floor(budget * TrimToShare);
const trimmable = transcript.length - keep_last;
const names = toolNames({ transcript });
/**
* Everything after the newest user turn is what the run is working
* from right now. Cutting it is the last resort, not the first: it is
* why a run over budget kept its command and lost its answer.
*/
const newest_turn = Math.max(
0,
Math.min(trimmable, transcript.reduce((last, message, index) => (message.role == "user" ? index : last), trimmable)),
);
const replace = ({ index, message }: { index: number; message: HarnessMessage }) => {
const before = messageTokens({ message: transcript[index]! });
@@ -104,24 +133,22 @@ export default function fitTranscriptToContext({
* A tool result cut down to its two ends and a note: the run works from
* what it kept, rather than paying for the call again.
*/
const trimResult = ({ index, content, name }: { index: number; content: string; name: string | undefined }) => {
const kept = content.length > TrimmedKeepChars * 4;
const head = kept ? content.slice(0, TrimmedKeepChars) : "";
const tail = kept ? content.slice(-TrimmedKeepChars) : "";
const trimResult = ({ content, name }: { content: string; name: string | undefined }) => {
const head = content.slice(0, TrimmedKeepChars);
const tail = content.slice(-TrimmedKeepChars);
const cut = content.length - head.length - tail.length;
const label = name ? `${name} output` : "tool output";
if (!kept) return `[Trimmed: ${cut} characters of this ${label} to fit the working context.]`;
const note = `[Trimmed: ${cut} characters of the middle of this ${label} to fit the working context. Its start and end are kept here: work from them, and narrow the call (a smaller range, a filter, one row) rather than repeating it.]`;
return `${head}\n\n${note}\n\n${tail}`;
};
for (let index = 0; index < trimmable && total > target; index++) {
const trimToolResult = ({ index }: { index: number }) => {
const message = transcript[index]!;
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
if (message.role != "tool" || isTrimmed({ text: message.content })) return;
if (message.content.length <= ResultKeepWholeChars) return;
const name = names.get(message.tool_call_id);
@@ -129,12 +156,14 @@ export default function fitTranscriptToContext({
index,
message: {
...message,
content: trimResult({ index, content: message.content, name }),
content: trimResult({ content: message.content, name }),
},
});
}
};
for (let index = 0; index < trimmable && total > target; index++) {
for (let index = 0; index < newest_turn && total > target; index++) trimToolResult({ index });
for (let index = 0; index < newest_turn && total > target; index++) {
const message = transcript[index]!;
if (message.role != "assistant" || !message.tool_calls?.some((call) => call.arguments.length > ArgumentsKeepChars)) {
@@ -159,7 +188,7 @@ export default function fitTranscriptToContext({
});
}
for (let index = 0; index < trimmable && total > target; index++) {
for (let index = 0; index < newest_turn && total > target; index++) {
const message = transcript[index]!;
if (message.role != "assistant" || typeof message.content != "string" || isTrimmed({ text: message.content })) {
@@ -183,23 +212,17 @@ export default function fitTranscriptToContext({
* they are cut last, and only once everything older is gone. A user's
* own text is never touched.
*/
for (let index = Math.max(trimmable, 0); index < transcript.length && total > target; index++) {
const message = transcript[index]!;
for (let index = newest_turn; index < transcript.length && total > target; index++) trimToolResult({ index });
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
const name = names.get(message.tool_call_id);
replace({
index,
message: {
...message,
content: trimResult({ index, content: message.content, name }),
},
});
}
return { trimmed, estimated_tokens: total, budget, over_budget: total > budget };
return {
trimmed,
estimated_tokens: total,
budget,
base,
system_tokens,
tools_tokens,
over_budget: total > budget ? (base >= budget ? ("static" as const) : ("request" as const)) : (false as const),
};
}
/**
+107 -5
View File
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import { UnlimitedLimit } from "@/src/utils/run-limit";
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import type { HarnessCandidate, HarnessTool } from "../types";
import type { HarnessTrace } from "../trace/types";
@@ -14,6 +14,7 @@ import runTextLoop, {
stepsLowWarningLeft,
wrapUpPrompt,
} from "./run-text-loop";
import { WorkingContextReserveMax } from "./working-context";
/**
* A reviewer that threw is logged (`logError`), and the log goes to the
@@ -280,7 +281,7 @@ describe("runTextLoop", () => {
});
});
test("a run with no step limit keeps going, and records that its limits were off", async () => {
test("a run with no step limit keeps going, and records the window it works to", async () => {
memory.length = 0;
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
@@ -304,7 +305,11 @@ describe("runTextLoop", () => {
expect(seen[0]!.limits).toEqual({
steps: UnlimitedLimit,
run_tokens: UnlimitedLimit,
context_tokens: UnlimitedLimit,
// The working context is a number even with no cap: the model's
// window less the room its answer needs.
context_tokens: AppData.HarnessUnknownContextWindow - WorkingContextReserveMax,
system_tokens: 1,
tools_tokens: expect.any(Number),
});
});
@@ -1039,6 +1044,99 @@ describe("runTextLoop", () => {
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", "srv__small"]);
expect(String(seen[0]!.messages[0]!.content)).not.toContain("Tools you can load");
});
/**
* A model with a small window, which is where a bot's own tool
* definitions are a real share of the prompt (the default candidate
* declares none, so its working context is ~936,000 tokens).
*/
const narrow = async () => [{ ...candidate, model: { ...candidate.model, context_length: 20_000 } }];
const bulk = (name: string, group?: string): HarnessTool => ({
name,
description: "Works on the tracker. ".repeat(220),
parameters: { type: "object", properties: {} },
group,
deferred: true,
run: async () => "done",
});
const family = ["list_tasks", "create_task", "update_task", "delete_task", "defer_task"].map((name) =>
bulk(name, "tasks"),
);
test("defers a family of the bot's own tools once it is worth a load turn", async () => {
const { generate, seen } = scripted([{ text: "Hi." }]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember, ...family],
generate,
resolveCandidates: narrow,
});
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", "load_tools"]);
expect(String(seen[0]!.messages[0]!.content)).toContain("Tools you can load");
expect(String(seen[0]!.messages[0]!.content)).toContain(
"- tasks: list_tasks, create_task, update_task, delete_task, defer_task (load the family by its name)",
);
});
test("keeps the tools that end a run loaded, however big they are", async () => {
const { generate, seen } = scripted([{ text: "Hi." }]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember, ...family, bulk("send_reply", "sessions"), bulk("write_file", "files")],
generate,
resolveCandidates: narrow,
});
const names = seen[0]!.tools!.map((tool) => tool.name);
expect(names).toContain("send_reply");
expect(names).toContain("write_file");
expect(names).toContain("load_tools");
expect(names).not.toContain("list_tasks");
});
test("defers its own tools only once together they take a share of the context", async () => {
// The same family on a model with room to spare: the turn a load
// costs is not worth saving 7,000 tokens out of 936,000.
const { generate, seen } = scripted([{ text: "Hi." }]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember, ...family],
generate,
resolveCandidates,
});
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", ...family.map((tool) => tool.name)]);
});
test("stops at once when its own instructions alone are past the working context", async () => {
const { generate, seen } = scripted([{ text: "never" }]);
const call = runTextLoop({
system: "x".repeat(3_000),
messages: [{ role: "user", content: "go" }],
tools: [remember],
generate,
resolveCandidates,
context_budget: 100,
});
await expect(call).rejects.toBeInstanceOf(HarnessError);
await expect(call).rejects.toThrow("stopped before its first answer");
// Nothing was sent, and no turn was spent trimming its way to an
// answer it could not write.
expect(seen).toHaveLength(0);
});
});
describe("runTextLoop repeated reads", () => {
@@ -2338,7 +2436,11 @@ describe("runTextLoop answer not sent", () => {
describe("runTextLoop over budget", () => {
test("tells a run whose own request is over the working context, once", async () => {
const brief = "x".repeat(30_000);
const note = oversizedRequestNote({ budget: 4_000 });
/**
* A phrase from `oversizedRequestNote`: the note's numbers are the
* loop's own arithmetic, so only its fixed words are matched here.
*/
const note = "larger than the working context this model may be sent";
const { generate, seen } = scripted([
{ text: "One piece.", tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"a"}` }] },
@@ -2364,7 +2466,7 @@ describe("runTextLoop over budget", () => {
});
test("says nothing when the transcript fits, or when trimming was enough", async () => {
const note = oversizedRequestNote({ budget: 20_000 });
const note = "larger than the working context this model may be sent";
const { generate, seen } = scripted([
{ text: "One.", tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"a"}` }] },
+121 -21
View File
@@ -16,6 +16,7 @@ import {
replyClosingRequiredNote,
replyDraftNote,
replyNoTextNote,
staticPromptOverBudgetNote,
tokensLowNote,
} from "@/src/data/harness-prompts";
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
@@ -26,9 +27,9 @@ import { logError } from "@/src/functions/backend/logger";
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
import { ReplyStatuses } from "@/src/dict/reply-status-dict";
import HarnessError from "../harness-error";
import isClosingTool, { SendReplyToolName } from "../tools/closing-tool-names";
import isClosingTool, { ClosingToolNames, SendReplyToolName } from "../tools/closing-tool-names";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
import loadToolsTool from "../tools/load-tools-tool";
import loadToolsTool, { LoadToolsToolName } from "../tools/load-tools-tool";
import repeatToolCallKey, { toolCallKey } from "../tools/repeat-tool-call-key";
import isRepeatableTool from "../tools/repeatable-tool-names";
import runToolCall from "../tools/run-tool-call";
@@ -53,6 +54,7 @@ import generateText from "./generate-text";
import pushUserTurn from "./push-user-turn";
import supersedeToolOutputs from "./supersede-tool-outputs";
import toolImagesTurn from "./tool-images-turn";
import workingContextTokens from "./working-context";
export type TextLoopStep = {
index: number;
@@ -72,8 +74,12 @@ type Params = {
messages: HarnessMessage[];
/**
* The run's tools. Deferred ones (`HarnessTool.deferred`) are listed
* by name and loaded with `load_tools`, when together they're large
* enough to be worth it (`AppData.HarnessDeferToolsMinChars`).
* by name and loaded with `load_tools` when they are large enough to
* be worth keeping out of every turn: an extension's definitions
* together past `AppData.HarnessDeferToolsMinChars`, or the bot's own
* (`HarnessTool.group`) past `AppData.HarnessDeferBuiltinToolsMinChars`
* and `AppData.HarnessDeferBuiltinToolsShare` of the working context.
* The tools that save or send the answer are never deferred.
*/
tools?: HarnessTool[];
max_steps?: RunLimit;
@@ -84,9 +90,10 @@ type Params = {
*/
max_prompt_tokens?: RunLimit;
/**
* The working context (`grabContextBudgetTokens`): the most each turn
* sends before old tool output is trimmed, whatever the model's
* window. Unlimited or left out, the window decides.
* A tighter cap on the working context (`grabContextBudgetTokens`),
* when the install set one: the most each turn sends before old tool
* output is trimmed. Unlimited or left out, the model's window decides
* (`workingContextTokens`).
*/
context_budget?: RunLimit;
signal?: AbortSignal;
@@ -232,6 +239,19 @@ export const WrapUpAnswerToolNames = [SendReplyToolName];
*/
export const WrapUpToolNames = [...WrapUpSaveToolNames, ...WrapUpHandOffToolNames, ...WrapUpAnswerToolNames];
/**
* Tools a run keeps loaded whatever their size: the ones a wrap up saves
* or answers with, the closing tools that end the run, and `load_tools`
* itself. Deferring any of them leaves a run that can no longer act.
*/
const KeepLoadedToolNames: readonly string[] = [...WrapUpToolNames, ...ClosingToolNames, LoadToolsToolName];
/**
* Rough characters per token for the tool definitions: the same estimate
* the transcript is sized with, so the two are compared on one scale.
*/
const DefinitionCharsPerToken = 3;
/**
* Saving turns a wrap up may take: the first, and one more when it reached
* for a tool it no longer has. After them the run answers with no tools.
@@ -415,13 +435,47 @@ export default async function runTextLoop({
}: Params): Promise<TextLoopResult> {
const candidates = await resolveCandidates();
/**
* Deferred tools wait to be loaded only when their definitions
* together are worth keeping out of every turn.
* The model the run is on, or will start on: its window sizes every
* turn (`workingContextTokens`) and decides whether the bot's own
* tools are worth keeping out of it.
*/
const deferrable = tools.filter((tool) => tool.deferred);
const defer =
deferrable.reduce((sum, tool) => sum + JSON.stringify(toolDefinition({ tool })).length, 0) >=
AppData.HarnessDeferToolsMinChars;
const start_model = (candidates.find((candidate) => candidate.key == planned_key) || candidates[0])?.model;
const start_context = workingContextTokens({
context_length: start_model?.context_length,
max_output_tokens: start_model?.max_output_tokens,
context_budget,
});
const definitionChars = ({ list }: { list: HarnessTool[] }) =>
list.reduce((sum, tool) => sum + JSON.stringify(toolDefinition({ tool })).length, 0);
/**
* What may wait to be loaded at all: the tools a wrap up saves or
* answers with, the closing tools and `load_tools` itself never do,
* since a run out of steps with its saving tools deferred would have
* nothing left to save with.
*/
const can_defer = ({ tool }: { tool: HarnessTool }) => Boolean(tool.deferred) && !KeepLoadedToolNames.includes(tool.name);
const builtin_deferrable = tools.filter((tool) => can_defer({ tool }) && tool.group);
const extension_deferrable = tools.filter((tool) => can_defer({ tool }) && !tool.group);
const builtin_chars = definitionChars({ list: builtin_deferrable });
const extension_chars = definitionChars({ list: extension_deferrable });
/**
* Extensions are deferred once they are heavy in absolute terms: an MCP
* server can be a hundred thousand characters on its own. The bot's own
* tools are deferred only when they are heavy *for this model*: at
* about 33k tokens of definitions they left a 131k-window model less
* than half its window for the conversation, while a 1M-window model
* holds them comfortably and pays a turn to load them for nothing.
*/
const defer_builtin =
builtin_chars >= AppData.HarnessDeferBuiltinToolsMinChars &&
builtin_chars / DefinitionCharsPerToken > start_context.tokens * AppData.HarnessDeferBuiltinToolsShare;
const defer_extensions = extension_chars >= AppData.HarnessDeferToolsMinChars;
const deferrable: HarnessTool[] = [
...(defer_builtin ? builtin_deferrable : []),
...(defer_extensions ? extension_deferrable : []),
];
const defer = deferrable.length > 0;
const deferred_names = new Set(deferrable.map((tool) => tool.name));
/**
* Loaded deferred tools, in the order they were loaded: their
* definitions go after the others, so the start of the list (and of
@@ -440,7 +494,7 @@ export default async function runTextLoop({
: tools;
const all_definitions = new Map(run_tools.map((tool) => [tool.name, toolDefinition({ tool })]));
const definitionsNow = () => [
...run_tools.filter((tool) => !defer || !tool.deferred).map((tool) => all_definitions.get(tool.name)!),
...run_tools.filter((tool) => !deferred_names.has(tool.name)).map((tool) => all_definitions.get(tool.name)!),
...loaded.map((name) => all_definitions.get(name)!),
];
const run_system = defer ? `${system}\n\n${deferredToolsNote({ tools: deferrable })}` : system;
@@ -492,7 +546,20 @@ export default async function runTextLoop({
const call_limits = {
steps: max_steps,
run_tokens: max_prompt_tokens ?? UnlimitedLimit,
context_tokens: context_budget ?? UnlimitedLimit,
/**
* The working context actually used, in tokens, not the setting:
* a bot asked to explain a cost has to be able to name the window
* it was held to, and "unlimited" told the user nothing when the
* real ceiling was 70% of a guessed window.
*/
context_tokens: start_context.tokens,
/**
* What the app itself spends of it before the conversation starts:
* the system prompt and the tool definitions, which are resent on
* every turn and which nothing may trim.
*/
system_tokens: Math.ceil(run_system.length / DefinitionCharsPerToken),
tools_tokens: Math.ceil(JSON.stringify(definitionsNow()).length / DefinitionCharsPerToken),
};
/**
* A step count to count against, for the loop itself: an unlimited run
@@ -754,29 +821,62 @@ export default async function runTextLoop({
: definitionsNow();
/**
* Sized for the model the run is on (or will start on). A fallback
* with a smaller window gets a 400 and the next model is tried.
* Sized for the model the run is on (or will start on): its own
* window, less the room its answer needs (`workingContextTokens`),
* never a fixed share of a guessed one. A provider that says the
* prompt was too long stops the run with its own message
* (`isContextOverflowError`), naming the real limit.
*/
const model = (candidates.find((c) => c.key == prefer_key) || candidates[0])?.model;
const working = workingContextTokens({
context_length: model?.context_length,
max_output_tokens: model?.max_output_tokens,
context_budget,
});
const fit = fitTranscriptToContext({
system: run_system,
transcript,
context_length: model?.context_length || AppData.HarnessUnknownContextWindow,
budget_tokens: typeof context_budget == "number" ? context_budget : undefined,
working_tokens: working.tokens,
tools_chars: JSON.stringify(definitions).length,
});
/**
* The app's own instructions and tool definitions are already past
* the working context on their own, so nothing trimmable can make
* room. A run that went on trimmed every tool result of every turn
* and answered from nothing: stop here and say what the arithmetic
* is, instead of blinding it (`staticPromptOverBudgetNote`).
*/
if (fit.over_budget == "static") {
const note = staticPromptOverBudgetNote({
working: working.tokens,
window: working.window,
assumed: working.assumed,
base: fit.base,
system: fit.system_tokens,
tools: fit.tools_tokens,
});
await traced({ kind: "event", index, name: "over_budget", text: note });
throw new HarnessError({ message: note, fatal: true });
}
/**
* Everything trimmable was trimmed and it still doesn't fit: what is
* over is what the user wrote, which is never cut. Told once, so it
* works in pieces and says what it could not reach instead of
* inventing the rest (`oversizedRequestNote`).
*/
if (fit.over_budget && !told_over_budget) {
if (fit.over_budget == "request" && !told_over_budget) {
told_over_budget = true;
const note = oversizedRequestNote({ budget: fit.budget });
const note = oversizedRequestNote({
budget: fit.budget,
base: fit.base,
conversation: fit.estimated_tokens - fit.base,
});
pushUserTurn({ transcript, content: note });
await traced({ kind: "event", index, name: "over_budget", text: note });
+60
View File
@@ -0,0 +1,60 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import workingContextTokens, { WorkingContextReserveMax, WorkingContextReserveMin } from "./working-context";
describe("workingContextTokens", () => {
test("a declared window keeps a tenth of it for the answer", () => {
const context = workingContextTokens({ context_length: 131_072 });
expect(context.window).toBe(131_072);
expect(context.assumed).toBe(false);
expect(context.reserve).toBe(13_107);
expect(context.tokens).toBe(117_965);
});
test("a 200,000 token window keeps 20,000 back", () => {
expect(workingContextTokens({ context_length: 200_000 }).tokens).toBe(180_000);
});
test("a 1,000,000 token window keeps the most a run ever reserves", () => {
const context = workingContextTokens({ context_length: 1_000_000 });
expect(context.reserve).toBe(WorkingContextReserveMax);
expect(context.tokens).toBe(936_000);
});
test("a model that declares its output size keeps exactly that back", () => {
const context = workingContextTokens({ context_length: 131_072, max_output_tokens: 4_096 });
expect(context.reserve).toBe(4_096);
expect(context.tokens).toBe(126_976);
});
test("a model with no declared window is worked to the install's assumption", () => {
const context = workingContextTokens({});
expect(context.window).toBe(AppData.HarnessUnknownContextWindow);
expect(context.assumed).toBe(true);
expect(context.tokens).toBe(AppData.HarnessUnknownContextWindow - WorkingContextReserveMax);
});
test("the install's cap holds a run below its window, never above it", () => {
expect(workingContextTokens({ context_length: 1_000_000, context_budget: 50_000 }).tokens).toBe(50_000);
expect(workingContextTokens({ context_length: 1_000_000, context_budget: 990_000 }).tokens).toBe(936_000);
});
test("an unlimited cap leaves the window deciding", () => {
expect(workingContextTokens({ context_length: 200_000, context_budget: "unlimited" }).tokens).toBe(180_000);
});
test("the reserve never swallows the window, on the smallest model", () => {
const context = workingContextTokens({ context_length: 12_000, max_output_tokens: 12_000 });
expect(context.reserve).toBe(11_999);
expect(context.tokens).toBe(1);
});
test("the smallest reserve is kept even on a tiny window", () => {
expect(workingContextTokens({ context_length: 50_000 }).reserve).toBe(WorkingContextReserveMin);
});
});
+91
View File
@@ -0,0 +1,91 @@
import { AppData } from "@/src/data/app-data";
import type { RunLimit } from "@/src/utils/run-limit";
type Params = {
/**
* The model's declared window, in tokens
* (`harness_models.context_length`), left out when its catalog never
* said.
*/
context_length?: number | null;
/**
* The room the model wants kept for its answer, when it declares one
* (`harness_models.max_output_tokens`).
*/
max_output_tokens?: number | null;
/**
* An optional tighter cap on the prompt (`grabContextBudgetTokens`).
* Unlimited or left out, the window decides.
*/
context_budget?: RunLimit;
};
/**
* The most a turn may send, and the arithmetic behind it.
*/
export type WorkingContext = {
/**
* The window the run works to: the model's own, or
* `AppData.HarnessUnknownContextWindow` when it never said.
*/
window: number;
/**
* The window is the install's assumption, not the model's own: the
* provider's refusal is then the only real limit, and the run says so
* when it hits one.
*/
assumed: boolean;
/**
* Tokens kept back for the model's answer.
*/
reserve: number;
/**
* What a turn may send: the window less the reserve, or less the
* install's own cap when that is smaller.
*/
tokens: number;
};
/**
* The least a run keeps for its answer.
*/
export const WorkingContextReserveMin = 8_000;
/**
* The most a run keeps for its answer, however big the window: a 1M
* window does not need a 100,000-token answer.
*/
export const WorkingContextReserveMax = 64_000;
/**
* The share of the window a run keeps for its answer when the model
* doesn't say what it needs. This replaced a flat 70% of the window,
* which turned an assumed 131,072-token window into a 91,750-token
* working context and left a run's own tool definitions most of it
* (`over_budget`, then every turn trimmed blind).
*/
export const WorkingContextReserveShare = 0.1;
/**
* The working context: the model's window less the room its answer
* needs, or the install's own cap when that is tighter.
*/
export default function workingContextTokens({ context_length, max_output_tokens, context_budget }: Params): WorkingContext {
const declared = Number(context_length || 0);
const assumed = !(declared > 0);
const window = assumed ? AppData.HarnessUnknownContextWindow : declared;
const reserve =
Number(max_output_tokens || 0) > 0
? Math.min(Number(max_output_tokens), Math.max(1, window - 1))
: Math.min(
WorkingContextReserveMax,
Math.max(WorkingContextReserveMin, Math.round(window * WorkingContextReserveShare)),
);
const from_window = Math.max(1, window - reserve);
const cap = typeof context_budget == "number" && context_budget > 0 ? context_budget : 0;
return {
window,
assumed,
reserve,
tokens: cap ? Math.min(from_window, cap) : from_window,
};
}
@@ -113,6 +113,12 @@ type Params = {
* refuses work, and `run-bot-reply` gates the tools to the allowlist.
*/
plan_mode?: boolean;
/**
* The plan whose step this reply works: the work its `send_reply` queues
* carries the plan, so that run's report ends on the card that moves the
* plan on.
*/
plan_id?: number | null;
};
/**
@@ -164,6 +170,7 @@ export default async function grabBotChatTools({
onTask,
onAttach,
plan_mode,
plan_id,
}: Params): Promise<HarnessTool[]> {
const bot_id = bot.id || 0;
const dirs = computerRunDirs({ bot_id, bot_kind: bot.kind, user_id, workspace_id });
@@ -191,6 +198,7 @@ export default async function grabBotChatTools({
run_kind,
onQueue,
plan_mode,
plan_id,
}),
...(computers.length
? [
+23 -5
View File
@@ -60,24 +60,42 @@ describe("Plan mode's tool gate", () => {
}
});
test("keeps a blocked tool's description, schema and deferral, so the model still sees what it is", async () => {
test("keeps a blocked tool's description and schema, and lists the bot's own tools now, so the model still sees what it is", async () => {
const deferred: HarnessTool = {
...tool("browser_navigate"),
description: "Open a page in the browser",
...tool("create_task"),
description: "Add a task to the tracker",
parameters: { type: "object" },
deferred: true,
group: "tasks",
timeout_ms: 5_000,
};
const planned = gatePlanModeTools({ tools: [deferred] })[0]!;
expect(planned.description).toBe("Open a page in the browser");
expect(planned.description).toBe("Add a task to the tracker");
expect(planned.parameters).toEqual({ type: "object" });
expect(planned.deferred).toBe(true);
/**
* A family tool is listed inline in a planning run: a write has to
* be visible to be refused by name, and a read has to be callable
* without a load step (`load_tools` is refused here too).
*/
expect(planned.deferred).toBe(false);
expect(planned.timeout_ms).toBe(5_000);
expect(planned.run).not.toBe(deferred.run);
});
test("leaves an extension tool deferred, since load_tools is refused here", () => {
const off: HarnessTool = { ...tool("exa__search"), deferred: true };
expect(gatePlanModeTools({ tools: [off] })[0]!.deferred).toBe(true);
});
test("lists an allowed tool it was holding off, so a read needs no load step", () => {
const off: HarnessTool = { ...tool("list_tasks"), deferred: true, group: "tasks" };
expect(gatePlanModeTools({ tools: [off] })[0]!.deferred).toBe(false);
});
test("holds a tool nobody named yet off, so the list stays an allowlist", async () => {
const [planned] = gatePlanModeTools({ tools: [tool("a_tool_shipped_later")] });
+11 -1
View File
@@ -73,13 +73,23 @@ function planModeRefusal({ name }: { name: string }) {
* `run` is replaced, and it throws so the call is reported as failed.
* `load_tools` is here too, so a deferred MCP or browser tool can never
* be pulled into a planning run.
*
* The bot's own tools (`groupTools` has named their family by now) are
* listed inline rather than deferred: the reads it is allowed (`list_tasks`,
* `read_file`) have to be callable without a loading step, and the writes it
* is refused have to be visible to be refused by name. Extensions stay as
* deferred as they were: `load_tools` is refused here, so listing their
* definitions inline would spend the run's context on tools it cannot call.
*/
export default function gatePlanModeTools({ tools }: { tools: HarnessTool[] }): HarnessTool[] {
const listed = ({ tool }: { tool: HarnessTool }) => (tool.group ? false : tool.deferred);
return tools.map((tool) =>
allowed.has(tool.name)
? tool
? { ...tool, deferred: listed({ tool }) }
: {
...tool,
deferred: listed({ tool }),
run: async () => {
throw new Error(planModeRefusal({ name: tool.name }));
},
@@ -22,8 +22,9 @@ type Args = {
/**
* The plan's current step is finished: the card checks it off with what it
* produced, and the app wakes the bot for the next one after this reply.
* A step is only ever finished by a run that did the work, one at a time.
* produced. The next step starts when the user answers the card the report
* ends on, so a step is only ever finished by a run that did the work, one
* at a time.
*/
export default function completePlanStepTool({ bot_id, session_id, in_run }: Params): HarnessTool<Args> {
let completed = false;
@@ -74,7 +75,7 @@ export default function completePlanStepTool({ bot_id, session_id, in_run }: Par
return `Step ${done.index + 1} is done: the card shows it. Carry on with step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}. Save your report for the end, when every step is done.`;
}
return `Step ${done.index + 1} is done: the card shows it. The next step starts on its own after this reply (step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}), so don't start it now. Write your report: two or three sentences on what this step produced.`;
return `Step ${done.index + 1} is done: the card shows it. The next step (step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}) starts when the user answers the card on your report, so don't start it now. Write your report: two or three sentences on what this step produced, and put the card up beside it.`;
},
};
}
@@ -5,7 +5,9 @@ import grabBotPlanTools from "./grab-bot-plan-tools";
* A run working a plan's step may only work it: writing another plan, or
* cancelling the one it was woken for, is the user's call on the card. A
* scheduled run has no card to approve anything on, so its plan starts
* itself and nothing is left for the bot to cancel.
* itself and nothing is left for the bot to cancel. A reply that isn't a
* step can't finish one either, or the plan would sit active with no card
* to start the next step from.
*/
const names = (tools: { name: string }[]) => tools.map((tool) => tool.name);
@@ -20,8 +22,8 @@ const build = (overrides: Parameters<typeof grabBotPlanTools>[0] | {} = {}) =>
});
describe("grabBotPlanTools", () => {
test("a chat reply can write a plan, change it, end it and finish its steps", () => {
expect(names(build())).toEqual(["create_plan", "cancel_plan", "update_plan", "complete_plan_step"]);
test("a chat reply can write a plan, change it and end it, but not finish a step", () => {
expect(names(build())).toEqual(["create_plan", "cancel_plan", "update_plan"]);
});
test("a run working a step can only change the plan and finish its step", () => {
@@ -35,6 +35,10 @@ type Params = {
* A run that is itself working a plan gets neither `create_plan` (the
* conversation already has one open) nor `cancel_plan` (whether the plan
* stands is the user's call), so the only thing it can do is work it.
*
* Only a step's own run can finish a step: a reply that isn't one would
* finish it with no card under its report, and the plan would sit active
* with nothing to start the next one.
*/
export default function grabBotPlanTools({ user_id, bot_id, session_id, workspace_id, on_step, approve, onPlan }: Params) {
const tools: HarnessTool[] = [];
@@ -48,7 +52,8 @@ export default function grabBotPlanTools({ user_id, bot_id, session_id, workspac
}
tools.push(updatePlanTool({ user_id, bot_id, session_id, onPlan }));
tools.push(completePlanStepTool({ bot_id, session_id, in_run: approve }));
if (on_step || approve) tools.push(completePlanStepTool({ bot_id, session_id, in_run: approve }));
return tools;
}
@@ -18,6 +18,11 @@ type Params = {
* approved plan is).
*/
plan_mode?: boolean;
/**
* The plan whose step this run works, when the card ends that step: its
* first option continues the plan, anything else pauses it.
*/
plan_id?: number | null;
/**
* Whether the run is a task, which stops and reports rather than waits.
*/
@@ -53,6 +58,7 @@ export default function askUserTool({
session_id,
workspace_id,
plan_mode,
plan_id,
in_task,
onAsk,
redact = (text) => text,
@@ -90,6 +96,7 @@ export default function askUserTool({
session_id,
workspace_id,
plan_mode: Boolean(plan_mode),
plan_id,
title: args.title?.trim() ? redact(args.title.trim()) : "",
questions: args.questions.map((item) => ({
question: redact(item.question),
+7
View File
@@ -23,6 +23,11 @@ type Params = {
computers: BUN_SQLITE_COBBLE_COMPUTERS[];
message_id?: number | string;
run_kind?: BrowserRunKind;
/**
* The plan whose step this work is: the run works that step and its
* report ends on the card that moves the plan on.
*/
plan_id?: number | null;
work: BotTaskWork;
/**
* The tool that asked, so a refusal tells the model to call that tool
@@ -47,6 +52,7 @@ export default async function queueBotTask({
computers,
message_id,
run_kind,
plan_id,
work,
tool_name,
}: Params): Promise<{ job_id: number; ahead: number; ask_id?: number }> {
@@ -94,6 +100,7 @@ export default async function queueBotTask({
params: {
...(work.max_steps ? { max_steps: work.max_steps } : {}),
...(run_kind ? { run_kind } : {}),
...(plan_id ? { plan_id: Number(plan_id) } : {}),
...(ask?.id ? { ask_id: Number(ask.id) } : {}),
},
});
+7
View File
@@ -30,6 +30,11 @@ type Params = {
* can't queue the work it was only meant to plan.
*/
plan_mode?: boolean;
/**
* The plan whose step this reply works: the work it queues carries the
* plan, so its report ends on the card that moves the plan on.
*/
plan_id?: number | null;
};
type Args = {
@@ -60,6 +65,7 @@ export default function sendReplyTool({
run_kind,
onQueue,
plan_mode,
plan_id,
}: Params): HarnessTool<Args> {
let queued: { job_id: number; ahead: number; ask_id?: number } | null = null;
@@ -149,6 +155,7 @@ export default function sendReplyTool({
computers,
message_id,
run_kind,
plan_id,
tool_name: "send_reply",
work: args.work,
});
+7
View File
@@ -25,6 +25,11 @@ type Params = {
* hidden session's reply queues never reaches the user's real browsers.
*/
run_kind?: BrowserRunKind;
/**
* The plan whose step this work is (a task run that hands its step on):
* the child run's report ends on the card that moves the plan on.
*/
plan_id?: number | null;
};
type Args = {
@@ -59,6 +64,7 @@ export default function startTaskTool({
computers,
message_id,
run_kind,
plan_id,
}: Params): HarnessTool<Args> {
const listed = computers
.map((computer) => `${computer.id} (${computer.name || computer.kind})`)
@@ -97,6 +103,7 @@ export default function startTaskTool({
computers,
message_id,
run_kind,
plan_id,
tool_name: "start_task",
work: {
title: args.title,
+25
View File
@@ -0,0 +1,25 @@
import type { HarnessTool } from "../types";
import { ToolGroups } from "./tool-groups";
/**
* Names the bot's own tools into their families (`ToolGroups`) so a run
* with a narrow window can defer whole families and load them by name
* (`runTextLoop` decides by size, so a model with room keeps them all
* inline). A tool in no family is left alone, and one an extension already
* deferred keeps its own flag.
*/
export default function groupTools({ tools }: { tools: HarnessTool[] }): HarnessTool[] {
const group_of = new Map<string, string>();
for (const [group, names] of Object.entries(ToolGroups)) {
for (const name of names) {
if (!group_of.has(name)) group_of.set(name, group);
}
}
return tools.map((tool) => {
const group = group_of.get(tool.name);
return group ? { ...tool, group, deferred: true } : tool;
});
}
+91
View File
@@ -0,0 +1,91 @@
import { describe, expect, test } from "bun:test";
import type { HarnessTool } from "../types";
import loadToolsTool, { LoadToolsToolName } from "./load-tools-tool";
const tool = ({ name, group }: { name: string; group?: string }): HarnessTool => ({
name,
description: `The ${name} tool.`,
schema: undefined as unknown as HarnessTool["schema"],
group,
deferred: true,
run: async () => "",
});
const deferred = [
tool({ name: "list_tasks", group: "tasks" }),
tool({ name: "create_task", group: "tasks" }),
tool({ name: "create_plan", group: "plans" }),
tool({ name: "exa__web_search_exa" }),
tool({ name: "exa__crawling_exa" }),
];
function loading() {
const loaded: string[][] = [];
const is_loaded = new Set<string>();
const loader = loadToolsTool({
deferred,
isLoaded: (name) => is_loaded.has(name),
onLoad: (names) => {
loaded.push(names);
for (const name of names) is_loaded.add(name);
},
});
return { loader, loaded };
}
describe(`loadToolsTool (${LoadToolsToolName})`, () => {
test("exact names load exactly those tools", async () => {
const { loader, loaded } = loading();
const result = await loader.run({ args: { names: ["list_tasks"] }, context: {} } as never);
expect(loaded).toEqual([["list_tasks"]]);
expect(String(result)).toContain("Loaded: list_tasks.");
});
test("a family's name loads the whole family", async () => {
const { loader, loaded } = loading();
await loader.run({ args: { names: ["tasks"] }, context: {} } as never);
expect(loaded).toEqual([["list_tasks", "create_task"]]);
});
test("a prefix loads every tool under it", async () => {
const { loader, loaded } = loading();
await loader.run({ args: { names: ["exa__*"] }, context: {} } as never);
expect(loaded).toEqual([["exa__web_search_exa", "exa__crawling_exa"]]);
});
test("a family and a name can be loaded in one call, each once", async () => {
const { loader, loaded } = loading();
await loader.run({ args: { names: ["tasks", "list_tasks", "create_plan"] }, context: {} } as never);
expect(loaded).toEqual([["list_tasks", "create_task", "create_plan"]]);
});
test("a tool already loaded is named as such, not loaded twice", async () => {
const { loader, loaded } = loading();
await loader.run({ args: { names: ["create_plan"] }, context: {} } as never);
const second = await loader.run({ args: { names: ["create_plan", "tasks"] }, context: {} } as never);
expect(loaded).toEqual([["create_plan"], ["list_tasks", "create_task"]]);
expect(String(second)).toContain("Already loaded: create_plan.");
});
test("a name nothing answers says so, without spoiling the rest", async () => {
const { loader, loaded } = loading();
const result = await loader.run({ args: { names: ["tasks", "no_such_tool"] }, context: {} } as never);
expect(loaded).toEqual([["list_tasks", "create_task"]]);
expect(String(result)).toContain("Not in the list: no_such_tool.");
expect(String(result)).toContain("family names");
});
});
+7 -4
View File
@@ -22,12 +22,13 @@ export const LoadToolsToolName = "load_tools";
* Brings deferred tools into the run (`runTextLoop`): the model sees them
* listed by name in its prompt and loads the ones it needs, rather than
* every turn carrying every extension's definitions. A name ending in `*`
* loads every deferred tool it starts.
* loads every deferred tool it starts; a family's name (`tasks`, `plans`)
* loads every tool in it.
*/
export default function loadToolsTool({ deferred, isLoaded, onLoad }: Params): HarnessTool<{ names: string[] }> {
return {
name: LoadToolsToolName,
description: `Loads tools from the "Tools you can load" list in your instructions, so you can call them from your next step. Give their exact names; "<prefix>*" loads every listed tool starting with the prefix (e.g. one server's). Load only what you're about to use.`,
description: `Loads tools from the "Tools you can load" list in your instructions, so you can call them from your next step. Give their exact names, a family's name to load all of it ("tasks"), or "<prefix>*" to load every listed tool starting with the prefix (e.g. one server's). Load only what you're about to use.`,
schema: z.object({
names: z.array(z.string().trim().min(1).max(200)).min(1).max(40),
}),
@@ -38,7 +39,7 @@ export default function loadToolsTool({ deferred, isLoaded, onLoad }: Params): H
for (const name of args.names) {
const matches = name.endsWith("*")
? deferred.filter((tool) => tool.name.startsWith(name.slice(0, -1)))
: deferred.filter((tool) => tool.name == name);
: deferred.filter((tool) => tool.name == name || tool.group == name);
if (!matches.length) missing.push(name);
@@ -53,7 +54,9 @@ export default function loadToolsTool({ deferred, isLoaded, onLoad }: Params): H
return [
fresh.length ? `Loaded: ${fresh.join(", ")}. Call them from your next step.` : "",
already.length ? `Already loaded: ${already.join(", ")}.` : "",
missing.length ? `Not in the list: ${missing.join(", ")}. Use the exact names under "Tools you can load".` : "",
missing.length
? `Not in the list: ${missing.join(", ")}. Use the exact names or family names under "Tools you can load".`
: "",
]
.filter(Boolean)
.join("\n");
+105
View File
@@ -0,0 +1,105 @@
/**
* The bot's own tools, by family (`groupTools`). A run short of window keeps
* a whole family out of every turn and the model loads it by name with
* `load_tools` (`deferredToolsNote`), while a model with room for them keeps
* every one inline and pays no loading turn at all.
*
* A family is worth a group when it is a coherent thing to load at once:
* the tracker's tools are used together or not at all, the same for a
* routine's or a knowledgebase's. The tools a run cannot act without
* (`send_reply`, `ask_user`, `suggest_next_steps`, `start_task`,
* `write_file`, `import_file`) are in none of them, and `runTextLoop`
* refuses to defer them whatever their size.
*/
export const ToolGroups: Record<string, readonly string[]> = {
computer: [
"computer_bash",
"computer_read_file",
"computer_write_file",
"computer_edit_file",
"search_computers",
"export_file",
"request_install",
"capture_secret",
"ask_user_to_take_over",
],
crew: [
"create_bot",
"update_bot",
"delete_bot",
"find_bot",
"create_workspace",
"update_workspace",
"delete_workspace",
"find_workspace",
"list_workspace_bots",
"list_workspace_people",
"set_user_workspace_role",
"set_bot_workspace_instructions",
"set_workspace_computer",
"add_bot_to_workspace",
"remove_bot_from_workspace",
"assign_computer",
"set_bot_type",
"delegate_task",
"hand_over_task",
"hand_over_schedule",
"ask_bot",
"list_asks",
"update_requester",
"answer_install_request",
],
extensions: [
"list_extensions",
"propose_custom_tool",
"update_custom_tool",
"propose_mcp_server",
"update_mcp_server",
"propose_skill",
"update_skill",
"delete_extension",
"set_extension_access",
],
files: [
"list_files",
"read_file",
"copy_file",
"move_file",
"delete_file",
"make_pdf",
"transform_image",
"generate_image",
"generate_video",
],
graphics: ["create_graphic", "update_graphic", "read_graphic", "list_graphics"],
hooks: ["list_hooks", "propose_hook", "pause_hook", "delete_hook", "search_hook_calls", "read_hook_call"],
knowledgebase: [
"list_knowledgebases",
"search_knowledgebase",
"read_knowledgebase_document",
"save_knowledgebase",
"add_knowledgebase_document",
"delete_knowledgebase_document",
"delete_knowledgebase",
"retry_failed_documents",
"reindex_knowledgebase",
],
memory: ["update_memory", "update_instructions", "set_picture", "read_settings", "read_message_usage"],
plans: ["create_plan", "update_plan", "cancel_plan", "complete_plan_step"],
schedules: [
"create_schedule",
"update_schedule",
"delete_schedule",
"list_schedules",
"report_run_failed",
],
secrets: ["request_secret", "show_secret"],
sessions: [
"search_past_sessions",
"read_past_session",
"send_message",
"continue_in_new_session",
"react_to_message",
],
tasks: ["list_tasks", "create_task", "update_task", "delete_task"],
};
@@ -4,6 +4,7 @@ import { WrapUpHandOffToolNames, WrapUpSaveToolNames } from "@/src/harness/text/
import { WritingToolNames } from "./writing-tool-names";
import { AppCardRefToolNames, WorkStartingTools } from "@/src/utils/reply-claim-problems";
import { AppStateTools } from "@/src/utils/reply-app-state-claims";
import PlanWorkStartingTools from "@/src/utils/plan-work-starting-tools";
import { PlanModeToolNames } from "./bot/plan-mode-tools";
/**
@@ -44,6 +45,7 @@ async function declaredToolNames() {
const Lists: Record<string, readonly string[]> = {
WorkStartingTools,
PlanWorkStartingTools,
AppCardRefToolNames,
AppStateTools,
WritingToolNames,
+7
View File
@@ -107,6 +107,13 @@ export type HarnessTool<Args = any> = {
* definitions would otherwise ride along on every turn.
*/
deferred?: boolean;
/**
* The bot's own tools are named by group (`tasks`, `plans`, `files`,
* ...) so a run short of window can keep a whole family out of every
* turn and load it by name, while a model with room keeps them all
* inline (`groupTools`). Extensions have none: they are deferred whole.
*/
group?: string;
/**
* This call's deadline, overriding `AppData.HarnessToolTimeoutMs`: a
* bigger one for a tool with its own slow work, `null` for none at all
+8
View File
@@ -80,6 +80,14 @@ export type HarnessCallLimits = {
steps: RunLimit | null;
run_tokens: RunLimit | null;
context_tokens: RunLimit | null;
/**
* How much of the working context the app's own prompt spends before
* the conversation: the system prompt and the tool definitions, resent
* on every turn. A bot asked to explain why a run had room for so
* little needs both halves, not just the total.
*/
system_tokens?: number;
tools_tokens?: number;
};
export type HarnessUsageCall = {
+5 -4
View File
@@ -6,6 +6,7 @@ import swipeGesture, {
IdleSwipeGesture,
type SwipeGesture,
} from "@/src/utils/swipe-gesture";
import touchInField from "@/src/utils/touch-in-field";
/**
* Below this width the rail is a slide-over (Tailwind's `md`), so the
@@ -15,11 +16,10 @@ import swipeGesture, {
const PhoneMaxWidth = 768;
/**
* What a touch on belongs to instead of the page: a field being typed in,
* a code editor, or a panel the app slid in itself.
* What a touch on belongs to instead of the page: a panel the app slid in
* itself. A field is `touchInField`.
*/
const OwnedTargets =
"input, textarea, select, [contenteditable='true'], .cm-editor, [data-no-swipe]";
const OwnedTargets = "[data-no-swipe]";
type Params = {
/**
@@ -38,6 +38,7 @@ type Params = {
*/
function ownsTouch({ target }: { target: EventTarget | null }): boolean {
if (!(target instanceof Element)) return true;
if (touchInField({ target })) return true;
if (target.closest(OwnedTargets)) return true;
for (let node: Element | null = target; node; node = node.parentElement) {
+24 -7
View File
@@ -23,6 +23,11 @@ type Params = {
* One folder of the files browser. The page's own copy is used when it is
* the folder asked for and nothing is searched; anything else loads from
* the API, so a page never carries the whole volume.
*
* A loaded folder is only ever handed back for the volume and path it
* belongs to: opening another folder shows its own name and a loading
* line, never the previous folder's entries (which would still be
* clickable, and open the folder the user just left).
*/
export default function useStorageFolder({ spec, path, search, page_folder }: Params) {
const from_page = Boolean(
@@ -33,21 +38,22 @@ export default function useStorageFolder({ spec, path, search, page_folder }: Pa
page_folder.path == path &&
!search,
);
const [folder, set_folder] = useState<StorageFolderPayload | null>(
from_page ? page_folder || null : null,
const request_key = folderKey({ spec, path });
const [loaded, set_loaded] = useState<{ key: string; folder: StorageFolderPayload | null } | null>(
from_page && page_folder ? { key: request_key, folder: page_folder } : null,
);
const [loading, set_loading] = useState(!from_page && Boolean(spec));
const [error, set_error] = useState<string>();
useEffect(() => {
if (!spec) {
set_folder(null);
set_loaded(null);
set_loading(false);
return;
}
if (from_page) {
set_folder(page_folder || null);
set_loaded({ key: request_key, folder: page_folder || null });
set_loading(false);
set_error(undefined);
return;
@@ -77,12 +83,12 @@ export default function useStorageFolder({ spec, path, search, page_folder }: Pa
set_loading(false);
if (!res?.success || !res.singleRes) {
set_folder(null);
set_loaded({ key: request_key, folder: null });
set_error(res?.msg || `Couldn't open that folder.`);
return;
}
set_folder(res.singleRes);
set_loaded({ key: request_key, folder: res.singleRes });
};
load().catch(() => {});
@@ -90,5 +96,16 @@ export default function useStorageFolder({ spec, path, search, page_folder }: Pa
return () => controller.abort();
}, [spec?.volume, spec?.owner_id, path, search, from_page, page_folder]);
return { folder, loading, error };
const folder = loaded?.key == request_key ? loaded.folder : null;
const pending = Boolean(spec) && loaded?.key != request_key;
return { folder, loading: loading || pending, error };
}
/**
* What a loaded folder belongs to: its volume, its owner and its path. A
* search is left out, since filtered entries are still that folder's.
*/
function folderKey({ spec, path }: { spec: Params["spec"]; path: string }) {
return `${spec?.volume || ""}:${spec?.owner_id ?? ""}:${path}`;
}
+120
View File
@@ -0,0 +1,120 @@
"use client";
import { useEffect, useRef, type RefObject } from "react";
import { AppData } from "@/src/data/app-data";
import swipeGesture, {
IdleSwipeGesture,
type SwipeGesture,
} from "@/src/utils/swipe-gesture";
import touchInField from "@/src/utils/touch-in-field";
type Params = {
/** The panel itself: only a finger that lands on it counts. */
panel_ref: RefObject<HTMLElement | null>;
/** Only while it is open; a panel that is closed keeps no listener. */
enabled: boolean;
/** The way back off the edge the panel slid in from. */
direction: "left" | "right";
on_close: () => void;
};
/**
* Closes an open side panel with a phone swipe back towards the edge it slid
* in from, where the page's own swipes are blocked on it (`data-no-swipe`).
* It reads the finger on the panel alone, so the panel that is open is the
* one that answers, and leaves the page's swipe hook to the page.
*
* The thresholds and the state machine are `swipe-gesture.ts`, the same ones
* the page's swipes use: a flick, not a long drag, and one that is clearly
* more sideways than up or down.
*/
export default function useSwipeToClose({
panel_ref,
enabled,
direction,
on_close,
}: Params) {
const close = useRef(on_close);
close.current = on_close;
useEffect(() => {
const panel = panel_ref.current;
if (!panel || !enabled) return;
let gesture: SwipeGesture = IdleSwipeGesture;
let touched_at = 0;
const restart = () => {
gesture = IdleSwipeGesture;
};
const onStart = (event: TouchEvent) => {
restart();
if (event.touches.length != 1) return;
if (document.getElementById("twui-modal-root")?.childElementCount) return;
if (touchInField({ target: event.target })) return;
const touch = event.touches[0];
if (!touch) return;
touched_at = Date.now();
gesture = swipeGesture({
gesture: IdleSwipeGesture,
input: { type: "start", x: touch.clientX, y: touch.clientY },
}).gesture;
};
const onMove = (event: TouchEvent) => {
if (!gesture.touching) return;
const touch = event.touches[0];
if (!touch || event.touches.length != 1) {
restart();
return;
}
/**
* A finger that has rested on the panel, or that is selecting
* text, is reading it, not pushing it away.
*/
if (Date.now() - touched_at > AppData.MobileSwipeMaxMs) {
restart();
return;
}
if (window.getSelection()?.toString()) {
restart();
return;
}
const step = swipeGesture({
gesture,
input: { type: "move", x: touch.clientX, y: touch.clientY },
});
gesture = step.gesture;
if (step.swipe != direction) return;
restart();
close.current();
};
panel.addEventListener("touchstart", onStart, { passive: true });
panel.addEventListener("touchmove", onMove, { passive: true });
panel.addEventListener("touchend", restart);
panel.addEventListener("touchcancel", restart);
return () => {
panel.removeEventListener("touchstart", onStart);
panel.removeEventListener("touchmove", onMove);
panel.removeEventListener("touchend", restart);
panel.removeEventListener("touchcancel", restart);
};
}, [panel_ref, enabled, direction]);
}
@@ -36,7 +36,7 @@ export function composerKnowledgebasesCopy({
Icon: Library,
one: "knowledgebase",
many: "knowledgebases",
empty_label: "Add knowledge",
empty_label: "knowledge",
title: `Knowledgebases ${bot_name} searches here`,
some: "Before it answers, it searches these for passages that fit, and it can search them again while it works. Remove one to take it away, or add another below.",
none: "It has none yet. Give it a knowledgebase below, or make one under Settings, under Knowledgebases.",
@@ -0,0 +1,11 @@
import { createContext } from "react";
/**
* The id of the user's newest message in the thread, and the id of the
* message being rendered. An ask written in a message (a take-over) is
* waiting for them only while no user message follows it, so handing the
* computer back - a chat message - ends the wait. Both are null outside a
* thread, where neither is known and nothing is said to be waiting.
*/
export const LastUserMessageContext = createContext<number | null>(null);
export const MessageIdContext = createContext<number | null>(null);
@@ -3,11 +3,11 @@ import type { APIResponseObject } from "@moduletrace/bunext/types";
import type { BotIdRequest } from "@/src/schemas/bot-schema";
/**
* A bot's core instructions, for its edit form.
* A bot's core instructions and memory, for its panel.
*/
export default async function fetchBotInstructions({ bot_id }: BotIdRequest) {
return await fetchApi<BotIdRequest, APIResponseObject<{ system_prompt: string }>>(
return await fetchApi<BotIdRequest, APIResponseObject<{ system_prompt: string; memory: string }>>(
`/api/admin/bots/bot-instructions`,
{ method: "POST", body: { bot_id } },
);
}
}
@@ -6,14 +6,14 @@ import type { BotPlanView } from "@/src/types";
type Params = {
plan_id: number;
/**
* Approve it, pick it back up, pause it, or end it.
* Approve it, pick it back up, start its next step, pause it, or end it.
*/
status: Extract<BotPlanState, "active" | "paused" | "cancelled">;
};
/**
* Moves a plan from its card. Approving it (or picking it back up) wakes
* the bot for the step it stands on, so the plan carries on by itself.
* Moves a plan from its card. Approving it, picking it back up, or Continue
* wakes the bot for the step it stands on.
*/
export default async function setBotPlanState({ plan_id, status }: Params) {
return await fetchApi<Params, APIResponseObject<BotPlanView>>(`/api/admin/bot-plans/set-plan-status`, {
@@ -1,7 +1,6 @@
import { useState } from "react";
import useServerEvent from "@/src/hooks/use-server-event";
import type { BotUpdatedData } from "@/src/types";
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
import type { BotUpdatedData, ComputerWithStatus } from "@/src/types";
import type { ComputerViewMode } from "@/src/dict/computer-dict";
import setBotComputer from "../(functions)/set-bot-computer";
@@ -20,7 +19,7 @@ export type BotComputers = {
/**
* The bot's computers, the one it's on first.
*/
computers: BUN_SQLITE_COBBLE_COMPUTERS[];
computers: ComputerWithStatus[];
/**
* The computer being switched to, while the switch runs.
*/
@@ -38,7 +37,7 @@ type Params = {
* In a workspace, switching changes the workspace's default computer.
*/
workspace_id?: number | null;
computers: BUN_SQLITE_COBBLE_COMPUTERS[];
computers: ComputerWithStatus[];
};
/**
@@ -4,23 +4,25 @@ import fetchBotInstructions from "../(functions)/fetch-bot-instructions";
type Params = {
bot_id: number;
/**
* Loads each time this turns true (the edit form opens), so the form
* starts from what was last saved.
* Loads each time this turns true (the panel opens), so its forms start
* from what was last saved.
*/
enabled: boolean;
};
/**
* The bot's core instructions for its edit form, loaded when it opens:
* page props leave them out of every bot row.
* The bot's core instructions and memory for its panel, loaded when it
* opens: page props leave them out of every bot row.
*/
export default function useBotInstructions({ bot_id, enabled }: Params) {
const [system_prompt, setSystemPrompt] = useState<string>();
const [memory, setMemory] = useState<string>();
const [error, setError] = useState<string>();
useEffect(() => {
/** Cleared on close, so the next open never shows an old copy. */
setSystemPrompt(undefined);
setMemory(undefined);
setError(undefined);
if (!enabled || !bot_id) return;
@@ -33,6 +35,7 @@ export default function useBotInstructions({ bot_id, enabled }: Params) {
if (res.success && res.singleRes) {
setSystemPrompt(res.singleRes.system_prompt);
setMemory(res.singleRes.memory);
} else {
setError(res.msg || "Couldn't load the instructions.");
}
@@ -46,5 +49,5 @@ export default function useBotInstructions({ bot_id, enabled }: Params) {
};
}, [enabled, bot_id]);
return { system_prompt, error };
}
return { system_prompt, memory, error };
}
@@ -21,8 +21,8 @@ type Params = {
/**
* A reply step pushed for the open session (`server:bot-job-update` with no
* task) means a reply is due here, even when the bot has the last word: the
* app queues a plan's next step itself, so nothing in the thread's last
* message says it is coming.
* app queues a plan's step itself on approval and on the card under the last
* one, so nothing in the thread's last message says it is coming.
*/
export default function useOpenReplyJobs({ bot_id, session_id, on_open_jobs }: Params) {
useServerEvent({
@@ -0,0 +1,28 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import BotComputerPreview from "./bot-computer-preview";
function render() {
return renderToString(
<BotComputerPreview
computer_id={7}
name="Dev box"
onOpen={() => {}}
/>,
);
}
describe("BotComputerPreview", () => {
test("it shows the computer's live browser, view only", () => {
const html = render();
expect(html).toContain('src="/computers/7/desktop/"');
expect(html).toContain("pointer-events-none");
});
test("a click opens it in the viewer", () => {
const html = render();
expect(html).toContain('aria-label="Open Dev box in the viewer"');
});
});
@@ -0,0 +1,43 @@
import Button from "@moduletrace/twui/layout/Button";
import Stack from "@moduletrace/twui/layout/Stack";
import { Maximize2 } from "lucide-react";
import ComputerViewFrame from "@/src/components/general/computer-view-frame";
type Props = {
computer_id: number;
name: string;
/**
* Opens the computer in the viewer, larger.
*/
onOpen: () => void;
};
/**
* The bot's computer live and small, in its panel's Tools tab, so the user
* sees what it is doing without leaving the conversation. The frame takes no
* pointer events, or the panel could not be scrolled past it; a click opens
* the viewer instead.
*/
export default function BotComputerPreview({ computer_id, name, onOpen }: Props) {
return (
<Stack className="relative w-full h-44 mt-2 overflow-hidden rounded-default border border-solid border-hairline bg-sunken">
<Stack className="absolute inset-0 pointer-events-none">
<ComputerViewFrame computer_id={computer_id} name={name} mode="browser" />
</Stack>
<Button
type="button"
variant="ghost"
color="text"
title={`Open ${name} in the viewer`}
aria-label={`Open ${name} in the viewer`}
onClick={onOpen}
className="absolute inset-0 w-full h-full p-0! rounded-none! focus-visible:ring-2 focus-visible:ring-ink"
buttonContentProps={{ className: "absolute right-2 bottom-2" }}
>
<Stack className="p-1.5 rounded-default bg-paper/90 border border-solid border-hairline text-ink-secondary">
<Maximize2 size={14} aria-hidden />
</Stack>
</Button>
</Stack>
);
}
@@ -0,0 +1,124 @@
import { useState } from "react";
import Form from "@moduletrace/twui/form/Form";
import Stack from "@moduletrace/twui/layout/Stack";
import CodeEditor from "@/src/components/general/code-editor";
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
type Props = {
bot_id: number;
bot_name: string;
/**
* Its core memory, from the panel's read.
*/
memory: string;
/**
* Where the conversation is, so its memory there is edited beside it.
*/
workspace_id?: number | null;
workspace_name?: string | null;
workspace_memory?: string;
onCancel?: () => void;
};
/**
* The bot panel's memory tab: what it keeps in mind everywhere, and (in a
* workspace) what it keeps in mind there. Both are markdown, replaced whole;
* the bot's memory of each person stays its own.
*/
export default function BotMemoryForm({
bot_id,
bot_name,
memory,
workspace_id,
workspace_name,
workspace_memory = "",
onCancel,
}: Props) {
const [core, setCore] = useState(memory);
const [here, setHere] = useState(workspace_memory);
const [loading, setLoading] = useState(false);
const [saved, setSaved] = useState(false);
const [error, setError] = useState<string>();
const submit = async () => {
if (loading) return;
if (!window.confirm(`Save ${bot_name}'s memory?`)) return;
setLoading(true);
setError(undefined);
setSaved(false);
try {
const coreRes = await postAdminApi({
path: "bots/update-bot-memory",
body: { bot_id, memory: core },
});
if (!coreRes.success) {
setError(coreRes.msg || "Couldn't save its memory.");
return;
}
if (workspace_id) {
const hereRes = await postAdminApi({
path: "workspaces/update-bot",
body: { workspace_id, bot_id, memory: here },
});
if (!hereRes.success) {
setError(
`Saved its memory everywhere, but not in ${workspace_name || "this workspace"}: ${hereRes.msg || "the save failed"}`,
);
return;
}
}
setSaved(true);
} catch {
setError("Couldn't save its memory.");
} finally {
setLoading(false);
}
};
return (
<Form onSubmit={submit} className="w-full gap-4! items-stretch">
<CodeEditor
title="Memory"
content={memory}
mode="markdown"
placeholder="What it should keep in mind wherever it works..."
info={`What ${bot_name} keeps in mind everywhere it works, for everyone. Markdown, replaced whole.`}
className="h-52"
onChange={(value) => {
setCore(value);
setSaved(false);
}}
/>
{workspace_id ? (
<CodeEditor
title={`Memory in ${workspace_name || "this workspace"}`}
content={workspace_memory}
mode="markdown"
placeholder="What it should keep in mind here..."
info={`What ${bot_name} keeps in mind while it works here, for everyone in this workspace.`}
className="h-40"
onChange={(value) => {
setHere(value);
setSaved(false);
}}
/>
) : null}
<AddFormActions
submit_label="Save"
loading={loading}
error={error}
notice={saved ? "Saved." : undefined}
onCancel={onCancel}
/>
</Form>
);
}

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