Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bab6683295 | ||
|
|
1757311262 | ||
|
|
d4469e6848 | ||
|
|
15a74cacde | ||
|
|
67395500b5 |
@@ -119,7 +119,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### Prompt and memory
|
||||
|
||||
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each whole-text replace (`update_workspace`'s context, `set_bot_workspace_instructions`, `update_memory`) refuses once a save that would drop a section (`markdownHeadings`) or cut the text below `AppData.SharedTextShrinkShare` of its length (`sharedTextProblem`, `src/utils/shared-text-guard.ts`), until the caller passes `replace: true`; the context is read before it is rewritten with `find_workspace` `include_context` (coordinator wherever it works, and a workspace admin), and each of them reads its save back before reporting it. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
|
||||
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), the name of the user the run is for (`grabUserName`; first and last, else username, and no section when they have neither, so no bot asks who it's talking to), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each whole-text replace (`update_workspace`'s context, `set_bot_workspace_instructions`, `update_memory`) refuses once a save that would drop a section (`markdownHeadings`) or cut the text below `AppData.SharedTextShrinkShare` of its length (`sharedTextProblem`, `src/utils/shared-text-guard.ts`), until the caller passes `replace: true`; the context is read before it is rewritten with `find_workspace` `include_context` (coordinator wherever it works, and a workspace admin), and each of them reads its save back before reporting it. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
|
||||
|
||||
Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one `ask_user` card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, crew request). The way they named is part of the request too: a tool, app, service, provider or path they asked for is the one to use, a blocked one is reported and asked about, never swapped for another way that reaches the same result, and a probe is not a deliverable. Memory, habits and the bot's own initiative never widen a request. Every prompt ends with `RoadblockNote`: a run that is blocked (a tool failing again and again, a computer or page down, access it does not have) stops after two or three attempts and reports what failed and what the user must do, never works around it another way or describes the work as done. The app enforces the tool-loop half itself: `AppData.HarnessStuckToolRepeats` consecutive calls of one tool with the same answer end the run at a wrap up (`stuckToolNote`, `run-text-loop.ts`).
|
||||
|
||||
@@ -240,7 +240,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited; the bench lives on a `globalCache` slot (`cobble.harnessCooldowns`) so a run-limits save clears the copy the queue reads, and that save, like queue startup, wakes the jobs a rest had parked ahead of time (`releaseRestingBotJobs`)), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). A call that only reaches benched models records a failed-call row for each resting candidate (`recordHarnessFailure`, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models; a resting call says how long the wait is ("The next try is possible in 27s."), since told only "trying again shortly" a bot told the user the models were benched until a restart. A failure carries the model the candidate ran on, the request's method and address, and a hint when a 404/405 came back with an empty body (no endpoint there), so the tool's message names the pick instead of leaving the bot to guess it: with only "HTTP 404", a production bot invented a model and its routing. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `send_reply` for a reply's answer or `start_task` for work a task run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-answer turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with `start_task` is following the plan. `computer_bash` whose command provably only reads (`isReadOnlyCommand`: an allow-listed program and no redirect, no `tee`/`xargs`, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: the working context is the model's declared window less the room its answer needs (`workingContextTokens`: `max_output_tokens` when declared, else a tenth of the window clamped to 8,000-64,000), capped by `grabContextBudgetTokens` when the install sets one (unlimited by default, so the window decides, never a flat share of a guessed window); `fitTranscriptToContext` trims to it, cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output, and a result under `TrimmedKeepChars * 4` is never cut at all (the same note once replaced a 14-character shell answer and the run read nothing for thirty steps); the newest turn's results are cut last, only once everything older is gone; every `AppData.HarnessTrimNoteEvery` trimmed turns the run is told its earlier readings were cut (`contextTrimmedNote`, traced as `trimmed`), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`, which says how much of the overage is the app's own instructions and tools and how much is the conversation: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget: "request"`; when the system prompt and tool definitions alone pass the working context it is `over_budget: "static"` instead and `runTextLoop` stops at once with a `HarnessError` (`fatal: true`, `staticPromptOverBudgetNote`: the arithmetic, Settings > Models, a bigger-window model, fewer extensions) rather than trimming every turn and answering from nothing. Only the newest `browser_snapshot` and `browser_find` per browser stay (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP, connector and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars` (a namespace of `HarnessDeferredNamespaceMin` tools or more is listed by name alone on one line: one GitHub connection's 905 tools were 148,000 characters of descriptions on every turn), and so are the bot's own tools by family (`groupTools` over `ToolGroups`, `HarnessTool.group`, once they pass `HarnessDeferBuiltinToolsMinChars` and `HarnessDeferBuiltinToolsShare` of the working context, since they are ~100k characters every turn: `load_tools` takes exact names, a family's name or `<prefix>*`, and `WrapUpToolNames`, the closing tools and `load_tools` itself are never deferred); loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process. A provider that caps a batch below `AppData.EmbeddingBatchSize` (Alibaba's Model Studio: "batch size is invalid, it should not be larger than 20") is answered by retrying the refused batch at the size it named, remembered per provider and model (`smaller-batch-limit.ts`), so one document's large batch no longer fails the whole ingest.
|
||||
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`); a custom provider's `/models` lists ids only, so its models take none and the form hides the Model settings target. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model. Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
|
||||
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`). Only OpenRouter's `/models` says what each model takes; every other provider lists ids only, so its models get what its provider declares (`harness_providers.parameters`, else its preset's list in `harness-provider-dict.ts`, else its host's: `provider-parameter-keys.ts`, which knows Alibaba's Token Plan hosts) written into `supported_parameters` at sync (`modelSupportedParameters`), and a provider that declares none hides the Model settings target. A super admin ticks them in the provider form. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model, and `reasoning_effort` nests as `reasoning: { effort }` on OpenRouter alone (`toWireChatParams`). Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `send_reply` with work, or `start_task` in a task run (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `send_reply`, `start_task`, `hand_over_task`, `update_requester` (an interim word to the bot that asked while a crew request is open), coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. A prompt-kind tool's filled template is the model's own input, so a secret env fills in as its `[KEY]` marker there, never its value (`runPromptTool`); http and script tools use secrets server-side, where the value never reaches the model. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
|
||||
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); knowledgebases are the exception it fills itself, since they live on the install (see Knowledgebases). Its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). A pending proposal for the same thing in the same conversation is replaced when another is made or one is confirmed (`replacePendingExtensionProposals`: a skill by `data.slug`, else the extension id, else the normalised name; `replacePendingHookProposals` by `hook_id`, then title), so a conversation carried into a new session no longer leaves a second card pending for the same skill (#41 stayed pending for ever while #42 made it, and the same target churned through #60-#63). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
|
||||
|
||||
@@ -3237,6 +3237,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
fieldDescription: `Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "parameters",
|
||||
fieldDescription: `JSON array of the generation settings this provider's models are offered, for the models whose own list carries none (a custom provider lists ids only). Null follows the preset's or host's own list; an empty array means it takes none`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "last_synced_at",
|
||||
fieldDescription: `Unix timestamp of the last model list sync`,
|
||||
|
||||
@@ -2009,6 +2009,10 @@ export type BUN_SQLITE_COBBLE_HARNESS_PROVIDERS = {
|
||||
* Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown
|
||||
*/
|
||||
context_length?: number | "";
|
||||
/**
|
||||
* JSON array of the generation settings this provider's models are offered, for the models whose own list carries none (a custom provider lists ids only). Null follows the preset's or host's own list; an empty array means it takes none
|
||||
*/
|
||||
parameters?: string;
|
||||
/**
|
||||
* Unix timestamp of the last model list sync
|
||||
*/
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.28.4",
|
||||
"version": "0.28.6",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -31,7 +31,11 @@ type Props = ComponentProps<typeof BotStone> & {
|
||||
* never a circle, so it isn't mistaken for a person), else its stone. Its
|
||||
* colour still marks it everywhere else, e.g. the unread dot.
|
||||
*/
|
||||
export default function BotAvatar({ image_media_id, src: picked, ...stone }: Props) {
|
||||
export default function BotAvatar({
|
||||
image_media_id,
|
||||
src: picked,
|
||||
...stone
|
||||
}: Props) {
|
||||
const saved = profileImageUrls({ media_id: image_media_id });
|
||||
const thumbnail_src = picked || saved.thumbnail_src;
|
||||
const src = picked || saved.src;
|
||||
@@ -49,6 +53,7 @@ export default function BotAvatar({ image_media_id, src: picked, ...stone }: Pro
|
||||
BotAvatarSizeClasses[size] || BotAvatarSizeClasses[32],
|
||||
stone.className,
|
||||
)}
|
||||
size={size}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ const UserAvatarSizeClasses = {
|
||||
sm: "size-6 text-[11px]",
|
||||
md: "size-8 text-xs",
|
||||
lg: "size-16 text-lg",
|
||||
xl: "size-24 text-xl",
|
||||
xxl: "size-32 text-2xl",
|
||||
} as const;
|
||||
|
||||
type Props = {
|
||||
@@ -47,7 +49,9 @@ export default function UserAvatar({
|
||||
size = "md",
|
||||
className,
|
||||
}: Props) {
|
||||
const photo = person?.profile_media_id ? grabMediaURL({ user: person }) : {};
|
||||
const photo = person?.profile_media_id
|
||||
? grabMediaURL({ user: person })
|
||||
: {};
|
||||
const src = passed_src || photo.media_thumbnail_url || photo.media_url;
|
||||
const img_err_src = passed_src ? passed_err_src : photo.media_url;
|
||||
const initials = passed_initials || userInitials(person || {});
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
harnessParametersFromOptions,
|
||||
harnessParameterValue,
|
||||
modelAdvertisesParameter,
|
||||
providerSupportedParameters,
|
||||
withHarnessParameters,
|
||||
} from "./harness-parameter-dict";
|
||||
|
||||
@@ -68,4 +69,14 @@ describe("harness parameters", () => {
|
||||
harnessParameterValue({ harness: "text", params: { temperature: 0 }, key: "temperature" }),
|
||||
).toEqual({ value: 0, saved: true });
|
||||
});
|
||||
|
||||
test("a provider's declared settings go under the names its models advertise", () => {
|
||||
expect(
|
||||
providerSupportedParameters({
|
||||
keys: ["temperature", "reasoning_effort"],
|
||||
}),
|
||||
).toEqual(["temperature", "reasoning"]);
|
||||
expect(providerSupportedParameters({})).toBeUndefined();
|
||||
expect(providerSupportedParameters({ keys: [] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* - `advertised`: the name a provider's model list uses for it, when it
|
||||
* differs (OpenRouter's `supported_parameters`)
|
||||
* - `wire`: how the field is written, for providers that nest it
|
||||
* - `wire_boolean`: saved as "true"/"false", sent as a JSON boolean
|
||||
*/
|
||||
export const HarnessParameters = [
|
||||
{
|
||||
@@ -104,12 +105,42 @@ export const HarnessParameters = [
|
||||
{ value: "high", title: "High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "enable_thinking",
|
||||
title: "Thinking",
|
||||
description: `Whether it thinks before it answers, which is slower and costs more. "Default" leaves each model's own setting alone. Providers that turn thinking on by another field ignore it.`,
|
||||
value_type: "select",
|
||||
wire_boolean: true,
|
||||
options: [
|
||||
{ value: "true", title: "On" },
|
||||
{ value: "false", title: "Off" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "thinking_budget",
|
||||
title: "Thinking budget",
|
||||
description: `How many tokens it may think with, up to 32768. Only some models take it, and usually only while thinking is on.`,
|
||||
value_type: "number",
|
||||
min: 0,
|
||||
max: 32768,
|
||||
step: 1,
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type HarnessParameter = (typeof HarnessParameters)[number];
|
||||
export type HarnessParameterKey = HarnessParameter["key"];
|
||||
export type HarnessParameterValue = number | string;
|
||||
|
||||
/**
|
||||
* The generation settings as they go on the wire: OpenRouter's reasoning
|
||||
* effort nests as `reasoning: { effort }`, a boolean setting as a JSON
|
||||
* boolean, the rest as they are.
|
||||
*/
|
||||
export type HarnessWireParams = Record<
|
||||
string,
|
||||
number | string | boolean | { effort: string }
|
||||
>;
|
||||
|
||||
/**
|
||||
* The harnesses whose models are chat models, so the only ones the
|
||||
* generation settings apply to.
|
||||
@@ -189,6 +220,30 @@ export function modelAdvertisesParameter({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The names a provider's declared settings go under: what its models'
|
||||
* `supported_parameters` should carry, so the same advertised names
|
||||
* OpenRouter's catalog uses. Undefined when the provider declares nothing,
|
||||
* which leaves its models with none.
|
||||
*/
|
||||
export function providerSupportedParameters({
|
||||
keys,
|
||||
}: {
|
||||
keys?: readonly HarnessParameterKey[] | null;
|
||||
}) {
|
||||
if (!keys) return undefined;
|
||||
|
||||
return keys.flatMap((key) => {
|
||||
const parameter = HarnessParameters.find((p) => p.key == key);
|
||||
|
||||
if (!parameter) return [];
|
||||
|
||||
return [
|
||||
"advertised" in parameter ? parameter.advertised : parameter.key,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The generation settings a saved `options` object holds.
|
||||
*/
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
* tools support and prices; `openai-compatible` gives only ids, so
|
||||
* capabilities are guessed from the names
|
||||
* - `local`: runs on the user's own hardware, so its models count as free
|
||||
* - `parameters`: the generation settings its models get when its own model
|
||||
* list carries none (`HarnessParameters` keys). Empty for a provider whose
|
||||
* catalog decides (OpenRouter) or whose host is checked instead (custom)
|
||||
* - `image_path`: image generation endpoint
|
||||
* - `image_edit_path`: where images made from reference images go. OpenRouter
|
||||
* takes them on `image_path` (`input_references`); the others take a
|
||||
@@ -22,6 +25,7 @@ export const HarnessProviderKinds = [
|
||||
{
|
||||
title: "OpenRouter",
|
||||
value: "openrouter",
|
||||
parameters: [],
|
||||
base_url: "https://openrouter.ai/api/v1",
|
||||
needs_key: true,
|
||||
key_env: "OPENROUTER_API_KEY",
|
||||
@@ -34,6 +38,7 @@ export const HarnessProviderKinds = [
|
||||
{
|
||||
title: "OpenAI",
|
||||
value: "openai",
|
||||
parameters: ["temperature", "top_p", "frequency_penalty", "presence_penalty", "seed", "reasoning_effort"],
|
||||
base_url: "https://api.openai.com/v1",
|
||||
needs_key: true,
|
||||
key_env: "OPENAI_API_KEY",
|
||||
@@ -46,6 +51,7 @@ export const HarnessProviderKinds = [
|
||||
{
|
||||
title: "Anthropic",
|
||||
value: "anthropic",
|
||||
parameters: ["temperature", "top_p", "top_k"],
|
||||
base_url: "https://api.anthropic.com/v1",
|
||||
needs_key: true,
|
||||
key_env: "ANTHROPIC_API_KEY",
|
||||
@@ -58,6 +64,7 @@ export const HarnessProviderKinds = [
|
||||
{
|
||||
title: "Google Gemini",
|
||||
value: "google",
|
||||
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty"],
|
||||
base_url: "https://generativelanguage.googleapis.com/v1beta/openai",
|
||||
needs_key: true,
|
||||
key_env: "GEMINI_API_KEY",
|
||||
@@ -70,6 +77,7 @@ export const HarnessProviderKinds = [
|
||||
{
|
||||
title: "DeepSeek",
|
||||
value: "deepseek",
|
||||
parameters: ["temperature", "top_p", "frequency_penalty", "presence_penalty"],
|
||||
base_url: "https://api.deepseek.com",
|
||||
needs_key: true,
|
||||
key_env: "DEEPSEEK_API_KEY",
|
||||
@@ -82,6 +90,7 @@ export const HarnessProviderKinds = [
|
||||
{
|
||||
title: "Groq",
|
||||
value: "groq",
|
||||
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty", "reasoning_effort"],
|
||||
base_url: "https://api.groq.com/openai/v1",
|
||||
needs_key: true,
|
||||
key_env: "GROQ_API_KEY",
|
||||
@@ -94,6 +103,7 @@ export const HarnessProviderKinds = [
|
||||
{
|
||||
title: "Mistral",
|
||||
value: "mistral",
|
||||
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty"],
|
||||
base_url: "https://api.mistral.ai/v1",
|
||||
needs_key: true,
|
||||
key_env: "MISTRAL_API_KEY",
|
||||
@@ -106,6 +116,7 @@ export const HarnessProviderKinds = [
|
||||
{
|
||||
title: "xAI",
|
||||
value: "xai",
|
||||
parameters: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "seed", "reasoning_effort"],
|
||||
base_url: "https://api.x.ai/v1",
|
||||
needs_key: true,
|
||||
key_env: "XAI_API_KEY",
|
||||
@@ -118,6 +129,7 @@ export const HarnessProviderKinds = [
|
||||
{
|
||||
title: "Ollama",
|
||||
value: "ollama",
|
||||
parameters: ["temperature", "top_p", "top_k", "min_p", "repetition_penalty", "seed"],
|
||||
base_url: "http://localhost:11434/v1",
|
||||
needs_key: false,
|
||||
key_env: "",
|
||||
@@ -130,6 +142,7 @@ export const HarnessProviderKinds = [
|
||||
{
|
||||
title: "Other (OpenAI-compatible)",
|
||||
value: "custom",
|
||||
parameters: [],
|
||||
base_url: "",
|
||||
needs_key: false,
|
||||
key_env: "",
|
||||
|
||||
@@ -3,13 +3,15 @@ import AppError from "@/src/utils/app-error";
|
||||
import grabSystemPromptAppend from "../app-settings/grab-system-prompt-append";
|
||||
import grabWorkspaceBot from "../workspaces/grab-workspace-bot";
|
||||
import grabWorkspaceUserRole from "../workspaces/grab-workspace-user-role";
|
||||
import grabUserName from "../users/grab-user-name";
|
||||
import grabBotUserMemory from "./grab-bot-user-memory";
|
||||
import grabUserBot from "./grab-user-bot";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* The user the bot works with: only their memory joins the prompt.
|
||||
* The user the bot works with: their name and their memory join the
|
||||
* prompt.
|
||||
*/
|
||||
user_id: number | string;
|
||||
/**
|
||||
@@ -23,8 +25,9 @@ type Params = {
|
||||
/**
|
||||
* The full prompt for one of the user's bots (`composeBotPrompt`): who it
|
||||
* is (its name and id), its core instructions, the install-wide appendix,
|
||||
* its memory, what it remembers about this user, and in a workspace that
|
||||
* workspace's context, what the bot has for it and who this user is there.
|
||||
* who the user it's working for is, its memory, what it remembers about this
|
||||
* user, and in a workspace that workspace's context, what the bot has for it
|
||||
* and who this user is there.
|
||||
*/
|
||||
export default async function grabBotPrompt({ bot_id, user_id, workspace_id }: Params) {
|
||||
const bot = await grabUserBot({ bot_id, user_id });
|
||||
@@ -45,6 +48,7 @@ export default async function grabBotPrompt({ bot_id, user_id, workspace_id }: P
|
||||
bot: { id: bot.id, name: bot.name, kind: bot.kind, role: bot.role },
|
||||
system_prompt: bot.system_prompt,
|
||||
appendix: await grabSystemPromptAppend(),
|
||||
user_name: await grabUserName({ user_id }),
|
||||
memory: bot.memory,
|
||||
user_memory: await grabBotUserMemory({ bot_id: bot.id, user_id }),
|
||||
workspace: found?.workspace,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import modelSupportedParameters from "./model-supported-parameters";
|
||||
|
||||
describe("model supported parameters", () => {
|
||||
test("the provider's own list wins", () => {
|
||||
expect(
|
||||
modelSupportedParameters({
|
||||
model: { supported_parameters: ["temperature"] },
|
||||
provider_parameters: ["temperature", "seed"],
|
||||
}),
|
||||
).toEqual(["temperature"]);
|
||||
});
|
||||
|
||||
test("a model that lists none gets the provider's", () => {
|
||||
expect(
|
||||
modelSupportedParameters({
|
||||
model: {},
|
||||
provider_parameters: ["temperature", "seed"],
|
||||
}),
|
||||
).toEqual(["temperature", "seed"]);
|
||||
});
|
||||
|
||||
test("nothing declared stays nothing", () => {
|
||||
expect(modelSupportedParameters({ model: {} })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { HarnessCatalogModel } from "@/src/harness/types";
|
||||
|
||||
type Params = {
|
||||
model: Pick<HarnessCatalogModel, "supported_parameters">;
|
||||
/**
|
||||
* The names the provider's own row declares, for the models it lists
|
||||
* without any (a custom provider lists ids only).
|
||||
*/
|
||||
provider_parameters?: string[] | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The parameters a `harness_models` row keeps: what the provider's own list
|
||||
* said, else the settings the provider declares (its preset, its host or a
|
||||
* super admin's pick). A model's own list wins, so OpenRouter's catalog is
|
||||
* never overridden.
|
||||
*/
|
||||
export default function modelSupportedParameters({
|
||||
model,
|
||||
provider_parameters,
|
||||
}: Params) {
|
||||
return model.supported_parameters ?? provider_parameters ?? null;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
HarnessParameterKeys,
|
||||
type HarnessParameterKey,
|
||||
} from "@/src/dict/harness-parameter-dict";
|
||||
|
||||
type Params = {
|
||||
text?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The generation settings a provider row saved, or undefined when it saved
|
||||
* none (which follows its preset or host instead). Unknown keys are dropped,
|
||||
* so an older release's name can't reach a model's `supported_parameters`
|
||||
* and be offered as a field that never gets sent.
|
||||
*/
|
||||
export default function parseProviderParameters({
|
||||
text,
|
||||
}: Params): HarnessParameterKey[] | undefined {
|
||||
if (!text) return undefined;
|
||||
|
||||
try {
|
||||
const value = JSON.parse(text);
|
||||
|
||||
if (!Array.isArray(value)) return undefined;
|
||||
|
||||
return value.filter((key): key is HarnessParameterKey =>
|
||||
HarnessParameterKeys.includes(key as HarnessParameterKey),
|
||||
);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
BunSQLiteTables,
|
||||
} from "@/db/types/db";
|
||||
import type { HarnessProviderKind } from "@/src/dict/harness-provider-dict";
|
||||
import type { HarnessParameterKey } from "@/src/dict/harness-parameter-dict";
|
||||
import grabProviderPreset from "@/src/harness/providers/grab-provider-preset";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import { encrypt } from "@/src/utils/crypt";
|
||||
@@ -27,6 +28,11 @@ type Params = {
|
||||
* leaves them unknown.
|
||||
*/
|
||||
context_length?: number;
|
||||
/**
|
||||
* The generation settings its models are offered. Left out follows its
|
||||
* preset or host; an empty array means it takes none.
|
||||
*/
|
||||
parameters?: HarnessParameterKey[];
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
@@ -42,6 +48,7 @@ export default async function saveHarnessProvider({
|
||||
api_key,
|
||||
clear_key,
|
||||
context_length,
|
||||
parameters,
|
||||
enabled,
|
||||
}: Params) {
|
||||
const preset = grabProviderPreset({ kind });
|
||||
@@ -75,6 +82,7 @@ export default async function saveHarnessProvider({
|
||||
* cleared with null (the plugin binds it as NULL).
|
||||
*/
|
||||
context_length: (context_length && context_length > 0 ? context_length : null) as number,
|
||||
parameters: (parameters ? JSON.stringify(parameters) : null) as string,
|
||||
...key_update,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_HARNESS_PROVIDERS } from "@/db/types/db";
|
||||
import grabHarnessAdapter from "@/src/harness/providers/grab-harness-adapter";
|
||||
import providerParameterKeys from "@/src/harness/providers/provider-parameter-keys";
|
||||
import { providerSupportedParameters } from "@/src/dict/harness-parameter-dict";
|
||||
import parseProviderParameters from "./parse-provider-parameters";
|
||||
import resolveProviderConfig from "./resolve-provider-config";
|
||||
import upsertHarnessModels from "./upsert-harness-models";
|
||||
|
||||
@@ -29,6 +32,15 @@ export default async function syncHarnessProviderModels({ provider }: Params) {
|
||||
provider_id: provider.id,
|
||||
models,
|
||||
provider_context_length: provider.context_length || null,
|
||||
provider_parameters: providerSupportedParameters({
|
||||
keys: providerParameterKeys({
|
||||
kind: config.kind,
|
||||
base_url: provider.base_url,
|
||||
declared: parseProviderParameters({
|
||||
text: provider.parameters,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
await BunSQLite.sql({
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { BUN_SQLITE_COBBLE_HARNESS_PROVIDERS } from "@/db/types/db";
|
||||
import grabProviderPreset from "@/src/harness/providers/grab-provider-preset";
|
||||
import providerParameterKeys from "@/src/harness/providers/provider-parameter-keys";
|
||||
import parseProviderParameters from "./parse-provider-parameters";
|
||||
import type { PublicHarnessProvider } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
@@ -14,19 +16,29 @@ export default function toPublicHarnessProvider({
|
||||
provider,
|
||||
}: Params): PublicHarnessProvider {
|
||||
const preset = grabProviderPreset({ kind: provider.kind });
|
||||
const base_url = provider.base_url || preset.base_url;
|
||||
|
||||
return {
|
||||
id: provider.id || 0,
|
||||
kind: preset.value,
|
||||
name: provider.name || preset.title,
|
||||
base_url: provider.base_url || preset.base_url,
|
||||
base_url,
|
||||
enabled: provider.enabled != 0,
|
||||
has_key: Boolean(provider.api_key),
|
||||
has_env_key: Boolean(preset.key_env && process.env[preset.key_env]),
|
||||
needs_key: preset.needs_key,
|
||||
key_env: preset.key_env || undefined,
|
||||
context_length: provider.context_length || undefined,
|
||||
/**
|
||||
* What its form shows ticked, and what its models get on the next
|
||||
* sync: its saved pick, else its preset's or host's list.
|
||||
*/
|
||||
parameters: providerParameterKeys({
|
||||
kind: preset.value,
|
||||
base_url,
|
||||
declared: parseProviderParameters({ text: provider.parameters }),
|
||||
}),
|
||||
last_synced_at: provider.last_synced_at || undefined,
|
||||
sync_error: provider.sync_error || undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { HarnessCatalogModel } from "@/src/harness/types";
|
||||
import modelContextLength from "./model-context-length";
|
||||
import modelSupportedParameters from "./model-supported-parameters";
|
||||
|
||||
type Params = {
|
||||
provider_id: number;
|
||||
@@ -10,6 +11,11 @@ type Params = {
|
||||
* of their own (a custom provider lists ids only).
|
||||
*/
|
||||
provider_context_length?: number | null;
|
||||
/**
|
||||
* The generation settings its provider declares, as the names a model's
|
||||
* `supported_parameters` carries, for the models it lists without any.
|
||||
*/
|
||||
provider_parameters?: string[] | null;
|
||||
now?: number;
|
||||
};
|
||||
|
||||
@@ -49,6 +55,7 @@ export default async function upsertHarnessModels({
|
||||
provider_id,
|
||||
models,
|
||||
provider_context_length,
|
||||
provider_parameters,
|
||||
now = Date.now(),
|
||||
}: Params) {
|
||||
const unique = [...new Map(models.map((m) => [m.slug, m])).values()];
|
||||
@@ -63,27 +70,36 @@ export default async function upsertHarnessModels({
|
||||
${Columns.filter((c) => c != "created_at" && c != "provider_id" && c != "slug")
|
||||
.map((c) => `${c} = excluded.${c}`)
|
||||
.join(", ")}`,
|
||||
values: chunk.flatMap((model) => [
|
||||
now,
|
||||
now,
|
||||
provider_id,
|
||||
model.slug,
|
||||
model.name || model.slug,
|
||||
model.free ? 1 : 0,
|
||||
1,
|
||||
JSON.stringify(model.input_modalities),
|
||||
JSON.stringify(model.output_modalities),
|
||||
model.supports_tools ? 1 : 0,
|
||||
modelContextLength({ model, provider_context_length }),
|
||||
model.max_output_tokens ?? null,
|
||||
model.voices ? JSON.stringify(model.voices) : null,
|
||||
model.supported_parameters ? JSON.stringify(model.supported_parameters) : null,
|
||||
model.intelligence_score ?? null,
|
||||
model.agentic_score ?? null,
|
||||
model.released_at ?? null,
|
||||
model.expires_at ?? null,
|
||||
now,
|
||||
]),
|
||||
values: chunk.flatMap((model) => {
|
||||
const supported_parameters = modelSupportedParameters({
|
||||
model,
|
||||
provider_parameters,
|
||||
});
|
||||
|
||||
return [
|
||||
now,
|
||||
now,
|
||||
provider_id,
|
||||
model.slug,
|
||||
model.name || model.slug,
|
||||
model.free ? 1 : 0,
|
||||
1,
|
||||
JSON.stringify(model.input_modalities),
|
||||
JSON.stringify(model.output_modalities),
|
||||
model.supports_tools ? 1 : 0,
|
||||
modelContextLength({ model, provider_context_length }),
|
||||
model.max_output_tokens ?? null,
|
||||
model.voices ? JSON.stringify(model.voices) : null,
|
||||
supported_parameters
|
||||
? JSON.stringify(supported_parameters)
|
||||
: null,
|
||||
model.intelligence_score ?? null,
|
||||
model.agentic_score ?? null,
|
||||
model.released_at ?? null,
|
||||
model.expires_at ?? null,
|
||||
now,
|
||||
];
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
type UserNameRow = {
|
||||
first_name: string | null;
|
||||
last_name: string | null;
|
||||
username: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The user's name as the app shows it (first and last, else username), or
|
||||
* empty when they have neither. Every run's prompt gets it, so its bot knows
|
||||
* who it's working for instead of asking them to confirm it.
|
||||
*/
|
||||
export default async function grabUserName({ user_id }: Params): Promise<string> {
|
||||
const row = (
|
||||
await BunSQLite.sql<UserNameRow>({
|
||||
sql: `SELECT first_name, last_name, username FROM users WHERE id = ? LIMIT 1`,
|
||||
values: [user_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
return (
|
||||
[row?.first_name, row?.last_name].filter(Boolean).join(" ").trim() ||
|
||||
row?.username?.trim() ||
|
||||
""
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ReadImagePrompt } from "@/src/data/harness-prompts";
|
||||
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
|
||||
import HarnessError from "../harness-error";
|
||||
import grabHarnessAdapter from "../providers/grab-harness-adapter";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
@@ -56,7 +57,7 @@ export default async function readImage({ url, focus, signal, bot_id, workspace_
|
||||
const { result } = await withCandidates<{
|
||||
text: string;
|
||||
usage?: HarnessUsage;
|
||||
sent_params: Record<string, number | string | { effort: string }>;
|
||||
sent_params: HarnessWireParams;
|
||||
}>({
|
||||
harness: "vision",
|
||||
candidates,
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { HarnessAdapter } from "../../types";
|
||||
import grabProviderPreset from "../grab-provider-preset";
|
||||
import providerRequest from "./provider-request";
|
||||
import readChatResponse from "./read-chat-response";
|
||||
import toWireChatParams from "./to-wire-chat-params";
|
||||
import toWireMessages from "./to-wire-messages";
|
||||
|
||||
/**
|
||||
@@ -24,7 +25,7 @@ const chat: HarnessAdapter["chat"] = async ({
|
||||
// Generation settings first, so the core fields below always win:
|
||||
// a saved parameter must never override the model, the messages,
|
||||
// the tools or the token ceiling (R12).
|
||||
...(params || {}),
|
||||
...toWireChatParams({ params, kind: provider.kind }),
|
||||
model: model.slug,
|
||||
messages: toWireMessages({ messages }),
|
||||
...(tools?.length
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import toWireChatParams from "./to-wire-chat-params";
|
||||
|
||||
describe("toWireChatParams", () => {
|
||||
test("OpenRouter nests the reasoning effort", () => {
|
||||
expect(
|
||||
toWireChatParams({
|
||||
kind: "openrouter",
|
||||
params: { temperature: 0.3, reasoning: { effort: "high" } },
|
||||
}),
|
||||
).toEqual({ temperature: 0.3, reasoning: { effort: "high" } });
|
||||
});
|
||||
|
||||
test("everyone else takes it flat", () => {
|
||||
expect(
|
||||
toWireChatParams({
|
||||
kind: "custom",
|
||||
params: { temperature: 0.3, reasoning: { effort: "high" } },
|
||||
}),
|
||||
).toEqual({ temperature: 0.3, reasoning_effort: "high" });
|
||||
});
|
||||
|
||||
test("the other settings pass through as they are", () => {
|
||||
expect(
|
||||
toWireChatParams({
|
||||
kind: "openai",
|
||||
params: { top_p: 0.5, enable_thinking: false },
|
||||
}),
|
||||
).toEqual({ top_p: 0.5, enable_thinking: false });
|
||||
});
|
||||
|
||||
test("nothing saved sends nothing", () => {
|
||||
expect(toWireChatParams({ kind: "openai" })).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { HarnessProviderKind } from "@/src/dict/harness-provider-dict";
|
||||
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
|
||||
|
||||
type Params = {
|
||||
params?: HarnessWireParams;
|
||||
kind: HarnessProviderKind;
|
||||
};
|
||||
|
||||
/**
|
||||
* The generation settings as a provider's `/chat/completions` takes them.
|
||||
* OpenRouter nests the reasoning effort as `reasoning: { effort }`; everyone
|
||||
* else (OpenAI, Groq, Alibaba, a custom host) takes it flat as
|
||||
* `reasoning_effort`, where the nested form is ignored.
|
||||
*/
|
||||
export default function toWireChatParams({ params, kind }: Params) {
|
||||
const wire: HarnessWireParams = { ...(params || {}) };
|
||||
|
||||
if (kind == "openrouter") return wire;
|
||||
|
||||
const reasoning = wire.reasoning;
|
||||
|
||||
if (reasoning && typeof reasoning == "object") {
|
||||
delete wire.reasoning;
|
||||
wire.reasoning_effort = reasoning.effort;
|
||||
}
|
||||
|
||||
return wire;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import providerParameterKeys from "./provider-parameter-keys";
|
||||
|
||||
describe("provider parameter keys", () => {
|
||||
test("a provider's own saved pick wins over its preset", () => {
|
||||
expect(
|
||||
providerParameterKeys({
|
||||
kind: "openai",
|
||||
declared: ["seed"],
|
||||
}),
|
||||
).toEqual(["seed"]);
|
||||
});
|
||||
|
||||
test("an empty saved pick means it takes none", () => {
|
||||
expect(
|
||||
providerParameterKeys({ kind: "openai", declared: [] }),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("a preset's list fills a provider that saved none", () => {
|
||||
expect(
|
||||
providerParameterKeys({ kind: "groq", base_url: "https://api.groq.com/openai/v1" }),
|
||||
).toContain("temperature");
|
||||
});
|
||||
|
||||
test("a custom provider on Alibaba gets Alibaba's list", () => {
|
||||
const keys = providerParameterKeys({
|
||||
kind: "custom",
|
||||
base_url: "https://token-plan.us-east-1.maas.aliyuncs.com/compatible-mode/v1",
|
||||
});
|
||||
|
||||
expect(keys).toContain("enable_thinking");
|
||||
expect(keys).toContain("thinking_budget");
|
||||
});
|
||||
|
||||
test("a custom provider elsewhere gets nothing rather than a guess", () => {
|
||||
expect(
|
||||
providerParameterKeys({
|
||||
kind: "custom",
|
||||
base_url: "http://localhost:8000/v1",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
test("OpenRouter keeps its catalog's own list", () => {
|
||||
expect(
|
||||
providerParameterKeys({
|
||||
kind: "openrouter",
|
||||
base_url: "https://openrouter.ai/api/v1",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { HarnessParameterKey } from "@/src/dict/harness-parameter-dict";
|
||||
import {
|
||||
HarnessProviderKinds,
|
||||
type HarnessProviderKind,
|
||||
} from "@/src/dict/harness-provider-dict";
|
||||
import { isDashScopeHost } from "./openai-compatible/dashscope-hosts";
|
||||
|
||||
/**
|
||||
* What Alibaba's compatible mode documents taking, the Token Plan hosts
|
||||
* included. `thinking_budget` is refused by a few of their models, so it is
|
||||
* offered but not sent until asked for.
|
||||
*/
|
||||
const DashScopeParameters: readonly HarnessParameterKey[] = [
|
||||
"temperature",
|
||||
"top_p",
|
||||
"presence_penalty",
|
||||
"seed",
|
||||
"enable_thinking",
|
||||
"thinking_budget",
|
||||
];
|
||||
|
||||
type Params = {
|
||||
kind: HarnessProviderKind;
|
||||
base_url?: string | null;
|
||||
/**
|
||||
* What the provider's own row saved, when a super admin set it. An empty
|
||||
* array is a real answer (it takes none); null or undefined follows the
|
||||
* preset, then the host.
|
||||
*/
|
||||
declared?: readonly HarnessParameterKey[] | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The generation settings a provider's models are offered: what its row
|
||||
* saved, else its preset's list, else the list for its host (a custom
|
||||
* provider pointed at Alibaba). Undefined when nobody knows, which leaves its
|
||||
* models with no settings rather than sending a field it might refuse.
|
||||
*/
|
||||
export default function providerParameterKeys({
|
||||
kind,
|
||||
base_url,
|
||||
declared,
|
||||
}: Params): HarnessParameterKey[] | undefined {
|
||||
if (declared) return [...declared];
|
||||
|
||||
const preset = HarnessProviderKinds.find((p) => p.value == kind);
|
||||
|
||||
if (preset?.parameters.length) return [...preset.parameters];
|
||||
|
||||
/**
|
||||
* OpenRouter's catalog says what each model takes, so its models keep
|
||||
* their own list.
|
||||
*/
|
||||
if (kind != "openrouter" && isDashScopeHost({ base_url })) {
|
||||
return [...DashScopeParameters];
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import HarnessError from "../harness-error";
|
||||
import grabHarnessAdapter from "../providers/grab-harness-adapter";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import withCandidates from "../resolve/with-candidates";
|
||||
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
|
||||
import type {
|
||||
HarnessCandidate,
|
||||
HarnessChatResult,
|
||||
@@ -38,7 +39,7 @@ export type GenerateTextParams = {
|
||||
/**
|
||||
* Overrides the saved generation settings (media reading wants 0).
|
||||
*/
|
||||
params?: Record<string, number | string | { effort: string }>;
|
||||
params?: HarnessWireParams;
|
||||
signal?: AbortSignal;
|
||||
/**
|
||||
* Media readings shared across calls of one run.
|
||||
@@ -67,7 +68,7 @@ type ChatAnswer = Omit<HarnessChatResult, "text"> & {
|
||||
/**
|
||||
* The generation settings sent to this candidate, for its usage row.
|
||||
*/
|
||||
sent_params?: Record<string, number | string | { effort: string }>;
|
||||
sent_params?: HarnessWireParams;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -83,6 +83,15 @@ describe("grabChatParams", () => {
|
||||
expect(paramsFor(model(["reasoning_effort"]))).toEqual({});
|
||||
});
|
||||
|
||||
test("thinking on/off goes on the wire as a boolean", async () => {
|
||||
options = { enable_thinking: "false" };
|
||||
const { paramsFor } = await grabChatParams({ harness: "text" });
|
||||
|
||||
expect(paramsFor(model(["enable_thinking"]))).toEqual({
|
||||
enable_thinking: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("the vision default is a literal 0", async () => {
|
||||
const { paramsFor } = await grabChatParams({ harness: "vision" });
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
HarnessParameters,
|
||||
harnessParameterValue,
|
||||
modelAdvertisesParameter,
|
||||
type HarnessWireParams,
|
||||
} from "@/src/dict/harness-parameter-dict";
|
||||
import grabHarnessSetting from "@/src/functions/backend/db/harness/grab-harness-setting";
|
||||
import type { HarnessModelInfo } from "../types";
|
||||
@@ -26,7 +27,7 @@ export default async function grabChatParams({
|
||||
bot_id,
|
||||
workspace_id,
|
||||
}: Params): Promise<{
|
||||
paramsFor: (model: HarnessModelInfo) => Record<string, number | string | { effort: string }>;
|
||||
paramsFor: (model: HarnessModelInfo) => HarnessWireParams;
|
||||
source: "default" | "bot" | "workspace";
|
||||
}> {
|
||||
const setting = await grabHarnessSetting({
|
||||
@@ -55,9 +56,17 @@ export default async function grabChatParams({
|
||||
return [];
|
||||
|
||||
const key = "wire" in parameter ? parameter.wire : parameter.key;
|
||||
const boolean = "wire_boolean" in parameter;
|
||||
|
||||
return [
|
||||
[key, key == "reasoning" ? { effort: String(value) } : value],
|
||||
[
|
||||
key,
|
||||
key == "reasoning"
|
||||
? { effort: String(value) }
|
||||
: boolean
|
||||
? value === "true"
|
||||
: value,
|
||||
],
|
||||
];
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { z } from "zod";
|
||||
import type { HarnessKind } from "@/src/dict/harness-dict";
|
||||
import type { HarnessProviderKind } from "@/src/dict/harness-provider-dict";
|
||||
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
|
||||
|
||||
/**
|
||||
* Part of a user message. Images are an https or `data:` URL; audio is
|
||||
@@ -234,7 +235,7 @@ export type HarnessChatParams = {
|
||||
* Sampling and reasoning fields, keyed by their wire name. The caller
|
||||
* only includes what the model advertises.
|
||||
*/
|
||||
params?: Record<string, number | string | { effort: string }>;
|
||||
params?: HarnessWireParams;
|
||||
signal: AbortSignal;
|
||||
};
|
||||
|
||||
|
||||
@@ -13,6 +13,12 @@ describe("flattenSentParams", () => {
|
||||
expect(flattenSentParams({ params: { temperature: 0, seed: "" } })).toEqual({ temperature: 0 });
|
||||
});
|
||||
|
||||
test("reads a boolean setting back as on or off", () => {
|
||||
expect(
|
||||
flattenSentParams({ params: { enable_thinking: false, temperature: 0.3 } }),
|
||||
).toEqual({ enable_thinking: "off", temperature: 0.3 });
|
||||
});
|
||||
|
||||
test("is undefined when nothing was sent", () => {
|
||||
expect(flattenSentParams({ params: {} })).toBeUndefined();
|
||||
expect(flattenSentParams({ params: null })).toBeUndefined();
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Keyed by the field sent on the wire (`grabChatParams`).
|
||||
*/
|
||||
params?: Record<string, number | string | { effort: string }> | null;
|
||||
params?: HarnessWireParams | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -17,6 +19,8 @@ export default function flattenSentParams({ params }: Params) {
|
||||
for (const [key, value] of Object.entries(params || {})) {
|
||||
if (value && typeof value == "object") {
|
||||
if (value.effort) flat[key == "reasoning" ? "reasoning_effort" : key] = String(value.effort);
|
||||
} else if (typeof value == "boolean") {
|
||||
flat[key] = value ? "on" : "off";
|
||||
} else if (typeof value == "number" || (typeof value == "string" && value)) {
|
||||
flat[key] = value;
|
||||
}
|
||||
|
||||
@@ -165,7 +165,7 @@ export default function BotForm({ bot, onCancel, onSaved }: Props) {
|
||||
stone={stone}
|
||||
image_media_id={image.image_media_id}
|
||||
picked_src={image.data_url}
|
||||
avatar_size={100}
|
||||
avatar_size={120}
|
||||
/>
|
||||
}
|
||||
has_image={image.has_image}
|
||||
|
||||
@@ -54,7 +54,13 @@ type PanelTab = "settings" | "tools";
|
||||
* 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, workspace, 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 });
|
||||
@@ -109,7 +115,11 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
|
||||
<Stack className="shrink-0">
|
||||
<BotAvatar
|
||||
image_media_id={bot.image_media_id}
|
||||
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
|
||||
{...botStoneProps({
|
||||
color: bot.color,
|
||||
stone: bot.stone,
|
||||
hue: bot.hue,
|
||||
})}
|
||||
face={(bot.face || "idle") as BotFace}
|
||||
size={35}
|
||||
/>
|
||||
@@ -134,8 +144,16 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
|
||||
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="Tools" active={tab == "tools"} onPick={() => setTab("tools")} />
|
||||
<TabButton
|
||||
title="Settings"
|
||||
active={tab == "settings"}
|
||||
onPick={() => setTab("settings")}
|
||||
/>
|
||||
<TabButton
|
||||
title="Tools"
|
||||
active={tab == "tools"}
|
||||
onPick={() => setTab("tools")}
|
||||
/>
|
||||
</Row>
|
||||
<Stack className="grow min-h-0 overflow-y-auto gap-4! items-stretch px-4 pt-4 pb-6 [&>*]:shrink-0">
|
||||
{open && tab == "settings" ? (
|
||||
@@ -161,13 +179,22 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
|
||||
bot_id={Number(bot.id) || 0}
|
||||
bot_name={name}
|
||||
memory={memory || ""}
|
||||
workspace_id={workspace_id || undefined}
|
||||
workspace_id={
|
||||
workspace_id || undefined
|
||||
}
|
||||
workspace_name={workspace?.name}
|
||||
workspace_memory={workspace_instructions.instructions?.memory || ""}
|
||||
workspace_memory={
|
||||
workspace_instructions
|
||||
.instructions?.memory ||
|
||||
""
|
||||
}
|
||||
onCancel={on_close}
|
||||
/>
|
||||
<Divider className="my-2 border-hairline dark:border-hairline" />
|
||||
<BotUserMemory bot_name={name} memory={user_memory || ""} />
|
||||
<BotUserMemory
|
||||
bot_name={name}
|
||||
memory={user_memory || ""}
|
||||
/>
|
||||
</>
|
||||
) : loaded_error ? (
|
||||
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
|
||||
@@ -203,4 +230,4 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
|
||||
</SidePanel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
import type { HarnessParameter } from "@/src/dict/harness-parameter-dict";
|
||||
|
||||
type Props = {
|
||||
parameter: HarnessParameter;
|
||||
checked: boolean;
|
||||
onChange: (checked: boolean) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One generation setting a provider's models are offered.
|
||||
*/
|
||||
export default function HarnessProviderParameterCheckbox({
|
||||
parameter,
|
||||
checked,
|
||||
onChange,
|
||||
}: Props) {
|
||||
return (
|
||||
<Checkbox
|
||||
title={parameter.title}
|
||||
label={parameter.title}
|
||||
info={parameter.description}
|
||||
checked={checked}
|
||||
clickDispatchHandler={onChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import P from "@moduletrace/twui/layout/P";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import {
|
||||
HarnessParameters,
|
||||
type HarnessParameterKey,
|
||||
} from "@/src/dict/harness-parameter-dict";
|
||||
import HarnessProviderParameterCheckbox from "./harness-provider-parameter-checkbox";
|
||||
|
||||
type Props = {
|
||||
parameters: HarnessParameterKey[];
|
||||
onChange: (parameters: HarnessParameterKey[]) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The generation settings a provider's models are offered, for the models
|
||||
* whose own list carries none (a custom provider lists ids only).
|
||||
*/
|
||||
export default function HarnessProviderParameters({
|
||||
parameters,
|
||||
onChange,
|
||||
}: Props) {
|
||||
return (
|
||||
<Stack className="gap-2! items-stretch">
|
||||
<P className="text-sm text-ink-secondary">
|
||||
The generation settings its models are offered, for the models
|
||||
whose own list carries none (a custom provider lists ids only).
|
||||
Models that list their own (OpenRouter) keep theirs. A provider
|
||||
that takes none unticks all of them, so no field it would refuse
|
||||
is ever sent.
|
||||
</P>
|
||||
{HarnessParameters.map((parameter) => (
|
||||
<HarnessProviderParameterCheckbox
|
||||
key={parameter.key}
|
||||
parameter={parameter}
|
||||
checked={parameters.includes(parameter.key)}
|
||||
onChange={(checked) =>
|
||||
onChange(
|
||||
checked
|
||||
? [...parameters, parameter.key]
|
||||
: parameters.filter((key) => key != parameter.key),
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,9 @@ import {
|
||||
HarnessProviderKinds,
|
||||
type HarnessProviderKind,
|
||||
} from "@/src/dict/harness-provider-dict";
|
||||
import type { HarnessParameterKey } from "@/src/dict/harness-parameter-dict";
|
||||
import providerParameterKeys from "@/src/harness/providers/provider-parameter-keys";
|
||||
import HarnessProviderParameters from "./harness-provider-parameters";
|
||||
import type {
|
||||
HarnessOverviewPayload,
|
||||
PublicHarnessProvider,
|
||||
@@ -43,12 +46,27 @@ export default function ProviderForm({ provider, onSaved, onCancel }: Props) {
|
||||
const [context_length, setContextLength] = useState(
|
||||
provider?.context_length ? String(provider.context_length) : "",
|
||||
);
|
||||
/**
|
||||
* What the admin ticked. Null follows the preset, then the host, so a
|
||||
* custom provider pointed at Alibaba starts with its settings ticked.
|
||||
*/
|
||||
const [chosen_parameters, setChosenParameters] = useState<
|
||||
HarnessParameterKey[] | null
|
||||
>(provider ? (provider.parameters ?? []) : null);
|
||||
const [enabled, setEnabled] = useState(provider?.enabled ?? true);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
const id = `provider-${provider?.id || "new"}`;
|
||||
|
||||
const parameters =
|
||||
chosen_parameters ??
|
||||
providerParameterKeys({
|
||||
kind,
|
||||
base_url: base_url || preset.base_url,
|
||||
}) ??
|
||||
[];
|
||||
|
||||
const submit = async () => {
|
||||
if (loading) return;
|
||||
if (
|
||||
@@ -73,6 +91,7 @@ export default function ProviderForm({ provider, onSaved, onCancel }: Props) {
|
||||
api_key: api_key || undefined,
|
||||
clear_key: clear_key || undefined,
|
||||
context_length: Number(context_length) || 0,
|
||||
parameters,
|
||||
enabled,
|
||||
},
|
||||
});
|
||||
@@ -174,6 +193,10 @@ export default function ProviderForm({ provider, onSaved, onCancel }: Props) {
|
||||
onChange={(e) => setContextLength(e.target.value)}
|
||||
placeholder="Eg. 1,000,000"
|
||||
/>
|
||||
<HarnessProviderParameters
|
||||
parameters={parameters}
|
||||
onChange={setChosenParameters}
|
||||
/>
|
||||
<Checkbox
|
||||
title="Turn this provider on"
|
||||
label="Turned on"
|
||||
|
||||
@@ -32,7 +32,12 @@ export default function ProfilePhotoField({
|
||||
|
||||
return (
|
||||
<Row className="w-full gap-4! flex-nowrap items-center">
|
||||
<UserAvatar src={preview_src} initials={initials} alt="Your photo" size="lg" />
|
||||
<UserAvatar
|
||||
src={preview_src}
|
||||
initials={initials}
|
||||
alt="Your photo"
|
||||
size="xxl"
|
||||
/>
|
||||
<Stack className="gap-2! min-w-0">
|
||||
<Row className="gap-2!">
|
||||
<Button
|
||||
|
||||
@@ -17,7 +17,8 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* One user: their photo, name, user types and email. The title opens
|
||||
* One user: their photo, name, user types, email and id (`#7`, so a crew
|
||||
* manager can name one to a bot or in a log). The title opens
|
||||
* their settings page; Revoke (not once revoked) and Delete sit at the
|
||||
* end where the actor may (`canRevokeUser`; never yourself).
|
||||
*/
|
||||
@@ -48,7 +49,7 @@ export default function UserSettingsRow({
|
||||
href={`/admin/settings/users/${person.id}`}
|
||||
title={name}
|
||||
badge={is_self ? "You" : undefined}
|
||||
subtitle={[types_title, person.email].filter(Boolean).join(" · ")}
|
||||
subtitle={[types_title, person.email, `#${person.id}`].filter(Boolean).join(" · ")}
|
||||
>
|
||||
{can_revoke ? (
|
||||
<SettingsRowAction
|
||||
|
||||
@@ -5,6 +5,10 @@ import {
|
||||
HarnessProviderKinds,
|
||||
type HarnessProviderKind,
|
||||
} from "@/src/dict/harness-provider-dict";
|
||||
import {
|
||||
HarnessParameterKeys,
|
||||
type HarnessParameterKey,
|
||||
} from "@/src/dict/harness-parameter-dict";
|
||||
|
||||
const ProviderIdSchema = z.coerce
|
||||
.number()
|
||||
@@ -43,6 +47,22 @@ export const SaveHarnessProviderRequestSchema = z.object({
|
||||
},
|
||||
)
|
||||
.default(0),
|
||||
/**
|
||||
* The generation settings its models are offered, for the models whose
|
||||
* own list carries none. Left out follows its preset or host; an empty
|
||||
* array means it takes none.
|
||||
*/
|
||||
parameters: z
|
||||
.array(
|
||||
z.enum(
|
||||
HarnessParameterKeys as [
|
||||
HarnessParameterKey,
|
||||
...HarnessParameterKey[],
|
||||
],
|
||||
"That is not a generation setting",
|
||||
),
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const HarnessProviderIdRequestSchema = z.object({
|
||||
|
||||
@@ -38,6 +38,7 @@ import type { APIResponseObject, BunextPageModuleServerReturnURLObject } from "@
|
||||
import type { BUN_SQLITE_COBBLE_USERS_JOIN } from "./sql-joins";
|
||||
import type { ImageInputToBase64FunctionReturn } from "@moduletrace/twui/utils/form/imageInputToBase64";
|
||||
import type { HarnessKind } from "../dict/harness-dict";
|
||||
import type { HarnessParameterKey } from "../dict/harness-parameter-dict";
|
||||
import type { HarnessProviderKind } from "../dict/harness-provider-dict";
|
||||
import type { EnvParadigm, KnownEnv, SecretRequestStatus } from "../dict/env-dict";
|
||||
import type { BotQuestionKind, BotQuestionStatus } from "../dict/bot-question-dict";
|
||||
@@ -794,6 +795,11 @@ export type PublicHarnessProvider = {
|
||||
* own (a custom provider lists ids only).
|
||||
*/
|
||||
context_length?: number;
|
||||
/**
|
||||
* The generation settings its models are offered (its saved pick, else
|
||||
* its preset's or host's list). Undefined: it takes none.
|
||||
*/
|
||||
parameters?: HarnessParameterKey[];
|
||||
last_synced_at?: number;
|
||||
sync_error?: string;
|
||||
};
|
||||
|
||||
@@ -106,6 +106,30 @@ describe("composeBotPrompt", () => {
|
||||
expect(composeBotPrompt({ system_prompt: "Core.", appendix: " " })).toBe("Core.");
|
||||
});
|
||||
|
||||
test("says who it's working for, so it never asks them to confirm it", () => {
|
||||
expect(composeBotPrompt({ system_prompt: "Core.", user_name: " Ada Lane " })).toBe(
|
||||
"Core.\n\n# Who you're working for\n\nYou're working for Ada Lane. Every message in this conversation is theirs (the app marks anything another bot passed on), so never ask them to confirm who they are.",
|
||||
);
|
||||
|
||||
const prompt = composeBotPrompt({
|
||||
appendix: "Be brief.",
|
||||
user_name: "Ada Lane",
|
||||
workspace: { name: "Launch" },
|
||||
});
|
||||
|
||||
expect(prompt.indexOf("# Install-wide instructions")).toBeLessThan(
|
||||
prompt.indexOf("# Who you're working for"),
|
||||
);
|
||||
expect(prompt.indexOf("# Who you're working for")).toBeLessThan(
|
||||
prompt.indexOf("# Workspace: Launch"),
|
||||
);
|
||||
});
|
||||
|
||||
test("leaves the user out when the caller doesn't name them", () => {
|
||||
expect(composeBotPrompt({ system_prompt: "Core.", user_name: " " })).toBe("Core.");
|
||||
expect(composeBotPrompt({ system_prompt: "Core." })).toBe("Core.");
|
||||
});
|
||||
|
||||
test("leaves out empty parts and has no workspace outside one", () => {
|
||||
expect(
|
||||
composeBotPrompt({
|
||||
|
||||
@@ -38,6 +38,11 @@ type Params = {
|
||||
* instructions (Settings > General).
|
||||
*/
|
||||
appendix?: string | null;
|
||||
/**
|
||||
* The name of the user whose conversation this run is for, so the bot
|
||||
* never has to ask who it's talking to.
|
||||
*/
|
||||
user_name?: string | null;
|
||||
memory?: string | null;
|
||||
/**
|
||||
* What the bot remembers about the user it's working with.
|
||||
@@ -61,16 +66,18 @@ type Params = {
|
||||
/**
|
||||
* The full prompt a bot runs with (markdown): who it is (its name and id,
|
||||
* so it always knows which bot it is), its own core instructions, then the
|
||||
* install-wide appendix, then, in a workspace, the workspace's
|
||||
* context, the bot's instructions there and the user's role there, then its core memory, its
|
||||
* memory about the user and its memory in the workspace (said to be the
|
||||
* bot's own notes, not the workspace's context). Empty parts are left out;
|
||||
* the workspace heading always shows, so the bot knows where it is.
|
||||
* install-wide appendix, then who the user it's working for is, then, in a
|
||||
* workspace, the workspace's context, the bot's instructions there and the
|
||||
* user's role there, then its core memory, its memory about the user and its
|
||||
* memory in the workspace (said to be the bot's own notes, not the
|
||||
* workspace's context). Empty parts are left out; the workspace heading
|
||||
* always shows, so the bot knows where it is.
|
||||
*/
|
||||
export default function composeBotPrompt({
|
||||
bot,
|
||||
system_prompt,
|
||||
appendix,
|
||||
user_name,
|
||||
memory,
|
||||
user_memory,
|
||||
workspace,
|
||||
@@ -93,6 +100,15 @@ export default function composeBotPrompt({
|
||||
parts.push(`# Install-wide instructions\n\n${appendix.trim()}`);
|
||||
}
|
||||
|
||||
if (user_name?.trim()) {
|
||||
parts.push(
|
||||
[
|
||||
`# Who you're working for`,
|
||||
`You're working for ${user_name.trim()}. Every message in this conversation is theirs (the app marks anything another bot passed on), so never ask them to confirm who they are.`,
|
||||
].join("\n\n"),
|
||||
);
|
||||
}
|
||||
|
||||
if (workspace) {
|
||||
const context = [workspace.description?.trim(), workspace.system_prompt?.trim()].filter(
|
||||
Boolean,
|
||||
|
||||
Reference in New Issue
Block a user