Compare commits

...
13 Commits
Author SHA1 Message Date
tben a5dbde1da7 Release 0.27.8
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
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
99 changed files with 3002 additions and 455 deletions
+5 -4
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.27.4",
"version": "0.27.8",
"module": "index.ts",
"type": "module",
"private": true,
+4 -1
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";
@@ -714,7 +715,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(),
+5 -2
View File
@@ -51,6 +51,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";
@@ -696,7 +697,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
@@ -727,7 +729,8 @@ export default async function runBotTask({
...connectors.tools,
...skills.tools,
...knowledge.tools,
],
],
}),
max_steps,
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
+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,
+33 -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,6 +735,21 @@ 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.
+38 -8
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
@@ -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({
@@ -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 || [];
@@ -40,4 +40,25 @@ describe("shouldAdoptConnectorAccount", () => {
false,
);
});
test("skips a stranger once the provider lists none of the app's accounts", () => {
expect(
shouldAdoptConnectorAccount({
status: "connected",
reconnect: false,
claimed: false,
free_slot: true,
wiped: true,
}),
).toBe(false);
expect(
shouldAdoptConnectorAccount({
status: "connected",
reconnect: false,
claimed: true,
free_slot: true,
wiped: true,
}),
).toBe(true);
});
});
@@ -12,6 +12,12 @@ type Params = {
* its own sign-in (claimed).
*/
free_slot: boolean;
/**
* The provider lists none of the accounts the app knows: they were
* replaced there, so no stranger takes their place (the cards offer
* Reconnect instead).
*/
wiped?: boolean;
};
/**
@@ -21,8 +27,15 @@ type Params = {
* provider can't pile up as four rows of the same mailbox; a second account
* appears by signing in again, which claims its own row.
*/
export default function shouldAdoptConnectorAccount({ status, reconnect, claimed, free_slot }: Params) {
export default function shouldAdoptConnectorAccount({
status,
reconnect,
claimed,
free_slot,
wiped = false,
}: Params) {
if (reconnect || claimed) return true;
if (wiped) return false;
return status == "connected" && free_slot;
}
@@ -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();
});
@@ -44,13 +44,18 @@ 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)
.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
@@ -58,10 +63,16 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
* `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));
const seen = new Set(accounts.map((account) => account.provider_account_id));
const now = Date.now();
/**
* The provider lists none of the accounts the app knows: they were
* replaced there (a sign-in made outside the app), so its leftover takes
* no card and the known ones offer Reconnect.
*/
const wiped = local.length > 0 && !local.some((row) => seen.has(String(row.provider_account_id || "")));
/**
* The app's one free card: a live row still listed by the provider holds
* it. An account arriving without a sign-in here (an older attempt at
@@ -69,13 +80,20 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
*/
let free_slot = !local.some((row) => row.status == "connected" && seen.has(String(row.provider_account_id || "")));
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 = free_slot ? 0 : null;
@@ -87,9 +105,10 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
if (
!shouldAdoptConnectorAccount({
status: account.status,
reconnect: Boolean(reconnect_id),
reconnect: Boolean(reconnect_id) || (account.status == "connected" && Boolean(reconnect_row)),
claimed: claimed.has(provider_account_id),
free_slot,
wiped,
})
)
continue;
@@ -100,8 +119,11 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
account,
fallback_label: label,
reconnect_id,
reconnect_row: account.status == "connected" ? reconnect_row : null,
});
if (account.status == "connected" && reconnect_row) reconnect_row = null;
if (account.status != "connected") continue;
if (free_slot) free_slot = false;
@@ -138,6 +160,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;
@@ -148,9 +176,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) {
@@ -200,42 +234,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.
* When the provider's name differs from the label the user chose, the one
* dead row for this app is still the row a new sign-in takes over.
* 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 named_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 || [])
: [];
const dead = named_dead.length
? named_dead
: ((
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status IN ('revoked', 'expired') ORDER BY id ASC`,
values: [connector_id, user_id],
})
).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,
],
});
@@ -249,7 +266,7 @@ 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++) {
@@ -303,7 +320,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,
@@ -8,6 +8,14 @@ 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.
@@ -54,8 +62,20 @@ async function readCachedHeaders({ headers }: { headers: string | null }): Promi
* 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 {
@@ -92,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`,
@@ -113,8 +136,6 @@ export default async function ensureConnectorEndpoint({
}
}
await assertAccountStillThere({ connector, provider, user_id, account, now });
const tools = connector.tools
.map((tool) => tool.name)
.filter((name) => !connector.excluded_tools.includes(name));
@@ -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
+21 -5
View File
@@ -3,14 +3,30 @@ 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.
*/
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: 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) {
loose.push(tool);
continue;
}
families.set(tool.group, [...(families.get(tool.group) ?? []), tool.name]);
}
const lines = [
...[...families].map(([group, names]) => `- ${group}: ${names.join(", ")} (load the family by its name)`),
...loose.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 }) {
@@ -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,
};
}
+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 }));
},
+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"],
};
+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]);
}
@@ -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 } },
);
}
}
@@ -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 };
}
@@ -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>
);
}
@@ -0,0 +1,26 @@
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { ReactNode } from "react";
type Props = {
title: string;
/**
* One line under the title, saying what the section is.
*/
description: string;
children?: ReactNode;
};
/**
* One labelled part of the bot panel's tools tab: what it is, then its
* list.
*/
export default function BotPanelSection({ title, description, children }: Props) {
return (
<Stack className="w-full gap-1! items-stretch pb-4 border-0 border-b border-solid border-hairline last:border-b-0 last:pb-0">
<Span className="text-[13px] leading-[18px] font-bold text-ink">{title}</Span>
<Span className="text-[13px] leading-[18px] text-ink-secondary">{description}</Span>
{children}
</Stack>
);
}
@@ -1,6 +1,6 @@
"use client";
import { useContext, useEffect } from "react";
import { useContext, useEffect, useState } from "react";
import Button from "@moduletrace/twui/layout/Button";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
@@ -10,19 +10,29 @@ import Loading from "@moduletrace/twui/elements/Loading";
import { X } from "lucide-react";
import SidePanel from "@/src/components/general/side-panel";
import BotAvatar from "@/src/components/general/bot-avatar";
import TabButton from "@/src/components/general/tab-button";
import type { BotFace } from "@/src/dict/bot-dict";
import botStoneProps from "@/src/utils/bot-stone-props";
import { BotPanelOpenEvent } from "@/src/utils/bot-panel-open-event";
import type { BotWithLastMessage } from "@/src/types";
import type { BUN_SQLITE_COBBLE_WORKSPACES } from "@/db/types/db";
import BotForm from "@/src/layouts/bots/(partials)/bot-form";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import useBotInstructions from "../(hooks)/use-bot-instructions";
import useWorkspaceBotInstructions from "../(hooks)/use-workspace-bot-instructions";
import BotMemoryForm from "./bot-memory-form";
import BotPanelTrigger from "./bot-panel-trigger";
import BotToolsTab from "./bot-tools-tab";
type Props = {
bot: BotWithLastMessage;
/**
* The workspace the conversation is in, so its memory and instructions
* there are edited too.
*/
workspace?: BUN_SQLITE_COBBLE_WORKSPACES | null;
/**
* The header owns it, since the avatar and the name both open the panel.
*/
@@ -31,22 +41,37 @@ type Props = {
on_close: () => void;
};
type PanelTab = "settings" | "memory" | "tools";
/**
* The bot's profile (picture, name, job, colour, instructions) to edit,
* sliding in from the right over the conversation, for super admins and
* admins. The avatar and the name beside it open it, and so does a swipe from
* the right on a phone (`BotPanelOpenEvent`, sent by the layout, so a page
* without a conversation has nobody listening). The instructions load when
* it opens, and Escape, the backdrop or the X closes it.
* The bot's profile (picture, name, job, colour, instructions), its memory
* and what it works with (computer, tools, knowledgebases) to edit, sliding
* in from the right over the conversation, for super admins and admins. The
* avatar and the name beside it open it, and so does a swipe from the right
* on a phone (`BotPanelOpenEvent`, sent by the layout, so a page without a
* conversation has nobody listening). The tab's data loads when it opens,
* and Escape, the backdrop or the X closes it.
*/
export default function BotPanel({ bot, open, on_open, on_close }: Props) {
export default function BotPanel({ bot, workspace, open, on_open, on_close }: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
const { system_prompt, error } = useBotInstructions({
const [tab, setTab] = useState<PanelTab>("settings");
const workspace_id = Number(workspace?.id) || 0;
const { system_prompt, memory, error } = useBotInstructions({
bot_id: Number(bot.id) || 0,
enabled: open && can_edit,
});
const workspace_instructions = useWorkspaceBotInstructions({
workspace_id,
bot_id: Number(bot.id) || 0,
enabled: open && can_edit && Boolean(workspace_id) && tab == "memory",
});
const memory_ready =
system_prompt != undefined &&
memory != undefined &&
(!workspace_id || Boolean(workspace_instructions.instructions));
const loaded_error = error || workspace_instructions.error;
useTopModalEscape({ onClose: on_close, enabled: open });
@@ -76,7 +101,6 @@ export default function BotPanel({ bot, open, on_open, on_close }: Props) {
open={open}
onClose={on_close}
label={`Edit ${name}`}
className="w-[420px] max-w-[92vw]"
>
<Row className="shrink-0 gap-3! flex-nowrap items-center px-4 py-3 border-0 border-b border-solid border-hairline">
<Stack className="shrink-0">
@@ -102,26 +126,74 @@ export default function BotPanel({ bot, open, on_open, on_close }: Props) {
<X size={18} aria-hidden />
</Button>
</Row>
<Row
role="tablist"
aria-label={`Edit ${name}`}
className="shrink-0 gap-1! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline"
>
<TabButton title="Settings" active={tab == "settings"} onPick={() => setTab("settings")} />
<TabButton title="Memory" active={tab == "memory"} onPick={() => setTab("memory")} />
<TabButton title="Tools" active={tab == "tools"} onPick={() => setTab("tools")} />
</Row>
<Stack className="grow min-h-0 overflow-y-auto gap-1! items-stretch px-4 pt-4 pb-6">
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{bot.kind == "coordinator"
? "The coordinator keeps its name. Give it a picture, or change its core instructions."
: `${name}'s core instructions apply everywhere. What it does in one workspace is under Instructions here in the menu of its conversation there.`}
</Span>
{!open ? null : system_prompt != undefined ? (
<BotForm
bot={{ ...bot, system_prompt }}
onCancel={on_close}
{open && tab == "settings" ? (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{bot.kind == "coordinator"
? "The coordinator keeps its name. Give it a picture, or change its core instructions."
: `${name}'s core instructions apply everywhere. What it does in one workspace is under Instructions here in the menu of its conversation there.`}
</Span>
{system_prompt != undefined ? (
<BotForm
bot={{ ...bot, system_prompt }}
onCancel={on_close}
/>
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{loaded_error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
) : null}
{open && tab == "memory" ? (
memory_ready ? (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${name} keeps in mind, and can add to itself as it works.`}
</Span>
<BotMemoryForm
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={memory || ""}
workspace_id={workspace_id || undefined}
workspace_name={workspace?.name}
workspace_memory={workspace_instructions.instructions?.memory || ""}
onCancel={on_close}
/>
</>
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{loaded_error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)
) : null}
{open && tab == "tools" ? (
<BotToolsTab
bot={bot}
workspace_id={workspace_id || null}
initial={pageProps?.bot_extensions}
has_browsers={Boolean(pageProps?.has_browsers)}
open={open && tab == "tools"}
/>
) : error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
) : null}
</Stack>
</SidePanel>
</>
@@ -0,0 +1,24 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import BotSuggestionChip from "./bot-suggestion-chip";
const longStep =
"Write a full launch plan for next quarter with owners, deadlines and the review checkpoints for every team";
function render({ step }: { step: string }) {
return renderToString(<BotSuggestionChip step={step} />);
}
describe("BotSuggestionChip", () => {
test("shows the step and keeps it inside the chip", () => {
const html = render({ step: longStep });
expect(html).toContain(longStep);
// The twui button's content wrapper is nowrap by default, which let a
// long step spill out of the button's outline on a phone.
expect(html).toContain("[&amp;_.twui-button-content-wrapper]:whitespace-normal");
expect(html).toContain("[&amp;_.twui-button-content-wrapper]:min-w-0");
expect(html).toContain("break-words");
expect(html).toContain("max-w-full");
});
});
@@ -22,10 +22,10 @@ export default function BotSuggestionChip({ step }: Props) {
color="gray"
size="smaller"
title={`Put this in your input: ${step}`}
className="inline-flex h-auto max-w-full gap-1! flex-nowrap align-middle px-2! py-1! text-left text-[13px] font-normal whitespace-normal [&_.twui-button-content-wrapper]:min-w-0"
className="inline-flex h-auto max-w-full min-w-0 gap-1! flex-nowrap align-middle px-2! py-1! text-left text-[13px] font-normal whitespace-normal [&_.twui-button-content-wrapper]:min-w-0 [&_.twui-button-content-wrapper]:whitespace-normal"
onClick={() => onUseSuggestion({ text: step })}
>
<Span className="min-w-0">{step}</Span>
<Span className="min-w-0 break-words">{step}</Span>
<ArrowUpRight size={14} aria-hidden className="shrink-0" />
</Button>
);
@@ -0,0 +1,163 @@
import { useContext } from "react";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import useExtensions from "@/src/hooks/use-extensions";
import type {
BotExtensionsPayload,
BotWithLastMessage,
} from "@/src/types";
import { BotComputersContext } from "../(data)/bot-computers-context";
import {
composerKnowledgebasesCopy,
composerToolsCopy,
} from "../(data)/composer-extensions-copy";
import BotComputerOption from "./bot-computer-option";
import BotPanelSection from "./bot-panel-section";
import ComposerBrowserButton from "./composer-browser-button";
import ComposerConnectorsSection from "./composer-connectors-section";
import ComposerExtensionsList from "./composer-extensions-list";
type Props = {
bot: BotWithLastMessage;
workspace_id?: number | null;
initial?: BotExtensionsPayload | null;
/**
* Whether the user has a browser of their own; without one there is
* nothing to pick.
*/
has_browsers?: boolean;
/**
* Whether the tab is on show, so its connectors are read then and its
* computer switches show.
*/
open: boolean;
};
/**
* The bot panel's third tab: where it works and what it can use there - its
* computer, the MCP servers, tools and skills it was given (the apps its
* connectors reach for you among them), its knowledgebases, and which of
* your browsers it acts as you in.
*/
export default function BotToolsTab({ bot, workspace_id, initial, has_browsers, open }: Props) {
const bot_name = bot.name || "this bot";
const extensions = useExtensions({
owner: { bot_id: bot.id || 0, workspace_id },
owner_name: bot_name,
initial,
});
const { computers, switching_id, error: computer_error, switchComputer, openComputer } =
useContext(BotComputersContext);
const is_knowledge = (item: { kind: string }) => item.kind == "knowledgebase";
const tools = {
attached: extensions.attached.filter((item) => !is_knowledge(item)),
addable: extensions.addable.filter((item) => !is_knowledge(item)),
};
const knowledge = {
attached: extensions.attached.filter(is_knowledge),
addable: extensions.addable.filter(is_knowledge),
};
const tools_copy = composerToolsCopy({ bot_name });
const knowledge_copy = composerKnowledgebasesCopy({ bot_name });
return (
<Stack className="w-full gap-4! items-stretch">
<BotPanelSection
title="Computer"
description={`A computer is a sandbox ${bot_name} works in: a shell, a browser and files of its own. Its tasks run on the checked one. Open one to use it yourself.`}
>
{computers.length ? (
<Stack
role="radiogroup"
aria-label={`${bot_name}'s computers`}
className="w-full mt-2 py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface"
>
{computers.map((computer, index) => (
<BotComputerOption
key={computer.id}
computer={computer}
current={index == 0}
onPick={async () => {
await switchComputer({ computer_id: computer.id || 0 });
}}
onOpen={() => {
openComputer({ computer_id: computer.id || 0 });
}}
/>
))}
</Stack>
) : (
<Span className="mt-2 text-[13px] leading-[18px] text-ink-secondary">
{`No computer is set up for ${bot_name} yet.`}
</Span>
)}
{switching_id ? (
<Span className="mt-2 text-[13px] leading-[18px] text-ink-secondary">
Switching its computer. The tasks it has open finish where they are.
</Span>
) : null}
{computer_error ? (
<Span role="alert" className="mt-2 text-[13px] leading-[18px] text-ink-secondary">
{computer_error}
</Span>
) : null}
</BotPanelSection>
<BotPanelSection title="Tools" description={tools_copy.some}>
<ComposerExtensionsList
id="panel-add-extension"
label={tools_copy.title}
items={tools.attached}
addable={tools.addable}
can_manage={extensions.can_manage}
busy={extensions.busy}
empty={tools_copy.none}
add_hint={tools_copy.add_hint}
add_noun={tools_copy.add_noun}
onAdd={extensions.add}
onRemove={extensions.remove}
/>
<ComposerConnectorsSection
bot_id={bot.id || 0}
workspace_id={workspace_id}
open={open}
/>
{has_browsers ? (
<Stack className="w-full mt-4 gap-2! items-start">
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`Which of your browsers ${bot_name} acts as you in.`}
</Span>
<ComposerBrowserButton
bot_id={bot.id || 0}
bot_name={bot_name}
workspace_id={workspace_id}
/>
</Stack>
) : null}
</BotPanelSection>
<BotPanelSection title="Knowledgebases" description={knowledge_copy.some}>
<ComposerExtensionsList
id="panel-add-knowledgebase"
label={knowledge_copy.title}
items={knowledge.attached}
addable={knowledge.addable}
can_manage={extensions.can_manage}
busy={extensions.busy}
empty={knowledge_copy.none}
add_hint={knowledge_copy.add_hint}
add_noun={knowledge_copy.add_noun}
onAdd={extensions.add}
onRemove={extensions.remove}
/>
</BotPanelSection>
{extensions.status?.error ? (
<Span role="alert" className="text-[13px] leading-[18px] text-ink-secondary">
{extensions.status.msg}
</Span>
) : null}
</Stack>
);
}
@@ -0,0 +1,103 @@
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import ExtensionAddSelect from "@/src/components/general/extension-add-select";
import type {
BotExtension,
BotExtensionKind,
BotExtensionsPayload,
} from "@/src/types";
import ComposerToolRow from "./composer-tool-row";
type Props = {
/**
* The add picker's element id, unique on the page.
*/
id: string;
/**
* What the list is, for screen readers.
*/
label: string;
items: BotExtension[];
addable: BotExtensionsPayload["addable"];
can_manage: boolean;
/**
* The extension being changed, as `kind:id`.
*/
busy?: string;
/**
* Said instead of the list when it holds nothing.
*/
empty?: string;
add_hint: string;
add_noun: string;
onAdd: (params: { kind: BotExtensionKind; id: number }) => Promise<boolean>;
onRemove: (params: {
kind: BotExtensionKind;
id: number;
name: string;
}) => Promise<boolean>;
};
/**
* What a bot can use here as a list, then the picker for more: shared by
* the composer's modals and the bot panel's tools tab. Super admins and
* admins take away any it was given (even one every bot started with); a
* workspace's own stay.
*/
export default function ComposerExtensionsList({
id,
label,
items,
addable,
can_manage,
busy,
empty,
add_hint,
add_noun,
onAdd,
onRemove,
}: Props) {
return (
<>
{items.length ? (
<Stack
aria-label={label}
className="w-full mt-4 py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface"
>
{items.map((item) => (
<ComposerToolRow
key={`${item.kind}:${item.id}`}
item={item}
busy={busy == `${item.kind}:${item.id}`}
onRemove={
can_manage && item.source == "bot"
? () =>
onRemove({
kind: item.kind,
id: item.id,
name: item.name,
})
: undefined
}
/>
))}
</Stack>
) : empty ? (
<Span className="mt-4 text-[13px] leading-[18px] text-ink-secondary">{empty}</Span>
) : null}
{can_manage && addable.length ? (
<Stack className="w-full mt-4 gap-2! items-stretch">
<Span className="text-[13px] leading-[18px] text-ink-secondary">{add_hint}</Span>
<ExtensionAddSelect
id={id}
noun={add_noun}
addable={addable}
loading={Boolean(busy)}
onAdd={onAdd}
/>
</Stack>
) : null}
</>
);
}
@@ -0,0 +1,58 @@
import Button from "@moduletrace/twui/layout/Button";
import Card from "@moduletrace/twui/elements/Card";
import Span from "@moduletrace/twui/layout/Span";
import { TriangleAlert, X } from "lucide-react";
import { twMerge } from "tailwind-merge";
type Props = {
message: string;
tone?: "error" | "warning";
onClose: () => void;
};
/**
* Why the last send didn't go, or why dictation stopped, under the composer.
* A card rather than a line of grey text, so a failed send reads as a
* failure, and it can be put away once read.
*/
export default function ComposerNotice({
message,
tone = "error",
onClose,
}: Props) {
return (
<Card
role="alert"
className={twMerge(
"w-full gap-2! rounded-default border-solid py-2! px-3!",
tone == "error"
? "border-error/40! bg-error/5!"
: "border-warning/40! bg-warning/5!",
)}
>
<TriangleAlert
size={15}
aria-hidden
className={twMerge(
"shrink-0",
tone == "error" ? "text-error" : "text-warning",
)}
/>
<Span className="min-w-0 flex-1 text-xs leading-5 break-words">
{message}
</Span>
<Button
title="Dismiss"
aria-label="Dismiss"
type="button"
variant="ghost"
color="text"
size="smaller"
onClick={onClose}
className="shrink-0 rounded-default-xs p-1! text-ink-secondary hover:text-ink"
>
<X size={14} aria-hidden />
</Button>
</Card>
);
}
@@ -7,7 +7,6 @@ import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { CircleAlert, type LucideIcon } from "lucide-react";
import ExtensionAddSelect from "@/src/components/general/extension-add-select";
import type {
BotExtension,
BotExtensionKind,
@@ -15,7 +14,7 @@ import type {
ConnectorAppIcon,
} from "@/src/types";
import ComposerConnectorsSection from "./composer-connectors-section";
import ComposerToolRow from "./composer-tool-row";
import ComposerExtensionsList from "./composer-extensions-list";
import { twMerge } from "tailwind-merge";
/**
@@ -168,45 +167,18 @@ export default function ComposerToolsModal({
</Span>
</Stack>
{count ? (
<Stack
aria-label={copy.title}
className="w-full mt-4 py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface"
>
{attached.map((item) => (
<ComposerToolRow
key={`${item.kind}:${item.id}`}
item={item}
busy={busy == `${item.kind}:${item.id}`}
onRemove={
can_manage && item.source == "bot"
? () =>
onRemove({
kind: item.kind,
id: item.id,
name: item.name,
})
: undefined
}
/>
))}
</Stack>
) : null}
{can_manage && addable.length ? (
<Stack className="w-full mt-4 gap-2! items-stretch">
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{copy.add_hint}
</Span>
<ExtensionAddSelect
id={copy.id}
noun={copy.add_noun}
addable={addable}
loading={Boolean(busy)}
onAdd={onAdd}
/>
</Stack>
) : null}
<ComposerExtensionsList
id={copy.id}
label={copy.title}
items={attached}
addable={addable}
can_manage={can_manage}
busy={busy}
add_hint={copy.add_hint}
add_noun={copy.add_noun}
onAdd={onAdd}
onRemove={onRemove}
/>
{connectors ? (
<ComposerConnectorsSection
@@ -8,7 +8,6 @@ import {
} from "react";
import Row from "@moduletrace/twui/layout/Row";
import Stack from "@moduletrace/twui/layout/Stack";
import P from "@moduletrace/twui/layout/P";
import type {
BotExtensionsPayload,
BotMessageAttachment,
@@ -34,10 +33,12 @@ import ComposerAttachments from "./composer-attachments";
import ComposerClearButton from "./composer-clear-button";
import ComposerEditor from "./composer-editor";
import ComposerMentionList from "./composer-mention-list";
import ComposerNotice from "./composer-notice";
import ComposerReplyPreview from "./composer-reply-preview";
import ComposerSendButton from "./composer-send-button";
import ComposerTools from "./composer-tools";
import ComposerVoiceButton from "./composer-voice-button";
import { twMerge } from "tailwind-merge";
/**
* What the conversation can do to the composer from outside it.
@@ -477,13 +478,23 @@ export default function Composer({
/>
</Row>
{notice ? (
<P
role="alert"
className="w-full max-w-container mx-auto px-3 md:px-6 -mt-5 pb-3 text-xs text-ink-secondary"
<Stack
className={twMerge(
"w-full px-3 pb-3 md:px-6 gap-0! items-stretch max-w-container m-auto",
"mb-4",
)}
>
{notice}
</P>
<ComposerNotice
message={notice}
tone={error ? "error" : "warning"}
onClose={() => {
setError(undefined);
recorder.setError(undefined);
}}
/>
</Stack>
) : null}
<ComposerTools
bot={bot}
workspace_id={workspace_id}
@@ -108,6 +108,7 @@ export default function ConversationHeader({
{is_workspace ? <BackButton /> : null}
<BotPanel
bot={bot}
workspace={workspace}
open={bot_panel_open}
on_open={open_bot_panel}
on_close={close_bot_panel}
@@ -5,6 +5,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { StorageFolderPayload, StorageSpecOption } from "@/src/types";
import type { StorageSpec } from "@/src/utils/storage-volumes";
import { storageBreadcrumbs } from "@/src/utils/storage-volumes";
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import FilesBreadcrumbRow from "@/src/components/general/files-breadcrumb-row";
@@ -48,6 +49,7 @@ export default function FilesBrowser({
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
[folder],
);
const crumbs = spec ? storageBreadcrumbs({ spec, path }) : folder?.breadcrumbs || [];
return (
<Row className="w-full mt-6 gap-6! flex-wrap items-start lg:flex-nowrap">
@@ -82,16 +84,14 @@ export default function FilesBrowser({
<Stack className="grow min-w-0 w-full items-stretch">
<Stack className="gap-1! items-stretch">
<H2 className="text-[18px]! leading-6 font-bold tracking-normal text-ink">
{folder?.breadcrumbs.at(-1)?.name ||
folder?.label ||
"Files"}
{crumbs.at(-1)?.name || folder?.label || "Files"}
</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{folderSummary({ folder })}
{folderSummary({ folder, loading })}
</Span>
</Stack>
<FilesBreadcrumbRow
crumbs={folder?.breadcrumbs || []}
crumbs={crumbs}
onOpenFolder={onOpenFolder}
/>
<FilesSearchInput value={search} onChange={onSearch} />
+2 -2
View File
@@ -1,9 +1,9 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import listStorageEntries, { storageBreadcrumbs } from "@/src/functions/backend/storage/list-storage-entries";
import listStorageEntries from "@/src/functions/backend/storage/list-storage-entries";
import resolveStoragePath from "@/src/functions/backend/storage/resolve-storage-path";
import resolveStorageSpec, { grabStorageSpecs } from "@/src/functions/backend/storage/resolve-storage-spec";
import type { PagePropsType, StorageFolderPayload } from "@/src/types";
import { parseStorageSpec, type StorageSpec } from "@/src/utils/storage-volumes";
import { parseStorageSpec, storageBreadcrumbs, type StorageSpec } from "@/src/utils/storage-volumes";
import type { BunextPageServerFn } from "@moduletrace/bunext/types";
/**
@@ -107,7 +107,7 @@ export default function ConnectorAccessModal({
setOpen={(next) => !next && onCancel()}
title={`Who gets ${connector.name}`}
description={
"A bot picked here is yours: it reaches the connector only in your runs there. A workspace reaches everyone working in it; every bot reaches the whole install."
"A bot picked here is yours: it reaches the connector only in your runs there, with your own accounts. A workspace reaches everyone working in it, with every account connected for this connector. Every bot reaches the whole install, each user with their own accounts."
}
>
<Form
@@ -80,7 +80,7 @@ export default function ConnectorConnectionModal({ connection, onSaved, onCancel
description={
connection
? "Renaming keeps its apps. A new key lists them again."
: "Each connection is one provider account with its own key, so a work account and a personal one live side by side. Once saved, every app that key holds is listed here: give one to every bot, a workspace or your own runs, and each person signs in to their own account for it."
: "Each connection is one provider account with its own key, so a work account and a personal one live side by side. Once saved, every app that key holds is listed here: give one to every bot, a workspace or your own runs, and a workspace's apps use every account connected for them, whoever connected them."
}
>
<Form className="w-full gap-4! items-stretch pt-4" onSubmit={submit}>
@@ -75,7 +75,7 @@ export default function ConnectorAppsSection() {
return (
<SettingsShell
title={connection.name}
description={`The apps ${connection.name} offers. Give one to every bot, to a workspace, or to your own runs on a bot; each person then signs in to their own account for it.`}
description={`The apps ${connection.name} offers. Give one to every bot, to a workspace, or to your own runs on a bot; a workspace uses every account connected for that app, whoever connected it.`}
>
<Row className="w-full items-center gap-2!">
<Link href="/admin/settings/connectors" className="text-sm">
@@ -46,7 +46,7 @@ export default function ConnectorsSettingsSection() {
return (
<SettingsGroup
title="Connectors"
description="Connect a paradigm once and every app it offers is listed under it. Open a connection to search its apps and give one to every bot, to a workspace, or to your own runs on a bot; each person then signs in to their own account for it."
description="Connect a paradigm once and every app it offers is listed under it. Open a connection to search its apps and give one to every bot, to a workspace, or to your own runs on a bot; a workspace uses every account connected for that app, whoever connected it."
>
<SettingsList is_empty={!connections.length} empty="No connectors yet">
{connections.map((connection) => (
@@ -53,7 +53,14 @@ const valuesOf = (limits?: RunLimitsOverview | null): Values => {
* per task, ...".
*/
const savedMessage = (limits: RunLimitsOverview) =>
`Saved: ${described(limits.task_steps)} steps per task, ${described(limits.reply_steps)} per chat reply, ${described(limits.unattended_steps)} per routine or hook call, ${described(limits.run_tokens)} prompt tokens per run, ${described(limits.context_tokens)} tokens of working context, and ${described(limits.model_rest_seconds)} seconds of model rest.`;
`Saved: ${described(limits.task_steps)} steps per task, ${described(limits.reply_steps)} per chat reply, ${described(limits.unattended_steps)} per routine or hook call, ${described(limits.run_tokens)} prompt tokens per run, ${workingContextText(limits.context_tokens)}, and ${described(limits.model_rest_seconds)} seconds of model rest.`;
/**
* A working context that is unlimited is the model's own window, not a
* number: "unlimited tokens" read as if a run could send anything.
*/
const workingContextText = (limit: RunLimit) =>
isUnlimitedLimit(limit) ? "the model's own window as working context" : `${count(limit)} tokens of working context`;
/**
* How long a bot may work on one run: the model turns a task, a chat
@@ -282,7 +289,7 @@ export default function RunLimitsForm({ limits }: Props) {
suffix="tokens"
onChange={change("context_tokens")}
onUnlimitedChange={changeUnlimited("context_tokens")}
info={`How much a run sends per turn (its prompt, its tools and what it has done so far) before the oldest tool output is cut, whatever the model's window. Smaller costs less per turn; larger lets a bot keep more of what it read. Between ${count(overview?.context_tokens_min)} and ${count(overview?.context_tokens_max)}; 0 uses the default (${described(overview?.context_tokens_default ?? 0)}). With No limit on, the model's own window decides.`}
info={`How much of the model's window a run may use per turn, once the room its answer needs is kept back (a tenth of the window, between 8,000 and 64,000 tokens, unless the model declares its own output size). What the app's instructions and tool definitions take comes out of it first, and only what is left holds the conversation. Unset, the model's own window decides; a number holds every run below it (smaller costs less per turn, larger lets a bot keep more of what it read). Between ${count(overview?.context_tokens_min)} and ${count(overview?.context_tokens_max)}; 0 puts the default back.`}
/>
<RunLimitInput
id="model_rest_seconds"
@@ -11,6 +11,7 @@ import HarnessParamsButton from "./harness-params-button";
import HarnessProviderSelect from "./harness-provider-select";
import HarnessTextFallbacks from "./harness-text-fallbacks";
import HarnessVoiceControls from "./harness-voice-controls";
import HarnessWindowNote from "./harness-window-note";
type Props = {
harness: HarnessOverview;
@@ -70,6 +71,9 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
<HarnessCurrentModel
harness={value.inherit && harness.default ? { ...harness, ...harness.default } : harness}
/>
{harness.harness == "text" ? (
<HarnessWindowNote model={value.inherit ? harness.default?.current : picked || harness.current} />
) : null}
<HarnessOptionsCheckboxes
harness={harness}
value={value}
@@ -0,0 +1,32 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import HarnessWindowNote from "./harness-window-note";
const model = (context_length?: number) => ({
id: 1,
provider_id: 10,
provider_name: "Nvidia Cloud",
slug: "nvidia/nemotron-3-ultra-550b-a55b",
name: "nemotron-3-ultra",
free: false,
context_length,
});
describe("HarnessWindowNote", () => {
test("says what a run assumes for a model with no declared window", () => {
const html = renderToString(<HarnessWindowNote model={model()} />);
expect(html).toContain("declares no context window");
expect(html).toContain("1,000,000");
expect(html).toContain("936,000");
expect(html).toContain("stops the run with its own limit");
});
test("says nothing for a model that declares one", () => {
expect(renderToString(<HarnessWindowNote model={model(131_072)} />)).toBe("");
});
test("says nothing when there's no model to judge", () => {
expect(renderToString(<HarnessWindowNote />)).toBe("");
});
});
@@ -0,0 +1,27 @@
import Span from "@moduletrace/twui/layout/Span";
import { AppData } from "@/src/data/app-data";
import workingContextTokens from "@/src/harness/text/working-context";
import type { HarnessModelOption } from "@/src/types";
type Props = {
model?: HarnessModelOption;
};
/**
* A word when the text model never declared a window: a run assumes
* `AppData.HarnessUnknownContextWindow` and works to that less the room its
* answer needs. Said out loud because the app used to size runs at 70% of a
* guessed 131,072 without a word, which left one chat 91,750 tokens of
* working context and then reading nothing at all (`workingContextTokens`).
*/
export default function HarnessWindowNote({ model }: Props) {
if (!model || model.context_length) return null;
const working = workingContextTokens({});
return (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`${model.name} declares no context window, so a run assumes ${AppData.HarnessUnknownContextWindow.toLocaleString("en-US")} tokens and works to ${working.tokens.toLocaleString("en-US")} of them, keeping the rest for its answer. A model smaller than that refuses the prompt and stops the run with its own limit: set the window on its provider, or pick a model that declares one.`}
</Span>
);
}
@@ -170,7 +170,7 @@ export default function ProviderForm({ provider, onSaved, onCancel }: Props) {
rawNumber
defaultValue={context_length}
suffix="tokens"
info={`The window every model this provider lists without one of its own is given. Leave empty if its list carries them (OpenRouter's does); a run assumes ${AppData.HarnessUnknownContextWindow.toLocaleString("en-US")} when nothing says.`}
info={`The window every model this provider lists without one of its own is given. Leave empty if its list carries them (OpenRouter's does). A run sizes itself to the model's window less the room its answer needs, so with nothing declared it assumes ${AppData.HarnessUnknownContextWindow.toLocaleString("en-US")} tokens, and a smaller model refuses such a prompt and stops the run with its own limit.`}
onChange={(e) => setContextLength(e.target.value)}
placeholder="Eg. 1,000,000"
/>
@@ -57,8 +57,19 @@ export default function harnessModelSelectOptions({
},
...models.map((model) => ({
value: String(model.id),
title: `${model.name}${provider_name ? "" : ` · ${model.provider_name}`}${model.free && !/free/i.test(model.name) ? " · free" : ""}`,
title: `${model.name}${provider_name ? "" : ` · ${model.provider_name}`}${model.free && !/free/i.test(model.name) ? " · free" : ""}${windowText({ model })}`,
default: model.id == model_id,
})),
];
}
/**
* What the model's window is, on its picker line: a model with none
* declared is the one whose runs are sized for a guess, and the user is
* picking it right here.
*/
function windowText({ model }: { model: HarnessModelOption }) {
if (model.context_length) return ` · ${model.context_length.toLocaleString("en-US")} tokens`;
return " · no context window declared";
}
+5 -5
View File
@@ -11,12 +11,12 @@ import type {
} from "@moduletrace/bunext/types";
/**
* A bot's core instructions, for its edit form in the conversation, which
* loads them when it opens (page props leave them out). For super admins
* and admins; only the super admin reaches the coordinator.
* A bot's core instructions and memory, for its panel in the conversation,
* which loads them when it opens (page props leave them out). For super
* admins and admins; only the super admin reaches the coordinator.
*/
export const handler: BunextAPIRouteHandler<
APIResponseObject<{ system_prompt: string }>
APIResponseObject<{ system_prompt: string; memory: string }>
> = async ({ req, body }) => {
try {
if (req.method != "POST") {
@@ -40,7 +40,7 @@ export const handler: BunextAPIRouteHandler<
throw new AppError(`Bot not found.`);
}
return { success: true, singleRes: { system_prompt: bot.system_prompt || "" } };
return { success: true, singleRes: { system_prompt: bot.system_prompt || "", memory: bot.memory || "" } };
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
@@ -0,0 +1,60 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import updateBotMemory from "@/src/functions/backend/db/bots/update-bot-memory";
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
import { UpdateBotMemoryRequestSchema } from "@/src/schemas/bot-schema";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type {
APIResponseObject,
BunextAPIRouteHandler,
} from "@moduletrace/bunext/types";
/**
* Replaces a bot's core memory from its panel (the memory tab), for super
* admins and admins. Its memory of each user and its memory in a workspace
* are separate rows.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const { user, user_types } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (isReadOnlyUser({ user_types: user_types || [] })) {
throw new AppError(`This user can only read records.`);
}
if (!canManageCrew({ user_types })) {
throw new AppError(`Only an admin can edit a bot.`);
}
const { bot_id, memory } = parseWithSchema({
schema: UpdateBotMemoryRequestSchema,
data: body,
});
await updateBotMemory({ user_id: user.id, bot_id, memory });
await logEvent({
title: "Bot memory changed",
category: "system",
user_id: user.id,
plain_text: `User #${user.id} edited bot #${bot_id}'s memory.`,
metadata: { bot_id },
ip_address: grabRequestIP(req),
});
return { success: true, msg: `Saved.` };
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+2 -2
View File
@@ -1,12 +1,12 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import listStorageEntries, { storageBreadcrumbs } from "@/src/functions/backend/storage/list-storage-entries";
import listStorageEntries from "@/src/functions/backend/storage/list-storage-entries";
import resolveStoragePath from "@/src/functions/backend/storage/resolve-storage-path";
import resolveStorageSpec from "@/src/functions/backend/storage/resolve-storage-spec";
import type { StorageFolderPayload } from "@/src/types";
import parseWithSchema from "@/src/utils/parse-with-schema";
import safeErrorMessage from "@/src/utils/safe-error-message";
import { StorageListRequestSchema } from "@/src/schemas/storage-schema";
import { parseStorageSpec } from "@/src/utils/storage-volumes";
import { parseStorageSpec, storageBreadcrumbs } from "@/src/utils/storage-volumes";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
+19 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { MessageDetailsRequestSchema } from "./bot-schema";
import { MessageDetailsRequestSchema, UpdateBotMemoryRequestSchema } from "./bot-schema";
describe("MessageDetailsRequestSchema", () => {
test("asks for the modal's calls by default", () => {
@@ -21,3 +21,21 @@ describe("MessageDetailsRequestSchema", () => {
expect(MessageDetailsRequestSchema.safeParse({}).success).toBe(false);
});
});
describe("UpdateBotMemoryRequestSchema", () => {
test("takes the whole new memory", () => {
expect(UpdateBotMemoryRequestSchema.parse({ bot_id: "3", memory: "It writes short." })).toEqual({
bot_id: 3,
memory: "It writes short.",
});
});
test("allows clearing it", () => {
expect(UpdateBotMemoryRequestSchema.parse({ bot_id: 3, memory: "" }).memory).toBe("");
});
test("refuses a bot or a memory that isn't there", () => {
expect(UpdateBotMemoryRequestSchema.safeParse({ bot_id: 3 }).success).toBe(false);
expect(UpdateBotMemoryRequestSchema.safeParse({ bot_id: 0, memory: "x" }).success).toBe(false);
});
});
+13
View File
@@ -234,6 +234,19 @@ export const UpdateBotRequestSchema = CreateBotRequestSchema.omit({ workspace_id
export type UpdateBotRequest = z.infer<typeof UpdateBotRequestSchema>;
/**
* The bot's core memory, edited from its panel: the whole new text.
*/
export const UpdateBotMemoryRequestSchema = z.object({
bot_id: z.coerce.number().int().positive("Pick a bot"),
memory: z
.string()
.trim()
.max(AppData.PromptMaxLength, `Keep memory under ${AppData.PromptMaxLength} characters`),
});
export type UpdateBotMemoryRequest = z.infer<typeof UpdateBotMemoryRequestSchema>;
export const UploadBotAttachmentRequestSchema = z.object({
/**
* The file as a base64 data URL.
+11
View File
@@ -0,0 +1,11 @@
import { describe, expect, test } from "bun:test";
import { UpdateWorkspaceBotRequestSchema } from "./workspace-schema";
describe("UpdateWorkspaceBotRequestSchema", () => {
test("leaves the fields it wasn't given alone", () => {
const parsed = UpdateWorkspaceBotRequestSchema.parse({ workspace_id: "2", bot_id: "5", memory: "Short here." });
expect(parsed).toEqual({ workspace_id: 2, bot_id: 5, memory: "Short here." });
expect("system_prompt" in parsed).toBe(false);
});
});
+6 -2
View File
@@ -32,9 +32,13 @@ export const WorkspaceBotRequestSchema = z.object({
export type WorkspaceBotRequest = z.infer<typeof WorkspaceBotRequestSchema>;
/**
* Either one alone: the bot panel's memory tab saves the workspace memory
* without rewriting the instructions here, and vice versa.
*/
export const UpdateWorkspaceBotRequestSchema = WorkspaceBotRequestSchema.extend({
system_prompt: Prompt.default(""),
memory: Prompt.default(""),
system_prompt: Prompt.optional(),
memory: Prompt.optional(),
});
export type UpdateWorkspaceBotRequest = z.infer<typeof UpdateWorkspaceBotRequestSchema>;
+6
View File
@@ -819,6 +819,12 @@ export type HarnessModelOption = {
* The generation settings the model takes; undefined: all of them.
*/
supported_parameters?: string[];
/**
* Its context window, when the catalog or its provider declares one. A
* model with none is given `AppData.HarnessUnknownContextWindow` by
* every run, which the picker says out loud.
*/
context_length?: number;
};
/**
@@ -0,0 +1,23 @@
import { describe, expect, test } from "bun:test";
import connectorAccountReachSql from "./connector-account-reach-sql";
describe("connectorAccountReachSql", () => {
test("a connector given to a workspace hands every connected account of it to that workspace", () => {
const { sql, values } = connectorAccountReachSql({ workspace_id: 4 });
expect(sql).toContain("SELECT 1 FROM workspace_connectors wc");
expect(sql).toContain("wc.connector_id = a.connector_id");
expect(sql).toContain("wc.workspace_id = ?");
expect(values).toEqual([4]);
});
test("the global scope brings no accounts, only the workspace grant does", () => {
expect(connectorAccountReachSql({ workspace_id: 4 }).sql).not.toContain("all_bots");
});
test("a run outside a workspace gets no clause", () => {
expect(connectorAccountReachSql({})).toEqual({ sql: "", values: [] });
expect(connectorAccountReachSql({ workspace_id: null })).toEqual({ sql: "", values: [] });
expect(connectorAccountReachSql({ workspace_id: 0 })).toEqual({ sql: "", values: [] });
});
});
+18
View File
@@ -0,0 +1,18 @@
type Params = {
workspace_id?: number | string | null;
};
/**
* The extra account clause a workspace brings: a connector given to a
* workspace reaches everyone working in it, so every connected account of
* that connector does too, whoever connected it. Empty outside a workspace,
* and the global scope brings no accounts (only the workspace grant does).
*/
export default function connectorAccountReachSql({ workspace_id }: Params): { sql: string; values: number[] } {
if (!workspace_id) return { sql: "", values: [] };
return {
sql: `OR EXISTS (SELECT 1 FROM workspace_connectors wc WHERE wc.connector_id = a.connector_id AND wc.workspace_id = ?)`,
values: [Number(workspace_id)],
};
}
+17
View File
@@ -65,6 +65,23 @@ describe("describeRunUsage", () => {
expect(text).toContain("Today's settings: unlimited steps per task, 20 per reply, unlimited per routine or hook call");
});
test("an unlimited working-context setting names the model's own window", () => {
const text = describeRunUsage({
usage: {
...usage,
current_limits: {
task_steps: 60,
reply_steps: 20,
unattended_steps: 12,
run_tokens: 250_000,
context_tokens: "unlimited",
},
},
});
expect(text).toContain("the model's own window, less the room its answer needs of working context per turn.");
});
test("a call recorded before runs kept their limits says so", () => {
expect(describeRunUsage({ usage: { ...usage, limits: null } })).toContain("recorded no limits");
});
+26 -6
View File
@@ -20,11 +20,18 @@ const when = (value: number | null) => (value ? new Date(value).toISOString().re
const limitsLine = ({ limits }: { limits: RunUsage["limits"] }) => {
if (!limits) return "Their calls recorded no limits (made before runs kept them).";
return [
`The run was allowed ${limitText({ value: limits.steps, none: "an unrecorded number of" })} steps,`,
`${limitText({ value: limits.run_tokens, none: "an unrecorded number of" })} prompt tokens in all,`,
`and ${limits.context_tokens === null ? "an unrecorded working context" : `${limitText({ value: limits.context_tokens, none: "an unrecorded working context" })} tokens of working context`} per turn.`,
].join(" ");
const staticSplit =
limits.system_tokens || limits.tools_tokens
? ` Of that, its own instructions took ${count(limits.system_tokens || 0)} and its tool definitions ${count(limits.tools_tokens || 0)}, before any of the conversation.`
: "";
return (
[
`The run was allowed ${limitText({ value: limits.steps, none: "an unrecorded number of" })} steps,`,
`${limitText({ value: limits.run_tokens, none: "an unrecorded number of" })} prompt tokens in all,`,
`and ${limits.context_tokens === null ? "an unrecorded working context" : `${limitText({ value: limits.context_tokens, none: "an unrecorded working context" })} tokens of working context`} per turn.`,
].join(" ") + staticSplit
);
};
const changeLimitsLine = [
@@ -37,8 +44,21 @@ const changeLimitsLine = [
const costDriversLine = `More steps is the usual reason a run costs more than the work looks: every turn resends the prompt, the tool list and the whole transcript, so a long run grows with the square of its turns. A long session makes every reply cost more too (${generalSettingsRef({ section: "sessions", field: "max_messages" })} starts a new one sooner).`;
/**
* The working-context setting as a run reads it today: unlimited means the
* model's own window, less the room its answer needs, never "no ceiling",
* since a bot reporting "unlimited of context per turn" tells the user
* nothing about what actually bounded the run.
*/
const contextToday = (value: RunLimit | null) => {
if (value === null) return "an unrecorded amount";
if (isUnlimitedLimit(value)) return "the model's own window, less the room its answer needs";
return `${count(value)} tokens`;
};
const todayLine = ({ current }: { current: CurrentRunLimits }) =>
`Today's settings: ${limitText({ value: current.task_steps, none: "an unrecorded number of" })} steps per task, ${limitText({ value: current.reply_steps, none: "an unrecorded number of" })} per reply, ${limitText({ value: current.unattended_steps, none: "an unrecorded number of" })} per routine or hook call, ${limitText({ value: current.run_tokens, none: "an unrecorded number of" })} prompt tokens per run, ${limitText({ value: current.context_tokens, none: "an unrecorded working context" })} tokens of working context per turn.`;
`Today's settings: ${limitText({ value: current.task_steps, none: "an unrecorded number of" })} steps per task, ${limitText({ value: current.reply_steps, none: "an unrecorded number of" })} per reply, ${limitText({ value: current.unattended_steps, none: "an unrecorded number of" })} per routine or hook call, ${limitText({ value: current.run_tokens, none: "an unrecorded number of" })} prompt tokens per run, ${contextToday(current.context_tokens)} of working context per turn.`;
/**
* What one run spent, in the shape a bot reports it: what it cost, the
+5
View File
@@ -30,6 +30,11 @@ describe("folderSummary", () => {
test("asks for a folder when there is none", () => {
expect(folderSummary({ folder: null })).toBe("Pick a folder to look inside.");
});
test("a folder still loading is never counted as none", () => {
expect(folderSummary({ folder: null, loading: true })).toBe("Loading...");
expect(folderSummary({ folder: folder({ total: 4 }), loading: true })).toBe("Loading...");
});
});
describe("emptyFolderText", () => {
+8 -1
View File
@@ -5,7 +5,14 @@ import type { StorageFolderPayload } from "@/src/types";
* that isn't on disk, that it isn't there. A stale folder link must never
* read as an empty folder.
*/
export function folderSummary({ folder }: { folder: StorageFolderPayload | null }) {
export function folderSummary({
folder,
loading,
}: {
folder: StorageFolderPayload | null;
loading?: boolean;
}) {
if (loading) return "Loading...";
if (!folder) return "Pick a folder to look inside.";
if (folder.missing) {
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, test } from "bun:test";
import sidePanelCloseSwipe from "./side-panel-close-swipe";
describe("sidePanelCloseSwipe", () => {
test("a panel from the left closes on a swipe back to the left", () => {
expect(sidePanelCloseSwipe({ side: "left" })).toBe("left");
});
test("a panel from the right closes on a swipe back to the right", () => {
expect(sidePanelCloseSwipe({ side: "right" })).toBe("right");
});
test("closing is always the opposite of the page swipe that opened it", () => {
expect(sidePanelCloseSwipe({ side: "left" })).not.toBe("right");
expect(sidePanelCloseSwipe({ side: "right" })).not.toBe("left");
});
});
+15
View File
@@ -0,0 +1,15 @@
export type SidePanelSide = "left" | "right";
type Params = {
side: SidePanelSide;
};
/**
* The swipe that closes a panel: back towards the edge it slid in from, so
* the way it came. The rail slides in from the left and closes on a drag to
* the left; the bot panel slides in from the right and closes on a drag to
* the right. That is the opposite of the page swipe that opens each one.
*/
export default function sidePanelCloseSwipe({ side }: Params): "left" | "right" {
return side == "left" ? "left" : "right";
}
+23
View File
@@ -4,6 +4,7 @@ import {
isSameStorageSpec,
isStorageVolume,
parseStorageSpec,
storageBreadcrumbs,
storagePathName,
storageSpecHref,
storageVolumeFromRef,
@@ -77,6 +78,28 @@ describe("volume names", () => {
});
});
describe("storageBreadcrumbs", () => {
const spec = { volume: "computers", owner_id: 1 } as const;
test("at the top of a volume there is only the way back to it", () => {
expect(storageBreadcrumbs({ spec })).toEqual([
{ name: "", href: `${StorageBrowserPath}?volume=computers&owner=1` },
]);
expect(storageBreadcrumbs({ spec, path: "/" })).toHaveLength(1);
});
test("walks down one crumb per segment", () => {
expect(storageBreadcrumbs({ spec, path: "seo/raw mes" })).toEqual([
{ name: "", href: `${StorageBrowserPath}?volume=computers&owner=1` },
{ name: "seo", href: `${StorageBrowserPath}?volume=computers&owner=1&path=seo` },
{
name: "raw mes",
href: `${StorageBrowserPath}?volume=computers&owner=1&path=seo%2Fraw+mes`,
},
]);
});
});
describe("isSameStorageSpec", () => {
test("compares volume and owner", () => {
const a = { volume: "bots", owner_id: 1 } as const;
+25
View File
@@ -154,6 +154,31 @@ export function storageSpecHref({ spec, path }: { spec: StorageSpec; path?: stri
return `${StorageBrowserPath}?${query.toString()}`;
}
/**
* The breadcrumb trail of a folder, from the volume's top: one crumb per
* segment, each with the address that opens it. Built from the path asked
* for, so a trail can be shown while its listing still loads.
*/
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;
}
/**
* A folder's label for a chip: the last path segment, or the volume's
* title at the top.
+20
View File
@@ -0,0 +1,20 @@
/**
* Where a sideways drag belongs to the control instead of the page: typing,
* selecting a field's text or moving its caret all live here.
*/
export const FieldTouchTargets =
"input, textarea, select, [contenteditable='true'], .cm-editor";
type Params = {
target: EventTarget | null;
};
/**
* Whether a touch landed on a field, which owns it: a swipe read there would
* take a caret or a selection, not a pane.
*/
export default function touchInField({ target }: Params): boolean {
if (!(target instanceof Element)) return false;
return Boolean(target.closest(FieldTouchTargets));
}